]> git.localhorst.tv Git - blobs.git/blobdiff - src/creature/creature.cpp
better heading implementation
[blobs.git] / src / creature / creature.cpp
index 468967887ee96a1d62b7547c2d7a2ad8cff04461..0a8b460c09e8b568af1e138ae7ae962386fc98ca 100644 (file)
@@ -6,6 +6,7 @@
 #include "Situation.hpp"
 #include "Steering.hpp"
 
+#include "AttackGoal.hpp"
 #include "BlobBackgroundTask.hpp"
 #include "Goal.hpp"
 #include "IdleGoal.hpp"
 namespace blobs {
 namespace creature {
 
-Composition::Composition()
-: components()
-, total_mass(0.0) {
+Composition::Composition(const world::Set<world::Resource> &resources)
+: resources(resources)
+, components()
+, total_mass(0.0)
+, total_volume(0.0)
+, state_mass{0.0} {
 }
 
 Composition::~Composition() {
@@ -49,6 +53,7 @@ void Composition::Add(int res, double amount) {
                if (c->resource == res) {
                        c->value += amount;
                        if (c->value <= 0.0) {
+                               amount += c->value;
                                components.erase(c);
                        }
                        found = true;
@@ -59,7 +64,9 @@ void Composition::Add(int res, double amount) {
                components.emplace_back(res, amount);
        }
        std::sort(components.begin(), components.end(), CompositionCompare);
+       state_mass[resources[res].state] += amount;
        total_mass += amount;
+       total_volume += amount / resources[res].density;
 }
 
 bool Composition::Has(int res) const noexcept {
@@ -80,13 +87,46 @@ double Composition::Get(int res) const noexcept {
        return 0.0;
 }
 
+double Composition::Proportion(int res) const noexcept {
+       return Get(res) / TotalMass();
+}
+
+double Composition::StateProportion(int res) const noexcept {
+       return Get(res) / StateMass(resources[res].state);
+}
+
+double Composition::Compatibility(int res) const noexcept {
+       if (Has(res)) {
+               return StateProportion(res);
+       }
+       double max_compat = -1.0;
+       double min_compat = 1.0;
+       for (const auto &c : components) {
+               double prop = c.value / StateMass(resources[res].state);
+               for (const auto &compat : resources[c.resource].compatibility) {
+                       double value = compat.second * prop;
+                       if (value > max_compat) {
+                               max_compat = value;
+                       }
+                       if (value < min_compat) {
+                               min_compat = value;
+                       }
+               }
+       }
+       if (min_compat < 0.0) {
+               return min_compat;
+       } else {
+               return max_compat;
+       }
+}
+
 
 Creature::Creature(world::Simulation &sim)
 : sim(sim)
 , name()
 , genome()
 , properties()
-, composition()
+, composition(sim.Resources())
 , base_color(1.0)
 , highlight_color(0.0, 0.0, 0.0, 1.0)
 , mass(1.0)
@@ -102,6 +142,13 @@ Creature::Creature(world::Simulation &sim)
 , goals()
 , situation()
 , steering(*this)
+, heading_target(0.0, 0.0, -1.0)
+, heading_manual(false)
+, perception_range(1.0)
+, perception_range_squared(1.0)
+, perception_omni_range(1.0)
+, perception_omni_range_squared(1.0)
+, perception_field(1.0)
 , vao() {
        sim.SetAlive(this);
        // all creatures avoid each other for now
@@ -116,8 +163,8 @@ void Creature::AddMass(int res, double amount) {
        double nonsolid = 0.0;
        double volume = 0.0;
        for (const auto &c : composition) {
-               volume += c.value / sim.Assets().data.resources[c.resource].density;
-               if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
+               volume += c.value / sim.Resources()[c.resource].density;
+               if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
                        nonsolid += c.value;
                }
        }
@@ -131,13 +178,12 @@ void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
 }
 
 void Creature::Ingest(int res, double amount) noexcept {
-       // TODO: check foreign materials
        if (sim.Resources()[res].state == world::Resource::SOLID) {
-               // 15% of solids stays in body
-               AddMass(res, amount * 0.15);
+               // 30% of solids stays in body
+               AddMass(res, amount * 0.3 * composition.Compatibility(res));
        } else {
-               // 10% of fluids stays in body
-               AddMass(res, amount * 0.05);
+               // 5% of fluids stays in body
+               AddMass(res, amount * 0.05 * composition.Compatibility(res));
        }
        math::GaloisLFSR &random = sim.Assets().random;
        if (random.UNorm() < AdaptChance()) {
@@ -180,10 +226,10 @@ void Creature::Ingest(int res, double amount) noexcept {
                                } else if (diff > 0.5) {
                                        diff -= 1.0;
                                }
-                               // move ±15% of distance
-                               d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
+                               // move 0-15% of distance
+                               d->Mean(std::fmod(d->Mean() + diff * random.UNorm() * 0.15, 1.0));
                        } else {
-                               d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
+                               d->Mean(glm::clamp(d->Mean() + diff * random.UNorm() * 0.15, 0.0, 1.0));
                        }
                } else {
                        // scale by ±15%, enforce bounds
@@ -266,7 +312,7 @@ void Creature::AddParent(Creature &p) {
 }
 
 double Creature::Age() const noexcept {
-       return sim.Time() - birth;
+       return Dead() ? death - birth : sim.Time() - birth;
 }
 
 double Creature::AgeFactor(double peak) const noexcept {
@@ -294,18 +340,38 @@ double Creature::Strength() const noexcept {
        return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
 }
 
+double Creature::StrengthFactor() const noexcept {
+       double str = Strength();
+       return str / (str + 1.0);
+}
+
 double Creature::Stamina() const noexcept {
        return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
 }
 
+double Creature::StaminaFactor() const noexcept {
+       double stm = Stamina();
+       return stm / (stm + 1.0);
+}
+
 double Creature::Dexerty() const noexcept {
        return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
 }
 
+double Creature::DexertyFactor() const noexcept {
+       double dex = Dexerty();
+       return dex / (dex + 1.0);
+}
+
 double Creature::Intelligence() const noexcept {
        return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
 }
 
+double Creature::IntelligenceFactor() const noexcept {
+       double intl = Intelligence();
+       return intl / (intl + 1.0);
+}
+
 double Creature::Lifetime() const noexcept {
        return properties.Lifetime();
 }
@@ -327,25 +393,23 @@ double Creature::OffspringMass() const noexcept {
 }
 
 double Creature::PerceptionRange() const noexcept {
-       return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
+       return perception_range;
 }
 
 double Creature::PerceptionOmniRange() const noexcept {
-       return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
+       return perception_omni_range;
 }
 
 double Creature::PerceptionField() const noexcept {
-       // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
-       return 0.8 - (Dexerty() / (Dexerty() + 1));
+       return perception_field;
 }
 
 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
        const glm::dvec3 diff(p - situation.Position());
-       double omni_range = PerceptionOmniRange();
-       if (length2(diff) < omni_range * omni_range) return true;
-       double range = PerceptionRange();
-       if (length2(diff) > range * range) return false;
-       return dot(normalize(diff), situation.Heading()) > PerceptionField();
+       double ldiff = glm::length2(diff);
+       if (ldiff < perception_omni_range_squared) return true;
+       if (ldiff > perception_range_squared) return false;
+       return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
 }
 
 double Creature::OffspringChance() const noexcept {
@@ -368,6 +432,14 @@ void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
        goals.emplace_back(std::move(g));
 }
 
+void Creature::SetBackgroundTask(std::unique_ptr<Goal> &&g) {
+       bg_task = std::move(g);
+}
+
+Goal &Creature::BackgroundTask() {
+       return *bg_task;
+}
+
 namespace {
 
 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
@@ -377,11 +449,22 @@ bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b)
 }
 
 void Creature::Tick(double dt) {
+       Cache();
        TickState(dt);
        TickStats(dt);
        TickBrain(dt);
 }
 
+void Creature::Cache() noexcept {
+       double dex_fact = DexertyFactor();
+       perception_range = 3.0 * dex_fact + size;
+       perception_range_squared = perception_range * perception_range;
+       perception_omni_range = 0.5 * dex_fact + size;
+       perception_omni_range_squared = perception_omni_range * perception_omni_range;
+       // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
+       perception_field = 0.8 - dex_fact;
+}
+
 void Creature::TickState(double dt) {
        steering.MaxSpeed(Dexerty());
        steering.MaxForce(Strength());
@@ -397,42 +480,49 @@ void Creature::TickState(double dt) {
        state.pos += f.vel * dt;
        state.vel += f.acc * dt;
        situation.EnforceConstraints(state);
-       if (length2(state.vel) > 0.000001) {
-               glm::dvec3 nvel(normalize(state.vel));
-               double ang = angle(nvel, state.dir);
-               double turn_rate = PI * 0.75 * dt;
-               if (ang < turn_rate) {
-                       state.dir = normalize(state.vel);
-               } else if (std::abs(ang - PI) < 0.001) {
-                       state.dir = rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
-               } else {
-                       state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
+
+       if (!heading_manual && glm::length2(state.vel) > 0.000001) {
+               const glm::dvec3 normal(situation.GetPlanet().NormalAt(state.pos));
+               const glm::dvec3 tangent(state.vel - (normal * glm::dot(state.vel, normal)));
+               if (glm::length2(tangent) > 0.000001) {
+                       heading_target = glm::normalize(tangent);
                }
        }
+       double ang = glm::angle(heading_target, state.dir);
+       double turn_rate = PI * 0.75 * dt;
+       if (ang < turn_rate) {
+               state.dir = heading_target;
+               heading_manual = false;
+       } else {
+               state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, heading_target)));
+       }
+
        situation.SetState(state);
        // work is force times distance
-       DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
+       // keep 10% of gravity as a kind of background burn
+       DoWork(glm::length(f.acc - (0.9 * situation.GetPlanet().GravityAt(state.pos))) * Mass() * glm::length(f.vel) * dt);
 }
 
 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
        Situation::State s = situation.GetState();
        s.pos += ds.vel * dt;
        s.vel += ds.acc * dt;
+       situation.EnforceConstraints(s);
        glm::dvec3 force(steering.Force(s));
        // gravity = antinormal * mass * Gm / r²
-       double elevation = situation.GetPlanet().DistanceAt(s.pos);
        glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
        force += glm::dvec3(
                -normal
-               * Mass() * situation.GetPlanet().GravitationalParameter()
-               / (elevation * elevation));
+               * (Mass() * situation.GetPlanet().GravitationalParameter()
+               / glm::length2(s.pos)));
        // if net force is applied and in contact with surface
-       if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
-               // apply friction = -|normal force| * tangential force * coefficient
-               glm::dvec3 fn(normal * dot(force, normal));
+       if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
+               // apply friction
+               glm::dvec3 fn(normal * glm::dot(force, normal));
+               // TODO: friction somehow bigger than force?
                glm::dvec3 ft(force - fn);
                double u = 0.4;
-               glm::dvec3 friction(-length(fn) * ft * u);
+               glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
                force += friction;
        }
        return {
@@ -498,7 +588,7 @@ void Creature::TickBrain(double dt) {
        }
 }
 
-math::AABB Creature::CollisionBox() const noexcept {
+math::AABB Creature::CollisionBounds() const noexcept {
        return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
 }
 
@@ -508,16 +598,20 @@ glm::dmat4 Creature::CollisionTransform() const noexcept {
        glm::dmat3 orient;
        orient[1] = situation.GetPlanet().NormalAt(pos);
        orient[2] = situation.Heading();
-       if (std::abs(dot(orient[1], orient[2])) > 0.999) {
+       if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
                orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
        }
-       orient[0] = normalize(cross(orient[1], orient[2]));
-       orient[2] = normalize(cross(orient[0], orient[1]));
+       orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
+       orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
        return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
                * glm::dmat4(orient)
                * glm::translate(glm::dvec3(0.0, half_size, 0.0));
 }
 
+void Creature::OnCollide(Creature &other) {
+       memory.TrackCollision(other);
+}
+
 glm::dmat4 Creature::LocalTransform() noexcept {
        const double half_size = size * 0.5;
        return CollisionTransform()
@@ -622,6 +716,7 @@ void Spawn(Creature &c, world::Planet &p) {
        p.AddCreature(&c);
        c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
        c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
+       c.HeadingTarget(glm::dvec3(1.0, 0.0, 0.0));
 
        // probe surrounding area for common resources
        int start = p.SideLength() / 2 - 2;
@@ -740,7 +835,7 @@ void Split(Creature &c) {
        // TODO: duplicate situation somehow
        a->GetSituation().SetPlanetSurface(
                s.GetPlanet(),
-               s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
+               s.Position() + glm::rotate(s.Heading() * a->Size() * 0.86, PI * 0.5, s.SurfaceNormal()));
        a->BuildVAO();
        c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
 
@@ -754,7 +849,7 @@ void Split(Creature &c) {
        s.GetPlanet().AddCreature(b);
        b->GetSituation().SetPlanetSurface(
                s.GetPlanet(),
-               s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
+               s.Position() + glm::rotate(s.Heading() * b->Size() * 0.86, PI * -0.5, s.SurfaceNormal()));
        b->BuildVAO();
        c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
 
@@ -771,6 +866,53 @@ Memory::~Memory() {
 
 void Memory::Erase() {
        known_types.clear();
+       known_creatures.clear();
+}
+
+bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
+       double best_rating = -1.0;
+       for (const auto &k : known_types) {
+               const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
+               auto entry = t.FindBestResource(accept);
+               if (entry != t.resources.end()) {
+                       double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
+                       if (rating > best_rating) {
+                               best_rating = rating;
+                               pos = k.second.first_loc.position;
+                       }
+                       rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
+                       if (rating > best_rating) {
+                               best_rating = rating;
+                               pos = k.second.last_loc.position;
+                       }
+               }
+       }
+       if (best_rating > 0.0) {
+               glm::dvec3 error(
+                       c.GetSimulation().Assets().random.SNorm(),
+                       c.GetSimulation().Assets().random.SNorm(),
+                       c.GetSimulation().Assets().random.SNorm());
+               pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
+               pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
+               return true;
+       } else {
+               return false;
+       }
+}
+
+void Memory::TrackCollision(Creature &other) {
+       // TODO: find out whose fault it was
+       // TODO: source values from personality
+       Profile &p = known_creatures[&other];
+       p.annoyance += 0.1;
+       const double annoy_fact = p.annoyance / (p.annoyance + 1.0);
+       if (c.GetSimulation().Assets().random.UNorm() > annoy_fact * 0.1 * (1.0 - c.GetStats().Damage().value)) {
+               AttackGoal *g = new AttackGoal(c, other);
+               g->SetDamageTarget(annoy_fact);
+               g->Urgency(annoy_fact);
+               c.AddGoal(std::unique_ptr<Goal>(g));
+               p.annoyance *= 0.5;
+       }
 }
 
 void Memory::Tick(double dt) {
@@ -778,6 +920,7 @@ void Memory::Tick(double dt) {
        if (s.OnSurface()) {
                TrackStay({ &s.GetPlanet(), s.Position() }, dt);
        }
+       // TODO: forget
 }
 
 void Memory::TrackStay(const Location &l, double t) {
@@ -843,6 +986,14 @@ bool Situation::OnSurface() const noexcept {
        return type == PLANET_SURFACE;
 }
 
+bool Situation::OnGround() const noexcept {
+       return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
+}
+
+glm::dvec3 Situation::SurfaceNormal() const noexcept {
+       return planet->NormalAt(state.pos);
+}
+
 world::Tile &Situation::GetTile() const noexcept {
        return planet->TileAt(state.pos);
 }
@@ -861,11 +1012,13 @@ void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
        EnforceConstraints(state);
 }
 
-void Situation::EnforceConstraints(State &s) noexcept {
+void Situation::EnforceConstraints(State &s) const noexcept {
        if (OnSurface()) {
                double r = GetPlanet().Radius();
-               if (length2(s.pos) < r * r) {
-                       s.pos = normalize(s.pos) * r;
+               if (glm::length2(s.pos) < r * r) {
+                       const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
+                       s.pos = normal * r;
+                       s.vel -= normal * glm::dot(normal, s.vel);
                }
        }
 }
@@ -947,32 +1100,36 @@ glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
                for (auto &other : s.GetPlanet().Creatures()) {
                        if (&*other == &c) continue;
                        glm::dvec3 diff = s.Position() - other->GetSituation().Position();
-                       if (length2(diff) > max_look * max_look) continue;
+                       if (glm::length2(diff) > max_look * max_look) continue;
                        if (!c.PerceptionTest(other->GetSituation().Position())) continue;
-                       double sep = glm::clamp(length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
-                       repulse += normalize(diff) * (1.0 - sep / min_dist) * force;
+                       double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
+                       repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
                }
                result += repulse;
        }
        if (halting) {
-               // break twice as hard
-               result += -2.0 * s.vel * force;
+               // brake hard
+               result += -5.0 * s.vel * force;
        }
        if (seeking) {
                glm::dvec3 diff = target - s.pos;
                if (!allzero(diff)) {
-                       result += TargetVelocity(s, (normalize(diff) * speed), force);
+                       result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
                }
        }
        if (arriving) {
                glm::dvec3 diff = target - s.pos;
-               double dist = length(diff);
+               double dist = glm::length(diff);
                if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
                        result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
                }
        }
-       if (length2(result) > max_force * max_force) {
-               result = normalize(result) * max_force;
+       // remove vertical component, if any
+       const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
+       result -= normal * glm::dot(normal, result);
+       // clamp to max
+       if (glm::length2(result) > max_force * max_force) {
+               result = glm::normalize(result) * max_force;
        }
        return result;
 }