]> git.localhorst.tv Git - blobs.git/blob - src/world/world.cpp
eee12833b39ca80d467d0f8fc19868284f796419
[blobs.git] / src / world / world.cpp
1 #include "Body.hpp"
2 #include "Orbit.hpp"
3 #include "Planet.hpp"
4 #include "Resource.hpp"
5 #include "Set.hpp"
6 #include "Simulation.hpp"
7 #include "Sun.hpp"
8 #include "Tile.hpp"
9 #include "TileType.hpp"
10
11 #include "../app/Assets.hpp"
12 #include "../creature/Creature.hpp"
13 #include "../graphics/Viewport.hpp"
14 #include "../math/const.hpp"
15 #include "../math/OctaveNoise.hpp"
16 #include "../math/SimplexNoise.hpp"
17
18 #include <algorithm>
19 #include <cmath>
20 #include <iostream>
21 #include <glm/gtc/matrix_transform.hpp>
22 #include <glm/gtx/euler_angles.hpp>
23 #include <glm/gtx/io.hpp>
24 #include <glm/gtx/transform.hpp>
25
26 using blobs::G;
27 using blobs::PI_2p0;
28
29 using std::sin;
30 using std::cos;
31 using std::pow;
32 using std::sqrt;
33
34
35 namespace blobs {
36 namespace world {
37
38 Body::Body()
39 : sim(nullptr)
40 , parent(nullptr)
41 , children()
42 , mass(1.0)
43 , radius(1.0)
44 , orbit()
45 , surface_tilt(0.0, 0.0)
46 , axis_tilt(0.0, 0.0)
47 , rotation(0.0)
48 , angular(0.0)
49 , orbital(1.0)
50 , inverse_orbital(1.0)
51 , local(1.0)
52 , inverse_local(1.0)
53 , creatures()
54 , atmosphere(-1) {
55 }
56
57 Body::~Body() {
58         for (creature::Creature *c : creatures) {
59                 delete c;
60         }
61 }
62
63 void Body::SetSimulation(Simulation &s) noexcept {
64         sim = &s;
65         for (auto child : children) {
66                 child->SetSimulation(s);
67         }
68 }
69
70 void Body::SetParent(Body &p) {
71         if (HasParent()) {
72                 UnsetParent();
73         }
74         parent = &p;
75         parent->AddChild(*this);
76 }
77
78 void Body::UnsetParent() {
79         if (!HasParent()) return;
80         parent->RemoveChild(*this);
81         parent = nullptr;
82 }
83
84 void Body::AddChild(Body &c) {
85         children.push_back(&c);
86         c.SetSimulation(*sim);
87 }
88
89 void Body::RemoveChild(Body &c) {
90         auto entry = std::find(children.begin(), children.end(), &c);
91         if (entry != children.end()) {
92                 children.erase(entry);
93         }
94 }
95
96 double Body::Inertia() const noexcept {
97         // assume solid sphere for now
98         return (2.0/5.0) * Mass() * pow(Radius(), 2);
99 }
100
101 double Body::GravitationalParameter() const noexcept {
102         return G * Mass();
103 }
104
105 double Body::OrbitalPeriod() const noexcept {
106         if (parent) {
107                 return PI_2p0 * sqrt(pow(orbit.SemiMajorAxis(), 3) / (G * (parent->Mass() + Mass())));
108         } else {
109                 return 0.0;
110         }
111 }
112
113 double Body::RotationalPeriod() const noexcept {
114         if (std::abs(angular) < std::numeric_limits<double>::epsilon()) {
115                 return std::numeric_limits<double>::infinity();
116         } else {
117                 return PI_2p0 * Inertia() / angular;
118         }
119 }
120
121 glm::dmat4 Body::ToUniverse() const noexcept {
122         glm::dmat4 m(1.0);
123         const Body *b = this;
124         while (b->HasParent()) {
125                 m = b->ToParent() * m;
126                 b = &b->Parent();
127         }
128         return m;
129 }
130
131 glm::dmat4 Body::FromUniverse() const noexcept {
132         glm::dmat4 m(1.0);
133         const Body *b = this;
134         while (b->HasParent()) {
135                 m *= b->FromParent();
136                 b = &b->Parent();
137         }
138         return m;
139 }
140
141 namespace {
142 std::vector<creature::Creature *> ccache;
143 }
144
145 void Body::Tick(double dt) {
146         rotation += dt * AngularMomentum() / Inertia();
147         Cache();
148         ccache = Creatures();
149         for (creature::Creature *c : ccache) {
150                 c->Tick(dt);
151         }
152         for (auto c = Creatures().begin(); c != Creatures().end();) {
153                 if ((*c)->Removable()) {
154                         delete *c;
155                         c = Creatures().erase(c);
156                 } else {
157                         ++c;
158                 }
159         }
160 }
161
162 void Body::Cache() noexcept {
163         if (parent) {
164                 orbital =
165                         orbit.Matrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()))
166                         * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
167                 inverse_orbital =
168                         glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
169                         * orbit.InverseMatrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()));
170         } else {
171                 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
172                 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
173         }
174         local =
175                 glm::eulerAngleY(rotation)
176                 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
177         inverse_local =
178                 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
179                 * glm::eulerAngleY(-rotation);
180 }
181
182 void Body::AddCreature(creature::Creature *c) {
183         creatures.push_back(c);
184 }
185
186 void Body::RemoveCreature(creature::Creature *c) {
187         auto entry = std::find(creatures.begin(), creatures.end(), c);
188         if (entry != creatures.end()) {
189                 creatures.erase(entry);
190         }
191 }
192
193
194 Orbit::Orbit()
195 : sma(1.0)
196 , ecc(0.0)
197 , inc(0.0)
198 , asc(0.0)
199 , arg(0.0)
200 , mna(0.0) {
201 }
202
203 Orbit::~Orbit() {
204 }
205
206 double Orbit::SemiMajorAxis() const noexcept {
207         return sma;
208 }
209
210 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
211         sma = s;
212         return *this;
213 }
214
215 double Orbit::Eccentricity() const noexcept {
216         return ecc;
217 }
218
219 Orbit &Orbit::Eccentricity(double e) noexcept {
220         ecc = e;
221         return *this;
222 }
223
224 double Orbit::Inclination() const noexcept {
225         return inc;
226 }
227
228 Orbit &Orbit::Inclination(double i) noexcept {
229         inc = i;
230         return *this;
231 }
232
233 double Orbit::LongitudeAscending() const noexcept {
234         return asc;
235 }
236
237 Orbit &Orbit::LongitudeAscending(double l) noexcept {
238         asc = l;
239         return *this;
240 }
241
242 double Orbit::ArgumentPeriapsis() const noexcept {
243         return arg;
244 }
245
246 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
247         arg = a;
248         return *this;
249 }
250
251 double Orbit::MeanAnomaly() const noexcept {
252         return mna;
253 }
254
255 Orbit &Orbit::MeanAnomaly(double m) noexcept {
256         mna = m;
257         return *this;
258 }
259
260 namespace {
261
262 double mean2eccentric(double M, double e) {
263         double E = M; // eccentric anomaly, solve M = E - e sin E
264         // limit to 100 steps to prevent deadlocks in impossible situations
265         for (int i = 0; i < 100; ++i) {
266                 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
267                 E -= dE;
268                 if (abs(dE) < 1.0e-6) break;
269         }
270         return E;
271 }
272
273 }
274
275 glm::dmat4 Orbit::Matrix(double t) const noexcept {
276         double M = mna + t;
277         double E = mean2eccentric(M, ecc);
278
279         // coordinates in orbital plane, P=x, Q=-z
280         double P = sma * (cos(E) - ecc);
281         double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
282
283         return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
284 }
285
286 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
287         double M = mna + t;
288         double E = mean2eccentric(M, ecc);
289         double P = sma * (cos(E) - ecc);
290         double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
291         return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
292 }
293
294
295 Planet::Planet(int sidelength)
296 : Body()
297 , sidelength(sidelength)
298 , tiles(TilesTotal())
299 , vao() {
300         Radius(double(sidelength) / 2.0);
301 }
302
303 Planet::~Planet() {
304 }
305
306 const TileType &Planet::TypeAt(int srf, int x, int y) const {
307         return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
308 }
309
310 glm::ivec2 Planet::SurfacePosition(int srf, const glm::dvec3 &pos) const noexcept {
311         return glm::ivec2(
312                 PositionToTile(pos[(srf + 0) % 3]),
313                 PositionToTile(pos[(srf + 1) % 3]));
314 }
315
316 double Planet::SurfaceElevation(int srf, const glm::dvec3 &pos) const noexcept {
317         return srf < 3
318                 ? pos[(srf + 2) % 3] - Radius()
319                 : -pos[(srf + 2) % 3] - Radius();
320 }
321
322 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
323         glm::dvec3 center(0.0f);
324         center[(srf + 0) % 3] = x + 0.5 - Radius();
325         center[(srf + 1) % 3] = y + 0.5 - Radius();
326         center[(srf + 2) % 3] = srf < 3 ? (Radius() + e) : -(Radius() + e);
327         return center;
328 }
329
330 void Planet::BuildVAO(const Set<TileType> &ts) {
331         vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
332         vao->Bind();
333         vao->BindAttributes();
334         vao->EnableAttribute(0);
335         vao->EnableAttribute(1);
336         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
337         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, tex_coord));
338         vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
339         {
340                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
341                 float offset = Radius();
342
343                 // srf  0  1  2  3  4  5
344                 //  up +Z +X +Y -Z -X -Y
345
346                 for (int index = 0, surface = 0; surface < 6; ++surface) {
347                         for (int y = 0; y < sidelength; ++y) {
348                                 for (int x = 0; x < sidelength; ++x, ++index) {
349                                         float tex = ts[TileAt(surface, x, y).type].texture;
350                                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
351                                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
352                                         attrib[4 * index + 0].position[(surface + 0) % 3] = x + 0 - offset;
353                                         attrib[4 * index + 0].position[(surface + 1) % 3] = y + 0 - offset;
354                                         attrib[4 * index + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
355                                         attrib[4 * index + 0].tex_coord[0] = tex_u_begin;
356                                         attrib[4 * index + 0].tex_coord[1] = 1.0f;
357                                         attrib[4 * index + 0].tex_coord[2] = tex;
358
359                                         attrib[4 * index + 1].position[(surface + 0) % 3] = x + 0 - offset;
360                                         attrib[4 * index + 1].position[(surface + 1) % 3] = y + 1 - offset;
361                                         attrib[4 * index + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
362                                         attrib[4 * index + 1].tex_coord[0] = tex_u_end;
363                                         attrib[4 * index + 1].tex_coord[1] = 1.0f;
364                                         attrib[4 * index + 1].tex_coord[2] = tex;
365
366                                         attrib[4 * index + 2].position[(surface + 0) % 3] = x + 1 - offset;
367                                         attrib[4 * index + 2].position[(surface + 1) % 3] = y + 0 - offset;
368                                         attrib[4 * index + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
369                                         attrib[4 * index + 2].tex_coord[0] = tex_u_begin;
370                                         attrib[4 * index + 2].tex_coord[1] = 0.0f;
371                                         attrib[4 * index + 2].tex_coord[2] = tex;
372
373                                         attrib[4 * index + 3].position[(surface + 0) % 3] = x + 1 - offset;
374                                         attrib[4 * index + 3].position[(surface + 1) % 3] = y + 1 - offset;
375                                         attrib[4 * index + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
376                                         attrib[4 * index + 3].tex_coord[0] = tex_u_end;
377                                         attrib[4 * index + 3].tex_coord[1] = 0.0f;
378                                         attrib[4 * index + 3].tex_coord[2] = tex;
379                                 }
380                         }
381                 }
382         }
383         vao->BindElements();
384         vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
385         {
386                 auto element = vao->MapElements(GL_WRITE_ONLY);
387                 int index = 0;
388                 for (int surface = 0; surface < 3; ++surface) {
389                         for (int y = 0; y < sidelength; ++y) {
390                                 for (int x = 0; x < sidelength; ++x, ++index) {
391                                         element[6 * index + 0] = 4 * index + 0;
392                                         element[6 * index + 1] = 4 * index + 2;
393                                         element[6 * index + 2] = 4 * index + 1;
394                                         element[6 * index + 3] = 4 * index + 1;
395                                         element[6 * index + 4] = 4 * index + 2;
396                                         element[6 * index + 5] = 4 * index + 3;
397                                 }
398                         }
399                 }
400                 for (int surface = 3; surface < 6; ++surface) {
401                         for (int y = 0; y < sidelength; ++y) {
402                                 for (int x = 0; x < sidelength; ++x, ++index) {
403                                         element[6 * index + 0] = 4 * index + 0;
404                                         element[6 * index + 1] = 4 * index + 1;
405                                         element[6 * index + 2] = 4 * index + 2;
406                                         element[6 * index + 3] = 4 * index + 2;
407                                         element[6 * index + 4] = 4 * index + 1;
408                                         element[6 * index + 5] = 4 * index + 3;
409                                 }
410                         }
411                 }
412         }
413         vao->Unbind();
414 }
415
416 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
417         if (!vao) return;
418
419         vao->Bind();
420         const glm::mat4 &MV = assets.shaders.planet_surface.MV();
421         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f)));
422         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 0);
423         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(1.0f, 0.0f, 0.0f, 0.0f)));
424         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 1);
425         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)));
426         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 2);
427         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)));
428         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 3);
429         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f)));
430         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 4);
431         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, -1.0f, 0.0f, 0.0f)));
432         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 5);
433 }
434
435
436 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
437         math::SimplexNoise elevation_gen(0);
438         math::SimplexNoise variation_gen(45623752346);
439
440         const int ice = tiles["ice"].id;
441         const int ocean = tiles["ocean"].id;
442         const int water = tiles["water"].id;
443         const int sand = tiles["sand"].id;
444         const int grass = tiles["grass"].id;
445         const int tundra = tiles["tundra"].id;
446         const int taiga = tiles["taiga"].id;
447         const int desert = tiles["desert"].id;
448         const int mntn = tiles["mountain"].id;
449         const int algae = tiles["algae"].id;
450         const int forest = tiles["forest"].id;
451         const int jungle = tiles["jungle"].id;
452         const int rock = tiles["rock"].id;
453         const int wheat = tiles["wheat"].id;
454
455         constexpr double ocean_thresh = -0.2;
456         constexpr double water_thresh = 0.0;
457         constexpr double beach_thresh = 0.05;
458         constexpr double highland_thresh = 0.4;
459         constexpr double mountain_thresh = 0.5;
460
461         const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
462         const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
463         const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
464         const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
465         const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
466
467         for (int surface = 0; surface <= 5; ++surface) {
468                 for (int y = 0; y < p.SideLength(); ++y) {
469                         for (int x = 0; x < p.SideLength(); ++x) {
470                                 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
471                                 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
472                                 if (near_axis > cap_thresh) {
473                                         p.TileAt(surface, x, y).type = ice;
474                                         continue;
475                                 }
476                                 float elevation = math::OctaveNoise(
477                                         elevation_gen,
478                                         to_tile / p.Radius(),
479                                         3,   // octaves
480                                         0.5, // persistence
481                                         5 / p.Radius(), // frequency
482                                         2,   // amplitude
483                                         2    // growth
484                                 );
485                                 float variation = math::OctaveNoise(
486                                         variation_gen,
487                                         to_tile / p.Radius(),
488                                         3,   // octaves
489                                         0.5, // persistence
490                                         16 / p.Radius(), // frequency
491                                         2,   // amplitude
492                                         2    // growth
493                                 );
494                                 if (elevation < ocean_thresh) {
495                                         p.TileAt(surface, x, y).type = ocean;
496                                 } else if (elevation < water_thresh) {
497                                         if (variation > 0.3) {
498                                                 p.TileAt(surface, x, y).type = algae;
499                                         } else {
500                                                 p.TileAt(surface, x, y).type = water;
501                                         }
502                                 } else if (elevation < beach_thresh) {
503                                         p.TileAt(surface, x, y).type = sand;
504                                 } else if (elevation < highland_thresh) {
505                                         if (near_axis < equ_thresh) {
506                                                 if (variation > 0.6) {
507                                                         p.TileAt(surface, x, y).type = grass;
508                                                 } else if (variation > 0.2) {
509                                                         p.TileAt(surface, x, y).type = sand;
510                                                 } else {
511                                                         p.TileAt(surface, x, y).type = desert;
512                                                 }
513                                         } else if (near_axis < fzone_start) {
514                                                 if (variation > 0.4) {
515                                                         p.TileAt(surface, x, y).type = forest;
516                                                 } else if (variation < -0.5) {
517                                                         p.TileAt(surface, x, y).type = jungle;
518                                                 } else if (variation > -0.02 && variation < 0.02) {
519                                                         p.TileAt(surface, x, y).type = wheat;
520                                                 } else {
521                                                         p.TileAt(surface, x, y).type = grass;
522                                                 }
523                                         } else if (near_axis < fzone_end) {
524                                                 p.TileAt(surface, x, y).type = tundra;
525                                         } else {
526                                                 p.TileAt(surface, x, y).type = taiga;
527                                         }
528                                 } else if (elevation < mountain_thresh) {
529                                         if (variation > 0.3) {
530                                                 p.TileAt(surface, x, y).type = mntn;
531                                         } else {
532                                                 p.TileAt(surface, x, y).type = rock;
533                                         }
534                                 } else {
535                                         p.TileAt(surface, x, y).type = mntn;
536                                 }
537                         }
538                 }
539         }
540         p.BuildVAO(tiles);
541 }
542
543 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
544         for (int surface = 0; surface <= 5; ++surface) {
545                 for (int y = 0; y < p.SideLength(); ++y) {
546                         for (int x = 0; x < p.SideLength(); ++x) {
547                                 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
548                                         p.TileAt(surface, x, y).type = surface;
549                                 } else {
550                                         p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
551                                 }
552                         }
553                 }
554         }
555         p.BuildVAO(tiles);
556 }
557
558
559 Sun::Sun()
560 : Body() {
561 }
562
563 Sun::~Sun() {
564 }
565
566
567 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
568         auto yield = resources.cbegin();
569         for (; yield != resources.cend(); ++yield) {
570                 if (yield->resource == r) {
571                         break;
572                 }
573         }
574         return yield;
575 }
576
577 }
578 }