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, situation.GetPlanet().NormalAt(state.pos));
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 = situation.GetPlanet().DistanceAt(s.pos);
419 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
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();
495 orient[1] = situation.GetPlanet().NormalAt(pos);
496 orient[2] = situation.Heading();
497 if (std::abs(dot(orient[1], orient[2])) > 0.999) {
498 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
500 orient[0] = normalize(cross(orient[1], orient[2]));
501 orient[2] = normalize(cross(orient[0], orient[1]));
502 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
503 * glm::dmat4(orient);
506 glm::dmat4 Creature::LocalTransform() noexcept {
507 const double half_size = size * 0.5;
508 return CollisionTransform()
509 * glm::scale(glm::dvec3(half_size, half_size, half_size));
512 void Creature::BuildVAO() {
513 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
515 vao->BindAttributes();
516 vao->EnableAttribute(0);
517 vao->EnableAttribute(1);
518 vao->EnableAttribute(2);
519 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
520 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
521 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
522 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
524 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
525 const float offset = 1.0f;
526 for (int surface = 0; surface < 6; ++surface) {
527 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
528 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
530 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
531 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
532 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
533 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
534 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
535 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
536 attrib[4 * surface + 0].texture.x = tex_u_begin;
537 attrib[4 * surface + 0].texture.y = 1.0f;
538 attrib[4 * surface + 0].texture.z = surface;
540 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
541 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
542 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
543 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
544 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
545 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
546 attrib[4 * surface + 1].texture.x = tex_u_end;
547 attrib[4 * surface + 1].texture.y = 1.0f;
548 attrib[4 * surface + 1].texture.z = surface;
550 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
551 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
552 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
553 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
554 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
555 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
556 attrib[4 * surface + 2].texture.x = tex_u_begin;
557 attrib[4 * surface + 2].texture.y = 0.0f;
558 attrib[4 * surface + 2].texture.z = surface;
560 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
561 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
562 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
563 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
564 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
565 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
566 attrib[4 * surface + 3].texture.x = tex_u_end;
567 attrib[4 * surface + 3].texture.y = 0.0f;
568 attrib[4 * surface + 3].texture.z = surface;
572 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
574 auto element = vao->MapElements(GL_WRITE_ONLY);
575 for (int surface = 0; surface < 3; ++surface) {
576 element[6 * surface + 0] = 4 * surface + 0;
577 element[6 * surface + 1] = 4 * surface + 2;
578 element[6 * surface + 2] = 4 * surface + 1;
579 element[6 * surface + 3] = 4 * surface + 1;
580 element[6 * surface + 4] = 4 * surface + 2;
581 element[6 * surface + 5] = 4 * surface + 3;
583 for (int surface = 3; surface < 6; ++surface) {
584 element[6 * surface + 0] = 4 * surface + 0;
585 element[6 * surface + 1] = 4 * surface + 1;
586 element[6 * surface + 2] = 4 * surface + 2;
587 element[6 * surface + 3] = 4 * surface + 2;
588 element[6 * surface + 4] = 4 * surface + 1;
589 element[6 * surface + 5] = 4 * surface + 3;
595 void Creature::KillVAO() {
599 void Creature::Draw(graphics::Viewport &viewport) {
602 vao->DrawTriangles(6 * 6);
606 void Spawn(Creature &c, world::Planet &p) {
608 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
609 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
611 // probe surrounding area for common resources
612 int start = p.SideLength() / 2 - 2;
614 std::map<int, double> yields;
615 for (int y = start; y < end; ++y) {
616 for (int x = start; x < end; ++x) {
617 const world::TileType &t = p.TypeAt(0, x, y);
618 for (auto yield : t.resources) {
619 yields[yield.resource] += yield.ubiquity;
625 for (auto e : yields) {
626 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
627 if (liquid < 0 || e.second > yields[liquid]) {
630 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
631 if (solid < 0 || e.second > yields[solid]) {
638 genome.properties.Strength() = { 2.0, 0.1 };
639 genome.properties.Stamina() = { 2.0, 0.1 };
640 genome.properties.Dexerty() = { 2.0, 0.1 };
641 genome.properties.Intelligence() = { 1.0, 0.1 };
642 genome.properties.Lifetime() = { 480.0, 60.0 };
643 genome.properties.Fertility() = { 0.5, 0.03 };
644 genome.properties.Mutability() = { 0.9, 0.1 };
645 genome.properties.Adaptability() = { 0.9, 0.1 };
646 genome.properties.OffspringMass() = { 0.3, 0.02 };
648 glm::dvec3 color_avg(0.0);
649 double color_divisor = 0.0;
651 if (p.HasAtmosphere()) {
652 c.AddMass(p.Atmosphere(), 0.01);
653 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
654 color_divisor += 0.1;
657 c.AddMass(liquid, 0.3);
658 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
659 color_divisor += 0.5;
662 c.AddMass(solid, 0.1);
663 color_avg += c.GetSimulation().Resources()[solid].base_color;
664 color_divisor += 1.0;
667 if (color_divisor > 0.001) {
668 color_avg /= color_divisor;
670 glm::dvec3 hsl = rgb2hsl(color_avg);
671 genome.base_hue = { hsl.x, 0.01 };
672 genome.base_saturation = { hsl.y, 0.01 };
673 genome.base_lightness = { hsl.z, 0.01 };
674 // use opposite color as start highlight
675 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
676 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
677 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
682 void Genome::Configure(Creature &c) const {
683 c.GetGenome() = *this;
685 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
687 c.GetProperties() = Instantiate(properties, random);
689 // TODO: derive stats from properties
690 c.GetStats().Damage().gain = (-1.0 / 100.0);
691 c.GetStats().Breath().gain = (1.0 / 5.0);
692 c.GetStats().Thirst().gain = (1.0 / 60.0);
693 c.GetStats().Hunger().gain = (1.0 / 200.0);
694 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
695 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
696 c.GetStats().Boredom().gain = (1.0 / 300.0);
698 glm::dvec3 base_color(
699 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
700 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
701 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
703 glm::dvec3 highlight_color(
704 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
705 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
706 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
708 c.BaseColor(hsl2rgb(base_color));
709 c.HighlightColor(hsl2rgb(highlight_color));
710 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
711 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
715 void Split(Creature &c) {
716 Creature *a = new Creature(c.GetSimulation());
717 const Situation &s = c.GetSituation();
719 a->Name(c.GetSimulation().Assets().name.Sequential());
720 c.GetGenome().Configure(*a);
721 for (const auto &cmp : c.GetComposition()) {
722 a->AddMass(cmp.resource, cmp.value * 0.5);
724 s.GetPlanet().AddCreature(a);
725 // TODO: duplicate situation somehow
726 a->GetSituation().SetPlanetSurface(
728 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
730 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
732 Creature *b = new Creature(c.GetSimulation());
734 b->Name(c.GetSimulation().Assets().name.Sequential());
735 c.GetGenome().Configure(*b);
736 for (const auto &cmp : c.GetComposition()) {
737 b->AddMass(cmp.resource, cmp.value * 0.5);
739 s.GetPlanet().AddCreature(b);
740 b->GetSituation().SetPlanetSurface(
742 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
744 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
750 Memory::Memory(Creature &c)
757 void Memory::Erase() {
761 void Memory::Tick(double dt) {
762 Situation &s = c.GetSituation();
764 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
768 void Memory::TrackStay(const Location &l, double t) {
769 const world::TileType &type = l.planet->TileTypeAt(l.position);
770 auto entry = known_types.find(type.id);
771 if (entry != known_types.end()) {
772 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
774 if (entry->second.time_spent > c.Age() * 0.25) {
775 // the place is very familiar
776 c.GetStats().Boredom().Add(-0.2);
779 c.GetStats().Boredom().Add(-0.1);
782 entry->second.last_been = c.GetSimulation().Time();
783 entry->second.last_loc = l;
784 entry->second.time_spent += t;
786 known_types.emplace(type.id, Stay{
787 c.GetSimulation().Time(),
789 c.GetSimulation().Time(),
793 // completely new place, interesting
794 // TODO: scale by personality trait
795 c.GetStats().Boredom().Add(-0.25);
800 NameGenerator::NameGenerator()
804 NameGenerator::~NameGenerator() {
807 std::string NameGenerator::Sequential() {
808 std::stringstream ss;
809 ss << "Blob " << ++counter;
814 Situation::Situation()
816 , state(glm::dvec3(0.0), glm::dvec3(0.0))
820 Situation::~Situation() {
823 bool Situation::OnPlanet() const noexcept {
824 return type == PLANET_SURFACE;
827 bool Situation::OnSurface() const noexcept {
828 return type == PLANET_SURFACE;
831 world::Tile &Situation::GetTile() const noexcept {
832 return planet->TileAt(state.pos);
835 const world::TileType &Situation::GetTileType() const noexcept {
836 return planet->TileTypeAt(state.pos);
839 void Situation::Move(const glm::dvec3 &dp) noexcept {
841 EnforceConstraints(state);
844 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
846 EnforceConstraints(state);
849 void Situation::EnforceConstraints(State &s) noexcept {
851 double r = GetPlanet().Radius();
852 if (length2(s.pos) < r * r) {
853 s.pos = normalize(s.pos) * r;
858 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
859 type = PLANET_SURFACE;
862 EnforceConstraints(state);
866 Steering::Steering(const Creature &c)
880 Steering::~Steering() {
883 void Steering::Off() noexcept {
890 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
892 min_dist = min_distance;
893 max_look = max_lookaround;
896 void Steering::DontSeparate() noexcept {
900 void Steering::ResumeSeparate() noexcept {
904 void Steering::Halt() noexcept {
910 void Steering::Pass(const glm::dvec3 &t) noexcept {
917 void Steering::GoTo(const glm::dvec3 &t) noexcept {
924 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
925 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
926 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
927 glm::dvec3 result(0.0);
929 // TODO: off surface situation
930 glm::dvec3 repulse(0.0);
931 const Situation &s = c.GetSituation();
932 for (auto &other : s.GetPlanet().Creatures()) {
933 if (&*other == &c) continue;
934 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
935 if (length2(diff) > max_look * max_look) continue;
936 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
937 double sep = glm::clamp(length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
938 repulse += normalize(diff) * (1.0 - sep / min_dist) * force;
943 // break twice as hard
944 result += -2.0 * s.vel * force;
947 glm::dvec3 diff = target - s.pos;
948 if (!allzero(diff)) {
949 result += TargetVelocity(s, (normalize(diff) * speed), force);
953 glm::dvec3 diff = target - s.pos;
954 double dist = length(diff);
955 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
956 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
959 if (length2(result) > max_force * max_force) {
960 result = normalize(result) * max_force;
965 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
966 return (vel - s.vel) * acc;