]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
overhaul need system
[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 "../world/Body.hpp"
15 #include "../world/Planet.hpp"
16 #include "../world/Simulation.hpp"
17 #include "../world/TileType.hpp"
18
19 #include <algorithm>
20 #include <sstream>
21 #include <glm/gtx/transform.hpp>
22 #include <glm/gtx/vector_angle.hpp>
23
24 #include <iostream>
25 #include <glm/gtx/io.hpp>
26
27
28 namespace blobs {
29 namespace creature {
30
31 Composition::Composition()
32 : components() {
33 }
34
35 Composition::~Composition() {
36 }
37
38 namespace {
39 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
40         return b.value < a.value;
41 }
42 }
43
44 void Composition::Add(int res, double amount) {
45         bool found = false;
46         for (auto &c : components) {
47                 if (c.resource == res) {
48                         c.value += amount;
49                         found = true;
50                         break;
51                 }
52         }
53         if (!found) {
54                 components.emplace_back(res, amount);
55         }
56         std::sort(components.begin(), components.end(), CompositionCompare);
57 }
58
59 bool Composition::Has(int res) const noexcept {
60         for (auto &c : components) {
61                 if (c.resource == res) {
62                         return true;
63                 }
64         }
65         return false;
66 }
67
68 double Composition::Get(int res) const noexcept {
69         for (auto &c : components) {
70                 if (c.resource == res) {
71                         return c.value;
72                 }
73         }
74         return 0.0;
75 }
76
77
78 Creature::Creature(world::Simulation &sim)
79 : sim(sim)
80 , name()
81 , genome()
82 , properties()
83 , composition()
84 , base_color(1.0)
85 , highlight_color(0.0, 0.0, 0.0, 1.0)
86 , mass(1.0)
87 , size(1.0)
88 , birth(sim.Time())
89 , on_death()
90 , removable(false)
91 , stats()
92 , memory(*this)
93 , bg_task()
94 , goals()
95 , situation()
96 , steering(*this)
97 , vao() {
98         // all creatures avoid each other for now
99         steering.Separate(0.1, 1.5);
100 }
101
102 Creature::~Creature() {
103 }
104
105 void Creature::AddMass(int res, double amount) {
106         composition.Add(res, amount);
107         double mass = 0.0;
108         double nonsolid = 0.0;
109         double volume = 0.0;
110         for (const auto &c : composition) {
111                 mass += c.value;
112                 volume += c.value / sim.Assets().data.resources[c.resource].density;
113                 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
114                         nonsolid += c.value;
115                 }
116         }
117         Mass(mass);
118         Size(std::cbrt(volume));
119         highlight_color.a = nonsolid / mass;
120 }
121
122 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
123         highlight_color = glm::dvec4(c, highlight_color.a);
124 }
125
126 void Creature::Ingest(int res, double amount) noexcept {
127         // TODO: check foreign materials
128         // 10% stays in body
129         AddMass(res, amount * 0.1);
130 }
131
132 void Creature::Hurt(double amount) noexcept {
133         stats.Damage().Add(amount);
134         if (stats.Damage().Full()) {
135                 std::cout << "[" << int(sim.Time()) << "s] " << name << " ";
136                 if (stats.Breath().Full()) {
137                         std::cout << "suffocated";
138                 } else if (stats.Thirst().Full()) {
139                         std::cout << "died of thirst";
140                 } else if (stats.Hunger().Full()) {
141                         std::cout << "starved to death";
142                 } else {
143                         std::cout << "succumed to wounds";
144                 }
145                 std::cout << std::endl;
146                 Die();
147         }
148 }
149
150 void Creature::Die() noexcept {
151         goals.clear();
152         steering.Halt();
153         if (on_death) {
154                 on_death(*this);
155         }
156         Remove();
157 }
158
159 double Creature::Age() const noexcept {
160         return sim.Time() - birth;
161 }
162
163 double Creature::AgeFactor(double peak) const noexcept {
164         // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
165         // goes negative below -0.5 and starts to rise again above 1.0
166         double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
167         return 1.0 - (3.0 * t * t) + (2.0 * t * t * t);
168 }
169
170 double Creature::ExhaustionFactor() const noexcept {
171         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
172 }
173
174 double Creature::FatigueFactor() const noexcept {
175         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
176 }
177
178 double Creature::Strength() const noexcept {
179         // TODO: replace all age factors with actual growth and decay
180         return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
181 }
182
183 double Creature::Stamina() const noexcept {
184         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
185 }
186
187 double Creature::Dexerty() const noexcept {
188         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
189 }
190
191 double Creature::Intelligence() const noexcept {
192         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
193 }
194
195 double Creature::Lifetime() const noexcept {
196         return properties.Lifetime();
197 }
198
199 double Creature::Fertility() const noexcept {
200         return properties.Fertility() * AgeFactor(0.25);
201 }
202
203 double Creature::Mutability() const noexcept {
204         return properties.Mutability();
205 }
206
207 double Creature::OffspringMass() const noexcept {
208         return properties.OffspringMass();
209 }
210
211 double Creature::OffspringChance() const noexcept {
212         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
213 }
214
215 double Creature::MutateChance() const noexcept {
216         return GetProperties().Mutability() * (1.0 / 3600.0);
217 }
218
219 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
220         g->Enable();
221         goals.emplace_back(std::move(g));
222 }
223
224 namespace {
225
226 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
227         return b->Urgency() < a->Urgency();
228 }
229
230 }
231
232 void Creature::Tick(double dt) {
233         TickState(dt);
234         TickStats(dt);
235         TickBrain(dt);
236 }
237
238 void Creature::TickState(double dt) {
239         steering.MaxSpeed(Dexerty());
240         steering.MaxForce(Strength());
241         Situation::State state(situation.GetState());
242         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
243         Situation::Derivative b(Step(a, dt * 0.5));
244         Situation::Derivative c(Step(b, dt * 0.5));
245         Situation::Derivative d(Step(c, dt));
246         Situation::Derivative f(
247                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
248                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
249         );
250         state.pos += f.vel * dt;
251         state.vel += f.acc * dt;
252         if (length2(state.vel) > 0.000001) {
253                 glm::dvec3 nvel(normalize(state.vel));
254                 double ang = angle(nvel, state.dir);
255                 double turn_rate = PI * 0.5 * dt;
256                 if (ang < turn_rate) {
257                         state.dir = normalize(state.vel);
258                 } else if (std::abs(ang - PI) < 0.001) {
259                         state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
260                 } else {
261                         state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
262                 }
263         }
264         situation.SetState(state);
265         stats.Exhaustion().Add(length(f.acc) * Mass() / Stamina() * dt);
266 }
267
268 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
269         Situation::State s = situation.GetState();
270         s.pos += ds.vel * dt;
271         s.vel += ds.acc * dt;
272         return {
273                 s.vel,
274                 steering.Force(s) / Mass()
275         };
276 }
277
278 void Creature::TickStats(double dt) {
279         for (auto &s : stats.stat) {
280                 s.Add(s.gain * dt);
281         }
282         stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
283         // TODO: damage values depending on properties
284         if (stats.Breath().Full()) {
285                 constexpr double dps = 1.0 / 4.0;
286                 Hurt(dps * dt);
287         }
288         if (stats.Thirst().Full()) {
289                 constexpr double dps = 1.0 / 32.0;
290                 Hurt(dps * dt);
291         }
292         if (stats.Hunger().Full()) {
293                 constexpr double dps = 1.0 / 128.0;
294                 Hurt(dps * dt);
295         }
296 }
297
298 void Creature::TickBrain(double dt) {
299         bg_task->Tick(dt);
300         bg_task->Action();
301         memory.Tick(dt);
302         // do background stuff
303         if (goals.empty()) {
304                 return;
305         }
306         for (auto &goal : goals) {
307                 goal->Tick(dt);
308         }
309         // if active goal can be interrupted, check priorities
310         if (goals.size() > 1 && goals[0]->Interruptible()) {
311                 std::sort(goals.begin(), goals.end(), GoalCompare);
312         }
313         goals[0]->Action();
314         for (auto goal = goals.begin(); goal != goals.end();) {
315                 if ((*goal)->Complete()) {
316                         goals.erase(goal);
317                 } else {
318                         ++goal;
319                 }
320         }
321 }
322
323 glm::dmat4 Creature::LocalTransform() noexcept {
324         const double half_size = size * 0.5;
325         const glm::dvec3 &pos = situation.Position();
326         const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
327         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
328                 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
329                 * glm::dmat4(srf)
330                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
331 }
332
333 void Creature::BuildVAO() {
334         vao.Bind();
335         vao.BindAttributes();
336         vao.EnableAttribute(0);
337         vao.EnableAttribute(1);
338         vao.EnableAttribute(2);
339         vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
340         vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
341         vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
342         vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
343         {
344                 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
345                 const float offset = 1.0f;
346                 for (int surface = 0; surface < 6; ++surface) {
347                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
348                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
349
350                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
351                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
352                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
353                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
354                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
355                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
356                         attrib[4 * surface + 0].texture.x = tex_u_begin;
357                         attrib[4 * surface + 0].texture.y = 1.0f;
358                         attrib[4 * surface + 0].texture.z = surface;
359
360                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
361                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
362                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
363                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
364                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
365                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
366                         attrib[4 * surface + 1].texture.x = tex_u_end;
367                         attrib[4 * surface + 1].texture.y = 1.0f;
368                         attrib[4 * surface + 1].texture.z = surface;
369
370                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
371                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
372                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
373                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
374                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
375                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
376                         attrib[4 * surface + 2].texture.x = tex_u_begin;
377                         attrib[4 * surface + 2].texture.y = 0.0f;
378                         attrib[4 * surface + 2].texture.z = surface;
379
380                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
381                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
382                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
383                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
384                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
385                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
386                         attrib[4 * surface + 3].texture.x = tex_u_end;
387                         attrib[4 * surface + 3].texture.y = 0.0f;
388                         attrib[4 * surface + 3].texture.z = surface;
389                 }
390         }
391         vao.BindElements();
392         vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
393         {
394                 auto element = vao.MapElements(GL_WRITE_ONLY);
395                 for (int surface = 0; surface < 3; ++surface) {
396                         element[6 * surface + 0] = 4 * surface + 0;
397                         element[6 * surface + 1] = 4 * surface + 2;
398                         element[6 * surface + 2] = 4 * surface + 1;
399                         element[6 * surface + 3] = 4 * surface + 1;
400                         element[6 * surface + 4] = 4 * surface + 2;
401                         element[6 * surface + 5] = 4 * surface + 3;
402                 }
403                 for (int surface = 3; surface < 6; ++surface) {
404                         element[6 * surface + 0] = 4 * surface + 0;
405                         element[6 * surface + 1] = 4 * surface + 1;
406                         element[6 * surface + 2] = 4 * surface + 2;
407                         element[6 * surface + 3] = 4 * surface + 2;
408                         element[6 * surface + 4] = 4 * surface + 1;
409                         element[6 * surface + 5] = 4 * surface + 3;
410                 }
411         }
412         vao.Unbind();
413 }
414
415 void Creature::Draw(graphics::Viewport &viewport) {
416         vao.Bind();
417         vao.DrawTriangles(6 * 6);
418 }
419
420
421 void Spawn(Creature &c, world::Planet &p) {
422         p.AddCreature(&c);
423         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
424         c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
425
426         // probe surrounding area for common resources
427         int start = p.SideLength() / 2 - 2;
428         int end = start + 5;
429         std::map<int, double> yields;
430         for (int y = start; y < end; ++y) {
431                 for (int x = start; x < end; ++x) {
432                         const world::TileType &t = p.TypeAt(0, x, y);
433                         for (auto yield : t.resources) {
434                                 yields[yield.resource] += yield.ubiquity;
435                         }
436                 }
437         }
438         int liquid = -1;
439         int solid = -1;
440         for (auto e : yields) {
441                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
442                         if (liquid < 0 || e.second > yields[liquid]) {
443                                 liquid = e.first;
444                         }
445                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
446                         if (solid < 0 || e.second > yields[solid]) {
447                                 solid = e.first;
448                         }
449                 }
450         }
451
452         Genome genome;
453         genome.properties.Strength() = { 2.0, 0.1 };
454         genome.properties.Stamina() = { 4.0, 0.1 };
455         genome.properties.Dexerty() = { 2.0, 0.1 };
456         genome.properties.Intelligence() = { 1.0, 0.1 };
457         genome.properties.Lifetime() = { 480.0, 60.0 };
458         genome.properties.Fertility() = { 0.5, 0.03 };
459         genome.properties.Mutability() = { 1.0, 0.1 };
460         genome.properties.OffspringMass() = { 0.3, 0.02 };
461
462         glm::dvec3 color_avg(0.0);
463         double color_divisor = 0.0;
464
465         if (p.HasAtmosphere()) {
466                 c.AddMass(p.Atmosphere(), 0.01);
467                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
468                 color_divisor += 0.1;
469         }
470         if (liquid > -1) {
471                 c.AddMass(liquid, 0.3);
472                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
473                 color_divisor += 0.5;
474         }
475         if (solid > -1) {
476                 c.AddMass(solid, 0.1);
477                 color_avg += c.GetSimulation().Resources()[solid].base_color;
478                 color_divisor += 1.0;
479         }
480
481         if (color_divisor > 0.001) {
482                 color_avg /= color_divisor;
483         }
484         glm::dvec3 hsl = rgb2hsl(color_avg);
485         genome.base_hue = { hsl.x, 0.01 };
486         genome.base_saturation = { hsl.y, 0.01 };
487         genome.base_lightness = { hsl.z, 0.01 };
488
489         genome.Configure(c);
490 }
491
492 void Genome::Configure(Creature &c) const {
493         c.GetGenome() = *this;
494
495         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
496
497         c.GetProperties() = Instantiate(properties, random);
498
499         // TODO: derive stats from properties
500         c.GetStats().Damage().gain = (-1.0 / 100.0);
501         c.GetStats().Breath().gain = (1.0 / 5.0);
502         c.GetStats().Thirst().gain = (1.0 / 60.0);
503         c.GetStats().Hunger().gain = (1.0 / 200.0);
504         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
505         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
506         c.GetStats().Boredom().gain = (1.0 / 300.0);
507
508         glm::dvec3 base_color(
509                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
510                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
511                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
512         );
513         glm::dvec3 highlight_color(
514                 std::fmod(base_color.x + 0.5, 1.0),
515                 1.0 - base_color.y,
516                 1.0 - base_color.z
517         );
518         c.BaseColor(hsl2rgb(base_color));
519         c.HighlightColor(hsl2rgb(highlight_color));
520         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
521         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
522 }
523
524
525 void Split(Creature &c) {
526         Creature *a = new Creature(c.GetSimulation());
527         const Situation &s = c.GetSituation();
528         a->Name(c.GetSimulation().Assets().name.Sequential());
529         c.GetGenome().Configure(*a);
530         for (const auto &cmp : c.GetComposition()) {
531                 a->AddMass(cmp.resource, cmp.value * 0.5);
532         }
533         s.GetPlanet().AddCreature(a);
534         // TODO: duplicate situation somehow
535         a->GetSituation().SetPlanetSurface(
536                 s.GetPlanet(), s.Surface(),
537                 s.Position() + glm::dvec3(0.0, a->Size() + 0.1, 0.0));
538         a->BuildVAO();
539         std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
540                 << a->Name() << " was born" << std::endl;
541
542         Creature *b = new Creature(c.GetSimulation());
543         b->Name(c.GetSimulation().Assets().name.Sequential());
544         c.GetGenome().Configure(*b);
545         for (const auto &cmp : c.GetComposition()) {
546                 b->AddMass(cmp.resource, cmp.value * 0.5);
547         }
548         s.GetPlanet().AddCreature(b);
549         b->GetSituation().SetPlanetSurface(
550                 s.GetPlanet(), s.Surface(),
551                 s.Position() + glm::dvec3(0.0, b->Size() - 0.1, 0.0));
552         b->BuildVAO();
553         std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
554                 << b->Name() << " was born" << std::endl;
555
556         c.Die();
557 }
558
559
560 Memory::Memory(Creature &c)
561 : c(c) {
562 }
563
564 Memory::~Memory() {
565 }
566
567 void Memory::Tick(double dt) {
568         Situation &s = c.GetSituation();
569         if (s.OnSurface()) {
570                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
571         }
572 }
573
574 void Memory::TrackStay(const Location &l, double t) {
575         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
576         auto entry = known_types.find(type.id);
577         if (entry != known_types.end()) {
578                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
579                         // "it's been ages"
580                         if (entry->second.time_spent > c.Age() * 0.25) {
581                                 // the place is very familiar
582                                 c.GetStats().Boredom().Add(-0.2);
583                         } else {
584                                 // infrequent stays
585                                 c.GetStats().Boredom().Add(-0.1);
586                         }
587                 }
588                 entry->second.last_been = c.GetSimulation().Time();
589                 entry->second.last_loc = l;
590                 entry->second.time_spent += t;
591         } else {
592                 known_types.emplace(type.id, Stay{
593                         c.GetSimulation().Time(),
594                         l,
595                         c.GetSimulation().Time(),
596                         l,
597                         t
598                 });
599                 // completely new place, interesting
600                 // TODO: scale by personality trait
601                 c.GetStats().Boredom().Add(-0.25);
602         }
603 }
604
605
606 NameGenerator::NameGenerator()
607 : counter(0) {
608 }
609
610 NameGenerator::~NameGenerator() {
611 }
612
613 std::string NameGenerator::Sequential() {
614         std::stringstream ss;
615         ss << "Blob " << ++counter;
616         return ss.str();
617 }
618
619
620 Situation::Situation()
621 : planet(nullptr)
622 , state(glm::dvec3(0.0), glm::dvec3(0.0))
623 , surface(0)
624 , type(LOST) {
625 }
626
627 Situation::~Situation() {
628 }
629
630 bool Situation::OnPlanet() const noexcept {
631         return type == PLANET_SURFACE;
632 }
633
634 bool Situation::OnSurface() const noexcept {
635         return type == PLANET_SURFACE;
636 }
637
638 bool Situation::OnTile() const noexcept {
639         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
640         return type == PLANET_SURFACE
641                 && t.x >= 0 && t.x < planet->SideLength()
642                 && t.y >= 0 && t.y < planet->SideLength();
643 }
644
645 glm::ivec2 Situation::SurfacePosition() const noexcept {
646         return planet->SurfacePosition(surface, state.pos);
647 }
648
649 world::Tile &Situation::GetTile() const noexcept {
650         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
651         return planet->TileAt(surface, t.x, t.y);
652 }
653
654 const world::TileType &Situation::GetTileType() const noexcept {
655         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
656         return planet->TypeAt(surface, t.x, t.y);
657 }
658
659 void Situation::Move(const glm::dvec3 &dp) noexcept {
660         state.pos += dp;
661         if (OnSurface()) {
662                 // enforce ground constraint
663                 if (Surface() < 3) {
664                         state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
665                 } else {
666                         state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
667                 }
668         }
669 }
670
671 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
672         type = PLANET_SURFACE;
673         planet = &p;
674         surface = srf;
675         state.pos = pos;
676 }
677
678
679 Steering::Steering(const Creature &c)
680 : c(c)
681 , target(0.0)
682 , haste(0.0)
683 , max_force(1.0)
684 , max_speed(1.0)
685 , min_dist(0.0)
686 , max_look(0.0)
687 , separating(false)
688 , halting(true)
689 , seeking(false)
690 , arriving(false) {
691 }
692
693 Steering::~Steering() {
694 }
695
696 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
697         separating = true;
698         min_dist = min_distance;
699         max_look = max_lookaround;
700 }
701
702 void Steering::DontSeparate() noexcept {
703         separating = false;
704 }
705
706 void Steering::Halt() noexcept {
707         halting = true;
708         seeking = false;
709         arriving = false;
710 }
711
712 void Steering::Pass(const glm::dvec3 &t) noexcept {
713         target = t;
714         halting = false;
715         seeking = true;
716         arriving = false;
717 }
718
719 void Steering::GoTo(const glm::dvec3 &t) noexcept {
720         target = t;
721         halting = false;
722         seeking = false;
723         arriving = true;
724 }
725
726 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
727         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
728         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
729         glm::dvec3 result(0.0);
730         if (separating) {
731                 // TODO: off surface situation
732                 glm::dvec3 repulse(0.0);
733                 const Situation &s = c.GetSituation();
734                 for (auto &other : s.GetPlanet().Creatures()) {
735                         if (&*other == &c) continue;
736                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
737                         if (length2(diff) > max_look * max_look) continue;
738                         double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
739                         if (sep < min_dist) {
740                                 repulse += normalize(diff) * (1.0 - sep / min_dist);
741                         }
742                 }
743                 SumForce(result, repulse, force);
744         }
745         if (halting) {
746                 SumForce(result, s.vel * -force, force);
747         }
748         if (seeking) {
749                 glm::dvec3 diff = target - s.pos;
750                 if (!allzero(diff)) {
751                         SumForce(result, TargetVelocity(s, (normalize(diff) * speed), force), force);
752                 }
753         }
754         if (arriving) {
755                 glm::dvec3 diff = target - s.pos;
756                 double dist = length(diff);
757                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
758                         SumForce(result, TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force), force);
759                 }
760         }
761         return result;
762 }
763
764 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
765         if (allzero(in) || anynan(in)) {
766                 return false;
767         }
768         double cur = allzero(out) ? 0.0 : length(out);
769         double rem = max - cur;
770         if (rem < 0.0) {
771                 return true;
772         }
773         double add = length(in);
774         if (add > rem) {
775                 // this method is off if in and out are in different
776                 // directions, but gives okayish results
777                 out += in * (1.0 / add);
778                 return true;
779         } else {
780                 out += in;
781                 return false;
782         }
783 }
784
785 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
786         return (vel - s.vel) * acc;
787 }
788
789 }
790 }