816c92d3884d9da98a31ff559d37339b7b5cf9a1
[supertux.git] / src / worldmap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.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 <iostream>
22 #include <fstream>
23 #include <vector>
24 #include <cassert>
25 #include <stdexcept>
26 #include <sstream>
27 #include <unistd.h>
28 #include <physfs.h>
29
30 #include "gettext.hpp"
31 #include "msg.hpp"
32 #include "video/surface.hpp"
33 #include "video/screen.hpp"
34 #include "video/drawing_context.hpp"
35 #include "sprite/sprite_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "lisp/parser.hpp"
38 #include "lisp/lisp.hpp"
39 #include "lisp/list_iterator.hpp"
40 #include "lisp/writer.hpp"
41 #include "game_session.hpp"
42 #include "sector.hpp"
43 #include "worldmap.hpp"
44 #include "resources.hpp"
45 #include "misc.hpp"
46 #include "player_status.hpp"
47 #include "textscroller.hpp"
48 #include "main.hpp"
49 #include "spawn_point.hpp"
50 #include "file_system.hpp"
51 #include "gui/menu.hpp"
52 #include "gui/mousecursor.hpp"
53 #include "control/joystickkeyboardcontroller.hpp"
54 #include "object/background.hpp"
55 #include "object/tilemap.hpp"
56 #include "scripting/script_interpreter.hpp"
57 #include "exceptions.hpp"
58
59 Menu* worldmap_menu  = 0;
60
61 static const float TUXSPEED = 200;
62 static const float map_message_TIME = 2.8;
63
64 namespace WorldMapNS {
65
66 Direction reverse_dir(Direction direction)
67 {
68   switch(direction)
69     {
70     case D_WEST:
71       return D_EAST;
72     case D_EAST:
73       return D_WEST;
74     case D_NORTH:
75       return D_SOUTH;
76     case D_SOUTH:
77       return D_NORTH;
78     case D_NONE:
79       return D_NONE;
80     }
81   return D_NONE;
82 }
83
84 std::string
85 direction_to_string(Direction direction)
86 {
87   switch(direction)
88     {
89     case D_WEST:
90       return "west";
91     case D_EAST:
92       return "east";
93     case D_NORTH:
94       return "north";
95     case D_SOUTH:
96       return "south";
97     default:
98       return "none";
99     }
100 }
101
102 Direction
103 string_to_direction(const std::string& directory)
104 {
105   if (directory == "west")
106     return D_WEST;
107   else if (directory == "east")
108     return D_EAST;
109   else if (directory == "north")
110     return D_NORTH;
111   else if (directory == "south")
112     return D_SOUTH;
113   else
114     return D_NONE;
115 }
116
117 //---------------------------------------------------------------------------
118
119 Tux::Tux(WorldMap* worldmap_)
120   : worldmap(worldmap_)
121 {
122   tux_sprite = sprite_manager->create("images/worldmap/common/tux.sprite");
123   
124   offset = 0;
125   moving = false;
126   direction = D_NONE;
127   input_direction = D_NONE;
128 }
129
130 Tux::~Tux()
131 {
132   delete tux_sprite;
133 }
134
135 void
136 Tux::draw(DrawingContext& context)
137 {
138   switch (player_status->bonus) {
139     case GROWUP_BONUS:
140       tux_sprite->set_action(moving ? "large-walking" : "large-stop");
141       break;
142     case FIRE_BONUS:
143       tux_sprite->set_action(moving ? "fire-walking" : "fire-stop");
144       break;
145     case NO_BONUS:
146       tux_sprite->set_action(moving ? "small-walking" : "small-stop");
147       break;
148     default:
149       msg_debug("Bonus type not handled in worldmap.");
150       tux_sprite->set_action("large-stop");
151       break;
152   }
153
154   tux_sprite->draw(context, get_pos(), LAYER_OBJECTS);
155 }
156
157
158 Vector
159 Tux::get_pos()
160 {
161   float x = tile_pos.x * 32;
162   float y = tile_pos.y * 32;
163
164   switch(direction)
165     {
166     case D_WEST:
167       x -= offset - 32;
168       break;
169     case D_EAST:
170       x += offset - 32;
171       break;
172     case D_NORTH:
173       y -= offset - 32;
174       break;
175     case D_SOUTH:
176       y += offset - 32;
177       break;
178     case D_NONE:
179       break;
180     }
181   
182   return Vector(x, y);
183 }
184
185 void
186 Tux::stop()
187 {
188   offset = 0;
189   direction = D_NONE;
190   input_direction = D_NONE;
191   moving = false;
192 }
193
194 void
195 Tux::set_direction(Direction dir)
196 {
197   input_direction = dir;
198 }
199
200 void
201 Tux::update(float delta)
202 {
203   // check controller
204   if(main_controller->pressed(Controller::UP))
205     input_direction = D_NORTH;
206   else if(main_controller->pressed(Controller::DOWN))
207     input_direction = D_SOUTH;
208   else if(main_controller->pressed(Controller::LEFT))
209     input_direction = D_WEST;
210   else if(main_controller->pressed(Controller::RIGHT))
211     input_direction = D_EAST;
212
213   if(!moving)
214     {
215       if (input_direction != D_NONE)
216         { 
217           WorldMap::Level* level = worldmap->at_level();
218
219           // We got a new direction, so lets start walking when possible
220           Vector next_tile;
221           if ((!level || level->solved)
222               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
223             {
224               tile_pos = next_tile;
225               moving = true;
226               direction = input_direction;
227               back_direction = reverse_dir(direction);
228             }
229           else if (input_direction == back_direction)
230             {
231               moving = true;
232               direction = input_direction;
233               tile_pos = worldmap->get_next_tile(tile_pos, direction);
234               back_direction = reverse_dir(direction);
235             }
236         }
237     }
238   else
239     {
240       // Let tux walk
241       offset += TUXSPEED * delta;
242
243       if (offset > 32)
244         { // We reached the next tile, so we check what to do now
245           offset -= 32;
246
247           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
248           if(special_tile && special_tile->passive_message)
249             {  // direction and the apply_action_ are opposites, since they "see"
250                // directions in a different way
251             if((direction == D_NORTH && special_tile->apply_action_south) ||
252                (direction == D_SOUTH && special_tile->apply_action_north) ||
253                (direction == D_WEST && special_tile->apply_action_east) ||
254                (direction == D_EAST && special_tile->apply_action_west))
255               {
256               worldmap->passive_message = special_tile->map_message;
257               worldmap->passive_message_timer.start(map_message_TIME);
258               }
259             }
260
261           if (worldmap->at(tile_pos)->getData() & Tile::WORLDMAP_STOP ||
262              (special_tile && !special_tile->passive_message) ||
263               worldmap->at_level())
264             {
265               if(special_tile && !special_tile->map_message.empty() &&
266                 !special_tile->passive_message)
267                 worldmap->passive_message_timer.start(0);
268               stop();
269             }
270           else
271             {
272               const Tile* tile = worldmap->at(tile_pos);
273               if (direction != input_direction)
274                 { 
275                   // Turn to a new direction
276                   const Tile* tile = worldmap->at(tile_pos);
277
278                   if((tile->getData() & Tile::WORLDMAP_NORTH 
279                       && input_direction == D_NORTH) ||
280                      (tile->getData() & Tile::WORLDMAP_SOUTH
281                       && input_direction == D_SOUTH) ||
282                      (tile->getData() & Tile::WORLDMAP_EAST
283                       && input_direction == D_EAST) ||
284                      (tile->getData() & Tile::WORLDMAP_WEST
285                       && input_direction == D_WEST))
286                     {  // player has changed direction during auto-movement
287                       direction = input_direction;
288                       back_direction = reverse_dir(direction);
289                     }
290                   else
291                     {  // player has changed to impossible tile
292                       back_direction = reverse_dir(direction);
293                       stop();
294                     }
295                 }
296               else
297                 {
298                 Direction dir = D_NONE;
299               
300                 if (tile->getData() & Tile::WORLDMAP_NORTH
301                     && back_direction != D_NORTH)
302                   dir = D_NORTH;
303                 else if (tile->getData() & Tile::WORLDMAP_SOUTH
304                     && back_direction != D_SOUTH)
305                   dir = D_SOUTH;
306                 else if (tile->getData() & Tile::WORLDMAP_EAST
307                     && back_direction != D_EAST)
308                   dir = D_EAST;
309                 else if (tile->getData() & Tile::WORLDMAP_WEST
310                     && back_direction != D_WEST)
311                   dir = D_WEST;
312
313                 if (dir != D_NONE)
314                   {
315                   direction = dir;
316                   input_direction = direction;
317                   back_direction = reverse_dir(direction);
318                   }
319                 else
320                   {
321                   // Should never be reached if tiledata is good
322                   stop();
323                   return;
324                   }
325                 }
326
327               // Walk automatically to the next tile
328               if(direction != D_NONE)
329                 {
330                 Vector next_tile;
331                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
332                   {
333                   tile_pos = next_tile;
334                   }
335                 else
336                   {
337                   puts("Tilemap data is buggy");
338                   stop();
339                   }
340                 }
341             }
342         }
343     }
344 }
345
346 //---------------------------------------------------------------------------
347
348 WorldMap::WorldMap()
349   : tux(0), solids(0)
350 {
351   tile_manager = new TileManager("images/worldmap.strf");
352   
353   tux = new Tux(this);
354   add_object(tux);
355     
356   messagedot = new Surface("images/worldmap/common/messagedot.png");
357   teleporterdot = new Surface("images/worldmap/common/teleporterdot.png");
358
359   name = "<no title>";
360   music = "music/salcon.ogg";
361   intro_displayed = false;
362
363   total_stats.reset();
364 }
365
366 WorldMap::~WorldMap()
367 {
368   clear_objects();
369   for(SpawnPoints::iterator i = spawn_points.begin();
370       i != spawn_points.end(); ++i) {
371     delete *i;
372   }
373   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
374     Level& level = *i;
375     delete level.sprite;
376   }
377   
378   delete tile_manager;
379
380   delete messagedot;
381   delete teleporterdot;
382 }
383
384 void
385 WorldMap::add_object(GameObject* object)
386 {
387   TileMap* tilemap = dynamic_cast<TileMap*> (object);
388   if(tilemap != 0 && tilemap->is_solid()) {
389     solids = tilemap;
390   }
391
392   game_objects.push_back(object);
393 }
394
395 void
396 WorldMap::clear_objects()
397 {
398   for(GameObjects::iterator i = game_objects.begin();
399       i != game_objects.end(); ++i)
400     delete *i;
401   game_objects.clear();
402   solids = 0;
403   tux = new Tux(this);
404   add_object(tux);
405 }
406
407 // Don't forget to set map_filename before calling this
408 void
409 WorldMap::load_map()
410 {
411   levels_path = FileSystem::dirname(map_filename);
412
413   try {
414     lisp::Parser parser;
415     std::auto_ptr<lisp::Lisp> root (parser.parse(map_filename));
416
417     const lisp::Lisp* lisp = root->get_lisp("supertux-worldmap");
418     if(!lisp)
419       throw std::runtime_error("file isn't a supertux-worldmap file.");
420
421     clear_objects();
422     lisp::ListIterator iter(lisp);
423     while(iter.next()) {
424       if(iter.item() == "tilemap") {
425         add_object(new TileMap(*(iter.lisp()), tile_manager));
426       } else if(iter.item() == "background") {
427         add_object(new Background(*(iter.lisp())));
428       } else if(iter.item() == "properties") {
429         const lisp::Lisp* props = iter.lisp();
430         props->get("name", name);
431         props->get("music", music);
432       } else if(iter.item() == "intro-script") {
433         iter.value()->get(intro_script);
434       } else if(iter.item() == "spawnpoint") {
435         SpawnPoint* sp = new SpawnPoint(iter.lisp());
436         spawn_points.push_back(sp);
437       } else if(iter.item() == "level") {
438         parse_level_tile(iter.lisp());
439       } else if(iter.item() == "special-tile") {
440         parse_special_tile(iter.lisp());
441       } else {
442         msg_warning("Unknown token '" << iter.item() << "' in worldmap");
443       }
444     }
445     if(solids == 0)
446       throw std::runtime_error("No solid tilemap specified");
447
448     // search for main spawnpoint
449     for(SpawnPoints::iterator i = spawn_points.begin();
450         i != spawn_points.end(); ++i) {
451       SpawnPoint* sp = *i;
452       if(sp->name == "main") {
453         Vector p = sp->pos;
454         tux->set_tile_pos(p);
455         break;
456       }
457     }
458
459   } catch(std::exception& e) {
460     std::stringstream msg;
461     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
462       e.what();
463     throw std::runtime_error(msg.str());
464   }
465 }
466
467 void
468 WorldMap::parse_special_tile(const lisp::Lisp* lisp)
469 {
470   SpecialTile special_tile;
471   
472   lisp->get("x", special_tile.pos.x);
473   lisp->get("y", special_tile.pos.y);
474   lisp->get("map-message", special_tile.map_message);
475   special_tile.passive_message = false;
476   lisp->get("passive-message", special_tile.passive_message);
477   special_tile.teleport_dest = Vector(-1,-1);
478   lisp->get("teleport-to-x", special_tile.teleport_dest.x);
479   lisp->get("teleport-to-y", special_tile.teleport_dest.y);
480   special_tile.invisible = false;
481   lisp->get("invisible-tile", special_tile.invisible);
482
483   special_tile.apply_action_north = true;
484   special_tile.apply_action_south = true;
485   special_tile.apply_action_east = true;
486   special_tile.apply_action_west = true;
487
488   std::string apply_direction;
489   lisp->get("apply-to-direction", apply_direction);
490   if(!apply_direction.empty()) {
491     special_tile.apply_action_north = false;
492     special_tile.apply_action_south = false;
493     special_tile.apply_action_east = false;
494     special_tile.apply_action_west = false;
495     if(apply_direction.find("north") != std::string::npos)
496       special_tile.apply_action_north = true;
497     if(apply_direction.find("south") != std::string::npos)
498       special_tile.apply_action_south = true;
499     if(apply_direction.find("east") != std::string::npos)
500       special_tile.apply_action_east = true;
501     if(apply_direction.find("west") != std::string::npos)
502       special_tile.apply_action_west = true;
503   }
504   
505   special_tiles.push_back(special_tile);
506 }
507
508 void
509 WorldMap::parse_level_tile(const lisp::Lisp* level_lisp)
510 {
511   Level level;
512
513   level.solved = false;
514                   
515   level.north = true;
516   level.east  = true;
517   level.south = true;
518   level.west  = true;
519
520   std::string sprite = "images/worldmap/common/leveldot.sprite";
521   level_lisp->get("sprite", sprite);
522   level.sprite = sprite_manager->create(sprite);
523
524   level_lisp->get("extro-script", level.extro_script);
525   level_lisp->get("next-worldmap", level.next_worldmap);
526
527   level.quit_worldmap = false;
528   level_lisp->get("quit-worldmap", level.quit_worldmap);
529
530   level_lisp->get("name", level.name);
531   
532   if (!PHYSFS_exists((levels_path + level.name).c_str()))
533   {
534         // Do we want to bail out instead...? We might get messages from modders
535         // who can't make their levels run because they're too dumb to watch
536         // their terminals...
537     msg_warning("level file '" << level.name
538       << "' does not exist and will not be added to the worldmap");
539     return;
540   }
541
542   level_lisp->get("x", level.pos.x);
543   level_lisp->get("y", level.pos.y);
544
545   level.auto_path = true;
546   level_lisp->get("auto-path", level.auto_path);
547
548   level.vertical_flip = false;
549   level_lisp->get("vertical-flip", level.vertical_flip);
550
551   levels.push_back(level);
552 }
553
554 void
555 WorldMap::get_level_title(Level& level)
556 {
557   /** get special_tile's title */
558   level.title = "<no title>";
559
560   try {
561     lisp::Parser parser;
562     std::auto_ptr<lisp::Lisp> root (parser.parse(levels_path + level.name));
563
564     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
565     if(!level_lisp)
566       return;
567     
568     level_lisp->get("name", level.title);
569   } catch(std::exception& e) {
570     msg_warning("Problem when reading leveltitle: " << e.what());
571     return;
572   }
573 }
574
575 void WorldMap::calculate_total_stats()
576 {
577   total_stats.reset();
578   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
579     {
580     if (i->solved)
581       {
582       total_stats += i->statistics;
583       }
584     }
585 }
586
587 void
588 WorldMap::on_escape_press()
589 {
590   // Show or hide the menu
591   if(!Menu::current()) {
592     Menu::set_current(worldmap_menu);
593     tux->set_direction(D_NONE);  // stop tux movement when menu is called
594   } else {
595     Menu::set_current(0);
596   }
597 }
598
599 void
600 WorldMap::get_input()
601 {
602   main_controller->update();
603
604   SDL_Event event;
605   while (SDL_PollEvent(&event)) {
606     if (Menu::current())
607       Menu::current()->event(event);
608     main_controller->process_event(event);
609     if(event.type == SDL_QUIT)
610       throw graceful_shutdown();
611   }
612 }
613
614 Vector
615 WorldMap::get_next_tile(Vector pos, Direction direction)
616 {
617   switch(direction) {
618     case D_WEST:
619       pos.x -= 1;
620       break;
621     case D_EAST:
622       pos.x += 1;
623       break;
624     case D_NORTH:
625       pos.y -= 1;
626       break;
627     case D_SOUTH:
628       pos.y += 1;
629       break;
630     case D_NONE:
631       break;
632   }
633   return pos;
634 }
635
636 bool
637 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
638 {
639   *new_pos = get_next_tile(old_pos, direction);
640
641   if (!(new_pos->x >= 0 && new_pos->x < solids->get_width()
642         && new_pos->y >= 0 && new_pos->y < solids->get_height()))
643     { // New position is outsite the tilemap
644       return false;
645     }
646   else
647     { // Check if the tile allows us to go to new_pos
648       switch(direction)
649         {
650         case D_WEST:
651           return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
652               && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
653
654         case D_EAST:
655           return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
656               && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
657
658         case D_NORTH:
659           return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
660               && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
661
662         case D_SOUTH:
663           return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
664               && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
665
666         case D_NONE:
667           assert(!"path_ok() can't work if direction is NONE");
668         }
669       return false;
670     }
671 }
672
673 void
674 WorldMap::update(float delta)
675 {
676   Menu* menu = Menu::current();
677   if(menu) {
678     menu->update();
679
680     if(menu == worldmap_menu) {
681       switch (worldmap_menu->check())
682       {
683         case MNID_RETURNWORLDMAP: // Return to game  
684           Menu::set_current(0);
685           break;
686         case MNID_QUITWORLDMAP: // Quit Worldmap
687           quit = true;                               
688           break;
689       }
690     } else if(menu == options_menu) {
691       process_options_menu();
692     }
693
694     return;
695   }
696
697   // update GameObjects
698   for(GameObjects::iterator i = game_objects.begin();
699       i != game_objects.end(); ++i) {
700     GameObject* object = *i;
701     object->update(delta);
702   }
703   // remove old GameObjects
704   for(GameObjects::iterator i = game_objects.begin();
705       i != game_objects.end(); ) {
706     GameObject* object = *i;
707     if(!object->is_valid()) {
708       delete object;
709       i = game_objects.erase(i);
710     } else {
711       ++i;
712     }
713   }
714   
715   bool enter_level = false;
716   if(main_controller->pressed(Controller::ACTION)
717       || main_controller->pressed(Controller::JUMP)
718       || main_controller->pressed(Controller::MENU_SELECT))
719     enter_level = true;
720   if(main_controller->pressed(Controller::PAUSE_MENU))
721     on_escape_press();
722   
723   if (enter_level && !tux->is_moving())
724     {
725       /* Check special tile action */
726       SpecialTile* special_tile = at_special_tile();
727       if(special_tile)
728         {
729         if (special_tile->teleport_dest != Vector(-1,-1))
730           {
731           // TODO: an animation, camera scrolling or a fading would be a nice touch
732           sound_manager->play("sounds/warp.wav");
733           tux->back_direction = D_NONE;
734           tux->set_tile_pos(special_tile->teleport_dest);
735           SDL_Delay(1000);
736           }
737         }
738
739       /* Check level action */
740       bool level_finished = true;
741       Level* level = at_level();
742       if (!level)
743         {
744         msg_warning("No level to enter at: "
745           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y);
746         return;
747         }
748
749
750       if (level->pos == tux->get_tile_pos())
751         {
752           sound_manager->stop_music();
753           PlayerStatus old_player_status;
754           old_player_status = *player_status;
755
756           // do a shriking fade to the level
757           shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
758                              (level->pos.y*32 + 16 + offset.y)), 500);
759           GameSession session(levels_path + level->name,
760                               ST_GL_LOAD_LEVEL_FILE, &level->statistics);
761
762           switch (session.run())
763             {
764             case GameSession::ES_LEVEL_FINISHED:
765               {
766                 level_finished = true;
767                 bool old_level_state = level->solved;
768                 level->solved = true;
769                 level->sprite->set_action("solved");
770
771                 // deal with statistics
772                 level->statistics.merge(global_stats);
773                 calculate_total_stats();
774
775                 if (old_level_state != level->solved && level->auto_path)
776                   { // Try to detect the next direction to which we should walk
777                     // FIXME: Mostly a hack
778                     Direction dir = D_NONE;
779                 
780                     const Tile* tile = at(tux->get_tile_pos());
781
782                     if (tile->getData() & Tile::WORLDMAP_NORTH
783                         && tux->back_direction != D_NORTH)
784                       dir = D_NORTH;
785                     else if (tile->getData() & Tile::WORLDMAP_SOUTH
786                         && tux->back_direction != D_SOUTH)
787                       dir = D_SOUTH;
788                     else if (tile->getData() & Tile::WORLDMAP_EAST
789                         && tux->back_direction != D_EAST)
790                       dir = D_EAST;
791                     else if (tile->getData() & Tile::WORLDMAP_WEST
792                         && tux->back_direction != D_WEST)
793                       dir = D_WEST;
794
795                     if (dir != D_NONE)
796                       {
797                         tux->set_direction(dir);
798                       }
799                   }
800               }
801
802               break;
803             case GameSession::ES_LEVEL_ABORT:
804               level_finished = false;
805               /* In case the player's abort the level, keep it using the old
806                   status. But the minimum lives and no bonus. */
807               player_status->coins = old_player_status.coins;
808               player_status->lives = std::min(old_player_status.lives, player_status->lives);
809               player_status->bonus = NO_BONUS;
810
811               break;
812             case GameSession::ES_GAME_OVER:
813               {
814               level_finished = false;
815               /* draw an end screen */
816               /* TODO: in the future, this should make a dialog a la SuperMario, asking
817               if the player wants to restart the world map with no score and from
818               level 1 */
819               char str[80];
820
821               DrawingContext context;
822               context.draw_gradient(Color (200,240,220), Color(200,200,220),
823                   LAYER_BACKGROUND0);
824
825               context.draw_text(blue_text, _("GAMEOVER"), 
826                   Vector(SCREEN_WIDTH/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
827
828               sprintf(str, _("COINS: %d"), player_status->coins);
829               context.draw_text(gold_text, str,
830                   Vector(SCREEN_WIDTH/2, SCREEN_WIDTH - 32), CENTER_ALLIGN,
831                   LAYER_FOREGROUND1);
832
833               total_stats.draw_message_info(context, _("Total Statistics"));
834
835               context.do_drawing();
836
837               wait_for_event(2.0, 6.0);
838
839               quit = true;
840               player_status->reset();
841               break;
842               }
843             case GameSession::ES_NONE:
844               assert(false);
845               // Should never be reached 
846               break;
847             }
848
849           sound_manager->play_music(music);
850           Menu::set_current(0);
851           if (!savegame_file.empty())
852             savegame(savegame_file);
853         }
854       /* The porpose of the next checking is that if the player lost
855          the level (in case there is one), don't show anything */
856       if(level_finished) {
857         if (level->extro_script != "") {
858           try {
859             std::auto_ptr<ScriptInterpreter> interpreter 
860               (new ScriptInterpreter(levels_path));
861             std::istringstream in(level->extro_script);
862             interpreter->run_script(in, "level-extro-script");
863             add_object(interpreter.release());
864           } catch(std::exception& e) {
865             msg_warning("Couldn't run level-extro-script:" << e.what());
866           }
867         }
868
869         if (!level->next_worldmap.empty())
870           {
871           // Load given worldmap
872           loadmap(level->next_worldmap);
873           }
874         if (level->quit_worldmap)
875           quit = true;
876         }
877     }
878   else
879     {
880 //      tux->set_direction(input_direction);
881     }
882 }
883
884 const Tile*
885 WorldMap::at(Vector p)
886 {
887   return solids->get_tile((int) p.x, (int) p.y);
888 }
889
890 WorldMap::Level*
891 WorldMap::at_level()
892 {
893   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
894     {
895       if (i->pos == tux->get_tile_pos())
896         return &*i; 
897     }
898
899   return 0;
900 }
901
902 WorldMap::SpecialTile*
903 WorldMap::at_special_tile()
904 {
905   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
906     {
907       if (i->pos == tux->get_tile_pos())
908         return &*i; 
909     }
910
911   return 0;
912 }
913
914 void
915 WorldMap::draw(DrawingContext& context)
916 {
917   for(GameObjects::iterator i = game_objects.begin();
918       i != game_objects.end(); ++i) {
919     GameObject* object = *i;
920     object->draw(context);
921   }
922   
923   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
924     {
925       const Level& level = *i;
926       level.sprite->draw(context, level.pos*32 + Vector(16, 16), LAYER_TILES+1);
927     }
928
929   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
930     {
931       if(i->invisible)
932         continue;
933
934       if (i->teleport_dest != Vector(-1, -1))
935         context.draw_surface(teleporterdot,
936                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
937
938       else if (!i->map_message.empty() && !i->passive_message)
939         context.draw_surface(messagedot,
940                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
941     }
942
943   draw_status(context);
944 }
945
946 void
947 WorldMap::draw_status(DrawingContext& context)
948 {
949   context.push_transform();
950   context.set_translation(Vector(0, 0));
951  
952   player_status->draw(context);
953
954   if (!tux->is_moving())
955     {
956       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
957         {
958           if (i->pos == tux->get_tile_pos())
959             {
960               if(i->title == "")
961                 get_level_title(*i);
962
963               context.draw_text(white_text, i->title, 
964                   Vector(SCREEN_WIDTH/2,
965                          SCREEN_HEIGHT - white_text->get_height() - 30),
966                   CENTER_ALLIGN, LAYER_FOREGROUND1);
967
968               i->statistics.draw_worldmap_info(context);
969               break;
970             }
971         }
972       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
973         {
974           if (i->pos == tux->get_tile_pos())
975             {
976                /* Display an in-map message in the map, if any as been selected */
977               if(!i->map_message.empty() && !i->passive_message)
978                 context.draw_text(gold_text, i->map_message, 
979                     Vector(SCREEN_WIDTH/2,
980                            SCREEN_HEIGHT - white_text->get_height() - 60),
981                     CENTER_ALLIGN, LAYER_FOREGROUND1);
982               break;
983             }
984         }
985     }
986   /* Display a passive message in the map, if needed */
987   if(passive_message_timer.started())
988     context.draw_text(gold_text, passive_message, 
989             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
990             CENTER_ALLIGN, LAYER_FOREGROUND1);
991
992   context.pop_transform();
993 }
994
995 void
996 WorldMap::display()
997 {
998   Menu::set_current(0);
999
1000   quit = false;
1001
1002   sound_manager->play_music(music);
1003
1004   if(!intro_displayed && intro_script != "") {
1005     try {
1006       std::auto_ptr<ScriptInterpreter> interpreter 
1007         (new ScriptInterpreter(levels_path));
1008       std::istringstream in(intro_script);
1009       interpreter->run_script(in, "worldmap-intro-script");
1010       add_object(interpreter.release());
1011     } catch(std::exception& e) {
1012       msg_warning("Couldn't execute worldmap-intro-script: "
1013         << e.what());
1014     }
1015                                            
1016     intro_displayed = true;
1017   }
1018
1019   Uint32 lastticks = SDL_GetTicks();
1020   DrawingContext context;
1021   while(!quit) {
1022     Uint32 ticks = SDL_GetTicks();
1023     float elapsed_time = float(ticks - lastticks) / 1000;
1024     game_time += elapsed_time;
1025     lastticks = ticks;
1026     
1027     // 40 fps minimum // TODO use same code as in GameSession here
1028     if(elapsed_time > .025)
1029       elapsed_time = .025;
1030     
1031     Vector tux_pos = tux->get_pos();
1032     offset.x = tux_pos.x - SCREEN_WIDTH/2;
1033     offset.y = tux_pos.y - SCREEN_HEIGHT/2;
1034
1035     if (offset.x < 0)
1036       offset.x = 0;
1037     if (offset.y < 0)
1038       offset.y = 0;
1039
1040     if (offset.x > solids->get_width()*32 - SCREEN_WIDTH)
1041       offset.x = solids->get_width()*32 - SCREEN_WIDTH;
1042     if (offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
1043       offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
1044
1045     context.push_transform();
1046     context.set_translation(offset);
1047     draw(context);
1048     context.pop_transform();
1049     get_input();
1050     update(elapsed_time);
1051     sound_manager->update();
1052       
1053     if(Menu::current()) {
1054       Menu::current()->draw(context);
1055     }
1056
1057     context.do_drawing();
1058   }
1059 }
1060
1061 void
1062 WorldMap::savegame(const std::string& filename)
1063 {
1064   if(filename == "")
1065     return;
1066
1067   std::string dir = FileSystem::dirname(filename);
1068   if(PHYSFS_exists(dir.c_str()) == 0 && PHYSFS_mkdir(dir.c_str()) != 0) {
1069     std::ostringstream msg;
1070     msg << "Couldn't create directory '" << dir << "' for savegame:"
1071         << PHYSFS_getLastError();
1072     throw std::runtime_error(msg.str());
1073   }
1074   if(!PHYSFS_isDirectory(dir.c_str())) {
1075     std::ostringstream msg;
1076     msg << "'" << dir << "' is not a directory.";
1077     throw std::runtime_error(msg.str());
1078   }
1079   
1080   lisp::Writer writer(filename);
1081
1082   int nb_solved_levels = 0, total_levels = 0;
1083   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
1084     ++total_levels;
1085     if (i->solved)
1086       ++nb_solved_levels;
1087   }
1088   char nb_solved_levels_str[80], total_levels_str[80];
1089   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1090   sprintf(total_levels_str, "%d", total_levels);
1091
1092   writer.write_comment("Worldmap save file");
1093
1094   writer.start_list("supertux-savegame");
1095
1096   writer.write_int("version", 1);
1097   writer.write_string("title",
1098       std::string(name + " - " + nb_solved_levels_str+"/"+total_levels_str));
1099   writer.write_string("map", map_filename);
1100   writer.write_bool("intro-displayed", intro_displayed);
1101
1102   writer.start_list("tux");
1103
1104   writer.write_float("x", tux->get_tile_pos().x);
1105   writer.write_float("y", tux->get_tile_pos().y);
1106   writer.write_string("back", direction_to_string(tux->back_direction));
1107   player_status->write(writer);
1108   writer.write_string("back", direction_to_string(tux->back_direction));
1109
1110   writer.end_list("tux");
1111
1112   writer.start_list("levels");
1113
1114   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1115     {
1116       if (i->solved)
1117         {
1118         writer.start_list("level");
1119
1120         writer.write_string("name", i->name);
1121         writer.write_bool("solved", true);
1122         i->statistics.write(writer);
1123
1124         writer.end_list("level");
1125         }
1126     }  
1127
1128   writer.end_list("levels");
1129
1130   writer.end_list("supertux-savegame");
1131 }
1132
1133 void
1134 WorldMap::loadgame(const std::string& filename)
1135 {
1136   msg_debug("loadgame: " << filename);
1137   savegame_file = filename;
1138   
1139   if (PHYSFS_exists(filename.c_str())) // savegame exists
1140   {
1141     try {
1142       lisp::Parser parser;
1143       
1144       std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
1145     
1146       const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
1147       if(!savegame)
1148         throw std::runtime_error("File is not a supertux-savegame file.");
1149
1150       /* Get the Map filename and then load it before setting level settings */
1151       std::string cur_map_filename = map_filename;
1152       savegame->get("map", map_filename);
1153       load_map(); 
1154
1155       savegame->get("intro-displayed", intro_displayed);
1156       savegame->get("lives", player_status->lives);
1157       savegame->get("coins", player_status->coins);
1158       savegame->get("max-score-multiplier", player_status->max_score_multiplier);
1159       if (player_status->lives < 0)
1160       player_status->reset();
1161
1162       const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
1163       if(tux)
1164       {
1165         Vector p;
1166         std::string back_str = "none";
1167
1168         tux_lisp->get("x", p.x);
1169         tux_lisp->get("y", p.y);
1170         tux_lisp->get("back", back_str);
1171           player_status->read(*tux_lisp);
1172       
1173         tux->back_direction = string_to_direction(back_str);      
1174         tux->set_tile_pos(p);
1175       }
1176
1177       const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
1178       if(levels_lisp) {
1179         lisp::ListIterator iter(levels_lisp);
1180         while(iter.next()) {
1181           if(iter.item() == "level") {
1182             std::string name;
1183             bool solved = false;
1184
1185             const lisp::Lisp* level = iter.lisp();
1186             level->get("name", name);
1187             level->get("solved", solved);
1188
1189             for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1190             {
1191               if (name == i->name)
1192               {
1193                 i->solved = solved;
1194                 i->sprite->set_action(solved ? "solved" : "default");
1195                 i->statistics.parse(*level);
1196                 break;
1197               }
1198             }
1199           } else {
1200             msg_warning("Unknown token '" << iter.item() 
1201                       << "' in levels block in worldmap");
1202           }
1203         }
1204       }
1205     } catch(std::exception& e) {
1206       msg_warning("Problem loading game '" << filename << "': " << e.what());
1207       load_map();
1208       player_status->reset();
1209     }
1210   }
1211   else
1212   {
1213         load_map();
1214     player_status->reset();
1215   }
1216
1217   calculate_total_stats();
1218 }
1219
1220 void
1221 WorldMap::loadmap(const std::string& filename)
1222 {
1223   savegame_file = "";
1224   map_filename = filename;
1225   load_map();
1226 }
1227
1228 } // namespace WorldMapNS