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