2 #include "CreatureCreatureCollision.hpp"
5 #include "Resource.hpp"
7 #include "Simulation.hpp"
10 #include "TileType.hpp"
12 #include "../app/Assets.hpp"
13 #include "../creature/Composition.hpp"
14 #include "../creature/Creature.hpp"
15 #include "../graphics/Viewport.hpp"
16 #include "../math/const.hpp"
17 #include "../math/geometry.hpp"
18 #include "../math/OctaveNoise.hpp"
19 #include "../math/SimplexNoise.hpp"
24 #include <glm/gtc/matrix_transform.hpp>
25 #include <glm/gtx/euler_angles.hpp>
26 #include <glm/gtx/io.hpp>
27 #include <glm/gtx/transform.hpp>
48 , surface_tilt(0.0, 0.0)
53 , inverse_orbital(1.0)
61 for (creature::Creature *c : creatures) {
66 void Body::SetSimulation(Simulation &s) noexcept {
68 for (auto child : children) {
69 child->SetSimulation(s);
73 void Body::SetParent(Body &p) {
78 parent->AddChild(*this);
81 void Body::UnsetParent() {
82 if (!HasParent()) return;
83 parent->RemoveChild(*this);
87 void Body::AddChild(Body &c) {
88 children.push_back(&c);
89 c.SetSimulation(*sim);
92 void Body::RemoveChild(Body &c) {
93 auto entry = std::find(children.begin(), children.end(), &c);
94 if (entry != children.end()) {
95 children.erase(entry);
99 double Body::Inertia() const noexcept {
100 // assume solid sphere for now
101 return (2.0/5.0) * Mass() * pow(Radius(), 2);
104 double Body::GravitationalParameter() const noexcept {
108 double Body::OrbitalPeriod() const noexcept {
110 return PI_2p0 * sqrt(pow(orbit.SemiMajorAxis(), 3) / (G * (parent->Mass() + Mass())));
116 double Body::RotationalPeriod() const noexcept {
117 if (std::abs(angular) < std::numeric_limits<double>::epsilon()) {
118 return std::numeric_limits<double>::infinity();
120 return PI_2p0 * Inertia() / angular;
124 glm::dmat4 Body::ToUniverse() const noexcept {
126 const Body *b = this;
127 while (b->HasParent()) {
128 m = b->ToParent() * m;
134 glm::dmat4 Body::FromUniverse() const noexcept {
136 const Body *b = this;
137 while (b->HasParent()) {
138 m *= b->FromParent();
145 std::vector<creature::Creature *> ccache;
146 std::vector<CreatureCreatureCollision> collisions;
149 void Body::Tick(double dt) {
150 rotation += dt * AngularMomentum() / Inertia();
152 ccache = Creatures();
153 for (creature::Creature *c : ccache) {
156 // first remove creatures so they don't collide
157 for (auto c = Creatures().begin(); c != Creatures().end();) {
158 if ((*c)->Removable()) {
160 c = Creatures().erase(c);
168 void Body::Cache() noexcept {
171 orbit.Matrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()))
172 * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
174 glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
175 * orbit.InverseMatrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()));
177 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
178 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
181 glm::eulerAngleY(rotation)
182 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
184 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
185 * glm::eulerAngleY(-rotation);
188 void Body::CheckCollision() noexcept {
189 if (Creatures().size() < 2) return;
191 auto end = Creatures().end();
192 for (auto i = Creatures().begin(); i != end; ++i) {
193 math::AABB i_box((*i)->CollisionBox());
194 glm::dmat4 i_mat((*i)->CollisionTransform());
195 for (auto j = (i + 1); j != end; ++j) {
196 glm::dvec3 diff((*i)->GetSituation().Position() - (*j)->GetSituation().Position());
197 double max_dist = ((*i)->Size() + (*j)->Size()) * 1.74;
198 if (length2(diff) > max_dist * max_dist) continue;
199 math::AABB j_box((*j)->CollisionBox());
200 glm::dmat4 j_mat((*j)->CollisionTransform());
203 if (Intersect(i_box, i_mat, j_box, j_mat, normal, depth)) {
204 collisions.push_back({ **i, **j, normal, depth });
208 for (auto &c : collisions) {
209 c.A().GetSituation().Move(c.Normal() * (c.Depth() * -0.5));
210 c.B().GetSituation().Move(c.Normal() * (c.Depth() * 0.5));
211 c.A().GetSituation().Accelerate(c.Normal() * -dot(c.Normal(), c.AVel()));
212 c.B().GetSituation().Accelerate(c.Normal() * -dot(c.Normal(), c.BVel()));
213 // TODO: notify participants so they can be annoyed
217 void Body::AddCreature(creature::Creature *c) {
218 creatures.push_back(c);
221 void Body::RemoveCreature(creature::Creature *c) {
222 auto entry = std::find(creatures.begin(), creatures.end(), c);
223 if (entry != creatures.end()) {
224 creatures.erase(entry);
229 CreatureCreatureCollision::~CreatureCreatureCollision() {
232 const glm::dvec3 &CreatureCreatureCollision::APos() const noexcept {
233 return a->GetSituation().Position();
236 const glm::dvec3 &CreatureCreatureCollision::AVel() const noexcept {
237 return a->GetSituation().Velocity();
240 const glm::dvec3 &CreatureCreatureCollision::BPos() const noexcept {
241 return b->GetSituation().Position();
244 const glm::dvec3 &CreatureCreatureCollision::BVel() const noexcept {
245 return b->GetSituation().Velocity();
261 double Orbit::SemiMajorAxis() const noexcept {
265 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
270 double Orbit::Eccentricity() const noexcept {
274 Orbit &Orbit::Eccentricity(double e) noexcept {
279 double Orbit::Inclination() const noexcept {
283 Orbit &Orbit::Inclination(double i) noexcept {
288 double Orbit::LongitudeAscending() const noexcept {
292 Orbit &Orbit::LongitudeAscending(double l) noexcept {
297 double Orbit::ArgumentPeriapsis() const noexcept {
301 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
306 double Orbit::MeanAnomaly() const noexcept {
310 Orbit &Orbit::MeanAnomaly(double m) noexcept {
317 double mean2eccentric(double M, double e) {
318 double E = M; // eccentric anomaly, solve M = E - e sin E
319 // limit to 100 steps to prevent deadlocks in impossible situations
320 for (int i = 0; i < 100; ++i) {
321 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
323 if (abs(dE) < 1.0e-6) break;
330 glm::dmat4 Orbit::Matrix(double t) const noexcept {
332 double E = mean2eccentric(M, ecc);
334 // coordinates in orbital plane, P=x, Q=-z
335 double P = sma * (cos(E) - ecc);
336 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
338 return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
341 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
343 double E = mean2eccentric(M, ecc);
344 double P = sma * (cos(E) - ecc);
345 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
346 return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
350 Planet::Planet(int sidelength)
352 , sidelength(sidelength)
353 , tiles(TilesTotal())
355 Radius(double(sidelength) / 2.0);
361 const TileType &Planet::TypeAt(int srf, int x, int y) const {
362 return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
365 glm::ivec2 Planet::SurfacePosition(int srf, const glm::dvec3 &pos) const noexcept {
367 PositionToTile(pos[(srf + 0) % 3]),
368 PositionToTile(pos[(srf + 1) % 3]));
371 double Planet::SurfaceElevation(int srf, const glm::dvec3 &pos) const noexcept {
373 ? pos[(srf + 2) % 3] - Radius()
374 : -pos[(srf + 2) % 3] - Radius();
377 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
378 glm::dvec3 center(0.0f);
379 center[(srf + 0) % 3] = x + 0.5 - Radius();
380 center[(srf + 1) % 3] = y + 0.5 - Radius();
381 center[(srf + 2) % 3] = srf < 3 ? (Radius() + e) : -(Radius() + e);
385 void Planet::BuildVAO(const Set<TileType> &ts) {
386 vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
388 vao->BindAttributes();
389 vao->EnableAttribute(0);
390 vao->EnableAttribute(1);
391 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
392 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, tex_coord));
393 vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
395 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
396 float offset = Radius();
399 // up +Z +X +Y -Z -X -Y
401 for (int index = 0, surface = 0; surface < 6; ++surface) {
402 for (int y = 0; y < sidelength; ++y) {
403 for (int x = 0; x < sidelength; ++x, ++index) {
404 float tex = ts[TileAt(surface, x, y).type].texture;
405 const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
406 const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
407 attrib[4 * index + 0].position[(surface + 0) % 3] = x + 0 - offset;
408 attrib[4 * index + 0].position[(surface + 1) % 3] = y + 0 - offset;
409 attrib[4 * index + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
410 attrib[4 * index + 0].tex_coord[0] = 0.0f;
411 attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
412 attrib[4 * index + 0].tex_coord[2] = tex;
414 attrib[4 * index + 1].position[(surface + 0) % 3] = x + 0 - offset;
415 attrib[4 * index + 1].position[(surface + 1) % 3] = y + 1 - offset;
416 attrib[4 * index + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
417 attrib[4 * index + 1].tex_coord[0] = 0.0f;
418 attrib[4 * index + 1].tex_coord[1] = tex_v_end;
419 attrib[4 * index + 1].tex_coord[2] = tex;
421 attrib[4 * index + 2].position[(surface + 0) % 3] = x + 1 - offset;
422 attrib[4 * index + 2].position[(surface + 1) % 3] = y + 0 - offset;
423 attrib[4 * index + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
424 attrib[4 * index + 2].tex_coord[0] = 1.0f;
425 attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
426 attrib[4 * index + 2].tex_coord[2] = tex;
428 attrib[4 * index + 3].position[(surface + 0) % 3] = x + 1 - offset;
429 attrib[4 * index + 3].position[(surface + 1) % 3] = y + 1 - offset;
430 attrib[4 * index + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
431 attrib[4 * index + 3].tex_coord[0] = 1.0f;
432 attrib[4 * index + 3].tex_coord[1] = tex_v_end;
433 attrib[4 * index + 3].tex_coord[2] = tex;
439 vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
441 auto element = vao->MapElements(GL_WRITE_ONLY);
443 for (int surface = 0; surface < 3; ++surface) {
444 for (int y = 0; y < sidelength; ++y) {
445 for (int x = 0; x < sidelength; ++x, ++index) {
446 element[6 * index + 0] = 4 * index + 0;
447 element[6 * index + 1] = 4 * index + 2;
448 element[6 * index + 2] = 4 * index + 1;
449 element[6 * index + 3] = 4 * index + 1;
450 element[6 * index + 4] = 4 * index + 2;
451 element[6 * index + 5] = 4 * index + 3;
455 for (int surface = 3; surface < 6; ++surface) {
456 for (int y = 0; y < sidelength; ++y) {
457 for (int x = 0; x < sidelength; ++x, ++index) {
458 element[6 * index + 0] = 4 * index + 0;
459 element[6 * index + 1] = 4 * index + 1;
460 element[6 * index + 2] = 4 * index + 2;
461 element[6 * index + 3] = 4 * index + 2;
462 element[6 * index + 4] = 4 * index + 1;
463 element[6 * index + 5] = 4 * index + 3;
471 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
475 const glm::mat4 &MV = assets.shaders.planet_surface.MV();
476 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f)));
477 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 0);
478 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(1.0f, 0.0f, 0.0f, 0.0f)));
479 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 1);
480 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)));
481 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 2);
482 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)));
483 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 3);
484 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f)));
485 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 4);
486 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, -1.0f, 0.0f, 0.0f)));
487 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 5);
491 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
492 math::SimplexNoise elevation_gen(0);
493 math::SimplexNoise variation_gen(45623752346);
495 const int ice = tiles["ice"].id;
496 const int ocean = tiles["ocean"].id;
497 const int water = tiles["water"].id;
498 const int sand = tiles["sand"].id;
499 const int grass = tiles["grass"].id;
500 const int tundra = tiles["tundra"].id;
501 const int taiga = tiles["taiga"].id;
502 const int desert = tiles["desert"].id;
503 const int mntn = tiles["mountain"].id;
504 const int algae = tiles["algae"].id;
505 const int forest = tiles["forest"].id;
506 const int jungle = tiles["jungle"].id;
507 const int rock = tiles["rock"].id;
508 const int wheat = tiles["wheat"].id;
510 constexpr double ocean_thresh = -0.2;
511 constexpr double water_thresh = 0.0;
512 constexpr double beach_thresh = 0.05;
513 constexpr double highland_thresh = 0.4;
514 constexpr double mountain_thresh = 0.5;
516 const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
517 const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
518 const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
519 const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
520 const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
522 for (int surface = 0; surface <= 5; ++surface) {
523 for (int y = 0; y < p.SideLength(); ++y) {
524 for (int x = 0; x < p.SideLength(); ++x) {
525 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
526 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
527 if (near_axis > cap_thresh) {
528 p.TileAt(surface, x, y).type = ice;
531 float elevation = math::OctaveNoise(
533 to_tile / p.Radius(),
536 5 / p.Radius(), // frequency
540 float variation = math::OctaveNoise(
542 to_tile / p.Radius(),
545 16 / p.Radius(), // frequency
549 if (elevation < ocean_thresh) {
550 p.TileAt(surface, x, y).type = ocean;
551 } else if (elevation < water_thresh) {
552 if (variation > 0.3) {
553 p.TileAt(surface, x, y).type = algae;
555 p.TileAt(surface, x, y).type = water;
557 } else if (elevation < beach_thresh) {
558 p.TileAt(surface, x, y).type = sand;
559 } else if (elevation < highland_thresh) {
560 if (near_axis < equ_thresh) {
561 if (variation > 0.6) {
562 p.TileAt(surface, x, y).type = grass;
563 } else if (variation > 0.2) {
564 p.TileAt(surface, x, y).type = sand;
566 p.TileAt(surface, x, y).type = desert;
568 } else if (near_axis < fzone_start) {
569 if (variation > 0.4) {
570 p.TileAt(surface, x, y).type = forest;
571 } else if (variation < -0.5) {
572 p.TileAt(surface, x, y).type = jungle;
573 } else if (variation > -0.02 && variation < 0.02) {
574 p.TileAt(surface, x, y).type = wheat;
576 p.TileAt(surface, x, y).type = grass;
578 } else if (near_axis < fzone_end) {
579 p.TileAt(surface, x, y).type = tundra;
581 p.TileAt(surface, x, y).type = taiga;
583 } else if (elevation < mountain_thresh) {
584 if (variation > 0.3) {
585 p.TileAt(surface, x, y).type = mntn;
587 p.TileAt(surface, x, y).type = rock;
590 p.TileAt(surface, x, y).type = mntn;
598 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
599 for (int surface = 0; surface <= 5; ++surface) {
600 for (int y = 0; y < p.SideLength(); ++y) {
601 for (int x = 0; x < p.SideLength(); ++x) {
602 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
603 p.TileAt(surface, x, y).type = surface;
605 p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
622 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
623 auto yield = resources.cbegin();
624 for (; yield != resources.cend(); ++yield) {
625 if (yield->resource == r) {
632 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
633 auto best = resources.cend();
634 double best_value = 0.0;
635 for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
636 double value = comp.Get(yield->resource);
637 if (value > best_value) {