Merged changes from branches/supertux-milestone2-grumbel/ to trunk/supertux/
[supertux.git] / src / supertux / mainloop.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "supertux/mainloop.hpp"
18
19 #include "audio/sound_manager.hpp"
20 #include "control/joystickkeyboardcontroller.hpp"
21 #include "gui/menu.hpp"
22 #include "scripting/squirrel_util.hpp"
23 #include "scripting/time_scheduler.hpp"
24 #include "supertux/constants.hpp"
25 #include "supertux/console.hpp"
26 #include "supertux/gameconfig.hpp"
27 #include "supertux/main.hpp"
28 #include "supertux/player_status.hpp"
29 #include "supertux/resources.hpp"
30 #include "supertux/screen_fade.hpp"
31 #include "supertux/screen.hpp"
32 #include "supertux/timer.hpp"
33 #include "video/drawing_context.hpp"
34 #include "video/renderer.hpp"
35
36 /** ticks (as returned from SDL_GetTicks) per frame */
37 static const Uint32 TICKS_PER_FRAME = (Uint32) (1000.0 / LOGICAL_FPS);
38 /** don't skip more than every 2nd frame */
39 static const int MAX_FRAME_SKIP = 2;
40
41 float g_game_speed = 1.0f;
42
43 MainLoop* g_main_loop = NULL;
44
45 MainLoop::MainLoop() :
46   speed(1.0), 
47   nextpop(false), 
48   nextpush(false), 
49   fps(0), 
50   screenshot_requested(false)
51 {
52   using namespace Scripting;
53   TimeScheduler::instance = new TimeScheduler();
54 }
55
56 MainLoop::~MainLoop()
57 {
58   using namespace Scripting;
59   delete TimeScheduler::instance;
60   TimeScheduler::instance = NULL;
61
62   for(std::vector<Screen*>::iterator i = screen_stack.begin();
63       i != screen_stack.end(); ++i) {
64     delete *i;
65   }
66 }
67
68 void
69 MainLoop::push_screen(Screen* screen, ScreenFade* screen_fade)
70 {
71   this->next_screen.reset(screen);
72   this->screen_fade.reset(screen_fade);
73   nextpush = !nextpop;
74   nextpop = false;
75   speed = 1.0f;
76 }
77
78 void
79 MainLoop::exit_screen(ScreenFade* screen_fade)
80 {
81   next_screen.reset(NULL);
82   this->screen_fade.reset(screen_fade);
83   nextpop = true;
84   nextpush = false;
85 }
86
87 void
88 MainLoop::set_screen_fade(ScreenFade* screen_fade)
89 {
90   this->screen_fade.reset(screen_fade);
91 }
92
93 void
94 MainLoop::quit(ScreenFade* screen_fade)
95 {
96   for(std::vector<Screen*>::iterator i = screen_stack.begin();
97       i != screen_stack.end(); ++i)
98     delete *i;
99   screen_stack.clear();
100
101   exit_screen(screen_fade);
102 }
103
104 void
105 MainLoop::set_speed(float speed)
106 {
107   this->speed = speed;
108 }
109
110 float
111 MainLoop::get_speed() const
112 {
113   return speed;
114 }
115
116 bool
117 MainLoop::has_no_pending_fadeout() const
118 {
119   return screen_fade.get() == NULL || screen_fade->done();
120 }
121
122 void
123 MainLoop::draw_fps(DrawingContext& context, float fps_fps)
124 {
125   char str[60];
126   snprintf(str, sizeof(str), "%3.1f", fps_fps);
127   const char* fpstext = "FPS";
128   context.draw_text(small_font, fpstext, Vector(SCREEN_WIDTH - small_font->get_text_width(fpstext) - small_font->get_text_width(" 99999") - BORDER_X, BORDER_Y + 20), ALIGN_LEFT, LAYER_HUD);
129   context.draw_text(small_font, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), ALIGN_RIGHT, LAYER_HUD);
130 }
131
132 void
133 MainLoop::draw(DrawingContext& context)
134 {
135   static Uint32 fps_ticks = SDL_GetTicks();
136   static int frame_count = 0;
137
138   current_screen->draw(context);
139   if(Menu::current() != NULL)
140     Menu::current()->draw(context);
141   if(screen_fade.get() != NULL)
142     screen_fade->draw(context);
143   Console::instance->draw(context);
144
145   if(g_config->show_fps)
146     draw_fps(context, fps);
147
148   // if a screenshot was requested, pass request on to drawing_context
149   if (screenshot_requested) {
150     context.take_screenshot();
151     screenshot_requested = false;
152   }
153   context.do_drawing();
154
155   /* Calculate frames per second */
156   if(g_config->show_fps)
157   {
158     ++frame_count;
159
160     if(SDL_GetTicks() - fps_ticks >= 500)
161     {
162       fps = (float) frame_count / .5;
163       frame_count = 0;
164       fps_ticks = SDL_GetTicks();
165     }
166   }
167 }
168
169 void
170 MainLoop::update_gamelogic(float elapsed_time)
171 {
172   Scripting::update_debugger();
173   Scripting::TimeScheduler::instance->update(game_time);
174   current_screen->update(elapsed_time);
175   if (Menu::current() != NULL)
176     Menu::current()->update();
177   if(screen_fade.get() != NULL)
178     screen_fade->update(elapsed_time);
179   Console::instance->update(elapsed_time);
180 }
181
182 void
183 MainLoop::process_events()
184 {
185   g_main_controller->update();
186   Uint8* keystate = SDL_GetKeyState(NULL);
187   SDL_Event event;
188   while(SDL_PollEvent(&event)) 
189   {
190     g_main_controller->process_event(event);
191
192     if(Menu::current() != NULL)
193       Menu::current()->event(event);
194
195     switch(event.type)
196     {
197       case SDL_QUIT:
198         quit();
199         break;
200               
201       case SDL_VIDEORESIZE:
202         Renderer::instance()->resize(event.resize.w, event.resize.h);
203         Menu::recalc_pos();
204         break;
205             
206       case SDL_KEYDOWN:
207         if (event.key.keysym.sym == SDLK_F10)
208         {
209           g_config->show_fps = !g_config->show_fps;
210         }
211         if (event.key.keysym.sym == SDLK_F11) 
212         {
213           g_config->use_fullscreen = !g_config->use_fullscreen;
214           init_video();
215           Menu::recalc_pos();
216         }
217         else if (event.key.keysym.sym == SDLK_PRINT ||
218                  event.key.keysym.sym == SDLK_F12)
219         {
220           take_screenshot();
221         }
222         else if (event.key.keysym.sym == SDLK_F1 &&
223                  (keystate[SDLK_LCTRL] || keystate[SDLK_RCTRL]) &&
224                  keystate[SDLK_c])
225         {
226           Console::instance->toggle();
227           g_config->console_enabled = true;
228           g_config->save();
229         }
230         break;
231     }
232   }
233 }
234
235 void
236 MainLoop::handle_screen_switch()
237 {
238   while( (next_screen.get() != NULL || nextpop) &&
239          has_no_pending_fadeout()) {
240     if(current_screen.get() != NULL) {
241       current_screen->leave();
242     }
243
244     if(nextpop) {
245       if(screen_stack.empty()) {
246         running = false;
247         break;
248       }
249       next_screen.reset(screen_stack.back());
250       screen_stack.pop_back();
251     }
252     if(nextpush && current_screen.get() != NULL) {
253       screen_stack.push_back(current_screen.release());
254     }
255
256     nextpush = false;
257     nextpop = false;
258     speed = 1.0;
259     Screen* next_screen_ptr = next_screen.release();
260     next_screen.reset(0);
261     if(next_screen_ptr)
262       next_screen_ptr->setup();
263     current_screen.reset(next_screen_ptr);
264     screen_fade.reset(NULL);
265
266     waiting_threads.wakeup();
267   }
268 }
269
270 void
271 MainLoop::run(DrawingContext &context)
272 {
273   Uint32 last_ticks = 0;
274   Uint32 elapsed_ticks = 0;
275
276   running = true;
277   while(running) {
278
279     handle_screen_switch();
280     if(!running || current_screen.get() == NULL)
281       break;
282
283     Uint32 ticks = SDL_GetTicks();
284     elapsed_ticks += ticks - last_ticks;
285     last_ticks = ticks;
286
287     Uint32 ticks_per_frame = (Uint32) (TICKS_PER_FRAME * g_game_speed);
288
289     if (elapsed_ticks > ticks_per_frame*4) {
290       // when the game loads up or levels are switched the
291       // elapsed_ticks grows extremely large, so we just ignore those
292       // large time jumps
293       elapsed_ticks = 0;
294     }
295
296     if(elapsed_ticks < ticks_per_frame)
297     {
298       Uint32 delay_ticks = ticks_per_frame - elapsed_ticks;
299       SDL_Delay(delay_ticks);
300       last_ticks += delay_ticks;
301       elapsed_ticks += delay_ticks;
302     }
303
304     int frames = 0;
305
306     while(elapsed_ticks >= ticks_per_frame && frames < MAX_FRAME_SKIP) 
307     {
308       elapsed_ticks -= ticks_per_frame;
309       float timestep = 1.0 / LOGICAL_FPS;
310       real_time += timestep;
311       timestep *= speed;
312       game_time += timestep;
313
314       process_events();
315       update_gamelogic(timestep);
316       frames += 1;
317     }
318
319     draw(context);
320
321     sound_manager->update();
322   }
323 }
324
325 void 
326 MainLoop::take_screenshot()
327 {
328   screenshot_requested = true;
329 }
330
331 /* EOF */