]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
random walks
[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(-1.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         math::GaloisLFSR &random = sim.Assets().random;
143         if (random.UNorm() < AdaptChance()) {
144                 // change color to be slightly more like resource
145                 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
146                 // solids affect base color, others highlight
147                 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
148                 double q = random.UInt(3); // hue, sat, or val
149                 double r = random.UInt(2); // mean or deviation
150                 math::Distribution *d = nullptr;
151                 double ref = 0.0;
152                 if (p == 0) {
153                         if (q == 0) {
154                                 d = &genome.base_hue;
155                                 ref = color.x;
156                         } else if (q == 1) {
157                                 d = &genome.base_saturation;
158                                 ref = color.y;
159                         } else {
160                                 d = &genome.base_lightness;
161                                 ref = color.z;
162                         }
163                 } else {
164                         if (q == 0) {
165                                 d = &genome.highlight_hue;
166                                 ref = color.x;
167                         } else if (q == 1) {
168                                 d = &genome.highlight_saturation;
169                                 ref = color.y;
170                         } else {
171                                 d = &genome.highlight_lightness;
172                                 ref = color.z;
173                         }
174                 }
175                 if (r == 0) {
176                         double diff = ref - d->Mean();
177                         if (q == 0) {
178                                 if (diff < -0.5) {
179                                         diff += 1.0;
180                                 } else if (diff > 0.5) {
181                                         diff -= 1.0;
182                                 }
183                                 // move ±15% of distance
184                                 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
185                         } else {
186                                 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
187                         }
188                 } else {
189                         // scale by ±15%, enforce bounds
190                         d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
191                 }
192         }
193 }
194
195 void Creature::DoWork(double amount) noexcept {
196         stats.Exhaustion().Add(amount / (Stamina() + 1.0));
197         // burn resources proportional to composition
198         // factor = 1/total * 1/efficiency * amount * -1
199         double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
200         // make a copy to total remains constant and
201         // no entries disappear during iteration
202         Composition comp(composition);
203         for (auto &cmp : comp) {
204                 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
205                 AddMass(cmp.resource, value);
206         }
207         // doing work improves strength a little
208         properties.Strength() += amount * 0.0001;
209 }
210
211 void Creature::Hurt(double amount) noexcept {
212         stats.Damage().Add(amount);
213         if (stats.Damage().Full()) {
214                 Die();
215         }
216 }
217
218 void Creature::Die() noexcept {
219         if (Dead()) return;
220
221         if (stats.Damage().Full()) {
222                 std::ostream &log = sim.Log() << name << " ";
223                 if (stats.Exhaustion().Full()) {
224                         log << "died of exhaustion";
225                 } else if (stats.Breath().Full()) {
226                         log << "suffocated";
227                 } else if (stats.Thirst().Full()) {
228                         log << "died of thirst";
229                 } else if (stats.Hunger().Full()) {
230                         log << "starved to death";
231                 } else {
232                         log << "succumed to wounds";
233                 }
234                 log << " at an age of " << ui::TimeString(Age())
235                         << " (" << ui::PercentageString(Age() / properties.Lifetime())
236                         << " of life expectancy of " << ui::TimeString(properties.Lifetime())
237                         << ")" << std::endl;
238         }
239
240         sim.SetDead(this);
241         death = sim.Time();
242         steering.Off();
243         if (on_death) {
244                 on_death(*this);
245         }
246         Remove();
247 }
248
249 bool Creature::Dead() const noexcept {
250         return death > birth;
251 }
252
253 void Creature::Remove() noexcept {
254         removable = true;
255 }
256
257 void Creature::Removed() noexcept {
258         bg_task.reset();
259         goals.clear();
260         memory.Erase();
261         KillVAO();
262 }
263
264 void Creature::AddParent(Creature &p) {
265         parents.push_back(&p);
266 }
267
268 double Creature::Age() const noexcept {
269         return sim.Time() - birth;
270 }
271
272 double Creature::AgeFactor(double peak) const noexcept {
273         // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
274         // goes negative below -0.5 and starts to rise again above 1.0
275         double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
276         // guarantee at least 1%
277         return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
278 }
279
280 double Creature::EnergyEfficiency() const noexcept {
281         return 0.25 * AgeFactor(0.05);
282 }
283
284 double Creature::ExhaustionFactor() const noexcept {
285         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
286 }
287
288 double Creature::FatigueFactor() const noexcept {
289         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
290 }
291
292 double Creature::Strength() const noexcept {
293         // TODO: replace all age factors with actual growth and decay
294         return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
295 }
296
297 double Creature::Stamina() const noexcept {
298         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
299 }
300
301 double Creature::Dexerty() const noexcept {
302         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
303 }
304
305 double Creature::Intelligence() const noexcept {
306         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
307 }
308
309 double Creature::Lifetime() const noexcept {
310         return properties.Lifetime();
311 }
312
313 double Creature::Fertility() const noexcept {
314         return properties.Fertility() * AgeFactor(0.25);
315 }
316
317 double Creature::Mutability() const noexcept {
318         return properties.Mutability();
319 }
320
321 double Creature::Adaptability() const noexcept {
322         return properties.Adaptability();
323 }
324
325 double Creature::OffspringMass() const noexcept {
326         return properties.OffspringMass();
327 }
328
329 double Creature::PerceptionRange() const noexcept {
330         return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
331 }
332
333 double Creature::PerceptionOmniRange() const noexcept {
334         return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
335 }
336
337 double Creature::PerceptionField() const noexcept {
338         // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
339         return 0.8 - (Dexerty() / (Dexerty() + 1));
340 }
341
342 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
343         const glm::dvec3 diff(p - situation.Position());
344         double omni_range = PerceptionOmniRange();
345         if (length2(diff) < omni_range * omni_range) return true;
346         double range = PerceptionRange();
347         if (length2(diff) > range * range) return false;
348         return dot(normalize(diff), situation.Heading()) > PerceptionField();
349 }
350
351 double Creature::OffspringChance() const noexcept {
352         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
353 }
354
355 double Creature::MutateChance() const noexcept {
356         return GetProperties().Mutability() * (1.0 / 3600.0);
357 }
358
359 double Creature::AdaptChance() const noexcept {
360         return GetProperties().Adaptability() * (1.0 / 120.0);
361 }
362
363 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
364         g->Enable();
365         if (goals.empty()) {
366                 g->SetForeground();
367         }
368         goals.emplace_back(std::move(g));
369 }
370
371 namespace {
372
373 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
374         return b->Urgency() < a->Urgency();
375 }
376
377 }
378
379 void Creature::Tick(double dt) {
380         TickState(dt);
381         TickStats(dt);
382         TickBrain(dt);
383 }
384
385 void Creature::TickState(double dt) {
386         steering.MaxSpeed(Dexerty());
387         steering.MaxForce(Strength());
388         Situation::State state(situation.GetState());
389         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
390         Situation::Derivative b(Step(a, dt * 0.5));
391         Situation::Derivative c(Step(b, dt * 0.5));
392         Situation::Derivative d(Step(c, dt));
393         Situation::Derivative f(
394                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
395                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
396         );
397         state.pos += f.vel * dt;
398         state.vel += f.acc * dt;
399         situation.EnforceConstraints(state);
400         if (length2(state.vel) > 0.000001) {
401                 glm::dvec3 nvel(normalize(state.vel));
402                 double ang = angle(nvel, state.dir);
403                 double turn_rate = PI * 0.75 * dt;
404                 if (ang < turn_rate) {
405                         state.dir = normalize(state.vel);
406                 } else if (std::abs(ang - PI) < 0.001) {
407                         state.dir = rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
408                 } else {
409                         state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
410                 }
411         }
412         situation.SetState(state);
413         // work is force times distance
414         DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
415 }
416
417 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
418         Situation::State s = situation.GetState();
419         s.pos += ds.vel * dt;
420         s.vel += ds.acc * dt;
421         glm::dvec3 force(steering.Force(s));
422         // gravity = antinormal * mass * Gm / r²
423         double elevation = situation.GetPlanet().DistanceAt(s.pos);
424         glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
425         force += glm::dvec3(
426                 -normal
427                 * Mass() * situation.GetPlanet().GravitationalParameter()
428                 / (elevation * elevation));
429         // if net force is applied and in contact with surface
430         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
431                 // apply friction = -|normal force| * tangential force * coefficient
432                 glm::dvec3 fn(normal * dot(force, normal));
433                 glm::dvec3 ft(force - fn);
434                 double u = 0.4;
435                 glm::dvec3 friction(-length(fn) * ft * u);
436                 force += friction;
437         }
438         return {
439                 s.vel,
440                 force / Mass()
441         };
442 }
443
444 void Creature::TickStats(double dt) {
445         for (auto &s : stats.stat) {
446                 s.Add(s.gain * dt);
447         }
448         // TODO: damage values depending on properties
449         if (stats.Breath().Full()) {
450                 constexpr double dps = 1.0 / 4.0;
451                 Hurt(dps * dt);
452         }
453         if (stats.Thirst().Full()) {
454                 constexpr double dps = 1.0 / 32.0;
455                 Hurt(dps * dt);
456         }
457         if (stats.Hunger().Full()) {
458                 constexpr double dps = 1.0 / 128.0;
459                 Hurt(dps * dt);
460         }
461         if (!situation.Moving()) {
462                 // double exhaustion recovery when standing still
463                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
464         }
465 }
466
467 void Creature::TickBrain(double dt) {
468         bg_task->Tick(dt);
469         bg_task->Action();
470         memory.Tick(dt);
471         // do background stuff
472         if (goals.empty()) {
473                 return;
474         }
475         for (auto &goal : goals) {
476                 goal->Tick(dt);
477         }
478         Goal *top = &*goals.front();
479         // if active goal can be interrupted, check priorities
480         if (goals.size() > 1 && goals[0]->Interruptible()) {
481                 std::sort(goals.begin(), goals.end(), GoalCompare);
482         }
483         if (&*goals.front() != top) {
484                 top->SetBackground();
485                 goals.front()->SetForeground();
486                 top = &*goals.front();
487         }
488         goals[0]->Action();
489         for (auto goal = goals.begin(); goal != goals.end();) {
490                 if ((*goal)->Complete()) {
491                         goals.erase(goal);
492                 } else {
493                         ++goal;
494                 }
495         }
496         if (&*goals.front() != top) {
497                 goals.front()->SetForeground();
498         }
499 }
500
501 math::AABB Creature::CollisionBox() const noexcept {
502         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
503 }
504
505 glm::dmat4 Creature::CollisionTransform() const noexcept {
506         const double half_size = size * 0.5;
507         const glm::dvec3 &pos = situation.Position();
508         glm::dmat3 orient;
509         orient[1] = situation.GetPlanet().NormalAt(pos);
510         orient[2] = situation.Heading();
511         if (std::abs(dot(orient[1], orient[2])) > 0.999) {
512                 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
513         }
514         orient[0] = normalize(cross(orient[1], orient[2]));
515         orient[2] = normalize(cross(orient[0], orient[1]));
516         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
517                 * glm::dmat4(orient)
518                 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
519 }
520
521 glm::dmat4 Creature::LocalTransform() noexcept {
522         const double half_size = size * 0.5;
523         return CollisionTransform()
524                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
525 }
526
527 void Creature::BuildVAO() {
528         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
529         vao->Bind();
530         vao->BindAttributes();
531         vao->EnableAttribute(0);
532         vao->EnableAttribute(1);
533         vao->EnableAttribute(2);
534         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
535         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
536         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
537         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
538         {
539                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
540                 const float offset = 1.0f;
541                 for (int surface = 0; surface < 6; ++surface) {
542                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
543                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
544
545                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
546                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
547                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
548                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
549                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
550                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
551                         attrib[4 * surface + 0].texture.x = tex_u_begin;
552                         attrib[4 * surface + 0].texture.y = 1.0f;
553                         attrib[4 * surface + 0].texture.z = surface;
554
555                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
556                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
557                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
558                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
559                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
560                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
561                         attrib[4 * surface + 1].texture.x = tex_u_end;
562                         attrib[4 * surface + 1].texture.y = 1.0f;
563                         attrib[4 * surface + 1].texture.z = surface;
564
565                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
566                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
567                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
568                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
569                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
570                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
571                         attrib[4 * surface + 2].texture.x = tex_u_begin;
572                         attrib[4 * surface + 2].texture.y = 0.0f;
573                         attrib[4 * surface + 2].texture.z = surface;
574
575                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
576                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
577                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
578                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
579                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
580                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
581                         attrib[4 * surface + 3].texture.x = tex_u_end;
582                         attrib[4 * surface + 3].texture.y = 0.0f;
583                         attrib[4 * surface + 3].texture.z = surface;
584                 }
585         }
586         vao->BindElements();
587         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
588         {
589                 auto element = vao->MapElements(GL_WRITE_ONLY);
590                 for (int surface = 0; surface < 3; ++surface) {
591                         element[6 * surface + 0] = 4 * surface + 0;
592                         element[6 * surface + 1] = 4 * surface + 2;
593                         element[6 * surface + 2] = 4 * surface + 1;
594                         element[6 * surface + 3] = 4 * surface + 1;
595                         element[6 * surface + 4] = 4 * surface + 2;
596                         element[6 * surface + 5] = 4 * surface + 3;
597                 }
598                 for (int surface = 3; surface < 6; ++surface) {
599                         element[6 * surface + 0] = 4 * surface + 0;
600                         element[6 * surface + 1] = 4 * surface + 1;
601                         element[6 * surface + 2] = 4 * surface + 2;
602                         element[6 * surface + 3] = 4 * surface + 2;
603                         element[6 * surface + 4] = 4 * surface + 1;
604                         element[6 * surface + 5] = 4 * surface + 3;
605                 }
606         }
607         vao->Unbind();
608 }
609
610 void Creature::KillVAO() {
611         vao.reset();
612 }
613
614 void Creature::Draw(graphics::Viewport &viewport) {
615         if (!vao) return;
616         vao->Bind();
617         vao->DrawTriangles(6 * 6);
618 }
619
620
621 void Spawn(Creature &c, world::Planet &p) {
622         p.AddCreature(&c);
623         c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
624         c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
625
626         // probe surrounding area for common resources
627         int start = p.SideLength() / 2 - 2;
628         int end = start + 5;
629         std::map<int, double> yields;
630         for (int y = start; y < end; ++y) {
631                 for (int x = start; x < end; ++x) {
632                         const world::TileType &t = p.TypeAt(0, x, y);
633                         for (auto yield : t.resources) {
634                                 yields[yield.resource] += yield.ubiquity;
635                         }
636                 }
637         }
638         int liquid = -1;
639         int solid = -1;
640         for (auto e : yields) {
641                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
642                         if (liquid < 0 || e.second > yields[liquid]) {
643                                 liquid = e.first;
644                         }
645                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
646                         if (solid < 0 || e.second > yields[solid]) {
647                                 solid = e.first;
648                         }
649                 }
650         }
651
652         Genome genome;
653         genome.properties.Strength() = { 2.0, 0.1 };
654         genome.properties.Stamina() = { 2.0, 0.1 };
655         genome.properties.Dexerty() = { 2.0, 0.1 };
656         genome.properties.Intelligence() = { 1.0, 0.1 };
657         genome.properties.Lifetime() = { 480.0, 60.0 };
658         genome.properties.Fertility() = { 0.5, 0.03 };
659         genome.properties.Mutability() = { 0.9, 0.1 };
660         genome.properties.Adaptability() = { 0.9, 0.1 };
661         genome.properties.OffspringMass() = { 0.3, 0.02 };
662
663         glm::dvec3 color_avg(0.0);
664         double color_divisor = 0.0;
665
666         if (p.HasAtmosphere()) {
667                 c.AddMass(p.Atmosphere(), 0.01);
668                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
669                 color_divisor += 0.1;
670         }
671         if (liquid > -1) {
672                 c.AddMass(liquid, 0.3);
673                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
674                 color_divisor += 0.5;
675         }
676         if (solid > -1) {
677                 c.AddMass(solid, 0.1);
678                 color_avg += c.GetSimulation().Resources()[solid].base_color;
679                 color_divisor += 1.0;
680         }
681
682         if (color_divisor > 0.001) {
683                 color_avg /= color_divisor;
684         }
685         glm::dvec3 hsl = rgb2hsl(color_avg);
686         genome.base_hue = { hsl.x, 0.01 };
687         genome.base_saturation = { hsl.y, 0.01 };
688         genome.base_lightness = { hsl.z, 0.01 };
689         // use opposite color as start highlight
690         genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
691         genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
692         genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
693
694         genome.Configure(c);
695 }
696
697 void Genome::Configure(Creature &c) const {
698         c.GetGenome() = *this;
699
700         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
701
702         c.GetProperties() = Instantiate(properties, random);
703
704         // TODO: derive stats from properties
705         c.GetStats().Damage().gain = (-1.0 / 100.0);
706         c.GetStats().Breath().gain = (1.0 / 5.0);
707         c.GetStats().Thirst().gain = (1.0 / 60.0);
708         c.GetStats().Hunger().gain = (1.0 / 200.0);
709         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
710         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
711         c.GetStats().Boredom().gain = (1.0 / 300.0);
712
713         glm::dvec3 base_color(
714                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
715                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
716                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
717         );
718         glm::dvec3 highlight_color(
719                 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
720                 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
721                 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
722         );
723         c.BaseColor(hsl2rgb(base_color));
724         c.HighlightColor(hsl2rgb(highlight_color));
725         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
726         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
727 }
728
729
730 void Split(Creature &c) {
731         Creature *a = new Creature(c.GetSimulation());
732         const Situation &s = c.GetSituation();
733         a->AddParent(c);
734         a->Name(c.GetSimulation().Assets().name.Sequential());
735         c.GetGenome().Configure(*a);
736         for (const auto &cmp : c.GetComposition()) {
737                 a->AddMass(cmp.resource, cmp.value * 0.5);
738         }
739         s.GetPlanet().AddCreature(a);
740         // TODO: duplicate situation somehow
741         a->GetSituation().SetPlanetSurface(
742                 s.GetPlanet(),
743                 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
744         a->BuildVAO();
745         c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
746
747         Creature *b = new Creature(c.GetSimulation());
748         b->AddParent(c);
749         b->Name(c.GetSimulation().Assets().name.Sequential());
750         c.GetGenome().Configure(*b);
751         for (const auto &cmp : c.GetComposition()) {
752                 b->AddMass(cmp.resource, cmp.value * 0.5);
753         }
754         s.GetPlanet().AddCreature(b);
755         b->GetSituation().SetPlanetSurface(
756                 s.GetPlanet(),
757                 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
758         b->BuildVAO();
759         c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
760
761         c.Die();
762 }
763
764
765 Memory::Memory(Creature &c)
766 : c(c) {
767 }
768
769 Memory::~Memory() {
770 }
771
772 void Memory::Erase() {
773         known_types.clear();
774 }
775
776 void Memory::Tick(double dt) {
777         Situation &s = c.GetSituation();
778         if (s.OnSurface()) {
779                 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
780         }
781 }
782
783 void Memory::TrackStay(const Location &l, double t) {
784         const world::TileType &type = l.planet->TileTypeAt(l.position);
785         auto entry = known_types.find(type.id);
786         if (entry != known_types.end()) {
787                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
788                         // "it's been ages"
789                         if (entry->second.time_spent > c.Age() * 0.25) {
790                                 // the place is very familiar
791                                 c.GetStats().Boredom().Add(-0.2);
792                         } else {
793                                 // infrequent stays
794                                 c.GetStats().Boredom().Add(-0.1);
795                         }
796                 }
797                 entry->second.last_been = c.GetSimulation().Time();
798                 entry->second.last_loc = l;
799                 entry->second.time_spent += t;
800         } else {
801                 known_types.emplace(type.id, Stay{
802                         c.GetSimulation().Time(),
803                         l,
804                         c.GetSimulation().Time(),
805                         l,
806                         t
807                 });
808                 // completely new place, interesting
809                 // TODO: scale by personality trait
810                 c.GetStats().Boredom().Add(-0.25);
811         }
812 }
813
814
815 NameGenerator::NameGenerator()
816 : counter(0) {
817 }
818
819 NameGenerator::~NameGenerator() {
820 }
821
822 std::string NameGenerator::Sequential() {
823         std::stringstream ss;
824         ss << "Blob " << ++counter;
825         return ss.str();
826 }
827
828
829 Situation::Situation()
830 : planet(nullptr)
831 , state(glm::dvec3(0.0), glm::dvec3(0.0))
832 , type(LOST) {
833 }
834
835 Situation::~Situation() {
836 }
837
838 bool Situation::OnPlanet() const noexcept {
839         return type == PLANET_SURFACE;
840 }
841
842 bool Situation::OnSurface() const noexcept {
843         return type == PLANET_SURFACE;
844 }
845
846 world::Tile &Situation::GetTile() const noexcept {
847         return planet->TileAt(state.pos);
848 }
849
850 const world::TileType &Situation::GetTileType() const noexcept {
851         return planet->TileTypeAt(state.pos);
852 }
853
854 void Situation::Move(const glm::dvec3 &dp) noexcept {
855         state.pos += dp;
856         EnforceConstraints(state);
857 }
858
859 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
860         state.vel += dv;
861         EnforceConstraints(state);
862 }
863
864 void Situation::EnforceConstraints(State &s) noexcept {
865         if (OnSurface()) {
866                 double r = GetPlanet().Radius();
867                 if (length2(s.pos) < r * r) {
868                         s.pos = normalize(s.pos) * r;
869                 }
870         }
871 }
872
873 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
874         type = PLANET_SURFACE;
875         planet = &p;
876         state.pos = pos;
877         EnforceConstraints(state);
878 }
879
880
881 Steering::Steering(const Creature &c)
882 : c(c)
883 , target(0.0)
884 , haste(0.0)
885 , max_force(1.0)
886 , max_speed(1.0)
887 , min_dist(0.0)
888 , max_look(0.0)
889 , separating(false)
890 , halting(true)
891 , seeking(false)
892 , arriving(false) {
893 }
894
895 Steering::~Steering() {
896 }
897
898 void Steering::Off() noexcept {
899         separating = false;
900         halting = false;
901         seeking = false;
902         arriving = false;
903 }
904
905 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
906         separating = true;
907         min_dist = min_distance;
908         max_look = max_lookaround;
909 }
910
911 void Steering::DontSeparate() noexcept {
912         separating = false;
913 }
914
915 void Steering::ResumeSeparate() noexcept {
916         separating = true;
917 }
918
919 void Steering::Halt() noexcept {
920         halting = true;
921         seeking = false;
922         arriving = false;
923 }
924
925 void Steering::Pass(const glm::dvec3 &t) noexcept {
926         target = t;
927         halting = false;
928         seeking = true;
929         arriving = false;
930 }
931
932 void Steering::GoTo(const glm::dvec3 &t) noexcept {
933         target = t;
934         halting = false;
935         seeking = false;
936         arriving = true;
937 }
938
939 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
940         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
941         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
942         glm::dvec3 result(0.0);
943         if (separating) {
944                 // TODO: off surface situation
945                 glm::dvec3 repulse(0.0);
946                 const Situation &s = c.GetSituation();
947                 for (auto &other : s.GetPlanet().Creatures()) {
948                         if (&*other == &c) continue;
949                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
950                         if (length2(diff) > max_look * max_look) continue;
951                         if (!c.PerceptionTest(other->GetSituation().Position())) continue;
952                         double sep = glm::clamp(length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
953                         repulse += normalize(diff) * (1.0 - sep / min_dist) * force;
954                 }
955                 result += repulse;
956         }
957         if (halting) {
958                 // break twice as hard
959                 result += -2.0 * s.vel * force;
960         }
961         if (seeking) {
962                 glm::dvec3 diff = target - s.pos;
963                 if (!allzero(diff)) {
964                         result += TargetVelocity(s, (normalize(diff) * speed), force);
965                 }
966         }
967         if (arriving) {
968                 glm::dvec3 diff = target - s.pos;
969                 double dist = length(diff);
970                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
971                         result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
972                 }
973         }
974         if (length2(result) > max_force * max_force) {
975                 result = normalize(result) * max_force;
976         }
977         return result;
978 }
979
980 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
981         return (vel - s.vel) * acc;
982 }
983
984 }
985 }