Removed a global variable
[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 "video/surface.hpp"
37 #include "video/screen.hpp"
38 #include "video/drawing_context.hpp"
39 #include "sprite/sprite_manager.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "lisp/parser.hpp"
42 #include "lisp/lisp.hpp"
43 #include "lisp/list_iterator.hpp"
44 #include "lisp/writer.hpp"
45 #include "game_session.hpp"
46 #include "sector.hpp"
47 #include "worldmap.hpp"
48 #include "resources.hpp"
49 #include "log.hpp"
50 #include "world.hpp"
51 #include "player_status.hpp"
52 #include "textscroller.hpp"
53 #include "main.hpp"
54 #include "spawn_point.hpp"
55 #include "file_system.hpp"
56 #include "gui/menu.hpp"
57 #include "gui/mousecursor.hpp"
58 #include "control/joystickkeyboardcontroller.hpp"
59 #include "object/background.hpp"
60 #include "object/tilemap.hpp"
61 #include "script_manager.hpp"
62 #include "options_menu.hpp"
63 #include "scripting/squirrel_error.hpp"
64 #include "scripting/wrapper_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
127     return D_NONE;
128 }
129
130 //---------------------------------------------------------------------------
131
132 WorldMap::WorldMap(const std::string& filename)
133   : tux(0), solids(0)
134 {
135   tile_manager.reset(new TileManager("images/worldmap.strf"));
136   
137   tux = new Tux(this);
138   add_object(tux);
139     
140   name = "<no title>";
141   music = "music/salcon.ogg";
142
143   total_stats.reset();
144
145   worldmap_menu.reset(new Menu());
146   worldmap_menu->add_label(_("Pause"));
147   worldmap_menu->add_hl();
148   worldmap_menu->add_entry(MNID_RETURNWORLDMAP, _("Continue"));
149   worldmap_menu->add_submenu(_("Options"), get_options_menu());
150   worldmap_menu->add_hl();
151   worldmap_menu->add_entry(MNID_QUITWORLDMAP, _("Quit World"));
152
153   load(filename);
154 }
155
156 WorldMap::~WorldMap()
157 {
158   if(current_ == this)
159     current_ = NULL;
160
161   for(GameObjects::iterator i = game_objects.begin();
162       i != game_objects.end(); ++i)
163     delete *i;
164
165   for(SpawnPoints::iterator i = spawn_points.begin();
166       i != spawn_points.end(); ++i) {
167     delete *i;
168   }
169 }
170
171 void
172 WorldMap::add_object(GameObject* object)
173 {
174   TileMap* tilemap = dynamic_cast<TileMap*> (object);
175   if(tilemap != 0 && tilemap->is_solid()) {
176     solids = tilemap;
177   }
178
179   game_objects.push_back(object);
180 }
181
182 void
183 WorldMap::load(const std::string& filename)
184 {
185   map_filename = filename;
186   levels_path = FileSystem::dirname(map_filename);
187
188   try {
189     lisp::Parser parser;
190     std::auto_ptr<lisp::Lisp> root (parser.parse(map_filename));
191
192     const lisp::Lisp* lisp = root->get_lisp("supertux-level");
193     if(!lisp)
194       throw std::runtime_error("file isn't a supertux-level file.");
195
196     lisp->get("name", name);
197     
198     const lisp::Lisp* sector = lisp->get_lisp("sector");
199     if(!sector)
200       throw std::runtime_error("No sector sepcified in worldmap file.");
201     
202     lisp::ListIterator iter(sector);
203     while(iter.next()) {
204       if(iter.item() == "tilemap") {
205         add_object(new TileMap(*(iter.lisp()), tile_manager.get()));
206       } else if(iter.item() == "background") {
207         add_object(new Background(*(iter.lisp())));
208       } else if(iter.item() == "music") {
209         iter.value()->get(music);
210       } else if(iter.item() == "worldmap-spawnpoint") {
211         SpawnPoint* sp = new SpawnPoint(iter.lisp());
212         spawn_points.push_back(sp);
213       } else if(iter.item() == "level") {
214         LevelTile* level = new LevelTile(levels_path, iter.lisp());
215         levels.push_back(level);
216         game_objects.push_back(level);
217       } else if(iter.item() == "special-tile") {
218         SpecialTile* special_tile = new SpecialTile(iter.lisp());
219         special_tiles.push_back(special_tile);
220         game_objects.push_back(special_tile);
221       } else if(iter.item() == "sprite-change") {
222         SpriteChange* sprite_change = new SpriteChange(iter.lisp());
223         sprite_changes.push_back(sprite_change);
224         game_objects.push_back(sprite_change);
225       } else if(iter.item() == "name") {
226         // skip
227       } else {
228         log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
229       }
230     }
231     if(solids == 0)
232       throw std::runtime_error("No solid tilemap specified");
233
234     // search for main spawnpoint
235     for(SpawnPoints::iterator i = spawn_points.begin();
236         i != spawn_points.end(); ++i) {
237       SpawnPoint* sp = *i;
238       if(sp->name == "main") {
239         Vector p = sp->pos;
240         tux->set_tile_pos(p);
241         break;
242       }
243     }
244
245   } catch(std::exception& e) {
246     std::stringstream msg;
247     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
248       e.what();
249     throw std::runtime_error(msg.str());
250   }
251 }
252
253 void
254 WorldMap::get_level_title(LevelTile& level)
255 {
256   /** get special_tile's title */
257   level.title = "<no title>";
258
259   try {
260     lisp::Parser parser;
261     std::auto_ptr<lisp::Lisp> root (parser.parse(levels_path + level.name));
262
263     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
264     if(!level_lisp)
265       return;
266     
267     level_lisp->get("name", level.title);
268   } catch(std::exception& e) {
269     log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
270     return;
271   }
272 }
273
274 void WorldMap::calculate_total_stats()
275 {
276   total_stats.reset();
277   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
278     LevelTile* level = *i;
279     if (level->solved) {
280       total_stats += level->statistics;
281     }
282   }
283 }
284
285 void
286 WorldMap::on_escape_press()
287 {
288   // Show or hide the menu
289   if(!Menu::current()) {
290     Menu::set_current(worldmap_menu.get());
291     tux->set_direction(D_NONE);  // stop tux movement when menu is called
292   } else {
293     Menu::set_current(NULL);
294   }
295 }
296
297 Vector
298 WorldMap::get_next_tile(Vector pos, Direction direction)
299 {
300   switch(direction) {
301     case D_WEST:
302       pos.x -= 1;
303       break;
304     case D_EAST:
305       pos.x += 1;
306       break;
307     case D_NORTH:
308       pos.y -= 1;
309       break;
310     case D_SOUTH:
311       pos.y += 1;
312       break;
313     case D_NONE:
314       break;
315   }
316   return pos;
317 }
318
319 bool
320 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
321 {
322   *new_pos = get_next_tile(old_pos, direction);
323
324   if (!(new_pos->x >= 0 && new_pos->x < solids->get_width()
325         && new_pos->y >= 0 && new_pos->y < solids->get_height()))
326     { // New position is outsite the tilemap
327       return false;
328     }
329   else
330     { // Check if the tile allows us to go to new_pos
331       switch(direction)
332         {
333         case D_WEST:
334           return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
335               && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
336
337         case D_EAST:
338           return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
339               && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
340
341         case D_NORTH:
342           return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
343               && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
344
345         case D_SOUTH:
346           return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
347               && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
348
349         case D_NONE:
350           assert(!"path_ok() can't walk if direction is NONE");
351         }
352       return false;
353     }
354 }
355
356 void
357 WorldMap::finished_level(Level* gamelevel)
358 {
359   // TODO use Level* parameter here?
360   LevelTile* level = at_level();
361
362   bool old_level_state = level->solved;
363   level->solved = true;
364   level->sprite->set_action("solved");
365
366   // deal with statistics
367   level->statistics.merge(gamelevel->stats);
368   calculate_total_stats();
369
370   save_state();
371   if(World::current() != NULL)
372     World::current()->save_state();
373
374   if (old_level_state != level->solved && level->auto_path) {
375     // Try to detect the next direction to which we should walk
376     // FIXME: Mostly a hack
377     Direction dir = D_NONE;
378   
379     const Tile* tile = at(tux->get_tile_pos());
380
381     // first, test for crossroads
382     if (tile->getData() & Tile::WORLDMAP_CNSE || tile->getData() && Tile::WORLDMAP_CNSW
383      || tile->getData() & Tile::WORLDMAP_CNEW || tile->getData() && Tile::WORLDMAP_CSEW
384      || tile->getData() & Tile::WORLDMAP_CNSEW)
385       dir = D_NONE;
386     else if (tile->getData() & Tile::WORLDMAP_NORTH
387         && tux->back_direction != D_NORTH)
388       dir = D_NORTH;
389     else if (tile->getData() & Tile::WORLDMAP_SOUTH
390         && tux->back_direction != D_SOUTH)
391       dir = D_SOUTH;
392     else if (tile->getData() & Tile::WORLDMAP_EAST
393         && tux->back_direction != D_EAST)
394       dir = D_EAST;
395     else if (tile->getData() & Tile::WORLDMAP_WEST
396         && tux->back_direction != D_WEST)
397       dir = D_WEST;
398
399     if (dir != D_NONE) {
400       tux->set_direction(dir);
401     }
402   }
403
404   if (level->extro_script != "") {
405     try {
406       HSQUIRRELVM vm = ScriptManager::instance->create_thread();
407
408       std::istringstream in(level->extro_script);
409       Scripting::compile_and_run(vm, in, "worldmap,extro_script");
410     } catch(std::exception& e) {
411       log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
412     }
413   }
414 }
415
416 void
417 WorldMap::update(float delta)
418 {
419   Menu* menu = Menu::current();
420   if(menu != NULL) {
421     menu->update();
422
423     if(menu == worldmap_menu.get()) {
424       switch (worldmap_menu->check())
425       {
426         case MNID_RETURNWORLDMAP: // Return to game  
427           Menu::set_current(0);
428           break;
429         case MNID_QUITWORLDMAP: // Quit Worldmap
430           main_loop->exit_screen();
431           break;
432       }
433     }
434
435     return;
436   }
437
438   // update GameObjects
439   for(GameObjects::iterator i = game_objects.begin();
440       i != game_objects.end(); ++i) {
441     GameObject* object = *i;
442     object->update(delta);
443   }
444
445   // remove old GameObjects
446   for(GameObjects::iterator i = game_objects.begin();
447       i != game_objects.end(); ) {
448     GameObject* object = *i;
449     if(!object->is_valid()) {
450       delete object;
451       i = game_objects.erase(i);
452     } else {
453       ++i;
454     }
455   }
456
457   // position "camera"
458   Vector tux_pos = tux->get_pos();
459   camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
460   camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
461
462   if (camera_offset.x < 0)
463     camera_offset.x = 0;
464   if (camera_offset.y < 0)
465     camera_offset.y = 0;
466
467   if (camera_offset.x > solids->get_width()*32 - SCREEN_WIDTH)
468     camera_offset.x = solids->get_width()*32 - SCREEN_WIDTH;
469   if (camera_offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
470     camera_offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
471
472   // handle input
473   bool enter_level = false;
474   if(main_controller->pressed(Controller::ACTION)
475       || main_controller->pressed(Controller::JUMP)
476       || main_controller->pressed(Controller::MENU_SELECT))
477     enter_level = true;
478   if(main_controller->pressed(Controller::PAUSE_MENU))
479     on_escape_press();
480   
481   if (enter_level && !tux->is_moving())
482     {
483       /* Check special tile action */
484       SpecialTile* special_tile = at_special_tile();
485       if(special_tile)
486         {
487         if (special_tile->teleport_dest != Vector(-1,-1))
488           {
489           // TODO: an animation, camera scrolling or a fading would be a nice touch
490           sound_manager->play("sounds/warp.wav");
491           tux->back_direction = D_NONE;
492           tux->set_tile_pos(special_tile->teleport_dest);
493           SDL_Delay(1000);
494           }
495         }
496
497       /* Check level action */
498       LevelTile* level = at_level();
499       if (!level) {
500         log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
501         return;
502       }
503
504       if (level->pos == tux->get_tile_pos()) {
505         // do a shriking fade to the level
506         shrink_fade(Vector((level->pos.x*32 + 16 + camera_offset.x),
507                            (level->pos.y*32 + 16 + camera_offset.y)), 500);
508
509         try {
510           main_loop->push_screen(new GameSession(
511                 levels_path + level->name, &level->statistics));
512         } catch(std::exception& e) {
513           log_fatal << "Couldn't load level: " << e.what() << std::endl;
514         }
515       }
516     }
517   else
518     {
519 //      tux->set_direction(input_direction);
520     }
521 }
522
523 const Tile*
524 WorldMap::at(Vector p)
525 {
526   return solids->get_tile((int) p.x, (int) p.y);
527 }
528
529 LevelTile*
530 WorldMap::at_level()
531 {
532   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
533     LevelTile* level = *i;
534     if (level->pos == tux->get_tile_pos())
535       return level;
536   }
537
538   return NULL;
539 }
540
541 SpecialTile*
542 WorldMap::at_special_tile()
543 {
544   for(SpecialTiles::iterator i = special_tiles.begin();
545       i != special_tiles.end(); ++i) {
546     SpecialTile* special_tile = *i;
547     if (special_tile->pos == tux->get_tile_pos())
548       return special_tile; 
549   }
550
551   return NULL;
552 }
553
554 SpriteChange*
555 WorldMap::at_sprite_change(const Vector& pos)
556 {
557   for(SpriteChanges::iterator i = sprite_changes.begin();
558       i != sprite_changes.end(); ++i) {
559     SpriteChange* sprite_change = *i;
560     if(sprite_change->pos == pos)
561       return sprite_change;
562   }
563
564   return NULL;
565 }
566
567 void
568 WorldMap::draw(DrawingContext& context)
569 {
570   context.push_transform();
571   context.set_translation(camera_offset);
572   
573   for(GameObjects::iterator i = game_objects.begin();
574       i != game_objects.end(); ++i) {
575     GameObject* object = *i;
576     object->draw(context);
577   }
578   
579   draw_status(context);
580   context.pop_transform();
581 }
582
583 void
584 WorldMap::draw_status(DrawingContext& context)
585 {
586   context.push_transform();
587   context.set_translation(Vector(0, 0));
588  
589   player_status->draw(context);
590
591   if (!tux->is_moving()) {
592     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
593       LevelTile* level = *i;
594       
595       if (level->pos == tux->get_tile_pos()) {
596         if(level->title == "")
597           get_level_title(*level);
598
599         context.draw_text(white_text, level->title,
600             Vector(SCREEN_WIDTH/2,
601               SCREEN_HEIGHT - white_text->get_height() - 30),
602             CENTER_ALLIGN, LAYER_FOREGROUND1);
603         
604         level->statistics.draw_worldmap_info(context);
605         break;
606       }
607     }
608
609     for(SpecialTiles::iterator i = special_tiles.begin();
610         i != special_tiles.end(); ++i) {
611       SpecialTile* special_tile = *i;
612       
613       if (special_tile->pos == tux->get_tile_pos()) {
614         /* Display an in-map message in the map, if any as been selected */
615         if(!special_tile->map_message.empty() && !special_tile->passive_message)
616           context.draw_text(gold_text, special_tile->map_message, 
617               Vector(SCREEN_WIDTH/2,
618                 SCREEN_HEIGHT - white_text->get_height() - 60),
619               CENTER_ALLIGN, LAYER_FOREGROUND1);
620         break;
621       }
622     }
623   }
624   
625   /* Display a passive message in the map, if needed */
626   if(passive_message_timer.started())
627     context.draw_text(gold_text, passive_message, 
628             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
629             CENTER_ALLIGN, LAYER_FOREGROUND1);
630
631   context.pop_transform();
632 }
633
634 void
635 WorldMap::setup()
636 {
637   sound_manager->play_music(music);
638   Menu::set_current(NULL);
639
640   current_ = this;
641   load_state();
642 }
643
644 static void store_float(HSQUIRRELVM vm, const char* name, float val)
645 {
646   sq_pushstring(vm, name, -1);
647   sq_pushfloat(vm, val);
648   if(SQ_FAILED(sq_createslot(vm, -3)))
649     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
650 }
651
652 /*
653 static void store_int(HSQUIRRELVM vm, const char* name, int val)
654 {
655   sq_pushstring(vm, name, -1);
656   sq_pushinteger(vm, val);
657   if(SQ_FAILED(sq_createslot(vm, -3)))
658     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
659 }
660 */
661
662 static void store_string(HSQUIRRELVM vm, const char* name, const std::string& val)
663 {
664   sq_pushstring(vm, name, -1);
665   sq_pushstring(vm, val.c_str(), val.length());
666   if(SQ_FAILED(sq_createslot(vm, -3)))
667     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
668 }
669
670 static void store_bool(HSQUIRRELVM vm, const char* name, bool val)
671 {
672   sq_pushstring(vm, name, -1);
673   sq_pushbool(vm, val ? SQTrue : SQFalse);
674   if(SQ_FAILED(sq_createslot(vm, -3)))
675     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
676 }
677
678 static float read_float(HSQUIRRELVM vm, const char* name)
679 {
680   sq_pushstring(vm, name, -1);
681   if(SQ_FAILED(sq_get(vm, -2))) {
682     std::ostringstream msg;
683     msg << "Couldn't get float value for '" << name << "' from table";
684     throw Scripting::SquirrelError(vm, msg.str());
685   }
686   
687   float result;
688   if(SQ_FAILED(sq_getfloat(vm, -1, &result))) {
689     std::ostringstream msg;
690     msg << "Couldn't get float value for '" << name << "' from table";
691     throw Scripting::SquirrelError(vm, msg.str());
692   }
693   sq_pop(vm, 1);
694
695   return result;
696 }
697
698 static std::string read_string(HSQUIRRELVM vm, const char* name)
699 {
700   sq_pushstring(vm, name, -1);
701   if(SQ_FAILED(sq_get(vm, -2))) {
702     std::ostringstream msg;
703     msg << "Couldn't get string value for '" << name << "' from table";
704     throw Scripting::SquirrelError(vm, msg.str());
705   }
706   
707   const char* result;
708   if(SQ_FAILED(sq_getstring(vm, -1, &result))) {
709     std::ostringstream msg;
710     msg << "Couldn't get string value for '" << name << "' from table";
711     throw Scripting::SquirrelError(vm, msg.str());
712   }
713   sq_pop(vm, 1);
714
715   return std::string(result);
716 }
717
718 static bool read_bool(HSQUIRRELVM vm, const char* name)
719 {
720   sq_pushstring(vm, name, -1);
721   if(SQ_FAILED(sq_get(vm, -2))) {
722     std::ostringstream msg;
723     msg << "Couldn't get bool value for '" << name << "' from table";
724     throw Scripting::SquirrelError(vm, msg.str());
725   } 
726   
727   SQBool result;
728   if(SQ_FAILED(sq_getbool(vm, -1, &result))) {
729     std::ostringstream msg;
730     msg << "Couldn't get bool value for '" << name << "' from table";
731     throw Scripting::SquirrelError(vm, msg.str());
732   }
733   sq_pop(vm, 1);
734
735   return result == SQTrue;
736 }
737
738 void
739 WorldMap::save_state()
740 {
741   HSQUIRRELVM vm = ScriptManager::instance->get_vm();
742   int oldtop = sq_gettop(vm);
743
744   try {
745     // get state table
746     sq_pushroottable(vm);
747     sq_pushstring(vm, "state", -1);
748     if(SQ_FAILED(sq_get(vm, -2)))
749       throw Scripting::SquirrelError(vm, "Couldn't get state table");
750
751     // get or create worlds table
752     sq_pushstring(vm, "worlds", -1);
753     if(SQ_FAILED(sq_get(vm, -2))) {
754       sq_pushstring(vm, "worlds", -1);
755       sq_newtable(vm);
756       if(SQ_FAILED(sq_createslot(vm, -3)))
757         throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
758
759       sq_pushstring(vm, "worlds", -1);
760       if(SQ_FAILED(sq_get(vm, -2)))
761         throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
762     }
763     
764     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
765     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
766       sq_pop(vm, 1);
767
768     // construct new table for this worldmap
769     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
770     sq_newtable(vm);
771
772     // store tux
773     sq_pushstring(vm, "tux", -1);
774     sq_newtable(vm);
775     
776     store_float(vm, "x", tux->get_tile_pos().x);
777     store_float(vm, "y", tux->get_tile_pos().y);
778     store_string(vm, "back", direction_to_string(tux->back_direction));
779
780     sq_createslot(vm, -3);
781     
782     // levels...
783     sq_pushstring(vm, "levels", -1);
784     sq_newtable(vm);
785
786     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
787       LevelTile* level = *i;
788       
789       if (level->solved) {
790         sq_pushstring(vm, level->name.c_str(), -1);
791         sq_newtable(vm);
792
793         store_bool(vm, "solved", true);            
794         // TODO write statistics
795         // i->statistics.write(writer);
796
797         sq_createslot(vm, -3);
798       }
799     }
800     
801     sq_createslot(vm, -3);
802
803     // push world into worlds table
804     sq_createslot(vm, -3);
805   } catch(std::exception& e) {
806     sq_settop(vm, oldtop);
807   }
808
809   sq_settop(vm, oldtop);
810 }
811
812 void
813 WorldMap::load_state()
814 {
815   HSQUIRRELVM vm = ScriptManager::instance->get_vm();
816   int oldtop = sq_gettop(vm);
817  
818   try {
819     // get state table
820     sq_pushroottable(vm);
821     sq_pushstring(vm, "state", -1);
822     if(SQ_FAILED(sq_get(vm, -2)))
823       throw Scripting::SquirrelError(vm, "Couldn't get state table");
824
825     // get worlds table
826     sq_pushstring(vm, "worlds", -1);
827     if(SQ_FAILED(sq_get(vm, -2)))
828       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
829
830     // get table for our world
831     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
832     if(SQ_FAILED(sq_get(vm, -2)))
833       throw Scripting::SquirrelError(vm, "Couldn't get state.world.mapfilename");
834
835     // load tux
836     sq_pushstring(vm, "tux", -1);
837     if(SQ_FAILED(sq_get(vm, -2)))
838       throw Scripting::SquirrelError(vm, "Couldn't get tux");
839
840     Vector p;
841     p.x = read_float(vm, "x");
842     p.y = read_float(vm, "y");
843     std::string back_str = read_string(vm, "back");
844     tux->back_direction = string_to_direction(back_str);
845     tux->set_tile_pos(p);
846
847     sq_pop(vm, 1);
848
849     // load levels
850     sq_pushstring(vm, "levels", -1);
851     if(SQ_FAILED(sq_get(vm, -2)))
852       throw Scripting::SquirrelError(vm, "Couldn't get levels");
853
854     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
855       LevelTile* level = *i;
856       sq_pushstring(vm, level->name.c_str(), -1);
857       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
858         level->solved = read_bool(vm, "solved");
859         level->sprite->set_action(level->solved ? "solved" : "default");
860         // i->statistics.parse(*level);
861         sq_pop(vm, 1);
862       }
863     }
864     sq_pop(vm, 1);
865
866   } catch(std::exception& e) {
867     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
868   }
869   sq_settop(vm, oldtop);
870 }
871
872 size_t
873 WorldMap::level_count()
874 {
875   return levels.size();
876 }
877
878 size_t
879 WorldMap::solved_level_count()
880 {
881   size_t count = 0;
882   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
883     LevelTile* level = *i;
884     
885     if(level->solved)
886       count++;
887   }
888
889   return count;
890 }
891     
892 } // namespace WorldMapNS