Pause the game when window loses focus, fixes #513
[supertux.git] / src / supertux / screen_manager.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //                2014 Ingo Ruhnke <grumbel@gmail.com>
4 //
5 //  This program is free software: you can redistribute it and/or modify
6 //  it under the terms of the GNU General Public License as published by
7 //  the Free Software Foundation, either version 3 of the License, or
8 //  (at your option) any later version.
9 //
10 //  This program is distributed in the hope that it will be useful,
11 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 //  GNU General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 #include "supertux/screen_manager.hpp"
19
20 #include "audio/sound_manager.hpp"
21 #include "control/input_manager.hpp"
22 #include "gui/menu.hpp"
23 #include "gui/menu_manager.hpp"
24 #include "scripting/scripting.hpp"
25 #include "scripting/squirrel_util.hpp"
26 #include "scripting/time_scheduler.hpp"
27 #include "supertux/console.hpp"
28 #include "supertux/constants.hpp"
29 #include "supertux/gameconfig.hpp"
30 #include "supertux/game_session.hpp"
31 #include "supertux/globals.hpp"
32 #include "supertux/main.hpp"
33 #include "supertux/menu/menu_storage.hpp"
34 #include "supertux/player_status.hpp"
35 #include "supertux/resources.hpp"
36 #include "supertux/screen.hpp"
37 #include "supertux/screen_fade.hpp"
38 #include "supertux/timer.hpp"
39 #include "video/drawing_context.hpp"
40 #include "video/renderer.hpp"
41
42 #include <stdio.h>
43 /** ticks (as returned from SDL_GetTicks) per frame */
44 static const Uint32 TICKS_PER_FRAME = (Uint32) (1000.0 / LOGICAL_FPS);
45 /** don't skip more than every 2nd frame */
46 static const int MAX_FRAME_SKIP = 2;
47
48 ScreenManager::ScreenManager() :
49   m_waiting_threads(),
50   m_menu_storage(new MenuStorage),
51   m_menu_manager(new MenuManager),
52   m_speed(1.0),
53   m_actions(),
54   m_fps(0),
55   m_screen_fade(),
56   m_screen_stack(),
57   m_screenshot_requested(false)
58 {
59   using namespace scripting;
60   TimeScheduler::instance = new TimeScheduler();
61 }
62
63 ScreenManager::~ScreenManager()
64 {
65   using namespace scripting;
66   delete TimeScheduler::instance;
67   TimeScheduler::instance = NULL;
68 }
69
70 void
71 ScreenManager::push_screen(std::unique_ptr<Screen> screen, std::unique_ptr<ScreenFade> screen_fade)
72 {
73   log_debug << "ScreenManager::push_screen(): " << screen.get() << std::endl;
74   assert(screen);
75
76   m_screen_fade = std::move(screen_fade);
77   m_actions.push_back(Action(Action::PUSH_ACTION, std::move(screen)));
78 }
79
80 void
81 ScreenManager::pop_screen(std::unique_ptr<ScreenFade> screen_fade)
82 {
83   log_debug << "ScreenManager::pop_screen(): stack_size: " << m_screen_stack.size() << std::endl;
84
85   m_screen_fade = std::move(screen_fade);
86   m_actions.push_back(Action(Action::POP_ACTION));
87 }
88
89 void
90 ScreenManager::set_screen_fade(std::unique_ptr<ScreenFade> screen_fade)
91 {
92   m_screen_fade = std::move(screen_fade);
93 }
94
95 void
96 ScreenManager::quit(std::unique_ptr<ScreenFade> screen_fade)
97 {
98   m_screen_fade = std::move(screen_fade);
99   m_actions.push_back(Action(Action::QUIT_ACTION));
100 }
101
102 void
103 ScreenManager::set_speed(float speed)
104 {
105   m_speed = speed;
106 }
107
108 float
109 ScreenManager::get_speed() const
110 {
111   return m_speed;
112 }
113
114 void
115 ScreenManager::draw_fps(DrawingContext& context, float fps_fps)
116 {
117   char str[60];
118   snprintf(str, sizeof(str), "%3.1f", fps_fps);
119   const char* fpstext = "FPS";
120   context.draw_text(Resources::small_font, fpstext,
121                     Vector(SCREEN_WIDTH - Resources::small_font->get_text_width(fpstext) - Resources::small_font->get_text_width(" 99999") - BORDER_X,
122                            BORDER_Y + 20), ALIGN_LEFT, LAYER_HUD);
123   context.draw_text(Resources::small_font, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), ALIGN_RIGHT, LAYER_HUD);
124 }
125
126 void
127 ScreenManager::draw(DrawingContext& context)
128 {
129   assert(!m_screen_stack.empty());
130
131   static Uint32 fps_ticks = SDL_GetTicks();
132
133   m_screen_stack.back()->draw(context);
134   m_menu_manager->draw(context);
135
136   if (m_screen_fade)
137   {
138     m_screen_fade->draw(context);
139   }
140
141   Console::current()->draw(context);
142
143   if (g_config->show_fps)
144   {
145     draw_fps(context, m_fps);
146   }
147
148   // if a screenshot was requested, pass request on to drawing_context
149   if (m_screenshot_requested)
150   {
151     context.take_screenshot();
152     m_screenshot_requested = false;
153   }
154   context.do_drawing();
155
156   /* Calculate frames per second */
157   if (g_config->show_fps)
158   {
159     static int frame_count = 0;
160     ++frame_count;
161
162     if (SDL_GetTicks() - fps_ticks >= 500)
163     {
164       m_fps = (float) frame_count / .5;
165       frame_count = 0;
166       fps_ticks = SDL_GetTicks();
167     }
168   }
169 }
170
171 void
172 ScreenManager::update_gamelogic(float elapsed_time)
173 {
174   scripting::Scripting::current()->update_debugger();
175   scripting::TimeScheduler::instance->update(game_time);
176
177   if (!m_screen_stack.empty())
178   {
179     m_screen_stack.back()->update(elapsed_time);
180   }
181
182   m_menu_manager->process_input();
183
184   if (m_screen_fade)
185   {
186     m_screen_fade->update(elapsed_time);
187   }
188
189   Console::current()->update(elapsed_time);
190 }
191
192 void
193 ScreenManager::process_events()
194 {
195   InputManager::current()->update();
196   SDL_Event event;
197   while (SDL_PollEvent(&event))
198   {
199     InputManager::current()->process_event(event);
200
201     m_menu_manager->event(event);
202
203     switch(event.type)
204     {
205       case SDL_QUIT:
206         quit();
207         break;
208
209       case SDL_WINDOWEVENT:
210         switch(event.window.event)
211         {
212           case SDL_WINDOWEVENT_RESIZED:
213             VideoSystem::current()->resize(event.window.data1,
214                                            event.window.data2);
215             m_menu_manager->on_window_resize();
216             break;
217
218           case SDL_WINDOWEVENT_FOCUS_LOST:
219             if(GameSession::current() != NULL) {
220               GameSession::current()->toggle_pause();
221             }
222             break;
223         }
224         break;
225
226       case SDL_KEYDOWN:
227         if (event.key.keysym.sym == SDLK_F10)
228         {
229           g_config->show_fps = !g_config->show_fps;
230         }
231         else if (event.key.keysym.sym == SDLK_F11)
232         {
233           g_config->use_fullscreen = !g_config->use_fullscreen;
234           VideoSystem::current()->apply_config();
235           m_menu_manager->on_window_resize();
236         }
237         else if (event.key.keysym.sym == SDLK_PRINTSCREEN ||
238                  event.key.keysym.sym == SDLK_F12)
239         {
240           take_screenshot();
241         }
242         else if (event.key.keysym.sym == SDLK_F1 &&
243                  event.key.keysym.mod & KMOD_CTRL)
244         {
245           Console::current()->toggle();
246           g_config->console_enabled = true;
247           g_config->save();
248         }
249         else if (event.key.keysym.sym == SDLK_F2 &&
250                  event.key.keysym.mod & KMOD_CTRL)
251         {
252           g_config->developer_mode = !g_config->developer_mode;
253           log_info << "developer mode: " << g_config->developer_mode << std::endl;
254         }
255         break;
256     }
257   }
258 }
259
260 bool
261 ScreenManager::has_pending_fadeout() const
262 {
263   return m_screen_fade && !m_screen_fade->done();
264 }
265
266 void
267 ScreenManager::handle_screen_switch()
268 {
269   if (has_pending_fadeout())
270   {
271     // wait till the fadeout is completed before switching screens
272   }
273   else
274   {
275     m_screen_fade.reset();
276
277     // keep track of the current screen, as only that needs a call to Screen::leave()
278     Screen* current_screen = m_screen_stack.empty() ? nullptr : m_screen_stack.back().get();
279
280     // Screen::setup() might push more screens, so loop till everything is done
281     while (!m_actions.empty())
282     {
283       // move actions to a new vector since setup() might modify it
284       auto actions = std::move(m_actions);
285
286       for(auto it = actions.begin(); it != actions.end(); ++it)
287       {
288         auto& action = *it;
289
290         switch (action.type)
291         {
292           case Action::POP_ACTION:
293             assert(!m_screen_stack.empty());
294             if (current_screen == m_screen_stack.back().get())
295             {
296               m_screen_stack.back()->leave();
297             }
298             m_screen_stack.pop_back();
299             break;
300
301           case Action::PUSH_ACTION:
302             assert(action.screen);
303
304             if (!m_screen_stack.empty())
305             {
306               if (current_screen == m_screen_stack.back().get())
307               {
308                 m_screen_stack.back()->leave();
309               }
310             }
311             m_screen_stack.push_back(std::move(action.screen));
312             break;
313
314           case Action::QUIT_ACTION:
315             m_screen_stack.clear();
316             break;
317         }
318       }
319
320       if (!m_screen_stack.empty())
321       {
322         m_screen_stack.back()->setup();
323         m_speed = 1.0;
324         m_waiting_threads.wakeup();
325       }
326     }
327   }
328 }
329
330 void
331 ScreenManager::run(DrawingContext &context)
332 {
333   Uint32 last_ticks = 0;
334   Uint32 elapsed_ticks = 0;
335
336   handle_screen_switch();
337
338   while (!m_screen_stack.empty())
339   {
340     Uint32 ticks = SDL_GetTicks();
341     elapsed_ticks += ticks - last_ticks;
342     last_ticks = ticks;
343
344     Uint32 ticks_per_frame = (Uint32) (TICKS_PER_FRAME * g_game_speed);
345
346     if (elapsed_ticks > ticks_per_frame*4)
347     {
348       // when the game loads up or levels are switched the
349       // elapsed_ticks grows extremely large, so we just ignore those
350       // large time jumps
351       elapsed_ticks = 0;
352     }
353
354     if (elapsed_ticks < ticks_per_frame)
355     {
356       Uint32 delay_ticks = ticks_per_frame - elapsed_ticks;
357       SDL_Delay(delay_ticks);
358       last_ticks += delay_ticks;
359       elapsed_ticks += delay_ticks;
360     }
361
362     int frames = 0;
363
364     while (elapsed_ticks >= ticks_per_frame && frames < MAX_FRAME_SKIP)
365     {
366       elapsed_ticks -= ticks_per_frame;
367       float timestep = 1.0 / LOGICAL_FPS;
368       real_time += timestep;
369       timestep *= m_speed;
370       game_time += timestep;
371
372       process_events();
373       update_gamelogic(timestep);
374       frames += 1;
375     }
376
377     if (!m_screen_stack.empty())
378     {
379       draw(context);
380     }
381
382     SoundManager::current()->update();
383
384     handle_screen_switch();
385   }
386 }
387
388 void
389 ScreenManager::take_screenshot()
390 {
391   m_screenshot_requested = true;
392 }
393
394 /* EOF */