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 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
194 double q = random.UInt(3); // hue, sat, or val
195 double 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));
241 void Creature::DoWork(double amount) noexcept {
242 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
243 // burn resources proportional to composition
244 // factor = 1/total * 1/efficiency * amount * -1
245 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
246 // make a copy to total remains constant and
247 // no entries disappear during iteration
248 Composition comp(composition);
249 for (auto &cmp : comp) {
250 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
251 AddMass(cmp.resource, value);
253 // doing work improves strength a little
254 properties.Strength() += amount * 0.0001;
257 void Creature::Hurt(double amount) noexcept {
258 stats.Damage().Add(amount);
259 if (stats.Damage().Full()) {
264 void Creature::Die() noexcept {
267 if (stats.Damage().Full()) {
268 std::ostream &log = sim.Log() << name << " ";
269 if (stats.Exhaustion().Full()) {
270 log << "died of exhaustion";
271 } else if (stats.Breath().Full()) {
273 } else if (stats.Thirst().Full()) {
274 log << "died of thirst";
275 } else if (stats.Hunger().Full()) {
276 log << "starved to death";
278 log << "succumed to wounds";
280 log << " at an age of " << ui::TimeString(Age())
281 << " (" << ui::PercentageString(Age() / properties.Lifetime())
282 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
295 bool Creature::Dead() const noexcept {
296 return death > birth;
299 void Creature::Remove() noexcept {
303 void Creature::Removed() noexcept {
310 void Creature::AddParent(Creature &p) {
311 parents.push_back(&p);
314 double Creature::Age() const noexcept {
315 return Dead() ? death - birth : sim.Time() - birth;
318 double Creature::AgeFactor(double peak) const noexcept {
319 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
320 // goes negative below -0.5 and starts to rise again above 1.0
321 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
322 // guarantee at least 1%
323 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
326 double Creature::EnergyEfficiency() const noexcept {
327 return 0.25 * AgeFactor(0.05);
330 double Creature::ExhaustionFactor() const noexcept {
331 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
334 double Creature::FatigueFactor() const noexcept {
335 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
338 double Creature::Strength() const noexcept {
339 // TODO: replace all age factors with actual growth and decay
340 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
343 double Creature::StrengthFactor() const noexcept {
344 double str = Strength();
345 return str / (str + 1.0);
348 double Creature::Stamina() const noexcept {
349 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
352 double Creature::StaminaFactor() const noexcept {
353 double stm = Stamina();
354 return stm / (stm + 1.0);
357 double Creature::Dexerty() const noexcept {
358 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
361 double Creature::DexertyFactor() const noexcept {
362 double dex = Dexerty();
363 return dex / (dex + 1.0);
366 double Creature::Intelligence() const noexcept {
367 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
370 double Creature::IntelligenceFactor() const noexcept {
371 double intl = Intelligence();
372 return intl / (intl + 1.0);
375 double Creature::Lifetime() const noexcept {
376 return properties.Lifetime();
379 double Creature::Fertility() const noexcept {
380 return properties.Fertility() * AgeFactor(0.25);
383 double Creature::Mutability() const noexcept {
384 return properties.Mutability();
387 double Creature::Adaptability() const noexcept {
388 return properties.Adaptability();
391 double Creature::OffspringMass() const noexcept {
392 return properties.OffspringMass();
395 double Creature::PerceptionRange() const noexcept {
396 return perception_range;
399 double Creature::PerceptionOmniRange() const noexcept {
400 return perception_omni_range;
403 double Creature::PerceptionField() const noexcept {
404 return perception_field;
407 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
408 const glm::dvec3 diff(p - situation.Position());
409 double ldiff = glm::length2(diff);
410 if (ldiff < perception_omni_range_squared) return true;
411 if (ldiff > perception_range_squared) return false;
412 return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
415 double Creature::OffspringChance() const noexcept {
416 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
419 double Creature::MutateChance() const noexcept {
420 return GetProperties().Mutability() * (1.0 / 3600.0);
423 double Creature::AdaptChance() const noexcept {
424 return GetProperties().Adaptability() * (1.0 / 120.0);
427 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
432 goals.emplace_back(std::move(g));
435 void Creature::SetBackgroundTask(std::unique_ptr<Goal> &&g) {
436 bg_task = std::move(g);
439 Goal &Creature::BackgroundTask() {
445 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
446 return b->Urgency() < a->Urgency();
451 void Creature::Tick(double dt) {
458 void Creature::Cache() noexcept {
459 double dex_fact = DexertyFactor();
460 perception_range = 3.0 * dex_fact + size;
461 perception_range_squared = perception_range * perception_range;
462 perception_omni_range = 0.5 * dex_fact + size;
463 perception_omni_range_squared = perception_omni_range * perception_omni_range;
464 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
465 perception_field = 0.8 - dex_fact;
468 void Creature::TickState(double dt) {
469 steering.MaxSpeed(Dexerty());
470 steering.MaxForce(Strength());
471 Situation::State state(situation.GetState());
472 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
473 Situation::Derivative b(Step(a, dt * 0.5));
474 Situation::Derivative c(Step(b, dt * 0.5));
475 Situation::Derivative d(Step(c, dt));
476 Situation::Derivative f(
477 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
478 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
480 state.pos += f.vel * dt;
481 state.vel += f.acc * dt;
482 situation.EnforceConstraints(state);
484 if (!heading_manual && glm::length2(state.vel) > 0.000001) {
485 const glm::dvec3 normal(situation.GetPlanet().NormalAt(state.pos));
486 const glm::dvec3 tangent(state.vel - (normal * glm::dot(state.vel, normal)));
487 if (glm::length2(tangent) > 0.000001) {
488 heading_target = glm::normalize(tangent);
491 double ang = glm::angle(heading_target, state.dir);
492 double turn_rate = PI * 0.75 * dt;
493 if (ang < turn_rate) {
494 state.dir = heading_target;
495 heading_manual = false;
497 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, heading_target)));
500 situation.SetState(state);
501 // work is force times distance
502 // keep 10% of gravity as a kind of background burn
503 DoWork(glm::length(f.acc - (0.9 * situation.GetPlanet().GravityAt(state.pos))) * Mass() * glm::length(f.vel) * dt);
506 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
507 Situation::State s = situation.GetState();
508 s.pos += ds.vel * dt;
509 s.vel += ds.acc * dt;
510 situation.EnforceConstraints(s);
511 glm::dvec3 force(steering.Force(s));
512 // gravity = antinormal * mass * Gm / r²
513 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
516 * (Mass() * situation.GetPlanet().GravitationalParameter()
517 / glm::length2(s.pos)));
518 // if net force is applied and in contact with surface
519 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
521 glm::dvec3 fn(normal * glm::dot(force, normal));
522 // TODO: friction somehow bigger than force?
523 glm::dvec3 ft(force - fn);
525 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
534 void Creature::TickStats(double dt) {
535 for (auto &s : stats.stat) {
538 // TODO: damage values depending on properties
539 if (stats.Breath().Full()) {
540 constexpr double dps = 1.0 / 4.0;
543 if (stats.Thirst().Full()) {
544 constexpr double dps = 1.0 / 32.0;
547 if (stats.Hunger().Full()) {
548 constexpr double dps = 1.0 / 128.0;
551 if (!situation.Moving()) {
552 // double exhaustion recovery when standing still
553 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
557 void Creature::TickBrain(double dt) {
561 // do background stuff
565 for (auto &goal : goals) {
568 Goal *top = &*goals.front();
569 // if active goal can be interrupted, check priorities
570 if (goals.size() > 1 && goals[0]->Interruptible()) {
571 std::sort(goals.begin(), goals.end(), GoalCompare);
573 if (&*goals.front() != top) {
574 top->SetBackground();
575 goals.front()->SetForeground();
576 top = &*goals.front();
579 for (auto goal = goals.begin(); goal != goals.end();) {
580 if ((*goal)->Complete()) {
586 if (&*goals.front() != top) {
587 goals.front()->SetForeground();
591 math::AABB Creature::CollisionBounds() const noexcept {
592 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
595 glm::dmat4 Creature::CollisionTransform() const noexcept {
596 const double half_size = size * 0.5;
597 const glm::dvec3 &pos = situation.Position();
599 orient[1] = situation.GetPlanet().NormalAt(pos);
600 orient[2] = situation.Heading();
601 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
602 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
604 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
605 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
606 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
608 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
611 void Creature::OnCollide(Creature &other) {
612 memory.TrackCollision(other);
615 glm::dmat4 Creature::LocalTransform() noexcept {
616 const double half_size = size * 0.5;
617 return CollisionTransform()
618 * glm::scale(glm::dvec3(half_size, half_size, half_size));
621 void Creature::BuildVAO() {
622 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
624 vao->BindAttributes();
625 vao->EnableAttribute(0);
626 vao->EnableAttribute(1);
627 vao->EnableAttribute(2);
628 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
629 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
630 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
631 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
633 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
634 const float offset = 1.0f;
635 for (int surface = 0; surface < 6; ++surface) {
636 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
637 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
639 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
640 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
641 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
642 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
643 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
644 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
645 attrib[4 * surface + 0].texture.x = tex_u_begin;
646 attrib[4 * surface + 0].texture.y = 1.0f;
647 attrib[4 * surface + 0].texture.z = surface;
649 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
650 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
651 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
652 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
653 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
654 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
655 attrib[4 * surface + 1].texture.x = tex_u_end;
656 attrib[4 * surface + 1].texture.y = 1.0f;
657 attrib[4 * surface + 1].texture.z = surface;
659 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
660 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
661 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
662 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
663 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
664 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
665 attrib[4 * surface + 2].texture.x = tex_u_begin;
666 attrib[4 * surface + 2].texture.y = 0.0f;
667 attrib[4 * surface + 2].texture.z = surface;
669 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
670 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
671 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
672 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
673 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
674 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
675 attrib[4 * surface + 3].texture.x = tex_u_end;
676 attrib[4 * surface + 3].texture.y = 0.0f;
677 attrib[4 * surface + 3].texture.z = surface;
681 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
683 auto element = vao->MapElements(GL_WRITE_ONLY);
684 for (int surface = 0; surface < 3; ++surface) {
685 element[6 * surface + 0] = 4 * surface + 0;
686 element[6 * surface + 1] = 4 * surface + 2;
687 element[6 * surface + 2] = 4 * surface + 1;
688 element[6 * surface + 3] = 4 * surface + 1;
689 element[6 * surface + 4] = 4 * surface + 2;
690 element[6 * surface + 5] = 4 * surface + 3;
692 for (int surface = 3; surface < 6; ++surface) {
693 element[6 * surface + 0] = 4 * surface + 0;
694 element[6 * surface + 1] = 4 * surface + 1;
695 element[6 * surface + 2] = 4 * surface + 2;
696 element[6 * surface + 3] = 4 * surface + 2;
697 element[6 * surface + 4] = 4 * surface + 1;
698 element[6 * surface + 5] = 4 * surface + 3;
704 void Creature::KillVAO() {
708 void Creature::Draw(graphics::Viewport &viewport) {
711 vao->DrawTriangles(6 * 6);
715 void Spawn(Creature &c, world::Planet &p) {
717 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
718 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
719 c.HeadingTarget(glm::dvec3(1.0, 0.0, 0.0));
721 // probe surrounding area for common resources
722 int start = p.SideLength() / 2 - 2;
724 std::map<int, double> yields;
725 for (int y = start; y < end; ++y) {
726 for (int x = start; x < end; ++x) {
727 const world::TileType &t = p.TypeAt(0, x, y);
728 for (auto yield : t.resources) {
729 yields[yield.resource] += yield.ubiquity;
735 for (auto e : yields) {
736 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
737 if (liquid < 0 || e.second > yields[liquid]) {
740 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
741 if (solid < 0 || e.second > yields[solid]) {
748 genome.properties.Strength() = { 2.0, 0.1 };
749 genome.properties.Stamina() = { 2.0, 0.1 };
750 genome.properties.Dexerty() = { 2.0, 0.1 };
751 genome.properties.Intelligence() = { 1.0, 0.1 };
752 genome.properties.Lifetime() = { 480.0, 60.0 };
753 genome.properties.Fertility() = { 0.5, 0.03 };
754 genome.properties.Mutability() = { 0.9, 0.1 };
755 genome.properties.Adaptability() = { 0.9, 0.1 };
756 genome.properties.OffspringMass() = { 0.3, 0.02 };
758 glm::dvec3 color_avg(0.0);
759 double color_divisor = 0.0;
761 if (p.HasAtmosphere()) {
762 c.AddMass(p.Atmosphere(), 0.01);
763 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
764 color_divisor += 0.1;
767 c.AddMass(liquid, 0.3);
768 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
769 color_divisor += 0.5;
772 c.AddMass(solid, 0.1);
773 color_avg += c.GetSimulation().Resources()[solid].base_color;
774 color_divisor += 1.0;
777 if (color_divisor > 0.001) {
778 color_avg /= color_divisor;
780 glm::dvec3 hsl = rgb2hsl(color_avg);
781 genome.base_hue = { hsl.x, 0.01 };
782 genome.base_saturation = { hsl.y, 0.01 };
783 genome.base_lightness = { hsl.z, 0.01 };
784 // use opposite color as start highlight
785 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
786 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
787 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
792 void Genome::Configure(Creature &c) const {
793 c.GetGenome() = *this;
795 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
797 c.GetProperties() = Instantiate(properties, random);
799 // TODO: derive stats from properties
800 c.GetStats().Damage().gain = (-1.0 / 100.0);
801 c.GetStats().Breath().gain = (1.0 / 5.0);
802 c.GetStats().Thirst().gain = (1.0 / 60.0);
803 c.GetStats().Hunger().gain = (1.0 / 200.0);
804 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
805 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
806 c.GetStats().Boredom().gain = (1.0 / 300.0);
808 glm::dvec3 base_color(
809 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
810 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
811 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
813 glm::dvec3 highlight_color(
814 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
815 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
816 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
818 c.BaseColor(hsl2rgb(base_color));
819 c.HighlightColor(hsl2rgb(highlight_color));
820 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
821 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
825 void Split(Creature &c) {
826 Creature *a = new Creature(c.GetSimulation());
827 const Situation &s = c.GetSituation();
829 a->Name(c.GetSimulation().Assets().name.Sequential());
830 c.GetGenome().Configure(*a);
831 for (const auto &cmp : c.GetComposition()) {
832 a->AddMass(cmp.resource, cmp.value * 0.5);
834 s.GetPlanet().AddCreature(a);
835 // TODO: duplicate situation somehow
836 a->GetSituation().SetPlanetSurface(
838 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.86, PI * 0.5, s.SurfaceNormal()));
840 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
842 Creature *b = new Creature(c.GetSimulation());
844 b->Name(c.GetSimulation().Assets().name.Sequential());
845 c.GetGenome().Configure(*b);
846 for (const auto &cmp : c.GetComposition()) {
847 b->AddMass(cmp.resource, cmp.value * 0.5);
849 s.GetPlanet().AddCreature(b);
850 b->GetSituation().SetPlanetSurface(
852 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.86, PI * -0.5, s.SurfaceNormal()));
854 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
860 Memory::Memory(Creature &c)
867 void Memory::Erase() {
869 known_creatures.clear();
872 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
873 double best_rating = -1.0;
874 for (const auto &k : known_types) {
875 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
876 auto entry = t.FindBestResource(accept);
877 if (entry != t.resources.end()) {
878 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
879 if (rating > best_rating) {
880 best_rating = rating;
881 pos = k.second.first_loc.position;
883 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
884 if (rating > best_rating) {
885 best_rating = rating;
886 pos = k.second.last_loc.position;
890 if (best_rating > 0.0) {
892 c.GetSimulation().Assets().random.SNorm(),
893 c.GetSimulation().Assets().random.SNorm(),
894 c.GetSimulation().Assets().random.SNorm());
895 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
896 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
903 void Memory::TrackCollision(Creature &other) {
904 // TODO: find out whose fault it was
905 // TODO: source values from personality
906 Profile &p = known_creatures[&other];
908 const double annoy_fact = p.annoyance / (p.annoyance + 1.0);
909 if (c.GetSimulation().Assets().random.UNorm() > annoy_fact * 0.1 * (1.0 - c.GetStats().Damage().value)) {
910 AttackGoal *g = new AttackGoal(c, other);
911 g->SetDamageTarget(annoy_fact);
912 g->Urgency(annoy_fact);
913 c.AddGoal(std::unique_ptr<Goal>(g));
918 void Memory::Tick(double dt) {
919 Situation &s = c.GetSituation();
921 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
926 void Memory::TrackStay(const Location &l, double t) {
927 const world::TileType &type = l.planet->TileTypeAt(l.position);
928 auto entry = known_types.find(type.id);
929 if (entry != known_types.end()) {
930 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
932 if (entry->second.time_spent > c.Age() * 0.25) {
933 // the place is very familiar
934 c.GetStats().Boredom().Add(-0.2);
937 c.GetStats().Boredom().Add(-0.1);
940 entry->second.last_been = c.GetSimulation().Time();
941 entry->second.last_loc = l;
942 entry->second.time_spent += t;
944 known_types.emplace(type.id, Stay{
945 c.GetSimulation().Time(),
947 c.GetSimulation().Time(),
951 // completely new place, interesting
952 // TODO: scale by personality trait
953 c.GetStats().Boredom().Add(-0.25);
958 NameGenerator::NameGenerator()
962 NameGenerator::~NameGenerator() {
965 std::string NameGenerator::Sequential() {
966 std::stringstream ss;
967 ss << "Blob " << ++counter;
972 Situation::Situation()
974 , state(glm::dvec3(0.0), glm::dvec3(0.0))
978 Situation::~Situation() {
981 bool Situation::OnPlanet() const noexcept {
982 return type == PLANET_SURFACE;
985 bool Situation::OnSurface() const noexcept {
986 return type == PLANET_SURFACE;
989 bool Situation::OnGround() const noexcept {
990 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
993 glm::dvec3 Situation::SurfaceNormal() const noexcept {
994 return planet->NormalAt(state.pos);
997 world::Tile &Situation::GetTile() const noexcept {
998 return planet->TileAt(state.pos);
1001 const world::TileType &Situation::GetTileType() const noexcept {
1002 return planet->TileTypeAt(state.pos);
1005 void Situation::Move(const glm::dvec3 &dp) noexcept {
1007 EnforceConstraints(state);
1010 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
1012 EnforceConstraints(state);
1015 void Situation::EnforceConstraints(State &s) const noexcept {
1017 double r = GetPlanet().Radius();
1018 if (glm::length2(s.pos) < r * r) {
1019 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
1021 s.vel -= normal * glm::dot(normal, s.vel);
1026 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
1027 type = PLANET_SURFACE;
1030 EnforceConstraints(state);
1034 Steering::Steering(const Creature &c)
1048 Steering::~Steering() {
1051 void Steering::Off() noexcept {
1058 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1060 min_dist = min_distance;
1061 max_look = max_lookaround;
1064 void Steering::DontSeparate() noexcept {
1068 void Steering::ResumeSeparate() noexcept {
1072 void Steering::Halt() noexcept {
1078 void Steering::Pass(const glm::dvec3 &t) noexcept {
1085 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1092 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1093 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1094 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1095 glm::dvec3 result(0.0);
1097 // TODO: off surface situation
1098 glm::dvec3 repulse(0.0);
1099 const Situation &s = c.GetSituation();
1100 for (auto &other : s.GetPlanet().Creatures()) {
1101 if (&*other == &c) continue;
1102 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1103 if (glm::length2(diff) > max_look * max_look) continue;
1104 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1105 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1106 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1112 result += -5.0 * s.vel * force;
1115 glm::dvec3 diff = target - s.pos;
1116 if (!allzero(diff)) {
1117 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1121 glm::dvec3 diff = target - s.pos;
1122 double dist = glm::length(diff);
1123 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1124 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1127 // remove vertical component, if any
1128 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1129 result -= normal * glm::dot(normal, result);
1131 if (glm::length2(result) > max_force * max_force) {
1132 result = glm::normalize(result) * max_force;
1137 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1138 return (vel - s.vel) * acc;