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