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()) {
212 std::ostream &log = sim.Log() << name << " ";
213 if (stats.Exhaustion().Full()) {
214 log << "died of exhaustion";
215 } else if (stats.Breath().Full()) {
217 } else if (stats.Thirst().Full()) {
218 log << "died of thirst";
219 } else if (stats.Hunger().Full()) {
220 log << "starved to death";
222 log << "succumed to wounds";
224 log << " at an age of " << ui::TimeString(Age())
225 << " (" << ui::PercentageString(Age() / properties.Lifetime())
226 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
232 void Creature::Die() noexcept {
244 bool Creature::Dead() const noexcept {
245 return death > birth;
248 void Creature::Remove() noexcept {
252 void Creature::Removed() noexcept {
259 void Creature::AddParent(Creature &p) {
260 parents.push_back(&p);
263 double Creature::Age() const noexcept {
264 return sim.Time() - birth;
267 double Creature::AgeFactor(double peak) const noexcept {
268 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
269 // goes negative below -0.5 and starts to rise again above 1.0
270 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
271 // guarantee at least 1%
272 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
275 double Creature::EnergyEfficiency() const noexcept {
276 return 0.25 * AgeFactor(0.05);
279 double Creature::ExhaustionFactor() const noexcept {
280 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
283 double Creature::FatigueFactor() const noexcept {
284 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
287 double Creature::Strength() const noexcept {
288 // TODO: replace all age factors with actual growth and decay
289 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
292 double Creature::Stamina() const noexcept {
293 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
296 double Creature::Dexerty() const noexcept {
297 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
300 double Creature::Intelligence() const noexcept {
301 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
304 double Creature::Lifetime() const noexcept {
305 return properties.Lifetime();
308 double Creature::Fertility() const noexcept {
309 return properties.Fertility() * AgeFactor(0.25);
312 double Creature::Mutability() const noexcept {
313 return properties.Mutability();
316 double Creature::Adaptability() const noexcept {
317 return properties.Adaptability();
320 double Creature::OffspringMass() const noexcept {
321 return properties.OffspringMass();
324 double Creature::PerceptionRange() const noexcept {
325 return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
328 double Creature::PerceptionOmniRange() const noexcept {
329 return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
332 double Creature::PerceptionField() const noexcept {
333 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
334 return 0.8 - (Dexerty() / (Dexerty() + 1));
337 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
338 const glm::dvec3 diff(p - situation.Position());
339 double omni_range = PerceptionOmniRange();
340 if (length2(diff) < omni_range * omni_range) return true;
341 double range = PerceptionRange();
342 if (length2(diff) > range * range) return false;
343 return dot(normalize(diff), situation.Heading()) > PerceptionField();
346 double Creature::OffspringChance() const noexcept {
347 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
350 double Creature::MutateChance() const noexcept {
351 return GetProperties().Mutability() * (1.0 / 3600.0);
354 double Creature::AdaptChance() const noexcept {
355 return GetProperties().Adaptability() * (1.0 / 120.0);
358 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
360 goals.emplace_back(std::move(g));
365 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
366 return b->Urgency() < a->Urgency();
371 void Creature::Tick(double dt) {
377 void Creature::TickState(double dt) {
378 steering.MaxSpeed(Dexerty());
379 steering.MaxForce(Strength());
380 Situation::State state(situation.GetState());
381 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
382 Situation::Derivative b(Step(a, dt * 0.5));
383 Situation::Derivative c(Step(b, dt * 0.5));
384 Situation::Derivative d(Step(c, dt));
385 Situation::Derivative f(
386 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
387 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
389 state.pos += f.vel * dt;
390 state.vel += f.acc * dt;
391 situation.EnforceConstraints(state);
392 if (length2(state.vel) > 0.000001) {
393 glm::dvec3 nvel(normalize(state.vel));
394 double ang = angle(nvel, state.dir);
395 double turn_rate = PI * 0.75 * dt;
396 if (ang < turn_rate) {
397 state.dir = normalize(state.vel);
398 } else if (std::abs(ang - PI) < 0.001) {
399 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
401 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
404 situation.SetState(state);
405 // work is force times distance
406 DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
409 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
410 Situation::State s = situation.GetState();
411 s.pos += ds.vel * dt;
412 s.vel += ds.acc * dt;
413 glm::dvec3 force(steering.Force(s));
414 // gravity = antinormal * mass * Gm / r²
415 double elevation = s.pos[(situation.Surface() + 2) % 3];
416 glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
419 * Mass() * situation.GetPlanet().GravitationalParameter()
420 / (elevation * elevation));
421 // if net force is applied and in contact with surface
422 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
423 // apply friction = -|normal force| * tangential force * coefficient
424 glm::dvec3 fn(normal * dot(force, normal));
425 glm::dvec3 ft(force - fn);
427 glm::dvec3 friction(-length(fn) * ft * u);
436 void Creature::TickStats(double dt) {
437 for (auto &s : stats.stat) {
440 // TODO: damage values depending on properties
441 if (stats.Breath().Full()) {
442 constexpr double dps = 1.0 / 4.0;
445 if (stats.Thirst().Full()) {
446 constexpr double dps = 1.0 / 32.0;
449 if (stats.Hunger().Full()) {
450 constexpr double dps = 1.0 / 128.0;
453 if (!situation.Moving()) {
454 // double exhaustion recovery when standing still
455 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
459 void Creature::TickBrain(double dt) {
463 // do background stuff
467 for (auto &goal : goals) {
470 // if active goal can be interrupted, check priorities
471 if (goals.size() > 1 && goals[0]->Interruptible()) {
472 std::sort(goals.begin(), goals.end(), GoalCompare);
475 for (auto goal = goals.begin(); goal != goals.end();) {
476 if ((*goal)->Complete()) {
484 math::AABB Creature::CollisionBox() const noexcept {
485 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
488 glm::dmat4 Creature::CollisionTransform() const noexcept {
489 const double half_size = size * 0.5;
490 const glm::dvec3 &pos = situation.Position();
491 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
492 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
493 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
497 glm::dmat4 Creature::LocalTransform() noexcept {
498 const double half_size = size * 0.5;
499 return CollisionTransform()
500 * glm::scale(glm::dvec3(half_size, half_size, half_size));
503 void Creature::BuildVAO() {
504 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
506 vao->BindAttributes();
507 vao->EnableAttribute(0);
508 vao->EnableAttribute(1);
509 vao->EnableAttribute(2);
510 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
511 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
512 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
513 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
515 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
516 const float offset = 1.0f;
517 for (int surface = 0; surface < 6; ++surface) {
518 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
519 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
521 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
522 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
523 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
524 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
525 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
526 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
527 attrib[4 * surface + 0].texture.x = tex_u_begin;
528 attrib[4 * surface + 0].texture.y = 1.0f;
529 attrib[4 * surface + 0].texture.z = surface;
531 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
532 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
533 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
534 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
535 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
536 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
537 attrib[4 * surface + 1].texture.x = tex_u_end;
538 attrib[4 * surface + 1].texture.y = 1.0f;
539 attrib[4 * surface + 1].texture.z = surface;
541 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
542 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
543 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
544 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
545 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
546 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
547 attrib[4 * surface + 2].texture.x = tex_u_begin;
548 attrib[4 * surface + 2].texture.y = 0.0f;
549 attrib[4 * surface + 2].texture.z = surface;
551 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
552 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
553 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
554 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
555 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
556 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
557 attrib[4 * surface + 3].texture.x = tex_u_end;
558 attrib[4 * surface + 3].texture.y = 0.0f;
559 attrib[4 * surface + 3].texture.z = surface;
563 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
565 auto element = vao->MapElements(GL_WRITE_ONLY);
566 for (int surface = 0; surface < 3; ++surface) {
567 element[6 * surface + 0] = 4 * surface + 0;
568 element[6 * surface + 1] = 4 * surface + 2;
569 element[6 * surface + 2] = 4 * surface + 1;
570 element[6 * surface + 3] = 4 * surface + 1;
571 element[6 * surface + 4] = 4 * surface + 2;
572 element[6 * surface + 5] = 4 * surface + 3;
574 for (int surface = 3; surface < 6; ++surface) {
575 element[6 * surface + 0] = 4 * surface + 0;
576 element[6 * surface + 1] = 4 * surface + 1;
577 element[6 * surface + 2] = 4 * surface + 2;
578 element[6 * surface + 3] = 4 * surface + 2;
579 element[6 * surface + 4] = 4 * surface + 1;
580 element[6 * surface + 5] = 4 * surface + 3;
586 void Creature::KillVAO() {
590 void Creature::Draw(graphics::Viewport &viewport) {
593 vao->DrawTriangles(6 * 6);
597 void Spawn(Creature &c, world::Planet &p) {
599 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
600 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
602 // probe surrounding area for common resources
603 int start = p.SideLength() / 2 - 2;
605 std::map<int, double> yields;
606 for (int y = start; y < end; ++y) {
607 for (int x = start; x < end; ++x) {
608 const world::TileType &t = p.TypeAt(0, x, y);
609 for (auto yield : t.resources) {
610 yields[yield.resource] += yield.ubiquity;
616 for (auto e : yields) {
617 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
618 if (liquid < 0 || e.second > yields[liquid]) {
621 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
622 if (solid < 0 || e.second > yields[solid]) {
629 genome.properties.Strength() = { 2.0, 0.1 };
630 genome.properties.Stamina() = { 2.0, 0.1 };
631 genome.properties.Dexerty() = { 2.0, 0.1 };
632 genome.properties.Intelligence() = { 1.0, 0.1 };
633 genome.properties.Lifetime() = { 480.0, 60.0 };
634 genome.properties.Fertility() = { 0.5, 0.03 };
635 genome.properties.Mutability() = { 0.9, 0.1 };
636 genome.properties.Adaptability() = { 0.9, 0.1 };
637 genome.properties.OffspringMass() = { 0.3, 0.02 };
639 glm::dvec3 color_avg(0.0);
640 double color_divisor = 0.0;
642 if (p.HasAtmosphere()) {
643 c.AddMass(p.Atmosphere(), 0.01);
644 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
645 color_divisor += 0.1;
648 c.AddMass(liquid, 0.3);
649 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
650 color_divisor += 0.5;
653 c.AddMass(solid, 0.1);
654 color_avg += c.GetSimulation().Resources()[solid].base_color;
655 color_divisor += 1.0;
658 if (color_divisor > 0.001) {
659 color_avg /= color_divisor;
661 glm::dvec3 hsl = rgb2hsl(color_avg);
662 genome.base_hue = { hsl.x, 0.01 };
663 genome.base_saturation = { hsl.y, 0.01 };
664 genome.base_lightness = { hsl.z, 0.01 };
665 // use opposite color as start highlight
666 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
667 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
668 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
673 void Genome::Configure(Creature &c) const {
674 c.GetGenome() = *this;
676 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
678 c.GetProperties() = Instantiate(properties, random);
680 // TODO: derive stats from properties
681 c.GetStats().Damage().gain = (-1.0 / 100.0);
682 c.GetStats().Breath().gain = (1.0 / 5.0);
683 c.GetStats().Thirst().gain = (1.0 / 60.0);
684 c.GetStats().Hunger().gain = (1.0 / 200.0);
685 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
686 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
687 c.GetStats().Boredom().gain = (1.0 / 300.0);
689 glm::dvec3 base_color(
690 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
691 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
692 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
694 glm::dvec3 highlight_color(
695 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
696 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
697 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
699 c.BaseColor(hsl2rgb(base_color));
700 c.HighlightColor(hsl2rgb(highlight_color));
701 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
702 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
706 void Split(Creature &c) {
707 Creature *a = new Creature(c.GetSimulation());
708 const Situation &s = c.GetSituation();
710 a->Name(c.GetSimulation().Assets().name.Sequential());
711 c.GetGenome().Configure(*a);
712 for (const auto &cmp : c.GetComposition()) {
713 a->AddMass(cmp.resource, cmp.value * 0.5);
715 s.GetPlanet().AddCreature(a);
716 // TODO: duplicate situation somehow
717 a->GetSituation().SetPlanetSurface(
718 s.GetPlanet(), s.Surface(),
719 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
721 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
723 Creature *b = new Creature(c.GetSimulation());
725 b->Name(c.GetSimulation().Assets().name.Sequential());
726 c.GetGenome().Configure(*b);
727 for (const auto &cmp : c.GetComposition()) {
728 b->AddMass(cmp.resource, cmp.value * 0.5);
730 s.GetPlanet().AddCreature(b);
731 b->GetSituation().SetPlanetSurface(
732 s.GetPlanet(), s.Surface(),
733 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
735 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
741 Memory::Memory(Creature &c)
748 void Memory::Erase() {
752 void Memory::Tick(double dt) {
753 Situation &s = c.GetSituation();
755 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
759 void Memory::TrackStay(const Location &l, double t) {
760 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
761 auto entry = known_types.find(type.id);
762 if (entry != known_types.end()) {
763 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
765 if (entry->second.time_spent > c.Age() * 0.25) {
766 // the place is very familiar
767 c.GetStats().Boredom().Add(-0.2);
770 c.GetStats().Boredom().Add(-0.1);
773 entry->second.last_been = c.GetSimulation().Time();
774 entry->second.last_loc = l;
775 entry->second.time_spent += t;
777 known_types.emplace(type.id, Stay{
778 c.GetSimulation().Time(),
780 c.GetSimulation().Time(),
784 // completely new place, interesting
785 // TODO: scale by personality trait
786 c.GetStats().Boredom().Add(-0.25);
791 NameGenerator::NameGenerator()
795 NameGenerator::~NameGenerator() {
798 std::string NameGenerator::Sequential() {
799 std::stringstream ss;
800 ss << "Blob " << ++counter;
805 Situation::Situation()
807 , state(glm::dvec3(0.0), glm::dvec3(0.0))
812 Situation::~Situation() {
815 bool Situation::OnPlanet() const noexcept {
816 return type == PLANET_SURFACE;
819 bool Situation::OnSurface() const noexcept {
820 return type == PLANET_SURFACE;
823 bool Situation::OnTile() const noexcept {
824 if (type != PLANET_SURFACE) return false;
825 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
826 return t.x >= 0 && t.x < planet->SideLength()
827 && t.y >= 0 && t.y < planet->SideLength();
830 glm::ivec2 Situation::SurfacePosition() const noexcept {
831 return planet->SurfacePosition(surface, state.pos);
834 world::Tile &Situation::GetTile() const noexcept {
835 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
836 return planet->TileAt(surface, t.x, t.y);
839 const world::TileType &Situation::GetTileType() const noexcept {
840 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
841 return planet->TypeAt(surface, t.x, t.y);
844 void Situation::Move(const glm::dvec3 &dp) noexcept {
846 EnforceConstraints(state);
849 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
851 EnforceConstraints(state);
854 void Situation::EnforceConstraints(State &s) noexcept {
857 if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
858 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
859 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
862 if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
863 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
864 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
870 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
871 type = PLANET_SURFACE;
875 EnforceConstraints(state);
879 Steering::Steering(const Creature &c)
893 Steering::~Steering() {
896 void Steering::Off() noexcept {
903 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
905 min_dist = min_distance;
906 max_look = max_lookaround;
909 void Steering::DontSeparate() noexcept {
913 void Steering::ResumeSeparate() noexcept {
917 void Steering::Halt() noexcept {
923 void Steering::Pass(const glm::dvec3 &t) noexcept {
930 void Steering::GoTo(const glm::dvec3 &t) noexcept {
937 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
938 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
939 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
940 glm::dvec3 result(0.0);
942 // TODO: off surface situation
943 glm::dvec3 repulse(0.0);
944 const Situation &s = c.GetSituation();
945 for (auto &other : s.GetPlanet().Creatures()) {
946 if (&*other == &c) continue;
947 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
948 if (length2(diff) > max_look * max_look) continue;
949 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
950 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
951 if (sep < min_dist) {
952 repulse += normalize(diff) * (1.0 - sep / min_dist);
958 // break twice as hard
959 result += -2.0 * s.vel * force;
962 glm::dvec3 diff = target - s.pos;
963 if (!allzero(diff)) {
964 result += TargetVelocity(s, (normalize(diff) * speed), force);
968 glm::dvec3 diff = target - s.pos;
969 double dist = length(diff);
970 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
971 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
974 if (length2(result) > max_force * max_force) {
975 result = normalize(result) * max_force;
980 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
981 return (vel - s.vel) * acc;