implemented an install target in scons
[supertux.git] / src / worldmap.cpp
index 32f6747..655710d 100644 (file)
 //  along with this program; if not, write to the Free Software
 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
+#include <config.h>
+
 #include <iostream>
 #include <fstream>
 #include <vector>
-#include <assert.h>
+#include <cassert>
 #include <unistd.h>
-#include "globals.h"
-#include "screen/texture.h"
-#include "screen/screen.h"
-#include "screen/drawing_context.h"
-#include "lispreader.h"
+
+#include "app/globals.h"
+#include "video/surface.h"
+#include "video/screen.h"
+#include "video/drawing_context.h"
+#include "utils/lispreader.h"
+#include "utils/lispwriter.h"
+#include "special/frame_rate.h"
 #include "gameloop.h"
-#include "setup.h"
+#include "app/setup.h"
 #include "sector.h"
 #include "worldmap.h"
-#include "sound_manager.h"
+#include "audio/sound_manager.h"
 #include "resources.h"
-#include "gettext.h"
+#include "app/gettext.h"
+#include "misc.h"
+#include "scene.h"
+
+#define map_message_TIME 2.8
+
+Menu* worldmap_menu  = 0;
 
 namespace WorldMapNS {
 
@@ -94,7 +105,7 @@ TileManager::TileManager()
   lisp_object_t* root_obj = lisp_read_from_file(stwt_filename);
  
   if (!root_obj)
-    st_abort("Couldn't load file", stwt_filename);
+    Termination::abort("Couldn't load file", stwt_filename);
 
   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap-tiles") == 0)
     {
@@ -107,29 +118,70 @@ TileManager::TileManager()
           if (strcmp(lisp_symbol(lisp_car(element)), "tile") == 0)
             {
               int id = 0;
-              std::string filename = "<invalid>";
 
               Tile* tile = new Tile;             
-              tile->north = true;
-              tile->east  = true;
-              tile->south = true;
-              tile->west  = true;
+              tile->north = tile->east = tile->south = tile->west = true;
               tile->stop  = true;
               tile->auto_walk = false;
-  
+
               LispReader reader(lisp_cdr(element));
               reader.read_int("id", id);
+
+              std::string temp;
+              reader.read_string("possible-directions", temp);
+              if(!temp.empty())
+                {
+                tile->north = tile->east = tile->south = tile->west = false;
+                if(temp.find("north") != std::string::npos)
+                  tile->north = true;
+                if(temp.find("south") != std::string::npos)
+                  tile->south = true;
+                if(temp.find("east") != std::string::npos)
+                  tile->east = true;
+                if(temp.find("west") != std::string::npos)
+                  tile->west = true;
+                }
+
+              /* For backward compatibility */
               reader.read_bool("north", tile->north);
               reader.read_bool("south", tile->south);
               reader.read_bool("west",  tile->west);
               reader.read_bool("east",  tile->east);
+
               reader.read_bool("stop",  tile->stop);
               reader.read_bool("auto-walk",  tile->auto_walk);
-              reader.read_string("image", filename);
 
-              tile->sprite = new Surface(
-                           datadir +  "/images/worldmap/" + filename, 
-                           USE_ALPHA);
+              reader.read_string("one-way", temp);
+              tile->one_way = BOTH_WAYS;
+              if(!temp.empty())
+                {
+                if(temp == "north-south")
+                  tile->one_way = NORTH_SOUTH_WAY;
+                else if(temp == "south-north")
+                  tile->one_way = SOUTH_NORTH_WAY;
+                else if(temp == "east-west")
+                  tile->one_way = EAST_WEST_WAY;
+                else if(temp == "west-east")
+                  tile->one_way = WEST_EAST_WAY;
+                }
+
+              std::vector<std::string> filenames;
+              reader.read_string_vector("image", filenames);
+
+              if(filenames.size() == 0)
+                std::cerr << "Warning: no image specified for tile " << id
+                          << ".\nIgnoring...\n" << std::endl;
+
+              for(int i = 0; static_cast<unsigned int>(i) < filenames.size(); i++)
+                {
+                Surface* image = new Surface(
+                         datadir +  "/images/worldmap/" + filenames[i], true);
+                tile->images.push_back(image);
+                }
+
+              tile->anim_speed = 25;
+              reader.read_int("anim-speed", tile->anim_speed);
+
 
               if (id >= int(tiles.size()))
                 tiles.resize(id+1);
@@ -170,14 +222,14 @@ TileManager::get(int i)
 Tux::Tux(WorldMap* worldmap_)
   : worldmap(worldmap_)
 {
-  largetux_sprite = new Surface(datadir +  "/images/worldmap/tux.png", USE_ALPHA);
-  firetux_sprite = new Surface(datadir +  "/images/worldmap/firetux.png", USE_ALPHA);
-  smalltux_sprite = new Surface(datadir +  "/images/worldmap/smalltux.png", USE_ALPHA);
+  largetux_sprite = new Surface(datadir +  "/images/worldmap/tux.png", true);
+  firetux_sprite = new Surface(datadir +  "/images/worldmap/firetux.png", true);
+  smalltux_sprite = new Surface(datadir +  "/images/worldmap/smalltux.png", true);
 
   offset = 0;
   moving = false;
-  tile_pos.x = 4;
-  tile_pos.y = 5;
+  tile_pos.x = worldmap->get_start_x();
+  tile_pos.y = worldmap->get_start_y();
   direction = D_NONE;
   input_direction = D_NONE;
 }
@@ -243,10 +295,17 @@ Tux::stop()
 {
   offset = 0;
   direction = D_NONE;
+  input_direction = D_NONE;
   moving = false;
 }
 
 void
+Tux::set_direction(Direction dir)
+{
+input_direction = dir;
+}
+
+void
 Tux::action(float delta)
 {
   if (!moving)
@@ -267,7 +326,6 @@ Tux::action(float delta)
             }
           else if (input_direction == back_direction)
             {
-              std::cout << "Back triggered" << std::endl;
               moving = true;
               direction = input_direction;
               tile_pos = worldmap->get_next_tile(tile_pos, direction);
@@ -284,49 +342,90 @@ Tux::action(float delta)
         { // We reached the next tile, so we check what to do now
           offset -= 32;
 
-          if (worldmap->at(tile_pos)->stop || worldmap->at_level())
+          WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
+          if(special_tile && special_tile->passive_message)
+            {  // direction and the apply_action_ are opposites, since they "see"
+               // directions in a different way
+            if((direction == D_NORTH && special_tile->apply_action_south) ||
+               (direction == D_SOUTH && special_tile->apply_action_north) ||
+               (direction == D_WEST && special_tile->apply_action_east) ||
+               (direction == D_EAST && special_tile->apply_action_west))
+              {
+              worldmap->passive_message = special_tile->map_message;
+              worldmap->passive_message_timer.start(map_message_TIME);
+              }
+            }
+
+          if (worldmap->at(tile_pos)->stop ||
+             (special_tile && !special_tile->passive_message) ||
+              worldmap->at_level())
             {
+              if(special_tile && !special_tile->map_message.empty() &&
+                !special_tile->passive_message)
+                worldmap->passive_message_timer.start(0);
               stop();
             }
           else
             {
-              if (worldmap->at(tile_pos)->auto_walk)
+              if (worldmap->at(tile_pos)->auto_walk || direction != input_direction)
                 { // Turn to a new direction
                   Tile* tile = worldmap->at(tile_pos);
-                  Direction dir = D_NONE;
-                  
-                  if (tile->north && back_direction != D_NORTH)
-                    dir = D_NORTH;
-                  else if (tile->south && back_direction != D_SOUTH)
-                    dir = D_SOUTH;
-                  else if (tile->east && back_direction != D_EAST)
-                    dir = D_EAST;
-                  else if (tile->west && back_direction != D_WEST)
-                    dir = D_WEST;
-
-                  if (dir != D_NONE)
-                    {
-                      direction = dir;
+
+                  if(direction != input_direction && 
+                     ((tile->north && input_direction == D_NORTH) ||
+                     (tile->south && input_direction == D_SOUTH) ||
+                     (tile->east && input_direction == D_EAST) ||
+                     (tile->west && input_direction == D_WEST)))
+                    {  // player has changed direction during auto-movement
+                    direction = input_direction;
+                    back_direction = reverse_dir(direction);
+                    }
+                  else if(direction != input_direction)
+                    {  // player has changed to impossible tile
                       back_direction = reverse_dir(direction);
+                      stop();
                     }
                   else
                     {
+                    Direction dir = D_NONE;
+                  
+                    if (tile->north && back_direction != D_NORTH)
+                      dir = D_NORTH;
+                    else if (tile->south && back_direction != D_SOUTH)
+                      dir = D_SOUTH;
+                    else if (tile->east && back_direction != D_EAST)
+                      dir = D_EAST;
+                    else if (tile->west && back_direction != D_WEST)
+                      dir = D_WEST;
+
+                    if (dir != D_NONE)
+                      {
+                      direction = dir;
+                      input_direction = direction;
+                      back_direction = reverse_dir(direction);
+                      }
+                    else
+                      {
                       // Should never be reached if tiledata is good
                       stop();
                       return;
+                      }
                     }
-                }
+                  }
 
               // Walk automatically to the next tile
-              Vector next_tile;
-              if (worldmap->path_ok(direction, tile_pos, &next_tile))
+              if(direction != D_NONE)
                 {
+                Vector next_tile;
+                if (worldmap->path_ok(direction, tile_pos, &next_tile))
+                  {
                   tile_pos = next_tile;
-                }
-              else
-                {
+                  }
+                else
+                  {
                   puts("Tilemap data is buggy");
                   stop();
+                  }
                 }
             }
         }
@@ -340,7 +439,30 @@ Tile::Tile()
 
 Tile::~Tile()
 {
-  delete sprite;
+  for(std::vector<Surface*>::iterator i = images.begin(); i != images.end(); i++)
+    delete *i;
+}
+
+
+void
+Tile::draw(DrawingContext& context, Vector pos)
+{
+  // same code as from tile_manager.cpp draw_tile()
+
+  if(!images.size())
+    return;
+
+  if(images.size() > 1)
+    {
+    size_t frame 
+      = ((global_frame_counter*25) / anim_speed) % images.size();
+
+    context.draw_surface(images[frame], pos, LAYER_TILES);
+    }
+  else if (images.size() == 1)
+    {
+    context.draw_surface(images[0], pos, LAYER_TILES);
+    }
 }
 
 //---------------------------------------------------------------------------
@@ -348,22 +470,29 @@ Tile::~Tile()
 WorldMap::WorldMap()
 {
   tile_manager = new TileManager();
-  tux = new Tux(this);
-
+  //tux = new Tux(this);
+  
   width  = 20;
   height = 15;
+  
+  start_x = 4;
+  start_y = 5;
 
-  level_sprite = new Surface(datadir +  "/images/worldmap/levelmarker.png", USE_ALPHA);
-  leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", USE_ALPHA);
-  leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", USE_ALPHA);
+  tux = new Tux(this);
+  
+  leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", true);
+  leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", true);
+  messagedot   = new Surface(datadir +  "/images/worldmap/messagedot.png", true);
+  teleporterdot   = new Surface(datadir +  "/images/worldmap/teleporterdot.png", true);
 
-  input_direction = D_NONE;
   enter_level = false;
 
-  name = "<no file>";
-  music = "SALCON.MOD";
+  name = "<no title>";
+  music = "salcon.mod";
 
-  load_map();
+  global_frame_counter = 0;
+
+  total_stats.reset();
 }
 
 WorldMap::~WorldMap()
@@ -371,20 +500,20 @@ WorldMap::~WorldMap()
   delete tux;
   delete tile_manager;
 
-  delete level_sprite;
   delete leveldot_green;
   delete leveldot_red;
+  delete messagedot;
+  delete teleporterdot;
 }
 
+// Don't forget to set map_filename before calling this
 void
 WorldMap::load_map()
 {
-  std::string filename = datadir +  "/levels/default/worldmap.stwm";
-  
-  lisp_object_t* root_obj = lisp_read_from_file(filename);
+  lisp_object_t* root_obj = lisp_read_from_file(datadir + "/levels/worldmap/" + map_filename);
   if (!root_obj)
-    st_abort("Couldn't load file", filename);
-  
+    Termination::abort("Couldn't load file", datadir + "/levels/worldmap/" + map_filename);
+
   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
     {
       lisp_object_t* cur = lisp_cdr(root_obj);
@@ -403,18 +532,65 @@ WorldMap::load_map()
           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
             {
               LispReader reader(lisp_cdr(element));
-              reader.read_string("name", name);
+              reader.read_string("name", name, true);
               reader.read_string("music", music);
+             reader.read_int("start_pos_x", start_x);
+             reader.read_int("start_pos_y", start_y);
             }
-          else if (strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
+          else if (strcmp(lisp_symbol(lisp_car(element)), "special-tiles") == 0 ||
+                   strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
             {
               lisp_object_t* cur = lisp_cdr(element);
               
               while(!lisp_nil_p(cur))
                 {
                   lisp_object_t* element = lisp_car(cur);
-                  
-                  if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
+
+                  if (strcmp(lisp_symbol(lisp_car(element)), "special-tile") == 0)
+                    {
+                      SpecialTile special_tile;
+                      LispReader reader(lisp_cdr(element));
+                      
+                      reader.read_float("x", special_tile.pos.x);
+                      reader.read_float("y", special_tile.pos.y);
+
+                      special_tile.map_message.erase();
+                      reader.read_string("map-message", special_tile.map_message);
+                      special_tile.passive_message = false;
+                      reader.read_bool("passive-message", special_tile.passive_message);
+
+                      special_tile.teleport_dest = Vector(-1,-1);
+                      reader.read_float("teleport-to-x", special_tile.teleport_dest.x);
+                      reader.read_float("teleport-to-y", special_tile.teleport_dest.y);
+
+                      special_tile.invisible = false;
+                      reader.read_bool("invisible-tile", special_tile.invisible);
+
+                      special_tile.apply_action_north = special_tile.apply_action_south =
+                          special_tile.apply_action_east = special_tile.apply_action_west =
+                          true;
+
+                      std::string apply_direction;
+                      reader.read_string("apply-to-direction", apply_direction);
+                      if(!apply_direction.empty())
+                        {
+                        special_tile.apply_action_north = special_tile.apply_action_south =
+                            special_tile.apply_action_east = special_tile.apply_action_west =
+                            false;
+                        if(apply_direction.find("north") != std::string::npos)
+                          special_tile.apply_action_north = true;
+                        if(apply_direction.find("south") != std::string::npos)
+                          special_tile.apply_action_south = true;
+                        if(apply_direction.find("east") != std::string::npos)
+                          special_tile.apply_action_east = true;
+                        if(apply_direction.find("west") != std::string::npos)
+                          special_tile.apply_action_west = true;
+                        }
+
+                      special_tiles.push_back(special_tile);
+                    }
+
+                  else if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
                     {
                       Level level;
                       LispReader reader(lisp_cdr(element));
@@ -426,9 +602,20 @@ WorldMap::load_map()
                       level.west  = true;
 
                       reader.read_string("extro-filename", level.extro_filename);
-                      reader.read_string("name", level.name);
-                      reader.read_int("x", level.x);
-                      reader.read_int("y", level.y);
+                      reader.read_string("next-worldmap", level.next_worldmap);
+
+                      level.quit_worldmap = false;
+                      reader.read_bool("quit-worldmap", level.quit_worldmap);
+
+                      reader.read_string("name", level.name, true);
+                      reader.read_float("x", level.pos.x);
+                      reader.read_float("y", level.pos.y);
+
+                      level.auto_path = true;
+                      reader.read_bool("auto-path", level.auto_path);
+
+                      level.vertical_flip = false;
+                      reader.read_bool("vertical-flip", level.vertical_flip);
 
                       levels.push_back(level);
                     }
@@ -446,40 +633,37 @@ WorldMap::load_map()
     }
 
     lisp_free(root_obj);
+
+    delete tux;
+    tux = new Tux(this);
 }
 
 void WorldMap::get_level_title(Level& level)
 {
-  /** get level's title */
+  /** get special_tile's title */
   level.title = "<no title>";
 
-  FILE * fi;
-  lisp_object_t* root_obj = 0;
-  fi = fopen((datadir +  "/levels/" + level.name).c_str(), "r");
-  if (fi == NULL)
-  {
-    perror((datadir +  "/levels/" + level.name).c_str());
+  LispReader* reader = LispReader::load(datadir + "/levels/" + level.name, "supertux-level");
+  if(!reader)
+    {
+    std::cerr << "Error: Could not open level file. Ignoring...\n";
     return;
-  }
-
-  lisp_stream_t stream;
-  lisp_stream_init_file (&stream, fi);
-  root_obj = lisp_read (&stream);
-
-  if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
-  {
-    printf("World: Parse Error in file %s", level.name.c_str());
-  }
-
-  if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-level") == 0)
-  {
-    LispReader reader(lisp_cdr(root_obj));
-    reader.read_string("name", level.title);
-  }
+    }
 
-  lisp_free(root_obj);
+  reader->read_string("name", level.title, true);
+  delete reader;
+}
 
-  fclose(fi);
+void WorldMap::calculate_total_stats()
+{
+  total_stats.reset();
+  for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
+    {
+    if (i->solved)
+      {
+      total_stats += i->statistics;
+      }
+    }
 }
 
 void
@@ -487,7 +671,10 @@ WorldMap::on_escape_press()
 {
   // Show or hide the menu
   if(!Menu::current())
+    {
     Menu::set_current(worldmap_menu); 
+    tux->set_direction(D_NONE);  // stop tux movement when menu is called
+    }
   else
     Menu::set_current(0); 
 }
@@ -496,8 +683,8 @@ void
 WorldMap::get_input()
 {
   enter_level = false;
-  input_direction = D_NONE;
-   
+  SDLKey key;
+
   SDL_Event event;
   while (SDL_PollEvent(&event))
     {
@@ -510,38 +697,54 @@ WorldMap::get_input()
           switch(event.type)
             {
             case SDL_QUIT:
-              st_abort("Received window close", "");
+              Termination::abort("Received window close", "");
               break;
           
             case SDL_KEYDOWN:
-              switch(event.key.keysym.sym)
-                {
-                case SDLK_ESCAPE:
-                  on_escape_press();
-                  break;
-                case SDLK_LCTRL:
-                case SDLK_RETURN:
-                  enter_level = true;
-                  break;
-                default:
-                  break;
-                }
+              key = event.key.keysym.sym;
+
+              if(key == SDLK_ESCAPE)
+                on_escape_press();
+              else if(key == SDLK_RETURN || key == keymap.power)
+                enter_level = true;
+              else if(key == SDLK_LEFT || key == keymap.power)
+                tux->set_direction(D_WEST);
+              else if(key == SDLK_RIGHT || key == keymap.right)
+                tux->set_direction(D_EAST);
+              else if(key == SDLK_UP || key == keymap.up ||
+                key == keymap.jump)
+                  // there might be ppl that use jump as up key
+                tux->set_direction(D_NORTH);
+              else if(key == SDLK_DOWN || key == keymap.down)
+                tux->set_direction(D_SOUTH);
+              break;
+
+            case SDL_JOYHATMOTION:
+              if(event.jhat.value & SDL_HAT_UP) {
+                tux->set_direction(D_NORTH);
+              } else if(event.jhat.value & SDL_HAT_DOWN) {
+                tux->set_direction(D_SOUTH);
+              } else if(event.jhat.value & SDL_HAT_LEFT) {
+                tux->set_direction(D_WEST);
+              } else if(event.jhat.value & SDL_HAT_RIGHT) {
+                tux->set_direction(D_EAST);
+              }
               break;
           
             case SDL_JOYAXISMOTION:
               if (event.jaxis.axis == joystick_keymap.x_axis)
                 {
                   if (event.jaxis.value < -joystick_keymap.dead_zone)
-                    input_direction = D_WEST;
+                    tux->set_direction(D_WEST);
                   else if (event.jaxis.value > joystick_keymap.dead_zone)
-                    input_direction = D_EAST;
+                    tux->set_direction(D_EAST);
                 }
               else if (event.jaxis.axis == joystick_keymap.y_axis)
                 {
                   if (event.jaxis.value > joystick_keymap.dead_zone)
-                    input_direction = D_SOUTH;
+                    tux->set_direction(D_SOUTH);
                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
-                    input_direction = D_NORTH;
+                    tux->set_direction(D_NORTH);
                 }
               break;
 
@@ -557,20 +760,6 @@ WorldMap::get_input()
             }
         }
     }
-
-  if (!Menu::current())
-    {
-      Uint8 *keystate = SDL_GetKeyState(NULL);
-  
-      if (keystate[SDLK_LEFT])
-        input_direction = D_WEST;
-      else if (keystate[SDLK_RIGHT])
-        input_direction = D_EAST;
-      else if (keystate[SDLK_UP])
-        input_direction = D_NORTH;
-      else if (keystate[SDLK_DOWN])
-        input_direction = D_SOUTH;
-    }
 }
 
 Vector
@@ -606,6 +795,16 @@ WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
     { // New position is outsite the tilemap
       return false;
     }
+  else if(at(*new_pos)->one_way != BOTH_WAYS)
+    {
+std::cerr << "one way only\n";
+      if((at(*new_pos)->one_way == NORTH_SOUTH_WAY && direction != D_SOUTH) ||
+         (at(*new_pos)->one_way == SOUTH_NORTH_WAY && direction != D_NORTH) ||
+         (at(*new_pos)->one_way == EAST_WEST_WAY && direction != D_WEST) ||
+         (at(*new_pos)->one_way == WEST_EAST_WAY && direction != D_EAST))
+        return false;
+      return true;
+    }
   else
     { // Check if we the tile allows us to go to new_pos
       switch(direction)
@@ -632,30 +831,61 @@ WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
 void
 WorldMap::update(float delta)
 {
+  if(!frame_timer.check()) {
+    global_frame_counter++;
+  }
+
   if (enter_level && !tux->is_moving())
     {
+      /* Check special tile action */
+      SpecialTile* special_tile = at_special_tile();
+      if(special_tile)
+        {
+        if (special_tile->teleport_dest != Vector(-1,-1))
+          {
+          // TODO: an animation, camera scrolling or a fading would be a nice touch
+          SoundManager::get()->play_sound(IDToSound(SND_WARP));
+          tux->back_direction = D_NONE;
+          tux->set_tile_pos(special_tile->teleport_dest);
+          SDL_Delay(1000);
+          }
+        }
+
+      /* Check level action */
+      bool level_finished = true;
       Level* level = at_level();
-      if (level)
+      if (!level)
         {
-          if (level->x == tux->get_tile_pos().x && 
-              level->y == tux->get_tile_pos().y)
+        std::cout << "No level to enter at: "
+          << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
+        return;
+        }
+
+
+          if (level->pos == tux->get_tile_pos())
             {
               PlayerStatus old_player_status = player_status;
 
               std::cout << "Enter the current level: " << level->name << std::endl;
               // do a shriking fade to the level
-              shrink_fade(Vector((level->x*32 + 16 + offset.x),(level->y*32 + 16
+              shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),(level->pos.y*32 + 16
                       + offset.y)), 500);
-              GameSession session(datadir +  "/levels/" + level->name,
-                                  ST_GL_LOAD_LEVEL_FILE);
+              GameSession session(level->name,
+                                  ST_GL_LOAD_LEVEL_FILE, level->vertical_flip,
+                                  &level->statistics);
 
               switch (session.run())
                 {
                 case GameSession::ES_LEVEL_FINISHED:
                   {
+                    level_finished = true;
                     bool old_level_state = level->solved;
                     level->solved = true;
 
+                    // deal with statistics
+                    level->statistics.merge(global_stats);
+                    calculate_total_stats();
+
                     if (session.get_current_sector()->player->got_power !=
                           session.get_current_sector()->player->NONE_POWER)
                       player_status.bonus = PlayerStatus::FLOWER_BONUS;
@@ -664,7 +894,7 @@ WorldMap::update(float delta)
                     else
                       player_status.bonus = PlayerStatus::NO_BONUS;
 
-                    if (old_level_state != level->solved)
+                    if (old_level_state != level->solved && level->auto_path)
                       { // Try to detect the next direction to which we should walk
                         // FIXME: Mostly a hack
                         Direction dir = D_NONE;
@@ -688,82 +918,83 @@ WorldMap::update(float delta)
 
                         std::cout << "Walk to dir: " << dir << std::endl;
                       }
-
-                    if (!level->extro_filename.empty())
-                      { 
-                        MusicRef theme =
-                          sound_manager->load_music(datadir + "/music/theme.mod");
-                        sound_manager->play_music(theme);
-                        // Display final credits and go back to the main menu
-                        display_text_file(level->extro_filename,
-                                          "/images/background/extro.jpg", SCROLL_SPEED_MESSAGE);
-                        display_text_file("CREDITS",
-                                          "/images/background/oiltux.jpg", SCROLL_SPEED_CREDITS);
-                        quit = true;
-                      }
                   }
 
                   break;
                 case GameSession::ES_LEVEL_ABORT:
+                  level_finished = false;
                   /* In case the player's abort the level, keep it using the old
-                      status */
-                  player_status = old_player_status;
+                      status. But the minimum lives and no bonus. */
+                  player_status.distros = old_player_status.distros;
+                  player_status.lives = std::min(old_player_status.lives, player_status.lives);
+                  player_status.bonus = player_status.NO_BONUS;
+
                   break;
                 case GameSession::ES_GAME_OVER:
-                {
+                  {
+                  level_finished = false;
                   /* draw an end screen */
-                  /* in the future, this should make a dialog a la SuperMario, asking
+                  /* TODO: in the future, this should make a dialog a la SuperMario, asking
                   if the player wants to restart the world map with no score and from
                   level 1 */
                   char str[80];
 
                   DrawingContext context;
-                  context.draw_gradient(Color (0, 255, 0), Color (255, 0, 255),
+                  context.draw_gradient(Color (200,240,220), Color(200,200,220),
                       LAYER_BACKGROUND0);
 
-                  context.draw_text_center(blue_text, _("GAMEOVER"), 
-                      Vector(0, 200), LAYER_FOREGROUND1);
-
-                  sprintf(str, _("SCORE: %d"), player_status.score);
-                  context.draw_text_center(gold_text, str,
-                      Vector(0, 224), LAYER_FOREGROUND1);
+                  context.draw_text(blue_text, _("GAMEOVER"), 
+                      Vector(screen->w/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
 
                   sprintf(str, _("COINS: %d"), player_status.distros);
-                  context.draw_text_center(gold_text, str,
-                      Vector(0, screen->w - 32), LAYER_FOREGROUND1);
+                  context.draw_text(gold_text, str,
+                      Vector(screen->w/2, screen->w - 32), CENTER_ALLIGN, LAYER_FOREGROUND1);
+
+                  total_stats.draw_message_info(context, _("Total Statistics"));
 
                   context.do_drawing();
   
                   SDL_Event event;
-                  wait_for_event(event,2000,5000,true);
+                  wait_for_event(event,2000,6000,true);
 
                   quit = true;
                   player_status.reset();
                   break;
-                }
+                  }
                 case GameSession::ES_NONE:
                   assert(false);
                   // Should never be reached 
                   break;
                 }
 
-              sound_manager->play_music(song);
+              SoundManager::get()->play_music(song);
               Menu::set_current(0);
               if (!savegame_file.empty())
                 savegame(savegame_file);
-              return;
             }
-        }
-      else
+      /* The porpose of the next checking is that if the player lost
+         the level (in case there is one), don't show anything */
+      if(level_finished)
         {
-          std::cout << "Nothing to enter at: "
-                    << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
+        if (!level->extro_filename.empty())
+          {
+          // Display a text file
+          display_text_file(level->extro_filename, SCROLL_SPEED_MESSAGE, white_big_text , white_text, white_small_text, blue_text );
+          }
+
+        if (!level->next_worldmap.empty())
+          {
+          // Load given worldmap
+          loadmap(level->next_worldmap);
+          }
+        if (level->quit_worldmap)
+          quit = true;
         }
     }
   else
     {
       tux->action(delta);
-      tux->set_direction(input_direction);
+//      tux->set_direction(input_direction);
     }
   
   Menu* menu = Menu::current();
@@ -807,8 +1038,19 @@ WorldMap::at_level()
 {
   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
     {
-      if (i->x == tux->get_tile_pos().x && 
-          i->y == tux->get_tile_pos().y)
+      if (i->pos == tux->get_tile_pos())
+        return &*i; 
+    }
+
+  return 0;
+}
+
+WorldMap::SpecialTile*
+WorldMap::at_special_tile()
+{
+  for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
+    {
+      if (i->pos == tux->get_tile_pos())
         return &*i; 
     }
 
@@ -823,18 +1065,31 @@ WorldMap::draw(DrawingContext& context, const Vector& offset)
     for(int x = 0; x < width; ++x)
       {
         Tile* tile = at(Vector(x, y));
-        context.draw_surface(tile->sprite,
-            Vector(x*32 + offset.x, y*32 + offset.y), LAYER_TILES);
+        tile->draw(context, Vector(x*32 + offset.x, y*32 + offset.y));
       }
-  
+
   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
     {
       if (i->solved)
         context.draw_surface(leveldot_green,
-            Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
+            Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
       else
         context.draw_surface(leveldot_red,
-            Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
+            Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
+    }
+
+  for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
+    {
+      if(i->invisible)
+        continue;
+
+      if (i->teleport_dest != Vector(-1, -1))
+        context.draw_surface(teleporterdot,
+                Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
+
+      else if (!i->map_message.empty() && !i->passive_message)
+        context.draw_surface(messagedot,
+                Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
     }
 
   tux->draw(context, offset);
@@ -845,28 +1100,25 @@ void
 WorldMap::draw_status(DrawingContext& context)
 {
   char str[80];
-  sprintf(str, "%d", player_status.score);
+  sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
 
-  context.draw_text(white_text, _("SCORE"), Vector(0, 0), LAYER_FOREGROUND1);
-  context.draw_text(gold_text, str, Vector(96, 0), LAYER_FOREGROUND1);
+  context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
+  context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
 
   sprintf(str, "%d", player_status.distros);
   context.draw_text(white_text, _("COINS"), Vector(screen->w/2 - 16*5, 0),
-      LAYER_FOREGROUND1);
+      LEFT_ALLIGN, LAYER_FOREGROUND1);
   context.draw_text(gold_text, str, Vector(screen->w/2 + (16*5)/2, 0),
-        LAYER_FOREGROUND1);
+        LEFT_ALLIGN, LAYER_FOREGROUND1);
 
-  context.draw_text(white_text, _("LIVES"),
-      Vector(screen->w - white_text->get_text_width(_("LIVES"))*2, 0),
-      LAYER_FOREGROUND1);
   if (player_status.lives >= 5)
     {
       sprintf(str, "%dx", player_status.lives);
       context.draw_text(gold_text, str, 
           Vector(screen->w - gold_text->get_text_width(str) - tux_life->w, 0),
-          LAYER_FOREGROUND1);
+          LEFT_ALLIGN, LAYER_FOREGROUND1);
       context.draw_surface(tux_life, Vector(screen->w -
-            gold_text->get_text_width("9"), 0), LAYER_FOREGROUND1);
+            gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
     }
   else
     {
@@ -875,25 +1127,47 @@ WorldMap::draw_status(DrawingContext& context)
             Vector(screen->w - tux_life->w*4 + (tux_life->w*i), 0),
             LAYER_FOREGROUND1);
     }
+  context.draw_text(white_text, _("LIVES"),
+      Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
+      LEFT_ALLIGN, LAYER_FOREGROUND1);
 
   if (!tux->is_moving())
     {
       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
         {
-          if (i->x == tux->get_tile_pos().x && 
-              i->y == tux->get_tile_pos().y)
+          if (i->pos == tux->get_tile_pos())
             {
               if(i->title == "")
                 get_level_title(*i);
 
               context.draw_text(white_text, i->title, 
-                  Vector(screen->w/2 - white_text->get_text_width(i->title)/2,
-                         screen->h - white_text->get_height() - 50),
-                  LAYER_FOREGROUND1);
+                  Vector(screen->w/2,
+                         screen->h - white_text->get_height() - 30),
+                  CENTER_ALLIGN, LAYER_FOREGROUND1);
+
+              i->statistics.draw_worldmap_info(context);
+              break;
+            }
+        }
+      for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
+        {
+          if (i->pos == tux->get_tile_pos())
+            {
+               /* Display an in-map message in the map, if any as been selected */
+              if(!i->map_message.empty() && !i->passive_message)
+                context.draw_text(gold_text, i->map_message, 
+                    Vector(screen->w/2,
+                           screen->h - white_text->get_height() - 60),
+                    CENTER_ALLIGN, LAYER_FOREGROUND1);
               break;
             }
         }
     }
+  /* Display a passive message in the map, if needed */
+  if(passive_message_timer.check())
+    context.draw_text(gold_text, passive_message, 
+            Vector(screen->w/2, screen->h - white_text->get_height() - 60),
+            CENTER_ALLIGN, LAYER_FOREGROUND1);
 }
 
 void
@@ -903,26 +1177,26 @@ WorldMap::display()
 
   quit = false;
 
-  song = sound_manager->load_music(datadir +  "/music/" + music);
-  sound_manager->play_music(song);
+  song = SoundManager::get()->load_music(datadir +  "/music/" + music);
+  SoundManager::get()->play_music(song);
 
-  unsigned int last_update_time;
-  unsigned int update_time;
+  FrameRate frame_rate(10);
+  frame_rate.set_frame_limit(false);
 
-  last_update_time = update_time = st_get_ticks();
+  frame_rate.start();
+  frame_timer.start(.25, true);
 
   DrawingContext context;
   while(!quit)
     {
-      float delta = ((float)(update_time-last_update_time))/100.0;
+      float delta = frame_rate.get();
 
       delta *= 1.3f;
 
       if (delta > 10.0f)
         delta = .3f;
-      
-      last_update_time = update_time;
-      update_time      = st_get_ticks();
+       
+      frame_rate.update();
 
       Vector tux_pos = tux->get_pos();
       if (1)
@@ -940,7 +1214,7 @@ WorldMap::display()
       draw(context, offset);
       get_input();
       update(delta);
-
+      
       if(Menu::current())
         {
           Menu::current()->draw(context);
@@ -956,38 +1230,64 @@ WorldMap::display()
 void
 WorldMap::savegame(const std::string& filename)
 {
+  if(filename == "")
+    return;
+
   std::cout << "savegame: " << filename << std::endl;
-  std::ofstream out(filename.c_str());
 
-  int nb_solved_levels = 0;
+   std::ofstream file(filename.c_str(), std::ios::out);
+   LispWriter* writer = new LispWriter(file);
+
+  int nb_solved_levels = 0, total_levels = 0;
   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
     {
+      ++total_levels;
       if (i->solved)
         ++nb_solved_levels;
     }
+  char nb_solved_levels_str[80], total_levels_str[80];
+  sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
+  sprintf(total_levels_str, "%d", total_levels);
+
+  writer->write_comment("Worldmap save file");
+
+  writer->start_list("supertux-savegame");
+
+  writer->write_int("version", 1);
+  writer->write_string("title", std::string(name + " - " + nb_solved_levels_str + "/" + total_levels_str));
+  writer->write_string("map", map_filename);
+  writer->write_int("lives", player_status.lives);
+  writer->write_int("distros", player_status.lives);
+  writer->write_int("max-score-multiplier", player_status.max_score_multiplier);
+
+  writer->start_list("tux");
+
+  writer->write_float("x", tux->get_tile_pos().x);
+  writer->write_float("y", tux->get_tile_pos().y);
+  writer->write_string("back", direction_to_string(tux->back_direction));
+  writer->write_string("bonus", bonus_to_string(player_status.bonus));
+
+  writer->end_list("tux");
+
+  writer->start_list("levels");
 
-  out << "(supertux-savegame\n"
-      << "  (version 1)\n"
-      << "  (title  \"Icyisland - " << nb_solved_levels << "/" << levels.size() << "\")\n"
-      << "  (lives   " << player_status.lives << ")\n"
-      << "  (score   " << player_status.score << ")\n"
-      << "  (distros " << player_status.distros << ")\n"
-      << "  (tux (x " << tux->get_tile_pos().x << ") (y " << tux->get_tile_pos().y << ")\n"
-      << "       (back \"" << direction_to_string(tux->back_direction) << "\")\n"
-      << "       (bonus \"" << bonus_to_string(player_status.bonus) <<  "\"))\n"
-      << "  (levels\n";
-  
   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
     {
       if (i->solved)
         {
-          out << "     (level (name \"" << i->name << "\")\n"
-              << "            (solved #t))\n";
+        writer->start_list("level");
+
+        writer->write_string("name", i->name);
+        writer->write_bool("solved", true);
+        i->statistics.write(*writer);
+
+        writer->end_list("level");
         }
     }  
 
-  out << "   )\n"
-      << " )\n\n;; EOF ;;" << std::endl;
+  writer->end_list("levels");
+
+  writer->end_list("supertux-savegame");
 }
 
 void
@@ -997,26 +1297,42 @@ WorldMap::loadgame(const std::string& filename)
   savegame_file = filename;
 
   if (access(filename.c_str(), F_OK) != 0)
+    {
+    load_map();
+
+    player_status.reset();
+
     return;
+    }
   
   lisp_object_t* savegame = lisp_read_from_file(filename);
   if (!savegame)
     {
       std::cout << "WorldMap:loadgame: File not found: " << filename << std::endl;
+      load_map();
       return;
     }
 
   lisp_object_t* cur = savegame;
 
   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
+    {
+    load_map();
     return;
+    }
 
   cur = lisp_cdr(cur);
   LispReader reader(cur);
 
+  /* Get the Map filename and then load it before setting level settings */
+  std::string cur_map_filename = map_filename;
+  reader.read_string("map", map_filename);
+//  if(cur_map_filename != map_filename)
+    load_map(); 
+
   reader.read_int("lives", player_status.lives);
-  reader.read_int("score", player_status.score);
   reader.read_int("distros", player_status.distros);
+  reader.read_int("max-score-multiplier", player_status.max_score_multiplier);
 
   if (player_status.lives < 0)
     player_status.lives = START_LIVES;
@@ -1059,7 +1375,11 @@ WorldMap::loadgame(const std::string& filename)
               for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
                 {
                   if (name == i->name)
+                    {
                     i->solved = solved;
+                    i->statistics.parse(level_reader);
+                    break;
+                    }
                 }
             }
 
@@ -1068,6 +1388,16 @@ WorldMap::loadgame(const std::string& filename)
     }
  
   lisp_free(savegame);
+
+  calculate_total_stats();
+}
+
+void
+WorldMap::loadmap(const std::string& filename)
+{
+  savegame_file = "";
+  map_filename = filename;
+  load_map();
 }
 
 } // namespace WorldMapNS