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 "../graphics/color.hpp"
15 #include "../math/const.hpp"
16 #include "../ui/string.hpp"
17 #include "../world/Body.hpp"
18 #include "../world/Planet.hpp"
19 #include "../world/Simulation.hpp"
20 #include "../world/TileType.hpp"
24 #include <glm/gtx/rotate_vector.hpp>
25 #include <glm/gtx/transform.hpp>
26 #include <glm/gtx/vector_angle.hpp>
29 #include <glm/gtx/io.hpp>
31 using blobs::graphics::hsl2rgb;
32 using blobs::graphics::rgb2hsl;
38 Composition::Composition(const world::Set<world::Resource> &resources)
39 : resources(resources)
46 Composition::~Composition() {
50 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
51 return b.value < a.value;
55 void Composition::Add(int res, double amount) {
57 for (auto c = components.begin(); c != components.end(); ++c) {
58 if (c->resource == res) {
60 if (c->value <= 0.0) {
68 if (!found && amount > 0.0) {
69 components.emplace_back(res, amount);
71 std::sort(components.begin(), components.end(), CompositionCompare);
72 state_mass[resources[res].state] += amount;
74 total_volume += amount / resources[res].density;
77 bool Composition::Has(int res) const noexcept {
78 for (auto &c : components) {
79 if (c.resource == res) {
86 double Composition::Get(int res) const noexcept {
87 for (auto &c : components) {
88 if (c.resource == res) {
95 double Composition::Proportion(int res) const noexcept {
96 return Get(res) / TotalMass();
99 double Composition::StateProportion(int res) const noexcept {
100 return Get(res) / StateMass(resources[res].state);
103 double Composition::Compatibility(int res) const noexcept {
105 return StateProportion(res);
107 double max_compat = -1.0;
108 double min_compat = 1.0;
109 for (const auto &c : components) {
110 double prop = c.value / StateMass(resources[res].state);
111 for (const auto &compat : resources[c.resource].compatibility) {
112 double value = compat.second * prop;
113 if (value > max_compat) {
116 if (value < min_compat) {
121 if (min_compat < 0.0) {
129 Creature::Creature(world::Simulation &sim)
134 , composition(sim.Resources())
136 , highlight_color(0.0, 0.0, 0.0, 1.0)
150 , heading_target(0.0, 0.0, -1.0)
151 , heading_manual(false)
152 , perception_range(1.0)
153 , perception_range_squared(1.0)
154 , perception_omni_range(1.0)
155 , perception_omni_range_squared(1.0)
156 , perception_field(1.0)
159 // all creatures avoid each other for now
160 steering.Separate(0.1, 1.5);
163 Creature::~Creature() {
166 void Creature::AddMass(int res, double amount) {
167 composition.Add(res, amount);
168 double nonsolid = 0.0;
170 for (const auto &c : composition) {
171 volume += c.value / sim.Resources()[c.resource].density;
172 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
176 Mass(composition.TotalMass());
177 Size(std::cbrt(volume));
178 highlight_color.a = nonsolid / composition.TotalMass();
181 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
182 highlight_color = glm::dvec4(c, highlight_color.a);
185 void Creature::Ingest(int res, double amount) noexcept {
186 if (sim.Resources()[res].state == world::Resource::SOLID) {
187 // 30% of solids stays in body
188 AddMass(res, amount * 0.3 * composition.Compatibility(res));
190 // 10% of fluids stays in body
191 AddMass(res, amount * 0.1 * composition.Compatibility(res));
193 math::GaloisLFSR &random = sim.Assets().random;
194 if (random.UNorm() < AdaptChance()) {
195 // change color to be slightly more like resource
196 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
197 // solids affect base color, others highlight
198 int p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
199 int q = random.UInt(3); // hue, sat, or val
200 int r = random.UInt(2); // mean or deviation
201 math::Distribution *d = nullptr;
205 d = &genome.base_hue;
208 d = &genome.base_saturation;
211 d = &genome.base_lightness;
216 d = &genome.highlight_hue;
219 d = &genome.highlight_saturation;
222 d = &genome.highlight_lightness;
227 double diff = ref - d->Mean();
231 } else if (diff > 0.5) {
234 // move 0-15% of distance
235 d->Mean(std::fmod(d->Mean() + diff * random.UNorm() * 0.15, 1.0));
237 d->Mean(glm::clamp(d->Mean() + diff * random.UNorm() * 0.15, 0.0, 1.0));
240 // scale by ±15%, enforce bounds
241 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
244 if (sim.Resources()[res].state == world::Resource::LIQUID && random.UNorm() < AdaptChance()) {
245 // change texture randomly
246 // TODO: make change depending on surroundings and/or resource
247 int p = random.UInt(2); // back or side
248 int q = random.UInt(2); // mean or deviation
249 math::Distribution &d = p ? genome.skin_side : genome.skin_back;
251 // move ± one standard deviation
252 d.Mean(d.Mean() + (random.SNorm() * d.StandardDeviation()));
254 // scale by ±10%, enforce bounds
255 d.StandardDeviation(glm::clamp(d.StandardDeviation() * (1.0 + random.SNorm() * 0.1), 0.0001, 0.5));
260 void Creature::DoWork(double amount) noexcept {
261 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
262 // burn resources proportional to composition
263 // factor = 1/total * 1/efficiency * amount * -1
264 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
265 // make a copy to total remains constant and
266 // no entries disappear during iteration
267 Composition comp(composition);
268 for (auto &cmp : comp) {
269 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
270 AddMass(cmp.resource, value);
272 // doing work improves strength a little
273 properties.Strength() += amount * 0.0001;
276 void Creature::Hurt(double amount) noexcept {
277 stats.Damage().Add(amount);
278 if (stats.Damage().Full()) {
283 void Creature::Die() noexcept {
286 if (stats.Damage().Full()) {
287 std::ostream &log = sim.Log() << name << " ";
288 if (stats.Exhaustion().Full()) {
289 log << "died of exhaustion";
290 } else if (stats.Breath().Full()) {
292 } else if (stats.Thirst().Full()) {
293 log << "died of thirst";
294 } else if (stats.Hunger().Full()) {
295 log << "starved to death";
297 log << "succumed to wounds";
299 log << " at an age of " << ui::TimeString(Age())
300 << " (" << ui::PercentageString(Age() / properties.Lifetime())
301 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
314 bool Creature::Dead() const noexcept {
315 return death > birth;
318 void Creature::Remove() noexcept {
322 void Creature::Removed() noexcept {
329 void Creature::AddParent(Creature &p) {
330 parents.push_back(&p);
333 double Creature::Age() const noexcept {
334 return Dead() ? death - birth : sim.Time() - birth;
337 double Creature::AgeFactor(double peak) const noexcept {
338 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
339 // goes negative below -0.5 and starts to rise again above 1.0
340 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
341 // guarantee at least 1%
342 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
345 double Creature::EnergyEfficiency() const noexcept {
346 return 0.25 * AgeFactor(0.05);
349 double Creature::ExhaustionFactor() const noexcept {
350 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
353 double Creature::FatigueFactor() const noexcept {
354 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
357 double Creature::Strength() const noexcept {
358 // TODO: replace all age factors with actual growth and decay
359 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
362 double Creature::StrengthFactor() const noexcept {
363 double str = Strength();
364 return str / (str + 1.0);
367 double Creature::Stamina() const noexcept {
368 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
371 double Creature::StaminaFactor() const noexcept {
372 double stm = Stamina();
373 return stm / (stm + 1.0);
376 double Creature::Dexerty() const noexcept {
377 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
380 double Creature::DexertyFactor() const noexcept {
381 double dex = Dexerty();
382 return dex / (dex + 1.0);
385 double Creature::Intelligence() const noexcept {
386 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
389 double Creature::IntelligenceFactor() const noexcept {
390 double intl = Intelligence();
391 return intl / (intl + 1.0);
394 double Creature::Lifetime() const noexcept {
395 return properties.Lifetime();
398 double Creature::Fertility() const noexcept {
399 return properties.Fertility() * AgeFactor(0.25);
402 double Creature::Mutability() const noexcept {
403 return properties.Mutability();
406 double Creature::Adaptability() const noexcept {
407 return properties.Adaptability();
410 double Creature::OffspringMass() const noexcept {
411 return properties.OffspringMass();
414 double Creature::PerceptionRange() const noexcept {
415 return perception_range;
418 double Creature::PerceptionOmniRange() const noexcept {
419 return perception_omni_range;
422 double Creature::PerceptionField() const noexcept {
423 return perception_field;
426 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
427 const glm::dvec3 diff(p - situation.Position());
428 double ldiff = glm::length2(diff);
429 if (ldiff < perception_omni_range_squared) return true;
430 if (ldiff > perception_range_squared) return false;
431 return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
434 double Creature::OffspringChance() const noexcept {
435 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
438 double Creature::MutateChance() const noexcept {
439 return GetProperties().Mutability() * (1.0 / 3600.0);
442 double Creature::AdaptChance() const noexcept {
443 return GetProperties().Adaptability() * (1.0 / 120.0);
446 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
451 goals.emplace_back(std::move(g));
454 void Creature::SetBackgroundTask(std::unique_ptr<Goal> &&g) {
455 bg_task = std::move(g);
458 Goal &Creature::BackgroundTask() {
464 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
465 return b->Urgency() < a->Urgency();
470 void Creature::Tick(double dt) {
477 void Creature::Cache() noexcept {
478 double dex_fact = DexertyFactor();
479 perception_range = 3.0 * dex_fact + size;
480 perception_range_squared = perception_range * perception_range;
481 perception_omni_range = 0.5 * dex_fact + size;
482 perception_omni_range_squared = perception_omni_range * perception_omni_range;
483 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
484 perception_field = 0.8 - dex_fact;
487 void Creature::TickState(double dt) {
488 steering.MaxSpeed(Dexerty());
489 steering.MaxForce(Strength());
490 Situation::State state(situation.GetState());
491 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
492 Situation::Derivative b(Step(a, dt * 0.5));
493 Situation::Derivative c(Step(b, dt * 0.5));
494 Situation::Derivative d(Step(c, dt));
495 Situation::Derivative f(
496 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
497 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
499 state.pos += f.vel * dt;
500 state.vel += f.acc * dt;
501 situation.EnforceConstraints(state);
503 if (!heading_manual && glm::length2(state.vel) > 0.000001) {
504 const glm::dvec3 normal(situation.GetPlanet().NormalAt(state.pos));
505 const glm::dvec3 tangent(state.vel - (normal * glm::dot(state.vel, normal)));
506 if (glm::length2(tangent) > 0.000001) {
507 heading_target = glm::normalize(tangent);
510 double ang = glm::angle(heading_target, state.dir);
511 double turn_rate = PI * 0.75 * dt;
512 if (ang < turn_rate) {
513 state.dir = heading_target;
514 heading_manual = false;
516 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, heading_target)));
519 situation.SetState(state);
520 // work is force times distance
521 // keep 10% of gravity as a kind of background burn
522 DoWork(glm::length(f.acc - (0.9 * situation.GetPlanet().GravityAt(state.pos))) * Mass() * glm::length(f.vel) * dt);
525 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
526 Situation::State s = situation.GetState();
527 s.pos += ds.vel * dt;
528 s.vel += ds.acc * dt;
529 situation.EnforceConstraints(s);
530 glm::dvec3 force(steering.Force(s));
531 // gravity = antinormal * mass * Gm / r²
532 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
535 * (Mass() * situation.GetPlanet().GravitationalParameter()
536 / glm::length2(s.pos)));
537 // if net force is applied and in contact with surface
538 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
540 glm::dvec3 fn(normal * glm::dot(force, normal));
541 // TODO: friction somehow bigger than force?
542 glm::dvec3 ft(force - fn);
544 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
553 void Creature::TickStats(double dt) {
554 for (auto &s : stats.stat) {
557 // TODO: damage values depending on properties
558 if (stats.Breath().Full()) {
559 constexpr double dps = 1.0 / 4.0;
562 if (stats.Thirst().Full()) {
563 constexpr double dps = 1.0 / 32.0;
566 if (stats.Hunger().Full()) {
567 constexpr double dps = 1.0 / 128.0;
570 if (!situation.Moving()) {
571 // double exhaustion recovery when standing still
572 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
576 void Creature::TickBrain(double dt) {
580 // do background stuff
584 for (auto &goal : goals) {
587 Goal *top = &*goals.front();
588 // if active goal can be interrupted, check priorities
589 if (goals.size() > 1 && goals[0]->Interruptible()) {
590 std::sort(goals.begin(), goals.end(), GoalCompare);
592 if (&*goals.front() != top) {
593 top->SetBackground();
594 goals.front()->SetForeground();
595 top = &*goals.front();
598 for (auto goal = goals.begin(); goal != goals.end();) {
599 if ((*goal)->Complete()) {
605 if (&*goals.front() != top) {
606 goals.front()->SetForeground();
610 math::AABB Creature::CollisionBounds() const noexcept {
611 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
614 glm::dmat4 Creature::CollisionTransform() const noexcept {
615 const double half_size = size * 0.5;
616 const glm::dvec3 &pos = situation.Position();
618 orient[1] = situation.GetPlanet().NormalAt(pos);
619 orient[2] = situation.Heading();
620 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
621 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
623 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
624 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
625 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
627 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
630 void Creature::OnCollide(Creature &other) {
631 memory.TrackCollision(other);
634 glm::dmat4 Creature::LocalTransform() noexcept {
635 const double half_size = size * 0.5;
636 return CollisionTransform()
637 * glm::scale(glm::dvec3(half_size, half_size, half_size));
640 void Creature::BuildVAO() {
641 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
643 vao->BindAttributes();
644 vao->EnableAttribute(0);
645 vao->EnableAttribute(1);
646 vao->EnableAttribute(2);
647 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
648 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
649 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
650 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
652 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
653 constexpr float offset = 1.0f;
654 constexpr float max_tex = 5.999f;
655 const float tex[6] = {
657 float(std::floor(skin_side * max_tex)), // left
658 float(std::floor(skin_back * max_tex)), // top
659 float(std::floor(skin_back * max_tex)), // back
660 float(std::floor(skin_side * max_tex)), // right
663 for (int surface = 0; surface < 6; ++surface) {
664 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
665 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
667 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
668 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
669 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
670 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
671 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
672 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
673 attrib[4 * surface + 0].texture.x = tex_u_begin;
674 attrib[4 * surface + 0].texture.y = 1.0f;
675 attrib[4 * surface + 0].texture.z = tex[surface];
677 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
678 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
679 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
680 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
681 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
682 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
683 attrib[4 * surface + 1].texture.x = tex_u_end;
684 attrib[4 * surface + 1].texture.y = 1.0f;
685 attrib[4 * surface + 1].texture.z = tex[surface];
687 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
688 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
689 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
690 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
691 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
692 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
693 attrib[4 * surface + 2].texture.x = tex_u_begin;
694 attrib[4 * surface + 2].texture.y = 0.0f;
695 attrib[4 * surface + 2].texture.z = tex[surface];
697 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
698 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
699 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
700 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
701 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
702 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
703 attrib[4 * surface + 3].texture.x = tex_u_end;
704 attrib[4 * surface + 3].texture.y = 0.0f;
705 attrib[4 * surface + 3].texture.z = tex[surface];
709 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
711 auto element = vao->MapElements(GL_WRITE_ONLY);
712 for (int surface = 0; surface < 3; ++surface) {
713 element[6 * surface + 0] = 4 * surface + 0;
714 element[6 * surface + 1] = 4 * surface + 2;
715 element[6 * surface + 2] = 4 * surface + 1;
716 element[6 * surface + 3] = 4 * surface + 1;
717 element[6 * surface + 4] = 4 * surface + 2;
718 element[6 * surface + 5] = 4 * surface + 3;
720 for (int surface = 3; surface < 6; ++surface) {
721 element[6 * surface + 0] = 4 * surface + 0;
722 element[6 * surface + 1] = 4 * surface + 1;
723 element[6 * surface + 2] = 4 * surface + 2;
724 element[6 * surface + 3] = 4 * surface + 2;
725 element[6 * surface + 4] = 4 * surface + 1;
726 element[6 * surface + 5] = 4 * surface + 3;
732 void Creature::KillVAO() {
736 void Creature::Draw(graphics::Viewport &viewport) {
739 vao->DrawTriangles(6 * 6);
743 void Spawn(Creature &c, world::Planet &p) {
745 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
746 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
747 c.HeadingTarget(glm::dvec3(1.0, 0.0, 0.0));
749 // probe surrounding area for common resources
750 int start = p.SideLength() / 2 - 2;
752 std::map<int, double> yields;
753 for (int y = start; y < end; ++y) {
754 for (int x = start; x < end; ++x) {
755 const world::TileType &t = p.TypeAt(0, x, y);
756 for (auto yield : t.resources) {
757 yields[yield.resource] += yield.ubiquity;
763 for (auto e : yields) {
764 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
765 if (liquid < 0 || e.second > yields[liquid]) {
768 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
769 if (solid < 0 || e.second > yields[solid]) {
776 genome.properties.Strength() = { 2.0, 0.1 };
777 genome.properties.Stamina() = { 2.0, 0.1 };
778 genome.properties.Dexerty() = { 2.0, 0.1 };
779 genome.properties.Intelligence() = { 1.0, 0.1 };
780 genome.properties.Lifetime() = { 480.0, 60.0 };
781 genome.properties.Fertility() = { 0.5, 0.03 };
782 genome.properties.Mutability() = { 0.9, 0.1 };
783 genome.properties.Adaptability() = { 0.9, 0.1 };
784 genome.properties.OffspringMass() = { 0.3, 0.02 };
786 glm::dvec3 color_avg(0.0);
787 double color_divisor = 0.0;
789 if (p.HasAtmosphere()) {
790 c.AddMass(p.Atmosphere(), 0.005);
791 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
792 color_divisor += 0.1;
795 c.AddMass(liquid, 0.3);
796 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
797 color_divisor += 0.5;
800 c.AddMass(solid, 0.1);
801 color_avg += c.GetSimulation().Resources()[solid].base_color;
802 color_divisor += 1.0;
805 if (color_divisor > 0.001) {
806 color_avg /= color_divisor;
808 glm::dvec3 hsl = rgb2hsl(color_avg);
809 genome.base_hue = { hsl.x, 0.01 };
810 genome.base_saturation = { hsl.y, 0.01 };
811 genome.base_lightness = { hsl.z, 0.01 };
812 // use opposite color as start highlight
813 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
814 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
815 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
817 genome.skin_side = { 0.5, 0.01 };
818 genome.skin_back = { 0.5, 0.01 };
823 void Genome::Configure(Creature &c) const {
824 c.GetGenome() = *this;
826 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
828 c.GetProperties() = Instantiate(properties, random);
830 // TODO: derive stats from properties
831 c.GetStats().Damage().gain = (-1.0 / 100.0);
832 c.GetStats().Breath().gain = (1.0 / 5.0);
833 c.GetStats().Thirst().gain = (1.0 / 60.0);
834 c.GetStats().Hunger().gain = (1.0 / 200.0);
835 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
836 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
837 c.GetStats().Boredom().gain = (1.0 / 300.0);
839 glm::dvec3 base_color(
840 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
841 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
842 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
844 glm::dvec3 highlight_color(
845 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
846 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
847 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
849 c.BaseColor(hsl2rgb(base_color));
850 c.HighlightColor(hsl2rgb(highlight_color));
851 c.BackSkin(glm::clamp(skin_back.FakeNormal(random.SNorm()), 0.0, 1.0));
852 c.SideSkin(glm::clamp(skin_side.FakeNormal(random.SNorm()), 0.0, 1.0));
853 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
854 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
858 void Split(Creature &c) {
859 Creature *a = new Creature(c.GetSimulation());
860 const Situation &s = c.GetSituation();
862 a->Name(c.GetSimulation().Assets().name.Sequential());
863 c.GetGenome().Configure(*a);
864 for (const auto &cmp : c.GetComposition()) {
865 // require at least 0.1%
866 if (cmp.value > 0.002) {
867 a->AddMass(cmp.resource, cmp.value * 0.5);
870 s.GetPlanet().AddCreature(a);
871 // TODO: duplicate situation somehow
872 a->GetSituation().SetPlanetSurface(
874 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.86, PI * 0.5, s.SurfaceNormal()));
876 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
878 Creature *b = new Creature(c.GetSimulation());
880 b->Name(c.GetSimulation().Assets().name.Sequential());
881 c.GetGenome().Configure(*b);
882 for (const auto &cmp : c.GetComposition()) {
883 // require at least 0.1%
884 if (cmp.value > 0.002) {
885 b->AddMass(cmp.resource, cmp.value * 0.5);
888 s.GetPlanet().AddCreature(b);
889 b->GetSituation().SetPlanetSurface(
891 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.86, PI * -0.5, s.SurfaceNormal()));
893 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
899 Memory::Memory(Creature &c)
906 void Memory::Erase() {
908 known_creatures.clear();
911 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
912 double best_rating = -1.0;
913 for (const auto &k : known_types) {
914 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
915 auto entry = t.FindBestResource(accept);
916 if (entry != t.resources.end()) {
917 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
918 if (rating > best_rating) {
919 best_rating = rating;
920 pos = k.second.first_loc.position;
922 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
923 if (rating > best_rating) {
924 best_rating = rating;
925 pos = k.second.last_loc.position;
929 if (best_rating > 0.0) {
931 c.GetSimulation().Assets().random.SNorm(),
932 c.GetSimulation().Assets().random.SNorm(),
933 c.GetSimulation().Assets().random.SNorm());
934 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
935 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
942 void Memory::TrackCollision(Creature &other) {
943 // TODO: find out whose fault it was
944 // TODO: source values from personality
945 Profile &p = known_creatures[&other];
947 const double annoy_fact = p.annoyance / (p.annoyance + 1.0);
948 if (c.GetSimulation().Assets().random.UNorm() > annoy_fact * 0.1 * (1.0 - c.GetStats().Damage().value)) {
949 AttackGoal *g = new AttackGoal(c, other);
950 g->SetDamageTarget(annoy_fact);
951 g->Urgency(annoy_fact);
952 c.AddGoal(std::unique_ptr<Goal>(g));
957 void Memory::Tick(double dt) {
958 Situation &s = c.GetSituation();
960 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
965 void Memory::TrackStay(const Location &l, double t) {
966 const world::TileType &type = l.planet->TileTypeAt(l.position);
967 auto entry = known_types.find(type.id);
968 if (entry != known_types.end()) {
969 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
971 if (entry->second.time_spent > c.Age() * 0.25) {
972 // the place is very familiar
973 c.GetStats().Boredom().Add(-0.2);
976 c.GetStats().Boredom().Add(-0.1);
979 entry->second.last_been = c.GetSimulation().Time();
980 entry->second.last_loc = l;
981 entry->second.time_spent += t;
983 known_types.emplace(type.id, Stay{
984 c.GetSimulation().Time(),
986 c.GetSimulation().Time(),
990 // completely new place, interesting
991 // TODO: scale by personality trait
992 c.GetStats().Boredom().Add(-0.25);
997 NameGenerator::NameGenerator()
1001 NameGenerator::~NameGenerator() {
1004 std::string NameGenerator::Sequential() {
1005 std::stringstream ss;
1006 ss << "Blob " << ++counter;
1011 Situation::Situation()
1013 , state(glm::dvec3(0.0), glm::dvec3(0.0))
1017 Situation::~Situation() {
1020 bool Situation::OnPlanet() const noexcept {
1021 return type == PLANET_SURFACE;
1024 bool Situation::OnSurface() const noexcept {
1025 return type == PLANET_SURFACE;
1028 bool Situation::OnGround() const noexcept {
1029 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
1032 glm::dvec3 Situation::SurfaceNormal() const noexcept {
1033 return planet->NormalAt(state.pos);
1036 world::Tile &Situation::GetTile() const noexcept {
1037 return planet->TileAt(state.pos);
1040 const world::TileType &Situation::GetTileType() const noexcept {
1041 return planet->TileTypeAt(state.pos);
1044 void Situation::Move(const glm::dvec3 &dp) noexcept {
1046 EnforceConstraints(state);
1049 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
1051 EnforceConstraints(state);
1054 void Situation::EnforceConstraints(State &s) const noexcept {
1056 double r = GetPlanet().Radius();
1057 if (glm::length2(s.pos) < r * r) {
1058 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
1060 s.vel -= normal * glm::dot(normal, s.vel);
1065 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
1066 type = PLANET_SURFACE;
1069 EnforceConstraints(state);
1073 Steering::Steering(const Creature &c)
1087 Steering::~Steering() {
1090 void Steering::Off() noexcept {
1097 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1099 min_dist = min_distance;
1100 max_look = max_lookaround;
1103 void Steering::DontSeparate() noexcept {
1107 void Steering::ResumeSeparate() noexcept {
1111 void Steering::Halt() noexcept {
1117 void Steering::Pass(const glm::dvec3 &t) noexcept {
1124 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1131 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1132 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1133 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1134 glm::dvec3 result(0.0);
1136 // TODO: off surface situation
1137 glm::dvec3 repulse(0.0);
1138 const Situation &s = c.GetSituation();
1139 for (auto &other : s.GetPlanet().Creatures()) {
1140 if (&*other == &c) continue;
1141 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1142 if (glm::length2(diff) > max_look * max_look) continue;
1143 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1144 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1145 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1151 result += -5.0 * s.vel * force;
1154 glm::dvec3 diff = target - s.pos;
1155 if (!allzero(diff)) {
1156 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1160 glm::dvec3 diff = target - s.pos;
1161 double dist = glm::length(diff);
1162 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1163 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1166 // remove vertical component, if any
1167 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1168 result -= normal * glm::dot(normal, result);
1170 if (glm::length2(result) > max_force * max_force) {
1171 result = glm::normalize(result) * max_force;
1176 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1177 return (vel - s.vel) * acc;