Fixed strange error with saved Tux' state getting reset when quitting to the title...
[supertux.git] / src / worldmap / worldmap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
6 //
7 //  This program is free software; you can redistribute it and/or
8 //  modify it under the terms of the GNU General Public License
9 //  as published by the Free Software Foundation; either version 2
10 //  of the License, or (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 //
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program; if not, write to the Free Software
19 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 #include <config.h>
21
22 #include <iostream>
23 #include <fstream>
24 #include <vector>
25 #include <cassert>
26 #include <stdexcept>
27 #include <sstream>
28 #include <unistd.h>
29 #include <physfs.h>
30
31 #include "worldmap.hpp"
32
33 #include "gettext.hpp"
34 #include "log.hpp"
35 #include "mainloop.hpp"
36 #include "shrinkfade.hpp"
37 #include "video/surface.hpp"
38 #include "video/drawing_context.hpp"
39 #include "sprite/sprite.hpp"
40 #include "sprite/sprite_manager.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/list_iterator.hpp"
45 #include "lisp/writer.hpp"
46 #include "game_session.hpp"
47 #include "sector.hpp"
48 #include "worldmap.hpp"
49 #include "resources.hpp"
50 #include "log.hpp"
51 #include "world.hpp"
52 #include "player_status.hpp"
53 #include "textscroller.hpp"
54 #include "main.hpp"
55 #include "spawn_point.hpp"
56 #include "file_system.hpp"
57 #include "gui/menu.hpp"
58 #include "gui/mousecursor.hpp"
59 #include "control/joystickkeyboardcontroller.hpp"
60 #include "object/background.hpp"
61 #include "object/tilemap.hpp"
62 #include "options_menu.hpp"
63 #include "scripting/squirrel_error.hpp"
64 #include "scripting/squirrel_util.hpp"
65 #include "worldmap/level.hpp"
66 #include "worldmap/special_tile.hpp"
67 #include "worldmap/tux.hpp"
68 #include "worldmap/sprite_change.hpp"
69
70 namespace WorldMapNS {
71
72 enum WorldMapMenuIDs {
73   MNID_RETURNWORLDMAP,
74   MNID_QUITWORLDMAP
75 };
76
77 WorldMap* WorldMap::current_ = NULL;
78
79 Direction reverse_dir(Direction direction)
80 {
81   switch(direction)
82     {
83     case D_WEST:
84       return D_EAST;
85     case D_EAST:
86       return D_WEST;
87     case D_NORTH:
88       return D_SOUTH;
89     case D_SOUTH:
90       return D_NORTH;
91     case D_NONE:
92       return D_NONE;
93     }
94   return D_NONE;
95 }
96
97 std::string
98 direction_to_string(Direction direction)
99 {
100   switch(direction)
101     {
102     case D_WEST:
103       return "west";
104     case D_EAST:
105       return "east";
106     case D_NORTH:
107       return "north";
108     case D_SOUTH:
109       return "south";
110     default:
111       return "none";
112     }
113 }
114
115 Direction
116 string_to_direction(const std::string& directory)
117 {
118   if (directory == "west")
119     return D_WEST;
120   else if (directory == "east")
121     return D_EAST;
122   else if (directory == "north")
123     return D_NORTH;
124   else if (directory == "south")
125     return D_SOUTH;
126   else if (directory == "none")
127     return D_NONE;
128   else {
129     log_warning << "unknown direction: \"" << directory << "\"" << std::endl;
130     return D_NONE;
131   }
132 }
133
134 //---------------------------------------------------------------------------
135
136 WorldMap::WorldMap(const std::string& filename, const std::string& force_spawnpoint)
137   : tux(0), ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), force_spawnpoint(force_spawnpoint), in_level(false)
138 {
139   tile_manager.reset(new TileManager("images/worldmap.strf"));
140
141   tux = new Tux(this);
142   add_object(tux);
143
144   name = "<no title>";
145   music = "music/salcon.ogg";
146
147   total_stats.reset();
148
149   worldmap_menu.reset(new Menu());
150   worldmap_menu->add_label(_("Pause"));
151   worldmap_menu->add_hl();
152   worldmap_menu->add_entry(MNID_RETURNWORLDMAP, _("Continue"));
153   worldmap_menu->add_submenu(_("Options"), get_options_menu());
154   worldmap_menu->add_hl();
155   worldmap_menu->add_entry(MNID_QUITWORLDMAP, _("Quit World"));
156
157   // create a new squirrel table for the worldmap
158   using namespace Scripting;
159
160   sq_collectgarbage(global_vm);
161   sq_newtable(global_vm);
162   sq_pushroottable(global_vm);
163   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
164     throw Scripting::SquirrelError(global_vm, "Couldn't set worldmap_table delegate");
165
166   sq_resetobject(&worldmap_table);
167   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &worldmap_table)))
168     throw Scripting::SquirrelError(global_vm, "Couldn't get table from stack");
169
170   sq_addref(global_vm, &worldmap_table);
171   sq_pop(global_vm, 1);
172   
173   // load worldmap objects
174   load(filename);
175 }
176
177 WorldMap::~WorldMap()
178 {
179   using namespace Scripting;
180
181   for(GameObjects::iterator i = game_objects.begin();
182       i != game_objects.end(); ++i) {
183     GameObject* object = *i;
184     try_unexpose(object);
185     object->unref();
186   }
187
188   for(SpawnPoints::iterator i = spawn_points.begin();
189       i != spawn_points.end(); ++i) {
190     delete *i;
191   }
192
193   for(ScriptList::iterator i = scripts.begin();
194       i != scripts.end(); ++i) {
195     HSQOBJECT& object = *i;
196     sq_release(global_vm, &object);
197   }
198   sq_release(global_vm, &worldmap_table);
199
200   sq_collectgarbage(global_vm);
201
202   if(current_ == this)
203     current_ = NULL;
204 }
205
206 void
207 WorldMap::add_object(GameObject* object)
208 {
209   TileMap* tilemap = dynamic_cast<TileMap*> (object);
210   if(tilemap != 0 && tilemap->is_solid()) {
211     solid_tilemaps.push_back(tilemap);
212   }
213
214   object->ref();
215   try_expose(object);
216   game_objects.push_back(object);
217 }
218
219 void
220 WorldMap::try_expose(GameObject* object)
221 {
222   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
223   if(interface != NULL) {
224     HSQUIRRELVM vm = Scripting::global_vm;
225     sq_pushobject(vm, worldmap_table);
226     interface->expose(vm, -1);
227     sq_pop(vm, 1);
228   }
229 }
230
231 void
232 WorldMap::try_unexpose(GameObject* object)
233 {
234   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
235   if(interface != NULL) {
236     HSQUIRRELVM vm = Scripting::global_vm;
237     SQInteger oldtop = sq_gettop(vm);
238     sq_pushobject(vm, worldmap_table);
239     try {
240       interface->unexpose(vm, -1);
241     } catch(std::exception& e) {
242       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
243     }
244     sq_settop(vm, oldtop);
245   }
246 }
247
248 void
249 WorldMap::move_to_spawnpoint(const std::string& spawnpoint)
250 {
251   for(SpawnPoints::iterator i = spawn_points.begin(); i != spawn_points.end(); ++i) {
252     SpawnPoint* sp = *i;
253     if(sp->name == spawnpoint) {
254       Vector p = sp->pos;
255       tux->set_tile_pos(p);
256       tux->set_direction(sp->auto_dir);
257       return;
258     }
259   }
260   log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
261   if (spawnpoint != "main") {
262     move_to_spawnpoint("main");
263   }
264 }
265
266 void
267 WorldMap::change(const std::string& filename, const std::string& force_spawnpoint)
268 {
269   main_loop->exit_screen();
270   main_loop->push_screen(new WorldMap(filename, force_spawnpoint));
271 }
272
273 void
274 WorldMap::load(const std::string& filename)
275 {
276   map_filename = filename;
277   levels_path = FileSystem::dirname(map_filename);
278
279   try {
280     lisp::Parser parser;
281     const lisp::Lisp* root = parser.parse(map_filename);
282
283     const lisp::Lisp* lisp = root->get_lisp("supertux-level");
284     if(!lisp)
285       throw std::runtime_error("file isn't a supertux-level file.");
286
287     lisp->get("name", name);
288
289     const lisp::Lisp* sector = lisp->get_lisp("sector");
290     if(!sector)
291       throw std::runtime_error("No sector sepcified in worldmap file.");
292
293     lisp::ListIterator iter(sector);
294     while(iter.next()) {
295       if(iter.item() == "tilemap") {
296         add_object(new TileMap(*(iter.lisp()), tile_manager.get()));
297       } else if(iter.item() == "background") {
298         add_object(new Background(*(iter.lisp())));
299       } else if(iter.item() == "music") {
300         iter.value()->get(music);
301       } else if(iter.item() == "init-script") {
302         iter.value()->get(init_script);
303       } else if(iter.item() == "worldmap-spawnpoint") {
304         SpawnPoint* sp = new SpawnPoint(iter.lisp());
305         spawn_points.push_back(sp);
306       } else if(iter.item() == "level") {
307         LevelTile* level = new LevelTile(levels_path, iter.lisp());
308         levels.push_back(level);
309         add_object(level);
310       } else if(iter.item() == "special-tile") {
311         SpecialTile* special_tile = new SpecialTile(iter.lisp());
312         special_tiles.push_back(special_tile);
313         add_object(special_tile);
314       } else if(iter.item() == "sprite-change") {
315         SpriteChange* sprite_change = new SpriteChange(iter.lisp());
316         sprite_changes.push_back(sprite_change);
317         add_object(sprite_change);
318       } else if(iter.item() == "teleporter") {
319         Teleporter* teleporter = new Teleporter(iter.lisp());
320         teleporters.push_back(teleporter);
321         add_object(teleporter);
322       } else if(iter.item() == "ambient-light") {
323         std::vector<float> vColor;
324         sector->get_vector( "ambient-light", vColor );
325         if(vColor.size() < 3) {
326           log_warning << "(ambient-light) requires a color as argument" << std::endl;
327         } else {
328           ambient_light = Color( vColor );
329         }
330       } else if(iter.item() == "name") {
331         // skip
332       } else {
333         log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
334       }
335     }
336     if(solid_tilemaps.size() == 0)
337       throw std::runtime_error("No solid tilemap specified");
338
339     move_to_spawnpoint("main");
340
341   } catch(std::exception& e) {
342     std::stringstream msg;
343     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
344       e.what();
345     throw std::runtime_error(msg.str());
346   }
347 }
348
349 void
350 WorldMap::get_level_title(LevelTile& level)
351 {
352   /** get special_tile's title */
353   level.title = "<no title>";
354
355   try {
356     lisp::Parser parser;
357     const lisp::Lisp* root = parser.parse(levels_path + level.get_name());
358
359     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
360     if(!level_lisp)
361       return;
362
363     level_lisp->get("name", level.title);
364   } catch(std::exception& e) {
365     log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
366     return;
367   }
368 }
369
370 void WorldMap::calculate_total_stats()
371 {
372   total_stats.zero();
373   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
374     LevelTile* level = *i;
375     if (level->solved) {
376       total_stats += level->statistics;
377     }
378   }
379 }
380
381 void
382 WorldMap::on_escape_press()
383 {
384   // Show or hide the menu
385   if(!Menu::current()) {
386     Menu::set_current(worldmap_menu.get());
387     tux->set_direction(D_NONE);  // stop tux movement when menu is called
388   } else {
389     Menu::set_current(NULL);
390   }
391 }
392
393 Vector
394 WorldMap::get_next_tile(Vector pos, Direction direction)
395 {
396   switch(direction) {
397     case D_WEST:
398       pos.x -= 1;
399       break;
400     case D_EAST:
401       pos.x += 1;
402       break;
403     case D_NORTH:
404       pos.y -= 1;
405       break;
406     case D_SOUTH:
407       pos.y += 1;
408       break;
409     case D_NONE:
410       break;
411   }
412   return pos;
413 }
414
415 bool
416 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
417 {
418   *new_pos = get_next_tile(old_pos, direction);
419
420   if (!(new_pos->x >= 0 && new_pos->x < get_width()
421         && new_pos->y >= 0 && new_pos->y < get_height()))
422     { // New position is outsite the tilemap
423       return false;
424     }
425   else
426     { // Check if the tile allows us to go to new_pos
427       int old_tile_data = tile_data_at(old_pos);
428       int new_tile_data = tile_data_at(*new_pos);
429       switch(direction)
430         {
431         case D_WEST:
432           return (old_tile_data & Tile::WORLDMAP_WEST
433               && new_tile_data & Tile::WORLDMAP_EAST);
434
435         case D_EAST:
436           return (old_tile_data & Tile::WORLDMAP_EAST
437               && new_tile_data & Tile::WORLDMAP_WEST);
438
439         case D_NORTH:
440           return (old_tile_data & Tile::WORLDMAP_NORTH
441               && new_tile_data & Tile::WORLDMAP_SOUTH);
442
443         case D_SOUTH:
444           return (old_tile_data & Tile::WORLDMAP_SOUTH
445               && new_tile_data & Tile::WORLDMAP_NORTH);
446
447         case D_NONE:
448           assert(!"path_ok() can't walk if direction is NONE");
449         }
450       return false;
451     }
452 }
453
454 void
455 WorldMap::finished_level(Level* gamelevel)
456 {
457   // TODO use Level* parameter here?
458   LevelTile* level = at_level();
459
460   bool old_level_state = level->solved;
461   level->solved = true;
462   level->sprite->set_action("solved");
463
464   // deal with statistics
465   level->statistics.merge(gamelevel->stats);
466   calculate_total_stats();
467
468   save_state();
469
470   if (old_level_state != level->solved) {
471     // Try to detect the next direction to which we should walk
472     // FIXME: Mostly a hack
473     Direction dir = D_NONE;
474
475     int dirdata = available_directions_at(tux->get_tile_pos());
476     // first, test for crossroads
477     if (dirdata == Tile::WORLDMAP_CNSE ||
478                 dirdata == Tile::WORLDMAP_CNSW ||
479                 dirdata == Tile::WORLDMAP_CNEW ||
480                 dirdata == Tile::WORLDMAP_CSEW ||
481                 dirdata == Tile::WORLDMAP_CNSEW)
482       dir = D_NONE;
483     else if (dirdata & Tile::WORLDMAP_NORTH
484         && tux->back_direction != D_NORTH)
485       dir = D_NORTH;
486     else if (dirdata & Tile::WORLDMAP_SOUTH
487         && tux->back_direction != D_SOUTH)
488       dir = D_SOUTH;
489     else if (dirdata & Tile::WORLDMAP_EAST
490         && tux->back_direction != D_EAST)
491       dir = D_EAST;
492     else if (dirdata & Tile::WORLDMAP_WEST
493         && tux->back_direction != D_WEST)
494       dir = D_WEST;
495
496     if (dir != D_NONE) {
497       tux->set_direction(dir);
498     }
499   }
500
501   if (level->extro_script != "") {
502     try {
503       std::istringstream in(level->extro_script);
504       run_script(in, "worldmap:extro_script");
505     } catch(std::exception& e) {
506       log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
507     }
508   }
509 }
510
511 void
512 WorldMap::update(float delta)
513 {
514   if(!in_level) {
515     Menu* menu = Menu::current();
516     if(menu != NULL) {
517       menu->update();
518
519       if(menu == worldmap_menu.get()) {
520         switch (worldmap_menu->check())
521         {
522           case MNID_RETURNWORLDMAP: // Return to game
523             Menu::set_current(0);
524             break;
525           case MNID_QUITWORLDMAP: // Quit Worldmap
526             main_loop->exit_screen();
527             break;
528         }
529       }
530
531       return;
532     }
533
534     // update GameObjects
535     for(size_t i = 0; i < game_objects.size(); ++i) {
536       GameObject* object = game_objects[i];
537       object->update(delta);
538     }
539
540     // remove old GameObjects
541     for(GameObjects::iterator i = game_objects.begin();
542         i != game_objects.end(); ) {
543       GameObject* object = *i;
544       if(!object->is_valid()) {
545         try_unexpose(object);
546         object->unref();
547         i = game_objects.erase(i);
548       } else {
549         ++i;
550       }
551     }
552
553     /* update solid_tilemaps list */
554     //FIXME: this could be more efficient
555     solid_tilemaps.clear();
556     for(std::vector<GameObject*>::iterator i = game_objects.begin();
557         i != game_objects.end(); ++i)
558     {
559       TileMap* tm = dynamic_cast<TileMap*>(*i);
560       if (!tm) continue;
561       if (tm->is_solid()) solid_tilemaps.push_back(tm);
562     }
563
564     // position "camera"
565     Vector tux_pos = tux->get_pos();
566     camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
567     camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
568
569     if (camera_offset.x < 0)
570       camera_offset.x = 0;
571     if (camera_offset.y < 0)
572       camera_offset.y = 0;
573
574     if (camera_offset.x > (int)get_width()*32 - SCREEN_WIDTH)
575       camera_offset.x = (int)get_width()*32 - SCREEN_WIDTH;
576     if (camera_offset.y > (int)get_height()*32 - SCREEN_HEIGHT)
577       camera_offset.y = (int)get_height()*32 - SCREEN_HEIGHT;
578
579     if (int(get_width()*32) < SCREEN_WIDTH)
580       camera_offset.x = get_width()*16.0 - SCREEN_WIDTH/2.0;
581     if (int(get_height()*32) < SCREEN_HEIGHT)
582       camera_offset.y = get_height()*16.0 - SCREEN_HEIGHT/2.0;
583
584     // handle input
585     bool enter_level = false;
586     if(main_controller->pressed(Controller::ACTION)
587         || main_controller->pressed(Controller::JUMP)
588         || main_controller->pressed(Controller::MENU_SELECT)) {
589       /* some people define UP and JUMP on the same key... */
590       if(!main_controller->pressed(Controller::UP))
591             enter_level = true;
592         }
593     if(main_controller->pressed(Controller::PAUSE_MENU))
594       on_escape_press();
595
596     // check for teleporters
597     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
598     if (teleporter && (teleporter->automatic || (enter_level && (!tux->is_moving())))) {
599       enter_level = false;
600       if (teleporter->worldmap != "") {
601         change(teleporter->worldmap, teleporter->spawnpoint);
602       } else {
603         // TODO: an animation, camera scrolling or a fading would be a nice touch
604         sound_manager->play("sounds/warp.wav");
605         tux->back_direction = D_NONE;
606         move_to_spawnpoint(teleporter->spawnpoint);
607       }
608     }
609
610     // check for auto-play levels
611     LevelTile* level = at_level();
612     if (level && (level->auto_play) && (!level->solved) && (!tux->is_moving())) {
613       enter_level = true;
614     }
615
616     if (enter_level && !tux->is_moving())
617       {
618         /* Check level action */
619         LevelTile* level = at_level();
620         if (!level) {
621           //Respawn if player on a tile with no level and nowhere to go.
622           int tile_data = tile_data_at(tux->get_tile_pos());
623           if(!( tile_data & ( Tile::WORLDMAP_NORTH |  Tile::WORLDMAP_SOUTH | Tile::WORLDMAP_WEST | Tile::WORLDMAP_EAST ))){
624             log_warning << "Player at illegal position " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << " respawning." << std::endl;
625             move_to_spawnpoint("main");
626             return;
627           }
628           log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
629           return;
630         }
631
632         if (level->pos == tux->get_tile_pos()) {
633           try {
634             Vector shrinkpos = Vector(level->pos.x*32 + 16 - camera_offset.x,
635                                       level->pos.y*32 + 16 - camera_offset.y);
636             std::string levelfile = levels_path + level->get_name();
637
638             // update state and savegame
639             save_state();
640
641             main_loop->push_screen(new GameSession(levelfile, &level->statistics),
642                                    new ShrinkFade(shrinkpos, 0.5));
643             in_level = true;
644           } catch(std::exception& e) {
645             log_fatal << "Couldn't load level: " << e.what() << std::endl;
646           }
647         }
648       }
649     else
650       {
651   //      tux->set_direction(input_direction);
652       }
653   }
654 }
655
656 int
657 WorldMap::tile_data_at(Vector p)
658 {
659   int dirs = 0;
660
661   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
662     TileMap* tilemap = *i;
663     const Tile* tile = tilemap->get_tile((int)p.x, (int)p.y);
664     int dirdata = tile->getData();
665     dirs |= dirdata;
666   }
667
668   return dirs;
669 }
670
671 int
672 WorldMap::available_directions_at(Vector p)
673 {
674   return tile_data_at(p) & Tile::WORLDMAP_DIR_MASK;
675 }
676
677 LevelTile*
678 WorldMap::at_level()
679 {
680   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
681     LevelTile* level = *i;
682     if (level->pos == tux->get_tile_pos())
683       return level;
684   }
685
686   return NULL;
687 }
688
689 SpecialTile*
690 WorldMap::at_special_tile()
691 {
692   for(SpecialTiles::iterator i = special_tiles.begin();
693       i != special_tiles.end(); ++i) {
694     SpecialTile* special_tile = *i;
695     if (special_tile->pos == tux->get_tile_pos())
696       return special_tile;
697   }
698
699   return NULL;
700 }
701
702 SpriteChange*
703 WorldMap::at_sprite_change(const Vector& pos)
704 {
705   for(SpriteChanges::iterator i = sprite_changes.begin();
706       i != sprite_changes.end(); ++i) {
707     SpriteChange* sprite_change = *i;
708     if(sprite_change->pos == pos)
709       return sprite_change;
710   }
711
712   return NULL;
713 }
714
715 Teleporter*
716 WorldMap::at_teleporter(const Vector& pos)
717 {
718   for(std::vector<Teleporter*>::iterator i = teleporters.begin(); i != teleporters.end(); ++i) {
719     Teleporter* teleporter = *i;
720     if(teleporter->pos == pos) return teleporter;
721   }
722
723   return NULL;
724 }
725
726 void
727 WorldMap::draw(DrawingContext& context)
728 {
729   if (int(get_width()*32) < SCREEN_WIDTH || int(get_height()*32) < SCREEN_HEIGHT)
730     context.draw_filled_rect(Vector(0, 0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
731       Color(0.0f, 0.0f, 0.0f, 1.0f), LAYER_BACKGROUND0);
732
733   context.set_ambient_color( ambient_light );
734   context.push_transform();
735   context.set_translation(camera_offset);
736
737   for(GameObjects::iterator i = game_objects.begin();
738       i != game_objects.end(); ++i) {
739     GameObject* object = *i;
740     object->draw(context);
741   }
742
743 /*
744   // FIXME: make this a runtime switch similar to draw_collrects/show_collrects?
745   // draw visual indication of possible walk directions
746   static int flipme = 0; 
747   if (flipme++ & 0x04)
748   for (int x = 0; x < get_width(); x++) {
749     for (int y = 0; y < get_height(); y++) {
750       int data = tile_data_at(Vector(x,y));
751       int px = x * 32;
752       int py = y * 32;
753       const int W = 4;
754       if (data & Tile::WORLDMAP_NORTH)    context.draw_filled_rect(Rect(px + 16-W, py       , px + 16+W, py + 16-W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
755       if (data & Tile::WORLDMAP_SOUTH)    context.draw_filled_rect(Rect(px + 16-W, py + 16+W, px + 16+W, py + 32  ), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
756       if (data & Tile::WORLDMAP_EAST)     context.draw_filled_rect(Rect(px + 16+W, py + 16-W, px + 32  , py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
757       if (data & Tile::WORLDMAP_WEST)     context.draw_filled_rect(Rect(px       , py + 16-W, px + 16-W, py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
758       if (data & Tile::WORLDMAP_DIR_MASK) context.draw_filled_rect(Rect(px + 16-W, py + 16-W, px + 16+W, py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
759       if (data & Tile::WORLDMAP_STOP)     context.draw_filled_rect(Rect(px + 4   , py + 4   , px + 28  , py + 28  ), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
760     }
761   }
762 */
763
764   draw_status(context);
765   context.pop_transform();
766 }
767
768 void
769 WorldMap::draw_status(DrawingContext& context)
770 {
771   context.push_transform();
772   context.set_translation(Vector(0, 0));
773
774   player_status->draw(context);
775
776   if (!tux->is_moving()) {
777     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
778       LevelTile* level = *i;
779
780       if (level->pos == tux->get_tile_pos()) {
781         if(level->title == "")
782           get_level_title(*level);
783
784         context.draw_text(white_text, level->title,
785                           Vector(SCREEN_WIDTH/2,
786                                  SCREEN_HEIGHT - white_text->get_height() - 30),
787                           ALIGN_CENTER, LAYER_FOREGROUND1);
788
789         // if level is solved, draw level picture behind stats
790         /*
791         if (level->solved) {
792           if (const Surface* picture = level->get_picture()) {
793             Vector pos = Vector(SCREEN_WIDTH - picture->get_width(), SCREEN_HEIGHT - picture->get_height());
794             context.push_transform();
795             context.set_alpha(0.5);
796             context.draw_surface(picture, pos, LAYER_FOREGROUND1-1);
797             context.pop_transform();
798           }
799         }
800         */
801
802         level->statistics.draw_worldmap_info(context);
803         break;
804       }
805     }
806
807     for(SpecialTiles::iterator i = special_tiles.begin();
808         i != special_tiles.end(); ++i) {
809       SpecialTile* special_tile = *i;
810
811       if (special_tile->pos == tux->get_tile_pos()) {
812         /* Display an in-map message in the map, if any as been selected */
813         if(!special_tile->map_message.empty() && !special_tile->passive_message)
814           context.draw_text(gold_text, special_tile->map_message,
815               Vector(SCREEN_WIDTH/2,
816                 SCREEN_HEIGHT - white_text->get_height() - 60),
817               ALIGN_CENTER, LAYER_FOREGROUND1);
818         break;
819       }
820     }
821
822     // display teleporter messages
823     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
824     if (teleporter && (teleporter->message != "")) {
825       Vector pos = Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 30);
826       context.draw_text(white_text, teleporter->message, pos, ALIGN_CENTER, LAYER_FOREGROUND1);
827     }
828
829   }
830
831   /* Display a passive message in the map, if needed */
832   if(passive_message_timer.started())
833     context.draw_text(gold_text, passive_message,
834             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
835             ALIGN_CENTER, LAYER_FOREGROUND1);
836
837   context.pop_transform();
838 }
839
840 void
841 WorldMap::setup()
842 {
843   sound_manager->play_music(music);
844   Menu::set_current(NULL);
845
846   current_ = this;
847   load_state();
848
849   // if force_spawnpoint was set, move Tux there, then clear force_spawnpoint
850   if (force_spawnpoint != "") {
851     move_to_spawnpoint(force_spawnpoint);
852     force_spawnpoint = "";
853   }
854
855   tux->setup();
856
857   // register worldmap_table as worldmap in scripting
858   using namespace Scripting;
859
860   sq_pushroottable(global_vm);
861   sq_pushstring(global_vm, "worldmap", -1);
862   sq_pushobject(global_vm, worldmap_table);
863   if(SQ_FAILED(sq_createslot(global_vm, -3)))
864     throw SquirrelError(global_vm, "Couldn't set worldmap in roottable");
865   sq_pop(global_vm, 1);
866
867   if(init_script != "") {
868     std::istringstream in(init_script);
869     run_script(in, "WorldMap::init");
870   }
871 }
872
873 void
874 WorldMap::leave()
875 {
876   using namespace Scripting;
877
878   // save state of world and player
879   save_state();
880
881   // remove worldmap_table from roottable
882   sq_pushroottable(global_vm);
883   sq_pushstring(global_vm, "worldmap", -1);
884   if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
885     throw SquirrelError(global_vm, "Couldn't unset worldmap in roottable");
886   sq_pop(global_vm, 1);
887 }
888
889 void
890 WorldMap::save_state()
891 {
892   using namespace Scripting;
893
894   HSQUIRRELVM vm = global_vm;
895   int oldtop = sq_gettop(vm);
896
897   try {
898     // get state table
899     sq_pushroottable(vm);
900     sq_pushstring(vm, "state", -1);
901     if(SQ_FAILED(sq_get(vm, -2)))
902       throw Scripting::SquirrelError(vm, "Couldn't get state table");
903
904     // get or create worlds table
905     sq_pushstring(vm, "worlds", -1);
906     if(SQ_FAILED(sq_get(vm, -2))) {
907       sq_pushstring(vm, "worlds", -1);
908       sq_newtable(vm);
909       if(SQ_FAILED(sq_createslot(vm, -3)))
910         throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
911
912       sq_pushstring(vm, "worlds", -1);
913       if(SQ_FAILED(sq_get(vm, -2)))
914         throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
915     }
916
917     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
918     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
919       sq_pop(vm, 1);
920
921     // construct new table for this worldmap
922     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
923     sq_newtable(vm);
924
925     // store tux
926     sq_pushstring(vm, "tux", -1);
927     sq_newtable(vm);
928
929     store_float(vm, "x", tux->get_tile_pos().x);
930     store_float(vm, "y", tux->get_tile_pos().y);
931     store_string(vm, "back", direction_to_string(tux->back_direction));
932
933     sq_createslot(vm, -3);
934
935     // levels...
936     sq_pushstring(vm, "levels", -1);
937     sq_newtable(vm);
938
939     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
940       LevelTile* level = *i;
941
942           sq_pushstring(vm, level->get_name().c_str(), -1);
943           sq_newtable(vm);
944
945           store_bool(vm, "solved", level->solved);
946           level->statistics.serialize_to_squirrel(vm);
947
948           sq_createslot(vm, -3);
949     }
950
951     sq_createslot(vm, -3);
952
953     // overall statistics...
954     total_stats.serialize_to_squirrel(vm);
955
956     // push world into worlds table
957     sq_createslot(vm, -3);
958   } catch(std::exception& ) {
959     sq_settop(vm, oldtop);
960   }
961
962   sq_settop(vm, oldtop);
963
964   if(World::current() != NULL)
965     World::current()->save_state();
966 }
967
968 void
969 WorldMap::load_state()
970 {
971   using namespace Scripting;
972
973   HSQUIRRELVM vm = global_vm;
974   int oldtop = sq_gettop(vm);
975
976   try {
977     // get state table
978     sq_pushroottable(vm);
979     sq_pushstring(vm, "state", -1);
980     if(SQ_FAILED(sq_get(vm, -2)))
981       throw Scripting::SquirrelError(vm, "Couldn't get state table");
982
983     // get worlds table
984     sq_pushstring(vm, "worlds", -1);
985     if(SQ_FAILED(sq_get(vm, -2)))
986       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
987
988     // get table for our world
989     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
990     if(SQ_FAILED(sq_get(vm, -2)))
991       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds.mapfilename");
992
993     // load tux
994     sq_pushstring(vm, "tux", -1);
995     if(SQ_FAILED(sq_get(vm, -2)))
996       throw Scripting::SquirrelError(vm, "Couldn't get tux");
997
998     Vector p;
999     p.x = read_float(vm, "x");
1000     p.y = read_float(vm, "y");
1001     std::string back_str = read_string(vm, "back");
1002     tux->back_direction = string_to_direction(back_str);
1003     tux->set_tile_pos(p);
1004
1005     sq_pop(vm, 1);
1006
1007     // load levels
1008     sq_pushstring(vm, "levels", -1);
1009     if(SQ_FAILED(sq_get(vm, -2)))
1010       throw Scripting::SquirrelError(vm, "Couldn't get levels");
1011
1012     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1013       LevelTile* level = *i;
1014       sq_pushstring(vm, level->get_name().c_str(), -1);
1015       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
1016         level->solved = read_bool(vm, "solved");
1017         level->sprite->set_action(level->solved ? "solved" : "default");
1018         level->statistics.unserialize_from_squirrel(vm);
1019         sq_pop(vm, 1);
1020       }
1021     }
1022
1023     // leave state table
1024     sq_pop(vm, 1);
1025
1026     // load overall statistics
1027     total_stats.unserialize_from_squirrel(vm);
1028
1029   } catch(std::exception& e) {
1030     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
1031   }
1032   sq_settop(vm, oldtop);
1033
1034   in_level = false;
1035 }
1036
1037 size_t
1038 WorldMap::level_count()
1039 {
1040   return levels.size();
1041 }
1042
1043 size_t
1044 WorldMap::solved_level_count()
1045 {
1046   size_t count = 0;
1047   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1048     LevelTile* level = *i;
1049
1050     if(level->solved)
1051       count++;
1052   }
1053
1054   return count;
1055 }
1056
1057 HSQUIRRELVM
1058 WorldMap::run_script(std::istream& in, const std::string& sourcename)
1059 {
1060   using namespace Scripting;
1061
1062   // garbage collect thread list
1063   for(ScriptList::iterator i = scripts.begin();
1064       i != scripts.end(); ) {
1065     HSQOBJECT& object = *i;
1066     HSQUIRRELVM vm = object_to_vm(object);
1067
1068     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
1069       sq_release(global_vm, &object);
1070       i = scripts.erase(i);
1071       continue;
1072     }
1073
1074     ++i;
1075   }
1076
1077   HSQOBJECT object = create_thread(global_vm);
1078   scripts.push_back(object);
1079
1080   HSQUIRRELVM vm = object_to_vm(object);
1081
1082   // set worldmap_table as roottable for the thread
1083   sq_pushobject(vm, worldmap_table);
1084   sq_setroottable(vm);
1085
1086   compile_and_run(vm, in, sourcename);
1087
1088   return vm;
1089 }
1090
1091 float
1092 WorldMap::get_width() const
1093 {
1094   float width = 0;
1095   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1096     TileMap* solids = *i;
1097     if (solids->get_width() > width) width = solids->get_width();
1098   }
1099   return width;
1100 }
1101
1102 float
1103 WorldMap::get_height() const
1104 {
1105   float height = 0;
1106   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1107     TileMap* solids = *i;
1108     if (solids->get_height() > height) height = solids->get_height();
1109   }
1110   return height;
1111 }
1112
1113 } // namespace WorldMapNS