]> git.localhorst.tv Git - blobs.git/blob - src/app/states.cpp
(slightly) better camera handling
[blobs.git] / src / app / states.cpp
1 #include "MasterState.hpp"
2
3 #include "../world/Body.hpp"
4 #include "../world/Planet.hpp"
5 #include "../world/Simulation.hpp"
6 #include "../world/Sun.hpp"
7
8 #include <glm/gtx/transform.hpp>
9
10
11 namespace blobs {
12 namespace app {
13
14 MasterState::MasterState(Assets &assets, world::Simulation &sim) noexcept
15 : State()
16 , assets(assets)
17 , sim(sim)
18 , cam(sim.Root())
19 , remain(0)
20 , thirds(0)
21 , paused(false) {
22 }
23
24 MasterState::~MasterState() noexcept {
25 }
26
27
28 void MasterState::OnResize(int w, int h) {
29         cam.Aspect(float(w), float(h));
30 }
31
32 void MasterState::OnUpdate(int dt) {
33         remain += dt;
34         while (remain >= FrameMS()) {
35                 Tick();
36         }
37 }
38
39 void MasterState::Tick() {
40         if (!paused) {
41                 sim.Tick();
42         }
43         remain -= FrameMS();
44         thirds = (thirds + 1) % 3;
45 }
46
47 int MasterState::FrameMS() const noexcept {
48         return thirds == 0 ? 16 : 17;
49 }
50
51
52 void MasterState::OnKeyDown(const SDL_KeyboardEvent &e) {
53         if (e.keysym.sym == SDLK_p) {
54                 paused = !paused;
55         }
56 }
57
58 void MasterState::OnRender(graphics::Viewport &viewport) {
59         glm::dmat4 ppos = cam.Model(**sim.Suns().begin());
60         assets.shaders.planet_surface.Activate();
61         assets.shaders.planet_surface.SetTexture(assets.textures.tiles);
62         assets.shaders.planet_surface.SetLight(glm::vec3(cam.View() * ppos[3]), glm::vec3(1.0f, 1.0f, 1.0f), 1.0e6f);
63
64         for (auto planet : sim.Planets()) {
65                 assets.shaders.planet_surface.SetMVP(cam.Model(*planet), cam.View(), cam.Projection());
66                 planet->Draw(assets, viewport);
67         }
68
69         assets.shaders.sun_surface.Activate();
70         for (auto sun : sim.Suns()) {
71                 double sun_radius = sun->Radius();
72                 assets.shaders.sun_surface.SetMVP(
73                         cam.Model(*sun) * glm::scale(glm::vec3(sun_radius, sun_radius, sun_radius)),
74                         cam.View(), cam.Projection());
75                 assets.shaders.sun_surface.SetLight(glm::vec3(1.0f, 1.0f, 1.0f), 1.0e6f);
76                 assets.shaders.sun_surface.Draw();
77         }
78 }
79
80 }
81 }