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