1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "BlobBackgroundTask.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../ui/string.hpp"
15 #include "../world/Body.hpp"
16 #include "../world/Planet.hpp"
17 #include "../world/Simulation.hpp"
18 #include "../world/TileType.hpp"
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
26 #include <glm/gtx/io.hpp>
32 Composition::Composition()
37 Composition::~Composition() {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42 return b.value < a.value;
46 void Composition::Add(int res, double amount) {
48 for (auto c = components.begin(); c != components.end(); ++c) {
49 if (c->resource == res) {
51 if (c->value <= 0.0) {
58 if (!found && amount > 0.0) {
59 components.emplace_back(res, amount);
61 std::sort(components.begin(), components.end(), CompositionCompare);
65 bool Composition::Has(int res) const noexcept {
66 for (auto &c : components) {
67 if (c.resource == res) {
74 double Composition::Get(int res) const noexcept {
75 for (auto &c : components) {
76 if (c.resource == res) {
84 Creature::Creature(world::Simulation &sim)
91 , highlight_color(0.0, 0.0, 0.0, 1.0)
107 // all creatures avoid each other for now
108 steering.Separate(0.1, 1.5);
111 Creature::~Creature() {
114 void Creature::AddMass(int res, double amount) {
115 composition.Add(res, amount);
116 double nonsolid = 0.0;
118 for (const auto &c : composition) {
119 volume += c.value / sim.Assets().data.resources[c.resource].density;
120 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
124 Mass(composition.TotalMass());
125 Size(std::cbrt(volume));
126 highlight_color.a = nonsolid / composition.TotalMass();
129 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
130 highlight_color = glm::dvec4(c, highlight_color.a);
133 void Creature::Ingest(int res, double amount) noexcept {
134 // TODO: check foreign materials
135 if (sim.Resources()[res].state == world::Resource::SOLID) {
136 // 15% of solids stays in body
137 AddMass(res, amount * 0.15);
139 // 10% of fluids stays in body
140 AddMass(res, amount * 0.05);
144 void Creature::DoWork(double amount) noexcept {
145 stats.Exhaustion().Add(amount / Stamina());
146 // burn resources proportional to composition
147 // factor = 1/total * 1/efficiency * amount * -1
148 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
149 // make a copy to total remains constant and
150 // no entries disappear during iteration
151 Composition comp(composition);
152 for (auto &cmp : comp) {
153 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
154 AddMass(cmp.resource, value);
158 void Creature::Hurt(double amount) noexcept {
159 stats.Damage().Add(amount);
160 if (stats.Damage().Full()) {
161 std::cout << "[" << ui::TimeString(sim.Time()) << "] " << name << " ";
162 if (stats.Exhaustion().Full()) {
163 std::cout << "died of exhaustion";
164 } else if (stats.Breath().Full()) {
165 std::cout << "suffocated";
166 } else if (stats.Thirst().Full()) {
167 std::cout << "died of thirst";
168 } else if (stats.Hunger().Full()) {
169 std::cout << "starved to death";
171 std::cout << "succumed to wounds";
173 std::cout << " at an age of " << ui::TimeString(Age())
174 << " (" << ui::PercentageString(Age() / properties.Lifetime())
175 << "% of life expectancy of " << ui::TimeString(properties.Lifetime())
181 void Creature::Die() noexcept {
191 void Creature::Remove() noexcept {
195 void Creature::Removed() noexcept {
202 void Creature::AddParent(Creature &p) {
203 parents.push_back(&p);
206 double Creature::Age() const noexcept {
207 return sim.Time() - birth;
210 double Creature::AgeFactor(double peak) const noexcept {
211 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
212 // goes negative below -0.5 and starts to rise again above 1.0
213 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
214 // guarantee at least 1%
215 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
218 double Creature::EnergyEfficiency() const noexcept {
219 return 0.25 * AgeFactor(0.05);
222 double Creature::ExhaustionFactor() const noexcept {
223 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
226 double Creature::FatigueFactor() const noexcept {
227 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
230 double Creature::Strength() const noexcept {
231 // TODO: replace all age factors with actual growth and decay
232 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
235 double Creature::Stamina() const noexcept {
236 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
239 double Creature::Dexerty() const noexcept {
240 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
243 double Creature::Intelligence() const noexcept {
244 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
247 double Creature::Lifetime() const noexcept {
248 return properties.Lifetime();
251 double Creature::Fertility() const noexcept {
252 return properties.Fertility() * AgeFactor(0.25);
255 double Creature::Mutability() const noexcept {
256 return properties.Mutability();
259 double Creature::OffspringMass() const noexcept {
260 return properties.OffspringMass();
263 double Creature::OffspringChance() const noexcept {
264 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
267 double Creature::MutateChance() const noexcept {
268 return GetProperties().Mutability() * (1.0 / 3600.0);
271 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
273 goals.emplace_back(std::move(g));
278 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
279 return b->Urgency() < a->Urgency();
284 void Creature::Tick(double dt) {
290 void Creature::TickState(double dt) {
291 steering.MaxSpeed(Dexerty());
292 steering.MaxForce(Strength());
293 Situation::State state(situation.GetState());
294 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
295 Situation::Derivative b(Step(a, dt * 0.5));
296 Situation::Derivative c(Step(b, dt * 0.5));
297 Situation::Derivative d(Step(c, dt));
298 Situation::Derivative f(
299 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
300 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
302 state.pos += f.vel * dt;
303 state.vel += f.acc * dt;
304 situation.EnforceConstraints(state);
305 if (length2(state.vel) > 0.000001) {
306 glm::dvec3 nvel(normalize(state.vel));
307 double ang = angle(nvel, state.dir);
308 double turn_rate = PI * 0.75 * dt;
309 if (ang < turn_rate) {
310 state.dir = normalize(state.vel);
311 } else if (std::abs(ang - PI) < 0.001) {
312 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
314 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
317 situation.SetState(state);
318 // work is force times distance
319 DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
322 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
323 Situation::State s = situation.GetState();
324 s.pos += ds.vel * dt;
325 s.vel += ds.acc * dt;
326 glm::dvec3 force(steering.Force(s));
327 // gravity = antinormal * mass * Gm / r²
328 double elevation = s.pos[(situation.Surface() + 2) % 3];
329 glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
332 * Mass() * situation.GetPlanet().GravitationalParameter()
333 / (elevation * elevation));
334 // if net force is applied and in contact with surface
335 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
336 // apply friction = -|normal force| * tangential force * coefficient
337 glm::dvec3 fn(normal * dot(force, normal));
338 glm::dvec3 ft(force - fn);
340 glm::dvec3 friction(-length(fn) * ft * u);
349 void Creature::TickStats(double dt) {
350 for (auto &s : stats.stat) {
353 stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
354 // TODO: damage values depending on properties
355 if (stats.Breath().Full()) {
356 constexpr double dps = 1.0 / 4.0;
359 if (stats.Thirst().Full()) {
360 constexpr double dps = 1.0 / 32.0;
363 if (stats.Hunger().Full()) {
364 constexpr double dps = 1.0 / 128.0;
367 if (!situation.Moving()) {
368 // double exhaustion recovery when standing still
369 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
373 void Creature::TickBrain(double dt) {
377 // do background stuff
381 for (auto &goal : goals) {
384 // if active goal can be interrupted, check priorities
385 if (goals.size() > 1 && goals[0]->Interruptible()) {
386 std::sort(goals.begin(), goals.end(), GoalCompare);
389 for (auto goal = goals.begin(); goal != goals.end();) {
390 if ((*goal)->Complete()) {
398 math::AABB Creature::CollisionBox() const noexcept {
399 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
402 glm::dmat4 Creature::CollisionTransform() const noexcept {
403 const double half_size = size * 0.5;
404 const glm::dvec3 &pos = situation.Position();
405 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
406 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
407 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
411 glm::dmat4 Creature::LocalTransform() noexcept {
412 const double half_size = size * 0.5;
413 return CollisionTransform()
414 * glm::scale(glm::dvec3(half_size, half_size, half_size));
417 void Creature::BuildVAO() {
418 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
420 vao->BindAttributes();
421 vao->EnableAttribute(0);
422 vao->EnableAttribute(1);
423 vao->EnableAttribute(2);
424 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
425 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
426 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
427 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
429 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
430 const float offset = 1.0f;
431 for (int surface = 0; surface < 6; ++surface) {
432 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
433 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
435 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
436 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
437 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
438 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
439 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
440 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
441 attrib[4 * surface + 0].texture.x = tex_u_begin;
442 attrib[4 * surface + 0].texture.y = 1.0f;
443 attrib[4 * surface + 0].texture.z = surface;
445 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
446 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
447 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
448 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
449 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
450 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
451 attrib[4 * surface + 1].texture.x = tex_u_end;
452 attrib[4 * surface + 1].texture.y = 1.0f;
453 attrib[4 * surface + 1].texture.z = surface;
455 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
456 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
457 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
458 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
459 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
460 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
461 attrib[4 * surface + 2].texture.x = tex_u_begin;
462 attrib[4 * surface + 2].texture.y = 0.0f;
463 attrib[4 * surface + 2].texture.z = surface;
465 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
466 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
467 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
468 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
469 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
470 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
471 attrib[4 * surface + 3].texture.x = tex_u_end;
472 attrib[4 * surface + 3].texture.y = 0.0f;
473 attrib[4 * surface + 3].texture.z = surface;
477 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
479 auto element = vao->MapElements(GL_WRITE_ONLY);
480 for (int surface = 0; surface < 3; ++surface) {
481 element[6 * surface + 0] = 4 * surface + 0;
482 element[6 * surface + 1] = 4 * surface + 2;
483 element[6 * surface + 2] = 4 * surface + 1;
484 element[6 * surface + 3] = 4 * surface + 1;
485 element[6 * surface + 4] = 4 * surface + 2;
486 element[6 * surface + 5] = 4 * surface + 3;
488 for (int surface = 3; surface < 6; ++surface) {
489 element[6 * surface + 0] = 4 * surface + 0;
490 element[6 * surface + 1] = 4 * surface + 1;
491 element[6 * surface + 2] = 4 * surface + 2;
492 element[6 * surface + 3] = 4 * surface + 2;
493 element[6 * surface + 4] = 4 * surface + 1;
494 element[6 * surface + 5] = 4 * surface + 3;
500 void Creature::KillVAO() {
504 void Creature::Draw(graphics::Viewport &viewport) {
507 vao->DrawTriangles(6 * 6);
511 void Spawn(Creature &c, world::Planet &p) {
513 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
514 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
516 // probe surrounding area for common resources
517 int start = p.SideLength() / 2 - 2;
519 std::map<int, double> yields;
520 for (int y = start; y < end; ++y) {
521 for (int x = start; x < end; ++x) {
522 const world::TileType &t = p.TypeAt(0, x, y);
523 for (auto yield : t.resources) {
524 yields[yield.resource] += yield.ubiquity;
530 for (auto e : yields) {
531 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
532 if (liquid < 0 || e.second > yields[liquid]) {
535 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
536 if (solid < 0 || e.second > yields[solid]) {
543 genome.properties.Strength() = { 2.0, 0.1 };
544 genome.properties.Stamina() = { 2.0, 0.1 };
545 genome.properties.Dexerty() = { 2.0, 0.1 };
546 genome.properties.Intelligence() = { 1.0, 0.1 };
547 genome.properties.Lifetime() = { 480.0, 60.0 };
548 genome.properties.Fertility() = { 0.5, 0.03 };
549 genome.properties.Mutability() = { 1.0, 0.1 };
550 genome.properties.OffspringMass() = { 0.3, 0.02 };
552 glm::dvec3 color_avg(0.0);
553 double color_divisor = 0.0;
555 if (p.HasAtmosphere()) {
556 c.AddMass(p.Atmosphere(), 0.01);
557 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
558 color_divisor += 0.1;
561 c.AddMass(liquid, 0.3);
562 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
563 color_divisor += 0.5;
566 c.AddMass(solid, 0.1);
567 color_avg += c.GetSimulation().Resources()[solid].base_color;
568 color_divisor += 1.0;
571 if (color_divisor > 0.001) {
572 color_avg /= color_divisor;
574 glm::dvec3 hsl = rgb2hsl(color_avg);
575 genome.base_hue = { hsl.x, 0.01 };
576 genome.base_saturation = { hsl.y, 0.01 };
577 genome.base_lightness = { hsl.z, 0.01 };
582 void Genome::Configure(Creature &c) const {
583 c.GetGenome() = *this;
585 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
587 c.GetProperties() = Instantiate(properties, random);
589 // TODO: derive stats from properties
590 c.GetStats().Damage().gain = (-1.0 / 100.0);
591 c.GetStats().Breath().gain = (1.0 / 5.0);
592 c.GetStats().Thirst().gain = (1.0 / 60.0);
593 c.GetStats().Hunger().gain = (1.0 / 200.0);
594 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
595 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
596 c.GetStats().Boredom().gain = (1.0 / 300.0);
598 glm::dvec3 base_color(
599 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
600 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
601 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
603 glm::dvec3 highlight_color(
604 std::fmod(base_color.x + 0.5, 1.0),
608 c.BaseColor(hsl2rgb(base_color));
609 c.HighlightColor(hsl2rgb(highlight_color));
610 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
611 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
615 void Split(Creature &c) {
616 Creature *a = new Creature(c.GetSimulation());
617 const Situation &s = c.GetSituation();
619 a->Name(c.GetSimulation().Assets().name.Sequential());
620 c.GetGenome().Configure(*a);
621 for (const auto &cmp : c.GetComposition()) {
622 a->AddMass(cmp.resource, cmp.value * 0.5);
624 s.GetPlanet().AddCreature(a);
625 // TODO: duplicate situation somehow
626 a->GetSituation().SetPlanetSurface(
627 s.GetPlanet(), s.Surface(),
628 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
630 std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
631 << a->Name() << " was born" << std::endl;
633 Creature *b = new Creature(c.GetSimulation());
635 b->Name(c.GetSimulation().Assets().name.Sequential());
636 c.GetGenome().Configure(*b);
637 for (const auto &cmp : c.GetComposition()) {
638 b->AddMass(cmp.resource, cmp.value * 0.5);
640 s.GetPlanet().AddCreature(b);
641 b->GetSituation().SetPlanetSurface(
642 s.GetPlanet(), s.Surface(),
643 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
645 std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
646 << b->Name() << " was born" << std::endl;
652 Memory::Memory(Creature &c)
659 void Memory::Erase() {
663 void Memory::Tick(double dt) {
664 Situation &s = c.GetSituation();
666 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
670 void Memory::TrackStay(const Location &l, double t) {
671 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
672 auto entry = known_types.find(type.id);
673 if (entry != known_types.end()) {
674 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
676 if (entry->second.time_spent > c.Age() * 0.25) {
677 // the place is very familiar
678 c.GetStats().Boredom().Add(-0.2);
681 c.GetStats().Boredom().Add(-0.1);
684 entry->second.last_been = c.GetSimulation().Time();
685 entry->second.last_loc = l;
686 entry->second.time_spent += t;
688 known_types.emplace(type.id, Stay{
689 c.GetSimulation().Time(),
691 c.GetSimulation().Time(),
695 // completely new place, interesting
696 // TODO: scale by personality trait
697 c.GetStats().Boredom().Add(-0.25);
702 NameGenerator::NameGenerator()
706 NameGenerator::~NameGenerator() {
709 std::string NameGenerator::Sequential() {
710 std::stringstream ss;
711 ss << "Blob " << ++counter;
716 Situation::Situation()
718 , state(glm::dvec3(0.0), glm::dvec3(0.0))
723 Situation::~Situation() {
726 bool Situation::OnPlanet() const noexcept {
727 return type == PLANET_SURFACE;
730 bool Situation::OnSurface() const noexcept {
731 return type == PLANET_SURFACE;
734 bool Situation::OnTile() const noexcept {
735 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
736 return type == PLANET_SURFACE
737 && t.x >= 0 && t.x < planet->SideLength()
738 && t.y >= 0 && t.y < planet->SideLength();
741 glm::ivec2 Situation::SurfacePosition() const noexcept {
742 return planet->SurfacePosition(surface, state.pos);
745 world::Tile &Situation::GetTile() const noexcept {
746 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
747 return planet->TileAt(surface, t.x, t.y);
750 const world::TileType &Situation::GetTileType() const noexcept {
751 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
752 return planet->TypeAt(surface, t.x, t.y);
755 void Situation::Move(const glm::dvec3 &dp) noexcept {
757 EnforceConstraints(state);
760 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
762 EnforceConstraints(state);
765 void Situation::EnforceConstraints(State &s) noexcept {
768 if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
769 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
770 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
773 if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
774 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
775 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
781 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
782 type = PLANET_SURFACE;
786 EnforceConstraints(state);
790 Steering::Steering(const Creature &c)
804 Steering::~Steering() {
807 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
809 min_dist = min_distance;
810 max_look = max_lookaround;
813 void Steering::DontSeparate() noexcept {
817 void Steering::ResumeSeparate() noexcept {
821 void Steering::Halt() noexcept {
827 void Steering::Pass(const glm::dvec3 &t) noexcept {
834 void Steering::GoTo(const glm::dvec3 &t) noexcept {
841 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
842 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
843 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
844 glm::dvec3 result(0.0);
846 // TODO: off surface situation
847 glm::dvec3 repulse(0.0);
848 const Situation &s = c.GetSituation();
849 for (auto &other : s.GetPlanet().Creatures()) {
850 if (&*other == &c) continue;
851 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
852 if (length2(diff) > max_look * max_look) continue;
853 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
854 if (sep < min_dist) {
855 repulse += normalize(diff) * (1.0 - sep / min_dist);
858 SumForce(result, repulse, force);
861 // break twice as hard
862 SumForce(result, s.vel * force * -2.0, force);
865 glm::dvec3 diff = target - s.pos;
866 if (!allzero(diff)) {
867 SumForce(result, TargetVelocity(s, (normalize(diff) * speed), force), force);
871 glm::dvec3 diff = target - s.pos;
872 double dist = length(diff);
873 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
874 SumForce(result, TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force), force);
880 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
881 if (allzero(in) || anynan(in)) {
884 double cur = allzero(out) ? 0.0 : length(out);
885 double rem = max - cur;
889 double add = length(in);
891 // this method is off if in and out are in different
892 // directions, but gives okayish results
893 out += in * (1.0 / add);
901 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
902 return (vel - s.vel) * acc;