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 double Body::SphereOfInfluence() const noexcept {
120 return orbit.SemiMajorAxis() * std::pow(Mass() / Parent().Mass(), 2.0 / 5.0);
122 return std::numeric_limits<double>::infinity();
126 glm::dmat4 Body::ToUniverse() const noexcept {
128 const Body *b = this;
129 while (b->HasParent()) {
130 m = b->ToParent() * m;
136 glm::dmat4 Body::FromUniverse() const noexcept {
138 const Body *b = this;
139 while (b->HasParent()) {
140 m *= b->FromParent();
147 std::vector<creature::Creature *> ccache;
148 std::vector<CreatureCreatureCollision> collisions;
151 void Body::Tick(double dt) {
152 rotation += dt * AngularMomentum() / Inertia();
154 ccache = Creatures();
155 for (creature::Creature *c : ccache) {
158 // first remove creatures so they don't collide
159 for (auto c = Creatures().begin(); c != Creatures().end();) {
160 if ((*c)->Removable()) {
162 c = Creatures().erase(c);
170 void Body::Cache() noexcept {
173 orbit.Matrix(PI * 2.0 * (GetSimulation().Time() / OrbitalPeriod()))
174 * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
176 glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
177 * orbit.InverseMatrix(PI * 2.0 * (GetSimulation().Time() / OrbitalPeriod()));
179 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
180 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
183 glm::eulerAngleY(rotation)
184 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
186 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
187 * glm::eulerAngleY(-rotation);
190 void Body::CheckCollision() noexcept {
191 if (Creatures().size() < 2) return;
193 auto end = Creatures().end();
194 for (auto i = Creatures().begin(); i != end; ++i) {
195 math::AABB i_box((*i)->CollisionBounds());
196 glm::dmat4 i_mat((*i)->CollisionTransform());
197 for (auto j = (i + 1); j != end; ++j) {
198 glm::dvec3 diff((*i)->GetSituation().Position() - (*j)->GetSituation().Position());
199 double max_dist = ((*i)->Size() + (*j)->Size()) * 1.74;
200 if (glm::length2(diff) > max_dist * max_dist) continue;
201 math::AABB j_box((*j)->CollisionBounds());
202 glm::dmat4 j_mat((*j)->CollisionTransform());
205 if (Intersect(i_box, i_mat, j_box, j_mat, normal, depth)) {
206 collisions.push_back({ **i, **j, normal, depth });
210 for (auto &c : collisions) {
211 c.A().GetSituation().Move(c.Normal() * (c.Depth() * -0.5));
212 c.B().GetSituation().Move(c.Normal() * (c.Depth() * 0.5));
213 c.A().GetSituation().Accelerate(c.Normal() * -glm::dot(c.Normal(), c.AVel()));
214 c.B().GetSituation().Accelerate(c.Normal() * -glm::dot(c.Normal(), c.BVel()));
215 // TODO: notify participants so they can be annoyed
219 void Body::AddCreature(creature::Creature *c) {
220 creatures.push_back(c);
223 void Body::RemoveCreature(creature::Creature *c) {
224 auto entry = std::find(creatures.begin(), creatures.end(), c);
225 if (entry != creatures.end()) {
226 creatures.erase(entry);
231 CreatureCreatureCollision::~CreatureCreatureCollision() {
234 const glm::dvec3 &CreatureCreatureCollision::APos() const noexcept {
235 return a->GetSituation().Position();
238 const glm::dvec3 &CreatureCreatureCollision::AVel() const noexcept {
239 return a->GetSituation().Velocity();
242 const glm::dvec3 &CreatureCreatureCollision::BPos() const noexcept {
243 return b->GetSituation().Position();
246 const glm::dvec3 &CreatureCreatureCollision::BVel() const noexcept {
247 return b->GetSituation().Velocity();
263 double Orbit::SemiMajorAxis() const noexcept {
267 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
272 double Orbit::Eccentricity() const noexcept {
276 Orbit &Orbit::Eccentricity(double e) noexcept {
281 double Orbit::Inclination() const noexcept {
285 Orbit &Orbit::Inclination(double i) noexcept {
290 double Orbit::LongitudeAscending() const noexcept {
294 Orbit &Orbit::LongitudeAscending(double l) noexcept {
299 double Orbit::ArgumentPeriapsis() const noexcept {
303 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
308 double Orbit::MeanAnomaly() const noexcept {
312 Orbit &Orbit::MeanAnomaly(double m) noexcept {
319 double mean2eccentric(double M, double e) {
320 double E = M; // eccentric anomaly, solve M = E - e sin E
321 // limit to 100 steps to prevent deadlocks in impossible situations
322 for (int i = 0; i < 100; ++i) {
323 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
325 if (std::abs(dE) < 1.0e-6) break;
332 glm::dmat4 Orbit::Matrix(double t) const noexcept {
334 double E = mean2eccentric(M, ecc);
336 // coordinates in orbital plane, P=x, Q=-z
337 double P = sma * (cos(E) - ecc);
338 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
340 return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
343 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
345 double E = mean2eccentric(M, ecc);
346 double P = sma * (cos(E) - ecc);
347 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
348 return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
352 Planet::Planet(int sidelength)
354 , sidelength(sidelength)
355 , tiles(TilesTotal())
357 Radius(double(sidelength) / 2.0);
364 /// map p onto cube, s gives the surface, u and v the position in [-1,1]
365 void cubemap(const glm::dvec3 &p, int &s, double &u, double &v) noexcept {
366 const glm::dvec3 p_abs(glm::abs(p));
367 const glm::bvec3 p_pos(glm::greaterThan(p, glm::dvec3(0.0)));
368 double max_axis = 0.0;
370 if (p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
376 if (!p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
382 if (p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
388 if (!p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
394 if (p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
400 if (!p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
409 /// get p from cube, s being surface, u and v the position in [-1,1],
410 /// gives a vector from the center to the surface
411 glm::dvec3 cubeunmap(int s, double u, double v) {
414 case 0: return glm::dvec3(u, v, 1.0); // +Z
415 case 1: return glm::dvec3(1.0, u, v); // +X
416 case 2: return glm::dvec3(v, 1.0, u); // +Y
417 case 3: return glm::dvec3(-u, -v, -1.0); // -Z
418 case 4: return glm::dvec3(-1.0, -u, -v); // -X
419 case 5: return glm::dvec3(-v, -1.0, -u); // -Y
424 Tile &Planet::TileAt(const glm::dvec3 &p) noexcept {
428 cubemap(p, srf, u, v);
429 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
430 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
431 return TileAt(srf, x, y);
434 const Tile &Planet::TileAt(const glm::dvec3 &p) const noexcept {
438 cubemap(p, srf, u, v);
439 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
440 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
441 return TileAt(srf, x, y);
444 const TileType &Planet::TileTypeAt(const glm::dvec3 &p) const noexcept {
445 return GetSimulation().TileTypes()[TileAt(p).type];
448 Tile &Planet::TileAt(int surface, int x, int y) noexcept {
449 return tiles[IndexOf(surface, x, y)];
452 const Tile &Planet::TileAt(int surface, int x, int y) const noexcept {
453 return tiles[IndexOf(surface, x, y)];
456 const TileType &Planet::TypeAt(int srf, int x, int y) const noexcept {
457 return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
460 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
461 double u = (double(x) - Radius() + 0.5) / Radius();
462 double v = (double(y) - Radius() + 0.5) / Radius();
463 return glm::normalize(cubeunmap(srf, u, v)) * (Radius() + e);
466 void Planet::BuildVAO(const Set<TileType> &ts) {
467 vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
469 vao->BindAttributes();
470 vao->EnableAttribute(0);
471 vao->EnableAttribute(1);
472 vao->EnableAttribute(2);
473 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
474 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
475 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, tex_coord));
476 vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
478 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
479 float offset = Radius();
482 // up +Z +X +Y -Z -X -Y
484 for (int index = 0, surface = 0; surface < 6; ++surface) {
485 for (int y = 0; y < sidelength; ++y) {
486 for (int x = 0; x < sidelength; ++x, ++index) {
488 pos[0][(surface + 0) % 3] = float(x + 0) - offset;
489 pos[0][(surface + 1) % 3] = float(y + 0) - offset;
490 pos[0][(surface + 2) % 3] = offset;
491 pos[1][(surface + 0) % 3] = float(x + 0) - offset;
492 pos[1][(surface + 1) % 3] = float(y + 1) - offset;
493 pos[1][(surface + 2) % 3] = offset;
494 pos[2][(surface + 0) % 3] = float(x + 1) - offset;
495 pos[2][(surface + 1) % 3] = float(y + 0) - offset;
496 pos[2][(surface + 2) % 3] = offset;
497 pos[3][(surface + 0) % 3] = float(x + 1) - offset;
498 pos[3][(surface + 1) % 3] = float(y + 1) - offset;
499 pos[3][(surface + 2) % 3] = offset;
501 float tex = ts[TileAt(surface, x, y).type].texture;
502 const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
503 const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
505 attrib[4 * index + 0].position = glm::normalize(pos[0]) * (surface < 3 ? offset : -offset);
506 attrib[4 * index + 0].normal = pos[0];
507 attrib[4 * index + 0].tex_coord[0] = 0.0f;
508 attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
509 attrib[4 * index + 0].tex_coord[2] = tex;
511 attrib[4 * index + 1].position = glm::normalize(pos[1]) * (surface < 3 ? offset : -offset);
512 attrib[4 * index + 1].normal = pos[1];
513 attrib[4 * index + 1].tex_coord[0] = 0.0f;
514 attrib[4 * index + 1].tex_coord[1] = tex_v_end;
515 attrib[4 * index + 1].tex_coord[2] = tex;
517 attrib[4 * index + 2].position = glm::normalize(pos[2]) * (surface < 3 ? offset : -offset);
518 attrib[4 * index + 2].normal = pos[2];
519 attrib[4 * index + 2].tex_coord[0] = 1.0f;
520 attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
521 attrib[4 * index + 2].tex_coord[2] = tex;
523 attrib[4 * index + 3].position = glm::normalize(pos[3]) * (surface < 3 ? offset : -offset);
524 attrib[4 * index + 3].normal = pos[3];
525 attrib[4 * index + 3].tex_coord[0] = 1.0f;
526 attrib[4 * index + 3].tex_coord[1] = tex_v_end;
527 attrib[4 * index + 3].tex_coord[2] = tex;
533 vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
535 auto element = vao->MapElements(GL_WRITE_ONLY);
537 for (int surface = 0; surface < 3; ++surface) {
538 for (int y = 0; y < sidelength; ++y) {
539 for (int x = 0; x < sidelength; ++x, ++index) {
540 element[6 * index + 0] = 4 * index + 0;
541 element[6 * index + 1] = 4 * index + 2;
542 element[6 * index + 2] = 4 * index + 1;
543 element[6 * index + 3] = 4 * index + 1;
544 element[6 * index + 4] = 4 * index + 2;
545 element[6 * index + 5] = 4 * index + 3;
549 for (int surface = 3; surface < 6; ++surface) {
550 for (int y = 0; y < sidelength; ++y) {
551 for (int x = 0; x < sidelength; ++x, ++index) {
552 element[6 * index + 0] = 4 * index + 0;
553 element[6 * index + 1] = 4 * index + 1;
554 element[6 * index + 2] = 4 * index + 2;
555 element[6 * index + 3] = 4 * index + 2;
556 element[6 * index + 4] = 4 * index + 1;
557 element[6 * index + 5] = 4 * index + 3;
565 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
569 vao->DrawTriangles(TilesTotal() * 6);
573 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
574 math::SimplexNoise elevation_gen(0);
575 math::SimplexNoise variation_gen(45623752346);
577 const int ice = tiles["ice"].id;
578 const int ocean = tiles["ocean"].id;
579 const int water = tiles["water"].id;
580 const int sand = tiles["sand"].id;
581 const int grass = tiles["grass"].id;
582 const int tundra = tiles["tundra"].id;
583 const int taiga = tiles["taiga"].id;
584 const int desert = tiles["desert"].id;
585 const int mntn = tiles["mountain"].id;
586 const int algae = tiles["algae"].id;
587 const int forest = tiles["forest"].id;
588 const int jungle = tiles["jungle"].id;
589 const int rock = tiles["rock"].id;
590 const int wheat = tiles["wheat"].id;
592 constexpr double ocean_thresh = -0.2;
593 constexpr double water_thresh = 0.0;
594 constexpr double beach_thresh = 0.05;
595 constexpr double highland_thresh = 0.4;
596 constexpr double mountain_thresh = 0.5;
598 const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
599 const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
600 const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
601 const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
602 const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
604 for (int surface = 0; surface <= 5; ++surface) {
605 for (int y = 0; y < p.SideLength(); ++y) {
606 for (int x = 0; x < p.SideLength(); ++x) {
607 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
608 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
609 if (near_axis > cap_thresh) {
610 p.TileAt(surface, x, y).type = ice;
613 float elevation = math::OctaveNoise(
615 glm::vec3(to_tile / p.Radius()),
618 5 / p.Radius(), // frequency
622 float variation = math::OctaveNoise(
624 glm::vec3(to_tile / p.Radius()),
627 16 / p.Radius(), // frequency
631 if (elevation < ocean_thresh) {
632 p.TileAt(surface, x, y).type = ocean;
633 } else if (elevation < water_thresh) {
634 if (variation > 0.3) {
635 p.TileAt(surface, x, y).type = algae;
637 p.TileAt(surface, x, y).type = water;
639 } else if (elevation < beach_thresh) {
640 p.TileAt(surface, x, y).type = sand;
641 } else if (elevation < highland_thresh) {
642 if (near_axis < equ_thresh) {
643 if (variation > 0.6) {
644 p.TileAt(surface, x, y).type = grass;
645 } else if (variation > 0.2) {
646 p.TileAt(surface, x, y).type = sand;
648 p.TileAt(surface, x, y).type = desert;
650 } else if (near_axis < fzone_start) {
651 if (variation > 0.4) {
652 p.TileAt(surface, x, y).type = forest;
653 } else if (variation < -0.5) {
654 p.TileAt(surface, x, y).type = jungle;
655 } else if (variation > -0.02 && variation < 0.02) {
656 p.TileAt(surface, x, y).type = wheat;
658 p.TileAt(surface, x, y).type = grass;
660 } else if (near_axis < fzone_end) {
661 p.TileAt(surface, x, y).type = tundra;
663 p.TileAt(surface, x, y).type = taiga;
665 } else if (elevation < mountain_thresh) {
666 if (variation > 0.3) {
667 p.TileAt(surface, x, y).type = mntn;
669 p.TileAt(surface, x, y).type = rock;
672 p.TileAt(surface, x, y).type = mntn;
680 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
681 for (int surface = 0; surface <= 5; ++surface) {
682 for (int y = 0; y < p.SideLength(); ++y) {
683 for (int x = 0; x < p.SideLength(); ++x) {
684 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
685 p.TileAt(surface, x, y).type = surface;
687 p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
706 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
707 auto yield = resources.cbegin();
708 for (; yield != resources.cend(); ++yield) {
709 if (yield->resource == r) {
716 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
717 auto best = resources.cend();
718 double best_value = 0.0;
719 for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
720 double value = comp.Get(yield->resource);
721 if (value > best_value) {