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[] = {
101 using namespace WorldMapNS;
103 GameSession* GameSession::current_ = 0;
105 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
106 Statistics* statistics)
107 : level(0), currentsector(0), mode(mode),
108 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
109 levelfile(levelfile_), best_level_statistics(statistics),
110 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
118 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
119 Console::registerCommand(consoleCommands[i], this);
122 statistics_backdrop = new Surface("images/engine/menu/score-backdrop.png");
128 GameSession::restart_level(bool fromBeginning)
131 end_sequence = NO_ENDSEQUENCE;
133 main_controller->reset();
139 level->load(levelfile);
141 global_stats.reset();
142 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
143 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
147 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
151 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
152 j != sec->gameobjects.end(); ++j)
154 GameObject* obj = *j;
156 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
158 time += int(lt->get_level_time());
161 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
163 if (fromBeginning) reset_sector="";
164 if(reset_sector != "") {
165 currentsector = level->get_sector(reset_sector);
167 std::stringstream msg;
168 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
169 throw std::runtime_error(msg.str());
171 currentsector->activate(reset_pos);
173 currentsector = level->get_sector("main");
175 throw std::runtime_error("Couldn't find main sector");
176 currentsector->activate("main");
179 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
182 currentsector->play_music(LEVEL_MUSIC);
184 if(capture_file != "")
185 record_demo(capture_file);
188 GameSession::~GameSession()
190 delete capture_demo_stream;
191 delete playback_demo_stream;
192 delete demo_controller;
194 delete end_sequence_controller;
196 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
197 Console::unregisterCommand(consoleCommands[i], this);
200 delete statistics_backdrop;
206 GameSession::record_demo(const std::string& filename)
208 delete capture_demo_stream;
210 capture_demo_stream = new std::ofstream(filename.c_str());
211 if(!capture_demo_stream->good()) {
212 std::stringstream msg;
213 msg << "Couldn't open demo file '" << filename << "' for writing.";
214 throw std::runtime_error(msg.str());
216 capture_file = filename;
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);
238 GameSession::levelintro()
242 sound_manager->stop_music();
244 DrawingContext context;
245 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
246 i != currentsector->gameobjects.end(); ++i) {
247 Background* background = dynamic_cast<Background*> (*i);
249 background->draw(context);
251 Gradient* gradient = dynamic_cast<Gradient*> (*i);
253 gradient->draw(context);
257 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
258 // CENTER_ALLIGN, LAYER_FOREGROUND1);
259 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
262 sprintf(str, "Coins: %d", player_status->coins);
263 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
264 CENTER_ALLIGN, LAYER_FOREGROUND1);
266 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
267 //TODO make author check case/blank-insensitive
268 context.draw_text(white_small_text,
269 std::string(_("contributed by ")) + level->get_author(),
270 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
273 if(best_level_statistics != NULL)
274 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
276 wait_for_event(1.0, 3.0);
280 GameSession::on_escape_press()
282 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
283 return; // don't let the player open the menu, when he is dying
285 if(mode == ST_GL_TEST) {
286 main_loop->exit_screen();
287 } else if (!Menu::current()) {
288 Menu::set_current(game_menu);
289 game_menu->set_active_item(MNID_CONTINUE);
297 GameSession::process_events()
299 Player& tux = *currentsector->player;
301 // end of pause mode?
302 if(!Menu::current() && game_pause) {
306 if (end_sequence != NO_ENDSEQUENCE) {
307 if(end_sequence_controller == 0) {
308 end_sequence_controller = new CodeController();
309 tux.set_controller(end_sequence_controller);
312 end_sequence_controller->press(Controller::RIGHT);
314 if (int(last_x_pos) == int(tux.get_pos().x))
315 end_sequence_controller->press(Controller::JUMP);
316 last_x_pos = tux.get_pos().x;
320 if(playback_demo_stream != 0) {
321 demo_controller->update();
328 playback_demo_stream->get(left);
329 playback_demo_stream->get(right);
330 playback_demo_stream->get(up);
331 playback_demo_stream->get(down);
332 playback_demo_stream->get(jump);
333 playback_demo_stream->get(action);
334 demo_controller->press(Controller::LEFT, left);
335 demo_controller->press(Controller::RIGHT, right);
336 demo_controller->press(Controller::UP, up);
337 demo_controller->press(Controller::DOWN, down);
338 demo_controller->press(Controller::JUMP, jump);
339 demo_controller->press(Controller::ACTION, action);
342 // save input for demo?
343 if(capture_demo_stream != 0) {
344 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
345 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
346 capture_demo_stream ->put(main_controller->hold(Controller::UP));
347 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
348 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
349 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
354 GameSession::consoleCommand(std::string command, std::vector<std::string> arguments)
356 if (command == "foo") {
357 msg_info << "bar" << std::endl;
361 if (currentsector == 0) return false;
362 Player& tux = *currentsector->player;
364 // Cheating words (the goal of this is really for debugging,
365 // but could be used for some cheating, nothing wrong with that)
366 if (command == "grow") {
367 tux.set_bonus(GROWUP_BONUS, false);
370 if (command == "fire") {
371 tux.set_bonus(FIRE_BONUS, false);
374 if (command == "ice") {
375 tux.set_bonus(ICE_BONUS, false);
378 if (command == "coins") {
379 if ((arguments.size() < 1) || (!Console::string_is<int>(arguments[0]))) {
380 msg_info << "Usage: coins <number>" << std::endl;
382 player_status->coins = Console::string_to<int>(arguments[0]);
386 if (command == "numberofthebeast") {
387 player_status->coins += 55;
390 if (command == "grease") {
391 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
394 if (command == "invincible") {
395 // be invincle for the rest of the level
396 tux.invincible_timer.start(10000);
399 if (command == "mortal") {
400 // give up invincibility
401 tux.invincible_timer.stop();
404 if (command == "shrink") {
406 tux.kill(tux.SHRINK);
409 if (command == "kill") {
413 if (command == "restart") {
417 if (command == "whereami") {
418 msg_info << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << std::endl;
421 if (command == "gotoend") {
422 // goes to the end of the level
424 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
425 currentsector->camera->reset(
426 Vector(tux.get_pos().x, tux.get_pos().y));
429 if (command == "flip") {
430 FlipLevelTransformer flip_transformer;
431 flip_transformer.transform(GameSession::current()->get_current_level());
434 if (command == "finish") {
438 if (command == "camera") {
439 msg_info << "Camera is at " << Sector::current()->camera->get_translation().x << "," << Sector::current()->camera->get_translation().y << std::endl;
442 if (command == "quit") {
451 GameSession::check_end_conditions()
453 Player* tux = currentsector->player;
456 if(end_sequence && endsequence_timer.check()) {
459 } else if (!end_sequence && tux->is_dead()) {
460 if (player_status->coins < 0) {
461 // No more coins: restart level from beginning
462 player_status->coins = 0;
465 // Still has coins: restart level from last reset point
466 restart_level(false);
474 GameSession::draw(DrawingContext& context)
476 currentsector->draw(context);
484 GameSession::draw_pause(DrawingContext& context)
486 context.draw_filled_rect(
487 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
488 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
492 GameSession::process_menu()
494 Menu* menu = Menu::current();
498 if(menu == game_menu) {
499 switch (game_menu->check()) {
501 Menu::set_current(0);
503 case MNID_ABORTLEVEL:
504 Menu::set_current(0);
505 main_loop->exit_screen();
508 } else if(menu == options_menu) {
509 process_options_menu();
517 Menu::set_current(NULL);
520 // Eat unneeded events
522 while(SDL_PollEvent(&event))
527 GameSession::update(float elapsed_time)
532 check_end_conditions();
535 if(main_controller->pressed(Controller::PAUSE_MENU))
538 // respawning in new sector?
539 if(newsector != "" && newspawnpoint != "") {
540 Sector* sector = level->get_sector(newsector);
542 msg_warning << "Sector '" << newsector << "' not found" << std::endl;
544 sector->activate(newspawnpoint);
545 sector->play_music(LEVEL_MUSIC);
546 currentsector = sector;
551 // Update the world state and all objects in the world
554 if (end_sequence == ENDSEQUENCE_RUNNING) {
555 currentsector->update(elapsed_time/2);
556 } else if(end_sequence == NO_ENDSEQUENCE) {
557 if(!currentsector->player->growing_timer.started())
558 currentsector->update(elapsed_time);
563 sound_manager->set_listener_position(currentsector->player->get_pos());
566 if (currentsector->player->invincible_timer.started() &&
567 currentsector->player->invincible_timer.get_timeleft()
568 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence) {
569 currentsector->play_music(HERRING_MUSIC);
570 } else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence) {
571 currentsector->play_music(LEVEL_MUSIC);
576 GameSession::ExitStatus
579 Menu::set_current(0);
584 // Eat unneeded events
586 while(SDL_PollEvent(&event))
591 Uint32 fps_ticks = SDL_GetTicks();
592 Uint32 fps_nextframe_ticks = SDL_GetTicks();
594 bool skipdraw = false;
596 while (exit_status == ES_NONE) {
597 // we run in a logical framerate so elapsed time is a constant
598 // This will make the game run determistic and not different on different
600 static const float elapsed_time = 1.0 / LOGICAL_FPS;
601 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
603 game_time += elapsed_time;
606 ticks = SDL_GetTicks();
607 if(ticks > fps_nextframe_ticks) {
608 if(skipdraw == true) {
609 // already skipped last frame? we have to slow down the game then...
611 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
613 // don't draw all frames when we're getting too slow
618 while(fps_nextframe_ticks > ticks) {
620 // If we really have to wait long, then do an imprecise SDL_Delay()
621 Uint32 diff = fps_nextframe_ticks - ticks;
623 SDL_Delay(diff - 10);
625 ticks = SDL_GetTicks();
628 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
633 // Update the world state and all objects in the world
637 check_end_conditions();
638 if (end_sequence == ENDSEQUENCE_RUNNING)
639 update(elapsed_time/2);
640 else if(end_sequence == NO_ENDSEQUENCE)
641 update(elapsed_time);
648 sound_manager->update();
650 /* Time stops in pause mode */
651 if(game_pause || Menu::current())
657 if (currentsector->player->invincible_timer.started() &&
658 currentsector->player->invincible_timer.get_timeleft()
659 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
661 currentsector->play_music(HERRING_MUSIC);
663 /* or just normal music? */
664 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
666 currentsector->play_music(LEVEL_MUSIC);
669 /* Calculate frames per second */
674 if(SDL_GetTicks() - fps_ticks >= 500)
676 fps_fps = (float) fps_cnt / .5;
678 fps_ticks = SDL_GetTicks();
685 main_controller->reset();
691 GameSession::finish(bool win)
694 if(WorldMap::current())
695 WorldMap::current()->finished_level(levelfile);
698 main_loop->exit_screen();
702 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
705 newspawnpoint = spawnpoint;
709 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
711 reset_sector = sector;
716 GameSession::get_working_directory()
718 return FileSystem::dirname(levelfile);
722 GameSession::display_info_box(const std::string& text)
724 InfoBox* box = new InfoBox(text);
727 DrawingContext context;
731 main_controller->update();
733 while (SDL_PollEvent(&event)) {
734 main_controller->process_event(event);
735 if(event.type == SDL_QUIT)
736 throw graceful_shutdown();
739 if(main_controller->pressed(Controller::JUMP)
740 || main_controller->pressed(Controller::ACTION)
741 || main_controller->pressed(Controller::PAUSE_MENU)
742 || main_controller->pressed(Controller::MENU_SELECT))
744 else if(main_controller->pressed(Controller::DOWN))
746 else if(main_controller->pressed(Controller::UP))
750 context.do_drawing();
751 sound_manager->update();
758 GameSession::start_sequence(const std::string& sequencename)
760 if(sequencename == "endsequence" || sequencename == "fireworks") {
764 end_sequence = ENDSEQUENCE_RUNNING;
765 endsequence_timer.start(7.3);
767 sound_manager->play_music("music/leveldone.ogg", false);
768 currentsector->player->invincible_timer.start(7.3);
771 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
772 i != currentsector->gameobjects.end(); ++i)
774 GameObject* obj = *i;
776 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
781 // add time spent to statistics
782 int tottime = 0, remtime = 0;
783 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
787 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
788 j != sec->gameobjects.end(); ++j)
790 GameObject* obj = *j;
792 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
795 tottime += int(lt->get_level_time());
796 remtime += int(lt->get_remaining_time());
800 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
802 if(sequencename == "fireworks") {
803 currentsector->add_object(new Fireworks());
805 } else if(sequencename == "stoptux") {
807 msg_warning << "Final target reached without an active end sequence" << std::endl;
808 this->start_sequence("endsequence");
810 end_sequence = ENDSEQUENCE_WAITING;
812 msg_warning << "Unknown sequence '" << sequencename << "'" << std::endl;
818 GameSession::drawstatus(DrawingContext& context)
820 player_status->draw(context);
822 if(config->show_fps) {
824 snprintf(str, sizeof(str), "%3.1f", fps_fps);
825 const char* fpstext = "FPS";
826 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);
827 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);
830 // draw level stats while end_sequence is running
832 global_stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop);