]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
avoid others when steering
[blobs.git] / src / creature / creature.cpp
1 #include "Creature.hpp"
2 #include "Genome.hpp"
3 #include "Memory.hpp"
4 #include "NameGenerator.hpp"
5 #include "Situation.hpp"
6 #include "Steering.hpp"
7
8 #include "Goal.hpp"
9 #include "IdleGoal.hpp"
10 #include "InhaleNeed.hpp"
11 #include "IngestNeed.hpp"
12 #include "Need.hpp"
13 #include "../app/Assets.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 Creature::Creature(world::Simulation &sim)
32 : sim(sim)
33 , name()
34 , genome()
35 , properties()
36 , cur_prop(0)
37 , base_color(1.0)
38 , highlight_color(0.0)
39 , mass(1.0)
40 , density(1.0)
41 , size(1.0)
42 , birth(sim.Time())
43 , health(1.0)
44 , on_death()
45 , removable(false)
46 , memory(*this)
47 , needs()
48 , goals()
49 , situation()
50 , steering(*this)
51 , vao() {
52         // all creatures avoid each other for now
53         steering.Separate(0.1, 1.5);
54 }
55
56 Creature::~Creature() {
57 }
58
59 glm::dvec4 Creature::HighlightColor() const noexcept {
60         return glm::dvec4(highlight_color, AgeLerp(CurProps().highlight, NextProps().highlight));
61 }
62
63 void Creature::Ingest(int res, double amount) noexcept {
64         const Genome::Composition *cmp = nullptr;
65         for (const auto &c : genome.composition) {
66                 if (c.resource == res) {
67                         cmp = &c;
68                         break;
69                 }
70         }
71         if (cmp) {
72                 const double max_mass = AgeLerp(CurProps().mass, NextProps().mass);
73                 Mass(std::min(max_mass, mass + amount));
74         } else {
75                 // foreign material. poisonous?
76         }
77 }
78
79 void Creature::Hurt(double dt) noexcept {
80         health = std::max(0.0, health - dt);
81         if (health == 0.0) {
82                 std::cout << "[" << int(sim.Time()) << "s] "
83                         << name << " died" << std::endl;
84                 Die();
85         }
86 }
87
88 void Creature::Die() noexcept {
89         needs.clear();
90         goals.clear();
91         steering.Halt();
92         if (on_death) {
93                 on_death(*this);
94         }
95         Remove();
96 }
97
98 double Creature::Size() const noexcept {
99         return size;
100 }
101
102 double Creature::Age() const noexcept {
103         return sim.Time() - birth;
104 }
105
106 std::string Creature::AgeName() const {
107         switch (cur_prop) {
108                 case 0:
109                         return "Newborn";
110                 case 1:
111                         return "Child";
112                 case 2:
113                         return "Youth";
114                 case 3:
115                         return "Adult";
116                 case 4:
117                         return "Elder";
118                 case 5:
119                         return "Dead";
120                 default:
121                         return "Unknown";
122         }
123 }
124
125 double Creature::AgeLerp(double from, double to) const noexcept {
126         return glm::mix(from, to, glm::smoothstep(CurProps().age, NextProps().age, Age()));
127 }
128
129 double Creature::Fertility() const noexcept {
130         return AgeLerp(CurProps().fertility, NextProps().fertility) / 3600.0;
131 }
132
133 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
134         g->Enable();
135         goals.emplace_back(std::move(g));
136 }
137
138 namespace {
139
140 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
141         return b->Urgency() < a->Urgency();
142 }
143
144 }
145
146 void Creature::Tick(double dt) {
147         if (cur_prop < 5 && Age() > NextProps().age) {
148                 ++cur_prop;
149                 if (cur_prop == 5) {
150                         std::cout << "[" << int(sim.Time()) << "s] "
151                                 << name << " died of old age" << std::endl;
152                         Die();
153                 } else {
154                         std::cout << "[" << int(sim.Time()) << "s] "
155                                 << name << " grew up to " << AgeName() << std::endl;
156                 }
157         }
158
159         {
160                 Situation::State state(situation.GetState());
161                 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
162                 Situation::Derivative b(Step(a, dt * 0.5));
163                 Situation::Derivative c(Step(b, dt * 0.5));
164                 Situation::Derivative d(Step(c, dt));
165                 Situation::Derivative f(
166                         (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
167                         (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc),
168                         (1.0 / 6.0) * (a.turn + 2.0 * (b.turn + c.turn) + d.turn)
169                 );
170                 state.pos += f.vel * dt;
171                 state.vel += f.acc * dt;
172                 constexpr double turn_speed = 10.0;
173                 // TODO: this is crap
174                 state.dir = glm::normalize(state.dir + f.turn * turn_speed * dt);
175                 situation.SetState(state);
176         }
177
178         memory.Tick(dt);
179         for (auto &need : needs) {
180                 need->Tick(dt);
181         }
182         for (auto &goal : goals) {
183                 goal->Tick(dt);
184         }
185         // do background stuff
186         for (auto &need : needs) {
187                 need->ApplyEffect(*this, dt);
188         }
189         if (goals.empty()) {
190                 return;
191         }
192         // if active goal can be interrupted, check priorities
193         if (goals.size() > 1 && goals[0]->Interruptible()) {
194                 std::sort(goals.begin(), goals.end(), GoalCompare);
195         }
196         goals[0]->Action();
197         for (auto goal = goals.begin(); goal != goals.end();) {
198                 if ((*goal)->Complete()) {
199                         goals.erase(goal);
200                 } else {
201                         ++goal;
202                 }
203         }
204 }
205
206 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
207         Situation::State s = situation.GetState();
208         s.pos += ds.vel * dt;
209         s.vel += ds.acc * dt;
210         s.dir = normalize(s.dir + ds.turn * dt);
211         return {
212                 s.vel,
213                 steering.Acceleration(s),
214                 allzero(s.vel) ? glm::dvec3(0.0) : normalize(s.vel) - s.dir
215         };
216 }
217
218 glm::dmat4 Creature::LocalTransform() noexcept {
219         // TODO: surface transform
220         const double half_size = size * 0.5;
221         const glm::dvec3 &pos = situation.Position();
222         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
223                 * glm::dmat4(world::Planet::SurfaceOrientation(situation.Surface()))
224                 * glm::rotate(glm::orientedAngle(glm::dvec3(0.0, 0.0, -1.0), situation.Heading(), glm::dvec3(0.0, 1.0, 0.0)), glm::dvec3(0.0, 1.0, 0.0))
225                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
226 }
227
228 void Creature::BuildVAO() {
229         vao.Bind();
230         vao.BindAttributes();
231         vao.EnableAttribute(0);
232         vao.EnableAttribute(1);
233         vao.EnableAttribute(2);
234         vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
235         vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
236         vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
237         vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
238         {
239                 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
240                 const float offset = 1.0f;
241                 for (int surface = 0; surface < 6; ++surface) {
242                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
243                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
244
245                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
246                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
247                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
248                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
249                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
250                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
251                         attrib[4 * surface + 0].texture.x = tex_u_begin;
252                         attrib[4 * surface + 0].texture.y = 1.0f;
253                         attrib[4 * surface + 0].texture.z = surface;
254
255                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
256                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
257                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
258                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
259                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
260                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
261                         attrib[4 * surface + 1].texture.x = tex_u_end;
262                         attrib[4 * surface + 1].texture.y = 1.0f;
263                         attrib[4 * surface + 1].texture.z = surface;
264
265                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
266                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
267                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
268                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
269                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
270                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
271                         attrib[4 * surface + 2].texture.x = tex_u_begin;
272                         attrib[4 * surface + 2].texture.y = 0.0f;
273                         attrib[4 * surface + 2].texture.z = surface;
274
275                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
276                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
277                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
278                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
279                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
280                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
281                         attrib[4 * surface + 3].texture.x = tex_u_end;
282                         attrib[4 * surface + 3].texture.y = 0.0f;
283                         attrib[4 * surface + 3].texture.z = surface;
284                 }
285         }
286         vao.BindElements();
287         vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
288         {
289                 auto element = vao.MapElements(GL_WRITE_ONLY);
290                 for (int surface = 0; surface < 3; ++surface) {
291                         element[6 * surface + 0] = 4 * surface + 0;
292                         element[6 * surface + 1] = 4 * surface + 2;
293                         element[6 * surface + 2] = 4 * surface + 1;
294                         element[6 * surface + 3] = 4 * surface + 1;
295                         element[6 * surface + 4] = 4 * surface + 2;
296                         element[6 * surface + 5] = 4 * surface + 3;
297                 }
298                 for (int surface = 3; surface < 6; ++surface) {
299                         element[6 * surface + 0] = 4 * surface + 0;
300                         element[6 * surface + 1] = 4 * surface + 1;
301                         element[6 * surface + 2] = 4 * surface + 2;
302                         element[6 * surface + 3] = 4 * surface + 2;
303                         element[6 * surface + 4] = 4 * surface + 1;
304                         element[6 * surface + 5] = 4 * surface + 3;
305                 }
306         }
307         vao.Unbind();
308 }
309
310 void Creature::Draw(graphics::Viewport &viewport) {
311         vao.Bind();
312         vao.DrawTriangles(6 * 6);
313 }
314
315
316 void Spawn(Creature &c, world::Planet &p) {
317         p.AddCreature(&c);
318         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
319
320         // probe surrounding area for common resources
321         int start = p.SideLength() / 2 - 2;
322         int end = start + 5;
323         std::map<int, double> yields;
324         for (int y = start; y < end; ++y) {
325                 for (int x = start; x < end; ++x) {
326                         const world::TileType &t = p.TypeAt(0, x, y);
327                         for (auto yield : t.resources) {
328                                 yields[yield.resource] += yield.ubiquity;
329                         }
330                 }
331         }
332         int liquid = -1;
333         int solid = -1;
334         for (auto e : yields) {
335                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
336                         if (liquid < 0 || e.second > yields[liquid]) {
337                                 liquid = e.first;
338                         }
339                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
340                         if (solid < 0 || e.second > yields[solid]) {
341                                 solid = e.first;
342                         }
343                 }
344         }
345
346         Genome genome;
347
348         genome.properties.Birth().age = { 0.0, 0.0 };
349         genome.properties.Birth().mass = { 0.5, 0.05 };
350         genome.properties.Birth().fertility = { 0.0, 0.0 };
351         genome.properties.Birth().highlight = { 0.0, 0.0 };
352
353         genome.properties.Child().age = { 30.0, 1.0 };
354         genome.properties.Child().mass = { 0.7, 0.05 };
355         genome.properties.Child().fertility = { 0.0, 0.0 };
356         genome.properties.Child().highlight = { 0.2, 0.05 };
357
358         genome.properties.Youth().age = { 60.0, 5.0 };
359         genome.properties.Youth().mass = { 0.9, 0.1 };
360         genome.properties.Youth().fertility = { 0.5, 0.03 };
361         genome.properties.Youth().highlight = { 0.9, 0.1 };
362
363         genome.properties.Adult().age = { 120.0, 10.0 };
364         genome.properties.Adult().mass = { 1.2, 0.1 };
365         genome.properties.Adult().fertility = { 0.4, 0.01 };
366         genome.properties.Adult().highlight = { 0.7, 0.1 };
367
368         genome.properties.Elder().age = { 360.0, 30.0 };
369         genome.properties.Elder().mass = { 1.0, 0.05 };
370         genome.properties.Elder().fertility = { 0.1, 0.01 };
371         genome.properties.Elder().highlight = { 0.6, 0.1 };
372
373         genome.properties.Death().age = { 480.0, 60.0 };
374         genome.properties.Death().mass = { 0.9, 0.05 };
375         genome.properties.Death().fertility = { 0.0, 0.0 };
376         genome.properties.Death().highlight = { 0.5, 0.1 };
377
378         genome.properties.strength = { 1.0, 0.1 };
379         genome.properties.stamina = { 1.0, 0.1 };
380         genome.properties.dexerty = { 1.0, 0.1 };
381         genome.properties.intelligence = { 1.0, 0.1 };
382         genome.properties.mutability = { 1.0, 0.1 };
383
384         glm::dvec3 color_avg(0.0);
385         double color_divisor = 0.0;
386
387         if (p.HasAtmosphere()) {
388                 genome.composition.push_back({
389                         p.Atmosphere(),    // resource
390                         { 0.01, 0.00001 }, // mass
391                         { 0.5,  0.001 },   // intake
392                         { 0.1,  0.0005 },  // penalty
393                         { 0.0,  0.0 },     // growth
394                 });
395                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
396                 color_divisor += 0.1;
397         }
398         if (liquid > -1) {
399                 genome.composition.push_back({
400                         liquid,          // resource
401                         { 0.6,  0.01 },  // mass
402                         { 0.2,  0.001 }, // intake
403                         { 0.01, 0.002 }, // penalty
404                         { 0.1, 0.0 },   // growth
405                 });
406                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
407                 color_divisor += 0.5;
408         }
409         if (solid > -1) {
410                 genome.composition.push_back({
411                         solid,             // resource
412                         { 0.4,   0.01 },   // mass
413                         { 0.4,   0.001 },  // intake
414                         { 0.001, 0.0001 }, // penalty
415                         { 10.0,  0.002 },   // growth
416                 });
417                 color_avg += c.GetSimulation().Resources()[solid].base_color;
418                 color_divisor += 1.0;
419         }
420
421         if (color_divisor > 0.001) {
422                 color_avg /= color_divisor;
423         }
424         glm::dvec3 hsl = rgb2hsl(color_avg);
425         genome.base_hue = { hsl.x, 0.01 };
426         genome.base_saturation = { hsl.y, 0.01 };
427         genome.base_lightness = { hsl.z, 0.01 };
428
429         genome.Configure(c);
430 }
431
432 void Genome::Configure(Creature &c) const {
433         c.GetGenome() = *this;
434
435         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
436
437         c.GetProperties() = Instantiate(properties, random);
438
439         double mass = 0.0;
440         double volume = 0.0;
441         for (const auto &comp : composition) {
442                 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
443                 double comp_mass = comp.mass.FakeNormal(random.SNorm());
444                 double intake = comp.intake.FakeNormal(random.SNorm());
445                 double penalty = comp.penalty.FakeNormal(random.SNorm());
446
447                 mass += comp_mass;
448                 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
449
450                 std::unique_ptr<Need> need;
451                 if (resource.state == world::Resource::SOLID) {
452                         intake *= std::atan(c.GetProperties().strength);
453                         need.reset(new IngestNeed(comp.resource, intake, penalty));
454                         need->gain = intake * 0.05;
455                 } else if (resource.state == world::Resource::LIQUID) {
456                         intake *= std::atan(c.GetProperties().stamina);
457                         need.reset(new IngestNeed(comp.resource, intake, penalty));
458                         need->gain = intake * 0.1;
459                 } else {
460                         need.reset(new InhaleNeed(comp.resource, intake, penalty));
461                         need->gain = intake * 0.5;
462                 }
463                 need->name = c.GetSimulation().Resources()[comp.resource].label;
464                 need->inconvenient = 0.5;
465                 need->critical = 0.95;
466                 c.AddNeed(std::move(need));
467         }
468
469         glm::dvec3 base_color(
470                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
471                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
472                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
473         );
474         glm::dvec3 highlight_color(
475                 std::fmod(base_color.x + 0.5, 1.0),
476                 1.0 - base_color.y,
477                 1.0 - base_color.z
478         );
479         c.BaseColor(hsl2rgb(base_color));
480         c.HighlightColor(hsl2rgb(highlight_color));
481
482         c.Mass(c.GetProperties().props[0].mass);
483         c.Density(mass / volume);
484         c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
485         c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
486         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
487 }
488
489
490 void Split(Creature &c) {
491         Creature *a = new Creature(c.GetSimulation());
492         const Situation &s = c.GetSituation();
493         a->Name(c.GetSimulation().Assets().name.Sequential());
494         // TODO: mutate
495         c.GetGenome().Configure(*a);
496         s.GetPlanet().AddCreature(a);
497         // TODO: duplicate situation somehow
498         a->GetSituation().SetPlanetSurface(
499                 s.GetPlanet(), s.Surface(),
500                 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
501         a->BuildVAO();
502         std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
503                 << a->Name() << " was born" << std::endl;
504
505         Creature *b = new Creature(c.GetSimulation());
506         b->Name(c.GetSimulation().Assets().name.Sequential());
507         c.GetGenome().Configure(*b);
508         s.GetPlanet().AddCreature(b);
509         b->GetSituation().SetPlanetSurface(
510                 s.GetPlanet(), s.Surface(),
511                 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
512         b->BuildVAO();
513         std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
514                 << b->Name() << " was born" << std::endl;
515
516         c.Die();
517 }
518
519
520 Memory::Memory(Creature &c)
521 : c(c) {
522 }
523
524 Memory::~Memory() {
525 }
526
527 void Memory::Tick(double dt) {
528         Situation &s = c.GetSituation();
529         if (s.OnSurface()) {
530                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
531         }
532 }
533
534 void Memory::TrackStay(const Location &l, double t) {
535         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
536         auto entry = known_types.find(type.id);
537         if (entry != known_types.end()) {
538                 entry->second.last_been = c.GetSimulation().Time();
539                 entry->second.last_loc = l;
540                 entry->second.time_spent += t;
541         } else {
542                 known_types.emplace(type.id, Stay{
543                         c.GetSimulation().Time(),
544                         l,
545                         c.GetSimulation().Time(),
546                         l,
547                         t
548                 });
549         }
550 }
551
552
553 NameGenerator::NameGenerator()
554 : counter(0) {
555 }
556
557 NameGenerator::~NameGenerator() {
558 }
559
560 std::string NameGenerator::Sequential() {
561         std::stringstream ss;
562         ss << "Blob " << ++counter;
563         return ss.str();
564 }
565
566
567 Situation::Situation()
568 : planet(nullptr)
569 , state(glm::dvec3(0.0), glm::dvec3(0.0))
570 , surface(0)
571 , type(LOST) {
572 }
573
574 Situation::~Situation() {
575 }
576
577 bool Situation::OnPlanet() const noexcept {
578         return type == PLANET_SURFACE;
579 }
580
581 bool Situation::OnSurface() const noexcept {
582         return type == PLANET_SURFACE;
583 }
584
585 bool Situation::OnTile() const noexcept {
586         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
587         return type == PLANET_SURFACE
588                 && t.x >= 0 && t.x < planet->SideLength()
589                 && t.y >= 0 && t.y < planet->SideLength();
590 }
591
592 glm::ivec2 Situation::SurfacePosition() const noexcept {
593         return planet->SurfacePosition(surface, state.pos);
594 }
595
596 world::Tile &Situation::GetTile() const noexcept {
597         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
598         return planet->TileAt(surface, t.x, t.y);
599 }
600
601 const world::TileType &Situation::GetTileType() const noexcept {
602         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
603         return planet->TypeAt(surface, t.x, t.y);
604 }
605
606 void Situation::Move(const glm::dvec3 &dp) noexcept {
607         state.pos += dp;
608         if (OnSurface()) {
609                 // enforce ground constraint
610                 if (Surface() < 3) {
611                         state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
612                 } else {
613                         state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
614                 }
615         }
616 }
617
618 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
619         type = PLANET_SURFACE;
620         planet = &p;
621         surface = srf;
622         state.pos = pos;
623 }
624
625
626 Steering::Steering(const Creature &c)
627 : c(c)
628 , target(0.0)
629 , max_accel(1.0)
630 , max_speed(1.0)
631 , min_dist(0.0)
632 , max_look(0.0)
633 , separating(false)
634 , halting(true)
635 , seeking(false)
636 , arriving(false) {
637 }
638
639 Steering::~Steering() {
640 }
641
642 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
643         separating = true;
644         min_dist = min_distance;
645         max_look = max_lookaround;
646 }
647
648 void Steering::DontSeparate() noexcept {
649         separating = false;
650 }
651
652 void Steering::Halt() noexcept {
653         halting = true;
654         seeking = false;
655         arriving = false;
656 }
657
658 void Steering::Pass(const glm::dvec3 &t) noexcept {
659         target = t;
660         halting = false;
661         seeking = true;
662         arriving = false;
663 }
664
665 void Steering::GoTo(const glm::dvec3 &t) noexcept {
666         target = t;
667         halting = false;
668         seeking = false;
669         arriving = true;
670 }
671
672 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
673         glm::dvec3 acc(0.0);
674         if (separating) {
675                 // TODO: off surface situation
676                 glm::dvec3 repulse(0.0);
677                 const Situation &s = c.GetSituation();
678                 for (auto &other : s.GetPlanet().Creatures()) {
679                         if (&*other == &c) continue;
680                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
681                         if (length2(diff) > max_look * max_look) continue;
682                         double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
683                         if (sep < min_dist) {
684                                 repulse += normalize(diff) * (1.0 - sep / min_dist);
685                         }
686                 }
687                 SumForce(acc, repulse);
688         }
689         if (halting) {
690                 SumForce(acc, s.vel * -max_accel);
691         }
692         if (seeking) {
693                 glm::dvec3 diff = target - s.pos;
694                 if (!allzero(diff)) {
695                         SumForce(acc, TargetVelocity(s, (normalize(diff) * max_speed)));
696                 }
697         }
698         if (arriving) {
699                 glm::dvec3 diff = target - s.pos;
700                 double dist = length(diff);
701                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
702                         SumForce(acc, TargetVelocity(s, diff * std::min(dist * max_accel, max_speed) / dist));
703                 }
704         }
705         return acc;
706 }
707
708 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in) const noexcept {
709         if (allzero(in) || anynan(in)) {
710                 return false;
711         }
712         double cur = allzero(out) ? 0.0 : length(out);
713         double rem = max_accel - cur;
714         if (rem < 0.0) {
715                 return true;
716         }
717         double add = length(in);
718         if (add > rem) {
719                 // this method is off if in and out are in different
720                 // directions, but gives okayish results
721                 out += in * (1.0 / add);
722                 return true;
723         } else {
724                 out += in;
725                 return false;
726         }
727 }
728
729 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel) const noexcept {
730         return (vel - s.vel) * max_accel;
731 }
732
733 }
734 }