]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
fix resource locator
[blobs.git] / src / creature / creature.cpp
1 #include "Creature.hpp"
2 #include "Genome.hpp"
3 #include "Situation.hpp"
4 #include "Steering.hpp"
5
6 #include "Goal.hpp"
7 #include "IdleGoal.hpp"
8 #include "InhaleNeed.hpp"
9 #include "IngestNeed.hpp"
10 #include "Need.hpp"
11 #include "../app/Assets.hpp"
12 #include "../world/Body.hpp"
13 #include "../world/Planet.hpp"
14 #include "../world/Simulation.hpp"
15 #include "../world/TileType.hpp"
16
17 #include <algorithm>
18 #include <glm/gtx/transform.hpp>
19
20 #include <iostream>
21 #include <glm/gtx/io.hpp>
22
23
24 namespace blobs {
25 namespace creature {
26
27 Creature::Creature(world::Simulation &sim)
28 : sim(sim)
29 , name()
30 , genome()
31 , mass(1.0)
32 , density(1.0)
33 , size(1.0)
34 , birth(sim.Time())
35 , health(1.0)
36 , on_death()
37 , removable(false)
38 , needs()
39 , goals()
40 , situation()
41 , steering()
42 , vel(0.0)
43 , vao() {
44 }
45
46 Creature::~Creature() {
47 }
48
49 void Creature::Grow(double amount) noexcept {
50         Mass(std::min(properties.max_mass, mass + amount));
51 }
52
53 void Creature::Hurt(double dt) noexcept {
54         health = std::max(0.0, health - dt);
55         if (health == 0.0) {
56                 std::cout << "[" << int(sim.Time()) << "s] "
57                 << name << " died" << std::endl;
58                 Die();
59         }
60 }
61
62 void Creature::Die() noexcept {
63         needs.clear();
64         goals.clear();
65         steering.Halt();
66         if (on_death) {
67                 on_death(*this);
68         }
69         Remove();
70 }
71
72 double Creature::Size() const noexcept {
73         return size;
74 }
75
76 double Creature::Age() const noexcept {
77         return sim.Time() - birth;
78 }
79
80 double Creature::Fertility() const noexcept {
81         double age = Age();
82         if (mass < properties.fertile_mass
83                 || age < properties.fertile_age
84                 || age > properties.infertile_age) {
85                 return 0.0;
86         }
87         return properties.fertility / 3600.0;
88 }
89
90 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
91         std::cout << "[" << int(sim.Time()) << "s] " << name << " new goal: " << g->Describe() << std::endl;
92         g->Enable();
93         goals.emplace_back(std::move(g));
94 }
95
96 namespace {
97
98 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
99         return b->Urgency() < a->Urgency();
100 }
101
102 }
103
104 void Creature::Tick(double dt) {
105         // TODO: better integration method
106         glm::dvec3 acc(steering.Acceleration(*this));
107         situation.Move(vel * dt);
108         vel += acc * dt;
109
110         if (Age() > properties.death_age) {
111                 std::cout << "[" << int(sim.Time()) << "s] "
112                 << name << " died of old age" << std::endl;
113         }
114
115         for (auto &need : needs) {
116                 need->Tick(dt);
117         }
118         for (auto &goal : goals) {
119                 goal->Tick(dt);
120         }
121         // do background stuff
122         for (auto &need : needs) {
123                 need->ApplyEffect(*this, dt);
124         }
125         if (goals.empty()) {
126                 return;
127         }
128         // if active goal can be interrupted, check priorities
129         if (goals.size() > 1 && goals[0]->Interruptible()) {
130                 Goal *old_top = &*goals[0];
131                 std::sort(goals.begin(), goals.end(), GoalCompare);
132                 Goal *new_top = &*goals[0];
133                 if (new_top != old_top) {
134                         std::cout << "[" << int(sim.Time()) << "s] " << name
135                                 << " changing goal from " << old_top->Describe()
136                                 << " to " << new_top->Describe() << std::endl;
137                 }
138         }
139         goals[0]->Action();
140         for (auto goal = goals.begin(); goal != goals.end();) {
141                 if ((*goal)->Complete()) {
142                         std::cout << "[" << int(sim.Time()) << "s] " << name
143                                 << " complete goal: " << (*goal)->Describe() << std::endl;
144                         goals.erase(goal);
145                 } else {
146                         ++goal;
147                 }
148         }
149 }
150
151 glm::dmat4 Creature::LocalTransform() noexcept {
152         // TODO: surface transform
153         const double half_size = size * 0.5;
154         const glm::dvec3 &pos = situation.Position();
155         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
156                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
157 }
158
159 void Creature::BuildVAO() {
160         vao.Bind();
161         vao.BindAttributes();
162         vao.EnableAttribute(0);
163         vao.EnableAttribute(1);
164         vao.EnableAttribute(2);
165         vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
166         vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
167         vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
168         vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
169         {
170                 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
171                 const float offset = 1.0f;
172                 for (int surface = 0; surface < 6; ++surface) {
173                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
174                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
175
176                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
177                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
178                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
179                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
180                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
181                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
182                         attrib[4 * surface + 0].texture.x = tex_u_begin;
183                         attrib[4 * surface + 0].texture.y = 1.0f;
184                         attrib[4 * surface + 0].texture.z = surface;
185
186                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
187                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
188                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
189                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
190                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
191                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
192                         attrib[4 * surface + 1].texture.x = tex_u_end;
193                         attrib[4 * surface + 1].texture.y = 1.0f;
194                         attrib[4 * surface + 1].texture.z = surface;
195
196                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
197                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
198                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
199                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
200                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
201                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
202                         attrib[4 * surface + 2].texture.x = tex_u_begin;
203                         attrib[4 * surface + 2].texture.y = 0.0f;
204                         attrib[4 * surface + 2].texture.z = surface;
205
206                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
207                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
208                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
209                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
210                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
211                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
212                         attrib[4 * surface + 3].texture.x = tex_u_end;
213                         attrib[4 * surface + 3].texture.y = 0.0f;
214                         attrib[4 * surface + 3].texture.z = surface;
215                 }
216         }
217         vao.BindElements();
218         vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
219         {
220                 auto element = vao.MapElements(GL_WRITE_ONLY);
221                 for (int surface = 0; surface < 3; ++surface) {
222                         element[6 * surface + 0] = 4 * surface + 0;
223                         element[6 * surface + 1] = 4 * surface + 2;
224                         element[6 * surface + 2] = 4 * surface + 1;
225                         element[6 * surface + 3] = 4 * surface + 1;
226                         element[6 * surface + 4] = 4 * surface + 2;
227                         element[6 * surface + 5] = 4 * surface + 3;
228                 }
229                 for (int surface = 3; surface < 6; ++surface) {
230                         element[6 * surface + 0] = 4 * surface + 0;
231                         element[6 * surface + 1] = 4 * surface + 1;
232                         element[6 * surface + 2] = 4 * surface + 2;
233                         element[6 * surface + 3] = 4 * surface + 2;
234                         element[6 * surface + 4] = 4 * surface + 1;
235                         element[6 * surface + 5] = 4 * surface + 3;
236                 }
237         }
238         vao.Unbind();
239 }
240
241 void Creature::Draw(graphics::Viewport &viewport) {
242         vao.Bind();
243         vao.DrawTriangles(6 * 6);
244 }
245
246
247 void Spawn(Creature &c, world::Planet &p) {
248         p.AddCreature(&c);
249         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
250
251         // probe surrounding area for common resources
252         int start = p.SideLength() / 2 - 2;
253         int end = start + 5;
254         std::map<int, double> yields;
255         for (int y = start; y < end; ++y) {
256                 for (int x = start; x < end; ++x) {
257                         const world::TileType &t = p.TypeAt(0, x, y);
258                         for (auto yield : t.resources) {
259                                 yields[yield.resource] += yield.ubiquity;
260                         }
261                 }
262         }
263         int liquid = -1;
264         int solid = -1;
265         for (auto e : yields) {
266                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
267                         if (liquid < 0 || e.second > yields[liquid]) {
268                                 liquid = e.first;
269                         }
270                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
271                         if (solid < 0 || e.second > yields[solid]) {
272                                 solid = e.first;
273                         }
274                 }
275         }
276
277         Genome genome;
278         genome.properties.birth_mass = { 0.5, 0.1 };
279         genome.properties.fertile_mass = { 1.0, 0.1 };
280         genome.properties.max_mass = { 1.2, 0.1 };
281         genome.properties.fertile_age = { 60.0, 5.0 };
282         genome.properties.infertile_age = { 700.0, 30.0 };
283         genome.properties.death_age = { 900.0, 90.0 };
284         genome.properties.fertility = { 0.5, 0.01 };
285
286         if (p.HasAtmosphere()) {
287                 genome.composition.push_back({
288                         p.Atmosphere(),    // resource
289                         { 0.01, 0.00001 }, // mass
290                         { 0.5,  0.001 },   // intake
291                         { 0.1,  0.0005 },  // penalty
292                         { 0.0,  0.0 },     // growth
293                 });
294         }
295         if (liquid > -1) {
296                 genome.composition.push_back({
297                         liquid,          // resource
298                         { 0.6,  0.01 },  // mass
299                         { 0.2,  0.001 }, // intake
300                         { 0.01, 0.002 }, // penalty
301                         { 0.1, 0.0 },   // growth
302                 });
303         }
304         if (solid > -1) {
305                 genome.composition.push_back({
306                         solid,             // resource
307                         { 0.4,   0.01 },   // mass
308                         //{ 0.1,   0.001 },  // intake
309                         { 0.4,   0.001 },  // intake
310                         { 0.001, 0.0001 }, // penalty
311                         { 10.0,  0.002 },   // growth
312                 });
313         }
314
315         genome.Configure(c);
316 }
317
318 void Genome::Configure(Creature &c) const {
319         c.GetGenome() = *this;
320
321         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
322
323         c.GetProperties().birth_mass = properties.birth_mass.FakeNormal(random.SNorm());
324         c.GetProperties().fertile_mass = properties.fertile_mass.FakeNormal(random.SNorm());
325         c.GetProperties().max_mass = properties.max_mass.FakeNormal(random.SNorm());
326         c.GetProperties().fertile_age = properties.fertile_age.FakeNormal(random.SNorm());
327         c.GetProperties().infertile_age = properties.infertile_age.FakeNormal(random.SNorm());
328         c.GetProperties().death_age = properties.death_age.FakeNormal(random.SNorm());
329         c.GetProperties().fertility = properties.fertility.FakeNormal(random.SNorm());
330
331         double mass = 0.0;
332         double volume = 0.0;
333         for (const auto &comp : composition) {
334                 double comp_mass = comp.mass.FakeNormal(random.SNorm());
335                 double intake = comp.intake.FakeNormal(random.SNorm());
336                 double penalty = comp.penalty.FakeNormal(random.SNorm());
337
338                 mass += comp_mass;
339                 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
340
341                 std::unique_ptr<Need> need;
342                 if (c.GetSimulation().Resources()[comp.resource].state == world::Resource::SOLID) {
343                         need.reset(new IngestNeed(comp.resource, intake, penalty));
344                         need->gain = intake * 0.05;
345                 } else if (c.GetSimulation().Resources()[comp.resource].state == world::Resource::LIQUID) {
346                         need.reset(new IngestNeed(comp.resource, intake, penalty));
347                         need->gain = intake * 0.1;
348                 } else {
349                         need.reset(new InhaleNeed(comp.resource, intake, penalty));
350                         need->gain = intake * 0.5;
351                 }
352                 need->name = c.GetSimulation().Resources()[comp.resource].label;
353                 need->growth = comp.growth.FakeNormal(random.SNorm());
354                 need->inconvenient = 0.5;
355                 need->critical = 0.95;
356                 c.AddNeed(std::move(need));
357         }
358
359         c.Mass(c.GetProperties().birth_mass);
360         c.Density(mass / volume);
361         c.GetSteering().MaxAcceleration(1.4);
362         c.GetSteering().MaxSpeed(4.4);
363         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
364 }
365
366
367 void Split(Creature &c) {
368         Creature *a = new Creature(c.GetSimulation());
369         const Situation &s = c.GetSituation();
370         // TODO: generate names
371         a->Name("Blobby");
372         // TODO: mutate
373         c.GetGenome().Configure(*a);
374         s.GetPlanet().AddCreature(a);
375         // TODO: duplicate situation somehow
376         a->GetSituation().SetPlanetSurface(
377                 s.GetPlanet(), s.Surface(),
378                 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
379         a->BuildVAO();
380
381         Creature *b = new Creature(c.GetSimulation());
382         b->Name("Sir Blobalot");
383         c.GetGenome().Configure(*b);
384         s.GetPlanet().AddCreature(b);
385         b->GetSituation().SetPlanetSurface(
386                 s.GetPlanet(), s.Surface(),
387                 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
388         b->BuildVAO();
389
390         c.Die();
391 }
392
393
394 Situation::Situation()
395 : planet(nullptr)
396 , position(0.0)
397 , surface(0)
398 , type(LOST) {
399 }
400
401 Situation::~Situation() {
402 }
403
404 bool Situation::OnPlanet() const noexcept {
405         return type == PLANET_SURFACE;
406 }
407
408 bool Situation::OnSurface() const noexcept {
409         return type == PLANET_SURFACE;
410 }
411
412 bool Situation::OnTile() const noexcept {
413         glm::ivec2 t(planet->SurfacePosition(surface, position));
414         return type == PLANET_SURFACE
415                 && t.x >= 0 && t.x < planet->SideLength()
416                 && t.y >= 0 && t.y < planet->SideLength();
417 }
418
419 glm::ivec2 Situation::SurfacePosition() const noexcept {
420         return planet->SurfacePosition(surface, position);
421 }
422
423 world::Tile &Situation::GetTile() const noexcept {
424         glm::ivec2 t(planet->SurfacePosition(surface, position));
425         return planet->TileAt(surface, t.x, t.y);
426 }
427
428 const world::TileType &Situation::GetTileType() const noexcept {
429         glm::ivec2 t(planet->SurfacePosition(surface, position));
430         return planet->TypeAt(surface, t.x, t.y);
431 }
432
433 void Situation::Move(const glm::dvec3 &dp) noexcept {
434         position += dp;
435         if (OnSurface()) {
436                 // enforce ground constraint
437                 if (Surface() < 3) {
438                         position[(Surface() + 2) % 3] = std::max(0.0, position[(Surface() + 2) % 3]);
439                 } else {
440                         position[(Surface() + 2) % 3] = std::min(0.0, position[(Surface() + 2) % 3]);
441                 }
442         }
443 }
444
445 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
446         type = PLANET_SURFACE;
447         planet = &p;
448         surface = srf;
449         position = pos;
450 }
451
452
453 Steering::Steering()
454 : seek_target(0.0)
455 , max_accel(1.0)
456 , max_speed(1.0)
457 , halting(false)
458 , seeking(false) {
459 }
460
461 Steering::~Steering() {
462 }
463
464 void Steering::Halt() noexcept {
465         halting = true;
466         seeking = false;
467 }
468
469 void Steering::GoTo(const glm::dvec3 &t) noexcept {
470         seek_target = t;
471         halting = false;
472         seeking = true;
473 }
474
475 glm::dvec3 Steering::Acceleration(Creature &c) const noexcept {
476         glm::dvec3 acc(0.0);
477         if (halting) {
478                 SumForce(acc, c.Velocity() * -max_accel);
479         }
480         if (seeking) {
481                 glm::dvec3 diff = seek_target - c.GetSituation().Position();
482                 if (!allzero(diff)) {
483                         SumForce(acc, ((normalize(diff) * max_speed) - c.Velocity()) * max_accel);
484                 }
485         }
486         return acc;
487 }
488
489 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in) const noexcept {
490         if (allzero(in) || anynan(in)) {
491                 return false;
492         }
493         double cur = allzero(out) ? 0.0 : length(out);
494         double rem = max_accel - cur;
495         if (rem < 0.0) {
496                 return true;
497         }
498         double add = length(in);
499         if (add > rem) {
500                 // this method is off if in and out are in different
501                 // directions, but gives okayish results
502                 out += in * (1.0 / add);
503                 return true;
504         } else {
505                 out += in;
506                 return false;
507         }
508 }
509
510 }
511 }