move over rewritten lispreader from tuxkart (with additional fixes), generalized...
[supertux.git] / src / gameloop.cpp
1 //  $Id$
2 // 
3 //  SuperTux
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>
7 //
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.
12 //
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.
17 // 
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.
21 #include <config.h>
22
23 #include <iostream>
24 #include <sstream>
25 #include <cassert>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <cmath>
29 #include <cstring>
30 #include <cerrno>
31 #include <unistd.h>
32 #include <ctime>
33 #include <stdexcept>
34
35 #include "SDL.h"
36
37 #ifndef WIN32
38 #include <sys/types.h>
39 #include <ctype.h>
40 #endif
41
42 #include "defines.h"
43 #include "app/globals.h"
44 #include "gameloop.h"
45 #include "video/screen.h"
46 #include "app/setup.h"
47 #include "gui/menu.h"
48 #include "sector.h"
49 #include "level.h"
50 #include "scene.h"
51 #include "tile.h"
52 #include "object/particlesystem.h"
53 #include "object/background.h"
54 #include "object/tilemap.h"
55 #include "object/camera.h"
56 #include "object/player.h"
57 #include "lisp/lisp.h"
58 #include "lisp/parser.h"
59 #include "resources.h"
60 #include "app/gettext.h"
61 #include "worldmap.h"
62 #include "intro.h"
63 #include "misc.h"
64 #include "statistics.h"
65 #include "timer.h"
66 #include "object/fireworks.h"
67
68 GameSession* GameSession::current_ = 0;
69
70 bool compare_last(std::string& haystack, std::string needle)
71 {
72   int haystack_size = haystack.size();
73   int needle_size = needle.size();
74
75   if(haystack_size < needle_size)
76     return false;
77
78   if(haystack.compare(haystack_size-needle_size, needle_size, needle) == 0)
79     return true;
80   return false;
81 }
82
83 GameSession::GameSession(const std::string& levelfile_, int mode,
84     Statistics* statistics)
85   : level(0), currentsector(0), st_gl_mode(mode),
86     end_sequence(NO_ENDSEQUENCE), levelfile(levelfile_),
87     best_level_statistics(statistics)
88 {
89   current_ = this;
90   
91   game_pause = false;
92   fps_fps = 0;
93
94   context = new DrawingContext();
95
96   last_swap_point = Vector(-1, -1);
97   last_swap_stats.reset();
98
99   restart_level();
100 }
101
102 void
103 GameSession::restart_level()
104 {
105   game_pause   = false;
106   exit_status  = ES_NONE;
107   end_sequence = NO_ENDSEQUENCE;
108
109   last_keys.clear();
110
111 #if 0
112   Vector tux_pos = Vector(-1,-1);
113   if (currentsector)
114     { 
115       // Tux has lost a life, so we try to respawn him at the nearest reset point
116       tux_pos = currentsector->player->base;
117     }
118 #endif
119   
120   delete level;
121   currentsector = 0;
122
123   level = new Level;
124   level->load(levelfile);
125
126   global_stats.reset();
127   global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
128   global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
129   global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
130
131   currentsector = level->get_sector("main");
132   if(!currentsector)
133     Termination::abort("Level has no main sector.", "");
134   currentsector->activate("main");
135
136 #if 0
137   // Set Tux to the nearest reset point
138   if(tux_pos.x != -1)
139     {
140     tux_pos = currentsector->get_best_spawn_point(tux_pos);
141
142     if(last_swap_point.x > tux_pos.x)
143       tux_pos = last_swap_point;
144     else  // new swap point
145       {
146       last_swap_point = tux_pos;
147
148       last_swap_stats += global_stats;
149       }
150
151     currentsector->player->base.x = tux_pos.x;
152     currentsector->player->base.y = tux_pos.y;
153
154     // has to reset camera on swapping
155     currentsector->camera->reset(Vector(currentsector->player->base.x,
156                                         currentsector->player->base.y));
157     }
158 #endif
159
160   if (st_gl_mode != ST_GL_DEMO_GAME)
161     {
162       if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
163         levelintro();
164     }
165
166   start_timers();
167   currentsector->play_music(LEVEL_MUSIC);
168 }
169
170 GameSession::~GameSession()
171 {
172   delete level;
173   delete context;
174 }
175
176 void
177 GameSession::levelintro(void)
178 {
179   SoundManager::get()->halt_music();
180   
181   char str[60];
182
183   DrawingContext context;
184   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
185       i != currentsector->gameobjects.end(); ++i) {
186     Background* background = dynamic_cast<Background*> (*i);
187     if(background) {
188       background->draw(context);
189     }
190   }
191
192 //  context.draw_text(gold_text, level->get_name(), Vector(screen->w/2, 160),
193 //      CENTER_ALLIGN, LAYER_FOREGROUND1);
194   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
195       LAYER_FOREGROUND1);
196
197   sprintf(str, "TUX x %d", player_status.lives);
198   context.draw_text(white_text, str, Vector(screen->w/2, 210),
199       CENTER_ALLIGN, LAYER_FOREGROUND1);
200
201   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
202     //TODO make author check case/blank-insensitive
203     context.draw_text(white_small_text,
204       std::string(_("contributed by ")) + level->get_author(), 
205       Vector(screen->w/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
206
207
208   if(best_level_statistics != NULL)
209     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
210
211   context.do_drawing();
212
213   SDL_Event event;
214   wait_for_event(event,1000,3000,true);
215 }
216
217 /* Reset Timers */
218 void
219 GameSession::start_timers()
220 {
221   time_left.start(level->timelimit);
222   Ticks::pause_init();
223 }
224
225 void
226 GameSession::on_escape_press()
227 {
228   if(currentsector->player->dying || end_sequence != NO_ENDSEQUENCE)
229     return;   // don't let the player open the menu, when he is dying
230   
231   if(game_pause)
232     return;
233
234   if(st_gl_mode == ST_GL_TEST)
235     {
236       exit_status = ES_LEVEL_ABORT;
237     }
238   else if (!Menu::current())
239     {
240       /* Tell Tux that the keys are all down, otherwise
241         it could have nasty bugs, like going allways to the right
242         or whatever that key does */
243       Player& tux = *(currentsector->player);
244       tux.key_event((SDLKey)keymap.up, UP);
245       tux.key_event((SDLKey)keymap.down, UP);
246       tux.key_event((SDLKey)keymap.left, UP);
247       tux.key_event((SDLKey)keymap.right, UP);
248       tux.key_event((SDLKey)keymap.jump, UP);
249       tux.key_event((SDLKey)keymap.power, UP);
250
251       Menu::set_current(game_menu);
252       Ticks::pause_start();
253     }
254 }
255
256 void
257 GameSession::process_events()
258 {
259   if (end_sequence != NO_ENDSEQUENCE)
260     {
261       Player& tux = *currentsector->player;
262          
263       tux.input.fire  = UP;
264       tux.input.left  = UP;
265       tux.input.right = DOWN;
266       tux.input.down  = UP; 
267
268       if (int(last_x_pos) == int(tux.get_pos().x))
269         tux.input.up    = DOWN; 
270       else
271         tux.input.up    = UP; 
272
273       last_x_pos = tux.get_pos().x;
274
275       SDL_Event event;
276       while (SDL_PollEvent(&event))
277         {
278           /* Check for menu-events, if the menu is shown */
279           if (Menu::current())
280             {
281               Menu::current()->event(event);
282               if(!Menu::current())
283               Ticks::pause_stop();
284             }
285
286           switch(event.type)
287             {
288             case SDL_QUIT:        /* Quit event - quit: */
289               Termination::abort("Received window close", "");
290               break;
291               
292             case SDL_KEYDOWN:     /* A keypress! */
293               {
294                 SDLKey key = event.key.keysym.sym;
295            
296                 switch(key)
297                   {
298                   case SDLK_ESCAPE:    /* Escape: Open/Close the menu: */
299                     on_escape_press();
300                     break;
301                   default:
302                     break;
303                   }
304               }
305           
306             case SDL_JOYBUTTONDOWN:
307               if (event.jbutton.button == joystick_keymap.start_button)
308                 on_escape_press();
309               break;
310             }
311         }
312     }
313   else // normal mode
314     {
315       if(!Menu::current() && !game_pause)
316         Ticks::pause_stop();
317
318       SDL_Event event;
319       while (SDL_PollEvent(&event))
320         {
321           /* Check for menu-events, if the menu is shown */
322           if (Menu::current())
323             {
324               Menu::current()->event(event);
325               if(!Menu::current())
326                 Ticks::pause_stop();
327             }
328           else
329             {
330               Player& tux = *currentsector->player;
331   
332               switch(event.type)
333                 {
334                 case SDL_QUIT:        /* Quit event - quit: */
335                   Termination::abort("Received window close", "");
336                   break;
337
338                 case SDL_KEYDOWN:     /* A keypress! */
339                   {
340                     SDLKey key = event.key.keysym.sym;
341             
342                     if(tux.key_event(key,DOWN))
343                       break;
344
345                     switch(key)
346                       {
347                       case SDLK_ESCAPE:    /* Escape: Open/Close the menu: */
348                         on_escape_press();
349                         break;
350                       default:
351                         break;
352                       }
353                   }
354                   break;
355                 case SDL_KEYUP:      /* A keyrelease! */
356                   {
357                     SDLKey key = event.key.keysym.sym;
358
359                     if(tux.key_event(key, UP))
360                       break;
361
362                     switch(key)
363                       {
364                       case SDLK_a:
365                         if(debug_mode)
366                         {
367                           char buf[160];
368                           snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
369                               tux.get_pos().x, tux.get_pos().y);
370                           context->draw_text(white_text, buf,
371                               Vector(0, screen->h - white_text->get_height()),
372                               LEFT_ALLIGN, LAYER_FOREGROUND1);
373                           context->do_drawing();
374                           SDL_Delay(1000);
375                         }
376                         break;
377                       case SDLK_p:
378                         if(!Menu::current())
379                           {
380                           // "lifeup" cheat activates pause cause of the 'p'
381                           // so work around to ignore it
382                             if(compare_last(last_keys, "lifeu"))
383                               break;
384
385                             if(game_pause)
386                               {
387                                 game_pause = false;
388                                 Ticks::pause_stop();
389                               }
390                             else
391                               {
392                                 game_pause = true;
393                                 Ticks::pause_start();
394                               }
395                           }
396                         break;
397                       default:
398                         break;
399                       }
400                   }
401
402                         /* Check if chacrater is ASCII */
403                         char ch[2];
404                         if((event.key.keysym.unicode & 0xFF80) == 0)
405                           {
406                           ch[0] = event.key.keysym.unicode & 0x7F;
407                           ch[1] = '\0';
408                           }
409                         last_keys.append(ch);  // add to cheat keys
410
411                         // Cheating words (the goal of this is really for debugging,
412                         // but could be used for some cheating, nothing wrong with that)
413                         if(compare_last(last_keys, "grow"))
414                           {
415                           tux.grow(false);
416                           last_keys.clear();
417                           }
418                         if(compare_last(last_keys, "fire"))
419                           {
420                           tux.grow(false);
421                           tux.got_power = tux.FIRE_POWER;
422                           last_keys.clear();
423                           }
424                         if(compare_last(last_keys, "ice"))
425                           {
426                           tux.grow(false);
427                           tux.got_power = tux.ICE_POWER;
428                           last_keys.clear();
429                           }
430                         if(compare_last(last_keys, "lifeup"))
431                           {
432                           player_status.lives++;
433                           last_keys.clear();
434                           }
435                         if(compare_last(last_keys, "lifedown"))
436                           {
437                           player_status.lives--;
438                           last_keys.clear();
439                           }
440                         if(compare_last(last_keys, "grease"))
441                           {
442                           tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
443                           last_keys.clear();
444                           }
445                         if(compare_last(last_keys, "invincible"))
446                           {    // be invincle for the rest of the level
447                           tux.invincible_timer.start(10000);
448                           last_keys.clear();
449                           }
450                         if(compare_last(last_keys, "shrink"))
451                           {    // remove powerups
452                           tux.kill(tux.SHRINK);
453                           last_keys.clear();
454                           }
455                         if(compare_last(last_keys, "kill"))
456                           {    // kill Tux, but without losing a life
457                           player_status.lives++;
458                           tux.kill(tux.KILL);
459                           last_keys.clear();
460                           }
461                         if(compare_last(last_keys, "grid"))
462                           {    // toggle debug grid
463                           debug_grid = !debug_grid;
464                           last_keys.clear();
465                           }
466                         if(compare_last(last_keys, "hover"))
467                           {    // toggle hover ability on/off
468                           tux.enable_hover = !tux.enable_hover;
469                           last_keys.clear();
470                           }
471                         if(compare_last(last_keys, "gotoend"))
472                           {    // goes to the end of the level
473                           tux.move(Vector(
474                               (currentsector->solids->get_width()*32) 
475                                 - (screen->w*2),
476                                 0));
477                           currentsector->camera->reset(
478                               Vector(tux.get_pos().x, tux.get_pos().y));
479                           last_keys.clear();
480                           }
481                         // temporary to help player's choosing a flapping
482                         if(compare_last(last_keys, "marek"))
483                           {
484                           tux.flapping_mode = Player::MAREK_FLAP;
485                           last_keys.clear();
486                           }
487                         if(compare_last(last_keys, "ricardo"))
488                           {
489                           tux.flapping_mode = Player::RICARDO_FLAP;
490                           last_keys.clear();
491                           }
492                         if(compare_last(last_keys, "ryan"))
493                           {
494                           tux.flapping_mode = Player::RYAN_FLAP;
495                           last_keys.clear();
496                           }
497                   break;
498
499                 case SDL_JOYAXISMOTION:
500                   if (event.jaxis.axis == joystick_keymap.x_axis)
501                     {
502                       if (event.jaxis.value < -joystick_keymap.dead_zone)
503                         {
504                           tux.input.left  = DOWN;
505                           tux.input.right = UP;
506                         }
507                       else if (event.jaxis.value > joystick_keymap.dead_zone)
508                         {
509                           tux.input.left  = UP;
510                           tux.input.right = DOWN;
511                         }
512                       else
513                         {
514                           tux.input.left  = DOWN;
515                           tux.input.right = DOWN;
516                         }
517                     }
518                   else if (event.jaxis.axis == joystick_keymap.y_axis)
519                     {
520                       if (event.jaxis.value > joystick_keymap.dead_zone)
521                         {
522                         tux.input.up = DOWN;
523                         tux.input.down = UP;
524                         }
525                       else if (event.jaxis.value < -joystick_keymap.dead_zone)
526                         {
527                         tux.input.up = UP;
528                         tux.input.down = DOWN;
529                         }
530                       else
531                         {
532                         tux.input.up = DOWN;
533                         tux.input.down = DOWN;
534                         }
535                     }
536                   break;
537
538                 case SDL_JOYHATMOTION:
539                   if(event.jhat.value & SDL_HAT_UP) {
540                     tux.input.up = DOWN;
541                     tux.input.down = UP;
542                   } else if(event.jhat.value & SDL_HAT_DOWN) {
543                     tux.input.up = UP;
544                     tux.input.down = DOWN;
545                   } else if(event.jhat.value & SDL_HAT_LEFT) {
546                     tux.input.left = DOWN;
547                     tux.input.right = UP;
548                   } else if(event.jhat.value & SDL_HAT_RIGHT) {
549                     tux.input.left = UP;
550                     tux.input.right = DOWN;
551                   } else if(event.jhat.value == SDL_HAT_CENTERED) {
552                     tux.input.left = UP;
553                     tux.input.right = UP;
554                     tux.input.up = UP;
555                     tux.input.down = UP;
556                   }
557                   break;
558             
559                 case SDL_JOYBUTTONDOWN:
560                   if (event.jbutton.button == joystick_keymap.a_button)
561                     tux.input.jump = DOWN;
562                   else if (event.jbutton.button == joystick_keymap.b_button)
563                     tux.input.fire = DOWN;
564                   else if (event.jbutton.button == joystick_keymap.start_button)
565                     on_escape_press();
566                   break;
567                 case SDL_JOYBUTTONUP:
568                   if (event.jbutton.button == joystick_keymap.a_button)
569                     tux.input.jump = UP;
570                   else if (event.jbutton.button == joystick_keymap.b_button)
571                     tux.input.fire = UP;
572                   break;
573
574                 default:
575                   break;
576                 }  /* switch */
577             }
578         } /* while */
579     }
580 }
581
582 void
583 GameSession::check_end_conditions()
584 {
585   Player* tux = currentsector->player;
586
587   /* End of level? */
588   if(end_sequence && endsequence_timer.check()) {
589       exit_status = ES_LEVEL_FINISHED;
590       global_stats += last_swap_stats;  // add swap points stats
591       return;
592   } else if (!end_sequence && tux->is_dead()) {
593     player_status.bonus = PlayerStatus::NO_BONUS;
594
595     if (player_status.lives < 0) { // No more lives!?
596       exit_status = ES_GAME_OVER;
597     } else { // Still has lives, so reset Tux to the levelstart
598       restart_level();
599     }
600     
601     return;
602   }
603 }
604
605 void
606 GameSession::action(float elapsed_time)
607 {
608   // advance timers
609   if (exit_status == ES_NONE && !currentsector->player->growing_timer.check())
610     {
611       // Update Tux and the World
612       currentsector->action(elapsed_time);
613     }
614
615   // respawning in new sector?
616   if(newsector != "" && newspawnpoint != "") {
617     Sector* sector = level->get_sector(newsector);
618     currentsector = sector;
619     currentsector->activate(newspawnpoint);
620     currentsector->play_music(LEVEL_MUSIC);
621     newsector = newspawnpoint = "";
622   }
623 }
624
625 void 
626 GameSession::draw()
627 {
628   currentsector->draw(*context);
629   drawstatus(*context);
630
631   if(game_pause)
632     {
633       int x = screen->h / 20;
634       for(int i = 0; i < x; ++i)
635         {
636           context->draw_filled_rect(
637               Vector(i % 2 ? (pause_menu_frame * i)%screen->w :
638                 -((pause_menu_frame * i)%screen->w)
639                 ,(i*20+pause_menu_frame)%screen->h),
640               Vector(screen->w,10),
641               Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
642         }
643       context->draw_filled_rect(
644           Vector(0,0), Vector(screen->w, screen->h),
645           Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
646       context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
647           Vector(screen->w/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
648
649       char str1[60];
650       char str2[124];
651       sprintf(str1, _("Playing: "));
652       sprintf(str2, level->name.c_str());
653
654       context->draw_text(blue_text, str1,
655           Vector((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
656           LEFT_ALLIGN, LAYER_FOREGROUND1+2);
657       context->draw_text(white_text, str2,
658           Vector(((screen->w - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
659           LEFT_ALLIGN, LAYER_FOREGROUND1+2);
660     }
661
662   if(Menu::current())
663     {
664       Menu::current()->draw(*context);
665       mouse_cursor->draw(*context);
666     }
667
668   context->do_drawing();
669 }
670
671 void
672 GameSession::process_menu()
673 {
674   Menu* menu = Menu::current();
675   if(menu)
676     {
677       menu->action();
678
679       if(menu == game_menu)
680         {
681           switch (game_menu->check())
682             {
683             case MNID_CONTINUE:
684               Ticks::pause_stop();
685               break;
686             case MNID_ABORTLEVEL:
687               Ticks::pause_stop();
688               exit_status = ES_LEVEL_ABORT;
689               break;
690             }
691         }
692       else if(menu == options_menu)
693         {
694           process_options_menu();
695         }
696       else if(menu == load_game_menu )
697         {
698           process_load_game_menu();
699         }
700     }
701 }
702
703 GameSession::ExitStatus
704 GameSession::run()
705 {
706   Menu::set_current(0);
707   current_ = this;
708   
709   int fps_cnt = 0;
710
711   // Eat unneeded events
712   SDL_Event event;
713   while(SDL_PollEvent(&event))
714   {}
715
716   draw();
717
718   Uint32 lastticks = SDL_GetTicks();
719   fps_ticks = SDL_GetTicks();
720
721   while (exit_status == ES_NONE) {
722     Uint32 ticks = SDL_GetTicks();
723     float elapsed_time = float(ticks - lastticks) / 1000.;
724     if(!game_pause)
725       global_time += elapsed_time;
726     lastticks = ticks;
727
728     // 40fps is minimum
729     if(elapsed_time > .025)
730       elapsed_time = .025;
731     
732     /* Handle events: */
733     currentsector->player->input.old_fire = currentsector->player->input.fire;
734     currentsector->player->input.old_up = currentsector->player->input.old_up;
735
736     process_events();
737     process_menu();
738
739     // Update the world state and all objects in the world
740     // Do that with a constante time-delta so that the game will run
741     // determistic and not different on different machines
742     if(!game_pause && !Menu::current())
743     {
744       // Update the world
745       check_end_conditions();
746       if (end_sequence == ENDSEQUENCE_RUNNING)
747         action(elapsed_time/2);
748       else if(end_sequence == NO_ENDSEQUENCE)
749         action(elapsed_time);
750     }
751     else
752     {
753       ++pause_menu_frame;
754       SDL_Delay(50);
755     }
756
757     draw();
758
759     /* Time stops in pause mode */
760     if(game_pause || Menu::current())
761     {
762       continue;
763     }
764
765     //frame_rate.update();
766     
767     /* Handle time: */
768     if (time_left.check() && currentsector->player->dying == DYING_NOT
769         && !end_sequence)
770       currentsector->player->kill(Player::KILL);
771     
772     /* Handle music: */
773     if(currentsector->player->invincible_timer.check() && !end_sequence)
774     {
775       currentsector->play_music(HERRING_MUSIC);
776     }
777     /* are we low on time ? */
778     else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
779     {
780       currentsector->play_music(HURRYUP_MUSIC);
781     }
782     /* or just normal music? */
783     else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
784     {
785       currentsector->play_music(LEVEL_MUSIC);
786     }
787
788     /* Calculate frames per second */
789     if(show_fps)
790     {
791       ++fps_cnt;
792       
793       if(SDL_GetTicks() - fps_ticks >= 500)
794       {
795         fps_fps = (float) fps_cnt / .5;
796         fps_cnt = 0;
797         fps_ticks = SDL_GetTicks();
798       }
799     }
800   }
801   
802   return exit_status;
803 }
804
805 void
806 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
807 {
808   newsector = sector;
809   newspawnpoint = spawnpoint;
810 }
811
812 void
813 GameSession::start_sequence(const std::string& sequencename)
814 {
815   if(sequencename == "endsequence") {
816     if(end_sequence)
817       return;
818     
819     end_sequence = ENDSEQUENCE_RUNNING;
820     endsequence_timer.start(7.0); // 7 seconds until we finish the map
821     last_x_pos = -1;
822     SoundManager::get()->play_music(level_end_song, 0);
823     currentsector->player->invincible_timer.start(7.0);
824
825     // add left time to stats
826     global_stats.set_points(TIME_NEEDED_STAT,
827         int(time_left.get_period() - time_left.get_timeleft()));
828
829     if(level->get_end_sequence_type() == Level::FIREWORKS_ENDSEQ_ANIM) {
830       currentsector->add_object(new Fireworks());
831     }
832   } else {
833     std::cout << "Unknown sequence '" << sequencename << "'.\n";
834   }
835 }
836
837 /* (Status): */
838 void
839 GameSession::drawstatus(DrawingContext& context)
840 {
841   char str[60];
842   
843   snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
844   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
845   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
846
847   if(st_gl_mode == ST_GL_TEST)
848     {
849       context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
850           LEFT_ALLIGN, LAYER_FOREGROUND1);
851     }
852
853   if(time_left.check()) {
854     context.draw_text(white_text, _("TIME's UP"), Vector(screen->w/2, 0),
855         CENTER_ALLIGN, LAYER_FOREGROUND1);
856   } else if (time_left.get_timeleft() > TIME_WARNING
857       || int(global_time * 2.5) % 2) {
858     sprintf(str, " %d", int(time_left.get_timeleft()));
859     context.draw_text(white_text, _("TIME"),
860         Vector(screen->w/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
861     context.draw_text(gold_text, str,
862         Vector(screen->w/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
863   }
864
865   sprintf(str, " %d", player_status.distros);
866   context.draw_text(white_text, _("COINS"),
867       Vector(screen->w - white_text->get_text_width(_("COINS"))-white_text->get_text_width("   99"), 0),
868         LEFT_ALLIGN, LAYER_FOREGROUND1);
869   context.draw_text(gold_text, str,
870       Vector(screen->w - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
871
872   if (player_status.lives >= 5)
873     {
874       sprintf(str, "%dx", player_status.lives);
875       float x = screen->w - gold_text->get_text_width(str) - tux_life->w;
876       context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
877       context.draw_surface(tux_life, Vector(screen->w - 16, 20),
878           LAYER_FOREGROUND1);
879     }
880   else
881     {
882       for(int i= 0; i < player_status.lives; ++i)
883         context.draw_surface(tux_life, 
884             Vector(screen->w - tux_life->w*4 +(tux_life->w*i), 20),
885             LAYER_FOREGROUND1);
886     }
887
888   context.draw_text(white_text, _("LIVES"),
889       Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 20),
890       LEFT_ALLIGN, LAYER_FOREGROUND1);
891
892   if(show_fps)
893     {
894       sprintf(str, "%2.1f", fps_fps);
895       context.draw_text(white_text, "FPS", 
896           Vector(screen->w - white_text->get_text_width("FPS     "), 40),
897           LEFT_ALLIGN, LAYER_FOREGROUND1);
898       context.draw_text(gold_text, str,
899           Vector(screen->w-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
900     }
901 }
902
903 void
904 GameSession::drawresultscreen()
905 {
906   char str[80];
907
908   DrawingContext context;
909   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
910       i != currentsector->gameobjects.end(); ++i) {
911     Background* background = dynamic_cast<Background*> (*i);
912     if(background) {
913       background->draw(context);
914     }
915   }
916
917   context.draw_text(blue_text, _("Result:"), Vector(screen->w/2, 200),
918       CENTER_ALLIGN, LAYER_FOREGROUND1);
919
920   sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
921   context.draw_text(gold_text, str, Vector(screen->w/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
922
923   sprintf(str, _("COINS: %d"), player_status.distros);
924   context.draw_text(gold_text, str, Vector(screen->w/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
925
926   context.do_drawing();
927   
928   SDL_Event event;
929   wait_for_event(event,2000,5000,true);
930 }
931
932 std::string slotinfo(int slot)
933 {
934   std::string tmp;
935   std::string slotfile;
936   std::string title;
937   std::stringstream stream;
938   stream << slot;
939   slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
940
941   try {
942     lisp::Parser parser;
943     std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
944
945     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
946     if(!savegame)
947       throw std::runtime_error("file is not a supertux-savegame.");
948
949     savegame->get("title", title);
950   } catch(std::exception& e) {
951     return std::string(_("Slot")) + " " + stream.str() + " - " +
952       std::string(_("Free"));
953   }
954
955   return std::string("Slot ") + stream.str() + " - " + title;
956 }
957
958 bool process_load_game_menu()
959 {
960   int slot = load_game_menu->check();
961
962   if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
963     {
964       std::stringstream stream;
965       stream << slot;
966       std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
967
968       if (access(slotfile.c_str(), F_OK) != 0)
969         {
970           shrink_fade(Vector(screen->w/2,screen->h/2), 600);
971           draw_intro();
972         }
973
974       fadeout(256);
975       DrawingContext context;
976       context.draw_text(white_text, "Loading...",
977                         Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
978       context.do_drawing();
979
980       WorldMapNS::WorldMap worldmap;
981
982       worldmap.set_map_filename("icyisland.stwm");
983       // Load the game or at least set the savegame_file variable
984       worldmap.loadgame(slotfile);
985
986       worldmap.display();
987
988       Menu::set_current(main_menu);
989
990       Ticks::pause_stop();
991       return true;
992     }
993   else
994     {
995       return false;
996     }
997 }