]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
b609fe8a169c35462622a65aee816c17b4d8e077
[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         DoWork(glm::length(f.acc) * Mass() * glm::length(f.vel) * dt);
467 }
468
469 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
470         Situation::State s = situation.GetState();
471         s.pos += ds.vel * dt;
472         s.vel += ds.acc * dt;
473         glm::dvec3 force(steering.Force(s));
474         // gravity = antinormal * mass * Gm / r²
475         double elevation = situation.GetPlanet().DistanceAt(s.pos);
476         glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
477         force += glm::dvec3(
478                 -normal
479                 * Mass() * situation.GetPlanet().GravitationalParameter()
480                 / (elevation * elevation));
481         // if net force is applied and in contact with surface
482         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
483                 // apply friction = -|normal force| * tangential force * coefficient
484                 glm::dvec3 fn(normal * glm::dot(force, normal));
485                 glm::dvec3 ft(force - fn);
486                 double u = 0.4;
487                 glm::dvec3 friction(-glm::length(fn) * ft * u);
488                 force += friction;
489         }
490         return {
491                 s.vel,
492                 force / Mass()
493         };
494 }
495
496 void Creature::TickStats(double dt) {
497         for (auto &s : stats.stat) {
498                 s.Add(s.gain * dt);
499         }
500         // TODO: damage values depending on properties
501         if (stats.Breath().Full()) {
502                 constexpr double dps = 1.0 / 4.0;
503                 Hurt(dps * dt);
504         }
505         if (stats.Thirst().Full()) {
506                 constexpr double dps = 1.0 / 32.0;
507                 Hurt(dps * dt);
508         }
509         if (stats.Hunger().Full()) {
510                 constexpr double dps = 1.0 / 128.0;
511                 Hurt(dps * dt);
512         }
513         if (!situation.Moving()) {
514                 // double exhaustion recovery when standing still
515                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
516         }
517 }
518
519 void Creature::TickBrain(double dt) {
520         bg_task->Tick(dt);
521         bg_task->Action();
522         memory.Tick(dt);
523         // do background stuff
524         if (goals.empty()) {
525                 return;
526         }
527         for (auto &goal : goals) {
528                 goal->Tick(dt);
529         }
530         Goal *top = &*goals.front();
531         // if active goal can be interrupted, check priorities
532         if (goals.size() > 1 && goals[0]->Interruptible()) {
533                 std::sort(goals.begin(), goals.end(), GoalCompare);
534         }
535         if (&*goals.front() != top) {
536                 top->SetBackground();
537                 goals.front()->SetForeground();
538                 top = &*goals.front();
539         }
540         goals[0]->Action();
541         for (auto goal = goals.begin(); goal != goals.end();) {
542                 if ((*goal)->Complete()) {
543                         goals.erase(goal);
544                 } else {
545                         ++goal;
546                 }
547         }
548         if (&*goals.front() != top) {
549                 goals.front()->SetForeground();
550         }
551 }
552
553 math::AABB Creature::CollisionBox() const noexcept {
554         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
555 }
556
557 glm::dmat4 Creature::CollisionTransform() const noexcept {
558         const double half_size = size * 0.5;
559         const glm::dvec3 &pos = situation.Position();
560         glm::dmat3 orient;
561         orient[1] = situation.GetPlanet().NormalAt(pos);
562         orient[2] = situation.Heading();
563         if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
564                 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
565         }
566         orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
567         orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
568         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
569                 * glm::dmat4(orient)
570                 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
571 }
572
573 glm::dmat4 Creature::LocalTransform() noexcept {
574         const double half_size = size * 0.5;
575         return CollisionTransform()
576                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
577 }
578
579 void Creature::BuildVAO() {
580         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
581         vao->Bind();
582         vao->BindAttributes();
583         vao->EnableAttribute(0);
584         vao->EnableAttribute(1);
585         vao->EnableAttribute(2);
586         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
587         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
588         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
589         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
590         {
591                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
592                 const float offset = 1.0f;
593                 for (int surface = 0; surface < 6; ++surface) {
594                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
595                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
596
597                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
598                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
599                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
600                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
601                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
602                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
603                         attrib[4 * surface + 0].texture.x = tex_u_begin;
604                         attrib[4 * surface + 0].texture.y = 1.0f;
605                         attrib[4 * surface + 0].texture.z = surface;
606
607                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
608                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
609                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
610                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
611                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
612                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
613                         attrib[4 * surface + 1].texture.x = tex_u_end;
614                         attrib[4 * surface + 1].texture.y = 1.0f;
615                         attrib[4 * surface + 1].texture.z = surface;
616
617                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
618                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
619                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
620                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
621                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
622                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
623                         attrib[4 * surface + 2].texture.x = tex_u_begin;
624                         attrib[4 * surface + 2].texture.y = 0.0f;
625                         attrib[4 * surface + 2].texture.z = surface;
626
627                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
628                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
629                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
630                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
631                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
632                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
633                         attrib[4 * surface + 3].texture.x = tex_u_end;
634                         attrib[4 * surface + 3].texture.y = 0.0f;
635                         attrib[4 * surface + 3].texture.z = surface;
636                 }
637         }
638         vao->BindElements();
639         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
640         {
641                 auto element = vao->MapElements(GL_WRITE_ONLY);
642                 for (int surface = 0; surface < 3; ++surface) {
643                         element[6 * surface + 0] = 4 * surface + 0;
644                         element[6 * surface + 1] = 4 * surface + 2;
645                         element[6 * surface + 2] = 4 * surface + 1;
646                         element[6 * surface + 3] = 4 * surface + 1;
647                         element[6 * surface + 4] = 4 * surface + 2;
648                         element[6 * surface + 5] = 4 * surface + 3;
649                 }
650                 for (int surface = 3; surface < 6; ++surface) {
651                         element[6 * surface + 0] = 4 * surface + 0;
652                         element[6 * surface + 1] = 4 * surface + 1;
653                         element[6 * surface + 2] = 4 * surface + 2;
654                         element[6 * surface + 3] = 4 * surface + 2;
655                         element[6 * surface + 4] = 4 * surface + 1;
656                         element[6 * surface + 5] = 4 * surface + 3;
657                 }
658         }
659         vao->Unbind();
660 }
661
662 void Creature::KillVAO() {
663         vao.reset();
664 }
665
666 void Creature::Draw(graphics::Viewport &viewport) {
667         if (!vao) return;
668         vao->Bind();
669         vao->DrawTriangles(6 * 6);
670 }
671
672
673 void Spawn(Creature &c, world::Planet &p) {
674         p.AddCreature(&c);
675         c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
676         c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
677
678         // probe surrounding area for common resources
679         int start = p.SideLength() / 2 - 2;
680         int end = start + 5;
681         std::map<int, double> yields;
682         for (int y = start; y < end; ++y) {
683                 for (int x = start; x < end; ++x) {
684                         const world::TileType &t = p.TypeAt(0, x, y);
685                         for (auto yield : t.resources) {
686                                 yields[yield.resource] += yield.ubiquity;
687                         }
688                 }
689         }
690         int liquid = -1;
691         int solid = -1;
692         for (auto e : yields) {
693                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
694                         if (liquid < 0 || e.second > yields[liquid]) {
695                                 liquid = e.first;
696                         }
697                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
698                         if (solid < 0 || e.second > yields[solid]) {
699                                 solid = e.first;
700                         }
701                 }
702         }
703
704         Genome genome;
705         genome.properties.Strength() = { 2.0, 0.1 };
706         genome.properties.Stamina() = { 2.0, 0.1 };
707         genome.properties.Dexerty() = { 2.0, 0.1 };
708         genome.properties.Intelligence() = { 1.0, 0.1 };
709         genome.properties.Lifetime() = { 480.0, 60.0 };
710         genome.properties.Fertility() = { 0.5, 0.03 };
711         genome.properties.Mutability() = { 0.9, 0.1 };
712         genome.properties.Adaptability() = { 0.9, 0.1 };
713         genome.properties.OffspringMass() = { 0.3, 0.02 };
714
715         glm::dvec3 color_avg(0.0);
716         double color_divisor = 0.0;
717
718         if (p.HasAtmosphere()) {
719                 c.AddMass(p.Atmosphere(), 0.01);
720                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
721                 color_divisor += 0.1;
722         }
723         if (liquid > -1) {
724                 c.AddMass(liquid, 0.3);
725                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
726                 color_divisor += 0.5;
727         }
728         if (solid > -1) {
729                 c.AddMass(solid, 0.1);
730                 color_avg += c.GetSimulation().Resources()[solid].base_color;
731                 color_divisor += 1.0;
732         }
733
734         if (color_divisor > 0.001) {
735                 color_avg /= color_divisor;
736         }
737         glm::dvec3 hsl = rgb2hsl(color_avg);
738         genome.base_hue = { hsl.x, 0.01 };
739         genome.base_saturation = { hsl.y, 0.01 };
740         genome.base_lightness = { hsl.z, 0.01 };
741         // use opposite color as start highlight
742         genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
743         genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
744         genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
745
746         genome.Configure(c);
747 }
748
749 void Genome::Configure(Creature &c) const {
750         c.GetGenome() = *this;
751
752         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
753
754         c.GetProperties() = Instantiate(properties, random);
755
756         // TODO: derive stats from properties
757         c.GetStats().Damage().gain = (-1.0 / 100.0);
758         c.GetStats().Breath().gain = (1.0 / 5.0);
759         c.GetStats().Thirst().gain = (1.0 / 60.0);
760         c.GetStats().Hunger().gain = (1.0 / 200.0);
761         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
762         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
763         c.GetStats().Boredom().gain = (1.0 / 300.0);
764
765         glm::dvec3 base_color(
766                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
767                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
768                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
769         );
770         glm::dvec3 highlight_color(
771                 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
772                 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
773                 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
774         );
775         c.BaseColor(hsl2rgb(base_color));
776         c.HighlightColor(hsl2rgb(highlight_color));
777         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
778         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
779 }
780
781
782 void Split(Creature &c) {
783         Creature *a = new Creature(c.GetSimulation());
784         const Situation &s = c.GetSituation();
785         a->AddParent(c);
786         a->Name(c.GetSimulation().Assets().name.Sequential());
787         c.GetGenome().Configure(*a);
788         for (const auto &cmp : c.GetComposition()) {
789                 a->AddMass(cmp.resource, cmp.value * 0.5);
790         }
791         s.GetPlanet().AddCreature(a);
792         // TODO: duplicate situation somehow
793         a->GetSituation().SetPlanetSurface(
794                 s.GetPlanet(),
795                 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
796         a->BuildVAO();
797         c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
798
799         Creature *b = new Creature(c.GetSimulation());
800         b->AddParent(c);
801         b->Name(c.GetSimulation().Assets().name.Sequential());
802         c.GetGenome().Configure(*b);
803         for (const auto &cmp : c.GetComposition()) {
804                 b->AddMass(cmp.resource, cmp.value * 0.5);
805         }
806         s.GetPlanet().AddCreature(b);
807         b->GetSituation().SetPlanetSurface(
808                 s.GetPlanet(),
809                 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
810         b->BuildVAO();
811         c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
812
813         c.Die();
814 }
815
816
817 Memory::Memory(Creature &c)
818 : c(c) {
819 }
820
821 Memory::~Memory() {
822 }
823
824 void Memory::Erase() {
825         known_types.clear();
826 }
827
828 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
829         double best_rating = -1.0;
830         for (const auto &k : known_types) {
831                 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
832                 auto entry = t.FindBestResource(accept);
833                 if (entry != t.resources.end()) {
834                         double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
835                         if (rating > best_rating) {
836                                 best_rating = rating;
837                                 pos = k.second.first_loc.position;
838                         }
839                         rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
840                         if (rating > best_rating) {
841                                 best_rating = rating;
842                                 pos = k.second.last_loc.position;
843                         }
844                 }
845         }
846         if (best_rating > 0.0) {
847                 glm::dvec3 error(
848                         c.GetSimulation().Assets().random.SNorm(),
849                         c.GetSimulation().Assets().random.SNorm(),
850                         c.GetSimulation().Assets().random.SNorm());
851                 pos += error * (2.0 * (1.0 - c.IntelligenceFactor()));
852                 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
853                 return true;
854         } else {
855                 return false;
856         }
857 }
858
859 void Memory::Tick(double dt) {
860         Situation &s = c.GetSituation();
861         if (s.OnSurface()) {
862                 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
863         }
864         // TODO: forget
865 }
866
867 void Memory::TrackStay(const Location &l, double t) {
868         const world::TileType &type = l.planet->TileTypeAt(l.position);
869         auto entry = known_types.find(type.id);
870         if (entry != known_types.end()) {
871                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
872                         // "it's been ages"
873                         if (entry->second.time_spent > c.Age() * 0.25) {
874                                 // the place is very familiar
875                                 c.GetStats().Boredom().Add(-0.2);
876                         } else {
877                                 // infrequent stays
878                                 c.GetStats().Boredom().Add(-0.1);
879                         }
880                 }
881                 entry->second.last_been = c.GetSimulation().Time();
882                 entry->second.last_loc = l;
883                 entry->second.time_spent += t;
884         } else {
885                 known_types.emplace(type.id, Stay{
886                         c.GetSimulation().Time(),
887                         l,
888                         c.GetSimulation().Time(),
889                         l,
890                         t
891                 });
892                 // completely new place, interesting
893                 // TODO: scale by personality trait
894                 c.GetStats().Boredom().Add(-0.25);
895         }
896 }
897
898
899 NameGenerator::NameGenerator()
900 : counter(0) {
901 }
902
903 NameGenerator::~NameGenerator() {
904 }
905
906 std::string NameGenerator::Sequential() {
907         std::stringstream ss;
908         ss << "Blob " << ++counter;
909         return ss.str();
910 }
911
912
913 Situation::Situation()
914 : planet(nullptr)
915 , state(glm::dvec3(0.0), glm::dvec3(0.0))
916 , type(LOST) {
917 }
918
919 Situation::~Situation() {
920 }
921
922 bool Situation::OnPlanet() const noexcept {
923         return type == PLANET_SURFACE;
924 }
925
926 bool Situation::OnSurface() const noexcept {
927         return type == PLANET_SURFACE;
928 }
929
930 bool Situation::OnGround() const noexcept {
931         return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
932 }
933
934 glm::dvec3 Situation::SurfaceNormal() const noexcept {
935         return planet->NormalAt(state.pos);
936 }
937
938 world::Tile &Situation::GetTile() const noexcept {
939         return planet->TileAt(state.pos);
940 }
941
942 const world::TileType &Situation::GetTileType() const noexcept {
943         return planet->TileTypeAt(state.pos);
944 }
945
946 void Situation::Move(const glm::dvec3 &dp) noexcept {
947         state.pos += dp;
948         EnforceConstraints(state);
949 }
950
951 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
952         state.vel += dv;
953         EnforceConstraints(state);
954 }
955
956 void Situation::EnforceConstraints(State &s) noexcept {
957         if (OnSurface()) {
958                 double r = GetPlanet().Radius();
959                 if (glm::length2(s.pos) < r * r) {
960                         s.pos = glm::normalize(s.pos) * r;
961                 }
962         }
963 }
964
965 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
966         type = PLANET_SURFACE;
967         planet = &p;
968         state.pos = pos;
969         EnforceConstraints(state);
970 }
971
972
973 Steering::Steering(const Creature &c)
974 : c(c)
975 , target(0.0)
976 , haste(0.0)
977 , max_force(1.0)
978 , max_speed(1.0)
979 , min_dist(0.0)
980 , max_look(0.0)
981 , separating(false)
982 , halting(true)
983 , seeking(false)
984 , arriving(false) {
985 }
986
987 Steering::~Steering() {
988 }
989
990 void Steering::Off() noexcept {
991         separating = false;
992         halting = false;
993         seeking = false;
994         arriving = false;
995 }
996
997 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
998         separating = true;
999         min_dist = min_distance;
1000         max_look = max_lookaround;
1001 }
1002
1003 void Steering::DontSeparate() noexcept {
1004         separating = false;
1005 }
1006
1007 void Steering::ResumeSeparate() noexcept {
1008         separating = true;
1009 }
1010
1011 void Steering::Halt() noexcept {
1012         halting = true;
1013         seeking = false;
1014         arriving = false;
1015 }
1016
1017 void Steering::Pass(const glm::dvec3 &t) noexcept {
1018         target = t;
1019         halting = false;
1020         seeking = true;
1021         arriving = false;
1022 }
1023
1024 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1025         target = t;
1026         halting = false;
1027         seeking = false;
1028         arriving = true;
1029 }
1030
1031 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1032         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1033         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1034         glm::dvec3 result(0.0);
1035         if (separating) {
1036                 // TODO: off surface situation
1037                 glm::dvec3 repulse(0.0);
1038                 const Situation &s = c.GetSituation();
1039                 for (auto &other : s.GetPlanet().Creatures()) {
1040                         if (&*other == &c) continue;
1041                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1042                         if (glm::length2(diff) > max_look * max_look) continue;
1043                         if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1044                         double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1045                         repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1046                 }
1047                 result += repulse;
1048         }
1049         if (halting) {
1050                 // brake hard
1051                 result += -5.0 * s.vel * force;
1052         }
1053         if (seeking) {
1054                 glm::dvec3 diff = target - s.pos;
1055                 if (!allzero(diff)) {
1056                         result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1057                 }
1058         }
1059         if (arriving) {
1060                 glm::dvec3 diff = target - s.pos;
1061                 double dist = glm::length(diff);
1062                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1063                         result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1064                 }
1065         }
1066         // remove vertical component, if any
1067         const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1068         result += normal * glm::dot(normal, result);
1069         // clamp to max
1070         if (glm::length2(result) > max_force * max_force) {
1071                 result = glm::normalize(result) * max_force;
1072         }
1073         return result;
1074 }
1075
1076 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1077         return (vel - s.vel) * acc;
1078 }
1079
1080 }
1081 }