hopefully fixed the crash on exit, keep sectors script bundled in the sector and...
[supertux.git] / src / worldmap.cpp
index b667aec..209ea14 100644 (file)
@@ -30,6 +30,7 @@
 
 #include "gettext.hpp"
 #include "msg.hpp"
+#include "mainloop.hpp"
 #include "video/surface.hpp"
 #include "video/screen.hpp"
 #include "video/drawing_context.hpp"
@@ -44,6 +45,7 @@
 #include "worldmap.hpp"
 #include "resources.hpp"
 #include "misc.hpp"
+#include "msg.hpp"
 #include "player_status.hpp"
 #include "textscroller.hpp"
 #include "main.hpp"
@@ -54,8 +56,6 @@
 #include "control/joystickkeyboardcontroller.hpp"
 #include "object/background.hpp"
 #include "object/tilemap.hpp"
-#include "scripting/script_interpreter.hpp"
-#include "exceptions.hpp"
 
 Menu* worldmap_menu  = 0;
 
@@ -64,6 +64,8 @@ static const float map_message_TIME = 2.8;
 
 namespace WorldMapNS {
 
+WorldMap* WorldMap::current_ = NULL;
+
 Direction reverse_dir(Direction direction)
 {
   switch(direction)
@@ -147,7 +149,7 @@ Tux::draw(DrawingContext& context)
       tux_sprite->set_action(moving ? "small-walking" : "small-stop");
       break;
     default:
-      msg_debug("Bonus type not handled in worldmap.");
+      msg_debug << "Bonus type not handled in worldmap." << std::endl;
       tux_sprite->set_action("large-stop");
       break;
   }
@@ -292,7 +294,7 @@ Tux::tryContinueWalking(float elapsed_time)
     if (dir == D_NONE) 
     {
       // Should never be reached if tiledata is good
-      msg_warning("Could not determine where to walk next");
+      msg_warning << "Could not determine where to walk next" << std::endl;
       stop();
       return;
     }
@@ -312,7 +314,7 @@ Tux::tryContinueWalking(float elapsed_time)
     }
     else
     {
-      msg_warning("Tilemap data is buggy");
+      msg_warning << "Tilemap data is buggy" << std::endl;
       stop();
     }
   }
@@ -437,8 +439,10 @@ WorldMap::load_map()
         parse_level_tile(iter.lisp());
       } else if(iter.item() == "special-tile") {
         parse_special_tile(iter.lisp());
+      } else if(iter.item() == "name") {
+        // skip
       } else {
-        msg_warning("Unknown token '" << iter.item() << "' in worldmap");
+        msg_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
       }
     }
     if(solids == 0)
@@ -541,8 +545,7 @@ WorldMap::parse_level_tile(const lisp::Lisp* level_lisp)
        // Do we want to bail out instead...? We might get messages from modders
        // who can't make their levels run because they're too dumb to watch
        // their terminals...
-    msg_warning("level file '" << level.name
-      << "' does not exist and will not be added to the worldmap");
+    msg_warning << "level file '" << level.name << "' does not exist and will not be added to the worldmap" << std::endl;
     return;
   }
 
@@ -574,7 +577,7 @@ WorldMap::get_level_title(Level& level)
     
     level_lisp->get("name", level.title);
   } catch(std::exception& e) {
-    msg_warning("Problem when reading leveltitle: " << e.what());
+    msg_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
     return;
   }
 }
@@ -603,21 +606,6 @@ WorldMap::on_escape_press()
   }
 }
 
-void
-WorldMap::get_input()
-{
-  main_controller->update();
-
-  SDL_Event event;
-  while (SDL_PollEvent(&event)) {
-    if (Menu::current())
-      Menu::current()->event(event);
-    main_controller->process_event(event);
-    if(event.type == SDL_QUIT)
-      throw graceful_shutdown();
-  }
-}
-
 Vector
 WorldMap::get_next_tile(Vector pos, Direction direction)
 {
@@ -678,6 +666,72 @@ WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
 }
 
 void
+WorldMap::finished_level(const std::string& filename)
+{
+  // TODO calculate level from filename?
+  (void) filename;
+  Level* level = at_level();
+
+  bool old_level_state = level->solved;
+  level->solved = true;
+  level->sprite->set_action("solved");
+
+  // deal with statistics
+  level->statistics.merge(global_stats);
+  calculate_total_stats();
+
+  if(savegame_file != "")
+    savegame(savegame_file);
+
+  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;
+  
+    const Tile* tile = at(tux->get_tile_pos());
+
+    if (tile->getData() & Tile::WORLDMAP_NORTH
+        && tux->back_direction != D_NORTH)
+      dir = D_NORTH;
+    else if (tile->getData() & Tile::WORLDMAP_SOUTH
+        && tux->back_direction != D_SOUTH)
+      dir = D_SOUTH;
+    else if (tile->getData() & Tile::WORLDMAP_EAST
+        && tux->back_direction != D_EAST)
+      dir = D_EAST;
+    else if (tile->getData() & Tile::WORLDMAP_WEST
+        && tux->back_direction != D_WEST)
+      dir = D_WEST;
+
+    if (dir != D_NONE) {
+      tux->set_direction(dir);
+    }
+  }
+
+  if (level->extro_script != "") {
+    /* TODO
+    try {
+      std::auto_ptr<ScriptInterpreter> interpreter
+        (new ScriptInterpreter(levels_path));
+      std::istringstream in(level->extro_script);
+      interpreter->run_script(in, "level-extro-script");
+      add_object(interpreter.release());
+    } catch(std::exception& e) {
+      msg_fatal << "Couldn't run level-extro-script:" << e.what() << std::endl;
+    }
+    */
+  }
+  
+  if (!level->next_worldmap.empty()) {
+    // Load given worldmap
+    loadmap(level->next_worldmap);
+  }
+  
+  if (level->quit_worldmap)
+    main_loop->exit_screen();
+}
+
+void
 WorldMap::update(float delta)
 {
   Menu* menu = Menu::current();
@@ -691,11 +745,9 @@ WorldMap::update(float delta)
           Menu::set_current(0);
           break;
         case MNID_QUITWORLDMAP: // Quit Worldmap
-          quit = true;                               
+          main_loop->exit_screen();
           break;
       }
-    } else if(menu == options_menu) {
-      process_options_menu();
     }
 
     return;
@@ -707,6 +759,7 @@ WorldMap::update(float delta)
     GameObject* object = *i;
     object->update(delta);
   }
+
   // remove old GameObjects
   for(GameObjects::iterator i = game_objects.begin();
       i != game_objects.end(); ) {
@@ -718,7 +771,23 @@ WorldMap::update(float delta)
       ++i;
     }
   }
-  
+
+  // position "camera"
+  Vector tux_pos = tux->get_pos();
+  camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
+  camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
+
+  if (camera_offset.x < 0)
+    camera_offset.x = 0;
+  if (camera_offset.y < 0)
+    camera_offset.y = 0;
+
+  if (camera_offset.x > solids->get_width()*32 - SCREEN_WIDTH)
+    camera_offset.x = solids->get_width()*32 - SCREEN_WIDTH;
+  if (camera_offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
+    camera_offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
+
+  // handle input
   bool enter_level = false;
   if(main_controller->pressed(Controller::ACTION)
       || main_controller->pressed(Controller::JUMP)
@@ -744,143 +813,26 @@ WorldMap::update(float delta)
         }
 
       /* Check level action */
-      bool level_finished = true;
       Level* level = at_level();
-      if (!level)
-        {
-        msg_warning("No level to enter at: "
-          << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y);
+      if (!level) {
+        msg_warning << "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())
-        {
-          sound_manager->stop_music();
-          PlayerStatus old_player_status;
-          old_player_status = *player_status;
-
-          // do a shriking fade to the level
-          shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
-                             (level->pos.y*32 + 16 + offset.y)), 500);
-          GameSession session(levels_path + level->name,
-                              ST_GL_LOAD_LEVEL_FILE, &level->statistics);
-
-          switch (session.run())
-            {
-            case GameSession::ES_LEVEL_FINISHED:
-              {
-                level_finished = true;
-                bool old_level_state = level->solved;
-                level->solved = true;
-                level->sprite->set_action("solved");
-
-                // deal with statistics
-                level->statistics.merge(global_stats);
-                calculate_total_stats();
-
-                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;
-                
-                    const Tile* tile = at(tux->get_tile_pos());
-
-                    if (tile->getData() & Tile::WORLDMAP_NORTH
-                        && tux->back_direction != D_NORTH)
-                      dir = D_NORTH;
-                    else if (tile->getData() & Tile::WORLDMAP_SOUTH
-                        && tux->back_direction != D_SOUTH)
-                      dir = D_SOUTH;
-                    else if (tile->getData() & Tile::WORLDMAP_EAST
-                        && tux->back_direction != D_EAST)
-                      dir = D_EAST;
-                    else if (tile->getData() & Tile::WORLDMAP_WEST
-                        && tux->back_direction != D_WEST)
-                      dir = D_WEST;
-
-                    if (dir != D_NONE)
-                      {
-                        tux->set_direction(dir);
-                      }
-                  }
-              }
-
-              break;
-            case GameSession::ES_LEVEL_ABORT:
-              level_finished = false;
-              /* In case the player's abort the level, keep it using the old
-                  status. But the minimum lives and no bonus. */
-              player_status->coins = old_player_status.coins;
-              player_status->lives = std::min(old_player_status.lives, player_status->lives);
-              player_status->bonus = NO_BONUS;
-
-              break;
-            case GameSession::ES_GAME_OVER:
-              {
-              level_finished = false;
-              /* draw an end screen */
-              /* 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 (200,240,220), Color(200,200,220),
-                  LAYER_BACKGROUND0);
-
-              context.draw_text(blue_text, _("GAMEOVER"), 
-                  Vector(SCREEN_WIDTH/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
-
-              sprintf(str, _("COINS: %d"), player_status->coins);
-              context.draw_text(gold_text, str,
-                  Vector(SCREEN_WIDTH/2, SCREEN_WIDTH - 32), CENTER_ALLIGN,
-                  LAYER_FOREGROUND1);
-
-              total_stats.draw_message_info(context, _("Total Statistics"));
-
-              context.do_drawing();
-
-              wait_for_event(2.0, 6.0);
-
-              quit = true;
-              player_status->reset();
-              break;
-              }
-            case GameSession::ES_NONE:
-              assert(false);
-              // Should never be reached 
-              break;
-            }
+      }
 
-          sound_manager->play_music(music);
-          Menu::set_current(0);
-          if (!savegame_file.empty())
-            savegame(savegame_file);
-        }
-      /* 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) {
-        if (level->extro_script != "") {
-          try {
-            std::auto_ptr<ScriptInterpreter> interpreter 
-              (new ScriptInterpreter(levels_path));
-            std::istringstream in(level->extro_script);
-            interpreter->run_script(in, "level-extro-script");
-            add_object(interpreter.release());
-          } catch(std::exception& e) {
-            msg_warning("Couldn't run level-extro-script:" << e.what());
-          }
-        }
-
-        if (!level->next_worldmap.empty())
-          {
-          // Load given worldmap
-          loadmap(level->next_worldmap);
-          }
-        if (level->quit_worldmap)
-          quit = true;
+      if (level->pos == tux->get_tile_pos()) {
+        // do a shriking fade to the level
+        shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
+                           (level->pos.y*32 + 16 + offset.y)), 500);
+
+        try {
+          GameSession *session =
+            new GameSession(levels_path + level->name,
+                ST_GL_LOAD_LEVEL_FILE, &level->statistics);
+          main_loop->push_screen(session);
+        } catch(std::exception& e) {
+          msg_fatal << "Couldn't load level: " << e.what() << std::endl;
         }
+      }
     }
   else
     {
@@ -921,6 +873,9 @@ WorldMap::at_special_tile()
 void
 WorldMap::draw(DrawingContext& context)
 {
+  context.push_transform();
+  context.set_translation(camera_offset);
+  
   for(GameObjects::iterator i = game_objects.begin();
       i != game_objects.end(); ++i) {
     GameObject* object = *i;
@@ -950,6 +905,7 @@ WorldMap::draw(DrawingContext& context)
     }
 
   draw_status(context);
+  context.pop_transform();
 }
 
 void
@@ -1002,69 +958,12 @@ WorldMap::draw_status(DrawingContext& context)
 }
 
 void
-WorldMap::display()
+WorldMap::setup()
 {
-  Menu::set_current(0);
-
-  quit = false;
-
   sound_manager->play_music(music);
+  Menu::set_current(NULL);
 
-  if(!intro_displayed && intro_script != "") {
-    try {
-      std::auto_ptr<ScriptInterpreter> interpreter 
-        (new ScriptInterpreter(levels_path));
-      std::istringstream in(intro_script);
-      interpreter->run_script(in, "worldmap-intro-script");
-      add_object(interpreter.release());
-    } catch(std::exception& e) {
-      msg_warning("Couldn't execute worldmap-intro-script: "
-        << e.what());
-    }
-                                           
-    intro_displayed = true;
-  }
-
-  Uint32 lastticks = SDL_GetTicks();
-  DrawingContext context;
-  while(!quit) {
-    Uint32 ticks = SDL_GetTicks();
-    float elapsed_time = float(ticks - lastticks) / 1000;
-    game_time += elapsed_time;
-    lastticks = ticks;
-    
-    // 40 fps minimum // TODO use same code as in GameSession here
-    if(elapsed_time > .025)
-      elapsed_time = .025;
-    
-    Vector tux_pos = tux->get_pos();
-    offset.x = tux_pos.x - SCREEN_WIDTH/2;
-    offset.y = tux_pos.y - SCREEN_HEIGHT/2;
-
-    if (offset.x < 0)
-      offset.x = 0;
-    if (offset.y < 0)
-      offset.y = 0;
-
-    if (offset.x > solids->get_width()*32 - SCREEN_WIDTH)
-      offset.x = solids->get_width()*32 - SCREEN_WIDTH;
-    if (offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
-      offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
-
-    context.push_transform();
-    context.set_translation(offset);
-    draw(context);
-    context.pop_transform();
-    get_input();
-    update(elapsed_time);
-    sound_manager->update();
-      
-    if(Menu::current()) {
-      Menu::current()->draw(context);
-    }
-
-    context.do_drawing();
-  }
+  current_ = this;
 }
 
 void
@@ -1142,7 +1041,7 @@ WorldMap::savegame(const std::string& filename)
 void
 WorldMap::loadgame(const std::string& filename)
 {
-  msg_debug("loadgame: " << filename);
+  msg_debug << "loadgame: " << filename << std::endl;
   savegame_file = filename;
   
   if (PHYSFS_exists(filename.c_str())) // savegame exists
@@ -1162,11 +1061,6 @@ WorldMap::loadgame(const std::string& filename)
       load_map(); 
 
       savegame->get("intro-displayed", intro_displayed);
-      savegame->get("lives", player_status->lives);
-      savegame->get("coins", player_status->coins);
-      savegame->get("max-score-multiplier", player_status->max_score_multiplier);
-      if (player_status->lives < 0)
-      player_status->reset();
 
       const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
       if(tux)
@@ -1177,8 +1071,8 @@ WorldMap::loadgame(const std::string& filename)
         tux_lisp->get("x", p.x);
         tux_lisp->get("y", p.y);
         tux_lisp->get("back", back_str);
-          player_status->read(*tux_lisp);
-      
+        player_status->read(*tux_lisp);
+        if (player_status->coins < 0) player_status->reset();
         tux->back_direction = string_to_direction(back_str);      
         tux->set_tile_pos(p);
       }
@@ -1206,20 +1100,19 @@ WorldMap::loadgame(const std::string& filename)
               }
             }
           } else {
-            msg_warning("Unknown token '" << iter.item() 
-                      << "' in levels block in worldmap");
+            msg_warning << "Unknown token '" << iter.item() << "' in levels block in worldmap" << std::endl;
           }
         }
       }
     } catch(std::exception& e) {
-      msg_warning("Problem loading game '" << filename << "': " << e.what());
+      msg_warning << "Problem loading game '" << filename << "': " << e.what() << std::endl;
       load_map();
       player_status->reset();
     }
   }
   else
   {
-       load_map();
+    load_map();
     player_status->reset();
   }