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