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