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(const world::Set<world::Resource> &resources)
33 : resources(resources)
39 Composition::~Composition() {
43 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
44 return b.value < a.value;
48 void Composition::Add(int res, double amount) {
50 for (auto c = components.begin(); c != components.end(); ++c) {
51 if (c->resource == res) {
53 if (c->value <= 0.0) {
61 if (!found && amount > 0.0) {
62 components.emplace_back(res, amount);
64 std::sort(components.begin(), components.end(), CompositionCompare);
65 state_mass[resources[res].state] += amount;
69 bool Composition::Has(int res) const noexcept {
70 for (auto &c : components) {
71 if (c.resource == res) {
78 double Composition::Get(int res) const noexcept {
79 for (auto &c : components) {
80 if (c.resource == res) {
87 double Composition::Proportion(int res) const noexcept {
88 return Get(res) / TotalMass();
91 double Composition::StateProportion(int res) const noexcept {
92 return Get(res) / StateMass(resources[res].state);
95 double Composition::Compatibility(int res) const noexcept {
97 return StateProportion(res);
99 double max_compat = -1.0;
100 double min_compat = 1.0;
101 for (const auto &c : components) {
102 double prop = c.value / StateMass(resources[res].state);
103 for (const auto &compat : resources[c.resource].compatibility) {
104 double value = compat.second * prop;
105 if (value > max_compat) {
108 if (value < min_compat) {
113 if (min_compat < 0.0) {
121 Creature::Creature(world::Simulation &sim)
126 , composition(sim.Resources())
128 , highlight_color(0.0, 0.0, 0.0, 1.0)
144 // all creatures avoid each other for now
145 steering.Separate(0.1, 1.5);
148 Creature::~Creature() {
151 void Creature::AddMass(int res, double amount) {
152 composition.Add(res, amount);
153 double nonsolid = 0.0;
155 for (const auto &c : composition) {
156 volume += c.value / sim.Resources()[c.resource].density;
157 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
161 Mass(composition.TotalMass());
162 Size(std::cbrt(volume));
163 highlight_color.a = nonsolid / composition.TotalMass();
166 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
167 highlight_color = glm::dvec4(c, highlight_color.a);
170 void Creature::Ingest(int res, double amount) noexcept {
171 if (sim.Resources()[res].state == world::Resource::SOLID) {
172 // 30% of solids stays in body
173 AddMass(res, amount * 0.3 * composition.Compatibility(res));
175 // 5% of fluids stays in body
176 AddMass(res, amount * 0.05 * composition.Compatibility(res));
178 math::GaloisLFSR &random = sim.Assets().random;
179 if (random.UNorm() < AdaptChance()) {
180 // change color to be slightly more like resource
181 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
182 // solids affect base color, others highlight
183 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
184 double q = random.UInt(3); // hue, sat, or val
185 double r = random.UInt(2); // mean or deviation
186 math::Distribution *d = nullptr;
190 d = &genome.base_hue;
193 d = &genome.base_saturation;
196 d = &genome.base_lightness;
201 d = &genome.highlight_hue;
204 d = &genome.highlight_saturation;
207 d = &genome.highlight_lightness;
212 double diff = ref - d->Mean();
216 } else if (diff > 0.5) {
219 // move ±15% of distance
220 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
222 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
225 // scale by ±15%, enforce bounds
226 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
231 void Creature::DoWork(double amount) noexcept {
232 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
233 // burn resources proportional to composition
234 // factor = 1/total * 1/efficiency * amount * -1
235 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
236 // make a copy to total remains constant and
237 // no entries disappear during iteration
238 Composition comp(composition);
239 for (auto &cmp : comp) {
240 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
241 AddMass(cmp.resource, value);
243 // doing work improves strength a little
244 properties.Strength() += amount * 0.0001;
247 void Creature::Hurt(double amount) noexcept {
248 stats.Damage().Add(amount);
249 if (stats.Damage().Full()) {
254 void Creature::Die() noexcept {
257 if (stats.Damage().Full()) {
258 std::ostream &log = sim.Log() << name << " ";
259 if (stats.Exhaustion().Full()) {
260 log << "died of exhaustion";
261 } else if (stats.Breath().Full()) {
263 } else if (stats.Thirst().Full()) {
264 log << "died of thirst";
265 } else if (stats.Hunger().Full()) {
266 log << "starved to death";
268 log << "succumed to wounds";
270 log << " at an age of " << ui::TimeString(Age())
271 << " (" << ui::PercentageString(Age() / properties.Lifetime())
272 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
285 bool Creature::Dead() const noexcept {
286 return death > birth;
289 void Creature::Remove() noexcept {
293 void Creature::Removed() noexcept {
300 void Creature::AddParent(Creature &p) {
301 parents.push_back(&p);
304 double Creature::Age() const noexcept {
305 return Dead() ? death - birth : sim.Time() - birth;
308 double Creature::AgeFactor(double peak) const noexcept {
309 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
310 // goes negative below -0.5 and starts to rise again above 1.0
311 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
312 // guarantee at least 1%
313 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
316 double Creature::EnergyEfficiency() const noexcept {
317 return 0.25 * AgeFactor(0.05);
320 double Creature::ExhaustionFactor() const noexcept {
321 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
324 double Creature::FatigueFactor() const noexcept {
325 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
328 double Creature::Strength() const noexcept {
329 // TODO: replace all age factors with actual growth and decay
330 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
333 double Creature::StrengthFactor() const noexcept {
334 return Strength() / (Strength() + 1.0);
337 double Creature::Stamina() const noexcept {
338 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
341 double Creature::StaminaFactor() const noexcept {
342 return Stamina() / (Stamina() + 1.0);
345 double Creature::Dexerty() const noexcept {
346 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
349 double Creature::DexertyFactor() const noexcept {
350 return Dexerty() / (Dexerty() + 1.0);
353 double Creature::Intelligence() const noexcept {
354 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
357 double Creature::IntelligenceFactor() const noexcept {
358 return Intelligence() / (Intelligence() + 1.0);
361 double Creature::Lifetime() const noexcept {
362 return properties.Lifetime();
365 double Creature::Fertility() const noexcept {
366 return properties.Fertility() * AgeFactor(0.25);
369 double Creature::Mutability() const noexcept {
370 return properties.Mutability();
373 double Creature::Adaptability() const noexcept {
374 return properties.Adaptability();
377 double Creature::OffspringMass() const noexcept {
378 return properties.OffspringMass();
381 double Creature::PerceptionRange() const noexcept {
382 return 3.0 * DexertyFactor() + Size();
385 double Creature::PerceptionOmniRange() const noexcept {
386 return 0.5 * DexertyFactor() + Size();
389 double Creature::PerceptionField() const noexcept {
390 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
391 return 0.8 - DexertyFactor();
394 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
395 const glm::dvec3 diff(p - situation.Position());
396 double omni_range = PerceptionOmniRange();
397 if (glm::length2(diff) < omni_range * omni_range) return true;
398 double range = PerceptionRange();
399 if (glm::length2(diff) > range * range) return false;
400 return glm::dot(glm::normalize(diff), situation.Heading()) > PerceptionField();
403 double Creature::OffspringChance() const noexcept {
404 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
407 double Creature::MutateChance() const noexcept {
408 return GetProperties().Mutability() * (1.0 / 3600.0);
411 double Creature::AdaptChance() const noexcept {
412 return GetProperties().Adaptability() * (1.0 / 120.0);
415 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
420 goals.emplace_back(std::move(g));
425 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
426 return b->Urgency() < a->Urgency();
431 void Creature::Tick(double dt) {
437 void Creature::TickState(double dt) {
438 steering.MaxSpeed(Dexerty());
439 steering.MaxForce(Strength());
440 Situation::State state(situation.GetState());
441 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
442 Situation::Derivative b(Step(a, dt * 0.5));
443 Situation::Derivative c(Step(b, dt * 0.5));
444 Situation::Derivative d(Step(c, dt));
445 Situation::Derivative f(
446 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
447 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
449 state.pos += f.vel * dt;
450 state.vel += f.acc * dt;
451 situation.EnforceConstraints(state);
452 if (glm::length2(state.vel) > 0.000001) {
453 glm::dvec3 nvel(glm::normalize(state.vel));
454 double ang = glm::angle(nvel, state.dir);
455 double turn_rate = PI * 0.75 * dt;
456 if (ang < turn_rate) {
457 state.dir = glm::normalize(state.vel);
458 } else if (std::abs(ang - PI) < 0.001) {
459 state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
461 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
464 situation.SetState(state);
465 // work is force times distance
466 // exclude gravity for no apparent reason
467 // actually, this should solely be based on steering force
468 DoWork(glm::length(f.acc - situation.GetPlanet().GravityAt(state.pos)) * Mass() * glm::length(f.vel) * dt);
471 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
472 Situation::State s = situation.GetState();
473 s.pos += ds.vel * dt;
474 s.vel += ds.acc * dt;
475 situation.EnforceConstraints(s);
476 glm::dvec3 force(steering.Force(s));
477 // gravity = antinormal * mass * Gm / r²
478 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
481 * (Mass() * situation.GetPlanet().GravitationalParameter()
482 / glm::length2(s.pos)));
483 // if net force is applied and in contact with surface
484 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
486 glm::dvec3 fn(normal * glm::dot(force, normal));
487 // TODO: friction somehow bigger than force?
488 glm::dvec3 ft(force - fn);
490 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
499 void Creature::TickStats(double dt) {
500 for (auto &s : stats.stat) {
503 // TODO: damage values depending on properties
504 if (stats.Breath().Full()) {
505 constexpr double dps = 1.0 / 4.0;
508 if (stats.Thirst().Full()) {
509 constexpr double dps = 1.0 / 32.0;
512 if (stats.Hunger().Full()) {
513 constexpr double dps = 1.0 / 128.0;
516 if (!situation.Moving()) {
517 // double exhaustion recovery when standing still
518 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
522 void Creature::TickBrain(double dt) {
526 // do background stuff
530 for (auto &goal : goals) {
533 Goal *top = &*goals.front();
534 // if active goal can be interrupted, check priorities
535 if (goals.size() > 1 && goals[0]->Interruptible()) {
536 std::sort(goals.begin(), goals.end(), GoalCompare);
538 if (&*goals.front() != top) {
539 top->SetBackground();
540 goals.front()->SetForeground();
541 top = &*goals.front();
544 for (auto goal = goals.begin(); goal != goals.end();) {
545 if ((*goal)->Complete()) {
551 if (&*goals.front() != top) {
552 goals.front()->SetForeground();
556 math::AABB Creature::CollisionBounds() const noexcept {
557 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
560 glm::dmat4 Creature::CollisionTransform() const noexcept {
561 const double half_size = size * 0.5;
562 const glm::dvec3 &pos = situation.Position();
564 orient[1] = situation.GetPlanet().NormalAt(pos);
565 orient[2] = situation.Heading();
566 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
567 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
569 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
570 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
571 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
573 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
576 glm::dmat4 Creature::LocalTransform() noexcept {
577 const double half_size = size * 0.5;
578 return CollisionTransform()
579 * glm::scale(glm::dvec3(half_size, half_size, half_size));
582 void Creature::BuildVAO() {
583 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
585 vao->BindAttributes();
586 vao->EnableAttribute(0);
587 vao->EnableAttribute(1);
588 vao->EnableAttribute(2);
589 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
590 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
591 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
592 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
594 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
595 const float offset = 1.0f;
596 for (int surface = 0; surface < 6; ++surface) {
597 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
598 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
600 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
601 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
602 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
603 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
604 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
605 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
606 attrib[4 * surface + 0].texture.x = tex_u_begin;
607 attrib[4 * surface + 0].texture.y = 1.0f;
608 attrib[4 * surface + 0].texture.z = surface;
610 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
611 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
612 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
613 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
614 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
615 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
616 attrib[4 * surface + 1].texture.x = tex_u_end;
617 attrib[4 * surface + 1].texture.y = 1.0f;
618 attrib[4 * surface + 1].texture.z = surface;
620 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
621 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
622 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
623 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
624 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
625 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
626 attrib[4 * surface + 2].texture.x = tex_u_begin;
627 attrib[4 * surface + 2].texture.y = 0.0f;
628 attrib[4 * surface + 2].texture.z = surface;
630 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
631 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
632 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
633 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
634 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
635 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
636 attrib[4 * surface + 3].texture.x = tex_u_end;
637 attrib[4 * surface + 3].texture.y = 0.0f;
638 attrib[4 * surface + 3].texture.z = surface;
642 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
644 auto element = vao->MapElements(GL_WRITE_ONLY);
645 for (int surface = 0; surface < 3; ++surface) {
646 element[6 * surface + 0] = 4 * surface + 0;
647 element[6 * surface + 1] = 4 * surface + 2;
648 element[6 * surface + 2] = 4 * surface + 1;
649 element[6 * surface + 3] = 4 * surface + 1;
650 element[6 * surface + 4] = 4 * surface + 2;
651 element[6 * surface + 5] = 4 * surface + 3;
653 for (int surface = 3; surface < 6; ++surface) {
654 element[6 * surface + 0] = 4 * surface + 0;
655 element[6 * surface + 1] = 4 * surface + 1;
656 element[6 * surface + 2] = 4 * surface + 2;
657 element[6 * surface + 3] = 4 * surface + 2;
658 element[6 * surface + 4] = 4 * surface + 1;
659 element[6 * surface + 5] = 4 * surface + 3;
665 void Creature::KillVAO() {
669 void Creature::Draw(graphics::Viewport &viewport) {
672 vao->DrawTriangles(6 * 6);
676 void Spawn(Creature &c, world::Planet &p) {
678 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
679 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
681 // probe surrounding area for common resources
682 int start = p.SideLength() / 2 - 2;
684 std::map<int, double> yields;
685 for (int y = start; y < end; ++y) {
686 for (int x = start; x < end; ++x) {
687 const world::TileType &t = p.TypeAt(0, x, y);
688 for (auto yield : t.resources) {
689 yields[yield.resource] += yield.ubiquity;
695 for (auto e : yields) {
696 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
697 if (liquid < 0 || e.second > yields[liquid]) {
700 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
701 if (solid < 0 || e.second > yields[solid]) {
708 genome.properties.Strength() = { 2.0, 0.1 };
709 genome.properties.Stamina() = { 2.0, 0.1 };
710 genome.properties.Dexerty() = { 2.0, 0.1 };
711 genome.properties.Intelligence() = { 1.0, 0.1 };
712 genome.properties.Lifetime() = { 480.0, 60.0 };
713 genome.properties.Fertility() = { 0.5, 0.03 };
714 genome.properties.Mutability() = { 0.9, 0.1 };
715 genome.properties.Adaptability() = { 0.9, 0.1 };
716 genome.properties.OffspringMass() = { 0.3, 0.02 };
718 glm::dvec3 color_avg(0.0);
719 double color_divisor = 0.0;
721 if (p.HasAtmosphere()) {
722 c.AddMass(p.Atmosphere(), 0.01);
723 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
724 color_divisor += 0.1;
727 c.AddMass(liquid, 0.3);
728 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
729 color_divisor += 0.5;
732 c.AddMass(solid, 0.1);
733 color_avg += c.GetSimulation().Resources()[solid].base_color;
734 color_divisor += 1.0;
737 if (color_divisor > 0.001) {
738 color_avg /= color_divisor;
740 glm::dvec3 hsl = rgb2hsl(color_avg);
741 genome.base_hue = { hsl.x, 0.01 };
742 genome.base_saturation = { hsl.y, 0.01 };
743 genome.base_lightness = { hsl.z, 0.01 };
744 // use opposite color as start highlight
745 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
746 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
747 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
752 void Genome::Configure(Creature &c) const {
753 c.GetGenome() = *this;
755 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
757 c.GetProperties() = Instantiate(properties, random);
759 // TODO: derive stats from properties
760 c.GetStats().Damage().gain = (-1.0 / 100.0);
761 c.GetStats().Breath().gain = (1.0 / 5.0);
762 c.GetStats().Thirst().gain = (1.0 / 60.0);
763 c.GetStats().Hunger().gain = (1.0 / 200.0);
764 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
765 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
766 c.GetStats().Boredom().gain = (1.0 / 300.0);
768 glm::dvec3 base_color(
769 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
770 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
771 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
773 glm::dvec3 highlight_color(
774 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
775 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
776 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
778 c.BaseColor(hsl2rgb(base_color));
779 c.HighlightColor(hsl2rgb(highlight_color));
780 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
781 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
785 void Split(Creature &c) {
786 Creature *a = new Creature(c.GetSimulation());
787 const Situation &s = c.GetSituation();
789 a->Name(c.GetSimulation().Assets().name.Sequential());
790 c.GetGenome().Configure(*a);
791 for (const auto &cmp : c.GetComposition()) {
792 a->AddMass(cmp.resource, cmp.value * 0.5);
794 s.GetPlanet().AddCreature(a);
795 // TODO: duplicate situation somehow
796 a->GetSituation().SetPlanetSurface(
798 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
800 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
802 Creature *b = new Creature(c.GetSimulation());
804 b->Name(c.GetSimulation().Assets().name.Sequential());
805 c.GetGenome().Configure(*b);
806 for (const auto &cmp : c.GetComposition()) {
807 b->AddMass(cmp.resource, cmp.value * 0.5);
809 s.GetPlanet().AddCreature(b);
810 b->GetSituation().SetPlanetSurface(
812 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
814 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
820 Memory::Memory(Creature &c)
827 void Memory::Erase() {
831 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
832 double best_rating = -1.0;
833 for (const auto &k : known_types) {
834 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
835 auto entry = t.FindBestResource(accept);
836 if (entry != t.resources.end()) {
837 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
838 if (rating > best_rating) {
839 best_rating = rating;
840 pos = k.second.first_loc.position;
842 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
843 if (rating > best_rating) {
844 best_rating = rating;
845 pos = k.second.last_loc.position;
849 if (best_rating > 0.0) {
851 c.GetSimulation().Assets().random.SNorm(),
852 c.GetSimulation().Assets().random.SNorm(),
853 c.GetSimulation().Assets().random.SNorm());
854 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
855 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
862 void Memory::Tick(double dt) {
863 Situation &s = c.GetSituation();
865 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
870 void Memory::TrackStay(const Location &l, double t) {
871 const world::TileType &type = l.planet->TileTypeAt(l.position);
872 auto entry = known_types.find(type.id);
873 if (entry != known_types.end()) {
874 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
876 if (entry->second.time_spent > c.Age() * 0.25) {
877 // the place is very familiar
878 c.GetStats().Boredom().Add(-0.2);
881 c.GetStats().Boredom().Add(-0.1);
884 entry->second.last_been = c.GetSimulation().Time();
885 entry->second.last_loc = l;
886 entry->second.time_spent += t;
888 known_types.emplace(type.id, Stay{
889 c.GetSimulation().Time(),
891 c.GetSimulation().Time(),
895 // completely new place, interesting
896 // TODO: scale by personality trait
897 c.GetStats().Boredom().Add(-0.25);
902 NameGenerator::NameGenerator()
906 NameGenerator::~NameGenerator() {
909 std::string NameGenerator::Sequential() {
910 std::stringstream ss;
911 ss << "Blob " << ++counter;
916 Situation::Situation()
918 , state(glm::dvec3(0.0), glm::dvec3(0.0))
922 Situation::~Situation() {
925 bool Situation::OnPlanet() const noexcept {
926 return type == PLANET_SURFACE;
929 bool Situation::OnSurface() const noexcept {
930 return type == PLANET_SURFACE;
933 bool Situation::OnGround() const noexcept {
934 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
937 glm::dvec3 Situation::SurfaceNormal() const noexcept {
938 return planet->NormalAt(state.pos);
941 world::Tile &Situation::GetTile() const noexcept {
942 return planet->TileAt(state.pos);
945 const world::TileType &Situation::GetTileType() const noexcept {
946 return planet->TileTypeAt(state.pos);
949 void Situation::Move(const glm::dvec3 &dp) noexcept {
951 EnforceConstraints(state);
954 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
956 EnforceConstraints(state);
959 void Situation::EnforceConstraints(State &s) const noexcept {
961 double r = GetPlanet().Radius();
962 if (glm::length2(s.pos) < r * r) {
963 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
965 s.vel -= normal * glm::dot(normal, s.vel);
970 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
971 type = PLANET_SURFACE;
974 EnforceConstraints(state);
978 Steering::Steering(const Creature &c)
992 Steering::~Steering() {
995 void Steering::Off() noexcept {
1002 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1004 min_dist = min_distance;
1005 max_look = max_lookaround;
1008 void Steering::DontSeparate() noexcept {
1012 void Steering::ResumeSeparate() noexcept {
1016 void Steering::Halt() noexcept {
1022 void Steering::Pass(const glm::dvec3 &t) noexcept {
1029 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1036 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1037 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1038 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1039 glm::dvec3 result(0.0);
1041 // TODO: off surface situation
1042 glm::dvec3 repulse(0.0);
1043 const Situation &s = c.GetSituation();
1044 for (auto &other : s.GetPlanet().Creatures()) {
1045 if (&*other == &c) continue;
1046 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1047 if (glm::length2(diff) > max_look * max_look) continue;
1048 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1049 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1050 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1056 result += -5.0 * s.vel * force;
1059 glm::dvec3 diff = target - s.pos;
1060 if (!allzero(diff)) {
1061 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1065 glm::dvec3 diff = target - s.pos;
1066 double dist = glm::length(diff);
1067 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1068 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1071 // remove vertical component, if any
1072 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1073 result -= normal * glm::dot(normal, result);
1075 if (glm::length2(result) > max_force * max_force) {
1076 result = glm::normalize(result) * max_force;
1081 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1082 return (vel - s.vel) * acc;