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::instance->registerCommand(consoleCommands[i], this);
117 statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
123 GameSession::restart_level(bool fromBeginning)
126 end_sequence = NO_ENDSEQUENCE;
128 main_controller->reset();
132 level.reset(new Level);
133 level->load(levelfile);
135 global_stats.reset();
136 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
137 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
141 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
145 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
146 j != sec->gameobjects.end(); ++j)
148 GameObject* obj = *j;
150 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
152 time += int(lt->get_level_time());
155 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
157 if (fromBeginning) reset_sector="";
158 if(reset_sector != "") {
159 currentsector = level->get_sector(reset_sector);
161 std::stringstream msg;
162 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
163 throw std::runtime_error(msg.str());
165 currentsector->activate(reset_pos);
167 currentsector = level->get_sector("main");
169 throw std::runtime_error("Couldn't find main sector");
170 currentsector->activate("main");
173 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
176 currentsector->play_music(LEVEL_MUSIC);
178 if(capture_file != "")
179 record_demo(capture_file);
182 GameSession::~GameSession()
184 delete capture_demo_stream;
185 delete playback_demo_stream;
186 delete demo_controller;
188 delete end_sequence_controller;
194 GameSession::record_demo(const std::string& filename)
196 delete capture_demo_stream;
198 capture_demo_stream = new std::ofstream(filename.c_str());
199 if(!capture_demo_stream->good()) {
200 std::stringstream msg;
201 msg << "Couldn't open demo file '" << filename << "' for writing.";
202 throw std::runtime_error(msg.str());
204 capture_file = filename;
208 GameSession::play_demo(const std::string& filename)
210 delete playback_demo_stream;
211 delete demo_controller;
213 playback_demo_stream = new std::ifstream(filename.c_str());
214 if(!playback_demo_stream->good()) {
215 std::stringstream msg;
216 msg << "Couldn't open demo file '" << filename << "' for reading.";
217 throw std::runtime_error(msg.str());
220 Player& tux = *currentsector->player;
221 demo_controller = new CodeController();
222 tux.set_controller(demo_controller);
226 GameSession::levelintro()
230 sound_manager->stop_music();
232 DrawingContext context;
233 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
234 i != currentsector->gameobjects.end(); ++i) {
235 Background* background = dynamic_cast<Background*> (*i);
237 background->draw(context);
239 Gradient* gradient = dynamic_cast<Gradient*> (*i);
241 gradient->draw(context);
245 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
246 // CENTER_ALLIGN, LAYER_FOREGROUND1);
247 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
250 sprintf(str, "Coins: %d", player_status->coins);
251 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
252 CENTER_ALLIGN, LAYER_FOREGROUND1);
254 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
255 //TODO make author check case/blank-insensitive
256 context.draw_text(white_small_text,
257 std::string(_("contributed by ")) + level->get_author(),
258 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
261 if(best_level_statistics != NULL)
262 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
264 wait_for_event(1.0, 3.0);
268 GameSession::on_escape_press()
270 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
271 return; // don't let the player open the menu, when he is dying
273 if(mode == ST_GL_TEST) {
274 main_loop->exit_screen();
275 } else if (!Menu::current()) {
276 Menu::set_current(game_menu);
277 game_menu->set_active_item(MNID_CONTINUE);
285 GameSession::process_events()
287 Player& tux = *currentsector->player;
289 // end of pause mode?
290 if(!Menu::current() && game_pause) {
294 if (end_sequence != NO_ENDSEQUENCE) {
295 if(end_sequence_controller == 0) {
296 end_sequence_controller = new CodeController();
297 tux.set_controller(end_sequence_controller);
300 end_sequence_controller->press(Controller::RIGHT);
302 if (int(last_x_pos) == int(tux.get_pos().x))
303 end_sequence_controller->press(Controller::JUMP);
304 last_x_pos = tux.get_pos().x;
308 if(playback_demo_stream != 0) {
309 demo_controller->update();
316 playback_demo_stream->get(left);
317 playback_demo_stream->get(right);
318 playback_demo_stream->get(up);
319 playback_demo_stream->get(down);
320 playback_demo_stream->get(jump);
321 playback_demo_stream->get(action);
322 demo_controller->press(Controller::LEFT, left);
323 demo_controller->press(Controller::RIGHT, right);
324 demo_controller->press(Controller::UP, up);
325 demo_controller->press(Controller::DOWN, down);
326 demo_controller->press(Controller::JUMP, jump);
327 demo_controller->press(Controller::ACTION, action);
330 // save input for demo?
331 if(capture_demo_stream != 0) {
332 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
333 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
334 capture_demo_stream ->put(main_controller->hold(Controller::UP));
335 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
336 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
337 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
342 GameSession::consoleCommand(std::string command, std::vector<std::string>)
344 if (command == "foo") {
345 msg_info << "bar" << std::endl;
349 if (currentsector == 0) return false;
350 Player& tux = *currentsector->player;
352 // Cheating words (the goal of this is really for debugging,
353 // but could be used for some cheating, nothing wrong with that)
354 if (command == "grease") {
355 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
358 if (command == "invincible") {
359 // be invincle for the rest of the level
360 tux.invincible_timer.start(10000);
363 if (command == "mortal") {
364 // give up invincibility
365 tux.invincible_timer.stop();
368 if (command == "shrink") {
370 tux.kill(tux.SHRINK);
373 if (command == "kill") {
377 if (command == "restart") {
381 if (command == "whereami") {
382 msg_info << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << std::endl;
385 if (command == "gotoend") {
386 // goes to the end of the level
388 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
389 currentsector->camera->reset(
390 Vector(tux.get_pos().x, tux.get_pos().y));
393 if (command == "flip") {
394 FlipLevelTransformer flip_transformer;
395 flip_transformer.transform(GameSession::current()->get_current_level());
398 if (command == "finish") {
402 if (command == "camera") {
403 msg_info << "Camera is at " << Sector::current()->camera->get_translation().x << "," << Sector::current()->camera->get_translation().y << std::endl;
406 if (command == "quit") {
415 GameSession::check_end_conditions()
417 Player* tux = currentsector->player;
420 if(end_sequence && endsequence_timer.check()) {
423 } else if (!end_sequence && tux->is_dead()) {
424 if (player_status->coins < 0) {
425 // No more coins: restart level from beginning
426 player_status->coins = 0;
429 // Still has coins: restart level from last reset point
430 restart_level(false);
438 GameSession::draw(DrawingContext& context)
440 currentsector->draw(context);
448 GameSession::draw_pause(DrawingContext& context)
450 context.draw_filled_rect(
451 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
452 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
456 GameSession::process_menu()
458 Menu* menu = Menu::current();
462 if(menu == game_menu) {
463 switch (game_menu->check()) {
465 Menu::set_current(0);
467 case MNID_ABORTLEVEL:
468 Menu::set_current(0);
469 main_loop->exit_screen();
479 Menu::set_current(NULL);
482 // Eat unneeded events
484 while(SDL_PollEvent(&event))
489 GameSession::update(float elapsed_time)
494 check_end_conditions();
497 if(main_controller->pressed(Controller::PAUSE_MENU))
500 // respawning in new sector?
501 if(newsector != "" && newspawnpoint != "") {
502 Sector* sector = level->get_sector(newsector);
504 msg_warning << "Sector '" << newsector << "' not found" << std::endl;
506 sector->activate(newspawnpoint);
507 sector->play_music(LEVEL_MUSIC);
508 currentsector = sector;
513 // Update the world state and all objects in the world
516 if (end_sequence == ENDSEQUENCE_RUNNING) {
517 currentsector->update(elapsed_time/2);
518 } else if(end_sequence == NO_ENDSEQUENCE) {
519 if(!currentsector->player->growing_timer.started())
520 currentsector->update(elapsed_time);
525 sound_manager->set_listener_position(currentsector->player->get_pos());
531 if(currentsector->player->invincible_timer.started()) {
532 if(currentsector->player->invincible_timer.get_timeleft() <=
533 TUX_INVINCIBLE_TIME_WARNING) {
534 currentsector->play_music(HERRING_WARNING_MUSIC);
536 currentsector->play_music(HERRING_MUSIC);
538 } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
539 currentsector->play_music(LEVEL_MUSIC);
544 GameSession::ExitStatus
547 Menu::set_current(0);
552 // Eat unneeded events
554 while(SDL_PollEvent(&event))
559 Uint32 fps_ticks = SDL_GetTicks();
560 Uint32 fps_nextframe_ticks = SDL_GetTicks();
562 bool skipdraw = false;
564 while (exit_status == ES_NONE) {
565 // we run in a logical framerate so elapsed time is a constant
566 // This will make the game run determistic and not different on different
568 static const float elapsed_time = 1.0 / LOGICAL_FPS;
569 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
571 game_time += elapsed_time;
574 ticks = SDL_GetTicks();
575 if(ticks > fps_nextframe_ticks) {
576 if(skipdraw == true) {
577 // already skipped last frame? we have to slow down the game then...
579 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
581 // don't draw all frames when we're getting too slow
586 while(fps_nextframe_ticks > ticks) {
588 // If we really have to wait long, then do an imprecise SDL_Delay()
589 Uint32 diff = fps_nextframe_ticks - ticks;
591 SDL_Delay(diff - 10);
593 ticks = SDL_GetTicks();
596 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
601 // Update the world state and all objects in the world
605 check_end_conditions();
606 if (end_sequence == ENDSEQUENCE_RUNNING)
607 update(elapsed_time/2);
608 else if(end_sequence == NO_ENDSEQUENCE)
609 update(elapsed_time);
616 sound_manager->update();
618 /* Time stops in pause mode */
619 if(game_pause || Menu::current())
625 if (currentsector->player->invincible_timer.started() &&
626 currentsector->player->invincible_timer.get_timeleft()
627 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
629 currentsector->play_music(HERRING_MUSIC);
631 /* or just normal music? */
632 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
634 currentsector->play_music(LEVEL_MUSIC);
637 /* Calculate frames per second */
642 if(SDL_GetTicks() - fps_ticks >= 500)
644 fps_fps = (float) fps_cnt / .5;
646 fps_ticks = SDL_GetTicks();
653 main_controller->reset();
659 GameSession::finish(bool win)
662 if(WorldMap::current())
663 WorldMap::current()->finished_level(levelfile);
666 main_loop->exit_screen();
670 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
673 newspawnpoint = spawnpoint;
677 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
679 reset_sector = sector;
684 GameSession::get_working_directory()
686 return FileSystem::dirname(levelfile);
690 GameSession::display_info_box(const std::string& text)
692 InfoBox* box = new InfoBox(text);
695 DrawingContext context;
699 // TODO make a screen out of this, another mainloop is ugly
700 main_controller->update();
702 while (SDL_PollEvent(&event)) {
703 main_controller->process_event(event);
704 if(event.type == SDL_QUIT)
708 if(main_controller->pressed(Controller::JUMP)
709 || main_controller->pressed(Controller::ACTION)
710 || main_controller->pressed(Controller::PAUSE_MENU)
711 || main_controller->pressed(Controller::MENU_SELECT))
713 else if(main_controller->pressed(Controller::DOWN))
715 else if(main_controller->pressed(Controller::UP))
719 context.do_drawing();
720 sound_manager->update();
727 GameSession::start_sequence(const std::string& sequencename)
729 if(sequencename == "endsequence" || sequencename == "fireworks") {
733 end_sequence = ENDSEQUENCE_RUNNING;
734 endsequence_timer.start(7.3);
736 sound_manager->play_music("music/leveldone.ogg", false);
737 currentsector->player->invincible_timer.start(7.3);
740 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
741 i != currentsector->gameobjects.end(); ++i)
743 GameObject* obj = *i;
745 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
750 // add time spent to statistics
751 int tottime = 0, remtime = 0;
752 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
756 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
757 j != sec->gameobjects.end(); ++j)
759 GameObject* obj = *j;
761 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
764 tottime += int(lt->get_level_time());
765 remtime += int(lt->get_remaining_time());
769 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
771 if(sequencename == "fireworks") {
772 currentsector->add_object(new Fireworks());
774 } else if(sequencename == "stoptux") {
776 msg_warning << "Final target reached without an active end sequence" << std::endl;
777 this->start_sequence("endsequence");
779 end_sequence = ENDSEQUENCE_WAITING;
781 msg_warning << "Unknown sequence '" << sequencename << "'" << std::endl;
787 GameSession::drawstatus(DrawingContext& context)
789 player_status->draw(context);
791 if(config->show_fps) {
793 snprintf(str, sizeof(str), "%3.1f", fps_fps);
794 const char* fpstext = "FPS";
795 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);
796 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);
799 // draw level stats while end_sequence is running
801 global_stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());