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.
37 #include "game_session.hpp"
39 #include "worldmap.hpp"
40 #include "mainloop.hpp"
41 #include "video/screen.hpp"
42 #include "audio/sound_manager.hpp"
43 #include "gui/menu.hpp"
47 #include "player_status.hpp"
48 #include "object/particlesystem.hpp"
49 #include "object/background.hpp"
50 #include "object/gradient.hpp"
51 #include "object/tilemap.hpp"
52 #include "object/camera.hpp"
53 #include "object/player.hpp"
54 #include "object/level_time.hpp"
55 #include "lisp/lisp.hpp"
56 #include "lisp/parser.hpp"
57 #include "resources.hpp"
58 #include "worldmap.hpp"
60 #include "statistics.hpp"
62 #include "object/fireworks.hpp"
63 #include "textscroller.hpp"
64 #include "control/codecontroller.hpp"
65 #include "control/joystickkeyboardcontroller.hpp"
67 #include "file_system.hpp"
68 #include "gameconfig.hpp"
69 #include "gettext.hpp"
70 #include "exceptions.hpp"
71 #include "flip_level_transformer.hpp"
73 // the engine will be run with a logical framerate of 64fps.
74 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
76 static const float LOGICAL_FPS = 64.0;
78 using namespace WorldMapNS;
80 GameSession* GameSession::current_ = 0;
82 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
83 Statistics* statistics)
84 : level(0), currentsector(0), mode(mode),
85 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
86 levelfile(levelfile_), best_level_statistics(statistics),
87 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
95 Console::registerCommandReceiver(this);
101 GameSession::restart_level(bool fromBeginning)
104 end_sequence = NO_ENDSEQUENCE;
106 main_controller->reset();
112 level->load(levelfile);
114 global_stats.reset();
115 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
116 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
120 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
124 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
125 j != sec->gameobjects.end(); ++j)
127 GameObject* obj = *j;
129 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
131 time += int(lt->get_level_time());
134 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
136 if (fromBeginning) reset_sector="";
137 if(reset_sector != "") {
138 currentsector = level->get_sector(reset_sector);
140 std::stringstream msg;
141 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
142 throw std::runtime_error(msg.str());
144 currentsector->activate(reset_pos);
146 currentsector = level->get_sector("main");
148 throw std::runtime_error("Couldn't find main sector");
149 currentsector->activate("main");
152 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
155 currentsector->play_music(LEVEL_MUSIC);
157 if(capture_file != "")
158 record_demo(capture_file);
161 GameSession::~GameSession()
163 delete capture_demo_stream;
164 delete playback_demo_stream;
165 delete demo_controller;
167 delete end_sequence_controller;
169 Console::unregisterCommandReceiver(this);
175 GameSession::record_demo(const std::string& filename)
177 delete capture_demo_stream;
179 capture_demo_stream = new std::ofstream(filename.c_str());
180 if(!capture_demo_stream->good()) {
181 std::stringstream msg;
182 msg << "Couldn't open demo file '" << filename << "' for writing.";
183 throw std::runtime_error(msg.str());
185 capture_file = filename;
189 GameSession::play_demo(const std::string& filename)
191 delete playback_demo_stream;
192 delete demo_controller;
194 playback_demo_stream = new std::ifstream(filename.c_str());
195 if(!playback_demo_stream->good()) {
196 std::stringstream msg;
197 msg << "Couldn't open demo file '" << filename << "' for reading.";
198 throw std::runtime_error(msg.str());
201 Player& tux = *currentsector->player;
202 demo_controller = new CodeController();
203 tux.set_controller(demo_controller);
207 GameSession::levelintro()
211 sound_manager->stop_music();
213 DrawingContext context;
214 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
215 i != currentsector->gameobjects.end(); ++i) {
216 Background* background = dynamic_cast<Background*> (*i);
218 background->draw(context);
220 Gradient* gradient = dynamic_cast<Gradient*> (*i);
222 gradient->draw(context);
226 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
227 // CENTER_ALLIGN, LAYER_FOREGROUND1);
228 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
231 sprintf(str, "Coins: %d", player_status->coins);
232 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
233 CENTER_ALLIGN, LAYER_FOREGROUND1);
235 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
236 //TODO make author check case/blank-insensitive
237 context.draw_text(white_small_text,
238 std::string(_("contributed by ")) + level->get_author(),
239 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
242 if(best_level_statistics != NULL)
243 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
245 wait_for_event(1.0, 3.0);
249 GameSession::on_escape_press()
251 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
252 return; // don't let the player open the menu, when he is dying
254 if(mode == ST_GL_TEST) {
255 main_loop->exit_screen();
256 } else if (!Menu::current()) {
257 Menu::set_current(game_menu);
258 game_menu->set_active_item(MNID_CONTINUE);
266 GameSession::process_events()
268 Player& tux = *currentsector->player;
270 // end of pause mode?
271 if(!Menu::current() && game_pause) {
275 if (end_sequence != NO_ENDSEQUENCE) {
276 if(end_sequence_controller == 0) {
277 end_sequence_controller = new CodeController();
278 tux.set_controller(end_sequence_controller);
281 end_sequence_controller->press(Controller::RIGHT);
283 if (int(last_x_pos) == int(tux.get_pos().x))
284 end_sequence_controller->press(Controller::JUMP);
285 last_x_pos = tux.get_pos().x;
289 if(playback_demo_stream != 0) {
290 demo_controller->update();
297 playback_demo_stream->get(left);
298 playback_demo_stream->get(right);
299 playback_demo_stream->get(up);
300 playback_demo_stream->get(down);
301 playback_demo_stream->get(jump);
302 playback_demo_stream->get(action);
303 demo_controller->press(Controller::LEFT, left);
304 demo_controller->press(Controller::RIGHT, right);
305 demo_controller->press(Controller::UP, up);
306 demo_controller->press(Controller::DOWN, down);
307 demo_controller->press(Controller::JUMP, jump);
308 demo_controller->press(Controller::ACTION, action);
311 // save input for demo?
312 if(capture_demo_stream != 0) {
313 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
314 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
315 capture_demo_stream ->put(main_controller->hold(Controller::UP));
316 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
317 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
318 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
323 GameSession::consoleCommand(std::string command)
325 if (command == "foo") {
330 //TODO: Build command list automatically
331 if (command == "cmdlist") {
332 msg_info("foo, cmdlist, cheats, whereami, camera");
335 //TODO: remove (or at least hide) this before release
336 if (command == "cheats") {
337 msg_info("grow, fire, ice, lifeup, numberofthebeast, lifedown, grease, invincible, mortal, shrink, kill, gotoend, flip, finish");
341 if (currentsector == 0) return false;
342 Player& tux = *currentsector->player;
344 // Cheating words (the goal of this is really for debugging,
345 // but could be used for some cheating, nothing wrong with that)
346 if (command == "grow") {
347 tux.set_bonus(GROWUP_BONUS, false);
350 if (command == "fire") {
351 tux.set_bonus(FIRE_BONUS, false);
354 if (command == "ice") {
355 tux.set_bonus(ICE_BONUS, false);
358 if (command == "lifeup") {
359 player_status->incLives();
362 if (command == "numberofthebeast") {
363 player_status->coins += 55;
366 if (command == "lifedown") {
367 player_status->coins = std::max(player_status->coins-25, 0);
370 if (command == "grease") {
371 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
374 if (command == "invincible") {
375 // be invincle for the rest of the level
376 tux.invincible_timer.start(10000);
379 if (command == "mortal") {
380 // give up invincibility
381 tux.invincible_timer.stop();
384 if (command == "shrink") {
386 tux.kill(tux.SHRINK);
389 if (command == "kill") {
393 if (command == "whereami") {
394 msg_info("You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y);
397 if (command == "gotoend") {
398 // goes to the end of the level
400 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
401 currentsector->camera->reset(
402 Vector(tux.get_pos().x, tux.get_pos().y));
405 if (command == "flip") {
406 FlipLevelTransformer flip_transformer;
407 flip_transformer.transform(GameSession::current()->get_current_level());
410 if (command == "finish") {
414 if (command == "camera") {
415 msg_info("Camera is at "
416 << Sector::current()->camera->get_translation().x << ","
417 << Sector::current()->camera->get_translation().y);
425 GameSession::check_end_conditions()
427 Player* tux = currentsector->player;
430 if(end_sequence && endsequence_timer.check()) {
433 // add time spent to statistics
434 int tottime = 0, remtime = 0;
435 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
439 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
440 j != sec->gameobjects.end(); ++j)
442 GameObject* obj = *j;
444 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
447 tottime += int(lt->get_level_time());
448 remtime += int(lt->get_remaining_time());
452 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
455 } else if (!end_sequence && tux->is_dead()) {
456 if (player_status->coins < 0) {
457 // No more coins: restart level from beginning
458 player_status->coins = 0;
461 // Still has coins: restart level from last reset point
462 restart_level(false);
470 GameSession::draw(DrawingContext& context)
472 currentsector->draw(context);
480 GameSession::draw_pause(DrawingContext& context)
482 context.draw_filled_rect(
483 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
484 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
488 GameSession::process_menu()
490 Menu* menu = Menu::current();
494 if(menu == game_menu) {
495 switch (game_menu->check()) {
497 Menu::set_current(0);
499 case MNID_ABORTLEVEL:
500 Menu::set_current(0);
501 main_loop->exit_screen();
504 } else if(menu == options_menu) {
505 process_options_menu();
513 Menu::set_current(NULL);
516 // Eat unneeded events
518 while(SDL_PollEvent(&event))
523 GameSession::update(float elapsed_time)
528 check_end_conditions();
531 if(main_controller->pressed(Controller::PAUSE_MENU))
534 // respawning in new sector?
535 if(newsector != "" && newspawnpoint != "") {
536 Sector* sector = level->get_sector(newsector);
538 msg_warning("Sector '" << newsector << "' not found");
540 sector->activate(newspawnpoint);
541 sector->play_music(LEVEL_MUSIC);
542 currentsector = sector;
547 // Update the world state and all objects in the world
550 if (end_sequence == ENDSEQUENCE_RUNNING) {
551 currentsector->update(elapsed_time/2);
552 } else if(end_sequence == NO_ENDSEQUENCE) {
553 if(!currentsector->player->growing_timer.started())
554 currentsector->update(elapsed_time);
559 sound_manager->set_listener_position(currentsector->player->get_pos());
562 if (currentsector->player->invincible_timer.started() &&
563 currentsector->player->invincible_timer.get_timeleft()
564 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence) {
565 currentsector->play_music(HERRING_MUSIC);
566 } else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence) {
567 currentsector->play_music(LEVEL_MUSIC);
572 GameSession::ExitStatus
575 Menu::set_current(0);
580 // Eat unneeded events
582 while(SDL_PollEvent(&event))
587 Uint32 fps_ticks = SDL_GetTicks();
588 Uint32 fps_nextframe_ticks = SDL_GetTicks();
590 bool skipdraw = false;
592 while (exit_status == ES_NONE) {
593 // we run in a logical framerate so elapsed time is a constant
594 // This will make the game run determistic and not different on different
596 static const float elapsed_time = 1.0 / LOGICAL_FPS;
597 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
599 game_time += elapsed_time;
602 ticks = SDL_GetTicks();
603 if(ticks > fps_nextframe_ticks) {
604 if(skipdraw == true) {
605 // already skipped last frame? we have to slow down the game then...
607 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
609 // don't draw all frames when we're getting too slow
614 while(fps_nextframe_ticks > ticks) {
616 // If we really have to wait long, then do an imprecise SDL_Delay()
617 Uint32 diff = fps_nextframe_ticks - ticks;
619 SDL_Delay(diff - 10);
621 ticks = SDL_GetTicks();
624 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
629 // Update the world state and all objects in the world
633 check_end_conditions();
634 if (end_sequence == ENDSEQUENCE_RUNNING)
635 update(elapsed_time/2);
636 else if(end_sequence == NO_ENDSEQUENCE)
637 update(elapsed_time);
644 sound_manager->update();
646 /* Time stops in pause mode */
647 if(game_pause || Menu::current())
653 if (currentsector->player->invincible_timer.started() &&
654 currentsector->player->invincible_timer.get_timeleft()
655 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
657 currentsector->play_music(HERRING_MUSIC);
659 /* or just normal music? */
660 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
662 currentsector->play_music(LEVEL_MUSIC);
665 /* Calculate frames per second */
670 if(SDL_GetTicks() - fps_ticks >= 500)
672 fps_fps = (float) fps_cnt / .5;
674 fps_ticks = SDL_GetTicks();
681 main_controller->reset();
687 GameSession::finish(bool win)
690 if(WorldMap::current())
691 WorldMap::current()->finished_level(levelfile);
694 main_loop->exit_screen();
698 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
701 newspawnpoint = spawnpoint;
705 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
707 reset_sector = sector;
712 GameSession::get_working_directory()
714 return FileSystem::dirname(levelfile);
718 GameSession::display_info_box(const std::string& text)
720 InfoBox* box = new InfoBox(text);
723 DrawingContext context;
727 main_controller->update();
729 while (SDL_PollEvent(&event)) {
730 main_controller->process_event(event);
731 if(event.type == SDL_QUIT)
732 throw graceful_shutdown();
735 if(main_controller->pressed(Controller::JUMP)
736 || main_controller->pressed(Controller::ACTION)
737 || main_controller->pressed(Controller::PAUSE_MENU)
738 || main_controller->pressed(Controller::MENU_SELECT))
740 else if(main_controller->pressed(Controller::DOWN))
742 else if(main_controller->pressed(Controller::UP))
746 context.do_drawing();
747 sound_manager->update();
754 GameSession::start_sequence(const std::string& sequencename)
756 if(sequencename == "endsequence" || sequencename == "fireworks") {
760 end_sequence = ENDSEQUENCE_RUNNING;
761 endsequence_timer.start(7.3);
763 sound_manager->play_music("music/leveldone.ogg", false);
764 currentsector->player->invincible_timer.start(7.3);
767 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
768 i != currentsector->gameobjects.end(); ++i)
770 GameObject* obj = *i;
772 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
777 if(sequencename == "fireworks") {
778 currentsector->add_object(new Fireworks());
780 } else if(sequencename == "stoptux") {
782 msg_warning("Final target reached without "
783 << "an active end sequence");
784 this->start_sequence("endsequence");
786 end_sequence = ENDSEQUENCE_WAITING;
788 msg_warning("Unknown sequence '" << sequencename << "'");
794 GameSession::drawstatus(DrawingContext& context)
796 player_status->draw(context);
798 if(config->show_fps) {
800 snprintf(str, sizeof(str), "%3.1f", fps_fps);
801 const char* fpstext = "FPS";
802 context.draw_text(white_text, fpstext, Vector(SCREEN_WIDTH - white_text->get_text_width(fpstext) - gold_text->get_text_width(" 99999") - BORDER_X, BORDER_Y + 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
803 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);