]> git.localhorst.tv Git - blobs.git/blob - src/world/world.cpp
0b1260f8673d8a0eb1b054bec81847b61602d711
[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 "../const.hpp"
12 #include "../app/Assets.hpp"
13 #include "../creature/Creature.hpp"
14 #include "../graphics/Viewport.hpp"
15 #include "../rand/OctaveNoise.hpp"
16 #include "../rand/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 void Body::Tick(double dt) {
142         rotation += dt * AngularMomentum() / Inertia();
143         Cache();
144         for (creature::Creature *c : Creatures()) {
145                 c->Tick(dt);
146         }
147 }
148
149 void Body::Cache() noexcept {
150         if (parent) {
151                 orbital =
152                         orbit.Matrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()))
153                         * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
154                 inverse_orbital =
155                         glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
156                         * orbit.InverseMatrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()));
157         } else {
158                 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
159                 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
160         }
161         local =
162                 glm::eulerAngleY(rotation)
163                 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
164         inverse_local =
165                 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
166                 * glm::eulerAngleY(-rotation);
167 }
168
169 void Body::AddCreature(creature::Creature *c) {
170         creatures.push_back(c);
171 }
172
173 void Body::RemoveCreature(creature::Creature *c) {
174         auto entry = std::find(creatures.begin(), creatures.end(), c);
175         if (entry != creatures.end()) {
176                 creatures.erase(entry);
177         }
178 }
179
180
181 Orbit::Orbit()
182 : sma(1.0)
183 , ecc(0.0)
184 , inc(0.0)
185 , asc(0.0)
186 , arg(0.0)
187 , mna(0.0) {
188 }
189
190 Orbit::~Orbit() {
191 }
192
193 double Orbit::SemiMajorAxis() const noexcept {
194         return sma;
195 }
196
197 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
198         sma = s;
199         return *this;
200 }
201
202 double Orbit::Eccentricity() const noexcept {
203         return ecc;
204 }
205
206 Orbit &Orbit::Eccentricity(double e) noexcept {
207         ecc = e;
208         return *this;
209 }
210
211 double Orbit::Inclination() const noexcept {
212         return inc;
213 }
214
215 Orbit &Orbit::Inclination(double i) noexcept {
216         inc = i;
217         return *this;
218 }
219
220 double Orbit::LongitudeAscending() const noexcept {
221         return asc;
222 }
223
224 Orbit &Orbit::LongitudeAscending(double l) noexcept {
225         asc = l;
226         return *this;
227 }
228
229 double Orbit::ArgumentPeriapsis() const noexcept {
230         return arg;
231 }
232
233 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
234         arg = a;
235         return *this;
236 }
237
238 double Orbit::MeanAnomaly() const noexcept {
239         return mna;
240 }
241
242 Orbit &Orbit::MeanAnomaly(double m) noexcept {
243         mna = m;
244         return *this;
245 }
246
247 namespace {
248
249 double mean2eccentric(double M, double e) {
250         double E = M; // eccentric anomaly, solve M = E - e sin E
251         // limit to 100 steps to prevent deadlocks in impossible situations
252         for (int i = 0; i < 100; ++i) {
253                 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
254                 E -= dE;
255                 if (abs(dE) < 1.0e-6) break;
256         }
257         return E;
258 }
259
260 }
261
262 glm::dmat4 Orbit::Matrix(double t) const noexcept {
263         double M = mna + t;
264         double E = mean2eccentric(M, ecc);
265
266         // coordinates in orbital plane, P=x, Q=-z
267         double P = sma * (cos(E) - ecc);
268         double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
269
270         return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
271 }
272
273 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
274         double M = mna + t;
275         double E = mean2eccentric(M, ecc);
276         double P = sma * (cos(E) - ecc);
277         double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
278         return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
279 }
280
281
282 Planet::Planet(int sidelength)
283 : Body()
284 , sidelength(sidelength)
285 , tiles(TilesTotal())
286 , vao() {
287         Radius(double(sidelength) / 2.0);
288 }
289
290 Planet::~Planet() {
291 }
292
293 const TileType &Planet::TypeAt(int srf, int x, int y) const {
294         return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
295 }
296
297 glm::ivec2 Planet::SurfacePosition(int srf, const glm::dvec3 &pos) const noexcept {
298         return glm::ivec2(
299                 PositionToTile(pos[(srf + 0) % 3]),
300                 PositionToTile(pos[(srf + 1) % 3]));
301 }
302
303 double Planet::SurfaceElevation(int srf, const glm::dvec3 &pos) const noexcept {
304         return srf < 3
305                 ? pos[(srf + 2) % 3] - Radius()
306                 : -pos[(srf + 2) % 3] - Radius();
307 }
308
309 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
310         glm::dvec3 center(0.0f);
311         center[(srf + 0) % 3] = x + 0.5 - Radius();
312         center[(srf + 1) % 3] = y + 0.5 - Radius();
313         center[(srf + 2) % 3] = srf < 3 ? (Radius() + e) : -(Radius() + e);
314         return center;
315 }
316
317 void Planet::BuildVAO(const Set<TileType> &ts) {
318         vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
319         vao->Bind();
320         vao->BindAttributes();
321         vao->EnableAttribute(0);
322         vao->EnableAttribute(1);
323         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
324         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, tex_coord));
325         vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
326         {
327                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
328                 float offset = Radius();
329
330                 // srf  0  1  2  3  4  5
331                 //  up +Z +X +Y -Z -X -Y
332
333                 for (int index = 0, surface = 0; surface < 6; ++surface) {
334                         for (int y = 0; y < sidelength; ++y) {
335                                 for (int x = 0; x < sidelength; ++x, ++index) {
336                                         float tex = ts[TileAt(surface, x, y).type].texture;
337                                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
338                                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
339                                         attrib[4 * index + 0].position[(surface + 0) % 3] = x + 0 - offset;
340                                         attrib[4 * index + 0].position[(surface + 1) % 3] = y + 0 - offset;
341                                         attrib[4 * index + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
342                                         attrib[4 * index + 0].tex_coord[0] = tex_u_begin;
343                                         attrib[4 * index + 0].tex_coord[1] = 1.0f;
344                                         attrib[4 * index + 0].tex_coord[2] = tex;
345
346                                         attrib[4 * index + 1].position[(surface + 0) % 3] = x + 0 - offset;
347                                         attrib[4 * index + 1].position[(surface + 1) % 3] = y + 1 - offset;
348                                         attrib[4 * index + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
349                                         attrib[4 * index + 1].tex_coord[0] = tex_u_end;
350                                         attrib[4 * index + 1].tex_coord[1] = 1.0f;
351                                         attrib[4 * index + 1].tex_coord[2] = tex;
352
353                                         attrib[4 * index + 2].position[(surface + 0) % 3] = x + 1 - offset;
354                                         attrib[4 * index + 2].position[(surface + 1) % 3] = y + 0 - offset;
355                                         attrib[4 * index + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
356                                         attrib[4 * index + 2].tex_coord[0] = tex_u_begin;
357                                         attrib[4 * index + 2].tex_coord[1] = 0.0f;
358                                         attrib[4 * index + 2].tex_coord[2] = tex;
359
360                                         attrib[4 * index + 3].position[(surface + 0) % 3] = x + 1 - offset;
361                                         attrib[4 * index + 3].position[(surface + 1) % 3] = y + 1 - offset;
362                                         attrib[4 * index + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
363                                         attrib[4 * index + 3].tex_coord[0] = tex_u_end;
364                                         attrib[4 * index + 3].tex_coord[1] = 0.0f;
365                                         attrib[4 * index + 3].tex_coord[2] = tex;
366                                 }
367                         }
368                 }
369         }
370         vao->BindElements();
371         vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
372         {
373                 auto element = vao->MapElements(GL_WRITE_ONLY);
374                 int index = 0;
375                 for (int surface = 0; surface < 3; ++surface) {
376                         for (int y = 0; y < sidelength; ++y) {
377                                 for (int x = 0; x < sidelength; ++x, ++index) {
378                                         element[6 * index + 0] = 4 * index + 0;
379                                         element[6 * index + 1] = 4 * index + 2;
380                                         element[6 * index + 2] = 4 * index + 1;
381                                         element[6 * index + 3] = 4 * index + 1;
382                                         element[6 * index + 4] = 4 * index + 2;
383                                         element[6 * index + 5] = 4 * index + 3;
384                                 }
385                         }
386                 }
387                 for (int surface = 3; surface < 6; ++surface) {
388                         for (int y = 0; y < sidelength; ++y) {
389                                 for (int x = 0; x < sidelength; ++x, ++index) {
390                                         element[6 * index + 0] = 4 * index + 0;
391                                         element[6 * index + 1] = 4 * index + 1;
392                                         element[6 * index + 2] = 4 * index + 2;
393                                         element[6 * index + 3] = 4 * index + 2;
394                                         element[6 * index + 4] = 4 * index + 1;
395                                         element[6 * index + 5] = 4 * index + 3;
396                                 }
397                         }
398                 }
399         }
400         vao->Unbind();
401 }
402
403 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
404         if (!vao) return;
405
406         vao->Bind();
407         const glm::mat4 &MV = assets.shaders.planet_surface.MV();
408         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f)));
409         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 0);
410         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(1.0f, 0.0f, 0.0f, 0.0f)));
411         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 1);
412         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)));
413         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 2);
414         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)));
415         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 3);
416         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f)));
417         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 4);
418         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, -1.0f, 0.0f, 0.0f)));
419         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 5);
420 }
421
422
423 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
424         rand::SimplexNoise elevation_gen(0);
425         rand::SimplexNoise variation_gen(45623752346);
426
427         const int ice = tiles["ice"].id;
428         const int ocean = tiles["ocean"].id;
429         const int water = tiles["water"].id;
430         const int sand = tiles["sand"].id;
431         const int grass = tiles["grass"].id;
432         const int tundra = tiles["tundra"].id;
433         const int taiga = tiles["taiga"].id;
434         const int desert = tiles["desert"].id;
435         const int mntn = tiles["mountain"].id;
436         const int algae = tiles["algae"].id;
437         const int forest = tiles["forest"].id;
438         const int jungle = tiles["jungle"].id;
439         const int rock = tiles["rock"].id;
440         const int wheat = tiles["wheat"].id;
441
442         constexpr double ocean_thresh = -0.2;
443         constexpr double water_thresh = 0.0;
444         constexpr double beach_thresh = 0.05;
445         constexpr double highland_thresh = 0.4;
446         constexpr double mountain_thresh = 0.5;
447
448         const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
449         const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
450         const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
451         const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
452         const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
453
454         for (int surface = 0; surface <= 5; ++surface) {
455                 for (int y = 0; y < p.SideLength(); ++y) {
456                         for (int x = 0; x < p.SideLength(); ++x) {
457                                 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
458                                 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
459                                 if (near_axis > cap_thresh) {
460                                         p.TileAt(surface, x, y).type = ice;
461                                         continue;
462                                 }
463                                 float elevation = rand::OctaveNoise(
464                                         elevation_gen,
465                                         to_tile / p.Radius(),
466                                         3,   // octaves
467                                         0.5, // persistence
468                                         5 / p.Radius(), // frequency
469                                         2,   // amplitude
470                                         2    // growth
471                                 );
472                                 float variation = rand::OctaveNoise(
473                                         variation_gen,
474                                         to_tile / p.Radius(),
475                                         3,   // octaves
476                                         0.5, // persistence
477                                         16 / p.Radius(), // frequency
478                                         2,   // amplitude
479                                         2    // growth
480                                 );
481                                 if (elevation < ocean_thresh) {
482                                         p.TileAt(surface, x, y).type = ocean;
483                                 } else if (elevation < water_thresh) {
484                                         if (variation > 0.3) {
485                                                 p.TileAt(surface, x, y).type = algae;
486                                         } else {
487                                                 p.TileAt(surface, x, y).type = water;
488                                         }
489                                 } else if (elevation < beach_thresh) {
490                                         p.TileAt(surface, x, y).type = sand;
491                                 } else if (elevation < highland_thresh) {
492                                         if (near_axis < equ_thresh) {
493                                                 if (variation > 0.6) {
494                                                         p.TileAt(surface, x, y).type = grass;
495                                                 } else if (variation > 0.2) {
496                                                         p.TileAt(surface, x, y).type = sand;
497                                                 } else {
498                                                         p.TileAt(surface, x, y).type = desert;
499                                                 }
500                                         } else if (near_axis < fzone_start) {
501                                                 if (variation > 0.4) {
502                                                         p.TileAt(surface, x, y).type = forest;
503                                                 } else if (variation < -0.5) {
504                                                         p.TileAt(surface, x, y).type = jungle;
505                                                 } else if (variation > -0.02 && variation < 0.02) {
506                                                         p.TileAt(surface, x, y).type = wheat;
507                                                 } else {
508                                                         p.TileAt(surface, x, y).type = grass;
509                                                 }
510                                         } else if (near_axis < fzone_end) {
511                                                 p.TileAt(surface, x, y).type = tundra;
512                                         } else {
513                                                 p.TileAt(surface, x, y).type = taiga;
514                                         }
515                                 } else if (elevation < mountain_thresh) {
516                                         if (variation > 0.3) {
517                                                 p.TileAt(surface, x, y).type = mntn;
518                                         } else {
519                                                 p.TileAt(surface, x, y).type = rock;
520                                         }
521                                 } else {
522                                         p.TileAt(surface, x, y).type = mntn;
523                                 }
524                         }
525                 }
526         }
527         p.BuildVAO(tiles);
528 }
529
530 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
531         for (int surface = 0; surface <= 5; ++surface) {
532                 for (int y = 0; y < p.SideLength(); ++y) {
533                         for (int x = 0; x < p.SideLength(); ++x) {
534                                 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
535                                         p.TileAt(surface, x, y).type = surface;
536                                 } else {
537                                         p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
538                                 }
539                         }
540                 }
541         }
542         p.BuildVAO(tiles);
543 }
544
545
546 Sun::Sun()
547 : Body() {
548 }
549
550 Sun::~Sun() {
551 }
552
553
554 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
555         auto yield = resources.cbegin();
556         for (; yield != resources.cend(); ++yield) {
557                 if (yield->resource == r) {
558                         break;
559                 }
560         }
561         return yield;
562 }
563
564 }
565 }