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