]> git.localhorst.tv Git - sdl-test7.git/blob - src/app/Application.cpp
imported current version
[sdl-test7.git] / src / app / Application.cpp
1 /*
2  * Application.cpp
3  *
4  *  Created on: Apr 8, 2012
5  *      Author: holy
6  */
7
8 #include "Application.h"
9
10 #include "State.h"
11
12 #include <cassert>
13
14 namespace app {
15
16 Application::Application(sdl::InitScreen *screen, State *initialState)
17 : screen(screen)
18 , states()
19 , last(SDL_GetTicks()) {
20         assert(screen && "cannot create application without screen");
21         assert(initialState && "cannot create application without initial state");
22         RealPushState(initialState);
23 }
24
25 Application::~Application(void) {
26         PopAllStates();
27 }
28
29
30 State *Application::CurrentState(void) {
31         return states.top();
32 }
33
34 void Application::ChangeState(State *s) {
35         RealPopState();
36         RealPushState(s);
37 }
38
39 void Application::PushState(State *s) {
40         RealPushState(s);
41 }
42
43 void Application::RealPushState(State *s) {
44         states.push(s);
45         s->EnterState(this, screen->Screen());
46 }
47
48 void Application::PopState(void) {
49         RealPopState();
50 }
51
52 void Application::RealPopState(void) {
53         if (states.empty()) return;
54         states.top()->ExitState();
55         delete states.top();
56         states.pop();
57 }
58
59 void Application::Quit(void) {
60         PopAllStates();
61 }
62
63 void Application::PopAllStates(void) {
64         while (!states.empty()) {
65                 RealPopState();
66         }
67 }
68
69
70 void Application::Run(void) {
71         while (CurrentState()) {
72                 Loop();
73         }
74 }
75
76 void Application::Loop(void) {
77         Uint32 now(SDL_GetTicks());
78         Uint32 deltaT(now - last);
79         if (deltaT > 34) deltaT = 34;
80
81         HandleEvents();
82         UpdateWorld(deltaT);
83         Render();
84
85         last = now;
86 }
87
88
89 void Application::HandleEvents(void) {
90         if (!CurrentState()) return;
91         SDL_Event event;
92         while (SDL_PollEvent(&event)) {
93                 switch (event.type) {
94                         case SDL_QUIT:
95                                 PopAllStates();
96                                 break;
97                         default:
98                                 CurrentState()->HandleEvent(event);
99                                 break;
100                 }
101         }
102 }
103
104 void Application::UpdateWorld(Uint32 deltaT) {
105         if (!CurrentState()) return;
106         for (Uint32 i(0); i < deltaT; ++i) {
107                 CurrentState()->UpdateWorld(0.001f);
108         }
109 }
110
111 void Application::Render(void) {
112         if (!CurrentState()) return;
113         CurrentState()->Render(screen->Screen());
114         screen->Flip();
115 }
116
117 }