1 #include "Creature.hpp"
4 #include "NameGenerator.hpp"
5 #include "Situation.hpp"
6 #include "Steering.hpp"
9 #include "IdleGoal.hpp"
10 #include "InhaleNeed.hpp"
11 #include "IngestNeed.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"
21 #include <glm/gtx/transform.hpp>
22 #include <glm/gtx/vector_angle.hpp>
25 #include <glm/gtx/io.hpp>
31 Creature::Creature(world::Simulation &sim)
38 , highlight_color(0.0)
52 // all creatures avoid each other for now
53 steering.Separate(0.1, 1.5);
56 Creature::~Creature() {
59 glm::dvec4 Creature::HighlightColor() const noexcept {
60 return glm::dvec4(highlight_color, AgeLerp(CurProps().highlight, NextProps().highlight));
63 void Creature::Ingest(int res, double amount) noexcept {
64 const Genome::Composition *cmp = nullptr;
65 for (const auto &c : genome.composition) {
66 if (c.resource == res) {
72 const double max_mass = AgeLerp(CurProps().mass, NextProps().mass);
73 Mass(std::min(max_mass, mass + amount));
75 // foreign material. poisonous?
79 void Creature::Hurt(double dt) noexcept {
80 health = std::max(0.0, health - dt);
82 std::cout << "[" << int(sim.Time()) << "s] "
83 << name << " died" << std::endl;
88 void Creature::Die() noexcept {
98 double Creature::Size() const noexcept {
102 double Creature::Age() const noexcept {
103 return sim.Time() - birth;
106 std::string Creature::AgeName() const {
125 double Creature::AgeLerp(double from, double to) const noexcept {
126 return glm::mix(from, to, glm::smoothstep(CurProps().age, NextProps().age, Age()));
129 double Creature::Fertility() const noexcept {
130 return AgeLerp(CurProps().fertility, NextProps().fertility) / 3600.0;
133 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
135 goals.emplace_back(std::move(g));
140 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
141 return b->Urgency() < a->Urgency();
146 void Creature::Tick(double dt) {
147 if (cur_prop < 5 && Age() > NextProps().age) {
150 std::cout << "[" << int(sim.Time()) << "s] "
151 << name << " died of old age" << std::endl;
154 std::cout << "[" << int(sim.Time()) << "s] "
155 << name << " grew up to " << AgeName() << std::endl;
160 Situation::State state(situation.GetState());
161 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
162 Situation::Derivative b(Step(a, dt * 0.5));
163 Situation::Derivative c(Step(b, dt * 0.5));
164 Situation::Derivative d(Step(c, dt));
165 Situation::Derivative f(
166 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
167 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc),
168 (1.0 / 6.0) * (a.turn + 2.0 * (b.turn + c.turn) + d.turn)
170 state.pos += f.vel * dt;
171 state.vel += f.acc * dt;
172 constexpr double turn_speed = 10.0;
173 // TODO: this is crap
174 state.dir = glm::normalize(state.dir + f.turn * turn_speed * dt);
175 situation.SetState(state);
179 for (auto &need : needs) {
182 for (auto &goal : goals) {
185 // do background stuff
186 for (auto &need : needs) {
187 need->ApplyEffect(*this, dt);
192 // if active goal can be interrupted, check priorities
193 if (goals.size() > 1 && goals[0]->Interruptible()) {
194 std::sort(goals.begin(), goals.end(), GoalCompare);
197 for (auto goal = goals.begin(); goal != goals.end();) {
198 if ((*goal)->Complete()) {
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 s.dir = normalize(s.dir + ds.turn * dt);
213 steering.Acceleration(s),
214 allzero(s.vel) ? glm::dvec3(0.0) : normalize(s.vel) - s.dir
218 glm::dmat4 Creature::LocalTransform() noexcept {
219 // TODO: surface transform
220 const double half_size = size * 0.5;
221 const glm::dvec3 &pos = situation.Position();
222 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
223 * glm::dmat4(world::Planet::SurfaceOrientation(situation.Surface()))
224 * glm::rotate(glm::orientedAngle(glm::dvec3(0.0, 0.0, -1.0), situation.Heading(), glm::dvec3(0.0, 1.0, 0.0)), glm::dvec3(0.0, 1.0, 0.0))
225 * glm::scale(glm::dvec3(half_size, half_size, half_size));
228 void Creature::BuildVAO() {
230 vao.BindAttributes();
231 vao.EnableAttribute(0);
232 vao.EnableAttribute(1);
233 vao.EnableAttribute(2);
234 vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
235 vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
236 vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
237 vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
239 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
240 const float offset = 1.0f;
241 for (int surface = 0; surface < 6; ++surface) {
242 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
243 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
245 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
246 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
247 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
248 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
249 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
250 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
251 attrib[4 * surface + 0].texture.x = tex_u_begin;
252 attrib[4 * surface + 0].texture.y = 1.0f;
253 attrib[4 * surface + 0].texture.z = surface;
255 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
256 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
257 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
258 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
259 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
260 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
261 attrib[4 * surface + 1].texture.x = tex_u_end;
262 attrib[4 * surface + 1].texture.y = 1.0f;
263 attrib[4 * surface + 1].texture.z = surface;
265 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
266 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
267 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
268 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
269 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
270 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
271 attrib[4 * surface + 2].texture.x = tex_u_begin;
272 attrib[4 * surface + 2].texture.y = 0.0f;
273 attrib[4 * surface + 2].texture.z = surface;
275 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
276 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
277 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
278 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
279 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
280 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
281 attrib[4 * surface + 3].texture.x = tex_u_end;
282 attrib[4 * surface + 3].texture.y = 0.0f;
283 attrib[4 * surface + 3].texture.z = surface;
287 vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
289 auto element = vao.MapElements(GL_WRITE_ONLY);
290 for (int surface = 0; surface < 3; ++surface) {
291 element[6 * surface + 0] = 4 * surface + 0;
292 element[6 * surface + 1] = 4 * surface + 2;
293 element[6 * surface + 2] = 4 * surface + 1;
294 element[6 * surface + 3] = 4 * surface + 1;
295 element[6 * surface + 4] = 4 * surface + 2;
296 element[6 * surface + 5] = 4 * surface + 3;
298 for (int surface = 3; surface < 6; ++surface) {
299 element[6 * surface + 0] = 4 * surface + 0;
300 element[6 * surface + 1] = 4 * surface + 1;
301 element[6 * surface + 2] = 4 * surface + 2;
302 element[6 * surface + 3] = 4 * surface + 2;
303 element[6 * surface + 4] = 4 * surface + 1;
304 element[6 * surface + 5] = 4 * surface + 3;
310 void Creature::Draw(graphics::Viewport &viewport) {
312 vao.DrawTriangles(6 * 6);
316 void Spawn(Creature &c, world::Planet &p) {
318 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
320 // probe surrounding area for common resources
321 int start = p.SideLength() / 2 - 2;
323 std::map<int, double> yields;
324 for (int y = start; y < end; ++y) {
325 for (int x = start; x < end; ++x) {
326 const world::TileType &t = p.TypeAt(0, x, y);
327 for (auto yield : t.resources) {
328 yields[yield.resource] += yield.ubiquity;
334 for (auto e : yields) {
335 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
336 if (liquid < 0 || e.second > yields[liquid]) {
339 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
340 if (solid < 0 || e.second > yields[solid]) {
348 genome.properties.Birth().age = { 0.0, 0.0 };
349 genome.properties.Birth().mass = { 0.5, 0.05 };
350 genome.properties.Birth().fertility = { 0.0, 0.0 };
351 genome.properties.Birth().highlight = { 0.0, 0.0 };
353 genome.properties.Child().age = { 30.0, 1.0 };
354 genome.properties.Child().mass = { 0.7, 0.05 };
355 genome.properties.Child().fertility = { 0.0, 0.0 };
356 genome.properties.Child().highlight = { 0.2, 0.05 };
358 genome.properties.Youth().age = { 60.0, 5.0 };
359 genome.properties.Youth().mass = { 0.9, 0.1 };
360 genome.properties.Youth().fertility = { 0.5, 0.03 };
361 genome.properties.Youth().highlight = { 0.9, 0.1 };
363 genome.properties.Adult().age = { 120.0, 10.0 };
364 genome.properties.Adult().mass = { 1.2, 0.1 };
365 genome.properties.Adult().fertility = { 0.4, 0.01 };
366 genome.properties.Adult().highlight = { 0.7, 0.1 };
368 genome.properties.Elder().age = { 360.0, 30.0 };
369 genome.properties.Elder().mass = { 1.0, 0.05 };
370 genome.properties.Elder().fertility = { 0.1, 0.01 };
371 genome.properties.Elder().highlight = { 0.6, 0.1 };
373 genome.properties.Death().age = { 480.0, 60.0 };
374 genome.properties.Death().mass = { 0.9, 0.05 };
375 genome.properties.Death().fertility = { 0.0, 0.0 };
376 genome.properties.Death().highlight = { 0.5, 0.1 };
378 genome.properties.strength = { 1.0, 0.1 };
379 genome.properties.stamina = { 1.0, 0.1 };
380 genome.properties.dexerty = { 1.0, 0.1 };
381 genome.properties.intelligence = { 1.0, 0.1 };
382 genome.properties.mutability = { 1.0, 0.1 };
384 glm::dvec3 color_avg(0.0);
385 double color_divisor = 0.0;
387 if (p.HasAtmosphere()) {
388 genome.composition.push_back({
389 p.Atmosphere(), // resource
390 { 0.01, 0.00001 }, // mass
391 { 0.5, 0.001 }, // intake
392 { 0.1, 0.0005 }, // penalty
393 { 0.0, 0.0 }, // growth
395 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
396 color_divisor += 0.1;
399 genome.composition.push_back({
401 { 0.6, 0.01 }, // mass
402 { 0.2, 0.001 }, // intake
403 { 0.01, 0.002 }, // penalty
404 { 0.1, 0.0 }, // growth
406 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
407 color_divisor += 0.5;
410 genome.composition.push_back({
412 { 0.4, 0.01 }, // mass
413 { 0.4, 0.001 }, // intake
414 { 0.001, 0.0001 }, // penalty
415 { 10.0, 0.002 }, // growth
417 color_avg += c.GetSimulation().Resources()[solid].base_color;
418 color_divisor += 1.0;
421 if (color_divisor > 0.001) {
422 color_avg /= color_divisor;
424 glm::dvec3 hsl = rgb2hsl(color_avg);
425 genome.base_hue = { hsl.x, 0.01 };
426 genome.base_saturation = { hsl.y, 0.01 };
427 genome.base_lightness = { hsl.z, 0.01 };
432 void Genome::Configure(Creature &c) const {
433 c.GetGenome() = *this;
435 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
437 c.GetProperties() = Instantiate(properties, random);
441 for (const auto &comp : composition) {
442 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
443 double comp_mass = comp.mass.FakeNormal(random.SNorm());
444 double intake = comp.intake.FakeNormal(random.SNorm());
445 double penalty = comp.penalty.FakeNormal(random.SNorm());
448 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
450 std::unique_ptr<Need> need;
451 if (resource.state == world::Resource::SOLID) {
452 intake *= std::atan(c.GetProperties().strength);
453 need.reset(new IngestNeed(comp.resource, intake, penalty));
454 need->gain = intake * 0.05;
455 } else if (resource.state == world::Resource::LIQUID) {
456 intake *= std::atan(c.GetProperties().stamina);
457 need.reset(new IngestNeed(comp.resource, intake, penalty));
458 need->gain = intake * 0.1;
460 need.reset(new InhaleNeed(comp.resource, intake, penalty));
461 need->gain = intake * 0.5;
463 need->name = c.GetSimulation().Resources()[comp.resource].label;
464 need->inconvenient = 0.5;
465 need->critical = 0.95;
466 c.AddNeed(std::move(need));
469 glm::dvec3 base_color(
470 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
471 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
472 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
474 glm::dvec3 highlight_color(
475 std::fmod(base_color.x + 0.5, 1.0),
479 c.BaseColor(hsl2rgb(base_color));
480 c.HighlightColor(hsl2rgb(highlight_color));
482 c.Mass(c.GetProperties().props[0].mass);
483 c.Density(mass / volume);
484 c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
485 c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
486 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
490 void Split(Creature &c) {
491 Creature *a = new Creature(c.GetSimulation());
492 const Situation &s = c.GetSituation();
493 a->Name(c.GetSimulation().Assets().name.Sequential());
495 c.GetGenome().Configure(*a);
496 s.GetPlanet().AddCreature(a);
497 // TODO: duplicate situation somehow
498 a->GetSituation().SetPlanetSurface(
499 s.GetPlanet(), s.Surface(),
500 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
502 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
503 << a->Name() << " was born" << std::endl;
505 Creature *b = new Creature(c.GetSimulation());
506 b->Name(c.GetSimulation().Assets().name.Sequential());
507 c.GetGenome().Configure(*b);
508 s.GetPlanet().AddCreature(b);
509 b->GetSituation().SetPlanetSurface(
510 s.GetPlanet(), s.Surface(),
511 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
513 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
514 << b->Name() << " was born" << std::endl;
520 Memory::Memory(Creature &c)
527 void Memory::Tick(double dt) {
528 Situation &s = c.GetSituation();
530 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
534 void Memory::TrackStay(const Location &l, double t) {
535 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
536 auto entry = known_types.find(type.id);
537 if (entry != known_types.end()) {
538 entry->second.last_been = c.GetSimulation().Time();
539 entry->second.last_loc = l;
540 entry->second.time_spent += t;
542 known_types.emplace(type.id, Stay{
543 c.GetSimulation().Time(),
545 c.GetSimulation().Time(),
553 NameGenerator::NameGenerator()
557 NameGenerator::~NameGenerator() {
560 std::string NameGenerator::Sequential() {
561 std::stringstream ss;
562 ss << "Blob " << ++counter;
567 Situation::Situation()
569 , state(glm::dvec3(0.0), glm::dvec3(0.0))
574 Situation::~Situation() {
577 bool Situation::OnPlanet() const noexcept {
578 return type == PLANET_SURFACE;
581 bool Situation::OnSurface() const noexcept {
582 return type == PLANET_SURFACE;
585 bool Situation::OnTile() const noexcept {
586 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
587 return type == PLANET_SURFACE
588 && t.x >= 0 && t.x < planet->SideLength()
589 && t.y >= 0 && t.y < planet->SideLength();
592 glm::ivec2 Situation::SurfacePosition() const noexcept {
593 return planet->SurfacePosition(surface, state.pos);
596 world::Tile &Situation::GetTile() const noexcept {
597 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
598 return planet->TileAt(surface, t.x, t.y);
601 const world::TileType &Situation::GetTileType() const noexcept {
602 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
603 return planet->TypeAt(surface, t.x, t.y);
606 void Situation::Move(const glm::dvec3 &dp) noexcept {
609 // enforce ground constraint
611 state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
613 state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
618 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
619 type = PLANET_SURFACE;
626 Steering::Steering(const Creature &c)
639 Steering::~Steering() {
642 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
644 min_dist = min_distance;
645 max_look = max_lookaround;
648 void Steering::DontSeparate() noexcept {
652 void Steering::Halt() noexcept {
658 void Steering::Pass(const glm::dvec3 &t) noexcept {
665 void Steering::GoTo(const glm::dvec3 &t) noexcept {
672 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
675 // TODO: off surface situation
676 glm::dvec3 repulse(0.0);
677 const Situation &s = c.GetSituation();
678 for (auto &other : s.GetPlanet().Creatures()) {
679 if (&*other == &c) continue;
680 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
681 if (length2(diff) > max_look * max_look) continue;
682 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
683 if (sep < min_dist) {
684 repulse += normalize(diff) * (1.0 - sep / min_dist);
687 SumForce(acc, repulse);
690 SumForce(acc, s.vel * -max_accel);
693 glm::dvec3 diff = target - s.pos;
694 if (!allzero(diff)) {
695 SumForce(acc, TargetVelocity(s, (normalize(diff) * max_speed)));
699 glm::dvec3 diff = target - s.pos;
700 double dist = length(diff);
701 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
702 SumForce(acc, TargetVelocity(s, diff * std::min(dist * max_accel, max_speed) / dist));
708 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in) const noexcept {
709 if (allzero(in) || anynan(in)) {
712 double cur = allzero(out) ? 0.0 : length(out);
713 double rem = max_accel - cur;
717 double add = length(in);
719 // this method is off if in and out are in different
720 // directions, but gives okayish results
721 out += in * (1.0 / add);
729 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel) const noexcept {
730 return (vel - s.vel) * max_accel;