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;
79 const char* consoleCommands[] = {
100 using namespace WorldMapNS;
102 GameSession* GameSession::current_ = 0;
104 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
105 Statistics* statistics)
106 : level(0), currentsector(0), mode(mode),
107 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
108 levelfile(levelfile_), best_level_statistics(statistics),
109 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
117 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
118 Console::registerCommand(consoleCommands[i], this);
125 GameSession::restart_level(bool fromBeginning)
128 end_sequence = NO_ENDSEQUENCE;
130 main_controller->reset();
136 level->load(levelfile);
138 global_stats.reset();
139 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
140 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
144 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
148 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
149 j != sec->gameobjects.end(); ++j)
151 GameObject* obj = *j;
153 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
155 time += int(lt->get_level_time());
158 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
160 if (fromBeginning) reset_sector="";
161 if(reset_sector != "") {
162 currentsector = level->get_sector(reset_sector);
164 std::stringstream msg;
165 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
166 throw std::runtime_error(msg.str());
168 currentsector->activate(reset_pos);
170 currentsector = level->get_sector("main");
172 throw std::runtime_error("Couldn't find main sector");
173 currentsector->activate("main");
176 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
179 currentsector->play_music(LEVEL_MUSIC);
181 if(capture_file != "")
182 record_demo(capture_file);
185 GameSession::~GameSession()
187 delete capture_demo_stream;
188 delete playback_demo_stream;
189 delete demo_controller;
191 delete end_sequence_controller;
193 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
194 Console::unregisterCommand(consoleCommands[i], this);
201 GameSession::record_demo(const std::string& filename)
203 delete capture_demo_stream;
205 capture_demo_stream = new std::ofstream(filename.c_str());
206 if(!capture_demo_stream->good()) {
207 std::stringstream msg;
208 msg << "Couldn't open demo file '" << filename << "' for writing.";
209 throw std::runtime_error(msg.str());
211 capture_file = filename;
215 GameSession::play_demo(const std::string& filename)
217 delete playback_demo_stream;
218 delete demo_controller;
220 playback_demo_stream = new std::ifstream(filename.c_str());
221 if(!playback_demo_stream->good()) {
222 std::stringstream msg;
223 msg << "Couldn't open demo file '" << filename << "' for reading.";
224 throw std::runtime_error(msg.str());
227 Player& tux = *currentsector->player;
228 demo_controller = new CodeController();
229 tux.set_controller(demo_controller);
233 GameSession::levelintro()
237 sound_manager->stop_music();
239 DrawingContext context;
240 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
241 i != currentsector->gameobjects.end(); ++i) {
242 Background* background = dynamic_cast<Background*> (*i);
244 background->draw(context);
246 Gradient* gradient = dynamic_cast<Gradient*> (*i);
248 gradient->draw(context);
252 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
253 // CENTER_ALLIGN, LAYER_FOREGROUND1);
254 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
257 sprintf(str, "Coins: %d", player_status->coins);
258 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
259 CENTER_ALLIGN, LAYER_FOREGROUND1);
261 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
262 //TODO make author check case/blank-insensitive
263 context.draw_text(white_small_text,
264 std::string(_("contributed by ")) + level->get_author(),
265 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
268 if(best_level_statistics != NULL)
269 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
271 wait_for_event(1.0, 3.0);
275 GameSession::on_escape_press()
277 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
278 return; // don't let the player open the menu, when he is dying
280 if(mode == ST_GL_TEST) {
281 main_loop->exit_screen();
282 } else if (!Menu::current()) {
283 Menu::set_current(game_menu);
284 game_menu->set_active_item(MNID_CONTINUE);
292 GameSession::process_events()
294 Player& tux = *currentsector->player;
296 // end of pause mode?
297 if(!Menu::current() && game_pause) {
301 if (end_sequence != NO_ENDSEQUENCE) {
302 if(end_sequence_controller == 0) {
303 end_sequence_controller = new CodeController();
304 tux.set_controller(end_sequence_controller);
307 end_sequence_controller->press(Controller::RIGHT);
309 if (int(last_x_pos) == int(tux.get_pos().x))
310 end_sequence_controller->press(Controller::JUMP);
311 last_x_pos = tux.get_pos().x;
315 if(playback_demo_stream != 0) {
316 demo_controller->update();
323 playback_demo_stream->get(left);
324 playback_demo_stream->get(right);
325 playback_demo_stream->get(up);
326 playback_demo_stream->get(down);
327 playback_demo_stream->get(jump);
328 playback_demo_stream->get(action);
329 demo_controller->press(Controller::LEFT, left);
330 demo_controller->press(Controller::RIGHT, right);
331 demo_controller->press(Controller::UP, up);
332 demo_controller->press(Controller::DOWN, down);
333 demo_controller->press(Controller::JUMP, jump);
334 demo_controller->press(Controller::ACTION, action);
337 // save input for demo?
338 if(capture_demo_stream != 0) {
339 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
340 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
341 capture_demo_stream ->put(main_controller->hold(Controller::UP));
342 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
343 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
344 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
349 GameSession::consoleCommand(std::string command)
351 if (command == "foo") {
356 if (currentsector == 0) return false;
357 Player& tux = *currentsector->player;
359 // Cheating words (the goal of this is really for debugging,
360 // but could be used for some cheating, nothing wrong with that)
361 if (command == "grow") {
362 tux.set_bonus(GROWUP_BONUS, false);
365 if (command == "fire") {
366 tux.set_bonus(FIRE_BONUS, false);
369 if (command == "ice") {
370 tux.set_bonus(ICE_BONUS, false);
373 if (command == "lifeup") {
374 player_status->incLives();
377 if (command == "numberofthebeast") {
378 player_status->coins += 55;
381 if (command == "lifedown") {
382 player_status->coins = std::max(player_status->coins-25, 0);
385 if (command == "grease") {
386 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
389 if (command == "invincible") {
390 // be invincle for the rest of the level
391 tux.invincible_timer.start(10000);
394 if (command == "mortal") {
395 // give up invincibility
396 tux.invincible_timer.stop();
399 if (command == "shrink") {
401 tux.kill(tux.SHRINK);
404 if (command == "kill") {
408 if (command == "whereami") {
409 msg_info("You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y);
412 if (command == "gotoend") {
413 // goes to the end of the level
415 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
416 currentsector->camera->reset(
417 Vector(tux.get_pos().x, tux.get_pos().y));
420 if (command == "flip") {
421 FlipLevelTransformer flip_transformer;
422 flip_transformer.transform(GameSession::current()->get_current_level());
425 if (command == "finish") {
429 if (command == "camera") {
430 msg_info("Camera is at "
431 << Sector::current()->camera->get_translation().x << ","
432 << Sector::current()->camera->get_translation().y);
440 GameSession::check_end_conditions()
442 Player* tux = currentsector->player;
445 if(end_sequence && endsequence_timer.check()) {
448 // add time spent to statistics
449 int tottime = 0, remtime = 0;
450 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
454 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
455 j != sec->gameobjects.end(); ++j)
457 GameObject* obj = *j;
459 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
462 tottime += int(lt->get_level_time());
463 remtime += int(lt->get_remaining_time());
467 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
470 } else if (!end_sequence && tux->is_dead()) {
471 if (player_status->coins < 0) {
472 // No more coins: restart level from beginning
473 player_status->coins = 0;
476 // Still has coins: restart level from last reset point
477 restart_level(false);
485 GameSession::draw(DrawingContext& context)
487 currentsector->draw(context);
495 GameSession::draw_pause(DrawingContext& context)
497 context.draw_filled_rect(
498 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
499 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
503 GameSession::process_menu()
505 Menu* menu = Menu::current();
509 if(menu == game_menu) {
510 switch (game_menu->check()) {
512 Menu::set_current(0);
514 case MNID_ABORTLEVEL:
515 Menu::set_current(0);
516 main_loop->exit_screen();
519 } else if(menu == options_menu) {
520 process_options_menu();
528 Menu::set_current(NULL);
531 // Eat unneeded events
533 while(SDL_PollEvent(&event))
538 GameSession::update(float elapsed_time)
543 check_end_conditions();
546 if(main_controller->pressed(Controller::PAUSE_MENU))
549 // respawning in new sector?
550 if(newsector != "" && newspawnpoint != "") {
551 Sector* sector = level->get_sector(newsector);
553 msg_warning("Sector '" << newsector << "' not found");
555 sector->activate(newspawnpoint);
556 sector->play_music(LEVEL_MUSIC);
557 currentsector = sector;
562 // Update the world state and all objects in the world
565 if (end_sequence == ENDSEQUENCE_RUNNING) {
566 currentsector->update(elapsed_time/2);
567 } else if(end_sequence == NO_ENDSEQUENCE) {
568 if(!currentsector->player->growing_timer.started())
569 currentsector->update(elapsed_time);
574 sound_manager->set_listener_position(currentsector->player->get_pos());
577 if (currentsector->player->invincible_timer.started() &&
578 currentsector->player->invincible_timer.get_timeleft()
579 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence) {
580 currentsector->play_music(HERRING_MUSIC);
581 } else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence) {
582 currentsector->play_music(LEVEL_MUSIC);
587 GameSession::ExitStatus
590 Menu::set_current(0);
595 // Eat unneeded events
597 while(SDL_PollEvent(&event))
602 Uint32 fps_ticks = SDL_GetTicks();
603 Uint32 fps_nextframe_ticks = SDL_GetTicks();
605 bool skipdraw = false;
607 while (exit_status == ES_NONE) {
608 // we run in a logical framerate so elapsed time is a constant
609 // This will make the game run determistic and not different on different
611 static const float elapsed_time = 1.0 / LOGICAL_FPS;
612 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
614 game_time += elapsed_time;
617 ticks = SDL_GetTicks();
618 if(ticks > fps_nextframe_ticks) {
619 if(skipdraw == true) {
620 // already skipped last frame? we have to slow down the game then...
622 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
624 // don't draw all frames when we're getting too slow
629 while(fps_nextframe_ticks > ticks) {
631 // If we really have to wait long, then do an imprecise SDL_Delay()
632 Uint32 diff = fps_nextframe_ticks - ticks;
634 SDL_Delay(diff - 10);
636 ticks = SDL_GetTicks();
639 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
644 // Update the world state and all objects in the world
648 check_end_conditions();
649 if (end_sequence == ENDSEQUENCE_RUNNING)
650 update(elapsed_time/2);
651 else if(end_sequence == NO_ENDSEQUENCE)
652 update(elapsed_time);
659 sound_manager->update();
661 /* Time stops in pause mode */
662 if(game_pause || Menu::current())
668 if (currentsector->player->invincible_timer.started() &&
669 currentsector->player->invincible_timer.get_timeleft()
670 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
672 currentsector->play_music(HERRING_MUSIC);
674 /* or just normal music? */
675 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
677 currentsector->play_music(LEVEL_MUSIC);
680 /* Calculate frames per second */
685 if(SDL_GetTicks() - fps_ticks >= 500)
687 fps_fps = (float) fps_cnt / .5;
689 fps_ticks = SDL_GetTicks();
696 main_controller->reset();
702 GameSession::finish(bool win)
705 if(WorldMap::current())
706 WorldMap::current()->finished_level(levelfile);
709 main_loop->exit_screen();
713 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
716 newspawnpoint = spawnpoint;
720 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
722 reset_sector = sector;
727 GameSession::get_working_directory()
729 return FileSystem::dirname(levelfile);
733 GameSession::display_info_box(const std::string& text)
735 InfoBox* box = new InfoBox(text);
738 DrawingContext context;
742 main_controller->update();
744 while (SDL_PollEvent(&event)) {
745 main_controller->process_event(event);
746 if(event.type == SDL_QUIT)
747 throw graceful_shutdown();
750 if(main_controller->pressed(Controller::JUMP)
751 || main_controller->pressed(Controller::ACTION)
752 || main_controller->pressed(Controller::PAUSE_MENU)
753 || main_controller->pressed(Controller::MENU_SELECT))
755 else if(main_controller->pressed(Controller::DOWN))
757 else if(main_controller->pressed(Controller::UP))
761 context.do_drawing();
762 sound_manager->update();
769 GameSession::start_sequence(const std::string& sequencename)
771 if(sequencename == "endsequence" || sequencename == "fireworks") {
775 end_sequence = ENDSEQUENCE_RUNNING;
776 endsequence_timer.start(7.3);
778 sound_manager->play_music("music/leveldone.ogg", false);
779 currentsector->player->invincible_timer.start(7.3);
782 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
783 i != currentsector->gameobjects.end(); ++i)
785 GameObject* obj = *i;
787 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
792 if(sequencename == "fireworks") {
793 currentsector->add_object(new Fireworks());
795 } else if(sequencename == "stoptux") {
797 msg_warning("Final target reached without "
798 << "an active end sequence");
799 this->start_sequence("endsequence");
801 end_sequence = ENDSEQUENCE_WAITING;
803 msg_warning("Unknown sequence '" << sequencename << "'");
809 GameSession::drawstatus(DrawingContext& context)
811 player_status->draw(context);
813 if(config->show_fps) {
815 snprintf(str, sizeof(str), "%3.1f", fps_fps);
816 const char* fpstext = "FPS";
817 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);
818 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);