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() + 1.0));
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);
207 // doing work improves strength a little
208 properties.Strength() += amount * 0.0001;
211 void Creature::Hurt(double amount) noexcept {
212 stats.Damage().Add(amount);
213 if (stats.Damage().Full()) {
218 void Creature::Die() noexcept {
221 if (stats.Damage().Full()) {
222 std::ostream &log = sim.Log() << name << " ";
223 if (stats.Exhaustion().Full()) {
224 log << "died of exhaustion";
225 } else if (stats.Breath().Full()) {
227 } else if (stats.Thirst().Full()) {
228 log << "died of thirst";
229 } else if (stats.Hunger().Full()) {
230 log << "starved to death";
232 log << "succumed to wounds";
234 log << " at an age of " << ui::TimeString(Age())
235 << " (" << ui::PercentageString(Age() / properties.Lifetime())
236 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
249 bool Creature::Dead() const noexcept {
250 return death > birth;
253 void Creature::Remove() noexcept {
257 void Creature::Removed() noexcept {
264 void Creature::AddParent(Creature &p) {
265 parents.push_back(&p);
268 double Creature::Age() const noexcept {
269 return sim.Time() - birth;
272 double Creature::AgeFactor(double peak) const noexcept {
273 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
274 // goes negative below -0.5 and starts to rise again above 1.0
275 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
276 // guarantee at least 1%
277 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
280 double Creature::EnergyEfficiency() const noexcept {
281 return 0.25 * AgeFactor(0.05);
284 double Creature::ExhaustionFactor() const noexcept {
285 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
288 double Creature::FatigueFactor() const noexcept {
289 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
292 double Creature::Strength() const noexcept {
293 // TODO: replace all age factors with actual growth and decay
294 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
297 double Creature::StrengthFactor() const noexcept {
298 return Strength() / (Strength() + 1.0);
301 double Creature::Stamina() const noexcept {
302 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
305 double Creature::StaminaFactor() const noexcept {
306 return Stamina() / (Stamina() + 1.0);
309 double Creature::Dexerty() const noexcept {
310 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
313 double Creature::DexertyFactor() const noexcept {
314 return Dexerty() / (Dexerty() + 1.0);
317 double Creature::Intelligence() const noexcept {
318 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
321 double Creature::IntelligenceFactor() const noexcept {
322 return Intelligence() / (Intelligence() + 1.0);
325 double Creature::Lifetime() const noexcept {
326 return properties.Lifetime();
329 double Creature::Fertility() const noexcept {
330 return properties.Fertility() * AgeFactor(0.25);
333 double Creature::Mutability() const noexcept {
334 return properties.Mutability();
337 double Creature::Adaptability() const noexcept {
338 return properties.Adaptability();
341 double Creature::OffspringMass() const noexcept {
342 return properties.OffspringMass();
345 double Creature::PerceptionRange() const noexcept {
346 return 3.0 * DexertyFactor() + Size();
349 double Creature::PerceptionOmniRange() const noexcept {
350 return 0.5 * DexertyFactor() + Size();
353 double Creature::PerceptionField() const noexcept {
354 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
355 return 0.8 - DexertyFactor();
358 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
359 const glm::dvec3 diff(p - situation.Position());
360 double omni_range = PerceptionOmniRange();
361 if (glm::length2(diff) < omni_range * omni_range) return true;
362 double range = PerceptionRange();
363 if (glm::length2(diff) > range * range) return false;
364 return glm::dot(glm::normalize(diff), situation.Heading()) > PerceptionField();
367 double Creature::OffspringChance() const noexcept {
368 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
371 double Creature::MutateChance() const noexcept {
372 return GetProperties().Mutability() * (1.0 / 3600.0);
375 double Creature::AdaptChance() const noexcept {
376 return GetProperties().Adaptability() * (1.0 / 120.0);
379 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
384 goals.emplace_back(std::move(g));
389 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
390 return b->Urgency() < a->Urgency();
395 void Creature::Tick(double dt) {
401 void Creature::TickState(double dt) {
402 steering.MaxSpeed(Dexerty());
403 steering.MaxForce(Strength());
404 Situation::State state(situation.GetState());
405 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
406 Situation::Derivative b(Step(a, dt * 0.5));
407 Situation::Derivative c(Step(b, dt * 0.5));
408 Situation::Derivative d(Step(c, dt));
409 Situation::Derivative f(
410 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
411 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
413 state.pos += f.vel * dt;
414 state.vel += f.acc * dt;
415 situation.EnforceConstraints(state);
416 if (glm::length2(state.vel) > 0.000001) {
417 glm::dvec3 nvel(glm::normalize(state.vel));
418 double ang = glm::angle(nvel, state.dir);
419 double turn_rate = PI * 0.75 * dt;
420 if (ang < turn_rate) {
421 state.dir = glm::normalize(state.vel);
422 } else if (std::abs(ang - PI) < 0.001) {
423 state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
425 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
428 situation.SetState(state);
429 // work is force times distance
430 DoWork(glm::length(f.acc) * Mass() * glm::length(f.vel) * dt);
433 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
434 Situation::State s = situation.GetState();
435 s.pos += ds.vel * dt;
436 s.vel += ds.acc * dt;
437 glm::dvec3 force(steering.Force(s));
438 // gravity = antinormal * mass * Gm / r²
439 double elevation = situation.GetPlanet().DistanceAt(s.pos);
440 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
443 * Mass() * situation.GetPlanet().GravitationalParameter()
444 / (elevation * elevation));
445 // if net force is applied and in contact with surface
446 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
447 // apply friction = -|normal force| * tangential force * coefficient
448 glm::dvec3 fn(normal * glm::dot(force, normal));
449 glm::dvec3 ft(force - fn);
451 glm::dvec3 friction(-glm::length(fn) * ft * u);
460 void Creature::TickStats(double dt) {
461 for (auto &s : stats.stat) {
464 // TODO: damage values depending on properties
465 if (stats.Breath().Full()) {
466 constexpr double dps = 1.0 / 4.0;
469 if (stats.Thirst().Full()) {
470 constexpr double dps = 1.0 / 32.0;
473 if (stats.Hunger().Full()) {
474 constexpr double dps = 1.0 / 128.0;
477 if (!situation.Moving()) {
478 // double exhaustion recovery when standing still
479 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
483 void Creature::TickBrain(double dt) {
487 // do background stuff
491 for (auto &goal : goals) {
494 Goal *top = &*goals.front();
495 // if active goal can be interrupted, check priorities
496 if (goals.size() > 1 && goals[0]->Interruptible()) {
497 std::sort(goals.begin(), goals.end(), GoalCompare);
499 if (&*goals.front() != top) {
500 top->SetBackground();
501 goals.front()->SetForeground();
502 top = &*goals.front();
505 for (auto goal = goals.begin(); goal != goals.end();) {
506 if ((*goal)->Complete()) {
512 if (&*goals.front() != top) {
513 goals.front()->SetForeground();
517 math::AABB Creature::CollisionBox() const noexcept {
518 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
521 glm::dmat4 Creature::CollisionTransform() const noexcept {
522 const double half_size = size * 0.5;
523 const glm::dvec3 &pos = situation.Position();
525 orient[1] = situation.GetPlanet().NormalAt(pos);
526 orient[2] = situation.Heading();
527 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
528 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
530 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
531 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
532 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
534 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
537 glm::dmat4 Creature::LocalTransform() noexcept {
538 const double half_size = size * 0.5;
539 return CollisionTransform()
540 * glm::scale(glm::dvec3(half_size, half_size, half_size));
543 void Creature::BuildVAO() {
544 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
546 vao->BindAttributes();
547 vao->EnableAttribute(0);
548 vao->EnableAttribute(1);
549 vao->EnableAttribute(2);
550 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
551 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
552 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
553 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
555 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
556 const float offset = 1.0f;
557 for (int surface = 0; surface < 6; ++surface) {
558 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
559 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
561 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
562 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
563 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
564 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
565 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
566 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
567 attrib[4 * surface + 0].texture.x = tex_u_begin;
568 attrib[4 * surface + 0].texture.y = 1.0f;
569 attrib[4 * surface + 0].texture.z = surface;
571 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
572 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
573 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
574 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
575 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
576 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
577 attrib[4 * surface + 1].texture.x = tex_u_end;
578 attrib[4 * surface + 1].texture.y = 1.0f;
579 attrib[4 * surface + 1].texture.z = surface;
581 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
582 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
583 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
584 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
585 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
586 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
587 attrib[4 * surface + 2].texture.x = tex_u_begin;
588 attrib[4 * surface + 2].texture.y = 0.0f;
589 attrib[4 * surface + 2].texture.z = surface;
591 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
592 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
593 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
594 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
595 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
596 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
597 attrib[4 * surface + 3].texture.x = tex_u_end;
598 attrib[4 * surface + 3].texture.y = 0.0f;
599 attrib[4 * surface + 3].texture.z = surface;
603 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
605 auto element = vao->MapElements(GL_WRITE_ONLY);
606 for (int surface = 0; surface < 3; ++surface) {
607 element[6 * surface + 0] = 4 * surface + 0;
608 element[6 * surface + 1] = 4 * surface + 2;
609 element[6 * surface + 2] = 4 * surface + 1;
610 element[6 * surface + 3] = 4 * surface + 1;
611 element[6 * surface + 4] = 4 * surface + 2;
612 element[6 * surface + 5] = 4 * surface + 3;
614 for (int surface = 3; surface < 6; ++surface) {
615 element[6 * surface + 0] = 4 * surface + 0;
616 element[6 * surface + 1] = 4 * surface + 1;
617 element[6 * surface + 2] = 4 * surface + 2;
618 element[6 * surface + 3] = 4 * surface + 2;
619 element[6 * surface + 4] = 4 * surface + 1;
620 element[6 * surface + 5] = 4 * surface + 3;
626 void Creature::KillVAO() {
630 void Creature::Draw(graphics::Viewport &viewport) {
633 vao->DrawTriangles(6 * 6);
637 void Spawn(Creature &c, world::Planet &p) {
639 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
640 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
642 // probe surrounding area for common resources
643 int start = p.SideLength() / 2 - 2;
645 std::map<int, double> yields;
646 for (int y = start; y < end; ++y) {
647 for (int x = start; x < end; ++x) {
648 const world::TileType &t = p.TypeAt(0, x, y);
649 for (auto yield : t.resources) {
650 yields[yield.resource] += yield.ubiquity;
656 for (auto e : yields) {
657 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
658 if (liquid < 0 || e.second > yields[liquid]) {
661 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
662 if (solid < 0 || e.second > yields[solid]) {
669 genome.properties.Strength() = { 2.0, 0.1 };
670 genome.properties.Stamina() = { 2.0, 0.1 };
671 genome.properties.Dexerty() = { 2.0, 0.1 };
672 genome.properties.Intelligence() = { 1.0, 0.1 };
673 genome.properties.Lifetime() = { 480.0, 60.0 };
674 genome.properties.Fertility() = { 0.5, 0.03 };
675 genome.properties.Mutability() = { 0.9, 0.1 };
676 genome.properties.Adaptability() = { 0.9, 0.1 };
677 genome.properties.OffspringMass() = { 0.3, 0.02 };
679 glm::dvec3 color_avg(0.0);
680 double color_divisor = 0.0;
682 if (p.HasAtmosphere()) {
683 c.AddMass(p.Atmosphere(), 0.01);
684 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
685 color_divisor += 0.1;
688 c.AddMass(liquid, 0.3);
689 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
690 color_divisor += 0.5;
693 c.AddMass(solid, 0.1);
694 color_avg += c.GetSimulation().Resources()[solid].base_color;
695 color_divisor += 1.0;
698 if (color_divisor > 0.001) {
699 color_avg /= color_divisor;
701 glm::dvec3 hsl = rgb2hsl(color_avg);
702 genome.base_hue = { hsl.x, 0.01 };
703 genome.base_saturation = { hsl.y, 0.01 };
704 genome.base_lightness = { hsl.z, 0.01 };
705 // use opposite color as start highlight
706 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
707 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
708 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
713 void Genome::Configure(Creature &c) const {
714 c.GetGenome() = *this;
716 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
718 c.GetProperties() = Instantiate(properties, random);
720 // TODO: derive stats from properties
721 c.GetStats().Damage().gain = (-1.0 / 100.0);
722 c.GetStats().Breath().gain = (1.0 / 5.0);
723 c.GetStats().Thirst().gain = (1.0 / 60.0);
724 c.GetStats().Hunger().gain = (1.0 / 200.0);
725 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
726 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
727 c.GetStats().Boredom().gain = (1.0 / 300.0);
729 glm::dvec3 base_color(
730 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
731 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
732 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
734 glm::dvec3 highlight_color(
735 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
736 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
737 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
739 c.BaseColor(hsl2rgb(base_color));
740 c.HighlightColor(hsl2rgb(highlight_color));
741 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
742 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
746 void Split(Creature &c) {
747 Creature *a = new Creature(c.GetSimulation());
748 const Situation &s = c.GetSituation();
750 a->Name(c.GetSimulation().Assets().name.Sequential());
751 c.GetGenome().Configure(*a);
752 for (const auto &cmp : c.GetComposition()) {
753 a->AddMass(cmp.resource, cmp.value * 0.5);
755 s.GetPlanet().AddCreature(a);
756 // TODO: duplicate situation somehow
757 a->GetSituation().SetPlanetSurface(
759 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
761 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
763 Creature *b = new Creature(c.GetSimulation());
765 b->Name(c.GetSimulation().Assets().name.Sequential());
766 c.GetGenome().Configure(*b);
767 for (const auto &cmp : c.GetComposition()) {
768 b->AddMass(cmp.resource, cmp.value * 0.5);
770 s.GetPlanet().AddCreature(b);
771 b->GetSituation().SetPlanetSurface(
773 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
775 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
781 Memory::Memory(Creature &c)
788 void Memory::Erase() {
792 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
793 double best_rating = -1.0;
794 for (const auto &k : known_types) {
795 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
796 auto entry = t.FindBestResource(accept);
797 if (entry != t.resources.end()) {
798 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
799 if (rating > best_rating) {
800 best_rating = rating;
801 pos = k.second.first_loc.position;
803 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
804 if (rating > best_rating) {
805 best_rating = rating;
806 pos = k.second.last_loc.position;
810 if (best_rating > 0.0) {
812 c.GetSimulation().Assets().random.SNorm(),
813 c.GetSimulation().Assets().random.SNorm(),
814 c.GetSimulation().Assets().random.SNorm());
815 pos += error * (2.0 * (1.0 - c.IntelligenceFactor()));
816 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
823 void Memory::Tick(double dt) {
824 Situation &s = c.GetSituation();
826 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
831 void Memory::TrackStay(const Location &l, double t) {
832 const world::TileType &type = l.planet->TileTypeAt(l.position);
833 auto entry = known_types.find(type.id);
834 if (entry != known_types.end()) {
835 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
837 if (entry->second.time_spent > c.Age() * 0.25) {
838 // the place is very familiar
839 c.GetStats().Boredom().Add(-0.2);
842 c.GetStats().Boredom().Add(-0.1);
845 entry->second.last_been = c.GetSimulation().Time();
846 entry->second.last_loc = l;
847 entry->second.time_spent += t;
849 known_types.emplace(type.id, Stay{
850 c.GetSimulation().Time(),
852 c.GetSimulation().Time(),
856 // completely new place, interesting
857 // TODO: scale by personality trait
858 c.GetStats().Boredom().Add(-0.25);
863 NameGenerator::NameGenerator()
867 NameGenerator::~NameGenerator() {
870 std::string NameGenerator::Sequential() {
871 std::stringstream ss;
872 ss << "Blob " << ++counter;
877 Situation::Situation()
879 , state(glm::dvec3(0.0), glm::dvec3(0.0))
883 Situation::~Situation() {
886 bool Situation::OnPlanet() const noexcept {
887 return type == PLANET_SURFACE;
890 bool Situation::OnSurface() const noexcept {
891 return type == PLANET_SURFACE;
894 world::Tile &Situation::GetTile() const noexcept {
895 return planet->TileAt(state.pos);
898 const world::TileType &Situation::GetTileType() const noexcept {
899 return planet->TileTypeAt(state.pos);
902 void Situation::Move(const glm::dvec3 &dp) noexcept {
904 EnforceConstraints(state);
907 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
909 EnforceConstraints(state);
912 void Situation::EnforceConstraints(State &s) noexcept {
914 double r = GetPlanet().Radius();
915 if (glm::length2(s.pos) < r * r) {
916 s.pos = glm::normalize(s.pos) * r;
921 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
922 type = PLANET_SURFACE;
925 EnforceConstraints(state);
929 Steering::Steering(const Creature &c)
943 Steering::~Steering() {
946 void Steering::Off() noexcept {
953 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
955 min_dist = min_distance;
956 max_look = max_lookaround;
959 void Steering::DontSeparate() noexcept {
963 void Steering::ResumeSeparate() noexcept {
967 void Steering::Halt() noexcept {
973 void Steering::Pass(const glm::dvec3 &t) noexcept {
980 void Steering::GoTo(const glm::dvec3 &t) noexcept {
987 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
988 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
989 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
990 glm::dvec3 result(0.0);
992 // TODO: off surface situation
993 glm::dvec3 repulse(0.0);
994 const Situation &s = c.GetSituation();
995 for (auto &other : s.GetPlanet().Creatures()) {
996 if (&*other == &c) continue;
997 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
998 if (glm::length2(diff) > max_look * max_look) continue;
999 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1000 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1001 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1006 // break twice as hard
1007 result += -2.0 * s.vel * force;
1010 glm::dvec3 diff = target - s.pos;
1011 if (!allzero(diff)) {
1012 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1016 glm::dvec3 diff = target - s.pos;
1017 double dist = glm::length(diff);
1018 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1019 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1022 if (glm::length2(result) > max_force * max_force) {
1023 result = glm::normalize(result) * max_force;
1028 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1029 return (vel - s.vel) * acc;