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 , heading_target(0.0, 0.0, -1.0)
146 , heading_manual(false)
147 , perception_range(1.0)
148 , perception_range_squared(1.0)
149 , perception_omni_range(1.0)
150 , perception_omni_range_squared(1.0)
151 , perception_field(1.0)
154 // all creatures avoid each other for now
155 steering.Separate(0.1, 1.5);
158 Creature::~Creature() {
161 void Creature::AddMass(int res, double amount) {
162 composition.Add(res, amount);
163 double nonsolid = 0.0;
165 for (const auto &c : composition) {
166 volume += c.value / sim.Resources()[c.resource].density;
167 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
171 Mass(composition.TotalMass());
172 Size(std::cbrt(volume));
173 highlight_color.a = nonsolid / composition.TotalMass();
176 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
177 highlight_color = glm::dvec4(c, highlight_color.a);
180 void Creature::Ingest(int res, double amount) noexcept {
181 if (sim.Resources()[res].state == world::Resource::SOLID) {
182 // 30% of solids stays in body
183 AddMass(res, amount * 0.3 * composition.Compatibility(res));
185 // 5% of fluids stays in body
186 AddMass(res, amount * 0.05 * composition.Compatibility(res));
188 math::GaloisLFSR &random = sim.Assets().random;
189 if (random.UNorm() < AdaptChance()) {
190 // change color to be slightly more like resource
191 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
192 // solids affect base color, others highlight
193 int p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
194 int q = random.UInt(3); // hue, sat, or val
195 int r = random.UInt(2); // mean or deviation
196 math::Distribution *d = nullptr;
200 d = &genome.base_hue;
203 d = &genome.base_saturation;
206 d = &genome.base_lightness;
211 d = &genome.highlight_hue;
214 d = &genome.highlight_saturation;
217 d = &genome.highlight_lightness;
222 double diff = ref - d->Mean();
226 } else if (diff > 0.5) {
229 // move 0-15% of distance
230 d->Mean(std::fmod(d->Mean() + diff * random.UNorm() * 0.15, 1.0));
232 d->Mean(glm::clamp(d->Mean() + diff * random.UNorm() * 0.15, 0.0, 1.0));
235 // scale by ±15%, enforce bounds
236 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
239 if (sim.Resources()[res].state == world::Resource::LIQUID && random.UNorm() < AdaptChance()) {
240 // change texture randomly
241 // TODO: make change depending on surroundings and/or resource
242 int p = random.UInt(2); // back or side
243 int q = random.UInt(2); // mean or deviation
244 math::Distribution &d = p ? genome.skin_side : genome.skin_back;
246 // move ± one standard deviation
247 d.Mean(d.Mean() + (random.SNorm() * d.StandardDeviation()));
249 // scale by ±10%, enforce bounds
250 d.StandardDeviation(glm::clamp(d.StandardDeviation() * (1.0 + random.SNorm() * 0.1), 0.0001, 0.5));
255 void Creature::DoWork(double amount) noexcept {
256 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
257 // burn resources proportional to composition
258 // factor = 1/total * 1/efficiency * amount * -1
259 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
260 // make a copy to total remains constant and
261 // no entries disappear during iteration
262 Composition comp(composition);
263 for (auto &cmp : comp) {
264 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
265 AddMass(cmp.resource, value);
267 // doing work improves strength a little
268 properties.Strength() += amount * 0.0001;
271 void Creature::Hurt(double amount) noexcept {
272 stats.Damage().Add(amount);
273 if (stats.Damage().Full()) {
278 void Creature::Die() noexcept {
281 if (stats.Damage().Full()) {
282 std::ostream &log = sim.Log() << name << " ";
283 if (stats.Exhaustion().Full()) {
284 log << "died of exhaustion";
285 } else if (stats.Breath().Full()) {
287 } else if (stats.Thirst().Full()) {
288 log << "died of thirst";
289 } else if (stats.Hunger().Full()) {
290 log << "starved to death";
292 log << "succumed to wounds";
294 log << " at an age of " << ui::TimeString(Age())
295 << " (" << ui::PercentageString(Age() / properties.Lifetime())
296 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
309 bool Creature::Dead() const noexcept {
310 return death > birth;
313 void Creature::Remove() noexcept {
317 void Creature::Removed() noexcept {
324 void Creature::AddParent(Creature &p) {
325 parents.push_back(&p);
328 double Creature::Age() const noexcept {
329 return Dead() ? death - birth : sim.Time() - birth;
332 double Creature::AgeFactor(double peak) const noexcept {
333 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
334 // goes negative below -0.5 and starts to rise again above 1.0
335 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
336 // guarantee at least 1%
337 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
340 double Creature::EnergyEfficiency() const noexcept {
341 return 0.25 * AgeFactor(0.05);
344 double Creature::ExhaustionFactor() const noexcept {
345 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
348 double Creature::FatigueFactor() const noexcept {
349 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
352 double Creature::Strength() const noexcept {
353 // TODO: replace all age factors with actual growth and decay
354 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
357 double Creature::StrengthFactor() const noexcept {
358 double str = Strength();
359 return str / (str + 1.0);
362 double Creature::Stamina() const noexcept {
363 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
366 double Creature::StaminaFactor() const noexcept {
367 double stm = Stamina();
368 return stm / (stm + 1.0);
371 double Creature::Dexerty() const noexcept {
372 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
375 double Creature::DexertyFactor() const noexcept {
376 double dex = Dexerty();
377 return dex / (dex + 1.0);
380 double Creature::Intelligence() const noexcept {
381 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
384 double Creature::IntelligenceFactor() const noexcept {
385 double intl = Intelligence();
386 return intl / (intl + 1.0);
389 double Creature::Lifetime() const noexcept {
390 return properties.Lifetime();
393 double Creature::Fertility() const noexcept {
394 return properties.Fertility() * AgeFactor(0.25);
397 double Creature::Mutability() const noexcept {
398 return properties.Mutability();
401 double Creature::Adaptability() const noexcept {
402 return properties.Adaptability();
405 double Creature::OffspringMass() const noexcept {
406 return properties.OffspringMass();
409 double Creature::PerceptionRange() const noexcept {
410 return perception_range;
413 double Creature::PerceptionOmniRange() const noexcept {
414 return perception_omni_range;
417 double Creature::PerceptionField() const noexcept {
418 return perception_field;
421 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
422 const glm::dvec3 diff(p - situation.Position());
423 double ldiff = glm::length2(diff);
424 if (ldiff < perception_omni_range_squared) return true;
425 if (ldiff > perception_range_squared) return false;
426 return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
429 double Creature::OffspringChance() const noexcept {
430 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
433 double Creature::MutateChance() const noexcept {
434 return GetProperties().Mutability() * (1.0 / 3600.0);
437 double Creature::AdaptChance() const noexcept {
438 return GetProperties().Adaptability() * (1.0 / 120.0);
441 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
446 goals.emplace_back(std::move(g));
449 void Creature::SetBackgroundTask(std::unique_ptr<Goal> &&g) {
450 bg_task = std::move(g);
453 Goal &Creature::BackgroundTask() {
459 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
460 return b->Urgency() < a->Urgency();
465 void Creature::Tick(double dt) {
472 void Creature::Cache() noexcept {
473 double dex_fact = DexertyFactor();
474 perception_range = 3.0 * dex_fact + size;
475 perception_range_squared = perception_range * perception_range;
476 perception_omni_range = 0.5 * dex_fact + size;
477 perception_omni_range_squared = perception_omni_range * perception_omni_range;
478 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
479 perception_field = 0.8 - dex_fact;
482 void Creature::TickState(double dt) {
483 steering.MaxSpeed(Dexerty());
484 steering.MaxForce(Strength());
485 Situation::State state(situation.GetState());
486 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
487 Situation::Derivative b(Step(a, dt * 0.5));
488 Situation::Derivative c(Step(b, dt * 0.5));
489 Situation::Derivative d(Step(c, dt));
490 Situation::Derivative f(
491 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
492 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
494 state.pos += f.vel * dt;
495 state.vel += f.acc * dt;
496 situation.EnforceConstraints(state);
498 if (!heading_manual && glm::length2(state.vel) > 0.000001) {
499 const glm::dvec3 normal(situation.GetPlanet().NormalAt(state.pos));
500 const glm::dvec3 tangent(state.vel - (normal * glm::dot(state.vel, normal)));
501 if (glm::length2(tangent) > 0.000001) {
502 heading_target = glm::normalize(tangent);
505 double ang = glm::angle(heading_target, state.dir);
506 double turn_rate = PI * 0.75 * dt;
507 if (ang < turn_rate) {
508 state.dir = heading_target;
509 heading_manual = false;
511 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, heading_target)));
514 situation.SetState(state);
515 // work is force times distance
516 // keep 10% of gravity as a kind of background burn
517 DoWork(glm::length(f.acc - (0.9 * situation.GetPlanet().GravityAt(state.pos))) * Mass() * glm::length(f.vel) * dt);
520 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
521 Situation::State s = situation.GetState();
522 s.pos += ds.vel * dt;
523 s.vel += ds.acc * dt;
524 situation.EnforceConstraints(s);
525 glm::dvec3 force(steering.Force(s));
526 // gravity = antinormal * mass * Gm / r²
527 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
530 * (Mass() * situation.GetPlanet().GravitationalParameter()
531 / glm::length2(s.pos)));
532 // if net force is applied and in contact with surface
533 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
535 glm::dvec3 fn(normal * glm::dot(force, normal));
536 // TODO: friction somehow bigger than force?
537 glm::dvec3 ft(force - fn);
539 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
548 void Creature::TickStats(double dt) {
549 for (auto &s : stats.stat) {
552 // TODO: damage values depending on properties
553 if (stats.Breath().Full()) {
554 constexpr double dps = 1.0 / 4.0;
557 if (stats.Thirst().Full()) {
558 constexpr double dps = 1.0 / 32.0;
561 if (stats.Hunger().Full()) {
562 constexpr double dps = 1.0 / 128.0;
565 if (!situation.Moving()) {
566 // double exhaustion recovery when standing still
567 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
571 void Creature::TickBrain(double dt) {
575 // do background stuff
579 for (auto &goal : goals) {
582 Goal *top = &*goals.front();
583 // if active goal can be interrupted, check priorities
584 if (goals.size() > 1 && goals[0]->Interruptible()) {
585 std::sort(goals.begin(), goals.end(), GoalCompare);
587 if (&*goals.front() != top) {
588 top->SetBackground();
589 goals.front()->SetForeground();
590 top = &*goals.front();
593 for (auto goal = goals.begin(); goal != goals.end();) {
594 if ((*goal)->Complete()) {
600 if (&*goals.front() != top) {
601 goals.front()->SetForeground();
605 math::AABB Creature::CollisionBounds() const noexcept {
606 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
609 glm::dmat4 Creature::CollisionTransform() const noexcept {
610 const double half_size = size * 0.5;
611 const glm::dvec3 &pos = situation.Position();
613 orient[1] = situation.GetPlanet().NormalAt(pos);
614 orient[2] = situation.Heading();
615 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
616 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
618 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
619 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
620 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
622 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
625 void Creature::OnCollide(Creature &other) {
626 memory.TrackCollision(other);
629 glm::dmat4 Creature::LocalTransform() noexcept {
630 const double half_size = size * 0.5;
631 return CollisionTransform()
632 * glm::scale(glm::dvec3(half_size, half_size, half_size));
635 void Creature::BuildVAO() {
636 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
638 vao->BindAttributes();
639 vao->EnableAttribute(0);
640 vao->EnableAttribute(1);
641 vao->EnableAttribute(2);
642 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
643 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
644 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
645 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
647 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
648 constexpr float offset = 1.0f;
649 constexpr float max_tex = 5.999f;
650 const float tex[6] = {
652 float(std::floor(skin_side * max_tex)), // left
653 float(std::floor(skin_back * max_tex)), // top
654 float(std::floor(skin_back * max_tex)), // back
655 float(std::floor(skin_side * max_tex)), // right
658 for (int surface = 0; surface < 6; ++surface) {
659 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
660 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
662 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
663 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
664 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
665 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
666 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
667 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
668 attrib[4 * surface + 0].texture.x = tex_u_begin;
669 attrib[4 * surface + 0].texture.y = 1.0f;
670 attrib[4 * surface + 0].texture.z = tex[surface];
672 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
673 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
674 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
675 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
676 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
677 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
678 attrib[4 * surface + 1].texture.x = tex_u_end;
679 attrib[4 * surface + 1].texture.y = 1.0f;
680 attrib[4 * surface + 1].texture.z = tex[surface];
682 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
683 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
684 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
685 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
686 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
687 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
688 attrib[4 * surface + 2].texture.x = tex_u_begin;
689 attrib[4 * surface + 2].texture.y = 0.0f;
690 attrib[4 * surface + 2].texture.z = tex[surface];
692 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
693 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
694 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
695 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
696 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
697 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
698 attrib[4 * surface + 3].texture.x = tex_u_end;
699 attrib[4 * surface + 3].texture.y = 0.0f;
700 attrib[4 * surface + 3].texture.z = tex[surface];
704 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
706 auto element = vao->MapElements(GL_WRITE_ONLY);
707 for (int surface = 0; surface < 3; ++surface) {
708 element[6 * surface + 0] = 4 * surface + 0;
709 element[6 * surface + 1] = 4 * surface + 2;
710 element[6 * surface + 2] = 4 * surface + 1;
711 element[6 * surface + 3] = 4 * surface + 1;
712 element[6 * surface + 4] = 4 * surface + 2;
713 element[6 * surface + 5] = 4 * surface + 3;
715 for (int surface = 3; surface < 6; ++surface) {
716 element[6 * surface + 0] = 4 * surface + 0;
717 element[6 * surface + 1] = 4 * surface + 1;
718 element[6 * surface + 2] = 4 * surface + 2;
719 element[6 * surface + 3] = 4 * surface + 2;
720 element[6 * surface + 4] = 4 * surface + 1;
721 element[6 * surface + 5] = 4 * surface + 3;
727 void Creature::KillVAO() {
731 void Creature::Draw(graphics::Viewport &viewport) {
734 vao->DrawTriangles(6 * 6);
738 void Spawn(Creature &c, world::Planet &p) {
740 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
741 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
742 c.HeadingTarget(glm::dvec3(1.0, 0.0, 0.0));
744 // probe surrounding area for common resources
745 int start = p.SideLength() / 2 - 2;
747 std::map<int, double> yields;
748 for (int y = start; y < end; ++y) {
749 for (int x = start; x < end; ++x) {
750 const world::TileType &t = p.TypeAt(0, x, y);
751 for (auto yield : t.resources) {
752 yields[yield.resource] += yield.ubiquity;
758 for (auto e : yields) {
759 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
760 if (liquid < 0 || e.second > yields[liquid]) {
763 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
764 if (solid < 0 || e.second > yields[solid]) {
771 genome.properties.Strength() = { 2.0, 0.1 };
772 genome.properties.Stamina() = { 2.0, 0.1 };
773 genome.properties.Dexerty() = { 2.0, 0.1 };
774 genome.properties.Intelligence() = { 1.0, 0.1 };
775 genome.properties.Lifetime() = { 480.0, 60.0 };
776 genome.properties.Fertility() = { 0.5, 0.03 };
777 genome.properties.Mutability() = { 0.9, 0.1 };
778 genome.properties.Adaptability() = { 0.9, 0.1 };
779 genome.properties.OffspringMass() = { 0.3, 0.02 };
781 glm::dvec3 color_avg(0.0);
782 double color_divisor = 0.0;
784 if (p.HasAtmosphere()) {
785 c.AddMass(p.Atmosphere(), 0.01);
786 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
787 color_divisor += 0.1;
790 c.AddMass(liquid, 0.3);
791 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
792 color_divisor += 0.5;
795 c.AddMass(solid, 0.1);
796 color_avg += c.GetSimulation().Resources()[solid].base_color;
797 color_divisor += 1.0;
800 if (color_divisor > 0.001) {
801 color_avg /= color_divisor;
803 glm::dvec3 hsl = rgb2hsl(color_avg);
804 genome.base_hue = { hsl.x, 0.01 };
805 genome.base_saturation = { hsl.y, 0.01 };
806 genome.base_lightness = { hsl.z, 0.01 };
807 // use opposite color as start highlight
808 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
809 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
810 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
812 genome.skin_side = { 0.5, 0.01 };
813 genome.skin_back = { 0.5, 0.01 };
818 void Genome::Configure(Creature &c) const {
819 c.GetGenome() = *this;
821 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
823 c.GetProperties() = Instantiate(properties, random);
825 // TODO: derive stats from properties
826 c.GetStats().Damage().gain = (-1.0 / 100.0);
827 c.GetStats().Breath().gain = (1.0 / 5.0);
828 c.GetStats().Thirst().gain = (1.0 / 60.0);
829 c.GetStats().Hunger().gain = (1.0 / 200.0);
830 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
831 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
832 c.GetStats().Boredom().gain = (1.0 / 300.0);
834 glm::dvec3 base_color(
835 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
836 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
837 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
839 glm::dvec3 highlight_color(
840 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
841 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
842 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
844 c.BaseColor(hsl2rgb(base_color));
845 c.HighlightColor(hsl2rgb(highlight_color));
846 c.BackSkin(glm::clamp(skin_back.FakeNormal(random.SNorm()), 0.0, 1.0));
847 c.SideSkin(glm::clamp(skin_side.FakeNormal(random.SNorm()), 0.0, 1.0));
848 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
849 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
853 void Split(Creature &c) {
854 Creature *a = new Creature(c.GetSimulation());
855 const Situation &s = c.GetSituation();
857 a->Name(c.GetSimulation().Assets().name.Sequential());
858 c.GetGenome().Configure(*a);
859 for (const auto &cmp : c.GetComposition()) {
860 a->AddMass(cmp.resource, cmp.value * 0.5);
862 s.GetPlanet().AddCreature(a);
863 // TODO: duplicate situation somehow
864 a->GetSituation().SetPlanetSurface(
866 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.86, PI * 0.5, s.SurfaceNormal()));
868 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
870 Creature *b = new Creature(c.GetSimulation());
872 b->Name(c.GetSimulation().Assets().name.Sequential());
873 c.GetGenome().Configure(*b);
874 for (const auto &cmp : c.GetComposition()) {
875 b->AddMass(cmp.resource, cmp.value * 0.5);
877 s.GetPlanet().AddCreature(b);
878 b->GetSituation().SetPlanetSurface(
880 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.86, PI * -0.5, s.SurfaceNormal()));
882 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
888 Memory::Memory(Creature &c)
895 void Memory::Erase() {
897 known_creatures.clear();
900 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
901 double best_rating = -1.0;
902 for (const auto &k : known_types) {
903 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
904 auto entry = t.FindBestResource(accept);
905 if (entry != t.resources.end()) {
906 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
907 if (rating > best_rating) {
908 best_rating = rating;
909 pos = k.second.first_loc.position;
911 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
912 if (rating > best_rating) {
913 best_rating = rating;
914 pos = k.second.last_loc.position;
918 if (best_rating > 0.0) {
920 c.GetSimulation().Assets().random.SNorm(),
921 c.GetSimulation().Assets().random.SNorm(),
922 c.GetSimulation().Assets().random.SNorm());
923 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
924 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
931 void Memory::TrackCollision(Creature &other) {
932 // TODO: find out whose fault it was
933 // TODO: source values from personality
934 Profile &p = known_creatures[&other];
936 const double annoy_fact = p.annoyance / (p.annoyance + 1.0);
937 if (c.GetSimulation().Assets().random.UNorm() > annoy_fact * 0.1 * (1.0 - c.GetStats().Damage().value)) {
938 AttackGoal *g = new AttackGoal(c, other);
939 g->SetDamageTarget(annoy_fact);
940 g->Urgency(annoy_fact);
941 c.AddGoal(std::unique_ptr<Goal>(g));
946 void Memory::Tick(double dt) {
947 Situation &s = c.GetSituation();
949 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
954 void Memory::TrackStay(const Location &l, double t) {
955 const world::TileType &type = l.planet->TileTypeAt(l.position);
956 auto entry = known_types.find(type.id);
957 if (entry != known_types.end()) {
958 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
960 if (entry->second.time_spent > c.Age() * 0.25) {
961 // the place is very familiar
962 c.GetStats().Boredom().Add(-0.2);
965 c.GetStats().Boredom().Add(-0.1);
968 entry->second.last_been = c.GetSimulation().Time();
969 entry->second.last_loc = l;
970 entry->second.time_spent += t;
972 known_types.emplace(type.id, Stay{
973 c.GetSimulation().Time(),
975 c.GetSimulation().Time(),
979 // completely new place, interesting
980 // TODO: scale by personality trait
981 c.GetStats().Boredom().Add(-0.25);
986 NameGenerator::NameGenerator()
990 NameGenerator::~NameGenerator() {
993 std::string NameGenerator::Sequential() {
994 std::stringstream ss;
995 ss << "Blob " << ++counter;
1000 Situation::Situation()
1002 , state(glm::dvec3(0.0), glm::dvec3(0.0))
1006 Situation::~Situation() {
1009 bool Situation::OnPlanet() const noexcept {
1010 return type == PLANET_SURFACE;
1013 bool Situation::OnSurface() const noexcept {
1014 return type == PLANET_SURFACE;
1017 bool Situation::OnGround() const noexcept {
1018 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
1021 glm::dvec3 Situation::SurfaceNormal() const noexcept {
1022 return planet->NormalAt(state.pos);
1025 world::Tile &Situation::GetTile() const noexcept {
1026 return planet->TileAt(state.pos);
1029 const world::TileType &Situation::GetTileType() const noexcept {
1030 return planet->TileTypeAt(state.pos);
1033 void Situation::Move(const glm::dvec3 &dp) noexcept {
1035 EnforceConstraints(state);
1038 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
1040 EnforceConstraints(state);
1043 void Situation::EnforceConstraints(State &s) const noexcept {
1045 double r = GetPlanet().Radius();
1046 if (glm::length2(s.pos) < r * r) {
1047 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
1049 s.vel -= normal * glm::dot(normal, s.vel);
1054 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
1055 type = PLANET_SURFACE;
1058 EnforceConstraints(state);
1062 Steering::Steering(const Creature &c)
1076 Steering::~Steering() {
1079 void Steering::Off() noexcept {
1086 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1088 min_dist = min_distance;
1089 max_look = max_lookaround;
1092 void Steering::DontSeparate() noexcept {
1096 void Steering::ResumeSeparate() noexcept {
1100 void Steering::Halt() noexcept {
1106 void Steering::Pass(const glm::dvec3 &t) noexcept {
1113 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1120 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1121 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1122 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1123 glm::dvec3 result(0.0);
1125 // TODO: off surface situation
1126 glm::dvec3 repulse(0.0);
1127 const Situation &s = c.GetSituation();
1128 for (auto &other : s.GetPlanet().Creatures()) {
1129 if (&*other == &c) continue;
1130 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1131 if (glm::length2(diff) > max_look * max_look) continue;
1132 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1133 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1134 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1140 result += -5.0 * s.vel * force;
1143 glm::dvec3 diff = target - s.pos;
1144 if (!allzero(diff)) {
1145 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1149 glm::dvec3 diff = target - s.pos;
1150 double dist = glm::length(diff);
1151 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1152 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1155 // remove vertical component, if any
1156 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1157 result -= normal * glm::dot(normal, result);
1159 if (glm::length2(result) > max_force * max_force) {
1160 result = glm::normalize(result) * max_force;
1165 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1166 return (vel - s.vel) * acc;