Added MenuManager to keep track of created Menus
[supertux.git] / src / supertux / game_session.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/game_session.hpp"
18
19 #include <float.h>
20 #include <fstream>
21
22 #include "audio/sound_manager.hpp"
23 #include "control/joystickkeyboardcontroller.hpp"
24 #include "gui/menu.hpp"
25 #include "math/random_generator.hpp"
26 #include "object/camera.hpp"
27 #include "object/endsequence_fireworks.hpp"
28 #include "object/endsequence_walkleft.hpp"
29 #include "object/endsequence_walkright.hpp"
30 #include "object/level_time.hpp"
31 #include "object/player.hpp"
32 #include "scripting/squirrel_util.hpp"
33 #include "supertux/gameconfig.hpp"
34 #include "supertux/levelintro.hpp"
35 #include "supertux/globals.hpp"
36 #include "supertux/mainloop.hpp"
37 #include "supertux/menu/menu_manager.hpp"
38 #include "supertux/menu/options_menu.hpp"
39 #include "supertux/sector.hpp"
40 #include "util/file_system.hpp"
41 #include "util/gettext.hpp"
42 #include "worldmap/worldmap.hpp"
43
44 enum GameMenuIDs {
45   MNID_CONTINUE,
46   MNID_ABORTLEVEL
47 };
48
49 GameSession::GameSession(const std::string& levelfile_, Statistics* statistics) :
50   level(0), 
51   statistics_backdrop(),
52   scripts(),
53   currentsector(0),
54   levelnb(),
55   pause_menu_frame(),
56   end_sequence(0),
57   game_pause(),
58   speed_before_pause(),
59   levelfile(levelfile_), 
60   reset_sector(),
61   reset_pos(),
62   newsector(),
63   newspawnpoint(),
64   best_level_statistics(statistics),
65   capture_demo_stream(0), 
66   capture_file(),
67   playback_demo_stream(0), 
68   demo_controller(0),
69   game_menu(),
70   play_time(0), 
71   edit_mode(false), 
72   levelintro_shown(false)
73 {
74   currentsector = NULL;
75
76   game_pause = false;
77   speed_before_pause = g_main_loop->get_speed();
78
79   statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
80
81   restart_level();
82
83   game_menu.reset(new Menu());
84   game_menu->add_label(level->name);
85   game_menu->add_hl();
86   game_menu->add_entry(MNID_CONTINUE, _("Continue"));
87   game_menu->add_submenu(_("Options"), MenuManager::get_options_menu());
88   game_menu->add_hl();
89   game_menu->add_entry(MNID_ABORTLEVEL, _("Abort Level"));
90 }
91
92 void
93 GameSession::restart_level()
94 {
95
96   if (edit_mode) {
97     force_ghost_mode();
98     return;
99   }
100
101   game_pause   = false;
102   end_sequence = 0;
103
104   g_main_controller->reset();
105
106   currentsector = 0;
107
108   level.reset(new Level);
109   try {
110     level->load(levelfile);
111     level->stats.total_coins = level->get_total_coins();
112     level->stats.total_badguys = level->get_total_badguys();
113     level->stats.total_secrets = level->get_total_secrets();
114     level->stats.reset();
115
116     if(reset_sector != "") {
117       currentsector = level->get_sector(reset_sector);
118       if(!currentsector) {
119         std::stringstream msg;
120         msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
121         throw std::runtime_error(msg.str());
122       }
123       level->stats.declare_invalid();
124       currentsector->activate(reset_pos);
125     } else {
126       currentsector = level->get_sector("main");
127       if(!currentsector)
128         throw std::runtime_error("Couldn't find main sector");
129       play_time = 0;
130       currentsector->activate("main");
131     }
132   } catch(std::exception& e) {
133     log_fatal << "Couldn't start level: " << e.what() << std::endl;
134     g_main_loop->exit_screen();
135   }
136
137   sound_manager->stop_music();
138   currentsector->play_music(LEVEL_MUSIC);
139
140   if(capture_file != "") {
141     int newSeed=0;               // next run uses a new seed
142     while (newSeed == 0)            // which is the next non-zero random num.
143       newSeed = systemRandom.rand();
144     g_config->random_seed = systemRandom.srand(newSeed);
145     log_info << "Next run uses random seed " << g_config->random_seed <<std::endl;
146     record_demo(capture_file);
147   }
148 }
149
150 GameSession::~GameSession()
151 {
152   delete capture_demo_stream;
153   delete playback_demo_stream;
154   delete demo_controller;
155   MenuManager::free_options_menu();
156 }
157
158 void
159 GameSession::record_demo(const std::string& filename)
160 {
161   delete capture_demo_stream;
162
163   capture_demo_stream = new std::ofstream(filename.c_str());
164   if(!capture_demo_stream->good()) {
165     std::stringstream msg;
166     msg << "Couldn't open demo file '" << filename << "' for writing.";
167     throw std::runtime_error(msg.str());
168   }
169   capture_file = filename;
170
171   char buf[30];                            // save the seed in the demo file
172   snprintf(buf, sizeof(buf), "random_seed=%10d", g_config->random_seed);
173   for (int i=0; i==0 || buf[i-1]; i++)
174     capture_demo_stream->put(buf[i]);
175 }
176
177 int
178 GameSession::get_demo_random_seed(const std::string& filename)
179 {
180   std::istream* test_stream = new std::ifstream(filename.c_str());
181   if(test_stream->good()) {
182     char buf[30];                     // recall the seed from the demo file
183     int seed;
184     for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
185       test_stream->get(buf[i]);
186     if (sscanf(buf, "random_seed=%10d", &seed) == 1) {
187       log_info << "Random seed " << seed << " from demo file" << std::endl;
188       return seed;
189     }
190     else
191       log_info << "Demo file contains no random number" << std::endl;
192   }
193   return 0;
194 }
195
196 void
197 GameSession::play_demo(const std::string& filename)
198 {
199   delete playback_demo_stream;
200   delete demo_controller;
201
202   playback_demo_stream = new std::ifstream(filename.c_str());
203   if(!playback_demo_stream->good()) {
204     std::stringstream msg;
205     msg << "Couldn't open demo file '" << filename << "' for reading.";
206     throw std::runtime_error(msg.str());
207   }
208
209   Player& tux = *currentsector->player;
210   demo_controller = new CodeController();
211   tux.set_controller(demo_controller);
212
213   // skip over random seed, if it exists in the file
214   char buf[30];                            // ascii decimal seed
215   int seed;
216   for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
217     playback_demo_stream->get(buf[i]);
218   if (sscanf(buf, "random_seed=%010d", &seed) != 1)
219     playback_demo_stream->seekg(0);     // old style w/o seed, restart at beg
220 }
221
222 void
223 GameSession::on_escape_press()
224 {
225   if(currentsector->player->is_dying() || end_sequence)
226   {
227     // Let the timers run out, we fast-forward them to force past a sequence
228     if (end_sequence)
229       end_sequence->stop();
230
231     currentsector->player->dying_timer.start(FLT_EPSILON);
232     return;   // don't let the player open the menu, when he is dying
233   }
234
235   if(level->on_menukey_script != "") {
236     std::istringstream in(level->on_menukey_script);
237     run_script(in, "OnMenuKeyScript");
238   } else {
239     toggle_pause();
240   }
241 }
242
243 void
244 GameSession::toggle_pause()
245 {
246   // pause
247   if(!game_pause) {
248     speed_before_pause = g_main_loop->get_speed();
249     g_main_loop->set_speed(0);
250     Menu::set_current(game_menu.get());
251     game_menu->set_active_item(MNID_CONTINUE);
252     game_pause = true;
253   }
254
255   // unpause is done in update() after the menu is processed
256 }
257
258 void
259 GameSession::set_editmode(bool edit_mode)
260 {
261   if (this->edit_mode == edit_mode) return;
262   this->edit_mode = edit_mode;
263
264   currentsector->get_players()[0]->set_edit_mode(edit_mode);
265
266   if (edit_mode) {
267
268     // entering edit mode
269
270   } else {
271
272     // leaving edit mode
273     restart_level();
274
275   }
276 }
277
278 void
279 GameSession::force_ghost_mode()
280 {
281   currentsector->get_players()[0]->set_ghost_mode(true);
282 }
283
284 HSQUIRRELVM
285 GameSession::run_script(std::istream& in, const std::string& sourcename)
286 {
287   using namespace Scripting;
288
289   // garbage collect thread list
290   for(ScriptList::iterator i = scripts.begin();
291       i != scripts.end(); ) {
292     HSQOBJECT& object = *i;
293     HSQUIRRELVM vm = object_to_vm(object);
294
295     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
296       sq_release(global_vm, &object);
297       i = scripts.erase(i);
298       continue;
299     }
300
301     ++i;
302   }
303
304   HSQOBJECT object = create_thread(global_vm);
305   scripts.push_back(object);
306
307   HSQUIRRELVM vm = object_to_vm(object);
308
309   compile_and_run(vm, in, sourcename);
310
311   return vm;
312 }
313
314 void
315 GameSession::process_events()
316 {
317   // end of pause mode?
318   // XXX this looks like a fail-safe to unpause the game if there's no menu
319   // XXX having it enabled causes some unexpected problems
320   // XXX hopefully disabling it won't...
321   /*
322     if(!Menu::current() && game_pause) {
323     game_pause = false;
324     }
325   */
326
327   // playback a demo?
328   if(playback_demo_stream != 0) {
329     demo_controller->update();
330     char left = false;
331     char right = false;
332     char up = false;
333     char down = false;
334     char jump = false;
335     char action = false;
336     playback_demo_stream->get(left);
337     playback_demo_stream->get(right);
338     playback_demo_stream->get(up);
339     playback_demo_stream->get(down);
340     playback_demo_stream->get(jump);
341     playback_demo_stream->get(action);
342     demo_controller->press(Controller::LEFT, left);
343     demo_controller->press(Controller::RIGHT, right);
344     demo_controller->press(Controller::UP, up);
345     demo_controller->press(Controller::DOWN, down);
346     demo_controller->press(Controller::JUMP, jump);
347     demo_controller->press(Controller::ACTION, action);
348   }
349
350   // save input for demo?
351   if(capture_demo_stream != 0) {
352     capture_demo_stream ->put(g_main_controller->hold(Controller::LEFT));
353     capture_demo_stream ->put(g_main_controller->hold(Controller::RIGHT));
354     capture_demo_stream ->put(g_main_controller->hold(Controller::UP));
355     capture_demo_stream ->put(g_main_controller->hold(Controller::DOWN));
356     capture_demo_stream ->put(g_main_controller->hold(Controller::JUMP));
357     capture_demo_stream ->put(g_main_controller->hold(Controller::ACTION));
358   }
359 }
360
361 void
362 GameSession::check_end_conditions()
363 {
364   Player* tux = currentsector->player;
365
366   /* End of level? */
367   if(end_sequence && end_sequence->is_done()) {
368     finish(true);
369   } else if (!end_sequence && tux->is_dead()) {
370     restart_level();
371   }
372 }
373
374 void
375 GameSession::draw(DrawingContext& context)
376 {
377   currentsector->draw(context);
378   drawstatus(context);
379
380   if(game_pause)
381     draw_pause(context);
382 }
383
384 void
385 GameSession::draw_pause(DrawingContext& context)
386 {
387   context.draw_filled_rect(
388     Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
389     Color(0.0f, 0.0f, 0.0f, .25f), LAYER_FOREGROUND1);
390 }
391
392 void
393 GameSession::process_menu()
394 {
395   Menu* menu = Menu::current();
396   if(menu) {
397     if(menu == game_menu.get()) {
398       switch (game_menu->check()) {
399         case MNID_CONTINUE:
400           Menu::set_current(0);
401           toggle_pause();
402           break;
403         case MNID_ABORTLEVEL:
404           Menu::set_current(0);
405           g_main_loop->exit_screen();
406           break;
407       }
408     }
409   }
410 }
411
412 void
413 GameSession::setup()
414 {
415   if(currentsector != Sector::current()) {
416     currentsector->activate(currentsector->player->get_pos());
417   }
418   currentsector->play_music(LEVEL_MUSIC);
419
420   // Eat unneeded events
421   SDL_Event event;
422   while(SDL_PollEvent(&event))
423   {}
424
425   if (!levelintro_shown) {
426     levelintro_shown = true;
427     g_main_loop->push_screen(new LevelIntro(level.get(), best_level_statistics));
428   }
429 }
430
431 void
432 GameSession::update(float elapsed_time)
433 {
434   // handle controller
435   if(g_main_controller->pressed(Controller::PAUSE_MENU))
436     on_escape_press();
437
438   process_events();
439   process_menu();
440
441   // Unpause the game if the menu has been closed
442   if (game_pause && !Menu::current()) {
443     g_main_loop->set_speed(speed_before_pause);
444     game_pause = false;
445   }
446
447   check_end_conditions();
448
449   // respawning in new sector?
450   if(newsector != "" && newspawnpoint != "") {
451     Sector* sector = level->get_sector(newsector);
452     if(sector == 0) {
453       log_warning << "Sector '" << newsector << "' not found" << std::endl;
454       sector = level->get_sector("main");
455     }
456     sector->activate(newspawnpoint);
457     sector->play_music(LEVEL_MUSIC);
458     currentsector = sector;
459     //Keep persistent across sectors
460     if(edit_mode)
461       currentsector->get_players()[0]->set_edit_mode(edit_mode);
462     newsector = "";
463     newspawnpoint = "";
464   }
465
466   // Update the world state and all objects in the world
467   if(!game_pause) {
468     // Update the world
469     if (!end_sequence) {
470       play_time += elapsed_time; //TODO: make sure we don't count cutscene time
471       level->stats.time = play_time;
472       currentsector->update(elapsed_time);
473     } else {
474       if (!end_sequence->is_tux_stopped()) {
475         currentsector->update(elapsed_time);
476       } else {
477         end_sequence->update(elapsed_time);
478       }
479     }
480   }
481
482   // update sounds
483   if (currentsector && currentsector->camera) sound_manager->set_listener_position(currentsector->camera->get_center());
484
485   /* Handle music: */
486   if (end_sequence)
487     return;
488
489   if(currentsector->player->invincible_timer.started()) {
490     if(currentsector->player->invincible_timer.get_timeleft() <=
491        TUX_INVINCIBLE_TIME_WARNING) {
492       currentsector->play_music(HERRING_WARNING_MUSIC);
493     } else {
494       currentsector->play_music(HERRING_MUSIC);
495     }
496   } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
497     currentsector->play_music(LEVEL_MUSIC);
498   }
499 }
500
501 void
502 GameSession::finish(bool win)
503 {
504   using namespace WorldMapNS;
505
506   if (edit_mode) {
507     force_ghost_mode();
508     return;
509   }
510
511   if(win) {
512     if(WorldMap::current())
513       WorldMap::current()->finished_level(level.get());
514   }
515
516   g_main_loop->exit_screen();
517 }
518
519 void
520 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
521 {
522   newsector = sector;
523   newspawnpoint = spawnpoint;
524 }
525
526 void
527 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
528 {
529   reset_sector = sector;
530   reset_pos = pos;
531 }
532
533 std::string
534 GameSession::get_working_directory()
535 {
536   return FileSystem::dirname(levelfile);
537 }
538
539 void
540 GameSession::start_sequence(const std::string& sequencename)
541 {
542   // do not play sequences when in edit mode
543   if (edit_mode) {
544     force_ghost_mode();
545     return;
546   }
547
548   // handle special "stoptux" sequence
549   if (sequencename == "stoptux") {
550     if (!end_sequence) {
551       log_warning << "Final target reached without an active end sequence" << std::endl;
552       this->start_sequence("endsequence");
553     }
554     if (end_sequence) end_sequence->stop_tux();
555     return;
556   }
557
558   // abort if a sequence is already playing
559   if (end_sequence)
560     return;
561
562   if (sequencename == "endsequence") {
563     if (currentsector->get_players()[0]->get_physic().get_velocity_x() < 0) {
564       end_sequence = new EndSequenceWalkLeft();
565     } else {
566       end_sequence = new EndSequenceWalkRight();
567     }
568   } else if (sequencename == "fireworks") {
569     end_sequence = new EndSequenceFireworks();
570   } else {
571     log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
572     return;
573   }
574
575   /* slow down the game for end-sequence */
576   g_main_loop->set_speed(0.5f);
577
578   currentsector->add_object(end_sequence);
579   end_sequence->start();
580
581   sound_manager->play_music("music/leveldone.music", false);
582   currentsector->player->invincible_timer.start(10000.0f);
583
584   // Stop all clocks.
585   for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
586       i != currentsector->gameobjects.end(); ++i)
587   {
588     GameObject* obj = *i;
589
590     LevelTime* lt = dynamic_cast<LevelTime*> (obj);
591     if(lt)
592       lt->stop();
593   }
594 }
595
596 /* (Status): */
597 void
598 GameSession::drawstatus(DrawingContext& context)
599 {
600   player_status->draw(context);
601
602   // draw level stats while end_sequence is running
603   if (end_sequence) {
604     level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
605   }
606 }
607
608 /* EOF */