1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "AttackGoal.hpp"
10 #include "BlobBackgroundTask.hpp"
12 #include "IdleGoal.hpp"
13 #include "../app/Assets.hpp"
14 #include "../math/const.hpp"
15 #include "../ui/string.hpp"
16 #include "../world/Body.hpp"
17 #include "../world/Planet.hpp"
18 #include "../world/Simulation.hpp"
19 #include "../world/TileType.hpp"
23 #include <glm/gtx/transform.hpp>
24 #include <glm/gtx/vector_angle.hpp>
27 #include <glm/gtx/io.hpp>
33 Composition::Composition(const world::Set<world::Resource> &resources)
34 : resources(resources)
41 Composition::~Composition() {
45 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
46 return b.value < a.value;
50 void Composition::Add(int res, double amount) {
52 for (auto c = components.begin(); c != components.end(); ++c) {
53 if (c->resource == res) {
55 if (c->value <= 0.0) {
63 if (!found && amount > 0.0) {
64 components.emplace_back(res, amount);
66 std::sort(components.begin(), components.end(), CompositionCompare);
67 state_mass[resources[res].state] += amount;
69 total_volume += amount / resources[res].density;
72 bool Composition::Has(int res) const noexcept {
73 for (auto &c : components) {
74 if (c.resource == res) {
81 double Composition::Get(int res) const noexcept {
82 for (auto &c : components) {
83 if (c.resource == res) {
90 double Composition::Proportion(int res) const noexcept {
91 return Get(res) / TotalMass();
94 double Composition::StateProportion(int res) const noexcept {
95 return Get(res) / StateMass(resources[res].state);
98 double Composition::Compatibility(int res) const noexcept {
100 return StateProportion(res);
102 double max_compat = -1.0;
103 double min_compat = 1.0;
104 for (const auto &c : components) {
105 double prop = c.value / StateMass(resources[res].state);
106 for (const auto &compat : resources[c.resource].compatibility) {
107 double value = compat.second * prop;
108 if (value > max_compat) {
111 if (value < min_compat) {
116 if (min_compat < 0.0) {
124 Creature::Creature(world::Simulation &sim)
129 , composition(sim.Resources())
131 , highlight_color(0.0, 0.0, 0.0, 1.0)
145 , perception_range(1.0)
146 , perception_range_squared(1.0)
147 , perception_omni_range(1.0)
148 , perception_omni_range_squared(1.0)
149 , perception_field(1.0)
152 // all creatures avoid each other for now
153 steering.Separate(0.1, 1.5);
156 Creature::~Creature() {
159 void Creature::AddMass(int res, double amount) {
160 composition.Add(res, amount);
161 double nonsolid = 0.0;
163 for (const auto &c : composition) {
164 volume += c.value / sim.Resources()[c.resource].density;
165 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
169 Mass(composition.TotalMass());
170 Size(std::cbrt(volume));
171 highlight_color.a = nonsolid / composition.TotalMass();
174 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
175 highlight_color = glm::dvec4(c, highlight_color.a);
178 void Creature::Ingest(int res, double amount) noexcept {
179 if (sim.Resources()[res].state == world::Resource::SOLID) {
180 // 30% of solids stays in body
181 AddMass(res, amount * 0.3 * composition.Compatibility(res));
183 // 5% of fluids stays in body
184 AddMass(res, amount * 0.05 * composition.Compatibility(res));
186 math::GaloisLFSR &random = sim.Assets().random;
187 if (random.UNorm() < AdaptChance()) {
188 // change color to be slightly more like resource
189 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
190 // solids affect base color, others highlight
191 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
192 double q = random.UInt(3); // hue, sat, or val
193 double r = random.UInt(2); // mean or deviation
194 math::Distribution *d = nullptr;
198 d = &genome.base_hue;
201 d = &genome.base_saturation;
204 d = &genome.base_lightness;
209 d = &genome.highlight_hue;
212 d = &genome.highlight_saturation;
215 d = &genome.highlight_lightness;
220 double diff = ref - d->Mean();
224 } else if (diff > 0.5) {
227 // move ±15% of distance
228 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
230 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
233 // scale by ±15%, enforce bounds
234 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
239 void Creature::DoWork(double amount) noexcept {
240 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
241 // burn resources proportional to composition
242 // factor = 1/total * 1/efficiency * amount * -1
243 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
244 // make a copy to total remains constant and
245 // no entries disappear during iteration
246 Composition comp(composition);
247 for (auto &cmp : comp) {
248 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
249 AddMass(cmp.resource, value);
251 // doing work improves strength a little
252 properties.Strength() += amount * 0.0001;
255 void Creature::Hurt(double amount) noexcept {
256 stats.Damage().Add(amount);
257 if (stats.Damage().Full()) {
262 void Creature::Die() noexcept {
265 if (stats.Damage().Full()) {
266 std::ostream &log = sim.Log() << name << " ";
267 if (stats.Exhaustion().Full()) {
268 log << "died of exhaustion";
269 } else if (stats.Breath().Full()) {
271 } else if (stats.Thirst().Full()) {
272 log << "died of thirst";
273 } else if (stats.Hunger().Full()) {
274 log << "starved to death";
276 log << "succumed to wounds";
278 log << " at an age of " << ui::TimeString(Age())
279 << " (" << ui::PercentageString(Age() / properties.Lifetime())
280 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
293 bool Creature::Dead() const noexcept {
294 return death > birth;
297 void Creature::Remove() noexcept {
301 void Creature::Removed() noexcept {
308 void Creature::AddParent(Creature &p) {
309 parents.push_back(&p);
312 double Creature::Age() const noexcept {
313 return Dead() ? death - birth : sim.Time() - birth;
316 double Creature::AgeFactor(double peak) const noexcept {
317 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
318 // goes negative below -0.5 and starts to rise again above 1.0
319 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
320 // guarantee at least 1%
321 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
324 double Creature::EnergyEfficiency() const noexcept {
325 return 0.25 * AgeFactor(0.05);
328 double Creature::ExhaustionFactor() const noexcept {
329 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
332 double Creature::FatigueFactor() const noexcept {
333 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
336 double Creature::Strength() const noexcept {
337 // TODO: replace all age factors with actual growth and decay
338 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
341 double Creature::StrengthFactor() const noexcept {
342 double str = Strength();
343 return str / (str + 1.0);
346 double Creature::Stamina() const noexcept {
347 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
350 double Creature::StaminaFactor() const noexcept {
351 double stm = Stamina();
352 return stm / (stm + 1.0);
355 double Creature::Dexerty() const noexcept {
356 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
359 double Creature::DexertyFactor() const noexcept {
360 double dex = Dexerty();
361 return dex / (dex + 1.0);
364 double Creature::Intelligence() const noexcept {
365 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
368 double Creature::IntelligenceFactor() const noexcept {
369 double intl = Intelligence();
370 return intl / (intl + 1.0);
373 double Creature::Lifetime() const noexcept {
374 return properties.Lifetime();
377 double Creature::Fertility() const noexcept {
378 return properties.Fertility() * AgeFactor(0.25);
381 double Creature::Mutability() const noexcept {
382 return properties.Mutability();
385 double Creature::Adaptability() const noexcept {
386 return properties.Adaptability();
389 double Creature::OffspringMass() const noexcept {
390 return properties.OffspringMass();
393 double Creature::PerceptionRange() const noexcept {
394 return perception_range;
397 double Creature::PerceptionOmniRange() const noexcept {
398 return perception_omni_range;
401 double Creature::PerceptionField() const noexcept {
402 return perception_field;
405 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
406 const glm::dvec3 diff(p - situation.Position());
407 double ldiff = glm::length2(diff);
408 if (ldiff < perception_omni_range_squared) return true;
409 if (ldiff > perception_range_squared) return false;
410 return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
413 double Creature::OffspringChance() const noexcept {
414 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
417 double Creature::MutateChance() const noexcept {
418 return GetProperties().Mutability() * (1.0 / 3600.0);
421 double Creature::AdaptChance() const noexcept {
422 return GetProperties().Adaptability() * (1.0 / 120.0);
425 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
430 goals.emplace_back(std::move(g));
435 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
436 return b->Urgency() < a->Urgency();
441 void Creature::Tick(double dt) {
448 void Creature::Cache() noexcept {
449 double dex_fact = DexertyFactor();
450 perception_range = 3.0 * dex_fact + size;
451 perception_range_squared = perception_range * perception_range;
452 perception_omni_range = 0.5 * dex_fact + size;
453 perception_omni_range_squared = perception_omni_range * perception_omni_range;
454 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
455 perception_field = 0.8 - dex_fact;
458 void Creature::TickState(double dt) {
459 steering.MaxSpeed(Dexerty());
460 steering.MaxForce(Strength());
461 Situation::State state(situation.GetState());
462 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
463 Situation::Derivative b(Step(a, dt * 0.5));
464 Situation::Derivative c(Step(b, dt * 0.5));
465 Situation::Derivative d(Step(c, dt));
466 Situation::Derivative f(
467 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
468 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
470 state.pos += f.vel * dt;
471 state.vel += f.acc * dt;
472 situation.EnforceConstraints(state);
473 if (glm::length2(state.vel) > 0.000001) {
474 glm::dvec3 nvel(glm::normalize(state.vel));
475 double ang = glm::angle(nvel, state.dir);
476 double turn_rate = PI * 0.75 * dt;
477 if (ang < turn_rate) {
478 state.dir = glm::normalize(state.vel);
479 } else if (std::abs(ang - PI) < 0.001) {
480 state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
482 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
485 situation.SetState(state);
486 // work is force times distance
487 // exclude gravity for no apparent reason
488 // actually, this should solely be based on steering force
489 DoWork(glm::length(f.acc - situation.GetPlanet().GravityAt(state.pos)) * Mass() * glm::length(f.vel) * dt);
492 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
493 Situation::State s = situation.GetState();
494 s.pos += ds.vel * dt;
495 s.vel += ds.acc * dt;
496 situation.EnforceConstraints(s);
497 glm::dvec3 force(steering.Force(s));
498 // gravity = antinormal * mass * Gm / r²
499 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
502 * (Mass() * situation.GetPlanet().GravitationalParameter()
503 / glm::length2(s.pos)));
504 // if net force is applied and in contact with surface
505 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
507 glm::dvec3 fn(normal * glm::dot(force, normal));
508 // TODO: friction somehow bigger than force?
509 glm::dvec3 ft(force - fn);
511 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
520 void Creature::TickStats(double dt) {
521 for (auto &s : stats.stat) {
524 // TODO: damage values depending on properties
525 if (stats.Breath().Full()) {
526 constexpr double dps = 1.0 / 4.0;
529 if (stats.Thirst().Full()) {
530 constexpr double dps = 1.0 / 32.0;
533 if (stats.Hunger().Full()) {
534 constexpr double dps = 1.0 / 128.0;
537 if (!situation.Moving()) {
538 // double exhaustion recovery when standing still
539 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
543 void Creature::TickBrain(double dt) {
547 // do background stuff
551 for (auto &goal : goals) {
554 Goal *top = &*goals.front();
555 // if active goal can be interrupted, check priorities
556 if (goals.size() > 1 && goals[0]->Interruptible()) {
557 std::sort(goals.begin(), goals.end(), GoalCompare);
559 if (&*goals.front() != top) {
560 top->SetBackground();
561 goals.front()->SetForeground();
562 top = &*goals.front();
565 for (auto goal = goals.begin(); goal != goals.end();) {
566 if ((*goal)->Complete()) {
572 if (&*goals.front() != top) {
573 goals.front()->SetForeground();
577 math::AABB Creature::CollisionBounds() const noexcept {
578 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
581 glm::dmat4 Creature::CollisionTransform() const noexcept {
582 const double half_size = size * 0.5;
583 const glm::dvec3 &pos = situation.Position();
585 orient[1] = situation.GetPlanet().NormalAt(pos);
586 orient[2] = situation.Heading();
587 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
588 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
590 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
591 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
592 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
594 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
597 void Creature::OnCollide(Creature &other) {
598 memory.TrackCollision(other);
601 glm::dmat4 Creature::LocalTransform() noexcept {
602 const double half_size = size * 0.5;
603 return CollisionTransform()
604 * glm::scale(glm::dvec3(half_size, half_size, half_size));
607 void Creature::BuildVAO() {
608 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
610 vao->BindAttributes();
611 vao->EnableAttribute(0);
612 vao->EnableAttribute(1);
613 vao->EnableAttribute(2);
614 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
615 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
616 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
617 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
619 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
620 const float offset = 1.0f;
621 for (int surface = 0; surface < 6; ++surface) {
622 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
623 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
625 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
626 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
627 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
628 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
629 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
630 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
631 attrib[4 * surface + 0].texture.x = tex_u_begin;
632 attrib[4 * surface + 0].texture.y = 1.0f;
633 attrib[4 * surface + 0].texture.z = surface;
635 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
636 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
637 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
638 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
639 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
640 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
641 attrib[4 * surface + 1].texture.x = tex_u_end;
642 attrib[4 * surface + 1].texture.y = 1.0f;
643 attrib[4 * surface + 1].texture.z = surface;
645 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
646 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
647 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
648 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
649 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
650 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
651 attrib[4 * surface + 2].texture.x = tex_u_begin;
652 attrib[4 * surface + 2].texture.y = 0.0f;
653 attrib[4 * surface + 2].texture.z = surface;
655 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
656 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
657 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
658 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
659 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
660 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
661 attrib[4 * surface + 3].texture.x = tex_u_end;
662 attrib[4 * surface + 3].texture.y = 0.0f;
663 attrib[4 * surface + 3].texture.z = surface;
667 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
669 auto element = vao->MapElements(GL_WRITE_ONLY);
670 for (int surface = 0; surface < 3; ++surface) {
671 element[6 * surface + 0] = 4 * surface + 0;
672 element[6 * surface + 1] = 4 * surface + 2;
673 element[6 * surface + 2] = 4 * surface + 1;
674 element[6 * surface + 3] = 4 * surface + 1;
675 element[6 * surface + 4] = 4 * surface + 2;
676 element[6 * surface + 5] = 4 * surface + 3;
678 for (int surface = 3; surface < 6; ++surface) {
679 element[6 * surface + 0] = 4 * surface + 0;
680 element[6 * surface + 1] = 4 * surface + 1;
681 element[6 * surface + 2] = 4 * surface + 2;
682 element[6 * surface + 3] = 4 * surface + 2;
683 element[6 * surface + 4] = 4 * surface + 1;
684 element[6 * surface + 5] = 4 * surface + 3;
690 void Creature::KillVAO() {
694 void Creature::Draw(graphics::Viewport &viewport) {
697 vao->DrawTriangles(6 * 6);
701 void Spawn(Creature &c, world::Planet &p) {
703 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
704 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
706 // probe surrounding area for common resources
707 int start = p.SideLength() / 2 - 2;
709 std::map<int, double> yields;
710 for (int y = start; y < end; ++y) {
711 for (int x = start; x < end; ++x) {
712 const world::TileType &t = p.TypeAt(0, x, y);
713 for (auto yield : t.resources) {
714 yields[yield.resource] += yield.ubiquity;
720 for (auto e : yields) {
721 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
722 if (liquid < 0 || e.second > yields[liquid]) {
725 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
726 if (solid < 0 || e.second > yields[solid]) {
733 genome.properties.Strength() = { 2.0, 0.1 };
734 genome.properties.Stamina() = { 2.0, 0.1 };
735 genome.properties.Dexerty() = { 2.0, 0.1 };
736 genome.properties.Intelligence() = { 1.0, 0.1 };
737 genome.properties.Lifetime() = { 480.0, 60.0 };
738 genome.properties.Fertility() = { 0.5, 0.03 };
739 genome.properties.Mutability() = { 0.9, 0.1 };
740 genome.properties.Adaptability() = { 0.9, 0.1 };
741 genome.properties.OffspringMass() = { 0.3, 0.02 };
743 glm::dvec3 color_avg(0.0);
744 double color_divisor = 0.0;
746 if (p.HasAtmosphere()) {
747 c.AddMass(p.Atmosphere(), 0.01);
748 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
749 color_divisor += 0.1;
752 c.AddMass(liquid, 0.3);
753 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
754 color_divisor += 0.5;
757 c.AddMass(solid, 0.1);
758 color_avg += c.GetSimulation().Resources()[solid].base_color;
759 color_divisor += 1.0;
762 if (color_divisor > 0.001) {
763 color_avg /= color_divisor;
765 glm::dvec3 hsl = rgb2hsl(color_avg);
766 genome.base_hue = { hsl.x, 0.01 };
767 genome.base_saturation = { hsl.y, 0.01 };
768 genome.base_lightness = { hsl.z, 0.01 };
769 // use opposite color as start highlight
770 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
771 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
772 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
777 void Genome::Configure(Creature &c) const {
778 c.GetGenome() = *this;
780 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
782 c.GetProperties() = Instantiate(properties, random);
784 // TODO: derive stats from properties
785 c.GetStats().Damage().gain = (-1.0 / 100.0);
786 c.GetStats().Breath().gain = (1.0 / 5.0);
787 c.GetStats().Thirst().gain = (1.0 / 60.0);
788 c.GetStats().Hunger().gain = (1.0 / 200.0);
789 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
790 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
791 c.GetStats().Boredom().gain = (1.0 / 300.0);
793 glm::dvec3 base_color(
794 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
795 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
796 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
798 glm::dvec3 highlight_color(
799 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
800 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
801 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
803 c.BaseColor(hsl2rgb(base_color));
804 c.HighlightColor(hsl2rgb(highlight_color));
805 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
806 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
810 void Split(Creature &c) {
811 Creature *a = new Creature(c.GetSimulation());
812 const Situation &s = c.GetSituation();
814 a->Name(c.GetSimulation().Assets().name.Sequential());
815 c.GetGenome().Configure(*a);
816 for (const auto &cmp : c.GetComposition()) {
817 a->AddMass(cmp.resource, cmp.value * 0.5);
819 s.GetPlanet().AddCreature(a);
820 // TODO: duplicate situation somehow
821 a->GetSituation().SetPlanetSurface(
823 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
825 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
827 Creature *b = new Creature(c.GetSimulation());
829 b->Name(c.GetSimulation().Assets().name.Sequential());
830 c.GetGenome().Configure(*b);
831 for (const auto &cmp : c.GetComposition()) {
832 b->AddMass(cmp.resource, cmp.value * 0.5);
834 s.GetPlanet().AddCreature(b);
835 b->GetSituation().SetPlanetSurface(
837 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
839 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
845 Memory::Memory(Creature &c)
852 void Memory::Erase() {
854 known_creatures.clear();
857 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
858 double best_rating = -1.0;
859 for (const auto &k : known_types) {
860 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
861 auto entry = t.FindBestResource(accept);
862 if (entry != t.resources.end()) {
863 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
864 if (rating > best_rating) {
865 best_rating = rating;
866 pos = k.second.first_loc.position;
868 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
869 if (rating > best_rating) {
870 best_rating = rating;
871 pos = k.second.last_loc.position;
875 if (best_rating > 0.0) {
877 c.GetSimulation().Assets().random.SNorm(),
878 c.GetSimulation().Assets().random.SNorm(),
879 c.GetSimulation().Assets().random.SNorm());
880 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
881 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
888 void Memory::TrackCollision(Creature &other) {
889 // TODO: find out whose fault it was
890 // TODO: source values from personality
891 Profile &p = known_creatures[&other];
893 const double annoy_fact = p.annoyance / (p.annoyance + 1.0);
894 if (c.GetSimulation().Assets().random.UNorm() > annoy_fact * 0.1 * (1.0 - c.GetStats().Damage().value)) {
895 AttackGoal *g = new AttackGoal(c, other);
896 g->SetDamageTarget(annoy_fact);
897 g->Urgency(annoy_fact);
898 c.AddGoal(std::unique_ptr<Goal>(g));
903 void Memory::Tick(double dt) {
904 Situation &s = c.GetSituation();
906 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
911 void Memory::TrackStay(const Location &l, double t) {
912 const world::TileType &type = l.planet->TileTypeAt(l.position);
913 auto entry = known_types.find(type.id);
914 if (entry != known_types.end()) {
915 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
917 if (entry->second.time_spent > c.Age() * 0.25) {
918 // the place is very familiar
919 c.GetStats().Boredom().Add(-0.2);
922 c.GetStats().Boredom().Add(-0.1);
925 entry->second.last_been = c.GetSimulation().Time();
926 entry->second.last_loc = l;
927 entry->second.time_spent += t;
929 known_types.emplace(type.id, Stay{
930 c.GetSimulation().Time(),
932 c.GetSimulation().Time(),
936 // completely new place, interesting
937 // TODO: scale by personality trait
938 c.GetStats().Boredom().Add(-0.25);
943 NameGenerator::NameGenerator()
947 NameGenerator::~NameGenerator() {
950 std::string NameGenerator::Sequential() {
951 std::stringstream ss;
952 ss << "Blob " << ++counter;
957 Situation::Situation()
959 , state(glm::dvec3(0.0), glm::dvec3(0.0))
963 Situation::~Situation() {
966 bool Situation::OnPlanet() const noexcept {
967 return type == PLANET_SURFACE;
970 bool Situation::OnSurface() const noexcept {
971 return type == PLANET_SURFACE;
974 bool Situation::OnGround() const noexcept {
975 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
978 glm::dvec3 Situation::SurfaceNormal() const noexcept {
979 return planet->NormalAt(state.pos);
982 world::Tile &Situation::GetTile() const noexcept {
983 return planet->TileAt(state.pos);
986 const world::TileType &Situation::GetTileType() const noexcept {
987 return planet->TileTypeAt(state.pos);
990 void Situation::Move(const glm::dvec3 &dp) noexcept {
992 EnforceConstraints(state);
995 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
997 EnforceConstraints(state);
1000 void Situation::EnforceConstraints(State &s) const noexcept {
1002 double r = GetPlanet().Radius();
1003 if (glm::length2(s.pos) < r * r) {
1004 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
1006 s.vel -= normal * glm::dot(normal, s.vel);
1011 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
1012 type = PLANET_SURFACE;
1015 EnforceConstraints(state);
1019 Steering::Steering(const Creature &c)
1033 Steering::~Steering() {
1036 void Steering::Off() noexcept {
1043 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1045 min_dist = min_distance;
1046 max_look = max_lookaround;
1049 void Steering::DontSeparate() noexcept {
1053 void Steering::ResumeSeparate() noexcept {
1057 void Steering::Halt() noexcept {
1063 void Steering::Pass(const glm::dvec3 &t) noexcept {
1070 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1077 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1078 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1079 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1080 glm::dvec3 result(0.0);
1082 // TODO: off surface situation
1083 glm::dvec3 repulse(0.0);
1084 const Situation &s = c.GetSituation();
1085 for (auto &other : s.GetPlanet().Creatures()) {
1086 if (&*other == &c) continue;
1087 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1088 if (glm::length2(diff) > max_look * max_look) continue;
1089 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1090 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1091 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1097 result += -5.0 * s.vel * force;
1100 glm::dvec3 diff = target - s.pos;
1101 if (!allzero(diff)) {
1102 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1106 glm::dvec3 diff = target - s.pos;
1107 double dist = glm::length(diff);
1108 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1109 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1112 // remove vertical component, if any
1113 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1114 result -= normal * glm::dot(normal, result);
1116 if (glm::length2(result) > max_force * max_force) {
1117 result = glm::normalize(result) * max_force;
1122 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1123 return (vel - s.vel) * acc;