Allowed multiple solid Tilemaps on a Worldmap
[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   save_state();
182
183   for(GameObjects::iterator i = game_objects.begin();
184       i != game_objects.end(); ++i) {
185     GameObject* object = *i;
186     try_unexpose(object);
187     object->unref();
188   }
189
190   for(SpawnPoints::iterator i = spawn_points.begin();
191       i != spawn_points.end(); ++i) {
192     delete *i;
193   }
194
195   for(ScriptList::iterator i = scripts.begin();
196       i != scripts.end(); ++i) {
197     HSQOBJECT& object = *i;
198     sq_release(global_vm, &object);
199   }
200   sq_release(global_vm, &worldmap_table);
201
202   sq_collectgarbage(global_vm);
203
204   if(current_ == this)
205     current_ = NULL;
206 }
207
208 void
209 WorldMap::add_object(GameObject* object)
210 {
211   TileMap* tilemap = dynamic_cast<TileMap*> (object);
212   if(tilemap != 0 && tilemap->is_solid()) {
213     solid_tilemaps.push_back(tilemap);
214   }
215
216   object->ref();
217   try_expose(object);
218   game_objects.push_back(object);
219 }
220
221 void
222 WorldMap::try_expose(GameObject* object)
223 {
224   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
225   if(interface != NULL) {
226     HSQUIRRELVM vm = Scripting::global_vm;
227     sq_pushobject(vm, worldmap_table);
228     interface->expose(vm, -1);
229     sq_pop(vm, 1);
230   }
231 }
232
233 void
234 WorldMap::try_unexpose(GameObject* object)
235 {
236   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
237   if(interface != NULL) {
238     HSQUIRRELVM vm = Scripting::global_vm;
239     SQInteger oldtop = sq_gettop(vm);
240     sq_pushobject(vm, worldmap_table);
241     try {
242       interface->unexpose(vm, -1);
243     } catch(std::exception& e) {
244       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
245     }
246     sq_settop(vm, oldtop);
247   }
248 }
249
250 void
251 WorldMap::move_to_spawnpoint(const std::string& spawnpoint)
252 {
253   for(SpawnPoints::iterator i = spawn_points.begin(); i != spawn_points.end(); ++i) {
254     SpawnPoint* sp = *i;
255     if(sp->name == spawnpoint) {
256       Vector p = sp->pos;
257       tux->set_tile_pos(p);
258       tux->set_direction(sp->auto_dir);
259       return;
260     }
261   }
262   log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
263   if (spawnpoint != "main") {
264     move_to_spawnpoint("main");
265   }
266 }
267
268 void
269 WorldMap::change(const std::string& filename, const std::string& force_spawnpoint)
270 {
271   main_loop->exit_screen();
272   main_loop->push_screen(new WorldMap(filename, force_spawnpoint));
273 }
274
275 void
276 WorldMap::load(const std::string& filename)
277 {
278   map_filename = filename;
279   levels_path = FileSystem::dirname(map_filename);
280
281   try {
282     lisp::Parser parser;
283     const lisp::Lisp* root = parser.parse(map_filename);
284
285     const lisp::Lisp* lisp = root->get_lisp("supertux-level");
286     if(!lisp)
287       throw std::runtime_error("file isn't a supertux-level file.");
288
289     lisp->get("name", name);
290
291     const lisp::Lisp* sector = lisp->get_lisp("sector");
292     if(!sector)
293       throw std::runtime_error("No sector sepcified in worldmap file.");
294
295     lisp::ListIterator iter(sector);
296     while(iter.next()) {
297       if(iter.item() == "tilemap") {
298         add_object(new TileMap(*(iter.lisp()), tile_manager.get()));
299       } else if(iter.item() == "background") {
300         add_object(new Background(*(iter.lisp())));
301       } else if(iter.item() == "music") {
302         iter.value()->get(music);
303       } else if(iter.item() == "init-script") {
304         iter.value()->get(init_script);
305       } else if(iter.item() == "worldmap-spawnpoint") {
306         SpawnPoint* sp = new SpawnPoint(iter.lisp());
307         spawn_points.push_back(sp);
308       } else if(iter.item() == "level") {
309         LevelTile* level = new LevelTile(levels_path, iter.lisp());
310         levels.push_back(level);
311         add_object(level);
312       } else if(iter.item() == "special-tile") {
313         SpecialTile* special_tile = new SpecialTile(iter.lisp());
314         special_tiles.push_back(special_tile);
315         add_object(special_tile);
316       } else if(iter.item() == "sprite-change") {
317         SpriteChange* sprite_change = new SpriteChange(iter.lisp());
318         sprite_changes.push_back(sprite_change);
319         add_object(sprite_change);
320       } else if(iter.item() == "teleporter") {
321         Teleporter* teleporter = new Teleporter(iter.lisp());
322         teleporters.push_back(teleporter);
323         add_object(teleporter);
324       } else if(iter.item() == "ambient-light") {
325         std::vector<float> vColor;
326         sector->get_vector( "ambient-light", vColor );
327         if(vColor.size() < 3) {
328           log_warning << "(ambient-light) requires a color as argument" << std::endl;
329         } else {
330           ambient_light = Color( vColor );
331         }
332       } else if(iter.item() == "name") {
333         // skip
334       } else {
335         log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
336       }
337     }
338     if(solid_tilemaps.size() == 0)
339       throw std::runtime_error("No solid tilemap specified");
340
341     move_to_spawnpoint("main");
342
343   } catch(std::exception& e) {
344     std::stringstream msg;
345     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
346       e.what();
347     throw std::runtime_error(msg.str());
348   }
349 }
350
351 void
352 WorldMap::get_level_title(LevelTile& level)
353 {
354   /** get special_tile's title */
355   level.title = "<no title>";
356
357   try {
358     lisp::Parser parser;
359     const lisp::Lisp* root = parser.parse(levels_path + level.get_name());
360
361     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
362     if(!level_lisp)
363       return;
364
365     level_lisp->get("name", level.title);
366   } catch(std::exception& e) {
367     log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
368     return;
369   }
370 }
371
372 void WorldMap::calculate_total_stats()
373 {
374   total_stats.reset();
375   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
376     LevelTile* level = *i;
377     if (level->solved) {
378       total_stats += level->statistics;
379     }
380   }
381 }
382
383 void
384 WorldMap::on_escape_press()
385 {
386   // Show or hide the menu
387   if(!Menu::current()) {
388     Menu::set_current(worldmap_menu.get());
389     tux->set_direction(D_NONE);  // stop tux movement when menu is called
390   } else {
391     Menu::set_current(NULL);
392   }
393 }
394
395 Vector
396 WorldMap::get_next_tile(Vector pos, Direction direction)
397 {
398   switch(direction) {
399     case D_WEST:
400       pos.x -= 1;
401       break;
402     case D_EAST:
403       pos.x += 1;
404       break;
405     case D_NORTH:
406       pos.y -= 1;
407       break;
408     case D_SOUTH:
409       pos.y += 1;
410       break;
411     case D_NONE:
412       break;
413   }
414   return pos;
415 }
416
417 bool
418 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
419 {
420   *new_pos = get_next_tile(old_pos, direction);
421
422   if (!(new_pos->x >= 0 && new_pos->x < get_width()
423         && new_pos->y >= 0 && new_pos->y < get_height()))
424     { // New position is outsite the tilemap
425       return false;
426     }
427   else
428     { // Check if the tile allows us to go to new_pos
429       int old_tile_data = tile_data_at(old_pos);
430       int new_tile_data = tile_data_at(*new_pos);
431       switch(direction)
432         {
433         case D_WEST:
434           return (old_tile_data & Tile::WORLDMAP_WEST
435               && new_tile_data & Tile::WORLDMAP_EAST);
436
437         case D_EAST:
438           return (old_tile_data & Tile::WORLDMAP_EAST
439               && new_tile_data & Tile::WORLDMAP_WEST);
440
441         case D_NORTH:
442           return (old_tile_data & Tile::WORLDMAP_NORTH
443               && new_tile_data & Tile::WORLDMAP_SOUTH);
444
445         case D_SOUTH:
446           return (old_tile_data & Tile::WORLDMAP_SOUTH
447               && new_tile_data & Tile::WORLDMAP_NORTH);
448
449         case D_NONE:
450           assert(!"path_ok() can't walk if direction is NONE");
451         }
452       return false;
453     }
454 }
455
456 void
457 WorldMap::finished_level(Level* gamelevel)
458 {
459   // TODO use Level* parameter here?
460   LevelTile* level = at_level();
461
462   bool old_level_state = level->solved;
463   level->solved = true;
464   level->sprite->set_action("solved");
465
466   // deal with statistics
467   level->statistics.merge(gamelevel->stats);
468   calculate_total_stats();
469
470   save_state();
471
472   if (old_level_state != level->solved) {
473     // Try to detect the next direction to which we should walk
474     // FIXME: Mostly a hack
475     Direction dir = D_NONE;
476
477     int dirdata = available_directions_at(tux->get_tile_pos());
478     // first, test for crossroads
479     if (dirdata == Tile::WORLDMAP_CNSE ||
480                 dirdata == Tile::WORLDMAP_CNSW ||
481                 dirdata == Tile::WORLDMAP_CNEW ||
482                 dirdata == Tile::WORLDMAP_CSEW ||
483                 dirdata == Tile::WORLDMAP_CNSEW)
484       dir = D_NONE;
485     else if (dirdata & Tile::WORLDMAP_NORTH
486         && tux->back_direction != D_NORTH)
487       dir = D_NORTH;
488     else if (dirdata & Tile::WORLDMAP_SOUTH
489         && tux->back_direction != D_SOUTH)
490       dir = D_SOUTH;
491     else if (dirdata & Tile::WORLDMAP_EAST
492         && tux->back_direction != D_EAST)
493       dir = D_EAST;
494     else if (dirdata & Tile::WORLDMAP_WEST
495         && tux->back_direction != D_WEST)
496       dir = D_WEST;
497
498     if (dir != D_NONE) {
499       tux->set_direction(dir);
500     }
501   }
502
503   if (level->extro_script != "") {
504     try {
505       std::istringstream in(level->extro_script);
506       run_script(in, "worldmap:extro_script");
507     } catch(std::exception& e) {
508       log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
509     }
510   }
511 }
512
513 void
514 WorldMap::update(float delta)
515 {
516   if(!in_level) {
517     Menu* menu = Menu::current();
518     if(menu != NULL) {
519       menu->update();
520
521       if(menu == worldmap_menu.get()) {
522         switch (worldmap_menu->check())
523         {
524           case MNID_RETURNWORLDMAP: // Return to game
525             Menu::set_current(0);
526             break;
527           case MNID_QUITWORLDMAP: // Quit Worldmap
528             main_loop->exit_screen();
529             break;
530         }
531       }
532
533       return;
534     }
535
536     // update GameObjects
537     for(size_t i = 0; i < game_objects.size(); ++i) {
538       GameObject* object = game_objects[i];
539       object->update(delta);
540     }
541
542     // remove old GameObjects
543     for(GameObjects::iterator i = game_objects.begin();
544         i != game_objects.end(); ) {
545       GameObject* object = *i;
546       if(!object->is_valid()) {
547         try_unexpose(object);
548         object->unref();
549         i = game_objects.erase(i);
550       } else {
551         ++i;
552       }
553     }
554
555     /* update solid_tilemaps list */
556     //FIXME: this could be more efficient
557     solid_tilemaps.clear();
558     for(std::vector<GameObject*>::iterator i = game_objects.begin();
559         i != game_objects.end(); ++i)
560     {
561       TileMap* tm = dynamic_cast<TileMap*>(*i);
562       if (!tm) continue;
563       if (tm->is_solid()) solid_tilemaps.push_back(tm);
564     }
565
566     // position "camera"
567     Vector tux_pos = tux->get_pos();
568     camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
569     camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
570
571     if (camera_offset.x < 0)
572       camera_offset.x = 0;
573     if (camera_offset.y < 0)
574       camera_offset.y = 0;
575
576     if (camera_offset.x > (int)get_width()*32 - SCREEN_WIDTH)
577       camera_offset.x = (int)get_width()*32 - SCREEN_WIDTH;
578     if (camera_offset.y > (int)get_height()*32 - SCREEN_HEIGHT)
579       camera_offset.y = (int)get_height()*32 - SCREEN_HEIGHT;
580
581     if (int(get_width()*32) < SCREEN_WIDTH)
582       camera_offset.x = get_width()*16.0 - SCREEN_WIDTH/2.0;
583     if (int(get_height()*32) < SCREEN_HEIGHT)
584       camera_offset.y = get_height()*16.0 - SCREEN_HEIGHT/2.0;
585
586     // handle input
587     bool enter_level = false;
588     if(main_controller->pressed(Controller::ACTION)
589         || main_controller->pressed(Controller::JUMP)
590         || main_controller->pressed(Controller::MENU_SELECT)) {
591       /* some people define UP and JUMP on the same key... */
592       if(!main_controller->pressed(Controller::UP))
593             enter_level = true;
594         }
595     if(main_controller->pressed(Controller::PAUSE_MENU))
596       on_escape_press();
597
598     // check for teleporters
599     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
600     if (teleporter && (teleporter->automatic || (enter_level && (!tux->is_moving())))) {
601       enter_level = false;
602       if (teleporter->worldmap != "") {
603         change(teleporter->worldmap, teleporter->spawnpoint);
604       } else {
605         // TODO: an animation, camera scrolling or a fading would be a nice touch
606         sound_manager->play("sounds/warp.wav");
607         tux->back_direction = D_NONE;
608         move_to_spawnpoint(teleporter->spawnpoint);
609       }
610     }
611
612     // check for auto-play levels
613     LevelTile* level = at_level();
614     if (level && (level->auto_play) && (!level->solved) && (!tux->is_moving())) {
615       enter_level = true;
616     }
617
618     if (enter_level && !tux->is_moving())
619       {
620         /* Check level action */
621         LevelTile* level = at_level();
622         if (!level) {
623           //Respawn if player on a tile with no level and nowhere to go.
624           int tile_data = tile_data_at(tux->get_tile_pos());
625           if(!( tile_data & ( Tile::WORLDMAP_NORTH |  Tile::WORLDMAP_SOUTH | Tile::WORLDMAP_WEST | Tile::WORLDMAP_EAST ))){
626             log_warning << "Player at illegal position " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << " respawning." << std::endl;
627             move_to_spawnpoint("main");
628             return;
629           }
630           log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
631           return;
632         }
633
634         if (level->pos == tux->get_tile_pos()) {
635           try {
636             Vector shrinkpos = Vector(level->pos.x*32 + 16 - camera_offset.x,
637                                       level->pos.y*32 + 16 - camera_offset.y);
638             std::string levelfile = levels_path + level->get_name();
639
640             // update state and savegame
641             save_state();
642
643             main_loop->push_screen(new GameSession(levelfile, &level->statistics),
644                                    new ShrinkFade(shrinkpos, 0.5));
645             in_level = true;
646           } catch(std::exception& e) {
647             log_fatal << "Couldn't load level: " << e.what() << std::endl;
648           }
649         }
650       }
651     else
652       {
653   //      tux->set_direction(input_direction);
654       }
655   }
656 }
657
658 int
659 WorldMap::tile_data_at(Vector p)
660 {
661   int dirs = 0;
662
663   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
664     TileMap* tilemap = *i;
665     const Tile* tile = tilemap->get_tile((int)p.x, (int)p.y);
666     int dirdata = tile->getData();
667     dirs |= dirdata;
668   }
669
670   return dirs;
671 }
672
673 int
674 WorldMap::available_directions_at(Vector p)
675 {
676   return tile_data_at(p) & Tile::WORLDMAP_DIR_MASK;
677 }
678
679 LevelTile*
680 WorldMap::at_level()
681 {
682   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
683     LevelTile* level = *i;
684     if (level->pos == tux->get_tile_pos())
685       return level;
686   }
687
688   return NULL;
689 }
690
691 SpecialTile*
692 WorldMap::at_special_tile()
693 {
694   for(SpecialTiles::iterator i = special_tiles.begin();
695       i != special_tiles.end(); ++i) {
696     SpecialTile* special_tile = *i;
697     if (special_tile->pos == tux->get_tile_pos())
698       return special_tile;
699   }
700
701   return NULL;
702 }
703
704 SpriteChange*
705 WorldMap::at_sprite_change(const Vector& pos)
706 {
707   for(SpriteChanges::iterator i = sprite_changes.begin();
708       i != sprite_changes.end(); ++i) {
709     SpriteChange* sprite_change = *i;
710     if(sprite_change->pos == pos)
711       return sprite_change;
712   }
713
714   return NULL;
715 }
716
717 Teleporter*
718 WorldMap::at_teleporter(const Vector& pos)
719 {
720   for(std::vector<Teleporter*>::iterator i = teleporters.begin(); i != teleporters.end(); ++i) {
721     Teleporter* teleporter = *i;
722     if(teleporter->pos == pos) return teleporter;
723   }
724
725   return NULL;
726 }
727
728 void
729 WorldMap::draw(DrawingContext& context)
730 {
731   if (int(get_width()*32) < SCREEN_WIDTH || int(get_height()*32) < SCREEN_HEIGHT)
732     context.draw_filled_rect(Vector(0, 0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
733       Color(0.0f, 0.0f, 0.0f, 1.0f), LAYER_BACKGROUND0);
734
735   context.set_ambient_color( ambient_light );
736   context.push_transform();
737   context.set_translation(camera_offset);
738
739   for(GameObjects::iterator i = game_objects.begin();
740       i != game_objects.end(); ++i) {
741     GameObject* object = *i;
742     object->draw(context);
743   }
744
745 /*
746   // FIXME: make this a runtime switch similar to draw_collrects/show_collrects?
747   // draw visual indication of possible walk directions
748   static int flipme = 0; 
749   if (flipme++ & 0x04)
750   for (int x = 0; x < get_width(); x++) {
751     for (int y = 0; y < get_height(); y++) {
752       int data = tile_data_at(Vector(x,y));
753       int px = x * 32;
754       int py = y * 32;
755       const int W = 4;
756       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);
757       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);
758       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);
759       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);
760       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);
761       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);
762     }
763   }
764 */
765
766   draw_status(context);
767   context.pop_transform();
768 }
769
770 void
771 WorldMap::draw_status(DrawingContext& context)
772 {
773   context.push_transform();
774   context.set_translation(Vector(0, 0));
775
776   player_status->draw(context);
777
778   if (!tux->is_moving()) {
779     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
780       LevelTile* level = *i;
781
782       if (level->pos == tux->get_tile_pos()) {
783         if(level->title == "")
784           get_level_title(*level);
785
786         context.draw_text(white_text, level->title,
787                           Vector(SCREEN_WIDTH/2,
788                                  SCREEN_HEIGHT - white_text->get_height() - 30),
789                           ALIGN_CENTER, LAYER_FOREGROUND1);
790
791         // if level is solved, draw level picture behind stats
792         /*
793         if (level->solved) {
794           if (const Surface* picture = level->get_picture()) {
795             Vector pos = Vector(SCREEN_WIDTH - picture->get_width(), SCREEN_HEIGHT - picture->get_height());
796             context.push_transform();
797             context.set_alpha(0.5);
798             context.draw_surface(picture, pos, LAYER_FOREGROUND1-1);
799             context.pop_transform();
800           }
801         }
802         */
803
804         level->statistics.draw_worldmap_info(context);
805         break;
806       }
807     }
808
809     for(SpecialTiles::iterator i = special_tiles.begin();
810         i != special_tiles.end(); ++i) {
811       SpecialTile* special_tile = *i;
812
813       if (special_tile->pos == tux->get_tile_pos()) {
814         /* Display an in-map message in the map, if any as been selected */
815         if(!special_tile->map_message.empty() && !special_tile->passive_message)
816           context.draw_text(gold_text, special_tile->map_message,
817               Vector(SCREEN_WIDTH/2,
818                 SCREEN_HEIGHT - white_text->get_height() - 60),
819               ALIGN_CENTER, LAYER_FOREGROUND1);
820         break;
821       }
822     }
823
824     // display teleporter messages
825     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
826     if (teleporter && (teleporter->message != "")) {
827       Vector pos = Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 30);
828       context.draw_text(white_text, teleporter->message, pos, ALIGN_CENTER, LAYER_FOREGROUND1);
829     }
830
831   }
832
833   /* Display a passive message in the map, if needed */
834   if(passive_message_timer.started())
835     context.draw_text(gold_text, passive_message,
836             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
837             ALIGN_CENTER, LAYER_FOREGROUND1);
838
839   context.pop_transform();
840 }
841
842 void
843 WorldMap::setup()
844 {
845   sound_manager->play_music(music);
846   Menu::set_current(NULL);
847
848   current_ = this;
849   load_state();
850
851   // if force_spawnpoint was set, move Tux there, then clear force_spawnpoint
852   if (force_spawnpoint != "") {
853     move_to_spawnpoint(force_spawnpoint);
854     force_spawnpoint = "";
855   }
856
857   tux->setup();
858
859   // register worldmap_table as worldmap in scripting
860   using namespace Scripting;
861
862   sq_pushroottable(global_vm);
863   sq_pushstring(global_vm, "worldmap", -1);
864   sq_pushobject(global_vm, worldmap_table);
865   if(SQ_FAILED(sq_createslot(global_vm, -3)))
866     throw SquirrelError(global_vm, "Couldn't set worldmap in roottable");
867   sq_pop(global_vm, 1);
868
869   if(init_script != "") {
870     std::istringstream in(init_script);
871     run_script(in, "WorldMap::init");
872   }
873 }
874
875 void
876 WorldMap::leave()
877 {
878   // remove worldmap_table from roottable
879   using namespace Scripting;
880
881   sq_pushroottable(global_vm);
882   sq_pushstring(global_vm, "worldmap", -1);
883   if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
884     throw SquirrelError(global_vm, "Couldn't unset worldmap in roottable");
885   sq_pop(global_vm, 1);
886 }
887
888 static void store_float(HSQUIRRELVM vm, const char* name, float val)
889 {
890   sq_pushstring(vm, name, -1);
891   sq_pushfloat(vm, val);
892   if(SQ_FAILED(sq_createslot(vm, -3)))
893     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
894 }
895
896 /*
897 static void store_int(HSQUIRRELVM vm, const char* name, int val)
898 {
899   sq_pushstring(vm, name, -1);
900   sq_pushinteger(vm, val);
901   if(SQ_FAILED(sq_createslot(vm, -3)))
902     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
903 }
904 */
905
906 static void store_string(HSQUIRRELVM vm, const char* name, const std::string& val)
907 {
908   sq_pushstring(vm, name, -1);
909   sq_pushstring(vm, val.c_str(), val.length());
910   if(SQ_FAILED(sq_createslot(vm, -3)))
911     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
912 }
913
914 static void store_bool(HSQUIRRELVM vm, const char* name, bool val)
915 {
916   sq_pushstring(vm, name, -1);
917   sq_pushbool(vm, val ? SQTrue : SQFalse);
918   if(SQ_FAILED(sq_createslot(vm, -3)))
919     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
920 }
921
922 static float read_float(HSQUIRRELVM vm, const char* name)
923 {
924   sq_pushstring(vm, name, -1);
925   if(SQ_FAILED(sq_get(vm, -2))) {
926     std::ostringstream msg;
927     msg << "Couldn't get float value for '" << name << "' from table";
928     throw Scripting::SquirrelError(vm, msg.str());
929   }
930
931   float result;
932   if(SQ_FAILED(sq_getfloat(vm, -1, &result))) {
933     std::ostringstream msg;
934     msg << "Couldn't get float value for '" << name << "' from table";
935     throw Scripting::SquirrelError(vm, msg.str());
936   }
937   sq_pop(vm, 1);
938
939   return result;
940 }
941
942 static std::string read_string(HSQUIRRELVM vm, const char* name)
943 {
944   sq_pushstring(vm, name, -1);
945   if(SQ_FAILED(sq_get(vm, -2))) {
946     std::ostringstream msg;
947     msg << "Couldn't get string value for '" << name << "' from table";
948     throw Scripting::SquirrelError(vm, msg.str());
949   }
950
951   const char* result;
952   if(SQ_FAILED(sq_getstring(vm, -1, &result))) {
953     std::ostringstream msg;
954     msg << "Couldn't get string value for '" << name << "' from table";
955     throw Scripting::SquirrelError(vm, msg.str());
956   }
957   sq_pop(vm, 1);
958
959   return std::string(result);
960 }
961
962 static bool read_bool(HSQUIRRELVM vm, const char* name)
963 {
964   sq_pushstring(vm, name, -1);
965   if(SQ_FAILED(sq_get(vm, -2))) {
966     std::ostringstream msg;
967     msg << "Couldn't get bool value for '" << name << "' from table";
968     throw Scripting::SquirrelError(vm, msg.str());
969   }
970
971   SQBool result;
972   if(SQ_FAILED(sq_getbool(vm, -1, &result))) {
973     std::ostringstream msg;
974     msg << "Couldn't get bool value for '" << name << "' from table";
975     throw Scripting::SquirrelError(vm, msg.str());
976   }
977   sq_pop(vm, 1);
978
979   return result == SQTrue;
980 }
981
982 void
983 WorldMap::save_state()
984 {
985   using namespace Scripting;
986
987   HSQUIRRELVM vm = global_vm;
988   int oldtop = sq_gettop(vm);
989
990   try {
991     // get state table
992     sq_pushroottable(vm);
993     sq_pushstring(vm, "state", -1);
994     if(SQ_FAILED(sq_get(vm, -2)))
995       throw Scripting::SquirrelError(vm, "Couldn't get state table");
996
997     // get or create worlds table
998     sq_pushstring(vm, "worlds", -1);
999     if(SQ_FAILED(sq_get(vm, -2))) {
1000       sq_pushstring(vm, "worlds", -1);
1001       sq_newtable(vm);
1002       if(SQ_FAILED(sq_createslot(vm, -3)))
1003         throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
1004
1005       sq_pushstring(vm, "worlds", -1);
1006       if(SQ_FAILED(sq_get(vm, -2)))
1007         throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
1008     }
1009
1010     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1011     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
1012       sq_pop(vm, 1);
1013
1014     // construct new table for this worldmap
1015     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1016     sq_newtable(vm);
1017
1018     // store tux
1019     sq_pushstring(vm, "tux", -1);
1020     sq_newtable(vm);
1021
1022     store_float(vm, "x", tux->get_tile_pos().x);
1023     store_float(vm, "y", tux->get_tile_pos().y);
1024     store_string(vm, "back", direction_to_string(tux->back_direction));
1025
1026     sq_createslot(vm, -3);
1027
1028     // levels...
1029     sq_pushstring(vm, "levels", -1);
1030     sq_newtable(vm);
1031
1032     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1033       LevelTile* level = *i;
1034
1035           sq_pushstring(vm, level->get_name().c_str(), -1);
1036           sq_newtable(vm);
1037
1038           store_bool(vm, "solved", level->solved);
1039           // TODO write statistics
1040           // i->statistics.write(writer);
1041
1042           sq_createslot(vm, -3);
1043     }
1044
1045     sq_createslot(vm, -3);
1046
1047     // push world into worlds table
1048     sq_createslot(vm, -3);
1049   } catch(std::exception& ) {
1050     sq_settop(vm, oldtop);
1051   }
1052
1053   sq_settop(vm, oldtop);
1054
1055   if(World::current() != NULL)
1056     World::current()->save_state();
1057 }
1058
1059 void
1060 WorldMap::load_state()
1061 {
1062   using namespace Scripting;
1063
1064   HSQUIRRELVM vm = global_vm;
1065   int oldtop = sq_gettop(vm);
1066
1067   try {
1068     // get state table
1069     sq_pushroottable(vm);
1070     sq_pushstring(vm, "state", -1);
1071     if(SQ_FAILED(sq_get(vm, -2)))
1072       throw Scripting::SquirrelError(vm, "Couldn't get state table");
1073
1074     // get worlds table
1075     sq_pushstring(vm, "worlds", -1);
1076     if(SQ_FAILED(sq_get(vm, -2)))
1077       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
1078
1079     // get table for our world
1080     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1081     if(SQ_FAILED(sq_get(vm, -2)))
1082       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds.mapfilename");
1083
1084     // load tux
1085     sq_pushstring(vm, "tux", -1);
1086     if(SQ_FAILED(sq_get(vm, -2)))
1087       throw Scripting::SquirrelError(vm, "Couldn't get tux");
1088
1089     Vector p;
1090     p.x = read_float(vm, "x");
1091     p.y = read_float(vm, "y");
1092     std::string back_str = read_string(vm, "back");
1093     tux->back_direction = string_to_direction(back_str);
1094     tux->set_tile_pos(p);
1095
1096     sq_pop(vm, 1);
1097
1098     // load levels
1099     sq_pushstring(vm, "levels", -1);
1100     if(SQ_FAILED(sq_get(vm, -2)))
1101       throw Scripting::SquirrelError(vm, "Couldn't get levels");
1102
1103     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1104       LevelTile* level = *i;
1105       sq_pushstring(vm, level->get_name().c_str(), -1);
1106       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
1107         level->solved = read_bool(vm, "solved");
1108         level->sprite->set_action(level->solved ? "solved" : "default");
1109         // i->statistics.parse(*level);
1110         sq_pop(vm, 1);
1111       }
1112     }
1113     sq_pop(vm, 1);
1114
1115   } catch(std::exception& e) {
1116     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
1117   }
1118   sq_settop(vm, oldtop);
1119
1120   in_level = false;
1121 }
1122
1123 size_t
1124 WorldMap::level_count()
1125 {
1126   return levels.size();
1127 }
1128
1129 size_t
1130 WorldMap::solved_level_count()
1131 {
1132   size_t count = 0;
1133   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1134     LevelTile* level = *i;
1135
1136     if(level->solved)
1137       count++;
1138   }
1139
1140   return count;
1141 }
1142
1143 HSQUIRRELVM
1144 WorldMap::run_script(std::istream& in, const std::string& sourcename)
1145 {
1146   using namespace Scripting;
1147
1148   // garbage collect thread list
1149   for(ScriptList::iterator i = scripts.begin();
1150       i != scripts.end(); ) {
1151     HSQOBJECT& object = *i;
1152     HSQUIRRELVM vm = object_to_vm(object);
1153
1154     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
1155       sq_release(global_vm, &object);
1156       i = scripts.erase(i);
1157       continue;
1158     }
1159
1160     ++i;
1161   }
1162
1163   HSQOBJECT object = create_thread(global_vm);
1164   scripts.push_back(object);
1165
1166   HSQUIRRELVM vm = object_to_vm(object);
1167
1168   // set worldmap_table as roottable for the thread
1169   sq_pushobject(vm, worldmap_table);
1170   sq_setroottable(vm);
1171
1172   compile_and_run(vm, in, sourcename);
1173
1174   return vm;
1175 }
1176
1177 float
1178 WorldMap::get_width() const
1179 {
1180   float width = 0;
1181   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1182     TileMap* solids = *i;
1183     if (solids->get_width() > width) width = solids->get_width();
1184   }
1185   return width;
1186 }
1187
1188 float
1189 WorldMap::get_height() const
1190 {
1191   float height = 0;
1192   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1193     TileMap* solids = *i;
1194     if (solids->get_height() > height) height = solids->get_height();
1195   }
1196   return height;
1197 }
1198
1199 } // namespace WorldMapNS