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