2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
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.
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.
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/>.
17 #include "supertux/game_session.hpp"
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"
49 GameSession::GameSession(const std::string& levelfile_, Statistics* statistics) :
51 statistics_backdrop(),
59 levelfile(levelfile_),
64 best_level_statistics(statistics),
65 capture_demo_stream(0),
67 playback_demo_stream(0),
72 levelintro_shown(false)
77 speed_before_pause = g_main_loop->get_speed();
79 statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
83 game_menu.reset(new Menu());
84 game_menu->add_label(level->name);
86 game_menu->add_entry(MNID_CONTINUE, _("Continue"));
87 game_menu->add_submenu(_("Options"), MenuManager::get_options_menu());
89 game_menu->add_entry(MNID_ABORTLEVEL, _("Abort Level"));
93 GameSession::restart_level()
104 g_main_controller->reset();
108 level.reset(new Level);
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();
116 if(reset_sector != "") {
117 currentsector = level->get_sector(reset_sector);
119 std::stringstream msg;
120 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
121 throw std::runtime_error(msg.str());
123 level->stats.declare_invalid();
124 currentsector->activate(reset_pos);
126 currentsector = level->get_sector("main");
128 throw std::runtime_error("Couldn't find main sector");
130 currentsector->activate("main");
132 } catch(std::exception& e) {
133 log_fatal << "Couldn't start level: " << e.what() << std::endl;
134 g_main_loop->exit_screen();
137 sound_manager->stop_music();
138 currentsector->play_music(LEVEL_MUSIC);
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);
150 GameSession::~GameSession()
152 delete capture_demo_stream;
153 delete playback_demo_stream;
154 delete demo_controller;
155 MenuManager::free_options_menu();
159 GameSession::record_demo(const std::string& filename)
161 delete capture_demo_stream;
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());
169 capture_file = filename;
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]);
178 GameSession::get_demo_random_seed(const std::string& filename)
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
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;
191 log_info << "Demo file contains no random number" << std::endl;
197 GameSession::play_demo(const std::string& filename)
199 delete playback_demo_stream;
200 delete demo_controller;
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());
209 Player& tux = *currentsector->player;
210 demo_controller = new CodeController();
211 tux.set_controller(demo_controller);
213 // skip over random seed, if it exists in the file
214 char buf[30]; // ascii decimal 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
223 GameSession::on_escape_press()
225 if(currentsector->player->is_dying() || end_sequence)
227 // Let the timers run out, we fast-forward them to force past a sequence
229 end_sequence->stop();
231 currentsector->player->dying_timer.start(FLT_EPSILON);
232 return; // don't let the player open the menu, when he is dying
235 if(level->on_menukey_script != "") {
236 std::istringstream in(level->on_menukey_script);
237 run_script(in, "OnMenuKeyScript");
244 GameSession::toggle_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);
255 // unpause is done in update() after the menu is processed
259 GameSession::set_editmode(bool edit_mode)
261 if (this->edit_mode == edit_mode) return;
262 this->edit_mode = edit_mode;
264 currentsector->get_players()[0]->set_edit_mode(edit_mode);
268 // entering edit mode
279 GameSession::force_ghost_mode()
281 currentsector->get_players()[0]->set_ghost_mode(true);
285 GameSession::run_script(std::istream& in, const std::string& sourcename)
287 using namespace Scripting;
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);
295 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
296 sq_release(global_vm, &object);
297 i = scripts.erase(i);
304 HSQOBJECT object = create_thread(global_vm);
305 scripts.push_back(object);
307 HSQUIRRELVM vm = object_to_vm(object);
309 compile_and_run(vm, in, sourcename);
315 GameSession::process_events()
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...
322 if(!Menu::current() && game_pause) {
328 if(playback_demo_stream != 0) {
329 demo_controller->update();
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);
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));
362 GameSession::check_end_conditions()
364 Player* tux = currentsector->player;
367 if(end_sequence && end_sequence->is_done()) {
369 } else if (!end_sequence && tux->is_dead()) {
375 GameSession::draw(DrawingContext& context)
377 currentsector->draw(context);
385 GameSession::draw_pause(DrawingContext& context)
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);
393 GameSession::process_menu()
395 Menu* menu = Menu::current();
397 if(menu == game_menu.get()) {
398 switch (game_menu->check()) {
400 Menu::set_current(0);
403 case MNID_ABORTLEVEL:
404 Menu::set_current(0);
405 g_main_loop->exit_screen();
415 if(currentsector != Sector::current()) {
416 currentsector->activate(currentsector->player->get_pos());
418 currentsector->play_music(LEVEL_MUSIC);
420 // Eat unneeded events
422 while(SDL_PollEvent(&event))
425 if (!levelintro_shown) {
426 levelintro_shown = true;
427 g_main_loop->push_screen(new LevelIntro(level.get(), best_level_statistics));
432 GameSession::update(float elapsed_time)
435 if(g_main_controller->pressed(Controller::PAUSE_MENU))
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);
447 check_end_conditions();
449 // respawning in new sector?
450 if(newsector != "" && newspawnpoint != "") {
451 Sector* sector = level->get_sector(newsector);
453 log_warning << "Sector '" << newsector << "' not found" << std::endl;
454 sector = level->get_sector("main");
456 sector->activate(newspawnpoint);
457 sector->play_music(LEVEL_MUSIC);
458 currentsector = sector;
459 //Keep persistent across sectors
461 currentsector->get_players()[0]->set_edit_mode(edit_mode);
466 // Update the world state and all objects in the world
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);
474 if (!end_sequence->is_tux_stopped()) {
475 currentsector->update(elapsed_time);
477 end_sequence->update(elapsed_time);
483 if (currentsector && currentsector->camera) sound_manager->set_listener_position(currentsector->camera->get_center());
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);
494 currentsector->play_music(HERRING_MUSIC);
496 } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
497 currentsector->play_music(LEVEL_MUSIC);
502 GameSession::finish(bool win)
504 using namespace WorldMapNS;
512 if(WorldMap::current())
513 WorldMap::current()->finished_level(level.get());
516 g_main_loop->exit_screen();
520 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
523 newspawnpoint = spawnpoint;
527 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
529 reset_sector = sector;
534 GameSession::get_working_directory()
536 return FileSystem::dirname(levelfile);
540 GameSession::start_sequence(const std::string& sequencename)
542 // do not play sequences when in edit mode
548 // handle special "stoptux" sequence
549 if (sequencename == "stoptux") {
551 log_warning << "Final target reached without an active end sequence" << std::endl;
552 this->start_sequence("endsequence");
554 if (end_sequence) end_sequence->stop_tux();
558 // abort if a sequence is already playing
562 if (sequencename == "endsequence") {
563 if (currentsector->get_players()[0]->get_physic().get_velocity_x() < 0) {
564 end_sequence = new EndSequenceWalkLeft();
566 end_sequence = new EndSequenceWalkRight();
568 } else if (sequencename == "fireworks") {
569 end_sequence = new EndSequenceFireworks();
571 log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
575 /* slow down the game for end-sequence */
576 g_main_loop->set_speed(0.5f);
578 currentsector->add_object(end_sequence);
579 end_sequence->start();
581 sound_manager->play_music("music/leveldone.music", false);
582 currentsector->player->invincible_timer.start(10000.0f);
585 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
586 i != currentsector->gameobjects.end(); ++i)
588 GameObject* obj = *i;
590 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
598 GameSession::drawstatus(DrawingContext& context)
600 player_status->draw(context);
602 // draw level stats while end_sequence is running
604 level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());