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 "console.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[] = {
96 using namespace WorldMapNS;
98 GameSession* GameSession::current_ = 0;
100 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
101 Statistics* statistics)
102 : level(0), currentsector(0), mode(mode),
103 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
104 levelfile(levelfile_), best_level_statistics(statistics),
105 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
113 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
114 Console::registerCommand(consoleCommands[i], this);
117 statistics_backdrop = new Surface("images/engine/menu/score-backdrop.png");
123 GameSession::restart_level(bool fromBeginning)
126 end_sequence = NO_ENDSEQUENCE;
128 main_controller->reset();
134 level->load(levelfile);
136 global_stats.reset();
137 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
138 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
142 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
146 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
147 j != sec->gameobjects.end(); ++j)
149 GameObject* obj = *j;
151 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
153 time += int(lt->get_level_time());
156 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
158 if (fromBeginning) reset_sector="";
159 if(reset_sector != "") {
160 currentsector = level->get_sector(reset_sector);
162 std::stringstream msg;
163 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
164 throw std::runtime_error(msg.str());
166 currentsector->activate(reset_pos);
168 currentsector = level->get_sector("main");
170 throw std::runtime_error("Couldn't find main sector");
171 currentsector->activate("main");
174 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
177 currentsector->play_music(LEVEL_MUSIC);
179 if(capture_file != "")
180 record_demo(capture_file);
183 GameSession::~GameSession()
185 delete capture_demo_stream;
186 delete playback_demo_stream;
187 delete demo_controller;
189 delete end_sequence_controller;
192 delete statistics_backdrop;
198 GameSession::record_demo(const std::string& filename)
200 delete capture_demo_stream;
202 capture_demo_stream = new std::ofstream(filename.c_str());
203 if(!capture_demo_stream->good()) {
204 std::stringstream msg;
205 msg << "Couldn't open demo file '" << filename << "' for writing.";
206 throw std::runtime_error(msg.str());
208 capture_file = filename;
212 GameSession::play_demo(const std::string& filename)
214 delete playback_demo_stream;
215 delete demo_controller;
217 playback_demo_stream = new std::ifstream(filename.c_str());
218 if(!playback_demo_stream->good()) {
219 std::stringstream msg;
220 msg << "Couldn't open demo file '" << filename << "' for reading.";
221 throw std::runtime_error(msg.str());
224 Player& tux = *currentsector->player;
225 demo_controller = new CodeController();
226 tux.set_controller(demo_controller);
230 GameSession::levelintro()
234 sound_manager->stop_music();
236 DrawingContext context;
237 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
238 i != currentsector->gameobjects.end(); ++i) {
239 Background* background = dynamic_cast<Background*> (*i);
241 background->draw(context);
243 Gradient* gradient = dynamic_cast<Gradient*> (*i);
245 gradient->draw(context);
249 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
250 // CENTER_ALLIGN, LAYER_FOREGROUND1);
251 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
254 sprintf(str, "Coins: %d", player_status->coins);
255 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
256 CENTER_ALLIGN, LAYER_FOREGROUND1);
258 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
259 //TODO make author check case/blank-insensitive
260 context.draw_text(white_small_text,
261 std::string(_("contributed by ")) + level->get_author(),
262 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
265 if(best_level_statistics != NULL)
266 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
268 wait_for_event(1.0, 3.0);
272 GameSession::on_escape_press()
274 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
275 return; // don't let the player open the menu, when he is dying
277 if(mode == ST_GL_TEST) {
278 main_loop->exit_screen();
279 } else if (!Menu::current()) {
280 Menu::set_current(game_menu);
281 game_menu->set_active_item(MNID_CONTINUE);
289 GameSession::process_events()
291 Player& tux = *currentsector->player;
293 // end of pause mode?
294 if(!Menu::current() && game_pause) {
298 if (end_sequence != NO_ENDSEQUENCE) {
299 if(end_sequence_controller == 0) {
300 end_sequence_controller = new CodeController();
301 tux.set_controller(end_sequence_controller);
304 end_sequence_controller->press(Controller::RIGHT);
306 if (int(last_x_pos) == int(tux.get_pos().x))
307 end_sequence_controller->press(Controller::JUMP);
308 last_x_pos = tux.get_pos().x;
312 if(playback_demo_stream != 0) {
313 demo_controller->update();
320 playback_demo_stream->get(left);
321 playback_demo_stream->get(right);
322 playback_demo_stream->get(up);
323 playback_demo_stream->get(down);
324 playback_demo_stream->get(jump);
325 playback_demo_stream->get(action);
326 demo_controller->press(Controller::LEFT, left);
327 demo_controller->press(Controller::RIGHT, right);
328 demo_controller->press(Controller::UP, up);
329 demo_controller->press(Controller::DOWN, down);
330 demo_controller->press(Controller::JUMP, jump);
331 demo_controller->press(Controller::ACTION, action);
334 // save input for demo?
335 if(capture_demo_stream != 0) {
336 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
337 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
338 capture_demo_stream ->put(main_controller->hold(Controller::UP));
339 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
340 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
341 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
346 GameSession::consoleCommand(std::string command, std::vector<std::string>)
348 if (command == "foo") {
349 msg_info << "bar" << std::endl;
353 if (currentsector == 0) return false;
354 Player& tux = *currentsector->player;
356 // Cheating words (the goal of this is really for debugging,
357 // but could be used for some cheating, nothing wrong with that)
358 if (command == "grease") {
359 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
362 if (command == "invincible") {
363 // be invincle for the rest of the level
364 tux.invincible_timer.start(10000);
367 if (command == "mortal") {
368 // give up invincibility
369 tux.invincible_timer.stop();
372 if (command == "shrink") {
374 tux.kill(tux.SHRINK);
377 if (command == "kill") {
381 if (command == "restart") {
385 if (command == "whereami") {
386 msg_info << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << std::endl;
389 if (command == "gotoend") {
390 // goes to the end of the level
392 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
393 currentsector->camera->reset(
394 Vector(tux.get_pos().x, tux.get_pos().y));
397 if (command == "flip") {
398 FlipLevelTransformer flip_transformer;
399 flip_transformer.transform(GameSession::current()->get_current_level());
402 if (command == "finish") {
406 if (command == "camera") {
407 msg_info << "Camera is at " << Sector::current()->camera->get_translation().x << "," << Sector::current()->camera->get_translation().y << std::endl;
410 if (command == "quit") {
419 GameSession::check_end_conditions()
421 Player* tux = currentsector->player;
424 if(end_sequence && endsequence_timer.check()) {
427 } else if (!end_sequence && tux->is_dead()) {
428 if (player_status->coins < 0) {
429 // No more coins: restart level from beginning
430 player_status->coins = 0;
433 // Still has coins: restart level from last reset point
434 restart_level(false);
442 GameSession::draw(DrawingContext& context)
444 currentsector->draw(context);
452 GameSession::draw_pause(DrawingContext& context)
454 context.draw_filled_rect(
455 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
456 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
460 GameSession::process_menu()
462 Menu* menu = Menu::current();
466 if(menu == game_menu) {
467 switch (game_menu->check()) {
469 Menu::set_current(0);
471 case MNID_ABORTLEVEL:
472 Menu::set_current(0);
473 main_loop->exit_screen();
483 Menu::set_current(NULL);
486 // Eat unneeded events
488 while(SDL_PollEvent(&event))
493 GameSession::update(float elapsed_time)
498 check_end_conditions();
501 if(main_controller->pressed(Controller::PAUSE_MENU))
504 // respawning in new sector?
505 if(newsector != "" && newspawnpoint != "") {
506 Sector* sector = level->get_sector(newsector);
508 msg_warning << "Sector '" << newsector << "' not found" << std::endl;
510 sector->activate(newspawnpoint);
511 sector->play_music(LEVEL_MUSIC);
512 currentsector = sector;
517 // Update the world state and all objects in the world
520 if (end_sequence == ENDSEQUENCE_RUNNING) {
521 currentsector->update(elapsed_time/2);
522 } else if(end_sequence == NO_ENDSEQUENCE) {
523 if(!currentsector->player->growing_timer.started())
524 currentsector->update(elapsed_time);
529 sound_manager->set_listener_position(currentsector->player->get_pos());
532 if (currentsector->player->invincible_timer.started() &&
533 currentsector->player->invincible_timer.get_timeleft()
534 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence) {
535 currentsector->play_music(HERRING_MUSIC);
536 } else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence) {
537 currentsector->play_music(LEVEL_MUSIC);
542 GameSession::ExitStatus
545 Menu::set_current(0);
550 // Eat unneeded events
552 while(SDL_PollEvent(&event))
557 Uint32 fps_ticks = SDL_GetTicks();
558 Uint32 fps_nextframe_ticks = SDL_GetTicks();
560 bool skipdraw = false;
562 while (exit_status == ES_NONE) {
563 // we run in a logical framerate so elapsed time is a constant
564 // This will make the game run determistic and not different on different
566 static const float elapsed_time = 1.0 / LOGICAL_FPS;
567 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
569 game_time += elapsed_time;
572 ticks = SDL_GetTicks();
573 if(ticks > fps_nextframe_ticks) {
574 if(skipdraw == true) {
575 // already skipped last frame? we have to slow down the game then...
577 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
579 // don't draw all frames when we're getting too slow
584 while(fps_nextframe_ticks > ticks) {
586 // If we really have to wait long, then do an imprecise SDL_Delay()
587 Uint32 diff = fps_nextframe_ticks - ticks;
589 SDL_Delay(diff - 10);
591 ticks = SDL_GetTicks();
594 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
599 // Update the world state and all objects in the world
603 check_end_conditions();
604 if (end_sequence == ENDSEQUENCE_RUNNING)
605 update(elapsed_time/2);
606 else if(end_sequence == NO_ENDSEQUENCE)
607 update(elapsed_time);
614 sound_manager->update();
616 /* Time stops in pause mode */
617 if(game_pause || Menu::current())
623 if (currentsector->player->invincible_timer.started() &&
624 currentsector->player->invincible_timer.get_timeleft()
625 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
627 currentsector->play_music(HERRING_MUSIC);
629 /* or just normal music? */
630 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
632 currentsector->play_music(LEVEL_MUSIC);
635 /* Calculate frames per second */
640 if(SDL_GetTicks() - fps_ticks >= 500)
642 fps_fps = (float) fps_cnt / .5;
644 fps_ticks = SDL_GetTicks();
651 main_controller->reset();
657 GameSession::finish(bool win)
660 if(WorldMap::current())
661 WorldMap::current()->finished_level(levelfile);
664 main_loop->exit_screen();
668 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
671 newspawnpoint = spawnpoint;
675 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
677 reset_sector = sector;
682 GameSession::get_working_directory()
684 return FileSystem::dirname(levelfile);
688 GameSession::display_info_box(const std::string& text)
690 InfoBox* box = new InfoBox(text);
693 DrawingContext context;
697 // TODO make a screen out of this, another mainloop is ugly
698 main_controller->update();
700 while (SDL_PollEvent(&event)) {
701 main_controller->process_event(event);
702 if(event.type == SDL_QUIT)
706 if(main_controller->pressed(Controller::JUMP)
707 || main_controller->pressed(Controller::ACTION)
708 || main_controller->pressed(Controller::PAUSE_MENU)
709 || main_controller->pressed(Controller::MENU_SELECT))
711 else if(main_controller->pressed(Controller::DOWN))
713 else if(main_controller->pressed(Controller::UP))
717 context.do_drawing();
718 sound_manager->update();
725 GameSession::start_sequence(const std::string& sequencename)
727 if(sequencename == "endsequence" || sequencename == "fireworks") {
731 end_sequence = ENDSEQUENCE_RUNNING;
732 endsequence_timer.start(7.3);
734 sound_manager->play_music("music/leveldone.ogg", false);
735 currentsector->player->invincible_timer.start(7.3);
738 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
739 i != currentsector->gameobjects.end(); ++i)
741 GameObject* obj = *i;
743 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
748 // add time spent to statistics
749 int tottime = 0, remtime = 0;
750 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
754 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
755 j != sec->gameobjects.end(); ++j)
757 GameObject* obj = *j;
759 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
762 tottime += int(lt->get_level_time());
763 remtime += int(lt->get_remaining_time());
767 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
769 if(sequencename == "fireworks") {
770 currentsector->add_object(new Fireworks());
772 } else if(sequencename == "stoptux") {
774 msg_warning << "Final target reached without an active end sequence" << std::endl;
775 this->start_sequence("endsequence");
777 end_sequence = ENDSEQUENCE_WAITING;
779 msg_warning << "Unknown sequence '" << sequencename << "'" << std::endl;
785 GameSession::drawstatus(DrawingContext& context)
787 player_status->draw(context);
789 if(config->show_fps) {
791 snprintf(str, sizeof(str), "%3.1f", fps_fps);
792 const char* fpstext = "FPS";
793 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);
794 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);
797 // draw level stats while end_sequence is running
799 global_stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop);