1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "BlobBackgroundTask.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../world/Body.hpp"
15 #include "../world/Planet.hpp"
16 #include "../world/Simulation.hpp"
17 #include "../world/TileType.hpp"
21 #include <glm/gtx/transform.hpp>
22 #include <glm/gtx/vector_angle.hpp>
25 #include <glm/gtx/io.hpp>
31 Composition::Composition()
35 Composition::~Composition() {
39 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
40 return b.value < a.value;
44 void Composition::Add(int res, double amount) {
46 for (auto &c : components) {
47 if (c.resource == res) {
54 components.emplace_back(res, amount);
56 std::sort(components.begin(), components.end(), CompositionCompare);
59 bool Composition::Has(int res) const noexcept {
60 for (auto &c : components) {
61 if (c.resource == res) {
68 double Composition::Get(int res) const noexcept {
69 for (auto &c : components) {
70 if (c.resource == res) {
78 Creature::Creature(world::Simulation &sim)
85 , highlight_color(0.0, 0.0, 0.0, 1.0)
98 // all creatures avoid each other for now
99 steering.Separate(0.1, 1.5);
102 Creature::~Creature() {
105 void Creature::AddMass(int res, double amount) {
106 composition.Add(res, amount);
108 double nonsolid = 0.0;
110 for (const auto &c : composition) {
112 volume += c.value / sim.Assets().data.resources[c.resource].density;
113 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
118 Size(std::cbrt(volume));
119 highlight_color.a = nonsolid / mass;
122 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
123 highlight_color = glm::dvec4(c, highlight_color.a);
126 void Creature::Ingest(int res, double amount) noexcept {
127 // TODO: check foreign materials
129 AddMass(res, amount * 0.1);
132 void Creature::Hurt(double amount) noexcept {
133 stats.Damage().Add(amount);
134 if (stats.Damage().Full()) {
135 std::cout << "[" << int(sim.Time()) << "s] " << name << " ";
136 if (stats.Breath().Full()) {
137 std::cout << "suffocated";
138 } else if (stats.Thirst().Full()) {
139 std::cout << "died of thirst";
140 } else if (stats.Hunger().Full()) {
141 std::cout << "starved to death";
143 std::cout << "succumed to wounds";
145 std::cout << std::endl;
150 void Creature::Die() noexcept {
159 double Creature::Age() const noexcept {
160 return sim.Time() - birth;
163 double Creature::AgeFactor(double peak) const noexcept {
164 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
165 // goes negative below -0.5 and starts to rise again above 1.0
166 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
167 return 1.0 - (3.0 * t * t) + (2.0 * t * t * t);
170 double Creature::ExhaustionFactor() const noexcept {
171 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
174 double Creature::FatigueFactor() const noexcept {
175 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
178 double Creature::Strength() const noexcept {
179 // TODO: replace all age factors with actual growth and decay
180 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
183 double Creature::Stamina() const noexcept {
184 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
187 double Creature::Dexerty() const noexcept {
188 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
191 double Creature::Intelligence() const noexcept {
192 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
195 double Creature::Lifetime() const noexcept {
196 return properties.Lifetime();
199 double Creature::Fertility() const noexcept {
200 return properties.Fertility() * AgeFactor(0.25);
203 double Creature::Mutability() const noexcept {
204 return properties.Mutability();
207 double Creature::OffspringMass() const noexcept {
208 return properties.OffspringMass();
211 double Creature::OffspringChance() const noexcept {
212 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
215 double Creature::MutateChance() const noexcept {
216 return GetProperties().Mutability() * (1.0 / 3600.0);
219 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
221 goals.emplace_back(std::move(g));
226 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
227 return b->Urgency() < a->Urgency();
232 void Creature::Tick(double dt) {
238 void Creature::TickState(double dt) {
239 steering.MaxSpeed(Dexerty());
240 steering.MaxForce(Strength());
241 Situation::State state(situation.GetState());
242 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
243 Situation::Derivative b(Step(a, dt * 0.5));
244 Situation::Derivative c(Step(b, dt * 0.5));
245 Situation::Derivative d(Step(c, dt));
246 Situation::Derivative f(
247 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
248 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
250 state.pos += f.vel * dt;
251 state.vel += f.acc * dt;
252 if (length2(state.vel) > 0.000001) {
253 glm::dvec3 nvel(normalize(state.vel));
254 double ang = angle(nvel, state.dir);
255 double turn_rate = PI * 0.5 * dt;
256 if (ang < turn_rate) {
257 state.dir = normalize(state.vel);
258 } else if (std::abs(ang - PI) < 0.001) {
259 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
261 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
264 situation.SetState(state);
265 stats.Exhaustion().Add(length(f.acc) * Mass() / Stamina() * dt);
268 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
269 Situation::State s = situation.GetState();
270 s.pos += ds.vel * dt;
271 s.vel += ds.acc * dt;
274 steering.Force(s) / Mass()
278 void Creature::TickStats(double dt) {
279 for (auto &s : stats.stat) {
282 stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
283 // TODO: damage values depending on properties
284 if (stats.Breath().Full()) {
285 constexpr double dps = 1.0 / 4.0;
288 if (stats.Thirst().Full()) {
289 constexpr double dps = 1.0 / 32.0;
292 if (stats.Hunger().Full()) {
293 constexpr double dps = 1.0 / 128.0;
298 void Creature::TickBrain(double dt) {
302 // do background stuff
306 for (auto &goal : goals) {
309 // if active goal can be interrupted, check priorities
310 if (goals.size() > 1 && goals[0]->Interruptible()) {
311 std::sort(goals.begin(), goals.end(), GoalCompare);
314 for (auto goal = goals.begin(); goal != goals.end();) {
315 if ((*goal)->Complete()) {
323 glm::dmat4 Creature::LocalTransform() noexcept {
324 const double half_size = size * 0.5;
325 const glm::dvec3 &pos = situation.Position();
326 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
327 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
328 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
330 * glm::scale(glm::dvec3(half_size, half_size, half_size));
333 void Creature::BuildVAO() {
335 vao.BindAttributes();
336 vao.EnableAttribute(0);
337 vao.EnableAttribute(1);
338 vao.EnableAttribute(2);
339 vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
340 vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
341 vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
342 vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
344 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
345 const float offset = 1.0f;
346 for (int surface = 0; surface < 6; ++surface) {
347 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
348 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
350 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
351 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
352 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
353 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
354 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
355 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
356 attrib[4 * surface + 0].texture.x = tex_u_begin;
357 attrib[4 * surface + 0].texture.y = 1.0f;
358 attrib[4 * surface + 0].texture.z = surface;
360 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
361 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
362 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
363 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
364 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
365 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
366 attrib[4 * surface + 1].texture.x = tex_u_end;
367 attrib[4 * surface + 1].texture.y = 1.0f;
368 attrib[4 * surface + 1].texture.z = surface;
370 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
371 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
372 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
373 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
374 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
375 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
376 attrib[4 * surface + 2].texture.x = tex_u_begin;
377 attrib[4 * surface + 2].texture.y = 0.0f;
378 attrib[4 * surface + 2].texture.z = surface;
380 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
381 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
382 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
383 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
384 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
385 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
386 attrib[4 * surface + 3].texture.x = tex_u_end;
387 attrib[4 * surface + 3].texture.y = 0.0f;
388 attrib[4 * surface + 3].texture.z = surface;
392 vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
394 auto element = vao.MapElements(GL_WRITE_ONLY);
395 for (int surface = 0; surface < 3; ++surface) {
396 element[6 * surface + 0] = 4 * surface + 0;
397 element[6 * surface + 1] = 4 * surface + 2;
398 element[6 * surface + 2] = 4 * surface + 1;
399 element[6 * surface + 3] = 4 * surface + 1;
400 element[6 * surface + 4] = 4 * surface + 2;
401 element[6 * surface + 5] = 4 * surface + 3;
403 for (int surface = 3; surface < 6; ++surface) {
404 element[6 * surface + 0] = 4 * surface + 0;
405 element[6 * surface + 1] = 4 * surface + 1;
406 element[6 * surface + 2] = 4 * surface + 2;
407 element[6 * surface + 3] = 4 * surface + 2;
408 element[6 * surface + 4] = 4 * surface + 1;
409 element[6 * surface + 5] = 4 * surface + 3;
415 void Creature::Draw(graphics::Viewport &viewport) {
417 vao.DrawTriangles(6 * 6);
421 void Spawn(Creature &c, world::Planet &p) {
423 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
424 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
426 // probe surrounding area for common resources
427 int start = p.SideLength() / 2 - 2;
429 std::map<int, double> yields;
430 for (int y = start; y < end; ++y) {
431 for (int x = start; x < end; ++x) {
432 const world::TileType &t = p.TypeAt(0, x, y);
433 for (auto yield : t.resources) {
434 yields[yield.resource] += yield.ubiquity;
440 for (auto e : yields) {
441 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
442 if (liquid < 0 || e.second > yields[liquid]) {
445 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
446 if (solid < 0 || e.second > yields[solid]) {
453 genome.properties.Strength() = { 2.0, 0.1 };
454 genome.properties.Stamina() = { 4.0, 0.1 };
455 genome.properties.Dexerty() = { 2.0, 0.1 };
456 genome.properties.Intelligence() = { 1.0, 0.1 };
457 genome.properties.Lifetime() = { 480.0, 60.0 };
458 genome.properties.Fertility() = { 0.5, 0.03 };
459 genome.properties.Mutability() = { 1.0, 0.1 };
460 genome.properties.OffspringMass() = { 0.3, 0.02 };
462 glm::dvec3 color_avg(0.0);
463 double color_divisor = 0.0;
465 if (p.HasAtmosphere()) {
466 c.AddMass(p.Atmosphere(), 0.01);
467 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
468 color_divisor += 0.1;
471 c.AddMass(liquid, 0.3);
472 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
473 color_divisor += 0.5;
476 c.AddMass(solid, 0.1);
477 color_avg += c.GetSimulation().Resources()[solid].base_color;
478 color_divisor += 1.0;
481 if (color_divisor > 0.001) {
482 color_avg /= color_divisor;
484 glm::dvec3 hsl = rgb2hsl(color_avg);
485 genome.base_hue = { hsl.x, 0.01 };
486 genome.base_saturation = { hsl.y, 0.01 };
487 genome.base_lightness = { hsl.z, 0.01 };
492 void Genome::Configure(Creature &c) const {
493 c.GetGenome() = *this;
495 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
497 c.GetProperties() = Instantiate(properties, random);
499 // TODO: derive stats from properties
500 c.GetStats().Damage().gain = (-1.0 / 100.0);
501 c.GetStats().Breath().gain = (1.0 / 5.0);
502 c.GetStats().Thirst().gain = (1.0 / 60.0);
503 c.GetStats().Hunger().gain = (1.0 / 200.0);
504 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
505 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
506 c.GetStats().Boredom().gain = (1.0 / 300.0);
508 glm::dvec3 base_color(
509 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
510 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
511 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
513 glm::dvec3 highlight_color(
514 std::fmod(base_color.x + 0.5, 1.0),
518 c.BaseColor(hsl2rgb(base_color));
519 c.HighlightColor(hsl2rgb(highlight_color));
520 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
521 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
525 void Split(Creature &c) {
526 Creature *a = new Creature(c.GetSimulation());
527 const Situation &s = c.GetSituation();
528 a->Name(c.GetSimulation().Assets().name.Sequential());
529 c.GetGenome().Configure(*a);
530 for (const auto &cmp : c.GetComposition()) {
531 a->AddMass(cmp.resource, cmp.value * 0.5);
533 s.GetPlanet().AddCreature(a);
534 // TODO: duplicate situation somehow
535 a->GetSituation().SetPlanetSurface(
536 s.GetPlanet(), s.Surface(),
537 s.Position() + glm::dvec3(0.0, a->Size() + 0.1, 0.0));
539 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
540 << a->Name() << " was born" << std::endl;
542 Creature *b = new Creature(c.GetSimulation());
543 b->Name(c.GetSimulation().Assets().name.Sequential());
544 c.GetGenome().Configure(*b);
545 for (const auto &cmp : c.GetComposition()) {
546 b->AddMass(cmp.resource, cmp.value * 0.5);
548 s.GetPlanet().AddCreature(b);
549 b->GetSituation().SetPlanetSurface(
550 s.GetPlanet(), s.Surface(),
551 s.Position() + glm::dvec3(0.0, b->Size() - 0.1, 0.0));
553 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
554 << b->Name() << " was born" << std::endl;
560 Memory::Memory(Creature &c)
567 void Memory::Tick(double dt) {
568 Situation &s = c.GetSituation();
570 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
574 void Memory::TrackStay(const Location &l, double t) {
575 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
576 auto entry = known_types.find(type.id);
577 if (entry != known_types.end()) {
578 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
580 if (entry->second.time_spent > c.Age() * 0.25) {
581 // the place is very familiar
582 c.GetStats().Boredom().Add(-0.2);
585 c.GetStats().Boredom().Add(-0.1);
588 entry->second.last_been = c.GetSimulation().Time();
589 entry->second.last_loc = l;
590 entry->second.time_spent += t;
592 known_types.emplace(type.id, Stay{
593 c.GetSimulation().Time(),
595 c.GetSimulation().Time(),
599 // completely new place, interesting
600 // TODO: scale by personality trait
601 c.GetStats().Boredom().Add(-0.25);
606 NameGenerator::NameGenerator()
610 NameGenerator::~NameGenerator() {
613 std::string NameGenerator::Sequential() {
614 std::stringstream ss;
615 ss << "Blob " << ++counter;
620 Situation::Situation()
622 , state(glm::dvec3(0.0), glm::dvec3(0.0))
627 Situation::~Situation() {
630 bool Situation::OnPlanet() const noexcept {
631 return type == PLANET_SURFACE;
634 bool Situation::OnSurface() const noexcept {
635 return type == PLANET_SURFACE;
638 bool Situation::OnTile() const noexcept {
639 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
640 return type == PLANET_SURFACE
641 && t.x >= 0 && t.x < planet->SideLength()
642 && t.y >= 0 && t.y < planet->SideLength();
645 glm::ivec2 Situation::SurfacePosition() const noexcept {
646 return planet->SurfacePosition(surface, state.pos);
649 world::Tile &Situation::GetTile() const noexcept {
650 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
651 return planet->TileAt(surface, t.x, t.y);
654 const world::TileType &Situation::GetTileType() const noexcept {
655 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
656 return planet->TypeAt(surface, t.x, t.y);
659 void Situation::Move(const glm::dvec3 &dp) noexcept {
662 // enforce ground constraint
664 state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
666 state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
671 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
672 type = PLANET_SURFACE;
679 Steering::Steering(const Creature &c)
693 Steering::~Steering() {
696 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
698 min_dist = min_distance;
699 max_look = max_lookaround;
702 void Steering::DontSeparate() noexcept {
706 void Steering::Halt() noexcept {
712 void Steering::Pass(const glm::dvec3 &t) noexcept {
719 void Steering::GoTo(const glm::dvec3 &t) noexcept {
726 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
727 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
728 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
729 glm::dvec3 result(0.0);
731 // TODO: off surface situation
732 glm::dvec3 repulse(0.0);
733 const Situation &s = c.GetSituation();
734 for (auto &other : s.GetPlanet().Creatures()) {
735 if (&*other == &c) continue;
736 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
737 if (length2(diff) > max_look * max_look) continue;
738 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
739 if (sep < min_dist) {
740 repulse += normalize(diff) * (1.0 - sep / min_dist);
743 SumForce(result, repulse, force);
746 SumForce(result, s.vel * -force, force);
749 glm::dvec3 diff = target - s.pos;
750 if (!allzero(diff)) {
751 SumForce(result, TargetVelocity(s, (normalize(diff) * speed), force), force);
755 glm::dvec3 diff = target - s.pos;
756 double dist = length(diff);
757 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
758 SumForce(result, TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force), force);
764 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
765 if (allzero(in) || anynan(in)) {
768 double cur = allzero(out) ? 0.0 : length(out);
769 double rem = max - cur;
773 double add = length(in);
775 // this method is off if in and out are in different
776 // directions, but gives okayish results
777 out += in * (1.0 / add);
785 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
786 return (vel - s.vel) * acc;