]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
lose weight through exercise
[blobs.git] / src / creature / creature.cpp
1 #include "Composition.hpp"
2 #include "Creature.hpp"
3 #include "Genome.hpp"
4 #include "Memory.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
8
9 #include "BlobBackgroundTask.hpp"
10 #include "Goal.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../ui/string.hpp"
15 #include "../world/Body.hpp"
16 #include "../world/Planet.hpp"
17 #include "../world/Simulation.hpp"
18 #include "../world/TileType.hpp"
19
20 #include <algorithm>
21 #include <sstream>
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
24
25 #include <iostream>
26 #include <glm/gtx/io.hpp>
27
28
29 namespace blobs {
30 namespace creature {
31
32 Composition::Composition()
33 : components()
34 , total_mass(0.0) {
35 }
36
37 Composition::~Composition() {
38 }
39
40 namespace {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42         return b.value < a.value;
43 }
44 }
45
46 void Composition::Add(int res, double amount) {
47         bool found = false;
48         for (auto c = components.begin(); c != components.end(); ++c) {
49                 if (c->resource == res) {
50                         c->value += amount;
51                         if (c->value <= 0.0) {
52                                 components.erase(c);
53                         }
54                         found = true;
55                         break;
56                 }
57         }
58         if (!found && amount > 0.0) {
59                 components.emplace_back(res, amount);
60         }
61         std::sort(components.begin(), components.end(), CompositionCompare);
62         total_mass += amount;
63 }
64
65 bool Composition::Has(int res) const noexcept {
66         for (auto &c : components) {
67                 if (c.resource == res) {
68                         return true;
69                 }
70         }
71         return false;
72 }
73
74 double Composition::Get(int res) const noexcept {
75         for (auto &c : components) {
76                 if (c.resource == res) {
77                         return c.value;
78                 }
79         }
80         return 0.0;
81 }
82
83
84 Creature::Creature(world::Simulation &sim)
85 : sim(sim)
86 , name()
87 , genome()
88 , properties()
89 , composition()
90 , base_color(1.0)
91 , highlight_color(0.0, 0.0, 0.0, 1.0)
92 , mass(1.0)
93 , size(1.0)
94 , birth(sim.Time())
95 , death(0.0)
96 , on_death()
97 , removable(false)
98 , parents()
99 , stats()
100 , memory(*this)
101 , bg_task()
102 , goals()
103 , situation()
104 , steering(*this)
105 , vao() {
106         sim.SetAlive(this);
107         // all creatures avoid each other for now
108         steering.Separate(0.1, 1.5);
109 }
110
111 Creature::~Creature() {
112 }
113
114 void Creature::AddMass(int res, double amount) {
115         composition.Add(res, amount);
116         double nonsolid = 0.0;
117         double volume = 0.0;
118         for (const auto &c : composition) {
119                 volume += c.value / sim.Assets().data.resources[c.resource].density;
120                 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
121                         nonsolid += c.value;
122                 }
123         }
124         Mass(composition.TotalMass());
125         Size(std::cbrt(volume));
126         highlight_color.a = nonsolid / composition.TotalMass();
127 }
128
129 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
130         highlight_color = glm::dvec4(c, highlight_color.a);
131 }
132
133 void Creature::Ingest(int res, double amount) noexcept {
134         // TODO: check foreign materials
135         if (sim.Resources()[res].state == world::Resource::SOLID) {
136                 // 15% of solids stays in body
137                 AddMass(res, amount * 0.15);
138         } else {
139                 // 10% of fluids stays in body
140                 AddMass(res, amount * 0.05);
141         }
142 }
143
144 void Creature::DoWork(double amount) noexcept {
145         stats.Exhaustion().Add(amount / Stamina());
146         // burn resources proportional to composition
147         // factor = 1/total * 1/efficiency * amount * -1
148         double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
149         // make a copy to total remains constant and
150         // no entries disappear during iteration
151         Composition comp(composition);
152         for (auto &cmp : comp) {
153                 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
154                 AddMass(cmp.resource, value);
155         }
156 }
157
158 void Creature::Hurt(double amount) noexcept {
159         stats.Damage().Add(amount);
160         if (stats.Damage().Full()) {
161                 std::cout << "[" << ui::TimeString(sim.Time()) << "] " << name << " ";
162                 if (stats.Exhaustion().Full()) {
163                         std::cout << "died of exhaustion";
164                 } else if (stats.Breath().Full()) {
165                         std::cout << "suffocated";
166                 } else if (stats.Thirst().Full()) {
167                         std::cout << "died of thirst";
168                 } else if (stats.Hunger().Full()) {
169                         std::cout << "starved to death";
170                 } else {
171                         std::cout << "succumed to wounds";
172                 }
173                 std::cout << " at an age of " << ui::TimeString(Age())
174                         << " (" << ui::PercentageString(Age() / properties.Lifetime())
175                         << "% of life expectancy of " << ui::TimeString(properties.Lifetime())
176                         << ")" << std::endl;
177                 Die();
178         }
179 }
180
181 void Creature::Die() noexcept {
182         sim.SetDead(this);
183         death = sim.Time();
184         steering.Halt();
185         if (on_death) {
186                 on_death(*this);
187         }
188         Remove();
189 }
190
191 void Creature::Remove() noexcept {
192         removable = true;
193 }
194
195 void Creature::Removed() noexcept {
196         bg_task.reset();
197         goals.clear();
198         memory.Erase();
199         KillVAO();
200 }
201
202 void Creature::AddParent(Creature &p) {
203         parents.push_back(&p);
204 }
205
206 double Creature::Age() const noexcept {
207         return sim.Time() - birth;
208 }
209
210 double Creature::AgeFactor(double peak) const noexcept {
211         // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
212         // goes negative below -0.5 and starts to rise again above 1.0
213         double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
214         // guarantee at least 1%
215         return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
216 }
217
218 double Creature::EnergyEfficiency() const noexcept {
219         return 0.25 * AgeFactor(0.05);
220 }
221
222 double Creature::ExhaustionFactor() const noexcept {
223         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
224 }
225
226 double Creature::FatigueFactor() const noexcept {
227         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
228 }
229
230 double Creature::Strength() const noexcept {
231         // TODO: replace all age factors with actual growth and decay
232         return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
233 }
234
235 double Creature::Stamina() const noexcept {
236         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
237 }
238
239 double Creature::Dexerty() const noexcept {
240         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
241 }
242
243 double Creature::Intelligence() const noexcept {
244         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
245 }
246
247 double Creature::Lifetime() const noexcept {
248         return properties.Lifetime();
249 }
250
251 double Creature::Fertility() const noexcept {
252         return properties.Fertility() * AgeFactor(0.25);
253 }
254
255 double Creature::Mutability() const noexcept {
256         return properties.Mutability();
257 }
258
259 double Creature::OffspringMass() const noexcept {
260         return properties.OffspringMass();
261 }
262
263 double Creature::OffspringChance() const noexcept {
264         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
265 }
266
267 double Creature::MutateChance() const noexcept {
268         return GetProperties().Mutability() * (1.0 / 3600.0);
269 }
270
271 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
272         g->Enable();
273         goals.emplace_back(std::move(g));
274 }
275
276 namespace {
277
278 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
279         return b->Urgency() < a->Urgency();
280 }
281
282 }
283
284 void Creature::Tick(double dt) {
285         TickState(dt);
286         TickStats(dt);
287         TickBrain(dt);
288 }
289
290 void Creature::TickState(double dt) {
291         steering.MaxSpeed(Dexerty());
292         steering.MaxForce(Strength());
293         Situation::State state(situation.GetState());
294         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
295         Situation::Derivative b(Step(a, dt * 0.5));
296         Situation::Derivative c(Step(b, dt * 0.5));
297         Situation::Derivative d(Step(c, dt));
298         Situation::Derivative f(
299                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
300                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
301         );
302         state.pos += f.vel * dt;
303         state.vel += f.acc * dt;
304         situation.EnforceConstraints(state);
305         if (length2(state.vel) > 0.000001) {
306                 glm::dvec3 nvel(normalize(state.vel));
307                 double ang = angle(nvel, state.dir);
308                 double turn_rate = PI * 0.75 * dt;
309                 if (ang < turn_rate) {
310                         state.dir = normalize(state.vel);
311                 } else if (std::abs(ang - PI) < 0.001) {
312                         state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
313                 } else {
314                         state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
315                 }
316         }
317         situation.SetState(state);
318         // work is force times distance
319         DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
320 }
321
322 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
323         Situation::State s = situation.GetState();
324         s.pos += ds.vel * dt;
325         s.vel += ds.acc * dt;
326         glm::dvec3 force(steering.Force(s));
327         // gravity = antinormal * mass * Gm / r²
328         double elevation = s.pos[(situation.Surface() + 2) % 3];
329         glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
330         force += glm::dvec3(
331                 -normal
332                 * Mass() * situation.GetPlanet().GravitationalParameter()
333                 / (elevation * elevation));
334         // if net force is applied and in contact with surface
335         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
336                 // apply friction = -|normal force| * tangential force * coefficient
337                 glm::dvec3 fn(normal * dot(force, normal));
338                 glm::dvec3 ft(force - fn);
339                 double u = 0.4;
340                 glm::dvec3 friction(-length(fn) * ft * u);
341                 force += friction;
342         }
343         return {
344                 s.vel,
345                 force / Mass()
346         };
347 }
348
349 void Creature::TickStats(double dt) {
350         for (auto &s : stats.stat) {
351                 s.Add(s.gain * dt);
352         }
353         stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
354         // TODO: damage values depending on properties
355         if (stats.Breath().Full()) {
356                 constexpr double dps = 1.0 / 4.0;
357                 Hurt(dps * dt);
358         }
359         if (stats.Thirst().Full()) {
360                 constexpr double dps = 1.0 / 32.0;
361                 Hurt(dps * dt);
362         }
363         if (stats.Hunger().Full()) {
364                 constexpr double dps = 1.0 / 128.0;
365                 Hurt(dps * dt);
366         }
367         if (!situation.Moving()) {
368                 // double exhaustion recovery when standing still
369                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
370         }
371 }
372
373 void Creature::TickBrain(double dt) {
374         bg_task->Tick(dt);
375         bg_task->Action();
376         memory.Tick(dt);
377         // do background stuff
378         if (goals.empty()) {
379                 return;
380         }
381         for (auto &goal : goals) {
382                 goal->Tick(dt);
383         }
384         // if active goal can be interrupted, check priorities
385         if (goals.size() > 1 && goals[0]->Interruptible()) {
386                 std::sort(goals.begin(), goals.end(), GoalCompare);
387         }
388         goals[0]->Action();
389         for (auto goal = goals.begin(); goal != goals.end();) {
390                 if ((*goal)->Complete()) {
391                         goals.erase(goal);
392                 } else {
393                         ++goal;
394                 }
395         }
396 }
397
398 math::AABB Creature::CollisionBox() const noexcept {
399         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
400 }
401
402 glm::dmat4 Creature::CollisionTransform() const noexcept {
403         const double half_size = size * 0.5;
404         const glm::dvec3 &pos = situation.Position();
405         const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
406         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
407                 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
408                 * glm::dmat4(srf);
409 }
410
411 glm::dmat4 Creature::LocalTransform() noexcept {
412         const double half_size = size * 0.5;
413         return CollisionTransform()
414                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
415 }
416
417 void Creature::BuildVAO() {
418         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
419         vao->Bind();
420         vao->BindAttributes();
421         vao->EnableAttribute(0);
422         vao->EnableAttribute(1);
423         vao->EnableAttribute(2);
424         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
425         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
426         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
427         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
428         {
429                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
430                 const float offset = 1.0f;
431                 for (int surface = 0; surface < 6; ++surface) {
432                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
433                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
434
435                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
436                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
437                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
438                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
439                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
440                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
441                         attrib[4 * surface + 0].texture.x = tex_u_begin;
442                         attrib[4 * surface + 0].texture.y = 1.0f;
443                         attrib[4 * surface + 0].texture.z = surface;
444
445                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
446                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
447                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
448                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
449                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
450                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
451                         attrib[4 * surface + 1].texture.x = tex_u_end;
452                         attrib[4 * surface + 1].texture.y = 1.0f;
453                         attrib[4 * surface + 1].texture.z = surface;
454
455                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
456                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
457                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
458                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
459                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
460                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
461                         attrib[4 * surface + 2].texture.x = tex_u_begin;
462                         attrib[4 * surface + 2].texture.y = 0.0f;
463                         attrib[4 * surface + 2].texture.z = surface;
464
465                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
466                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
467                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
468                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
469                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
470                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
471                         attrib[4 * surface + 3].texture.x = tex_u_end;
472                         attrib[4 * surface + 3].texture.y = 0.0f;
473                         attrib[4 * surface + 3].texture.z = surface;
474                 }
475         }
476         vao->BindElements();
477         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
478         {
479                 auto element = vao->MapElements(GL_WRITE_ONLY);
480                 for (int surface = 0; surface < 3; ++surface) {
481                         element[6 * surface + 0] = 4 * surface + 0;
482                         element[6 * surface + 1] = 4 * surface + 2;
483                         element[6 * surface + 2] = 4 * surface + 1;
484                         element[6 * surface + 3] = 4 * surface + 1;
485                         element[6 * surface + 4] = 4 * surface + 2;
486                         element[6 * surface + 5] = 4 * surface + 3;
487                 }
488                 for (int surface = 3; surface < 6; ++surface) {
489                         element[6 * surface + 0] = 4 * surface + 0;
490                         element[6 * surface + 1] = 4 * surface + 1;
491                         element[6 * surface + 2] = 4 * surface + 2;
492                         element[6 * surface + 3] = 4 * surface + 2;
493                         element[6 * surface + 4] = 4 * surface + 1;
494                         element[6 * surface + 5] = 4 * surface + 3;
495                 }
496         }
497         vao->Unbind();
498 }
499
500 void Creature::KillVAO() {
501         vao.reset();
502 }
503
504 void Creature::Draw(graphics::Viewport &viewport) {
505         if (!vao) return;
506         vao->Bind();
507         vao->DrawTriangles(6 * 6);
508 }
509
510
511 void Spawn(Creature &c, world::Planet &p) {
512         p.AddCreature(&c);
513         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
514         c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
515
516         // probe surrounding area for common resources
517         int start = p.SideLength() / 2 - 2;
518         int end = start + 5;
519         std::map<int, double> yields;
520         for (int y = start; y < end; ++y) {
521                 for (int x = start; x < end; ++x) {
522                         const world::TileType &t = p.TypeAt(0, x, y);
523                         for (auto yield : t.resources) {
524                                 yields[yield.resource] += yield.ubiquity;
525                         }
526                 }
527         }
528         int liquid = -1;
529         int solid = -1;
530         for (auto e : yields) {
531                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
532                         if (liquid < 0 || e.second > yields[liquid]) {
533                                 liquid = e.first;
534                         }
535                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
536                         if (solid < 0 || e.second > yields[solid]) {
537                                 solid = e.first;
538                         }
539                 }
540         }
541
542         Genome genome;
543         genome.properties.Strength() = { 2.0, 0.1 };
544         genome.properties.Stamina() = { 2.0, 0.1 };
545         genome.properties.Dexerty() = { 2.0, 0.1 };
546         genome.properties.Intelligence() = { 1.0, 0.1 };
547         genome.properties.Lifetime() = { 480.0, 60.0 };
548         genome.properties.Fertility() = { 0.5, 0.03 };
549         genome.properties.Mutability() = { 1.0, 0.1 };
550         genome.properties.OffspringMass() = { 0.3, 0.02 };
551
552         glm::dvec3 color_avg(0.0);
553         double color_divisor = 0.0;
554
555         if (p.HasAtmosphere()) {
556                 c.AddMass(p.Atmosphere(), 0.01);
557                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
558                 color_divisor += 0.1;
559         }
560         if (liquid > -1) {
561                 c.AddMass(liquid, 0.3);
562                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
563                 color_divisor += 0.5;
564         }
565         if (solid > -1) {
566                 c.AddMass(solid, 0.1);
567                 color_avg += c.GetSimulation().Resources()[solid].base_color;
568                 color_divisor += 1.0;
569         }
570
571         if (color_divisor > 0.001) {
572                 color_avg /= color_divisor;
573         }
574         glm::dvec3 hsl = rgb2hsl(color_avg);
575         genome.base_hue = { hsl.x, 0.01 };
576         genome.base_saturation = { hsl.y, 0.01 };
577         genome.base_lightness = { hsl.z, 0.01 };
578
579         genome.Configure(c);
580 }
581
582 void Genome::Configure(Creature &c) const {
583         c.GetGenome() = *this;
584
585         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
586
587         c.GetProperties() = Instantiate(properties, random);
588
589         // TODO: derive stats from properties
590         c.GetStats().Damage().gain = (-1.0 / 100.0);
591         c.GetStats().Breath().gain = (1.0 / 5.0);
592         c.GetStats().Thirst().gain = (1.0 / 60.0);
593         c.GetStats().Hunger().gain = (1.0 / 200.0);
594         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
595         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
596         c.GetStats().Boredom().gain = (1.0 / 300.0);
597
598         glm::dvec3 base_color(
599                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
600                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
601                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
602         );
603         glm::dvec3 highlight_color(
604                 std::fmod(base_color.x + 0.5, 1.0),
605                 1.0 - base_color.y,
606                 1.0 - base_color.z
607         );
608         c.BaseColor(hsl2rgb(base_color));
609         c.HighlightColor(hsl2rgb(highlight_color));
610         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
611         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
612 }
613
614
615 void Split(Creature &c) {
616         Creature *a = new Creature(c.GetSimulation());
617         const Situation &s = c.GetSituation();
618         a->AddParent(c);
619         a->Name(c.GetSimulation().Assets().name.Sequential());
620         c.GetGenome().Configure(*a);
621         for (const auto &cmp : c.GetComposition()) {
622                 a->AddMass(cmp.resource, cmp.value * 0.5);
623         }
624         s.GetPlanet().AddCreature(a);
625         // TODO: duplicate situation somehow
626         a->GetSituation().SetPlanetSurface(
627                 s.GetPlanet(), s.Surface(),
628                 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
629         a->BuildVAO();
630         std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
631                 << a->Name() << " was born" << std::endl;
632
633         Creature *b = new Creature(c.GetSimulation());
634         b->AddParent(c);
635         b->Name(c.GetSimulation().Assets().name.Sequential());
636         c.GetGenome().Configure(*b);
637         for (const auto &cmp : c.GetComposition()) {
638                 b->AddMass(cmp.resource, cmp.value * 0.5);
639         }
640         s.GetPlanet().AddCreature(b);
641         b->GetSituation().SetPlanetSurface(
642                 s.GetPlanet(), s.Surface(),
643                 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
644         b->BuildVAO();
645         std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
646                 << b->Name() << " was born" << std::endl;
647
648         c.Die();
649 }
650
651
652 Memory::Memory(Creature &c)
653 : c(c) {
654 }
655
656 Memory::~Memory() {
657 }
658
659 void Memory::Erase() {
660         known_types.clear();
661 }
662
663 void Memory::Tick(double dt) {
664         Situation &s = c.GetSituation();
665         if (s.OnTile()) {
666                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
667         }
668 }
669
670 void Memory::TrackStay(const Location &l, double t) {
671         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
672         auto entry = known_types.find(type.id);
673         if (entry != known_types.end()) {
674                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
675                         // "it's been ages"
676                         if (entry->second.time_spent > c.Age() * 0.25) {
677                                 // the place is very familiar
678                                 c.GetStats().Boredom().Add(-0.2);
679                         } else {
680                                 // infrequent stays
681                                 c.GetStats().Boredom().Add(-0.1);
682                         }
683                 }
684                 entry->second.last_been = c.GetSimulation().Time();
685                 entry->second.last_loc = l;
686                 entry->second.time_spent += t;
687         } else {
688                 known_types.emplace(type.id, Stay{
689                         c.GetSimulation().Time(),
690                         l,
691                         c.GetSimulation().Time(),
692                         l,
693                         t
694                 });
695                 // completely new place, interesting
696                 // TODO: scale by personality trait
697                 c.GetStats().Boredom().Add(-0.25);
698         }
699 }
700
701
702 NameGenerator::NameGenerator()
703 : counter(0) {
704 }
705
706 NameGenerator::~NameGenerator() {
707 }
708
709 std::string NameGenerator::Sequential() {
710         std::stringstream ss;
711         ss << "Blob " << ++counter;
712         return ss.str();
713 }
714
715
716 Situation::Situation()
717 : planet(nullptr)
718 , state(glm::dvec3(0.0), glm::dvec3(0.0))
719 , surface(0)
720 , type(LOST) {
721 }
722
723 Situation::~Situation() {
724 }
725
726 bool Situation::OnPlanet() const noexcept {
727         return type == PLANET_SURFACE;
728 }
729
730 bool Situation::OnSurface() const noexcept {
731         return type == PLANET_SURFACE;
732 }
733
734 bool Situation::OnTile() const noexcept {
735         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
736         return type == PLANET_SURFACE
737                 && t.x >= 0 && t.x < planet->SideLength()
738                 && t.y >= 0 && t.y < planet->SideLength();
739 }
740
741 glm::ivec2 Situation::SurfacePosition() const noexcept {
742         return planet->SurfacePosition(surface, state.pos);
743 }
744
745 world::Tile &Situation::GetTile() const noexcept {
746         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
747         return planet->TileAt(surface, t.x, t.y);
748 }
749
750 const world::TileType &Situation::GetTileType() const noexcept {
751         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
752         return planet->TypeAt(surface, t.x, t.y);
753 }
754
755 void Situation::Move(const glm::dvec3 &dp) noexcept {
756         state.pos += dp;
757         EnforceConstraints(state);
758 }
759
760 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
761         state.vel += dv;
762         EnforceConstraints(state);
763 }
764
765 void Situation::EnforceConstraints(State &s) noexcept {
766         if (OnSurface()) {
767                 if (Surface() < 3) {
768                         if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
769                                 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
770                                 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
771                         }
772                 } else {
773                         if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
774                                 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
775                                 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
776                         }
777                 }
778         }
779 }
780
781 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
782         type = PLANET_SURFACE;
783         planet = &p;
784         surface = srf;
785         state.pos = pos;
786         EnforceConstraints(state);
787 }
788
789
790 Steering::Steering(const Creature &c)
791 : c(c)
792 , target(0.0)
793 , haste(0.0)
794 , max_force(1.0)
795 , max_speed(1.0)
796 , min_dist(0.0)
797 , max_look(0.0)
798 , separating(false)
799 , halting(true)
800 , seeking(false)
801 , arriving(false) {
802 }
803
804 Steering::~Steering() {
805 }
806
807 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
808         separating = true;
809         min_dist = min_distance;
810         max_look = max_lookaround;
811 }
812
813 void Steering::DontSeparate() noexcept {
814         separating = false;
815 }
816
817 void Steering::ResumeSeparate() noexcept {
818         separating = true;
819 }
820
821 void Steering::Halt() noexcept {
822         halting = true;
823         seeking = false;
824         arriving = false;
825 }
826
827 void Steering::Pass(const glm::dvec3 &t) noexcept {
828         target = t;
829         halting = false;
830         seeking = true;
831         arriving = false;
832 }
833
834 void Steering::GoTo(const glm::dvec3 &t) noexcept {
835         target = t;
836         halting = false;
837         seeking = false;
838         arriving = true;
839 }
840
841 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
842         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
843         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
844         glm::dvec3 result(0.0);
845         if (separating) {
846                 // TODO: off surface situation
847                 glm::dvec3 repulse(0.0);
848                 const Situation &s = c.GetSituation();
849                 for (auto &other : s.GetPlanet().Creatures()) {
850                         if (&*other == &c) continue;
851                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
852                         if (length2(diff) > max_look * max_look) continue;
853                         double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
854                         if (sep < min_dist) {
855                                 repulse += normalize(diff) * (1.0 - sep / min_dist);
856                         }
857                 }
858                 SumForce(result, repulse, force);
859         }
860         if (halting) {
861                 // break twice as hard
862                 SumForce(result, s.vel * force * -2.0, force);
863         }
864         if (seeking) {
865                 glm::dvec3 diff = target - s.pos;
866                 if (!allzero(diff)) {
867                         SumForce(result, TargetVelocity(s, (normalize(diff) * speed), force), force);
868                 }
869         }
870         if (arriving) {
871                 glm::dvec3 diff = target - s.pos;
872                 double dist = length(diff);
873                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
874                         SumForce(result, TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force), force);
875                 }
876         }
877         return result;
878 }
879
880 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
881         if (allzero(in) || anynan(in)) {
882                 return false;
883         }
884         double cur = allzero(out) ? 0.0 : length(out);
885         double rem = max - cur;
886         if (rem < 0.0) {
887                 return true;
888         }
889         double add = length(in);
890         if (add > rem) {
891                 // this method is off if in and out are in different
892                 // directions, but gives okayish results
893                 out += in * (1.0 / add);
894                 return true;
895         } else {
896                 out += in;
897                 return false;
898         }
899 }
900
901 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
902         return (vel - s.vel) * acc;
903 }
904
905 }
906 }