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 // XXX this looks like a fail-safe to unpause the game if there's no menu
382 // XXX having it enabled causes some unexpected problems
383 // XXX hopefully disabling it won't...
385 if(!Menu::current() && game_pause) {
391 if(playback_demo_stream != 0) {
392 demo_controller->update();
399 playback_demo_stream->get(left);
400 playback_demo_stream->get(right);
401 playback_demo_stream->get(up);
402 playback_demo_stream->get(down);
403 playback_demo_stream->get(jump);
404 playback_demo_stream->get(action);
405 demo_controller->press(Controller::LEFT, left);
406 demo_controller->press(Controller::RIGHT, right);
407 demo_controller->press(Controller::UP, up);
408 demo_controller->press(Controller::DOWN, down);
409 demo_controller->press(Controller::JUMP, jump);
410 demo_controller->press(Controller::ACTION, action);
413 // save input for demo?
414 if(capture_demo_stream != 0) {
415 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
416 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
417 capture_demo_stream ->put(main_controller->hold(Controller::UP));
418 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
419 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
420 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
425 GameSession::check_end_conditions()
427 Player* tux = currentsector->player;
430 if(end_sequence && end_sequence->is_done()) {
432 } else if (!end_sequence && tux->is_dead()) {
438 GameSession::draw(DrawingContext& context)
440 currentsector->draw(context);
448 GameSession::draw_pause(DrawingContext& context)
450 context.draw_filled_rect(
451 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
452 Color(0.0f, 0.0f, 0.0f, .25f), LAYER_FOREGROUND1);
456 GameSession::process_menu()
458 Menu* menu = Menu::current();
462 if(menu == game_menu.get()) {
463 switch (game_menu->check()) {
465 Menu::set_current(0);
468 case MNID_ABORTLEVEL:
469 Menu::set_current(0);
470 main_loop->exit_screen();
480 Menu::set_current(NULL);
483 if(currentsector != Sector::current()) {
484 currentsector->activate(currentsector->player->get_pos());
486 currentsector->play_music(LEVEL_MUSIC);
488 // Eat unneeded events
490 while(SDL_PollEvent(&event))
495 GameSession::update(float elapsed_time)
498 if(main_controller->pressed(Controller::PAUSE_MENU))
504 check_end_conditions();
506 // respawning in new sector?
507 if(newsector != "" && newspawnpoint != "") {
508 Sector* sector = level->get_sector(newsector);
510 log_warning << "Sector '" << newsector << "' not found" << std::endl;
512 sector->activate(newspawnpoint);
513 sector->play_music(LEVEL_MUSIC);
514 currentsector = sector;
519 // Update the world state and all objects in the world
523 play_time += elapsed_time; //TODO: make sure we don't count cutscene time
524 level->stats.time = play_time;
525 currentsector->update(elapsed_time);
527 if (!end_sequence->is_tux_stopped()) {
528 currentsector->update(elapsed_time);
530 end_sequence->update(elapsed_time);
536 if (currentsector && currentsector->camera) sound_manager->set_listener_position(currentsector->camera->get_center());
542 if(currentsector->player->invincible_timer.started()) {
543 if(currentsector->player->invincible_timer.get_timeleft() <=
544 TUX_INVINCIBLE_TIME_WARNING) {
545 currentsector->play_music(HERRING_WARNING_MUSIC);
547 currentsector->play_music(HERRING_MUSIC);
549 } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
550 currentsector->play_music(LEVEL_MUSIC);
555 GameSession::finish(bool win)
557 using namespace WorldMapNS;
565 if(WorldMap::current())
566 WorldMap::current()->finished_level(level.get());
569 main_loop->exit_screen();
573 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
576 newspawnpoint = spawnpoint;
580 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
582 reset_sector = sector;
587 GameSession::get_working_directory()
589 return FileSystem::dirname(levelfile);
593 GameSession::start_sequence(const std::string& sequencename)
595 // do not play sequences when in edit mode
601 // handle special "stoptux" sequence
602 if (sequencename == "stoptux") {
604 log_warning << "Final target reached without an active end sequence" << std::endl;
605 this->start_sequence("endsequence");
607 if (end_sequence) end_sequence->stop_tux();
611 // abort if a sequence is already playing
615 if (sequencename == "endsequence") {
616 if (currentsector->get_players()[0]->physic.get_velocity_x() < 0) {
617 end_sequence = new EndSequenceWalkLeft();
619 end_sequence = new EndSequenceWalkRight();
621 } else if (sequencename == "fireworks") {
622 end_sequence = new EndSequenceFireworks();
624 log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
628 /* slow down the game for end-sequence */
629 main_loop->set_speed(0.5f);
631 currentsector->add_object(end_sequence);
632 end_sequence->start();
634 sound_manager->play_music("music/leveldone.ogg", false);
635 currentsector->player->invincible_timer.start(10000.0f);
638 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
639 i != currentsector->gameobjects.end(); ++i)
641 GameObject* obj = *i;
643 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
651 GameSession::drawstatus(DrawingContext& context)
653 player_status->draw(context);
655 // draw level stats while end_sequence is running
657 level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());