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