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