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 std::ostream &log = sim.Log() << name << " ";
220 if (stats.Exhaustion().Full()) {
221 log << "died of exhaustion";
222 } else if (stats.Breath().Full()) {
224 } else if (stats.Thirst().Full()) {
225 log << "died of thirst";
226 } else if (stats.Hunger().Full()) {
227 log << "starved to death";
229 log << "succumed to wounds";
231 log << " at an age of " << ui::TimeString(Age())
232 << " (" << ui::PercentageString(Age() / properties.Lifetime())
233 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
245 bool Creature::Dead() const noexcept {
246 return death > birth;
249 void Creature::Remove() noexcept {
253 void Creature::Removed() noexcept {
260 void Creature::AddParent(Creature &p) {
261 parents.push_back(&p);
264 double Creature::Age() const noexcept {
265 return sim.Time() - birth;
268 double Creature::AgeFactor(double peak) const noexcept {
269 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
270 // goes negative below -0.5 and starts to rise again above 1.0
271 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
272 // guarantee at least 1%
273 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
276 double Creature::EnergyEfficiency() const noexcept {
277 return 0.25 * AgeFactor(0.05);
280 double Creature::ExhaustionFactor() const noexcept {
281 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
284 double Creature::FatigueFactor() const noexcept {
285 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
288 double Creature::Strength() const noexcept {
289 // TODO: replace all age factors with actual growth and decay
290 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
293 double Creature::Stamina() const noexcept {
294 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
297 double Creature::Dexerty() const noexcept {
298 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
301 double Creature::Intelligence() const noexcept {
302 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
305 double Creature::Lifetime() const noexcept {
306 return properties.Lifetime();
309 double Creature::Fertility() const noexcept {
310 return properties.Fertility() * AgeFactor(0.25);
313 double Creature::Mutability() const noexcept {
314 return properties.Mutability();
317 double Creature::Adaptability() const noexcept {
318 return properties.Adaptability();
321 double Creature::OffspringMass() const noexcept {
322 return properties.OffspringMass();
325 double Creature::PerceptionRange() const noexcept {
326 return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
329 double Creature::PerceptionOmniRange() const noexcept {
330 return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
333 double Creature::PerceptionField() const noexcept {
334 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
335 return 0.8 - (Dexerty() / (Dexerty() + 1));
338 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
339 const glm::dvec3 diff(p - situation.Position());
340 double omni_range = PerceptionOmniRange();
341 if (length2(diff) < omni_range * omni_range) return true;
342 double range = PerceptionRange();
343 if (length2(diff) > range * range) return false;
344 return dot(normalize(diff), situation.Heading()) > PerceptionField();
347 double Creature::OffspringChance() const noexcept {
348 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
351 double Creature::MutateChance() const noexcept {
352 return GetProperties().Mutability() * (1.0 / 3600.0);
355 double Creature::AdaptChance() const noexcept {
356 return GetProperties().Adaptability() * (1.0 / 120.0);
359 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
361 goals.emplace_back(std::move(g));
366 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
367 return b->Urgency() < a->Urgency();
372 void Creature::Tick(double dt) {
378 void Creature::TickState(double dt) {
379 steering.MaxSpeed(Dexerty());
380 steering.MaxForce(Strength());
381 Situation::State state(situation.GetState());
382 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
383 Situation::Derivative b(Step(a, dt * 0.5));
384 Situation::Derivative c(Step(b, dt * 0.5));
385 Situation::Derivative d(Step(c, dt));
386 Situation::Derivative f(
387 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
388 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
390 state.pos += f.vel * dt;
391 state.vel += f.acc * dt;
392 situation.EnforceConstraints(state);
393 if (length2(state.vel) > 0.000001) {
394 glm::dvec3 nvel(normalize(state.vel));
395 double ang = angle(nvel, state.dir);
396 double turn_rate = PI * 0.75 * dt;
397 if (ang < turn_rate) {
398 state.dir = normalize(state.vel);
399 } else if (std::abs(ang - PI) < 0.001) {
400 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
402 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
405 situation.SetState(state);
406 // work is force times distance
407 DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
410 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
411 Situation::State s = situation.GetState();
412 s.pos += ds.vel * dt;
413 s.vel += ds.acc * dt;
414 glm::dvec3 force(steering.Force(s));
415 // gravity = antinormal * mass * Gm / r²
416 double elevation = s.pos[(situation.Surface() + 2) % 3];
417 glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
420 * Mass() * situation.GetPlanet().GravitationalParameter()
421 / (elevation * elevation));
422 // if net force is applied and in contact with surface
423 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
424 // apply friction = -|normal force| * tangential force * coefficient
425 glm::dvec3 fn(normal * dot(force, normal));
426 glm::dvec3 ft(force - fn);
428 glm::dvec3 friction(-length(fn) * ft * u);
437 void Creature::TickStats(double dt) {
438 for (auto &s : stats.stat) {
441 // TODO: damage values depending on properties
442 if (stats.Breath().Full()) {
443 constexpr double dps = 1.0 / 4.0;
446 if (stats.Thirst().Full()) {
447 constexpr double dps = 1.0 / 32.0;
450 if (stats.Hunger().Full()) {
451 constexpr double dps = 1.0 / 128.0;
454 if (!situation.Moving()) {
455 // double exhaustion recovery when standing still
456 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
460 void Creature::TickBrain(double dt) {
464 // do background stuff
468 for (auto &goal : goals) {
471 // if active goal can be interrupted, check priorities
472 if (goals.size() > 1 && goals[0]->Interruptible()) {
473 std::sort(goals.begin(), goals.end(), GoalCompare);
476 for (auto goal = goals.begin(); goal != goals.end();) {
477 if ((*goal)->Complete()) {
485 math::AABB Creature::CollisionBox() const noexcept {
486 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
489 glm::dmat4 Creature::CollisionTransform() const noexcept {
490 const double half_size = size * 0.5;
491 const glm::dvec3 &pos = situation.Position();
492 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
493 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
494 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
498 glm::dmat4 Creature::LocalTransform() noexcept {
499 const double half_size = size * 0.5;
500 return CollisionTransform()
501 * glm::scale(glm::dvec3(half_size, half_size, half_size));
504 void Creature::BuildVAO() {
505 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
507 vao->BindAttributes();
508 vao->EnableAttribute(0);
509 vao->EnableAttribute(1);
510 vao->EnableAttribute(2);
511 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
512 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
513 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
514 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
516 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
517 const float offset = 1.0f;
518 for (int surface = 0; surface < 6; ++surface) {
519 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
520 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
522 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
523 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
524 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
525 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
526 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
527 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
528 attrib[4 * surface + 0].texture.x = tex_u_begin;
529 attrib[4 * surface + 0].texture.y = 1.0f;
530 attrib[4 * surface + 0].texture.z = surface;
532 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
533 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
534 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
535 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
536 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
537 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
538 attrib[4 * surface + 1].texture.x = tex_u_end;
539 attrib[4 * surface + 1].texture.y = 1.0f;
540 attrib[4 * surface + 1].texture.z = surface;
542 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
543 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
544 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
545 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
546 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
547 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
548 attrib[4 * surface + 2].texture.x = tex_u_begin;
549 attrib[4 * surface + 2].texture.y = 0.0f;
550 attrib[4 * surface + 2].texture.z = surface;
552 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
553 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
554 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
555 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
556 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
557 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
558 attrib[4 * surface + 3].texture.x = tex_u_end;
559 attrib[4 * surface + 3].texture.y = 0.0f;
560 attrib[4 * surface + 3].texture.z = surface;
564 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
566 auto element = vao->MapElements(GL_WRITE_ONLY);
567 for (int surface = 0; surface < 3; ++surface) {
568 element[6 * surface + 0] = 4 * surface + 0;
569 element[6 * surface + 1] = 4 * surface + 2;
570 element[6 * surface + 2] = 4 * surface + 1;
571 element[6 * surface + 3] = 4 * surface + 1;
572 element[6 * surface + 4] = 4 * surface + 2;
573 element[6 * surface + 5] = 4 * surface + 3;
575 for (int surface = 3; surface < 6; ++surface) {
576 element[6 * surface + 0] = 4 * surface + 0;
577 element[6 * surface + 1] = 4 * surface + 1;
578 element[6 * surface + 2] = 4 * surface + 2;
579 element[6 * surface + 3] = 4 * surface + 2;
580 element[6 * surface + 4] = 4 * surface + 1;
581 element[6 * surface + 5] = 4 * surface + 3;
587 void Creature::KillVAO() {
591 void Creature::Draw(graphics::Viewport &viewport) {
594 vao->DrawTriangles(6 * 6);
598 void Spawn(Creature &c, world::Planet &p) {
600 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
601 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
603 // probe surrounding area for common resources
604 int start = p.SideLength() / 2 - 2;
606 std::map<int, double> yields;
607 for (int y = start; y < end; ++y) {
608 for (int x = start; x < end; ++x) {
609 const world::TileType &t = p.TypeAt(0, x, y);
610 for (auto yield : t.resources) {
611 yields[yield.resource] += yield.ubiquity;
617 for (auto e : yields) {
618 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
619 if (liquid < 0 || e.second > yields[liquid]) {
622 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
623 if (solid < 0 || e.second > yields[solid]) {
630 genome.properties.Strength() = { 2.0, 0.1 };
631 genome.properties.Stamina() = { 2.0, 0.1 };
632 genome.properties.Dexerty() = { 2.0, 0.1 };
633 genome.properties.Intelligence() = { 1.0, 0.1 };
634 genome.properties.Lifetime() = { 480.0, 60.0 };
635 genome.properties.Fertility() = { 0.5, 0.03 };
636 genome.properties.Mutability() = { 0.9, 0.1 };
637 genome.properties.Adaptability() = { 0.9, 0.1 };
638 genome.properties.OffspringMass() = { 0.3, 0.02 };
640 glm::dvec3 color_avg(0.0);
641 double color_divisor = 0.0;
643 if (p.HasAtmosphere()) {
644 c.AddMass(p.Atmosphere(), 0.01);
645 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
646 color_divisor += 0.1;
649 c.AddMass(liquid, 0.3);
650 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
651 color_divisor += 0.5;
654 c.AddMass(solid, 0.1);
655 color_avg += c.GetSimulation().Resources()[solid].base_color;
656 color_divisor += 1.0;
659 if (color_divisor > 0.001) {
660 color_avg /= color_divisor;
662 glm::dvec3 hsl = rgb2hsl(color_avg);
663 genome.base_hue = { hsl.x, 0.01 };
664 genome.base_saturation = { hsl.y, 0.01 };
665 genome.base_lightness = { hsl.z, 0.01 };
666 // use opposite color as start highlight
667 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
668 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
669 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
674 void Genome::Configure(Creature &c) const {
675 c.GetGenome() = *this;
677 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
679 c.GetProperties() = Instantiate(properties, random);
681 // TODO: derive stats from properties
682 c.GetStats().Damage().gain = (-1.0 / 100.0);
683 c.GetStats().Breath().gain = (1.0 / 5.0);
684 c.GetStats().Thirst().gain = (1.0 / 60.0);
685 c.GetStats().Hunger().gain = (1.0 / 200.0);
686 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
687 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
688 c.GetStats().Boredom().gain = (1.0 / 300.0);
690 glm::dvec3 base_color(
691 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
692 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
693 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
695 glm::dvec3 highlight_color(
696 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
697 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
698 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
700 c.BaseColor(hsl2rgb(base_color));
701 c.HighlightColor(hsl2rgb(highlight_color));
702 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
703 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
707 void Split(Creature &c) {
708 Creature *a = new Creature(c.GetSimulation());
709 const Situation &s = c.GetSituation();
711 a->Name(c.GetSimulation().Assets().name.Sequential());
712 c.GetGenome().Configure(*a);
713 for (const auto &cmp : c.GetComposition()) {
714 a->AddMass(cmp.resource, cmp.value * 0.5);
716 s.GetPlanet().AddCreature(a);
717 // TODO: duplicate situation somehow
718 a->GetSituation().SetPlanetSurface(
719 s.GetPlanet(), s.Surface(),
720 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
722 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
724 Creature *b = new Creature(c.GetSimulation());
726 b->Name(c.GetSimulation().Assets().name.Sequential());
727 c.GetGenome().Configure(*b);
728 for (const auto &cmp : c.GetComposition()) {
729 b->AddMass(cmp.resource, cmp.value * 0.5);
731 s.GetPlanet().AddCreature(b);
732 b->GetSituation().SetPlanetSurface(
733 s.GetPlanet(), s.Surface(),
734 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
736 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
742 Memory::Memory(Creature &c)
749 void Memory::Erase() {
753 void Memory::Tick(double dt) {
754 Situation &s = c.GetSituation();
756 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
760 void Memory::TrackStay(const Location &l, double t) {
761 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
762 auto entry = known_types.find(type.id);
763 if (entry != known_types.end()) {
764 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
766 if (entry->second.time_spent > c.Age() * 0.25) {
767 // the place is very familiar
768 c.GetStats().Boredom().Add(-0.2);
771 c.GetStats().Boredom().Add(-0.1);
774 entry->second.last_been = c.GetSimulation().Time();
775 entry->second.last_loc = l;
776 entry->second.time_spent += t;
778 known_types.emplace(type.id, Stay{
779 c.GetSimulation().Time(),
781 c.GetSimulation().Time(),
785 // completely new place, interesting
786 // TODO: scale by personality trait
787 c.GetStats().Boredom().Add(-0.25);
792 NameGenerator::NameGenerator()
796 NameGenerator::~NameGenerator() {
799 std::string NameGenerator::Sequential() {
800 std::stringstream ss;
801 ss << "Blob " << ++counter;
806 Situation::Situation()
808 , state(glm::dvec3(0.0), glm::dvec3(0.0))
813 Situation::~Situation() {
816 bool Situation::OnPlanet() const noexcept {
817 return type == PLANET_SURFACE;
820 bool Situation::OnSurface() const noexcept {
821 return type == PLANET_SURFACE;
824 bool Situation::OnTile() const noexcept {
825 if (type != PLANET_SURFACE) return false;
826 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
827 return t.x >= 0 && t.x < planet->SideLength()
828 && t.y >= 0 && t.y < planet->SideLength();
831 glm::ivec2 Situation::SurfacePosition() const noexcept {
832 return planet->SurfacePosition(surface, state.pos);
835 world::Tile &Situation::GetTile() const noexcept {
836 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
837 return planet->TileAt(surface, t.x, t.y);
840 const world::TileType &Situation::GetTileType() const noexcept {
841 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
842 return planet->TypeAt(surface, t.x, t.y);
845 void Situation::Move(const glm::dvec3 &dp) noexcept {
847 EnforceConstraints(state);
850 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
852 EnforceConstraints(state);
855 void Situation::EnforceConstraints(State &s) noexcept {
858 if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
859 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
860 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
863 if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
864 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
865 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
871 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
872 type = PLANET_SURFACE;
876 EnforceConstraints(state);
880 Steering::Steering(const Creature &c)
894 Steering::~Steering() {
897 void Steering::Off() noexcept {
904 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
906 min_dist = min_distance;
907 max_look = max_lookaround;
910 void Steering::DontSeparate() noexcept {
914 void Steering::ResumeSeparate() noexcept {
918 void Steering::Halt() noexcept {
924 void Steering::Pass(const glm::dvec3 &t) noexcept {
931 void Steering::GoTo(const glm::dvec3 &t) noexcept {
938 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
939 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
940 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
941 glm::dvec3 result(0.0);
943 // TODO: off surface situation
944 glm::dvec3 repulse(0.0);
945 const Situation &s = c.GetSituation();
946 for (auto &other : s.GetPlanet().Creatures()) {
947 if (&*other == &c) continue;
948 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
949 if (length2(diff) > max_look * max_look) continue;
950 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
951 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
952 if (sep < min_dist) {
953 repulse += normalize(diff) * (1.0 - sep / min_dist);
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;