]> git.localhorst.tv Git - blank.git/blobdiff - src/app/app.cpp
enhanced application state control
[blank.git] / src / app / app.cpp
index 8577e45b48383ded5ef5d793b27a152cf424af42..880dc7118eaf2fcaa43e93b2a2e92c6ec91de5f1 100644 (file)
@@ -1,58 +1,41 @@
 #include "Application.hpp"
 #include "Assets.hpp"
+#include "Environment.hpp"
 #include "FrameCounter.hpp"
+#include "State.hpp"
+#include "StateControl.hpp"
 
+#include "init.hpp"
+#include "../audio/Sound.hpp"
+#include "../graphics/ArrayTexture.hpp"
 #include "../graphics/Font.hpp"
+#include "../graphics/Texture.hpp"
 #include "../world/BlockType.hpp"
 #include "../world/Entity.hpp"
 
 #include <iostream>
 #include <stdexcept>
+#include <SDL_image.h>
 
 using std::string;
 
 
-namespace {
-
-string get_asset_path() {
-       char *base = SDL_GetBasePath();
-       string assets(base);
-       assets += "assets/";
-       SDL_free(base);
-       return assets;
-}
-
-}
-
 namespace blank {
 
-Application::Application(const Config &config)
-: init(config.doublebuf, config.multisampling)
-, viewport()
-, assets(get_asset_path())
-, counter()
-, world(config.world)
-, interface(config.interface, assets, counter, world)
-, test_controller(MakeTestEntity(world))
-, running(false) {
-       viewport.VSync(config.vsync);
+Application::Application(Environment &e)
+: env(e)
+, states() {
+
 }
 
-Entity &Application::MakeTestEntity(World &world) {
-       Entity &e = world.AddEntity();
-       e.Name("test");
-       e.Position({ 0.0f, 0.0f, 0.0f });
-       e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
-       e.WorldCollidable(true);
-       e.SetShape(world.BlockTypes()[1].shape, { 1.0f, 1.0f, 0.0f });
-       e.AngularVelocity(glm::quat(glm::vec3{ 0.00001f, 0.000006f, 0.000013f }));
-       return e;
+Application::~Application() {
+       env.audio.StopAll();
 }
 
 
 void Application::RunN(size_t n) {
        Uint32 last = SDL_GetTicks();
-       for (size_t i = 0; i < n; ++i) {
+       for (size_t i = 0; HasState() && i < n; ++i) {
                Uint32 now = SDL_GetTicks();
                int delta = now - last;
                Loop(delta);
@@ -63,7 +46,7 @@ void Application::RunN(size_t n) {
 void Application::RunT(size_t t) {
        Uint32 last = SDL_GetTicks();
        Uint32 finish = last + t;
-       while (last < finish) {
+       while (HasState() && last < finish) {
                Uint32 now = SDL_GetTicks();
                int delta = now - last;
                Loop(delta);
@@ -72,17 +55,16 @@ void Application::RunT(size_t t) {
 }
 
 void Application::RunS(size_t n, size_t t) {
-       for (size_t i = 0; i < n; ++i) {
+       for (size_t i = 0; HasState() && i < n; ++i) {
                Loop(t);
        }
 }
 
 
 void Application::Run() {
-       running = true;
        Uint32 last = SDL_GetTicks();
-       init.window.GrabMouse();
-       while (running) {
+       env.window.GrabMouse();
+       while (HasState()) {
                Uint32 now = SDL_GetTicks();
                int delta = now - last;
                Loop(delta);
@@ -91,61 +73,48 @@ void Application::Run() {
 }
 
 void Application::Loop(int dt) {
-       counter.EnterFrame();
+       env.counter.EnterFrame();
        HandleEvents();
+       if (!HasState()) return;
        Update(dt);
+       env.state.Commit(*this);
+       if (!HasState()) return;
        Render();
-       counter.ExitFrame();
+       env.counter.ExitFrame();
 }
 
 
 void Application::HandleEvents() {
-       counter.EnterHandle();
+       env.counter.EnterHandle();
        SDL_Event event;
-       while (SDL_PollEvent(&event)) {
-               switch (event.type) {
-                       case SDL_KEYDOWN:
-                               interface.HandlePress(event.key);
-                               break;
-                       case SDL_KEYUP:
-                               interface.HandleRelease(event.key);
-                               break;
-                       case SDL_MOUSEBUTTONDOWN:
-                               interface.HandlePress(event.button);
-                               break;
-                       case SDL_MOUSEBUTTONUP:
-                               interface.HandleRelease(event.button);
-                               break;
-                       case SDL_MOUSEMOTION:
-                               interface.Handle(event.motion);
-                               break;
-                       case SDL_MOUSEWHEEL:
-                               interface.Handle(event.wheel);
-                               break;
-                       case SDL_QUIT:
-                               running = false;
-                               break;
-                       case SDL_WINDOWEVENT:
-                               Handle(event.window);
-                               break;
-                       default:
-                               break;
-               }
+       while (HasState() && SDL_PollEvent(&event)) {
+               Handle(event);
+               env.state.Commit(*this);
+       }
+       env.counter.ExitHandle();
+}
+
+void Application::Handle(const SDL_Event &event) {
+       switch (event.type) {
+               case SDL_WINDOWEVENT:
+                       Handle(event.window);
+                       break;
+               default:
+                       GetState().Handle(event);
+                       break;
        }
-       counter.ExitHandle();
 }
 
 void Application::Handle(const SDL_WindowEvent &event) {
        switch (event.event) {
                case SDL_WINDOWEVENT_FOCUS_GAINED:
-                       init.window.GrabMouse();
+                       env.window.GrabMouse();
                        break;
                case SDL_WINDOWEVENT_FOCUS_LOST:
-                       init.window.ReleaseMouse();
+                       env.window.ReleaseMouse();
                        break;
                case SDL_WINDOWEVENT_RESIZED:
-                       viewport.Resize(event.data1, event.data2);
-                       interface.Resize(viewport);
+                       env.viewport.Resize(event.data1, event.data2);
                        break;
                default:
                        break;
@@ -153,29 +122,104 @@ void Application::Handle(const SDL_WindowEvent &event) {
 }
 
 void Application::Update(int dt) {
-       counter.EnterUpdate();
-       interface.Update(dt);
-       test_controller.Update(dt);
-       world.Update(dt);
-       counter.ExitUpdate();
+       env.counter.EnterUpdate();
+       if (HasState()) {
+               GetState().Update(dt);
+       }
+       env.counter.ExitUpdate();
 }
 
 void Application::Render() {
        // gl implementation may (and will probably) delay vsync blocking until
        // the first write after flipping, which is this clear call
-       viewport.Clear();
-       counter.EnterRender();
+       env.viewport.Clear();
+       env.counter.EnterRender();
 
-       world.Render(viewport);
-       interface.Render(viewport);
+       if (HasState()) {
+               GetState().Render(env.viewport);
+       }
 
-       counter.ExitRender();
-       init.window.Flip();
+       env.counter.ExitRender();
+       env.window.Flip();
+}
+
+
+void Application::PushState(State *s) {
+       if (!states.empty()) {
+               states.top()->OnPause();
+       }
+       states.emplace(s);
+       ++s->ref_count;
+       if (s->ref_count == 1) {
+               s->OnEnter();
+       }
+       s->OnResume();
+}
+
+State *Application::PopState() {
+       State *s = states.top();
+       states.pop();
+       s->OnPause();
+       s->OnExit();
+       if (!states.empty()) {
+               states.top()->OnResume();
+       }
+       return s;
+}
+
+State *Application::SwitchState(State *s_new) {
+       State *s_old = states.top();
+       states.top() = s_new;
+       --s_old->ref_count;
+       ++s_new->ref_count;
+       s_old->OnPause();
+       if (s_old->ref_count == 0) {
+               s_old->OnExit();
+       }
+       if (s_new->ref_count == 1) {
+               s_new->OnEnter();
+       }
+       s_new->OnResume();
+       return s_old;
+}
+
+State &Application::GetState() {
+       return *states.top();
+}
+
+bool Application::HasState() const noexcept {
+       return !states.empty();
+}
+
+
+void StateControl::Commit(Application &app) {
+       while (!cue.empty()) {
+               Memo m(cue.front());
+               cue.pop();
+               switch (m.cmd) {
+                       case PUSH:
+                               app.PushState(m.state);
+                               break;
+                       case SWITCH:
+                               app.SwitchState(m.state);
+                               break;
+                       case POP:
+                               app.PopState();
+                               break;
+                       case POP_ALL:
+                               while (app.HasState()) {
+                                       app.PopState();
+                               }
+                               break;
+               }
+       }
 }
 
 
 Assets::Assets(const string &base)
-: fonts(base + "fonts/") {
+: fonts(base + "fonts/")
+, sounds(base + "sounds/")
+, textures(base + "textures/") {
 
 }
 
@@ -184,6 +228,40 @@ Font Assets::LoadFont(const string &name, int size) const {
        return Font(full.c_str(), size);
 }
 
+Sound Assets::LoadSound(const string &name) const {
+       string full = sounds + name + ".wav";
+       return Sound(full.c_str());
+}
+
+Texture Assets::LoadTexture(const string &name) const {
+       string full = textures + name + ".png";
+       Texture tex;
+       SDL_Surface *srf = IMG_Load(full.c_str());
+       if (!srf) {
+               throw SDLError("IMG_Load");
+       }
+       tex.Bind();
+       tex.Data(*srf);
+       SDL_FreeSurface(srf);
+       return tex;
+}
+
+void Assets::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
+       string full = textures + name + ".png";
+       SDL_Surface *srf = IMG_Load(full.c_str());
+       if (!srf) {
+               throw SDLError("IMG_Load");
+       }
+       tex.Bind();
+       try {
+               tex.Data(layer, *srf);
+       } catch (...) {
+               SDL_FreeSurface(srf);
+               throw;
+       }
+       SDL_FreeSurface(srf);
+}
+
 
 void FrameCounter::EnterFrame() noexcept {
        last_enter = SDL_GetTicks();
@@ -195,7 +273,7 @@ void FrameCounter::EnterHandle() noexcept {
 }
 
 void FrameCounter::ExitHandle() noexcept {
-       running.handle += Tick();
+       current.handle = Tick();
 }
 
 void FrameCounter::EnterUpdate() noexcept {
@@ -203,7 +281,7 @@ void FrameCounter::EnterUpdate() noexcept {
 }
 
 void FrameCounter::ExitUpdate() noexcept {
-       running.update += Tick();
+       current.update = Tick();
 }
 
 void FrameCounter::EnterRender() noexcept {
@@ -211,19 +289,19 @@ void FrameCounter::EnterRender() noexcept {
 }
 
 void FrameCounter::ExitRender() noexcept {
-       running.render += Tick();
+       current.render = Tick();
 }
 
 void FrameCounter::ExitFrame() noexcept {
        Uint32 now = SDL_GetTicks();
-       running.total += now - last_enter;
+       current.total = now - last_enter;
+       current.running = current.handle + current.update + current.render;
+       current.waiting = current.total - current.running;
+       Accumulate();
+
        ++cur_frame;
        if (cur_frame >= NUM_FRAMES) {
-               avg.handle = running.handle * factor;
-               avg.update = running.update * factor;
-               avg.render = running.render * factor;
-               avg.total = running.total * factor;
-               running = Frame<int>{};
+               Push();
                cur_frame = 0;
                changed = true;
        } else {
@@ -238,14 +316,35 @@ int FrameCounter::Tick() noexcept {
        return delta;
 }
 
-void FrameCounter::Print(std::ostream &out) const {
-       out << "frame:     " << AvgFrame() << std::endl;
-       out << "  handle:  " << AvgHandle() << std::endl;
-       out << "  update:  " << AvgUpdate() << std::endl;
-       out << "  render:  " << AvgRender() << std::endl;
-       out << "  running: " << AvgRunning() << std::endl;
-       out << "  waiting: " << AvgWaiting() << std::endl;
-       out << std::endl;
+void FrameCounter::Accumulate() noexcept {
+       sum.handle += current.handle;
+       sum.update += current.update;
+       sum.render += current.render;
+       sum.running += current.running;
+       sum.waiting += current.waiting;
+       sum.total += current.total;
+
+       max.handle = std::max(current.handle, max.handle);
+       max.update = std::max(current.update, max.update);
+       max.render = std::max(current.render, max.render);
+       max.running = std::max(current.running, max.running);
+       max.waiting = std::max(current.waiting, max.waiting);
+       max.total = std::max(current.total, max.total);
+
+       current = Frame<int>();
+}
+
+void FrameCounter::Push() noexcept {
+       peak = max;
+       avg.handle = sum.handle * factor;
+       avg.update = sum.update * factor;
+       avg.render = sum.render * factor;
+       avg.running = sum.running * factor;
+       avg.waiting = sum.waiting * factor;
+       avg.total = sum.total * factor;
+
+       sum = Frame<int>();
+       max = Frame<int>();
 }
 
 }