]> git.localhorst.tv Git - blobs.git/blob - src/creature/goal.cpp
track a few things
[blobs.git] / src / creature / goal.cpp
1 #include "BlobBackgroundTask.hpp"
2 #include "Goal.hpp"
3 #include "IdleGoal.hpp"
4 #include "IngestGoal.hpp"
5 #include "LocateResourceGoal.hpp"
6
7 #include "Creature.hpp"
8 #include "../app/Assets.hpp"
9 #include "../world/Planet.hpp"
10 #include "../world/Resource.hpp"
11 #include "../world/Simulation.hpp"
12 #include "../world/TileType.hpp"
13
14 #include <cstring>
15 #include <iostream>
16 #include <sstream>
17 #include <glm/gtx/io.hpp>
18
19
20 namespace blobs {
21 namespace creature {
22
23 BlobBackgroundTask::BlobBackgroundTask(Creature &c)
24 : Goal(c)
25 , breathing(false)
26 , drink_subtask(nullptr)
27 , eat_subtask(nullptr) {
28 }
29
30 BlobBackgroundTask::~BlobBackgroundTask() {
31 }
32
33 std::string BlobBackgroundTask::Describe() const {
34         return "being a blob";
35 }
36
37 void BlobBackgroundTask::Tick(double dt) {
38         if (breathing) {
39                 // TODO: derive breathing ability
40                 int gas = Assets().data.resources["air"].id;
41                 // TODO: check if in compatible atmosphere
42                 double amount = GetCreature().GetStats().Breath().gain * -(1.5 + 0.5 * GetCreature().ExhaustionFactor());
43                 GetCreature().GetStats().Breath().Add(amount * dt);
44                 // maintain ~2.5% gas composition
45                 double gas_amount = GetCreature().GetComposition().Get(gas);
46                 if (gas_amount < GetCreature().GetComposition().TotalMass() * 0.025) {
47                         double add = std::min(GetCreature().GetComposition().TotalMass() * 0.025 - gas_amount, -amount * dt);
48                         GetCreature().Ingest(gas, add);
49                 }
50                 if (GetCreature().GetStats().Breath().Empty()) {
51                         breathing = false;
52                 }
53         }
54 }
55
56 void BlobBackgroundTask::Action() {
57         CheckStats();
58         CheckSplit();
59         CheckMutate();
60 }
61
62 void BlobBackgroundTask::CheckStats() {
63         Creature::Stats &stats = GetCreature().GetStats();
64
65         if (!breathing && stats.Breath().Bad()) {
66                 breathing = true;
67         }
68
69         if (!drink_subtask && stats.Thirst().Bad()) {
70                 drink_subtask = new IngestGoal(GetCreature(), stats.Thirst());
71                 for (const auto &cmp : GetCreature().GetComposition()) {
72                         if (Assets().data.resources[cmp.resource].state == world::Resource::LIQUID) {
73                                 drink_subtask->Accept(cmp.resource, 1.0);
74                         }
75                 }
76                 drink_subtask->OnComplete([&](Goal &) { drink_subtask = nullptr; });
77                 GetCreature().AddGoal(std::unique_ptr<Goal>(drink_subtask));
78         }
79
80         if (!eat_subtask && stats.Hunger().Bad()) {
81                 eat_subtask = new IngestGoal(GetCreature(), stats.Hunger());
82                 for (const auto &cmp : GetCreature().GetComposition()) {
83                         if (Assets().data.resources[cmp.resource].state == world::Resource::SOLID) {
84                                 eat_subtask->Accept(cmp.resource, 1.0);
85                         }
86                 }
87                 eat_subtask->OnComplete([&](Goal &) { eat_subtask = nullptr; });
88                 GetCreature().AddGoal(std::unique_ptr<Goal>(eat_subtask));
89         }
90
91         // when in bad shape, don't make much effort
92         if (stats.Damage().Bad() || stats.Exhaustion().Bad() || stats.Fatigue().Critical()) {
93                 GetCreature().GetSteering().DontSeparate();
94         } else {
95                 GetCreature().GetSteering().ResumeSeparate();
96         }
97 }
98
99 void BlobBackgroundTask::CheckSplit() {
100         if (GetCreature().Mass() > GetCreature().OffspringMass() * 2.0
101                 && GetCreature().OffspringChance() > Assets().random.UNorm()) {
102                 std::cout << "[" << int(GetCreature().GetSimulation().Time())
103                         << "s] " << GetCreature().Name() << " split" << std::endl;
104                 Split(GetCreature());
105                 return;
106         }
107 }
108
109 void BlobBackgroundTask::CheckMutate() {
110         // check for random property mutation
111         if (GetCreature().MutateChance() > Assets().random.UNorm()) {
112                 double amount = 1.0 + (Assets().random.SNorm() * 0.05);
113                 math::Distribution &d = GetCreature().GetGenome().properties.props[(int(Assets().random.UNorm() * 8.0) % 8)];
114                 if (Assets().random.UNorm() < 0.5) {
115                         d.Mean(d.Mean() * amount);
116                 } else {
117                         d.StandardDeviation(d.StandardDeviation() * amount);
118                 }
119         }
120 }
121
122 namespace {
123
124 std::string summarize(const Composition &comp, const app::Assets &assets) {
125         std::stringstream s;
126         bool first = true;
127         for (const auto &c : comp) {
128                 if (first) {
129                         first = false;
130                 } else {
131                         s << " or ";
132                 }
133                 s << assets.data.resources[c.resource].label;
134         }
135         return s.str();
136 }
137
138 }
139
140 IngestGoal::IngestGoal(Creature &c, Creature::Stat &stat)
141 : Goal(c)
142 , stat(stat)
143 , accept()
144 , locate_subtask(nullptr)
145 , ingesting(false)
146 , resource(-1)
147 , yield(0.0) {
148         Urgency(stat.value);
149 }
150
151 IngestGoal::~IngestGoal() {
152 }
153
154 void IngestGoal::Accept(int resource, double value) {
155         accept.Add(resource, value);
156 }
157
158 std::string IngestGoal::Describe() const {
159         if (resource == -1) {
160                 return "ingest " + summarize(accept, Assets());
161         } else {
162                 const world::Resource &r = Assets().data.resources[resource];
163                 if (r.state == world::Resource::SOLID) {
164                         return "eat " + r.label;
165                 } else {
166                         return "drink " + r.label;
167                 }
168         }
169 }
170
171 void IngestGoal::Enable() {
172 }
173
174 void IngestGoal::Tick(double dt) {
175         Urgency(stat.value);
176         if (locate_subtask) {
177                 locate_subtask->Urgency(Urgency() + 0.1);
178         }
179         if (ingesting) {
180                 if (OnSuitableTile() && !GetSituation().Moving()) {
181                         // TODO: determine satisfaction factor
182                         GetCreature().Ingest(resource, yield * dt);
183                         stat.Add(-1.0 * yield * dt);
184                         if (stat.Empty()) {
185                                 SetComplete();
186                         }
187                 } else {
188                         // left tile somehow, some idiot probably pushed us off
189                         ingesting = false;
190                         Interruptible(true);
191                 }
192         }
193 }
194
195 void IngestGoal::Action() {
196         if (ingesting) {
197                 // all good
198                 return;
199         }
200         if (OnSuitableTile()) {
201                 if (GetSituation().Moving()) {
202                         // break with maximum force
203                         GetSteering().Haste(1.0);
204                         GetSteering().Halt();
205                 } else {
206                         // finally
207                         Interruptible(false);
208                         ingesting = true;
209                 }
210         } else {
211                 locate_subtask = new LocateResourceGoal(GetCreature());
212                 for (const auto &c : accept) {
213                         locate_subtask->Accept(c.resource, c.value);
214                 }
215                 locate_subtask->Urgency(Urgency() + 0.1);
216                 locate_subtask->OnComplete([&](Goal &){ locate_subtask = nullptr; });
217                 GetCreature().AddGoal(std::unique_ptr<Goal>(locate_subtask));
218         }
219 }
220
221 bool IngestGoal::OnSuitableTile() {
222         if (!GetSituation().OnTile()) {
223                 return false;
224         }
225         const world::TileType &t = GetSituation().GetTileType();
226         auto found = t.FindBestResource(accept);
227         if (found != t.resources.end()) {
228                 resource = found->resource;
229                 yield = found->ubiquity;
230                 return true;
231         } else {
232                 resource = -1;
233                 return false;
234         }
235 }
236
237
238 Goal::Goal(Creature &c)
239 : c(c)
240 , on_complete()
241 , urgency(0.0)
242 , interruptible(true)
243 , complete(false) {
244 }
245
246 Goal::~Goal() noexcept {
247 }
248
249 Situation &Goal::GetSituation() noexcept {
250         return c.GetSituation();
251 }
252
253 const Situation &Goal::GetSituation() const noexcept {
254         return c.GetSituation();
255 }
256
257 Steering &Goal::GetSteering() noexcept {
258         return c.GetSteering();
259 }
260
261 const Steering &Goal::GetSteering() const noexcept {
262         return c.GetSteering();
263 }
264
265 app::Assets &Goal::Assets() noexcept {
266         return c.GetSimulation().Assets();
267 }
268
269 const app::Assets &Goal::Assets() const noexcept {
270         return c.GetSimulation().Assets();
271 }
272
273 void Goal::SetComplete() noexcept {
274         if (!complete) {
275                 complete = true;
276                 if (on_complete) {
277                         on_complete(*this);
278                 }
279         }
280 }
281
282 void Goal::OnComplete(std::function<void(Goal &)> cb) noexcept {
283         on_complete = cb;
284         if (complete) {
285                 on_complete(*this);
286         }
287 }
288
289
290 IdleGoal::IdleGoal(Creature &c)
291 : Goal(c) {
292         Urgency(-1.0);
293         Interruptible(true);
294 }
295
296 IdleGoal::~IdleGoal() {
297 }
298
299 std::string IdleGoal::Describe() const {
300         return "idle";
301 }
302
303 void IdleGoal::Enable() {
304 }
305
306 void IdleGoal::Tick(double dt) {
307 }
308
309 void IdleGoal::Action() {
310 }
311
312
313 LocateResourceGoal::LocateResourceGoal(Creature &c)
314 : Goal(c)
315 , accept()
316 , found(false)
317 , target_pos(0.0)
318 , target_srf(0)
319 , target_tile(0)
320 , searching(false)
321 , reevaluate(0.0) {
322 }
323
324 LocateResourceGoal::~LocateResourceGoal() noexcept {
325 }
326
327 void LocateResourceGoal::Accept(int resource, double value) {
328         accept.Add(resource, value);
329 }
330
331 std::string LocateResourceGoal::Describe() const {
332         return "locate " + summarize(accept, Assets());
333 }
334
335 void LocateResourceGoal::Enable() {
336
337 }
338
339 void LocateResourceGoal::Tick(double dt) {
340         reevaluate -= dt;
341 }
342
343 void LocateResourceGoal::Action() {
344         if (reevaluate < 0.0) {
345                 LocateResource();
346                 reevaluate = 3.0;
347         } else if (!found) {
348                 if (!searching) {
349                         LocateResource();
350                 } else {
351                         double dist = glm::length2(GetSituation().Position() - target_pos);
352                         if (dist < 0.0001) {
353                                 LocateResource();
354                         } else {
355                                 GetSteering().GoTo(target_pos);
356                         }
357                 }
358         } else if (OnTargetTile()) {
359                 GetSteering().Halt();
360                 if (!GetSituation().Moving()) {
361                         SetComplete();
362                 }
363         } else {
364                 GetSteering().GoTo(target_pos);
365         }
366         GetSteering().Haste(Urgency());
367 }
368
369 void LocateResourceGoal::LocateResource() {
370         if (GetSituation().OnTile()) {
371                 const world::TileType &t = GetSituation().GetTileType();
372                 auto yield = t.FindBestResource(accept);
373                 if (yield != t.resources.cend()) {
374                         // hoooray
375                         GetSteering().Halt();
376                         found = true;
377                         searching = false;
378                         target_pos = GetSituation().Position();
379                         target_srf = GetSituation().Surface();
380                         target_tile = GetSituation().GetPlanet().SurfacePosition(target_srf, target_pos);
381                 } else {
382                         // go find somewhere else
383                         SearchVicinity();
384                 }
385         } else {
386                 // well, what now?
387         }
388 }
389
390 void LocateResourceGoal::SearchVicinity() {
391         const world::Planet &planet = GetSituation().GetPlanet();
392         int srf = GetSituation().Surface();
393         const glm::dvec3 &pos = GetSituation().Position();
394
395         glm::ivec2 loc = planet.SurfacePosition(srf, pos);
396         glm::ivec2 seek_radius(2);
397         glm::ivec2 begin(glm::max(glm::ivec2(0), loc - seek_radius));
398         glm::ivec2 end(glm::min(glm::ivec2(planet.SideLength()), loc + seek_radius + glm::ivec2(1)));
399
400         double rating[end.y - begin.y][end.x - begin.x];
401         std::memset(rating, 0, sizeof(double) * (end.y - begin.y) * (end.x - begin.x));
402
403         // find close and rich field
404         for (int y = begin.y; y < end.y; ++y) {
405                 for (int x = begin.x; x < end.x; ++x) {
406                         const world::TileType &type = planet.TypeAt(srf, x, y);
407                         auto yield = type.FindBestResource(accept);
408                         if (yield != type.resources.cend()) {
409                                 // TODO: subtract minimum yield
410                                 rating[y - begin.y][x - begin.x] = yield->ubiquity * accept.Get(yield->resource);
411                                 double dist = std::max(0.125, 0.25 * glm::length(planet.TileCenter(srf, x, y) - pos));
412                                 rating[y - begin.y][x - begin.x] /= dist;
413                         }
414                 }
415         }
416
417         // demote crowded tiles
418         for (auto &c : planet.Creatures()) {
419                 if (&*c == &GetCreature()) continue;
420                 if (c->GetSituation().Surface() != srf) continue;
421                 glm::ivec2 coords(c->GetSituation().SurfacePosition());
422                 if (coords.x < begin.x || coords.x >= end.x) continue;
423                 if (coords.y < begin.y || coords.y >= end.y) continue;
424                 rating[coords.y - begin.y][coords.x - begin.x] *= 0.9;
425         }
426
427         glm::ivec2 best_pos(0);
428         double best_rating = -1.0;
429
430         for (int y = begin.y; y < end.y; ++y) {
431                 for (int x = begin.x; x < end.x; ++x) {
432                         if (rating[y - begin.y][x - begin.x] > best_rating) {
433                                 best_pos = glm::ivec2(x, y);
434                                 best_rating = rating[y - begin.y][x - begin.x];
435                         }
436                 }
437         }
438
439         if (best_rating) {
440                 found = true;
441                 searching = false;
442                 target_pos = planet.TileCenter(srf, best_pos.x, best_pos.y);
443                 target_srf = srf;
444                 target_tile = best_pos;
445                 GetSteering().GoTo(target_pos);
446         } else if (!searching) {
447                 found = false;
448                 searching = true;
449                 target_pos = GetSituation().Position();
450                 target_pos[(srf + 0) % 3] += Assets().random.SNorm();
451                 target_pos[(srf + 1) % 3] += Assets().random.SNorm();
452                 // bias towards current direction
453                 target_pos += glm::normalize(GetSituation().Velocity()) * 0.5;
454                 target_pos = clamp(target_pos, -planet.Radius(), planet.Radius());
455                 GetSteering().GoTo(target_pos);
456         }
457 }
458
459 bool LocateResourceGoal::OnTargetTile() const noexcept {
460         const Situation &s = GetSituation();
461         return s.OnSurface()
462                 && s.Surface() == target_srf
463                 && s.OnTile()
464                 && s.SurfacePosition() == target_tile;
465 }
466
467 }
468 }