1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "BlobBackgroundTask.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../ui/string.hpp"
15 #include "../world/Body.hpp"
16 #include "../world/Planet.hpp"
17 #include "../world/Simulation.hpp"
18 #include "../world/TileType.hpp"
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
26 #include <glm/gtx/io.hpp>
32 Composition::Composition()
37 Composition::~Composition() {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42 return b.value < a.value;
46 void Composition::Add(int res, double amount) {
48 for (auto c = components.begin(); c != components.end(); ++c) {
49 if (c->resource == res) {
51 if (c->value <= 0.0) {
58 if (!found && amount > 0.0) {
59 components.emplace_back(res, amount);
61 std::sort(components.begin(), components.end(), CompositionCompare);
65 bool Composition::Has(int res) const noexcept {
66 for (auto &c : components) {
67 if (c.resource == res) {
74 double Composition::Get(int res) const noexcept {
75 for (auto &c : components) {
76 if (c.resource == res) {
84 Creature::Creature(world::Simulation &sim)
91 , highlight_color(0.0, 0.0, 0.0, 1.0)
107 // all creatures avoid each other for now
108 steering.Separate(0.1, 1.5);
111 Creature::~Creature() {
114 void Creature::AddMass(int res, double amount) {
115 composition.Add(res, amount);
116 double nonsolid = 0.0;
118 for (const auto &c : composition) {
119 volume += c.value / sim.Assets().data.resources[c.resource].density;
120 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
124 Mass(composition.TotalMass());
125 Size(std::cbrt(volume));
126 highlight_color.a = nonsolid / composition.TotalMass();
129 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
130 highlight_color = glm::dvec4(c, highlight_color.a);
133 void Creature::Ingest(int res, double amount) noexcept {
134 // TODO: check foreign materials
135 if (sim.Resources()[res].state == world::Resource::SOLID) {
136 // 15% of solids stays in body
137 AddMass(res, amount * 0.15);
139 // 10% of fluids stays in body
140 AddMass(res, amount * 0.05);
142 math::GaloisLFSR &random = sim.Assets().random;
143 if (random.UNorm() < AdaptChance()) {
144 // change color to be slightly more like resource
145 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
146 // solids affect base color, others highlight
147 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
148 double q = random.UInt(3); // hue, sat, or val
149 double r = random.UInt(2); // mean or deviation
150 math::Distribution *d = nullptr;
154 d = &genome.base_hue;
157 d = &genome.base_saturation;
160 d = &genome.base_lightness;
165 d = &genome.highlight_hue;
168 d = &genome.highlight_saturation;
171 d = &genome.highlight_lightness;
176 double diff = ref - d->Mean();
180 } else if (diff > 0.5) {
183 // move ±15% of distance
184 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
186 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
189 // scale by ±15%, enforce bounds
190 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
195 void Creature::DoWork(double amount) noexcept {
196 stats.Exhaustion().Add(amount / Stamina());
197 // burn resources proportional to composition
198 // factor = 1/total * 1/efficiency * amount * -1
199 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
200 // make a copy to total remains constant and
201 // no entries disappear during iteration
202 Composition comp(composition);
203 for (auto &cmp : comp) {
204 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
205 AddMass(cmp.resource, value);
209 void Creature::Hurt(double amount) noexcept {
210 stats.Damage().Add(amount);
211 if (stats.Damage().Full()) {
216 void Creature::Die() noexcept {
219 if (stats.Damage().Full()) {
220 std::ostream &log = sim.Log() << name << " ";
221 if (stats.Exhaustion().Full()) {
222 log << "died of exhaustion";
223 } else if (stats.Breath().Full()) {
225 } else if (stats.Thirst().Full()) {
226 log << "died of thirst";
227 } else if (stats.Hunger().Full()) {
228 log << "starved to death";
230 log << "succumed to wounds";
232 log << " at an age of " << ui::TimeString(Age())
233 << " (" << ui::PercentageString(Age() / properties.Lifetime())
234 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
247 bool Creature::Dead() const noexcept {
248 return death > birth;
251 void Creature::Remove() noexcept {
255 void Creature::Removed() noexcept {
262 void Creature::AddParent(Creature &p) {
263 parents.push_back(&p);
266 double Creature::Age() const noexcept {
267 return sim.Time() - birth;
270 double Creature::AgeFactor(double peak) const noexcept {
271 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
272 // goes negative below -0.5 and starts to rise again above 1.0
273 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
274 // guarantee at least 1%
275 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
278 double Creature::EnergyEfficiency() const noexcept {
279 return 0.25 * AgeFactor(0.05);
282 double Creature::ExhaustionFactor() const noexcept {
283 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
286 double Creature::FatigueFactor() const noexcept {
287 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
290 double Creature::Strength() const noexcept {
291 // TODO: replace all age factors with actual growth and decay
292 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
295 double Creature::Stamina() const noexcept {
296 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
299 double Creature::Dexerty() const noexcept {
300 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
303 double Creature::Intelligence() const noexcept {
304 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
307 double Creature::Lifetime() const noexcept {
308 return properties.Lifetime();
311 double Creature::Fertility() const noexcept {
312 return properties.Fertility() * AgeFactor(0.25);
315 double Creature::Mutability() const noexcept {
316 return properties.Mutability();
319 double Creature::Adaptability() const noexcept {
320 return properties.Adaptability();
323 double Creature::OffspringMass() const noexcept {
324 return properties.OffspringMass();
327 double Creature::PerceptionRange() const noexcept {
328 return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
331 double Creature::PerceptionOmniRange() const noexcept {
332 return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
335 double Creature::PerceptionField() const noexcept {
336 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
337 return 0.8 - (Dexerty() / (Dexerty() + 1));
340 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
341 const glm::dvec3 diff(p - situation.Position());
342 double omni_range = PerceptionOmniRange();
343 if (length2(diff) < omni_range * omni_range) return true;
344 double range = PerceptionRange();
345 if (length2(diff) > range * range) return false;
346 return dot(normalize(diff), situation.Heading()) > PerceptionField();
349 double Creature::OffspringChance() const noexcept {
350 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
353 double Creature::MutateChance() const noexcept {
354 return GetProperties().Mutability() * (1.0 / 3600.0);
357 double Creature::AdaptChance() const noexcept {
358 return GetProperties().Adaptability() * (1.0 / 120.0);
361 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
363 goals.emplace_back(std::move(g));
368 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
369 return b->Urgency() < a->Urgency();
374 void Creature::Tick(double dt) {
380 void Creature::TickState(double dt) {
381 steering.MaxSpeed(Dexerty());
382 steering.MaxForce(Strength());
383 Situation::State state(situation.GetState());
384 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
385 Situation::Derivative b(Step(a, dt * 0.5));
386 Situation::Derivative c(Step(b, dt * 0.5));
387 Situation::Derivative d(Step(c, dt));
388 Situation::Derivative f(
389 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
390 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
392 state.pos += f.vel * dt;
393 state.vel += f.acc * dt;
394 situation.EnforceConstraints(state);
395 if (length2(state.vel) > 0.000001) {
396 glm::dvec3 nvel(normalize(state.vel));
397 double ang = angle(nvel, state.dir);
398 double turn_rate = PI * 0.75 * dt;
399 if (ang < turn_rate) {
400 state.dir = normalize(state.vel);
401 } else if (std::abs(ang - PI) < 0.001) {
402 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
404 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
407 situation.SetState(state);
408 // work is force times distance
409 DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
412 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
413 Situation::State s = situation.GetState();
414 s.pos += ds.vel * dt;
415 s.vel += ds.acc * dt;
416 glm::dvec3 force(steering.Force(s));
417 // gravity = antinormal * mass * Gm / r²
418 double elevation = s.pos[(situation.Surface() + 2) % 3];
419 glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
422 * Mass() * situation.GetPlanet().GravitationalParameter()
423 / (elevation * elevation));
424 // if net force is applied and in contact with surface
425 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
426 // apply friction = -|normal force| * tangential force * coefficient
427 glm::dvec3 fn(normal * dot(force, normal));
428 glm::dvec3 ft(force - fn);
430 glm::dvec3 friction(-length(fn) * ft * u);
439 void Creature::TickStats(double dt) {
440 for (auto &s : stats.stat) {
443 // TODO: damage values depending on properties
444 if (stats.Breath().Full()) {
445 constexpr double dps = 1.0 / 4.0;
448 if (stats.Thirst().Full()) {
449 constexpr double dps = 1.0 / 32.0;
452 if (stats.Hunger().Full()) {
453 constexpr double dps = 1.0 / 128.0;
456 if (!situation.Moving()) {
457 // double exhaustion recovery when standing still
458 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
462 void Creature::TickBrain(double dt) {
466 // do background stuff
470 for (auto &goal : goals) {
473 // if active goal can be interrupted, check priorities
474 if (goals.size() > 1 && goals[0]->Interruptible()) {
475 std::sort(goals.begin(), goals.end(), GoalCompare);
478 for (auto goal = goals.begin(); goal != goals.end();) {
479 if ((*goal)->Complete()) {
487 math::AABB Creature::CollisionBox() const noexcept {
488 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
491 glm::dmat4 Creature::CollisionTransform() const noexcept {
492 const double half_size = size * 0.5;
493 const glm::dvec3 &pos = situation.Position();
494 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
495 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
496 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
500 glm::dmat4 Creature::LocalTransform() noexcept {
501 const double half_size = size * 0.5;
502 return CollisionTransform()
503 * glm::scale(glm::dvec3(half_size, half_size, half_size));
506 void Creature::BuildVAO() {
507 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
509 vao->BindAttributes();
510 vao->EnableAttribute(0);
511 vao->EnableAttribute(1);
512 vao->EnableAttribute(2);
513 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
514 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
515 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
516 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
518 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
519 const float offset = 1.0f;
520 for (int surface = 0; surface < 6; ++surface) {
521 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
522 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
524 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
525 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
526 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
527 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
528 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
529 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
530 attrib[4 * surface + 0].texture.x = tex_u_begin;
531 attrib[4 * surface + 0].texture.y = 1.0f;
532 attrib[4 * surface + 0].texture.z = surface;
534 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
535 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
536 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
537 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
538 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
539 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
540 attrib[4 * surface + 1].texture.x = tex_u_end;
541 attrib[4 * surface + 1].texture.y = 1.0f;
542 attrib[4 * surface + 1].texture.z = surface;
544 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
545 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
546 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
547 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
548 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
549 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
550 attrib[4 * surface + 2].texture.x = tex_u_begin;
551 attrib[4 * surface + 2].texture.y = 0.0f;
552 attrib[4 * surface + 2].texture.z = surface;
554 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
555 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
556 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
557 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
558 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
559 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
560 attrib[4 * surface + 3].texture.x = tex_u_end;
561 attrib[4 * surface + 3].texture.y = 0.0f;
562 attrib[4 * surface + 3].texture.z = surface;
566 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
568 auto element = vao->MapElements(GL_WRITE_ONLY);
569 for (int surface = 0; surface < 3; ++surface) {
570 element[6 * surface + 0] = 4 * surface + 0;
571 element[6 * surface + 1] = 4 * surface + 2;
572 element[6 * surface + 2] = 4 * surface + 1;
573 element[6 * surface + 3] = 4 * surface + 1;
574 element[6 * surface + 4] = 4 * surface + 2;
575 element[6 * surface + 5] = 4 * surface + 3;
577 for (int surface = 3; surface < 6; ++surface) {
578 element[6 * surface + 0] = 4 * surface + 0;
579 element[6 * surface + 1] = 4 * surface + 1;
580 element[6 * surface + 2] = 4 * surface + 2;
581 element[6 * surface + 3] = 4 * surface + 2;
582 element[6 * surface + 4] = 4 * surface + 1;
583 element[6 * surface + 5] = 4 * surface + 3;
589 void Creature::KillVAO() {
593 void Creature::Draw(graphics::Viewport &viewport) {
596 vao->DrawTriangles(6 * 6);
600 void Spawn(Creature &c, world::Planet &p) {
602 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
603 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
605 // probe surrounding area for common resources
606 int start = p.SideLength() / 2 - 2;
608 std::map<int, double> yields;
609 for (int y = start; y < end; ++y) {
610 for (int x = start; x < end; ++x) {
611 const world::TileType &t = p.TypeAt(0, x, y);
612 for (auto yield : t.resources) {
613 yields[yield.resource] += yield.ubiquity;
619 for (auto e : yields) {
620 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
621 if (liquid < 0 || e.second > yields[liquid]) {
624 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
625 if (solid < 0 || e.second > yields[solid]) {
632 genome.properties.Strength() = { 2.0, 0.1 };
633 genome.properties.Stamina() = { 2.0, 0.1 };
634 genome.properties.Dexerty() = { 2.0, 0.1 };
635 genome.properties.Intelligence() = { 1.0, 0.1 };
636 genome.properties.Lifetime() = { 480.0, 60.0 };
637 genome.properties.Fertility() = { 0.5, 0.03 };
638 genome.properties.Mutability() = { 0.9, 0.1 };
639 genome.properties.Adaptability() = { 0.9, 0.1 };
640 genome.properties.OffspringMass() = { 0.3, 0.02 };
642 glm::dvec3 color_avg(0.0);
643 double color_divisor = 0.0;
645 if (p.HasAtmosphere()) {
646 c.AddMass(p.Atmosphere(), 0.01);
647 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
648 color_divisor += 0.1;
651 c.AddMass(liquid, 0.3);
652 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
653 color_divisor += 0.5;
656 c.AddMass(solid, 0.1);
657 color_avg += c.GetSimulation().Resources()[solid].base_color;
658 color_divisor += 1.0;
661 if (color_divisor > 0.001) {
662 color_avg /= color_divisor;
664 glm::dvec3 hsl = rgb2hsl(color_avg);
665 genome.base_hue = { hsl.x, 0.01 };
666 genome.base_saturation = { hsl.y, 0.01 };
667 genome.base_lightness = { hsl.z, 0.01 };
668 // use opposite color as start highlight
669 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
670 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
671 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
676 void Genome::Configure(Creature &c) const {
677 c.GetGenome() = *this;
679 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
681 c.GetProperties() = Instantiate(properties, random);
683 // TODO: derive stats from properties
684 c.GetStats().Damage().gain = (-1.0 / 100.0);
685 c.GetStats().Breath().gain = (1.0 / 5.0);
686 c.GetStats().Thirst().gain = (1.0 / 60.0);
687 c.GetStats().Hunger().gain = (1.0 / 200.0);
688 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
689 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
690 c.GetStats().Boredom().gain = (1.0 / 300.0);
692 glm::dvec3 base_color(
693 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
694 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
695 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
697 glm::dvec3 highlight_color(
698 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
699 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
700 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
702 c.BaseColor(hsl2rgb(base_color));
703 c.HighlightColor(hsl2rgb(highlight_color));
704 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
705 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
709 void Split(Creature &c) {
710 Creature *a = new Creature(c.GetSimulation());
711 const Situation &s = c.GetSituation();
713 a->Name(c.GetSimulation().Assets().name.Sequential());
714 c.GetGenome().Configure(*a);
715 for (const auto &cmp : c.GetComposition()) {
716 a->AddMass(cmp.resource, cmp.value * 0.5);
718 s.GetPlanet().AddCreature(a);
719 // TODO: duplicate situation somehow
720 a->GetSituation().SetPlanetSurface(
721 s.GetPlanet(), s.Surface(),
722 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
724 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
726 Creature *b = new Creature(c.GetSimulation());
728 b->Name(c.GetSimulation().Assets().name.Sequential());
729 c.GetGenome().Configure(*b);
730 for (const auto &cmp : c.GetComposition()) {
731 b->AddMass(cmp.resource, cmp.value * 0.5);
733 s.GetPlanet().AddCreature(b);
734 b->GetSituation().SetPlanetSurface(
735 s.GetPlanet(), s.Surface(),
736 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
738 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
744 Memory::Memory(Creature &c)
751 void Memory::Erase() {
755 void Memory::Tick(double dt) {
756 Situation &s = c.GetSituation();
758 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
762 void Memory::TrackStay(const Location &l, double t) {
763 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
764 auto entry = known_types.find(type.id);
765 if (entry != known_types.end()) {
766 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
768 if (entry->second.time_spent > c.Age() * 0.25) {
769 // the place is very familiar
770 c.GetStats().Boredom().Add(-0.2);
773 c.GetStats().Boredom().Add(-0.1);
776 entry->second.last_been = c.GetSimulation().Time();
777 entry->second.last_loc = l;
778 entry->second.time_spent += t;
780 known_types.emplace(type.id, Stay{
781 c.GetSimulation().Time(),
783 c.GetSimulation().Time(),
787 // completely new place, interesting
788 // TODO: scale by personality trait
789 c.GetStats().Boredom().Add(-0.25);
794 NameGenerator::NameGenerator()
798 NameGenerator::~NameGenerator() {
801 std::string NameGenerator::Sequential() {
802 std::stringstream ss;
803 ss << "Blob " << ++counter;
808 Situation::Situation()
810 , state(glm::dvec3(0.0), glm::dvec3(0.0))
815 Situation::~Situation() {
818 bool Situation::OnPlanet() const noexcept {
819 return type == PLANET_SURFACE;
822 bool Situation::OnSurface() const noexcept {
823 return type == PLANET_SURFACE;
826 bool Situation::OnTile() const noexcept {
827 if (type != PLANET_SURFACE) return false;
828 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
829 return t.x >= 0 && t.x < planet->SideLength()
830 && t.y >= 0 && t.y < planet->SideLength();
833 glm::ivec2 Situation::SurfacePosition() const noexcept {
834 return planet->SurfacePosition(surface, state.pos);
837 world::Tile &Situation::GetTile() const noexcept {
838 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
839 return planet->TileAt(surface, t.x, t.y);
842 const world::TileType &Situation::GetTileType() const noexcept {
843 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
844 return planet->TypeAt(surface, t.x, t.y);
847 void Situation::Move(const glm::dvec3 &dp) noexcept {
849 EnforceConstraints(state);
852 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
854 EnforceConstraints(state);
857 void Situation::EnforceConstraints(State &s) noexcept {
860 if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
861 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
862 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
865 if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
866 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
867 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
873 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
874 type = PLANET_SURFACE;
878 EnforceConstraints(state);
882 Steering::Steering(const Creature &c)
896 Steering::~Steering() {
899 void Steering::Off() noexcept {
906 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
908 min_dist = min_distance;
909 max_look = max_lookaround;
912 void Steering::DontSeparate() noexcept {
916 void Steering::ResumeSeparate() noexcept {
920 void Steering::Halt() noexcept {
926 void Steering::Pass(const glm::dvec3 &t) noexcept {
933 void Steering::GoTo(const glm::dvec3 &t) noexcept {
940 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
941 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
942 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
943 glm::dvec3 result(0.0);
945 // TODO: off surface situation
946 glm::dvec3 repulse(0.0);
947 const Situation &s = c.GetSituation();
948 for (auto &other : s.GetPlanet().Creatures()) {
949 if (&*other == &c) continue;
950 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
951 if (length2(diff) > max_look * max_look) continue;
952 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
953 double sep = glm::clamp(length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
954 repulse += normalize(diff) * (1.0 - sep / min_dist) * force;
959 // break twice as hard
960 result += -2.0 * s.vel * force;
963 glm::dvec3 diff = target - s.pos;
964 if (!allzero(diff)) {
965 result += TargetVelocity(s, (normalize(diff) * speed), force);
969 glm::dvec3 diff = target - s.pos;
970 double dist = length(diff);
971 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
972 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
975 if (length2(result) > max_force * max_force) {
976 result = normalize(result) * max_force;
981 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
982 return (vel - s.vel) * acc;