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