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>
45 , surface_tilt(0.0, 0.0)
50 , inverse_orbital(1.0)
60 void Body::SetSimulation(Simulation &s) noexcept {
62 for (auto child : children) {
63 child->SetSimulation(s);
67 void Body::SetParent(Body &p) {
72 parent->AddChild(*this);
75 void Body::UnsetParent() {
76 if (!HasParent()) return;
77 parent->RemoveChild(*this);
81 void Body::AddChild(Body &c) {
82 children.push_back(&c);
83 c.SetSimulation(*sim);
86 void Body::RemoveChild(Body &c) {
87 auto entry = std::find(children.begin(), children.end(), &c);
88 if (entry != children.end()) {
89 children.erase(entry);
93 double Body::Inertia() const noexcept {
94 // assume solid sphere for now
95 return (2.0/5.0) * Mass() * pow(Radius(), 2);
98 double Body::GravitationalParameter() const noexcept {
102 double Body::OrbitalPeriod() const noexcept {
104 return PI * 2.0 * sqrt(pow(orbit.SemiMajorAxis(), 3) / (G * (parent->Mass() + Mass())));
110 double Body::RotationalPeriod() const noexcept {
111 if (std::abs(angular) < std::numeric_limits<double>::epsilon()) {
112 return std::numeric_limits<double>::infinity();
114 return PI * 2.0 * Inertia() / angular;
118 glm::dmat4 Body::ToUniverse() const noexcept {
120 const Body *b = this;
121 while (b->HasParent()) {
122 m = b->ToParent() * m;
128 glm::dmat4 Body::FromUniverse() const noexcept {
130 const Body *b = this;
131 while (b->HasParent()) {
132 m *= b->FromParent();
139 std::vector<creature::Creature *> ccache;
140 std::vector<CreatureCreatureCollision> collisions;
143 void Body::Tick(double dt) {
144 rotation += dt * AngularMomentum() / Inertia();
146 ccache = Creatures();
147 for (creature::Creature *c : ccache) {
150 // first remove creatures so they don't collide
151 for (auto c = Creatures().begin(); c != Creatures().end();) {
152 if ((*c)->Removable()) {
154 c = Creatures().erase(c);
162 void Body::Cache() noexcept {
165 orbit.Matrix(PI * 2.0 * (GetSimulation().Time() / OrbitalPeriod()))
166 * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
168 glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
169 * orbit.InverseMatrix(PI * 2.0 * (GetSimulation().Time() / OrbitalPeriod()));
171 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
172 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
175 glm::eulerAngleY(rotation)
176 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
178 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
179 * glm::eulerAngleY(-rotation);
182 void Body::CheckCollision() noexcept {
183 if (Creatures().size() < 2) return;
185 auto end = Creatures().end();
186 for (auto i = Creatures().begin(); i != end; ++i) {
187 math::AABB i_box((*i)->CollisionBox());
188 glm::dmat4 i_mat((*i)->CollisionTransform());
189 for (auto j = (i + 1); j != end; ++j) {
190 glm::dvec3 diff((*i)->GetSituation().Position() - (*j)->GetSituation().Position());
191 double max_dist = ((*i)->Size() + (*j)->Size()) * 1.74;
192 if (glm::length2(diff) > max_dist * max_dist) continue;
193 math::AABB j_box((*j)->CollisionBox());
194 glm::dmat4 j_mat((*j)->CollisionTransform());
197 if (Intersect(i_box, i_mat, j_box, j_mat, normal, depth)) {
198 collisions.push_back({ **i, **j, normal, depth });
202 for (auto &c : collisions) {
203 c.A().GetSituation().Move(c.Normal() * (c.Depth() * -0.5));
204 c.B().GetSituation().Move(c.Normal() * (c.Depth() * 0.5));
205 c.A().GetSituation().Accelerate(c.Normal() * -glm::dot(c.Normal(), c.AVel()));
206 c.B().GetSituation().Accelerate(c.Normal() * -glm::dot(c.Normal(), c.BVel()));
207 // TODO: notify participants so they can be annoyed
211 void Body::AddCreature(creature::Creature *c) {
212 creatures.push_back(c);
215 void Body::RemoveCreature(creature::Creature *c) {
216 auto entry = std::find(creatures.begin(), creatures.end(), c);
217 if (entry != creatures.end()) {
218 creatures.erase(entry);
223 CreatureCreatureCollision::~CreatureCreatureCollision() {
226 const glm::dvec3 &CreatureCreatureCollision::APos() const noexcept {
227 return a->GetSituation().Position();
230 const glm::dvec3 &CreatureCreatureCollision::AVel() const noexcept {
231 return a->GetSituation().Velocity();
234 const glm::dvec3 &CreatureCreatureCollision::BPos() const noexcept {
235 return b->GetSituation().Position();
238 const glm::dvec3 &CreatureCreatureCollision::BVel() const noexcept {
239 return b->GetSituation().Velocity();
255 double Orbit::SemiMajorAxis() const noexcept {
259 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
264 double Orbit::Eccentricity() const noexcept {
268 Orbit &Orbit::Eccentricity(double e) noexcept {
273 double Orbit::Inclination() const noexcept {
277 Orbit &Orbit::Inclination(double i) noexcept {
282 double Orbit::LongitudeAscending() const noexcept {
286 Orbit &Orbit::LongitudeAscending(double l) noexcept {
291 double Orbit::ArgumentPeriapsis() const noexcept {
295 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
300 double Orbit::MeanAnomaly() const noexcept {
304 Orbit &Orbit::MeanAnomaly(double m) noexcept {
311 double mean2eccentric(double M, double e) {
312 double E = M; // eccentric anomaly, solve M = E - e sin E
313 // limit to 100 steps to prevent deadlocks in impossible situations
314 for (int i = 0; i < 100; ++i) {
315 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
317 if (std::abs(dE) < 1.0e-6) break;
324 glm::dmat4 Orbit::Matrix(double t) const noexcept {
326 double E = mean2eccentric(M, ecc);
328 // coordinates in orbital plane, P=x, Q=-z
329 double P = sma * (cos(E) - ecc);
330 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
332 return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
335 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
337 double E = mean2eccentric(M, ecc);
338 double P = sma * (cos(E) - ecc);
339 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
340 return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
344 Planet::Planet(int sidelength)
346 , sidelength(sidelength)
347 , tiles(TilesTotal())
349 Radius(double(sidelength) / 2.0);
356 /// map p onto cube, s gives the surface, u and v the position in [-1,1]
357 void cubemap(const glm::dvec3 &p, int &s, double &u, double &v) noexcept {
358 const glm::dvec3 p_abs(glm::abs(p));
359 const glm::bvec3 p_pos(glm::greaterThan(p, glm::dvec3(0.0)));
360 double max_axis = 0.0;
362 if (p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
368 if (!p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
374 if (p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
380 if (!p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
386 if (p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
392 if (!p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
401 /// get p from cube, s being surface, u and v the position in [-1,1],
402 /// gives a vector from the center to the surface
403 glm::dvec3 cubeunmap(int s, double u, double v) {
406 case 0: return glm::dvec3(u, v, 1.0); // +Z
407 case 1: return glm::dvec3(1.0, u, v); // +X
408 case 2: return glm::dvec3(v, 1.0, u); // +Y
409 case 3: return glm::dvec3(-u, -v, -1.0); // -Z
410 case 4: return glm::dvec3(-1.0, -u, -v); // -X
411 case 5: return glm::dvec3(-v, -1.0, -u); // -Y
416 Tile &Planet::TileAt(const glm::dvec3 &p) noexcept {
420 cubemap(p, srf, u, v);
421 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
422 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
423 return TileAt(srf, x, y);
426 const Tile &Planet::TileAt(const glm::dvec3 &p) const noexcept {
430 cubemap(p, srf, u, v);
431 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
432 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
433 return TileAt(srf, x, y);
436 const TileType &Planet::TileTypeAt(const glm::dvec3 &p) const noexcept {
437 return GetSimulation().TileTypes()[TileAt(p).type];
440 Tile &Planet::TileAt(int surface, int x, int y) noexcept {
441 return tiles[IndexOf(surface, x, y)];
444 const Tile &Planet::TileAt(int surface, int x, int y) const noexcept {
445 return tiles[IndexOf(surface, x, y)];
448 const TileType &Planet::TypeAt(int srf, int x, int y) const noexcept {
449 return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
452 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
453 double u = (double(x) - Radius() + 0.5) / Radius();
454 double v = (double(y) - Radius() + 0.5) / Radius();
455 return glm::normalize(cubeunmap(srf, u, v)) * (Radius() + e);
458 void Planet::BuildVAO(const Set<TileType> &ts) {
459 vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
461 vao->BindAttributes();
462 vao->EnableAttribute(0);
463 vao->EnableAttribute(1);
464 vao->EnableAttribute(2);
465 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
466 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
467 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, tex_coord));
468 vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
470 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
471 float offset = Radius();
474 // up +Z +X +Y -Z -X -Y
476 for (int index = 0, surface = 0; surface < 6; ++surface) {
477 for (int y = 0; y < sidelength; ++y) {
478 for (int x = 0; x < sidelength; ++x, ++index) {
480 pos[0][(surface + 0) % 3] = x + 0 - offset;
481 pos[0][(surface + 1) % 3] = y + 0 - offset;
482 pos[0][(surface + 2) % 3] = offset;
483 pos[1][(surface + 0) % 3] = x + 0 - offset;
484 pos[1][(surface + 1) % 3] = y + 1 - offset;
485 pos[1][(surface + 2) % 3] = offset;
486 pos[2][(surface + 0) % 3] = x + 1 - offset;
487 pos[2][(surface + 1) % 3] = y + 0 - offset;
488 pos[2][(surface + 2) % 3] = offset;
489 pos[3][(surface + 0) % 3] = x + 1 - offset;
490 pos[3][(surface + 1) % 3] = y + 1 - offset;
491 pos[3][(surface + 2) % 3] = offset;
493 float tex = ts[TileAt(surface, x, y).type].texture;
494 const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
495 const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
497 attrib[4 * index + 0].position = glm::normalize(pos[0]) * (surface < 3 ? offset : -offset);
498 attrib[4 * index + 0].normal = pos[0];
499 attrib[4 * index + 0].tex_coord[0] = 0.0f;
500 attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
501 attrib[4 * index + 0].tex_coord[2] = tex;
503 attrib[4 * index + 1].position = glm::normalize(pos[1]) * (surface < 3 ? offset : -offset);
504 attrib[4 * index + 1].normal = pos[1];
505 attrib[4 * index + 1].tex_coord[0] = 0.0f;
506 attrib[4 * index + 1].tex_coord[1] = tex_v_end;
507 attrib[4 * index + 1].tex_coord[2] = tex;
509 attrib[4 * index + 2].position = glm::normalize(pos[2]) * (surface < 3 ? offset : -offset);
510 attrib[4 * index + 2].normal = pos[2];
511 attrib[4 * index + 2].tex_coord[0] = 1.0f;
512 attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
513 attrib[4 * index + 2].tex_coord[2] = tex;
515 attrib[4 * index + 3].position = glm::normalize(pos[3]) * (surface < 3 ? offset : -offset);
516 attrib[4 * index + 3].normal = pos[3];
517 attrib[4 * index + 3].tex_coord[0] = 1.0f;
518 attrib[4 * index + 3].tex_coord[1] = tex_v_end;
519 attrib[4 * index + 3].tex_coord[2] = tex;
525 vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
527 auto element = vao->MapElements(GL_WRITE_ONLY);
529 for (int surface = 0; surface < 3; ++surface) {
530 for (int y = 0; y < sidelength; ++y) {
531 for (int x = 0; x < sidelength; ++x, ++index) {
532 element[6 * index + 0] = 4 * index + 0;
533 element[6 * index + 1] = 4 * index + 2;
534 element[6 * index + 2] = 4 * index + 1;
535 element[6 * index + 3] = 4 * index + 1;
536 element[6 * index + 4] = 4 * index + 2;
537 element[6 * index + 5] = 4 * index + 3;
541 for (int surface = 3; surface < 6; ++surface) {
542 for (int y = 0; y < sidelength; ++y) {
543 for (int x = 0; x < sidelength; ++x, ++index) {
544 element[6 * index + 0] = 4 * index + 0;
545 element[6 * index + 1] = 4 * index + 1;
546 element[6 * index + 2] = 4 * index + 2;
547 element[6 * index + 3] = 4 * index + 2;
548 element[6 * index + 4] = 4 * index + 1;
549 element[6 * index + 5] = 4 * index + 3;
557 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
561 vao->DrawTriangles(TilesTotal() * 6);
565 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
566 math::SimplexNoise elevation_gen(0);
567 math::SimplexNoise variation_gen(45623752346);
569 const int ice = tiles["ice"].id;
570 const int ocean = tiles["ocean"].id;
571 const int water = tiles["water"].id;
572 const int sand = tiles["sand"].id;
573 const int grass = tiles["grass"].id;
574 const int tundra = tiles["tundra"].id;
575 const int taiga = tiles["taiga"].id;
576 const int desert = tiles["desert"].id;
577 const int mntn = tiles["mountain"].id;
578 const int algae = tiles["algae"].id;
579 const int forest = tiles["forest"].id;
580 const int jungle = tiles["jungle"].id;
581 const int rock = tiles["rock"].id;
582 const int wheat = tiles["wheat"].id;
584 constexpr double ocean_thresh = -0.2;
585 constexpr double water_thresh = 0.0;
586 constexpr double beach_thresh = 0.05;
587 constexpr double highland_thresh = 0.4;
588 constexpr double mountain_thresh = 0.5;
590 const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
591 const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
592 const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
593 const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
594 const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
596 for (int surface = 0; surface <= 5; ++surface) {
597 for (int y = 0; y < p.SideLength(); ++y) {
598 for (int x = 0; x < p.SideLength(); ++x) {
599 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
600 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
601 if (near_axis > cap_thresh) {
602 p.TileAt(surface, x, y).type = ice;
605 float elevation = math::OctaveNoise(
607 glm::vec3(to_tile / p.Radius()),
610 5 / p.Radius(), // frequency
614 float variation = math::OctaveNoise(
616 glm::vec3(to_tile / p.Radius()),
619 16 / p.Radius(), // frequency
623 if (elevation < ocean_thresh) {
624 p.TileAt(surface, x, y).type = ocean;
625 } else if (elevation < water_thresh) {
626 if (variation > 0.3) {
627 p.TileAt(surface, x, y).type = algae;
629 p.TileAt(surface, x, y).type = water;
631 } else if (elevation < beach_thresh) {
632 p.TileAt(surface, x, y).type = sand;
633 } else if (elevation < highland_thresh) {
634 if (near_axis < equ_thresh) {
635 if (variation > 0.6) {
636 p.TileAt(surface, x, y).type = grass;
637 } else if (variation > 0.2) {
638 p.TileAt(surface, x, y).type = sand;
640 p.TileAt(surface, x, y).type = desert;
642 } else if (near_axis < fzone_start) {
643 if (variation > 0.4) {
644 p.TileAt(surface, x, y).type = forest;
645 } else if (variation < -0.5) {
646 p.TileAt(surface, x, y).type = jungle;
647 } else if (variation > -0.02 && variation < 0.02) {
648 p.TileAt(surface, x, y).type = wheat;
650 p.TileAt(surface, x, y).type = grass;
652 } else if (near_axis < fzone_end) {
653 p.TileAt(surface, x, y).type = tundra;
655 p.TileAt(surface, x, y).type = taiga;
657 } else if (elevation < mountain_thresh) {
658 if (variation > 0.3) {
659 p.TileAt(surface, x, y).type = mntn;
661 p.TileAt(surface, x, y).type = rock;
664 p.TileAt(surface, x, y).type = mntn;
672 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
673 for (int surface = 0; surface <= 5; ++surface) {
674 for (int y = 0; y < p.SideLength(); ++y) {
675 for (int x = 0; x < p.SideLength(); ++x) {
676 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
677 p.TileAt(surface, x, y).type = surface;
679 p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
696 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
697 auto yield = resources.cbegin();
698 for (; yield != resources.cend(); ++yield) {
699 if (yield->resource == r) {
706 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
707 auto best = resources.cend();
708 double best_value = 0.0;
709 for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
710 double value = comp.Get(yield->resource);
711 if (value > best_value) {