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