4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 #include "game_session.hpp"
37 #include "worldmap.hpp"
38 #include "mainloop.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/gradient.hpp"
49 #include "object/tilemap.hpp"
50 #include "object/camera.hpp"
51 #include "object/player.hpp"
52 #include "object/level_time.hpp"
53 #include "lisp/lisp.hpp"
54 #include "lisp/parser.hpp"
55 #include "resources.hpp"
57 #include "statistics.hpp"
59 #include "object/fireworks.hpp"
60 #include "textscroller.hpp"
61 #include "control/codecontroller.hpp"
62 #include "control/joystickkeyboardcontroller.hpp"
64 #include "file_system.hpp"
65 #include "gameconfig.hpp"
66 #include "gettext.hpp"
67 #include "console.hpp"
68 #include "flip_level_transformer.hpp"
70 // the engine will be run with a logical framerate of 64fps.
71 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
73 static const float LOGICAL_FPS = 64.0;
75 using namespace WorldMapNS;
77 GameSession* GameSession::current_ = 0;
79 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
80 Statistics* statistics)
81 : level(0), currentsector(0), mode(mode),
82 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
83 levelfile(levelfile_), best_level_statistics(statistics),
84 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
92 statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
98 GameSession::restart_level(bool fromBeginning)
101 end_sequence = NO_ENDSEQUENCE;
103 main_controller->reset();
107 level.reset(new Level);
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());
116 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
120 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
121 j != sec->gameobjects.end(); ++j)
123 GameObject* obj = *j;
125 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
127 time += int(lt->get_level_time());
130 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
132 if (fromBeginning) reset_sector="";
133 if(reset_sector != "") {
134 currentsector = level->get_sector(reset_sector);
136 std::stringstream msg;
137 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
138 throw std::runtime_error(msg.str());
140 currentsector->activate(reset_pos);
142 currentsector = level->get_sector("main");
144 throw std::runtime_error("Couldn't find main sector");
145 currentsector->activate("main");
148 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
151 currentsector->play_music(LEVEL_MUSIC);
153 if(capture_file != "")
154 record_demo(capture_file);
157 GameSession::~GameSession()
159 delete capture_demo_stream;
160 delete playback_demo_stream;
161 delete demo_controller;
163 delete end_sequence_controller;
169 GameSession::record_demo(const std::string& filename)
171 delete capture_demo_stream;
173 capture_demo_stream = new std::ofstream(filename.c_str());
174 if(!capture_demo_stream->good()) {
175 std::stringstream msg;
176 msg << "Couldn't open demo file '" << filename << "' for writing.";
177 throw std::runtime_error(msg.str());
179 capture_file = filename;
183 GameSession::play_demo(const std::string& filename)
185 delete playback_demo_stream;
186 delete demo_controller;
188 playback_demo_stream = new std::ifstream(filename.c_str());
189 if(!playback_demo_stream->good()) {
190 std::stringstream msg;
191 msg << "Couldn't open demo file '" << filename << "' for reading.";
192 throw std::runtime_error(msg.str());
195 Player& tux = *currentsector->player;
196 demo_controller = new CodeController();
197 tux.set_controller(demo_controller);
201 GameSession::levelintro()
205 sound_manager->stop_music();
207 DrawingContext context;
208 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
209 i != currentsector->gameobjects.end(); ++i) {
210 Background* background = dynamic_cast<Background*> (*i);
212 background->draw(context);
214 Gradient* gradient = dynamic_cast<Gradient*> (*i);
216 gradient->draw(context);
220 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
221 // CENTER_ALLIGN, LAYER_FOREGROUND1);
222 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
225 sprintf(str, "Coins: %d", player_status->coins);
226 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
227 CENTER_ALLIGN, LAYER_FOREGROUND1);
229 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
230 //TODO make author check case/blank-insensitive
231 context.draw_text(white_small_text,
232 std::string(_("contributed by ")) + level->get_author(),
233 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
236 if(best_level_statistics != NULL)
237 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
239 wait_for_event(1.0, 3.0);
243 GameSession::on_escape_press()
245 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
246 return; // don't let the player open the menu, when he is dying
248 if(mode == ST_GL_TEST) {
249 main_loop->exit_screen();
250 } else if (!Menu::current()) {
251 Menu::set_current(game_menu);
252 game_menu->set_active_item(MNID_CONTINUE);
260 GameSession::process_events()
262 Player& tux = *currentsector->player;
264 // end of pause mode?
265 if(!Menu::current() && game_pause) {
269 if (end_sequence != NO_ENDSEQUENCE) {
270 if(end_sequence_controller == 0) {
271 end_sequence_controller = new CodeController();
272 tux.set_controller(end_sequence_controller);
275 end_sequence_controller->press(Controller::RIGHT);
277 if (int(last_x_pos) == int(tux.get_pos().x))
278 end_sequence_controller->press(Controller::JUMP);
279 last_x_pos = tux.get_pos().x;
283 if(playback_demo_stream != 0) {
284 demo_controller->update();
291 playback_demo_stream->get(left);
292 playback_demo_stream->get(right);
293 playback_demo_stream->get(up);
294 playback_demo_stream->get(down);
295 playback_demo_stream->get(jump);
296 playback_demo_stream->get(action);
297 demo_controller->press(Controller::LEFT, left);
298 demo_controller->press(Controller::RIGHT, right);
299 demo_controller->press(Controller::UP, up);
300 demo_controller->press(Controller::DOWN, down);
301 demo_controller->press(Controller::JUMP, jump);
302 demo_controller->press(Controller::ACTION, action);
305 // save input for demo?
306 if(capture_demo_stream != 0) {
307 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
308 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
309 capture_demo_stream ->put(main_controller->hold(Controller::UP));
310 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
311 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
312 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
317 GameSession::check_end_conditions()
319 Player* tux = currentsector->player;
322 if(end_sequence && endsequence_timer.check()) {
325 } else if (!end_sequence && tux->is_dead()) {
326 if (player_status->coins < 0) {
327 // No more coins: restart level from beginning
328 player_status->coins = 0;
331 // Still has coins: restart level from last reset point
332 restart_level(false);
340 GameSession::draw(DrawingContext& context)
342 currentsector->draw(context);
350 GameSession::draw_pause(DrawingContext& context)
352 context.draw_filled_rect(
353 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
354 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
358 GameSession::process_menu()
360 Menu* menu = Menu::current();
364 if(menu == game_menu) {
365 switch (game_menu->check()) {
367 Menu::set_current(0);
369 case MNID_ABORTLEVEL:
370 Menu::set_current(0);
371 main_loop->exit_screen();
381 Menu::set_current(NULL);
384 // Eat unneeded events
386 while(SDL_PollEvent(&event))
391 GameSession::update(float elapsed_time)
396 check_end_conditions();
399 if(main_controller->pressed(Controller::PAUSE_MENU))
402 // respawning in new sector?
403 if(newsector != "" && newspawnpoint != "") {
404 Sector* sector = level->get_sector(newsector);
406 log_warning << "Sector '" << newsector << "' not found" << std::endl;
408 sector->activate(newspawnpoint);
409 sector->play_music(LEVEL_MUSIC);
410 currentsector = sector;
415 // Update the world state and all objects in the world
418 if (end_sequence == ENDSEQUENCE_RUNNING) {
419 currentsector->update(elapsed_time/2);
420 } else if(end_sequence == NO_ENDSEQUENCE) {
421 if(!currentsector->player->growing_timer.started())
422 currentsector->update(elapsed_time);
427 sound_manager->set_listener_position(currentsector->player->get_pos());
433 if(currentsector->player->invincible_timer.started()) {
434 if(currentsector->player->invincible_timer.get_timeleft() <=
435 TUX_INVINCIBLE_TIME_WARNING) {
436 currentsector->play_music(HERRING_WARNING_MUSIC);
438 currentsector->play_music(HERRING_MUSIC);
440 } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
441 currentsector->play_music(LEVEL_MUSIC);
446 GameSession::ExitStatus
449 Menu::set_current(0);
454 // Eat unneeded events
456 while(SDL_PollEvent(&event))
461 Uint32 fps_ticks = SDL_GetTicks();
462 Uint32 fps_nextframe_ticks = SDL_GetTicks();
464 bool skipdraw = false;
466 while (exit_status == ES_NONE) {
467 // we run in a logical framerate so elapsed time is a constant
468 // This will make the game run determistic and not different on different
470 static const float elapsed_time = 1.0 / LOGICAL_FPS;
471 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
473 game_time += elapsed_time;
476 ticks = SDL_GetTicks();
477 if(ticks > fps_nextframe_ticks) {
478 if(skipdraw == true) {
479 // already skipped last frame? we have to slow down the game then...
481 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
483 // don't draw all frames when we're getting too slow
488 while(fps_nextframe_ticks > ticks) {
490 // If we really have to wait long, then do an imprecise SDL_Delay()
491 Uint32 diff = fps_nextframe_ticks - ticks;
493 SDL_Delay(diff - 10);
495 ticks = SDL_GetTicks();
498 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
503 // Update the world state and all objects in the world
507 check_end_conditions();
508 if (end_sequence == ENDSEQUENCE_RUNNING)
509 update(elapsed_time/2);
510 else if(end_sequence == NO_ENDSEQUENCE)
511 update(elapsed_time);
518 sound_manager->update();
520 /* Time stops in pause mode */
521 if(game_pause || Menu::current())
527 if (currentsector->player->invincible_timer.started() &&
528 currentsector->player->invincible_timer.get_timeleft()
529 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
531 currentsector->play_music(HERRING_MUSIC);
533 /* or just normal music? */
534 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
536 currentsector->play_music(LEVEL_MUSIC);
539 /* Calculate frames per second */
544 if(SDL_GetTicks() - fps_ticks >= 500)
546 fps_fps = (float) fps_cnt / .5;
548 fps_ticks = SDL_GetTicks();
555 main_controller->reset();
561 GameSession::finish(bool win)
564 if(WorldMap::current())
565 WorldMap::current()->finished_level(levelfile);
568 main_loop->exit_screen();
572 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
575 newspawnpoint = spawnpoint;
579 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
581 reset_sector = sector;
586 GameSession::get_working_directory()
588 return FileSystem::dirname(levelfile);
592 GameSession::display_info_box(const std::string& text)
594 InfoBox* box = new InfoBox(text);
597 DrawingContext context;
601 // TODO make a screen out of this, another mainloop is ugly
602 main_controller->update();
604 while (SDL_PollEvent(&event)) {
605 main_controller->process_event(event);
606 if(event.type == SDL_QUIT)
610 if(main_controller->pressed(Controller::JUMP)
611 || main_controller->pressed(Controller::ACTION)
612 || main_controller->pressed(Controller::PAUSE_MENU)
613 || main_controller->pressed(Controller::MENU_SELECT))
615 else if(main_controller->pressed(Controller::DOWN))
617 else if(main_controller->pressed(Controller::UP))
621 context.do_drawing();
622 sound_manager->update();
629 GameSession::start_sequence(const std::string& sequencename)
631 if(sequencename == "endsequence" || sequencename == "fireworks") {
635 end_sequence = ENDSEQUENCE_RUNNING;
636 endsequence_timer.start(7.3);
638 sound_manager->play_music("music/leveldone.ogg", false);
639 currentsector->player->invincible_timer.start(7.3);
642 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
643 i != currentsector->gameobjects.end(); ++i)
645 GameObject* obj = *i;
647 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
652 // add time spent to statistics
653 int tottime = 0, remtime = 0;
654 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
658 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
659 j != sec->gameobjects.end(); ++j)
661 GameObject* obj = *j;
663 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
666 tottime += int(lt->get_level_time());
667 remtime += int(lt->get_remaining_time());
671 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
673 if(sequencename == "fireworks") {
674 currentsector->add_object(new Fireworks());
676 } else if(sequencename == "stoptux") {
678 log_warning << "Final target reached without an active end sequence" << std::endl;
679 this->start_sequence("endsequence");
681 end_sequence = ENDSEQUENCE_WAITING;
683 log_warning << "Unknown sequence '" << sequencename << "'" << std::endl;
689 GameSession::drawstatus(DrawingContext& context)
691 player_status->draw(context);
693 if(config->show_fps) {
695 snprintf(str, sizeof(str), "%3.1f", fps_fps);
696 const char* fpstext = "FPS";
697 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);
698 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);
701 // draw level stats while end_sequence is running
703 global_stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());