4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 #include "game_session.hpp"
37 #include "console.hpp"
38 #include "worldmap/worldmap.hpp"
39 #include "mainloop.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
45 #include "player_status.hpp"
46 #include "object/particlesystem.hpp"
47 #include "object/background.hpp"
48 #include "object/gradient.hpp"
49 #include "object/tilemap.hpp"
50 #include "object/camera.hpp"
51 #include "object/player.hpp"
52 #include "object/level_time.hpp"
53 #include "lisp/lisp.hpp"
54 #include "lisp/parser.hpp"
55 #include "resources.hpp"
56 #include "statistics.hpp"
58 #include "options_menu.hpp"
59 #include "textscroller.hpp"
60 #include "control/codecontroller.hpp"
61 #include "control/joystickkeyboardcontroller.hpp"
63 #include "file_system.hpp"
64 #include "gameconfig.hpp"
65 #include "gettext.hpp"
66 #include "console.hpp"
67 #include "flip_level_transformer.hpp"
68 #include "trigger/secretarea_trigger.hpp"
69 #include "trigger/sequence_trigger.hpp"
70 #include "random_generator.hpp"
71 #include "scripting/squirrel_util.hpp"
72 #include "object/endsequence_walkright.hpp"
73 #include "object/endsequence_walkleft.hpp"
74 #include "object/endsequence_fireworks.hpp"
75 #include "direction.hpp"
76 #include "scripting/time_scheduler.hpp"
78 // the engine will be run with a logical framerate of 64fps.
79 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
81 static const float LOGICAL_FPS = 64.0;
88 GameSession* GameSession::current_ = NULL;
90 GameSession::GameSession(const std::string& levelfile_, Statistics* statistics)
91 : level(0), currentsector(0),
93 levelfile(levelfile_), best_level_statistics(statistics),
94 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0),
95 play_time(0), edit_mode(false)
101 speed_before_pause = main_loop->get_speed();
103 statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
107 game_menu.reset(new Menu());
108 game_menu->add_label(_("Pause"));
110 game_menu->add_entry(MNID_CONTINUE, _("Continue"));
111 game_menu->add_submenu(_("Options"), get_options_menu());
113 game_menu->add_entry(MNID_ABORTLEVEL, _("Abort Level"));
117 GameSession::restart_level()
128 main_controller->reset();
132 level.reset(new Level);
133 level->load(levelfile);
134 level->stats.total_coins = level->get_total_coins();
135 level->stats.total_badguys = level->get_total_badguys();
136 level->stats.total_secrets = level->get_total_count<SecretAreaTrigger>();
137 level->stats.reset();
139 if(reset_sector != "") {
140 currentsector = level->get_sector(reset_sector);
142 std::stringstream msg;
143 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
144 throw std::runtime_error(msg.str());
146 level->stats.declare_invalid();
147 currentsector->activate(reset_pos);
149 currentsector = level->get_sector("main");
151 throw std::runtime_error("Couldn't find main sector");
153 currentsector->activate("main");
158 sound_manager->stop_music();
159 currentsector->play_music(LEVEL_MUSIC);
161 if(capture_file != "") {
162 int newSeed=0; // next run uses a new seed
163 while (newSeed == 0) // which is the next non-zero random num.
164 newSeed = systemRandom.rand();
165 config->random_seed = systemRandom.srand(newSeed);
166 log_info << "Next run uses random seed " <<config->random_seed <<std::endl;
167 record_demo(capture_file);
171 GameSession::~GameSession()
173 delete capture_demo_stream;
174 delete playback_demo_stream;
175 delete demo_controller;
182 GameSession::record_demo(const std::string& filename)
184 delete capture_demo_stream;
186 capture_demo_stream = new std::ofstream(filename.c_str());
187 if(!capture_demo_stream->good()) {
188 std::stringstream msg;
189 msg << "Couldn't open demo file '" << filename << "' for writing.";
190 throw std::runtime_error(msg.str());
192 capture_file = filename;
194 char buf[30]; // save the seed in the demo file
195 snprintf(buf, sizeof(buf), "random_seed=%10d", config->random_seed);
196 for (int i=0; i==0 || buf[i-1]; i++)
197 capture_demo_stream->put(buf[i]);
201 GameSession::get_demo_random_seed(const std::string& filename)
203 std::istream* test_stream = new std::ifstream(filename.c_str());
204 if(test_stream->good()) {
205 char buf[30]; // recall the seed from the demo file
207 for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
208 test_stream->get(buf[i]);
209 if (sscanf(buf, "random_seed=%10d", &seed) == 1) {
210 log_info << "Random seed " << seed << " from demo file" << std::endl;
214 log_info << "Demo file contains no random number" << std::endl;
220 GameSession::play_demo(const std::string& filename)
222 delete playback_demo_stream;
223 delete demo_controller;
225 playback_demo_stream = new std::ifstream(filename.c_str());
226 if(!playback_demo_stream->good()) {
227 std::stringstream msg;
228 msg << "Couldn't open demo file '" << filename << "' for reading.";
229 throw std::runtime_error(msg.str());
232 Player& tux = *currentsector->player;
233 demo_controller = new CodeController();
234 tux.set_controller(demo_controller);
236 // skip over random seed, if it exists in the file
237 char buf[30]; // ascii decimal seed
239 for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
240 playback_demo_stream->get(buf[i]);
241 if (sscanf(buf, "random_seed=%010d", &seed) != 1)
242 playback_demo_stream->seekg(0); // old style w/o seed, restart at beg
246 GameSession::levelintro()
248 sound_manager->stop_music();
250 DrawingContext context;
251 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
252 i != currentsector->gameobjects.end(); ++i) {
253 Background* background = dynamic_cast<Background*> (*i);
255 background->draw(context);
257 Gradient* gradient = dynamic_cast<Gradient*> (*i);
259 gradient->draw(context);
263 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
264 // ALIGN_CENTER, LAYER_FOREGROUND1);
265 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
268 std::stringstream ss_coins;
269 ss_coins << _("Coins") << ": " << player_status->coins;
270 context.draw_text(white_text, ss_coins.str(), Vector(SCREEN_WIDTH/2, 210),
271 ALIGN_CENTER, LAYER_FOREGROUND1);
273 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
274 context.draw_text(white_small_text,
275 std::string(_("contributed by ")) + level->get_author(),
276 Vector(SCREEN_WIDTH/2, 350), ALIGN_CENTER, LAYER_FOREGROUND1);
278 if(best_level_statistics != NULL)
279 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
281 wait_for_event(1.0, 3.0);
285 GameSession::on_escape_press()
287 if(currentsector->player->is_dying() || end_sequence)
289 // Let the timers run out, we fast-forward them to force past a sequence
291 end_sequence->stop();
293 currentsector->player->dying_timer.start(FLT_EPSILON);
294 return; // don't let the player open the menu, when he is dying
297 if(level->on_menukey_script != "") {
298 std::istringstream in(level->on_menukey_script);
299 run_script(in, "OnMenuKeyScript");
306 GameSession::toggle_pause()
309 speed_before_pause = main_loop->get_speed();
310 main_loop->set_speed(0);
311 Menu::set_current(game_menu.get());
312 game_menu->set_active_item(MNID_CONTINUE);
315 main_loop->set_speed(speed_before_pause);
316 Menu::set_current(NULL);
322 GameSession::set_editmode(bool edit_mode)
324 if (this->edit_mode == edit_mode) return;
325 this->edit_mode = edit_mode;
327 currentsector->get_players()[0]->set_edit_mode(edit_mode);
331 // entering edit mode
342 GameSession::force_ghost_mode()
344 currentsector->get_players()[0]->set_ghost_mode(true);
348 GameSession::run_script(std::istream& in, const std::string& sourcename)
350 using namespace Scripting;
352 // garbage collect thread list
353 for(ScriptList::iterator i = scripts.begin();
354 i != scripts.end(); ) {
355 HSQOBJECT& object = *i;
356 HSQUIRRELVM vm = object_to_vm(object);
358 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
359 sq_release(global_vm, &object);
360 i = scripts.erase(i);
367 HSQOBJECT object = create_thread(global_vm);
368 scripts.push_back(object);
370 HSQUIRRELVM vm = object_to_vm(object);
372 compile_and_run(vm, in, sourcename);
378 GameSession::process_events()
380 // end of pause mode?
381 if(!Menu::current() && game_pause) {
386 if(playback_demo_stream != 0) {
387 demo_controller->update();
394 playback_demo_stream->get(left);
395 playback_demo_stream->get(right);
396 playback_demo_stream->get(up);
397 playback_demo_stream->get(down);
398 playback_demo_stream->get(jump);
399 playback_demo_stream->get(action);
400 demo_controller->press(Controller::LEFT, left);
401 demo_controller->press(Controller::RIGHT, right);
402 demo_controller->press(Controller::UP, up);
403 demo_controller->press(Controller::DOWN, down);
404 demo_controller->press(Controller::JUMP, jump);
405 demo_controller->press(Controller::ACTION, action);
408 // save input for demo?
409 if(capture_demo_stream != 0) {
410 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
411 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
412 capture_demo_stream ->put(main_controller->hold(Controller::UP));
413 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
414 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
415 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
420 GameSession::check_end_conditions()
422 Player* tux = currentsector->player;
425 if(end_sequence && end_sequence->is_done()) {
427 } else if (!end_sequence && tux->is_dead()) {
433 GameSession::draw(DrawingContext& context)
435 currentsector->draw(context);
443 GameSession::draw_pause(DrawingContext& context)
445 context.draw_filled_rect(
446 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
447 Color(.2f, .2f, .2f, .5f), LAYER_FOREGROUND1);
451 GameSession::process_menu()
453 Menu* menu = Menu::current();
457 if(menu == game_menu.get()) {
458 switch (game_menu->check()) {
460 Menu::set_current(0);
463 case MNID_ABORTLEVEL:
464 Menu::set_current(0);
465 main_loop->exit_screen();
475 Menu::set_current(NULL);
478 if(currentsector != Sector::current()) {
479 currentsector->activate(currentsector->player->get_pos());
481 currentsector->play_music(LEVEL_MUSIC);
483 // Eat unneeded events
485 while(SDL_PollEvent(&event))
490 GameSession::update(float elapsed_time)
493 if(main_controller->pressed(Controller::PAUSE_MENU))
499 check_end_conditions();
501 // respawning in new sector?
502 if(newsector != "" && newspawnpoint != "") {
503 Sector* sector = level->get_sector(newsector);
505 log_warning << "Sector '" << newsector << "' not found" << std::endl;
507 sector->activate(newspawnpoint);
508 sector->play_music(LEVEL_MUSIC);
509 currentsector = sector;
514 // Update the world state and all objects in the world
518 play_time += elapsed_time; //TODO: make sure we don't count cutscene time
519 level->stats.time = play_time;
520 currentsector->update(elapsed_time);
522 if (!end_sequence->is_tux_stopped()) {
523 currentsector->update(elapsed_time);
525 end_sequence->update(elapsed_time);
531 sound_manager->set_listener_position(currentsector->player->get_pos());
537 if(currentsector->player->invincible_timer.started()) {
538 if(currentsector->player->invincible_timer.get_timeleft() <=
539 TUX_INVINCIBLE_TIME_WARNING) {
540 currentsector->play_music(HERRING_WARNING_MUSIC);
542 currentsector->play_music(HERRING_MUSIC);
544 } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
545 currentsector->play_music(LEVEL_MUSIC);
550 GameSession::finish(bool win)
552 using namespace WorldMapNS;
560 if(WorldMap::current())
561 WorldMap::current()->finished_level(level.get());
564 main_loop->exit_screen();
568 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
571 newspawnpoint = spawnpoint;
575 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
577 reset_sector = sector;
582 GameSession::get_working_directory()
584 return FileSystem::dirname(levelfile);
588 GameSession::start_sequence(const std::string& sequencename)
590 // do not play sequences when in edit mode
596 // handle special "stoptux" sequence
597 if (sequencename == "stoptux") {
599 log_warning << "Final target reached without an active end sequence" << std::endl;
600 this->start_sequence("endsequence");
602 if (end_sequence) end_sequence->stop_tux();
606 // abort if a sequence is already playing
610 if (sequencename == "endsequence") {
611 if (currentsector->get_players()[0]->physic.get_velocity_x() < 0) {
612 end_sequence = new EndSequenceWalkLeft();
614 end_sequence = new EndSequenceWalkRight();
616 } else if (sequencename == "fireworks") {
617 end_sequence = new EndSequenceFireworks();
619 log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
623 /* slow down the game for end-sequence */
624 main_loop->set_speed(0.5f);
626 currentsector->add_object(end_sequence);
627 end_sequence->start();
629 sound_manager->play_music("music/leveldone.ogg", false);
630 currentsector->player->invincible_timer.start(10000.0f);
633 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
634 i != currentsector->gameobjects.end(); ++i)
636 GameObject* obj = *i;
638 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
646 GameSession::drawstatus(DrawingContext& context)
648 player_status->draw(context);
650 // draw level stats while end_sequence is running
652 level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());