X-Git-Url: https://git.localhorst.tv/?a=blobdiff_plain;f=src%2Fapp%2FApplication.cpp;fp=src%2Fapp%2FApplication.cpp;h=bcf4f29690bb3158f30ae8a108634b87214e6b4a;hb=8b4877fe48d21d7e789cf52f81c1d6a87b06bcbc;hp=0000000000000000000000000000000000000000;hpb=42db59e3850c958821e8396fadc20fbeb71050c4;p=sdl-test8.git diff --git a/src/app/Application.cpp b/src/app/Application.cpp new file mode 100644 index 0000000..bcf4f29 --- /dev/null +++ b/src/app/Application.cpp @@ -0,0 +1,119 @@ +/* + * Application.cpp + * + * Created on: Apr 8, 2012 + * Author: holy + */ + +#include "Application.h" + +#include "State.h" + +#include + +namespace app { + +Application::Application(sdl::InitScreen *screen, State *initialState) +: screen(screen) +, states() +, timer() +, last(SDL_GetTicks()) { + assert(screen && "cannot create application without screen"); + assert(initialState && "cannot create application without initial state"); + RealPushState(initialState); +} + +Application::~Application(void) { + PopAllStates(); +} + + +State *Application::CurrentState(void) { + return states.top(); +} + +void Application::ChangeState(State *s) { + RealPopState(); + RealPushState(s); +} + +void Application::PushState(State *s) { + RealPushState(s); +} + +void Application::RealPushState(State *s) { + states.push(s); + s->EnterState(this, screen->Screen()); +} + +void Application::PopState(void) { + RealPopState(); +} + +void Application::RealPopState(void) { + if (states.empty()) return; + states.top()->ExitState(); + delete states.top(); + states.pop(); +} + +void Application::Quit(void) { + PopAllStates(); +} + +void Application::PopAllStates(void) { + while (!states.empty()) { + RealPopState(); + } +} + + +void Application::Run(void) { + while (CurrentState()) { + Loop(); + } +} + +void Application::Loop(void) { + Uint32 now(SDL_GetTicks()); + Uint32 deltaT(now - last); + if (deltaT > 34) deltaT = 34; + + HandleEvents(); + UpdateWorld(deltaT); + Render(); + + last = now; +} + + +void Application::HandleEvents(void) { + if (!CurrentState()) return; + SDL_Event event; + while (SDL_PollEvent(&event)) { + switch (event.type) { + case SDL_QUIT: + PopAllStates(); + break; + default: + CurrentState()->HandleEvent(event); + break; + } + } +} + +void Application::UpdateWorld(Uint32 deltaT) { + if (!CurrentState()) return; + for (Uint32 i(0); i < deltaT; ++i) { + timer.Update(0.001); + CurrentState()->UpdateWorld(timer); + } +} + +void Application::Render(void) { + if (!CurrentState()) return; + CurrentState()->Render(screen->Screen()); + screen->Flip(); +} + +}