]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
brake hard, not break hard
[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 Dead() ? death - birth : 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::StrengthFactor() const noexcept {
298         return Strength() / (Strength() + 1.0);
299 }
300
301 double Creature::Stamina() const noexcept {
302         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
303 }
304
305 double Creature::StaminaFactor() const noexcept {
306         return Stamina() / (Stamina() + 1.0);
307 }
308
309 double Creature::Dexerty() const noexcept {
310         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
311 }
312
313 double Creature::DexertyFactor() const noexcept {
314         return Dexerty() / (Dexerty() + 1.0);
315 }
316
317 double Creature::Intelligence() const noexcept {
318         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
319 }
320
321 double Creature::IntelligenceFactor() const noexcept {
322         return Intelligence() / (Intelligence() + 1.0);
323 }
324
325 double Creature::Lifetime() const noexcept {
326         return properties.Lifetime();
327 }
328
329 double Creature::Fertility() const noexcept {
330         return properties.Fertility() * AgeFactor(0.25);
331 }
332
333 double Creature::Mutability() const noexcept {
334         return properties.Mutability();
335 }
336
337 double Creature::Adaptability() const noexcept {
338         return properties.Adaptability();
339 }
340
341 double Creature::OffspringMass() const noexcept {
342         return properties.OffspringMass();
343 }
344
345 double Creature::PerceptionRange() const noexcept {
346         return 3.0 * DexertyFactor() + Size();
347 }
348
349 double Creature::PerceptionOmniRange() const noexcept {
350         return 0.5 * DexertyFactor() + Size();
351 }
352
353 double Creature::PerceptionField() const noexcept {
354         // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
355         return 0.8 - DexertyFactor();
356 }
357
358 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
359         const glm::dvec3 diff(p - situation.Position());
360         double omni_range = PerceptionOmniRange();
361         if (glm::length2(diff) < omni_range * omni_range) return true;
362         double range = PerceptionRange();
363         if (glm::length2(diff) > range * range) return false;
364         return glm::dot(glm::normalize(diff), situation.Heading()) > PerceptionField();
365 }
366
367 double Creature::OffspringChance() const noexcept {
368         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
369 }
370
371 double Creature::MutateChance() const noexcept {
372         return GetProperties().Mutability() * (1.0 / 3600.0);
373 }
374
375 double Creature::AdaptChance() const noexcept {
376         return GetProperties().Adaptability() * (1.0 / 120.0);
377 }
378
379 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
380         g->Enable();
381         if (goals.empty()) {
382                 g->SetForeground();
383         }
384         goals.emplace_back(std::move(g));
385 }
386
387 namespace {
388
389 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
390         return b->Urgency() < a->Urgency();
391 }
392
393 }
394
395 void Creature::Tick(double dt) {
396         TickState(dt);
397         TickStats(dt);
398         TickBrain(dt);
399 }
400
401 void Creature::TickState(double dt) {
402         steering.MaxSpeed(Dexerty());
403         steering.MaxForce(Strength());
404         Situation::State state(situation.GetState());
405         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
406         Situation::Derivative b(Step(a, dt * 0.5));
407         Situation::Derivative c(Step(b, dt * 0.5));
408         Situation::Derivative d(Step(c, dt));
409         Situation::Derivative f(
410                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
411                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
412         );
413         state.pos += f.vel * dt;
414         state.vel += f.acc * dt;
415         situation.EnforceConstraints(state);
416         if (glm::length2(state.vel) > 0.000001) {
417                 glm::dvec3 nvel(glm::normalize(state.vel));
418                 double ang = glm::angle(nvel, state.dir);
419                 double turn_rate = PI * 0.75 * dt;
420                 if (ang < turn_rate) {
421                         state.dir = glm::normalize(state.vel);
422                 } else if (std::abs(ang - PI) < 0.001) {
423                         state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
424                 } else {
425                         state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
426                 }
427         }
428         situation.SetState(state);
429         // work is force times distance
430         DoWork(glm::length(f.acc) * Mass() * glm::length(f.vel) * dt);
431 }
432
433 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
434         Situation::State s = situation.GetState();
435         s.pos += ds.vel * dt;
436         s.vel += ds.acc * dt;
437         glm::dvec3 force(steering.Force(s));
438         // gravity = antinormal * mass * Gm / r²
439         double elevation = situation.GetPlanet().DistanceAt(s.pos);
440         glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
441         force += glm::dvec3(
442                 -normal
443                 * Mass() * situation.GetPlanet().GravitationalParameter()
444                 / (elevation * elevation));
445         // if net force is applied and in contact with surface
446         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
447                 // apply friction = -|normal force| * tangential force * coefficient
448                 glm::dvec3 fn(normal * glm::dot(force, normal));
449                 glm::dvec3 ft(force - fn);
450                 double u = 0.4;
451                 glm::dvec3 friction(-glm::length(fn) * ft * u);
452                 force += friction;
453         }
454         return {
455                 s.vel,
456                 force / Mass()
457         };
458 }
459
460 void Creature::TickStats(double dt) {
461         for (auto &s : stats.stat) {
462                 s.Add(s.gain * dt);
463         }
464         // TODO: damage values depending on properties
465         if (stats.Breath().Full()) {
466                 constexpr double dps = 1.0 / 4.0;
467                 Hurt(dps * dt);
468         }
469         if (stats.Thirst().Full()) {
470                 constexpr double dps = 1.0 / 32.0;
471                 Hurt(dps * dt);
472         }
473         if (stats.Hunger().Full()) {
474                 constexpr double dps = 1.0 / 128.0;
475                 Hurt(dps * dt);
476         }
477         if (!situation.Moving()) {
478                 // double exhaustion recovery when standing still
479                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
480         }
481 }
482
483 void Creature::TickBrain(double dt) {
484         bg_task->Tick(dt);
485         bg_task->Action();
486         memory.Tick(dt);
487         // do background stuff
488         if (goals.empty()) {
489                 return;
490         }
491         for (auto &goal : goals) {
492                 goal->Tick(dt);
493         }
494         Goal *top = &*goals.front();
495         // if active goal can be interrupted, check priorities
496         if (goals.size() > 1 && goals[0]->Interruptible()) {
497                 std::sort(goals.begin(), goals.end(), GoalCompare);
498         }
499         if (&*goals.front() != top) {
500                 top->SetBackground();
501                 goals.front()->SetForeground();
502                 top = &*goals.front();
503         }
504         goals[0]->Action();
505         for (auto goal = goals.begin(); goal != goals.end();) {
506                 if ((*goal)->Complete()) {
507                         goals.erase(goal);
508                 } else {
509                         ++goal;
510                 }
511         }
512         if (&*goals.front() != top) {
513                 goals.front()->SetForeground();
514         }
515 }
516
517 math::AABB Creature::CollisionBox() const noexcept {
518         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
519 }
520
521 glm::dmat4 Creature::CollisionTransform() const noexcept {
522         const double half_size = size * 0.5;
523         const glm::dvec3 &pos = situation.Position();
524         glm::dmat3 orient;
525         orient[1] = situation.GetPlanet().NormalAt(pos);
526         orient[2] = situation.Heading();
527         if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
528                 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
529         }
530         orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
531         orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
532         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
533                 * glm::dmat4(orient)
534                 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
535 }
536
537 glm::dmat4 Creature::LocalTransform() noexcept {
538         const double half_size = size * 0.5;
539         return CollisionTransform()
540                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
541 }
542
543 void Creature::BuildVAO() {
544         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
545         vao->Bind();
546         vao->BindAttributes();
547         vao->EnableAttribute(0);
548         vao->EnableAttribute(1);
549         vao->EnableAttribute(2);
550         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
551         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
552         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
553         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
554         {
555                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
556                 const float offset = 1.0f;
557                 for (int surface = 0; surface < 6; ++surface) {
558                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
559                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
560
561                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
562                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
563                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
564                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
565                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
566                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
567                         attrib[4 * surface + 0].texture.x = tex_u_begin;
568                         attrib[4 * surface + 0].texture.y = 1.0f;
569                         attrib[4 * surface + 0].texture.z = surface;
570
571                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
572                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
573                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
574                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
575                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
576                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
577                         attrib[4 * surface + 1].texture.x = tex_u_end;
578                         attrib[4 * surface + 1].texture.y = 1.0f;
579                         attrib[4 * surface + 1].texture.z = surface;
580
581                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
582                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
583                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
584                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
585                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
586                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
587                         attrib[4 * surface + 2].texture.x = tex_u_begin;
588                         attrib[4 * surface + 2].texture.y = 0.0f;
589                         attrib[4 * surface + 2].texture.z = surface;
590
591                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
592                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
593                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
594                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
595                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
596                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
597                         attrib[4 * surface + 3].texture.x = tex_u_end;
598                         attrib[4 * surface + 3].texture.y = 0.0f;
599                         attrib[4 * surface + 3].texture.z = surface;
600                 }
601         }
602         vao->BindElements();
603         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
604         {
605                 auto element = vao->MapElements(GL_WRITE_ONLY);
606                 for (int surface = 0; surface < 3; ++surface) {
607                         element[6 * surface + 0] = 4 * surface + 0;
608                         element[6 * surface + 1] = 4 * surface + 2;
609                         element[6 * surface + 2] = 4 * surface + 1;
610                         element[6 * surface + 3] = 4 * surface + 1;
611                         element[6 * surface + 4] = 4 * surface + 2;
612                         element[6 * surface + 5] = 4 * surface + 3;
613                 }
614                 for (int surface = 3; surface < 6; ++surface) {
615                         element[6 * surface + 0] = 4 * surface + 0;
616                         element[6 * surface + 1] = 4 * surface + 1;
617                         element[6 * surface + 2] = 4 * surface + 2;
618                         element[6 * surface + 3] = 4 * surface + 2;
619                         element[6 * surface + 4] = 4 * surface + 1;
620                         element[6 * surface + 5] = 4 * surface + 3;
621                 }
622         }
623         vao->Unbind();
624 }
625
626 void Creature::KillVAO() {
627         vao.reset();
628 }
629
630 void Creature::Draw(graphics::Viewport &viewport) {
631         if (!vao) return;
632         vao->Bind();
633         vao->DrawTriangles(6 * 6);
634 }
635
636
637 void Spawn(Creature &c, world::Planet &p) {
638         p.AddCreature(&c);
639         c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
640         c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
641
642         // probe surrounding area for common resources
643         int start = p.SideLength() / 2 - 2;
644         int end = start + 5;
645         std::map<int, double> yields;
646         for (int y = start; y < end; ++y) {
647                 for (int x = start; x < end; ++x) {
648                         const world::TileType &t = p.TypeAt(0, x, y);
649                         for (auto yield : t.resources) {
650                                 yields[yield.resource] += yield.ubiquity;
651                         }
652                 }
653         }
654         int liquid = -1;
655         int solid = -1;
656         for (auto e : yields) {
657                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
658                         if (liquid < 0 || e.second > yields[liquid]) {
659                                 liquid = e.first;
660                         }
661                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
662                         if (solid < 0 || e.second > yields[solid]) {
663                                 solid = e.first;
664                         }
665                 }
666         }
667
668         Genome genome;
669         genome.properties.Strength() = { 2.0, 0.1 };
670         genome.properties.Stamina() = { 2.0, 0.1 };
671         genome.properties.Dexerty() = { 2.0, 0.1 };
672         genome.properties.Intelligence() = { 1.0, 0.1 };
673         genome.properties.Lifetime() = { 480.0, 60.0 };
674         genome.properties.Fertility() = { 0.5, 0.03 };
675         genome.properties.Mutability() = { 0.9, 0.1 };
676         genome.properties.Adaptability() = { 0.9, 0.1 };
677         genome.properties.OffspringMass() = { 0.3, 0.02 };
678
679         glm::dvec3 color_avg(0.0);
680         double color_divisor = 0.0;
681
682         if (p.HasAtmosphere()) {
683                 c.AddMass(p.Atmosphere(), 0.01);
684                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
685                 color_divisor += 0.1;
686         }
687         if (liquid > -1) {
688                 c.AddMass(liquid, 0.3);
689                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
690                 color_divisor += 0.5;
691         }
692         if (solid > -1) {
693                 c.AddMass(solid, 0.1);
694                 color_avg += c.GetSimulation().Resources()[solid].base_color;
695                 color_divisor += 1.0;
696         }
697
698         if (color_divisor > 0.001) {
699                 color_avg /= color_divisor;
700         }
701         glm::dvec3 hsl = rgb2hsl(color_avg);
702         genome.base_hue = { hsl.x, 0.01 };
703         genome.base_saturation = { hsl.y, 0.01 };
704         genome.base_lightness = { hsl.z, 0.01 };
705         // use opposite color as start highlight
706         genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
707         genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
708         genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
709
710         genome.Configure(c);
711 }
712
713 void Genome::Configure(Creature &c) const {
714         c.GetGenome() = *this;
715
716         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
717
718         c.GetProperties() = Instantiate(properties, random);
719
720         // TODO: derive stats from properties
721         c.GetStats().Damage().gain = (-1.0 / 100.0);
722         c.GetStats().Breath().gain = (1.0 / 5.0);
723         c.GetStats().Thirst().gain = (1.0 / 60.0);
724         c.GetStats().Hunger().gain = (1.0 / 200.0);
725         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
726         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
727         c.GetStats().Boredom().gain = (1.0 / 300.0);
728
729         glm::dvec3 base_color(
730                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
731                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
732                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
733         );
734         glm::dvec3 highlight_color(
735                 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
736                 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
737                 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
738         );
739         c.BaseColor(hsl2rgb(base_color));
740         c.HighlightColor(hsl2rgb(highlight_color));
741         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
742         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
743 }
744
745
746 void Split(Creature &c) {
747         Creature *a = new Creature(c.GetSimulation());
748         const Situation &s = c.GetSituation();
749         a->AddParent(c);
750         a->Name(c.GetSimulation().Assets().name.Sequential());
751         c.GetGenome().Configure(*a);
752         for (const auto &cmp : c.GetComposition()) {
753                 a->AddMass(cmp.resource, cmp.value * 0.5);
754         }
755         s.GetPlanet().AddCreature(a);
756         // TODO: duplicate situation somehow
757         a->GetSituation().SetPlanetSurface(
758                 s.GetPlanet(),
759                 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
760         a->BuildVAO();
761         c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
762
763         Creature *b = new Creature(c.GetSimulation());
764         b->AddParent(c);
765         b->Name(c.GetSimulation().Assets().name.Sequential());
766         c.GetGenome().Configure(*b);
767         for (const auto &cmp : c.GetComposition()) {
768                 b->AddMass(cmp.resource, cmp.value * 0.5);
769         }
770         s.GetPlanet().AddCreature(b);
771         b->GetSituation().SetPlanetSurface(
772                 s.GetPlanet(),
773                 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
774         b->BuildVAO();
775         c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
776
777         c.Die();
778 }
779
780
781 Memory::Memory(Creature &c)
782 : c(c) {
783 }
784
785 Memory::~Memory() {
786 }
787
788 void Memory::Erase() {
789         known_types.clear();
790 }
791
792 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
793         double best_rating = -1.0;
794         for (const auto &k : known_types) {
795                 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
796                 auto entry = t.FindBestResource(accept);
797                 if (entry != t.resources.end()) {
798                         double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
799                         if (rating > best_rating) {
800                                 best_rating = rating;
801                                 pos = k.second.first_loc.position;
802                         }
803                         rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
804                         if (rating > best_rating) {
805                                 best_rating = rating;
806                                 pos = k.second.last_loc.position;
807                         }
808                 }
809         }
810         if (best_rating > 0.0) {
811                 glm::dvec3 error(
812                         c.GetSimulation().Assets().random.SNorm(),
813                         c.GetSimulation().Assets().random.SNorm(),
814                         c.GetSimulation().Assets().random.SNorm());
815                 pos += error * (2.0 * (1.0 - c.IntelligenceFactor()));
816                 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
817                 return true;
818         } else {
819                 return false;
820         }
821 }
822
823 void Memory::Tick(double dt) {
824         Situation &s = c.GetSituation();
825         if (s.OnSurface()) {
826                 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
827         }
828         // TODO: forget
829 }
830
831 void Memory::TrackStay(const Location &l, double t) {
832         const world::TileType &type = l.planet->TileTypeAt(l.position);
833         auto entry = known_types.find(type.id);
834         if (entry != known_types.end()) {
835                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
836                         // "it's been ages"
837                         if (entry->second.time_spent > c.Age() * 0.25) {
838                                 // the place is very familiar
839                                 c.GetStats().Boredom().Add(-0.2);
840                         } else {
841                                 // infrequent stays
842                                 c.GetStats().Boredom().Add(-0.1);
843                         }
844                 }
845                 entry->second.last_been = c.GetSimulation().Time();
846                 entry->second.last_loc = l;
847                 entry->second.time_spent += t;
848         } else {
849                 known_types.emplace(type.id, Stay{
850                         c.GetSimulation().Time(),
851                         l,
852                         c.GetSimulation().Time(),
853                         l,
854                         t
855                 });
856                 // completely new place, interesting
857                 // TODO: scale by personality trait
858                 c.GetStats().Boredom().Add(-0.25);
859         }
860 }
861
862
863 NameGenerator::NameGenerator()
864 : counter(0) {
865 }
866
867 NameGenerator::~NameGenerator() {
868 }
869
870 std::string NameGenerator::Sequential() {
871         std::stringstream ss;
872         ss << "Blob " << ++counter;
873         return ss.str();
874 }
875
876
877 Situation::Situation()
878 : planet(nullptr)
879 , state(glm::dvec3(0.0), glm::dvec3(0.0))
880 , type(LOST) {
881 }
882
883 Situation::~Situation() {
884 }
885
886 bool Situation::OnPlanet() const noexcept {
887         return type == PLANET_SURFACE;
888 }
889
890 bool Situation::OnSurface() const noexcept {
891         return type == PLANET_SURFACE;
892 }
893
894 glm::dvec3 Situation::SurfaceNormal() const noexcept {
895         return planet->NormalAt(state.pos);
896 }
897
898 world::Tile &Situation::GetTile() const noexcept {
899         return planet->TileAt(state.pos);
900 }
901
902 const world::TileType &Situation::GetTileType() const noexcept {
903         return planet->TileTypeAt(state.pos);
904 }
905
906 void Situation::Move(const glm::dvec3 &dp) noexcept {
907         state.pos += dp;
908         EnforceConstraints(state);
909 }
910
911 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
912         state.vel += dv;
913         EnforceConstraints(state);
914 }
915
916 void Situation::EnforceConstraints(State &s) noexcept {
917         if (OnSurface()) {
918                 double r = GetPlanet().Radius();
919                 if (glm::length2(s.pos) < r * r) {
920                         s.pos = glm::normalize(s.pos) * r;
921                 }
922         }
923 }
924
925 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
926         type = PLANET_SURFACE;
927         planet = &p;
928         state.pos = pos;
929         EnforceConstraints(state);
930 }
931
932
933 Steering::Steering(const Creature &c)
934 : c(c)
935 , target(0.0)
936 , haste(0.0)
937 , max_force(1.0)
938 , max_speed(1.0)
939 , min_dist(0.0)
940 , max_look(0.0)
941 , separating(false)
942 , halting(true)
943 , seeking(false)
944 , arriving(false) {
945 }
946
947 Steering::~Steering() {
948 }
949
950 void Steering::Off() noexcept {
951         separating = false;
952         halting = false;
953         seeking = false;
954         arriving = false;
955 }
956
957 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
958         separating = true;
959         min_dist = min_distance;
960         max_look = max_lookaround;
961 }
962
963 void Steering::DontSeparate() noexcept {
964         separating = false;
965 }
966
967 void Steering::ResumeSeparate() noexcept {
968         separating = true;
969 }
970
971 void Steering::Halt() noexcept {
972         halting = true;
973         seeking = false;
974         arriving = false;
975 }
976
977 void Steering::Pass(const glm::dvec3 &t) noexcept {
978         target = t;
979         halting = false;
980         seeking = true;
981         arriving = false;
982 }
983
984 void Steering::GoTo(const glm::dvec3 &t) noexcept {
985         target = t;
986         halting = false;
987         seeking = false;
988         arriving = true;
989 }
990
991 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
992         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
993         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
994         glm::dvec3 result(0.0);
995         if (separating) {
996                 // TODO: off surface situation
997                 glm::dvec3 repulse(0.0);
998                 const Situation &s = c.GetSituation();
999                 for (auto &other : s.GetPlanet().Creatures()) {
1000                         if (&*other == &c) continue;
1001                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1002                         if (glm::length2(diff) > max_look * max_look) continue;
1003                         if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1004                         double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1005                         repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1006                 }
1007                 result += repulse;
1008         }
1009         if (halting) {
1010                 // brake hard
1011                 result += -5.0 * s.vel * force;
1012         }
1013         if (seeking) {
1014                 glm::dvec3 diff = target - s.pos;
1015                 if (!allzero(diff)) {
1016                         result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1017                 }
1018         }
1019         if (arriving) {
1020                 glm::dvec3 diff = target - s.pos;
1021                 double dist = glm::length(diff);
1022                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1023                         result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1024                 }
1025         }
1026         if (glm::length2(result) > max_force * max_force) {
1027                 result = glm::normalize(result) * max_force;
1028         }
1029         return result;
1030 }
1031
1032 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1033         return (vel - s.vel) * acc;
1034 }
1035
1036 }
1037 }