4 // Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
5 // Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
6 // Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License
10 // as published by the Free Software Foundation; either version 2
11 // of the License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
38 #include "game_session.hpp"
39 #include "video/screen.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/tilemap.hpp"
49 #include "object/camera.hpp"
50 #include "object/player.hpp"
51 #include "lisp/lisp.hpp"
52 #include "lisp/parser.hpp"
53 #include "resources.hpp"
54 #include "worldmap.hpp"
56 #include "statistics.hpp"
58 #include "object/fireworks.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 "exceptions.hpp"
67 #include "flip_level_transformer.hpp"
69 // the engine will be run with a logical framerate of 64fps.
70 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
72 static const float LOGICAL_FPS = 64.0;
74 GameSession* GameSession::current_ = 0;
76 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
77 Statistics* statistics)
78 : level(0), currentsector(0), mode(mode),
79 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
80 levelfile(levelfile_), best_level_statistics(statistics),
81 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
87 music_playing = false;
90 context = new DrawingContext();
96 GameSession::restart_level()
99 exit_status = ES_NONE;
100 end_sequence = NO_ENDSEQUENCE;
102 main_controller->reset();
108 level->load(levelfile);
110 global_stats.reset();
111 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
112 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
113 //global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
115 if(reset_sector != "") {
116 currentsector = level->get_sector(reset_sector);
118 std::stringstream msg;
119 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
120 throw std::runtime_error(msg.str());
122 currentsector->activate(reset_pos);
124 currentsector = level->get_sector("main");
126 throw std::runtime_error("Couldn't find main sector");
127 currentsector->activate("main");
130 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
135 currentsector->play_music(LEVEL_MUSIC);
136 music_playing = true;
139 if(capture_file != "")
140 record_demo(capture_file);
143 GameSession::~GameSession()
145 delete capture_demo_stream;
146 delete playback_demo_stream;
147 delete demo_controller;
149 delete end_sequence_controller;
157 GameSession::record_demo(const std::string& filename)
159 delete capture_demo_stream;
161 capture_demo_stream = new std::ofstream(filename.c_str());
162 if(!capture_demo_stream->good()) {
163 std::stringstream msg;
164 msg << "Couldn't open demo file '" << filename << "' for writing.";
165 throw std::runtime_error(msg.str());
167 capture_file = filename;
171 GameSession::play_demo(const std::string& filename)
173 delete playback_demo_stream;
174 delete demo_controller;
176 playback_demo_stream = new std::ifstream(filename.c_str());
177 if(!playback_demo_stream->good()) {
178 std::stringstream msg;
179 msg << "Couldn't open demo file '" << filename << "' for reading.";
180 throw std::runtime_error(msg.str());
183 Player& tux = *currentsector->player;
184 demo_controller = new CodeController();
185 tux.set_controller(demo_controller);
189 GameSession::levelintro()
193 DrawingContext context;
194 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
195 i != currentsector->gameobjects.end(); ++i) {
196 Background* background = dynamic_cast<Background*> (*i);
198 background->draw(context);
202 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
203 // CENTER_ALLIGN, LAYER_FOREGROUND1);
204 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
207 sprintf(str, "TUX x %d", player_status->lives);
208 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
209 CENTER_ALLIGN, LAYER_FOREGROUND1);
211 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
212 //TODO make author check case/blank-insensitive
213 context.draw_text(white_small_text,
214 std::string(_("contributed by ")) + level->get_author(),
215 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
218 if(best_level_statistics != NULL)
219 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
221 context.do_drawing();
223 wait_for_event(1.0, 3.0);
227 GameSession::on_escape_press()
229 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
230 return; // don't let the player open the menu, when he is dying
232 if(mode == ST_GL_TEST) {
233 exit_status = ES_LEVEL_ABORT;
234 } else if (!Menu::current()) {
235 Menu::set_current(game_menu);
236 game_menu->set_active_item(MNID_CONTINUE);
244 GameSession::process_events()
246 Player& tux = *currentsector->player;
247 main_controller->update();
249 // end of pause mode?
250 if(!Menu::current() && game_pause) {
254 if (end_sequence != NO_ENDSEQUENCE) {
255 if(end_sequence_controller == 0) {
256 end_sequence_controller = new CodeController();
257 tux.set_controller(end_sequence_controller);
260 end_sequence_controller->press(Controller::RIGHT);
262 if (int(last_x_pos) == int(tux.get_pos().x))
263 end_sequence_controller->press(Controller::JUMP);
264 last_x_pos = tux.get_pos().x;
267 main_controller->update();
269 while (SDL_PollEvent(&event)) {
270 /* Check for menu-events, if the menu is shown */
272 Menu::current()->event(event);
273 main_controller->process_event(event);
274 if(event.type == SDL_QUIT)
275 throw graceful_shutdown();
279 if(playback_demo_stream != 0) {
280 demo_controller->update();
287 playback_demo_stream->get(left);
288 playback_demo_stream->get(right);
289 playback_demo_stream->get(up);
290 playback_demo_stream->get(down);
291 playback_demo_stream->get(jump);
292 playback_demo_stream->get(action);
293 demo_controller->press(Controller::LEFT, left);
294 demo_controller->press(Controller::RIGHT, right);
295 demo_controller->press(Controller::UP, up);
296 demo_controller->press(Controller::DOWN, down);
297 demo_controller->press(Controller::JUMP, jump);
298 demo_controller->press(Controller::ACTION, action);
301 // save input for demo?
302 if(capture_demo_stream != 0) {
303 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
304 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
305 capture_demo_stream ->put(main_controller->hold(Controller::UP));
306 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
307 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
308 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
313 GameSession::try_cheats()
315 if(currentsector == 0)
317 Player& tux = *currentsector->player;
319 // Cheating words (the goal of this is really for debugging,
320 // but could be used for some cheating, nothing wrong with that)
321 if(main_controller->check_cheatcode("grow")) {
322 tux.set_bonus(GROWUP_BONUS, false);
324 if(main_controller->check_cheatcode("fire")) {
325 tux.set_bonus(FIRE_BONUS, false);
327 if(main_controller->check_cheatcode("ice")) {
328 tux.set_bonus(ICE_BONUS, false);
330 if(main_controller->check_cheatcode("lifeup")) {
331 player_status->lives++;
333 if(main_controller->check_cheatcode("lifedown")) {
334 player_status->lives--;
336 if(main_controller->check_cheatcode("grease")) {
337 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
339 if(main_controller->check_cheatcode("invincible")) {
340 // be invincle for the rest of the level
341 tux.invincible_timer.start(10000);
343 if(main_controller->check_cheatcode("mortal")) {
344 // give up invincibility
345 tux.invincible_timer.stop();
347 if(main_controller->check_cheatcode("shrink")) {
349 tux.kill(tux.SHRINK);
351 if(main_controller->check_cheatcode("kill")) {
352 // kill Tux, but without losing a life
353 player_status->lives++;
356 if(main_controller->check_cheatcode("whereami")) {
357 std::cout << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << "." << std::endl;
360 if(main_controller->check_cheatcode("grid")) {
362 debug_grid = !debug_grid;
365 if(main_controller->check_cheatcode("gotoend")) {
366 // goes to the end of the level
368 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
369 currentsector->camera->reset(
370 Vector(tux.get_pos().x, tux.get_pos().y));
372 if(main_controller->check_cheatcode("flip")) {
373 FlipLevelTransformer flip_transformer;
374 flip_transformer.transform(GameSession::current()->get_current_level());
376 if(main_controller->check_cheatcode("finish")) {
377 // finish current sector
378 exit_status = ES_LEVEL_FINISHED;
379 // don't add points to stats though...
384 GameSession::check_end_conditions()
386 Player* tux = currentsector->player;
389 if(end_sequence && endsequence_timer.check()) {
390 exit_status = ES_LEVEL_FINISHED;
392 } else if (!end_sequence && tux->is_dead()) {
393 if (player_status->lives < 0) { // No more lives!?
394 exit_status = ES_GAME_OVER;
395 } else { // Still has lives, so reset Tux to the levelstart
404 GameSession::update(float elapsed_time)
407 if(main_controller->pressed(Controller::PAUSE_MENU))
411 if(!currentsector->player->growing_timer.started()) {
412 // Update Tux and the World
413 currentsector->update(elapsed_time);
416 // respawning in new sector?
417 if(newsector != "" && newspawnpoint != "") {
418 Sector* sector = level->get_sector(newsector);
420 std::cerr << "Sector '" << newsector << "' not found.\n";
422 sector->activate(newspawnpoint);
423 sector->play_music(LEVEL_MUSIC);
424 currentsector = sector;
430 sound_manager->set_listener_position(currentsector->player->get_pos());
436 currentsector->draw(*context);
437 drawstatus(*context);
442 if(Menu::current()) {
443 Menu::current()->draw(*context);
446 context->do_drawing();
450 GameSession::draw_pause()
452 context->draw_filled_rect(
453 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
454 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
458 GameSession::process_menu()
460 Menu* menu = Menu::current();
464 if(menu == game_menu) {
465 switch (game_menu->check()) {
467 Menu::set_current(0);
469 case MNID_ABORTLEVEL:
470 Menu::set_current(0);
471 exit_status = ES_LEVEL_ABORT;
474 } else if(menu == options_menu) {
475 process_options_menu();
476 } else if(menu == load_game_menu ) {
477 process_load_game_menu();
483 GameSession::ExitStatus
486 Menu::set_current(0);
491 // Eat unneeded events
493 while(SDL_PollEvent(&event))
498 Uint32 fps_ticks = SDL_GetTicks();
499 Uint32 fps_nextframe_ticks = SDL_GetTicks();
501 bool skipdraw = false;
503 while (exit_status == ES_NONE) {
504 // we run in a logical framerate so elapsed time is a constant
505 static const float elapsed_time = 1.0 / LOGICAL_FPS;
506 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
508 game_time += elapsed_time;
511 ticks = SDL_GetTicks();
512 if(ticks > fps_nextframe_ticks) {
513 if(skipdraw == true) {
514 // already skipped last frame? we have to slow down the game then...
516 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
518 // don't draw all frames when we're getting too slow
523 while(fps_nextframe_ticks > ticks) {
525 // If we really have to wait long, then do an imprecise SDL_Delay()
526 Uint32 diff = fps_nextframe_ticks - ticks;
528 SDL_Delay(diff - 10);
530 ticks = SDL_GetTicks();
533 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
536 float diff = SDL_GetTicks() - fps_nextframe_ticks;
538 // sets the ticks that must have elapsed
539 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
541 // sets the ticks that must have elapsed
542 // in order for the next frame to start.
543 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
550 // Update the world state and all objects in the world
551 // Do that with a constante time-delta so that the game will run
552 // determistic and not different on different machines
553 if(!game_pause && !Menu::current())
556 check_end_conditions();
557 if (end_sequence == ENDSEQUENCE_RUNNING)
558 update(elapsed_time/2);
559 else if(end_sequence == NO_ENDSEQUENCE)
560 update(elapsed_time);
571 sound_manager->update();
573 /* Time stops in pause mode */
574 if(game_pause || Menu::current())
579 //frame_rate.update();
582 if (currentsector->player->invincible_timer.started() &&
583 currentsector->player->invincible_timer.get_timeleft()
584 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
586 currentsector->play_music(HERRING_MUSIC);
588 /* or just normal music? */
589 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
591 currentsector->play_music(LEVEL_MUSIC);
594 /* Calculate frames per second */
599 if(SDL_GetTicks() - fps_ticks >= 500)
601 fps_fps = (float) fps_cnt / .5;
603 fps_ticks = SDL_GetTicks();
610 main_controller->reset();
615 GameSession::finish(bool win)
618 exit_status = ES_LEVEL_FINISHED;
620 exit_status = ES_LEVEL_ABORT;
624 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
627 newspawnpoint = spawnpoint;
631 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
633 reset_sector = sector;
638 GameSession::get_working_directory()
640 return FileSystem::dirname(levelfile);
644 GameSession::display_info_box(const std::string& text)
646 InfoBox* box = new InfoBox(text);
651 main_controller->update();
653 while (SDL_PollEvent(&event)) {
654 main_controller->process_event(event);
655 if(event.type == SDL_QUIT)
656 throw graceful_shutdown();
659 if(main_controller->pressed(Controller::JUMP)
660 || main_controller->pressed(Controller::ACTION)
661 || main_controller->pressed(Controller::PAUSE_MENU)
662 || main_controller->pressed(Controller::MENU_SELECT))
664 else if(main_controller->pressed(Controller::DOWN))
666 else if(main_controller->pressed(Controller::UP))
670 sound_manager->update();
677 GameSession::start_sequence(const std::string& sequencename)
679 if(sequencename == "endsequence" || sequencename == "fireworks") {
683 end_sequence = ENDSEQUENCE_RUNNING;
684 endsequence_timer.start(7.0); // 7 seconds until we finish the map
686 sound_manager->play_music("music/leveldone.ogg", false);
687 currentsector->player->invincible_timer.start(7.0);
689 if(sequencename == "fireworks") {
690 currentsector->add_object(new Fireworks());
692 } else if(sequencename == "stoptux") {
694 std::cout << "WARNING: Final target reached without "
695 << "an active end sequence." << std::endl;
696 this->start_sequence("endsequence");
698 end_sequence = ENDSEQUENCE_WAITING;
700 std::cout << "Unknown sequence '" << sequencename << "'.\n";
706 GameSession::drawstatus(DrawingContext& context)
708 player_status->draw(context);
710 if(config->show_fps) {
712 snprintf(str, sizeof(str), "%3.1f", fps_fps);
713 context.draw_text(white_text, "FPS",
714 Vector(SCREEN_WIDTH -
715 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
716 LEFT_ALLIGN, LAYER_FOREGROUND1);
717 context.draw_text(gold_text, str,
718 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
719 LEFT_ALLIGN, LAYER_FOREGROUND1);
724 GameSession::drawresultscreen()
728 DrawingContext context;
729 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
730 i != currentsector->gameobjects.end(); ++i) {
731 Background* background = dynamic_cast<Background*> (*i);
733 background->draw(context);
737 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
738 CENTER_ALLIGN, LAYER_FOREGROUND1);
740 // sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
741 // context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
743 // y == 256 before removal of score
744 sprintf(str, _("COINS: %d"), player_status->coins);
745 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
747 context.do_drawing();
749 wait_for_event(2.0, 5.0);
752 std::string slotinfo(int slot)
755 std::string slotfile;
757 std::stringstream stream;
759 slotfile = "save/slot" + stream.str() + ".stsg";
763 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
765 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
767 throw std::runtime_error("file is not a supertux-savegame.");
769 savegame->get("title", title);
770 } catch(std::exception& e) {
771 return std::string(_("Slot")) + " " + stream.str() + " - " +
772 std::string(_("Free"));
775 return std::string("Slot ") + stream.str() + " - " + title;
778 bool process_load_game_menu()
780 int slot = load_game_menu->check();
785 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
788 std::stringstream stream;
790 std::string slotfile = "save/slot" + stream.str() + ".stsg";
792 sound_manager->stop_music();
794 DrawingContext context;
795 context.draw_text(white_text, "Loading...",
796 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
797 CENTER_ALLIGN, LAYER_FOREGROUND1);
798 context.do_drawing();
800 WorldMapNS::WorldMap worldmap;
802 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
803 // Load the game or at least set the savegame_file variable
804 worldmap.loadgame(slotfile);
808 Menu::set_current(main_menu);