Reset play_time when level is restarted
[supertux.git] / src / game_session.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
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.
10 //
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.
15 //
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.
19 #include <config.h>
20
21 #include <fstream>
22 #include <sstream>
23 #include <assert.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <stdexcept>
32
33 #include <SDL.h>
34
35 #include "game_session.hpp"
36 #include "log.hpp"
37 #include "console.hpp"
38 #include "worldmap/worldmap.hpp"
39 #include "mainloop.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
42 #include "sector.hpp"
43 #include "level.hpp"
44 #include "tile.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"
56 #include "statistics.hpp"
57 #include "timer.hpp"
58 #include "options_menu.hpp"
59 #include "textscroller.hpp"
60 #include "control/codecontroller.hpp"
61 #include "control/joystickkeyboardcontroller.hpp"
62 #include "main.hpp"
63 #include "file_system.hpp"
64 #include "gameconfig.hpp"
65 #include "gettext.hpp"
66 #include "console.hpp"
67 #include "flip_level_transformer.hpp"
68 #include "trigger/secretarea_trigger.hpp"
69 #include "trigger/sequence_trigger.hpp"
70 #include "random_generator.hpp"
71 #include "scripting/squirrel_util.hpp"
72 #include "object/endsequence_walkright.hpp"
73 #include "object/endsequence_walkleft.hpp"
74 #include "object/endsequence_fireworks.hpp"
75 #include "direction.hpp"
76 #include "scripting/time_scheduler.hpp"
77
78 // the engine will be run with a logical framerate of 64fps.
79 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
80 // binary fraction...
81 static const float LOGICAL_FPS = 64.0;
82
83 enum GameMenuIDs {
84   MNID_CONTINUE,
85   MNID_ABORTLEVEL
86 };
87
88 GameSession* GameSession::current_ = NULL;
89
90 GameSession::GameSession(const std::string& levelfile_, Statistics* statistics)
91   : level(0), currentsector(0),
92     end_sequence(0),
93     levelfile(levelfile_), best_level_statistics(statistics),
94     capture_demo_stream(0), playback_demo_stream(0), demo_controller(0),
95     play_time(0), edit_mode(false)
96 {
97   current_ = this;
98   currentsector = NULL;
99
100   game_pause = false;
101   speed_before_pause = main_loop->get_speed();
102
103   statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
104
105   restart_level();
106
107   game_menu.reset(new Menu());
108   game_menu->add_label(_("Pause"));
109   game_menu->add_hl();
110   game_menu->add_entry(MNID_CONTINUE, _("Continue"));
111   game_menu->add_submenu(_("Options"), get_options_menu());
112   game_menu->add_hl();
113   game_menu->add_entry(MNID_ABORTLEVEL, _("Abort Level"));
114 }
115
116 void
117 GameSession::restart_level()
118 {
119
120   if (edit_mode) {
121     force_ghost_mode();
122     return;
123   }
124
125   game_pause   = false;
126   end_sequence = 0;
127
128   main_controller->reset();
129
130   currentsector = 0;
131
132   level.reset(new Level);
133   level->load(levelfile);
134   level->stats.total_coins = level->get_total_coins();
135   level->stats.total_badguys = level->get_total_badguys();
136   level->stats.total_secrets = level->get_total_count<SecretAreaTrigger>();
137   level->stats.reset();
138
139   if(reset_sector != "") {
140     currentsector = level->get_sector(reset_sector);
141     if(!currentsector) {
142       std::stringstream msg;
143       msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
144       throw std::runtime_error(msg.str());
145     }
146     level->stats.declare_invalid();
147     currentsector->activate(reset_pos);
148   } else {
149     currentsector = level->get_sector("main");
150     if(!currentsector)
151       throw std::runtime_error("Couldn't find main sector");
152     play_time = 0;
153     currentsector->activate("main");
154   }
155
156   //levelintro();
157
158   sound_manager->stop_music();
159   currentsector->play_music(LEVEL_MUSIC);
160
161   if(capture_file != "") {
162     int newSeed=0;               // next run uses a new seed
163     while (newSeed == 0)            // which is the next non-zero random num.
164         newSeed = systemRandom.rand();
165     config->random_seed = systemRandom.srand(newSeed);
166     log_info << "Next run uses random seed " <<config->random_seed <<std::endl;
167     record_demo(capture_file);
168   }
169 }
170
171 GameSession::~GameSession()
172 {
173   delete capture_demo_stream;
174   delete playback_demo_stream;
175   delete demo_controller;
176   free_options_menu();
177
178   current_ = NULL;
179 }
180
181 void
182 GameSession::record_demo(const std::string& filename)
183 {
184   delete capture_demo_stream;
185
186   capture_demo_stream = new std::ofstream(filename.c_str());
187   if(!capture_demo_stream->good()) {
188     std::stringstream msg;
189     msg << "Couldn't open demo file '" << filename << "' for writing.";
190     throw std::runtime_error(msg.str());
191   }
192   capture_file = filename;
193
194   char buf[30];                            // save the seed in the demo file
195   snprintf(buf, sizeof(buf), "random_seed=%10d", config->random_seed);
196   for (int i=0; i==0 || buf[i-1]; i++)
197     capture_demo_stream->put(buf[i]);
198 }
199
200 int
201 GameSession::get_demo_random_seed(const std::string& filename)
202 {
203   std::istream* test_stream = new std::ifstream(filename.c_str());
204   if(test_stream->good()) {
205     char buf[30];                     // recall the seed from the demo file
206     int seed;
207     for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
208       test_stream->get(buf[i]);
209     if (sscanf(buf, "random_seed=%10d", &seed) == 1) {
210       log_info << "Random seed " << seed << " from demo file" << std::endl;
211          return seed;
212     }
213     else
214       log_info << "Demo file contains no random number" << std::endl;
215   }
216   return 0;
217 }
218
219 void
220 GameSession::play_demo(const std::string& filename)
221 {
222   delete playback_demo_stream;
223   delete demo_controller;
224
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());
230   }
231
232   Player& tux = *currentsector->player;
233   demo_controller = new CodeController();
234   tux.set_controller(demo_controller);
235
236   // skip over random seed, if it exists in the file
237   char buf[30];                            // ascii decimal seed
238   int seed;
239   for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
240     playback_demo_stream->get(buf[i]);
241   if (sscanf(buf, "random_seed=%010d", &seed) != 1)
242     playback_demo_stream->seekg(0);     // old style w/o seed, restart at beg
243 }
244
245 void
246 GameSession::levelintro()
247 {
248   sound_manager->stop_music();
249
250   DrawingContext context;
251   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
252       i != currentsector->gameobjects.end(); ++i) {
253     Background* background = dynamic_cast<Background*> (*i);
254     if(background) {
255       background->draw(context);
256     }
257     Gradient* gradient = dynamic_cast<Gradient*> (*i);
258     if(gradient) {
259       gradient->draw(context);
260     }
261   }
262
263 //  context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
264 //      ALIGN_CENTER, LAYER_FOREGROUND1);
265   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
266       LAYER_FOREGROUND1);
267
268   std::stringstream ss_coins;
269   ss_coins << _("Coins") << ": " << player_status->coins;
270   context.draw_text(white_text, ss_coins.str(), Vector(SCREEN_WIDTH/2, 210),
271       ALIGN_CENTER, LAYER_FOREGROUND1);
272
273   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
274     context.draw_text(white_small_text,
275       std::string(_("contributed by ")) + level->get_author(),
276       Vector(SCREEN_WIDTH/2, 350), ALIGN_CENTER, LAYER_FOREGROUND1);
277
278   if(best_level_statistics != NULL)
279     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
280
281   wait_for_event(1.0, 3.0);
282 }
283
284 void
285 GameSession::on_escape_press()
286 {
287   if(currentsector->player->is_dying() || end_sequence)
288   {
289     // Let the timers run out, we fast-forward them to force past a sequence
290     if (end_sequence)
291       end_sequence->stop();
292
293     currentsector->player->dying_timer.start(FLT_EPSILON);
294     return;   // don't let the player open the menu, when he is dying
295   }
296
297   if(level->on_menukey_script != "") {
298     std::istringstream in(level->on_menukey_script);
299     run_script(in, "OnMenuKeyScript");
300   } else {
301     toggle_pause();
302   }
303 }
304
305 void
306 GameSession::toggle_pause()
307 {
308   if(!game_pause) {
309     speed_before_pause = main_loop->get_speed();
310     main_loop->set_speed(0);
311     Menu::set_current(game_menu.get());
312     game_menu->set_active_item(MNID_CONTINUE);
313     game_pause = true;
314   } else {
315     main_loop->set_speed(speed_before_pause);
316     Menu::set_current(NULL);
317     game_pause = false;
318   }
319 }
320
321 void
322 GameSession::set_editmode(bool edit_mode)
323 {
324   if (this->edit_mode == edit_mode) return;
325   this->edit_mode = edit_mode;
326
327   currentsector->get_players()[0]->set_edit_mode(edit_mode);
328
329   if (edit_mode) {
330
331     // entering edit mode
332
333   } else {
334
335     // leaving edit mode
336     restart_level();
337
338   }
339 }
340
341 void
342 GameSession::force_ghost_mode()
343 {
344   currentsector->get_players()[0]->set_ghost_mode(true);
345 }
346
347 HSQUIRRELVM
348 GameSession::run_script(std::istream& in, const std::string& sourcename)
349 {
350   using namespace Scripting;
351
352   // garbage collect thread list
353   for(ScriptList::iterator i = scripts.begin();
354       i != scripts.end(); ) {
355     HSQOBJECT& object = *i;
356     HSQUIRRELVM vm = object_to_vm(object);
357
358     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
359       sq_release(global_vm, &object);
360       i = scripts.erase(i);
361       continue;
362     }
363
364     ++i;
365   }
366
367   HSQOBJECT object = create_thread(global_vm);
368   scripts.push_back(object);
369
370   HSQUIRRELVM vm = object_to_vm(object);
371
372   compile_and_run(vm, in, sourcename);
373
374   return vm;
375 }
376
377 void
378 GameSession::process_events()
379 {
380   // end of pause mode?
381   if(!Menu::current() && game_pause) {
382     game_pause = false;
383   }
384
385   // playback a demo?
386   if(playback_demo_stream != 0) {
387     demo_controller->update();
388     char left = false;
389     char right = false;
390     char up = false;
391     char down = false;
392     char jump = false;
393     char action = false;
394     playback_demo_stream->get(left);
395     playback_demo_stream->get(right);
396     playback_demo_stream->get(up);
397     playback_demo_stream->get(down);
398     playback_demo_stream->get(jump);
399     playback_demo_stream->get(action);
400     demo_controller->press(Controller::LEFT, left);
401     demo_controller->press(Controller::RIGHT, right);
402     demo_controller->press(Controller::UP, up);
403     demo_controller->press(Controller::DOWN, down);
404     demo_controller->press(Controller::JUMP, jump);
405     demo_controller->press(Controller::ACTION, action);
406   }
407
408   // save input for demo?
409   if(capture_demo_stream != 0) {
410     capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
411     capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
412     capture_demo_stream ->put(main_controller->hold(Controller::UP));
413     capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
414     capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
415     capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
416   }
417 }
418
419 void
420 GameSession::check_end_conditions()
421 {
422   Player* tux = currentsector->player;
423
424   /* End of level? */
425   if(end_sequence && end_sequence->is_done()) {
426     finish(true);
427   } else if (!end_sequence && tux->is_dead()) {
428     restart_level();
429   }
430 }
431
432 void
433 GameSession::draw(DrawingContext& context)
434 {
435   currentsector->draw(context);
436   drawstatus(context);
437
438   if(game_pause)
439     draw_pause(context);
440 }
441
442 void
443 GameSession::draw_pause(DrawingContext& context)
444 {
445   context.draw_filled_rect(
446       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
447       Color(.2f, .2f, .2f, .5f), LAYER_FOREGROUND1);
448 }
449
450 void
451 GameSession::process_menu()
452 {
453   Menu* menu = Menu::current();
454   if(menu) {
455     menu->update();
456
457     if(menu == game_menu.get()) {
458       switch (game_menu->check()) {
459         case MNID_CONTINUE:
460           Menu::set_current(0);
461           toggle_pause();
462           break;
463         case MNID_ABORTLEVEL:
464           Menu::set_current(0);
465           main_loop->exit_screen();
466           break;
467       }
468     }
469   }
470 }
471
472 void
473 GameSession::setup()
474 {
475   Menu::set_current(NULL);
476   current_ = this;
477
478   if(currentsector != Sector::current()) {
479         currentsector->activate(currentsector->player->get_pos());
480   }
481   currentsector->play_music(LEVEL_MUSIC);
482
483   // Eat unneeded events
484   SDL_Event event;
485   while(SDL_PollEvent(&event))
486   {}
487 }
488
489 void
490 GameSession::update(float elapsed_time)
491 {
492   // handle controller
493   if(main_controller->pressed(Controller::PAUSE_MENU))
494     on_escape_press();
495
496   process_events();
497   process_menu();
498
499   check_end_conditions();
500
501   // respawning in new sector?
502   if(newsector != "" && newspawnpoint != "") {
503     Sector* sector = level->get_sector(newsector);
504     if(sector == 0) {
505       log_warning << "Sector '" << newsector << "' not found" << std::endl;
506     }
507     sector->activate(newspawnpoint);
508     sector->play_music(LEVEL_MUSIC);
509     currentsector = sector;
510     newsector = "";
511     newspawnpoint = "";
512   }
513
514   // Update the world state and all objects in the world
515   if(!game_pause) {
516     // Update the world
517     if (!end_sequence) {
518       play_time += elapsed_time; //TODO: make sure we don't count cutscene time
519       level->stats.time = play_time;
520       currentsector->update(elapsed_time);
521     } else {
522       if (!end_sequence->is_tux_stopped()) {
523         currentsector->update(elapsed_time);
524       } else {
525         end_sequence->update(elapsed_time);
526       }
527     }
528   }
529
530   // update sounds
531   sound_manager->set_listener_position(currentsector->player->get_pos());
532
533   /* Handle music: */
534   if (end_sequence)
535     return;
536
537   if(currentsector->player->invincible_timer.started()) {
538     if(currentsector->player->invincible_timer.get_timeleft() <=
539        TUX_INVINCIBLE_TIME_WARNING) {
540       currentsector->play_music(HERRING_WARNING_MUSIC);
541     } else {
542       currentsector->play_music(HERRING_MUSIC);
543     }
544   } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
545     currentsector->play_music(LEVEL_MUSIC);
546   }
547 }
548
549 void
550 GameSession::finish(bool win)
551 {
552   using namespace WorldMapNS;
553
554   if (edit_mode) {
555     force_ghost_mode();
556     return;
557   }
558
559   if(win) {
560     if(WorldMap::current())
561       WorldMap::current()->finished_level(level.get());
562   }
563
564   main_loop->exit_screen();
565 }
566
567 void
568 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
569 {
570   newsector = sector;
571   newspawnpoint = spawnpoint;
572 }
573
574 void
575 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
576 {
577   reset_sector = sector;
578   reset_pos = pos;
579 }
580
581 std::string
582 GameSession::get_working_directory()
583 {
584   return FileSystem::dirname(levelfile);
585 }
586
587 void
588 GameSession::start_sequence(const std::string& sequencename)
589 {
590   // do not play sequences when in edit mode
591   if (edit_mode) {
592     force_ghost_mode();
593     return;
594   }
595
596   // handle special "stoptux" sequence
597   if (sequencename == "stoptux") {
598     if (!end_sequence) {
599       log_warning << "Final target reached without an active end sequence" << std::endl;
600       this->start_sequence("endsequence");
601     }
602     if (end_sequence) end_sequence->stop_tux();
603     return;
604   }
605
606   // abort if a sequence is already playing
607   if (end_sequence)
608           return;
609
610   if (sequencename == "endsequence") {
611     if (currentsector->get_players()[0]->physic.get_velocity_x() < 0) {
612       end_sequence = new EndSequenceWalkLeft();
613     } else {
614       end_sequence = new EndSequenceWalkRight();
615     }
616   } else if (sequencename == "fireworks") {
617     end_sequence = new EndSequenceFireworks();
618   } else {
619     log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
620     return;
621   }
622
623   /* slow down the game for end-sequence */
624   main_loop->set_speed(0.5f);
625
626   currentsector->add_object(end_sequence);
627   end_sequence->start();
628
629   sound_manager->play_music("music/leveldone.ogg", false);
630   currentsector->player->invincible_timer.start(10000.0f);
631
632   // Stop all clocks.
633   for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
634                   i != currentsector->gameobjects.end(); ++i)
635   {
636     GameObject* obj = *i;
637
638     LevelTime* lt = dynamic_cast<LevelTime*> (obj);
639     if(lt)
640       lt->stop();
641   }
642 }
643
644 /* (Status): */
645 void
646 GameSession::drawstatus(DrawingContext& context)
647 {
648   player_status->draw(context);
649
650   // draw level stats while end_sequence is running
651   if (end_sequence) {
652     level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
653   }
654 }