the boat works now
[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         Level* level = new Level(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(Level& 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(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
278     Level* 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(const std::string& filename)
358 {
359   // TODO calculate level from filename?
360   (void) filename;
361   Level* level = at_level();
362
363   bool old_level_state = level->solved;
364   level->solved = true;
365   level->sprite->set_action("solved");
366
367   // deal with statistics
368   level->statistics.merge(global_stats);
369   calculate_total_stats();
370
371   save_state();
372   if(World::current() != NULL)
373     World::current()->save_state();
374
375   if (old_level_state != level->solved && level->auto_path) {
376     // Try to detect the next direction to which we should walk
377     // FIXME: Mostly a hack
378     Direction dir = D_NONE;
379   
380     const Tile* tile = at(tux->get_tile_pos());
381
382     // first, test for crossroads
383     if (tile->getData() & Tile::WORLDMAP_CNSE || tile->getData() && Tile::WORLDMAP_CNSW
384      || tile->getData() & Tile::WORLDMAP_CNEW || tile->getData() && Tile::WORLDMAP_CSEW
385      || tile->getData() & Tile::WORLDMAP_CNSEW)
386       dir = D_NONE;
387     else if (tile->getData() & Tile::WORLDMAP_NORTH
388         && tux->back_direction != D_NORTH)
389       dir = D_NORTH;
390     else if (tile->getData() & Tile::WORLDMAP_SOUTH
391         && tux->back_direction != D_SOUTH)
392       dir = D_SOUTH;
393     else if (tile->getData() & Tile::WORLDMAP_EAST
394         && tux->back_direction != D_EAST)
395       dir = D_EAST;
396     else if (tile->getData() & Tile::WORLDMAP_WEST
397         && tux->back_direction != D_WEST)
398       dir = D_WEST;
399
400     if (dir != D_NONE) {
401       tux->set_direction(dir);
402     }
403   }
404
405   if (level->extro_script != "") {
406     try {
407       HSQUIRRELVM vm = ScriptManager::instance->create_thread();
408
409       std::istringstream in(level->extro_script);
410       Scripting::compile_and_run(vm, in, "worldmap,extro_script");
411     } catch(std::exception& e) {
412       log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
413     }
414   }
415 }
416
417 void
418 WorldMap::update(float delta)
419 {
420   Menu* menu = Menu::current();
421   if(menu != NULL) {
422     menu->update();
423
424     if(menu == worldmap_menu.get()) {
425       switch (worldmap_menu->check())
426       {
427         case MNID_RETURNWORLDMAP: // Return to game  
428           Menu::set_current(0);
429           break;
430         case MNID_QUITWORLDMAP: // Quit Worldmap
431           main_loop->exit_screen();
432           break;
433       }
434     }
435
436     return;
437   }
438
439   // update GameObjects
440   for(GameObjects::iterator i = game_objects.begin();
441       i != game_objects.end(); ++i) {
442     GameObject* object = *i;
443     object->update(delta);
444   }
445
446   // remove old GameObjects
447   for(GameObjects::iterator i = game_objects.begin();
448       i != game_objects.end(); ) {
449     GameObject* object = *i;
450     if(!object->is_valid()) {
451       delete object;
452       i = game_objects.erase(i);
453     } else {
454       ++i;
455     }
456   }
457
458   // position "camera"
459   Vector tux_pos = tux->get_pos();
460   camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
461   camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
462
463   if (camera_offset.x < 0)
464     camera_offset.x = 0;
465   if (camera_offset.y < 0)
466     camera_offset.y = 0;
467
468   if (camera_offset.x > solids->get_width()*32 - SCREEN_WIDTH)
469     camera_offset.x = solids->get_width()*32 - SCREEN_WIDTH;
470   if (camera_offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
471     camera_offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
472
473   // handle input
474   bool enter_level = false;
475   if(main_controller->pressed(Controller::ACTION)
476       || main_controller->pressed(Controller::JUMP)
477       || main_controller->pressed(Controller::MENU_SELECT))
478     enter_level = true;
479   if(main_controller->pressed(Controller::PAUSE_MENU))
480     on_escape_press();
481   
482   if (enter_level && !tux->is_moving())
483     {
484       /* Check special tile action */
485       SpecialTile* special_tile = at_special_tile();
486       if(special_tile)
487         {
488         if (special_tile->teleport_dest != Vector(-1,-1))
489           {
490           // TODO: an animation, camera scrolling or a fading would be a nice touch
491           sound_manager->play("sounds/warp.wav");
492           tux->back_direction = D_NONE;
493           tux->set_tile_pos(special_tile->teleport_dest);
494           SDL_Delay(1000);
495           }
496         }
497
498       /* Check level action */
499       Level* level = at_level();
500       if (!level) {
501         log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
502         return;
503       }
504
505       if (level->pos == tux->get_tile_pos()) {
506         // do a shriking fade to the level
507         shrink_fade(Vector((level->pos.x*32 + 16 + camera_offset.x),
508                            (level->pos.y*32 + 16 + camera_offset.y)), 500);
509
510         try {
511           main_loop->push_screen(new GameSession(
512                 levels_path + level->name, &level->statistics));
513         } catch(std::exception& e) {
514           log_fatal << "Couldn't load level: " << e.what() << std::endl;
515         }
516       }
517     }
518   else
519     {
520 //      tux->set_direction(input_direction);
521     }
522 }
523
524 const Tile*
525 WorldMap::at(Vector p)
526 {
527   return solids->get_tile((int) p.x, (int) p.y);
528 }
529
530 Level*
531 WorldMap::at_level()
532 {
533   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
534     Level* level = *i;
535     if (level->pos == tux->get_tile_pos())
536       return level;
537   }
538
539   return NULL;
540 }
541
542 SpecialTile*
543 WorldMap::at_special_tile()
544 {
545   for(SpecialTiles::iterator i = special_tiles.begin();
546       i != special_tiles.end(); ++i) {
547     SpecialTile* special_tile = *i;
548     if (special_tile->pos == tux->get_tile_pos())
549       return special_tile; 
550   }
551
552   return NULL;
553 }
554
555 SpriteChange*
556 WorldMap::at_sprite_change(const Vector& pos)
557 {
558   for(SpriteChanges::iterator i = sprite_changes.begin();
559       i != sprite_changes.end(); ++i) {
560     SpriteChange* sprite_change = *i;
561     if(sprite_change->pos == pos)
562       return sprite_change;
563   }
564
565   return NULL;
566 }
567
568 void
569 WorldMap::draw(DrawingContext& context)
570 {
571   context.push_transform();
572   context.set_translation(camera_offset);
573   
574   for(GameObjects::iterator i = game_objects.begin();
575       i != game_objects.end(); ++i) {
576     GameObject* object = *i;
577     object->draw(context);
578   }
579   
580   draw_status(context);
581   context.pop_transform();
582 }
583
584 void
585 WorldMap::draw_status(DrawingContext& context)
586 {
587   context.push_transform();
588   context.set_translation(Vector(0, 0));
589  
590   player_status->draw(context);
591
592   if (!tux->is_moving()) {
593     for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
594       Level* level = *i;
595       
596       if (level->pos == tux->get_tile_pos()) {
597         if(level->title == "")
598           get_level_title(*level);
599
600         context.draw_text(white_text, level->title,
601             Vector(SCREEN_WIDTH/2,
602               SCREEN_HEIGHT - white_text->get_height() - 30),
603             CENTER_ALLIGN, LAYER_FOREGROUND1);
604         
605         level->statistics.draw_worldmap_info(context);
606         break;
607       }
608     }
609
610     for(SpecialTiles::iterator i = special_tiles.begin();
611         i != special_tiles.end(); ++i) {
612       SpecialTile* special_tile = *i;
613       
614       if (special_tile->pos == tux->get_tile_pos()) {
615         /* Display an in-map message in the map, if any as been selected */
616         if(!special_tile->map_message.empty() && !special_tile->passive_message)
617           context.draw_text(gold_text, special_tile->map_message, 
618               Vector(SCREEN_WIDTH/2,
619                 SCREEN_HEIGHT - white_text->get_height() - 60),
620               CENTER_ALLIGN, LAYER_FOREGROUND1);
621         break;
622       }
623     }
624   }
625   
626   /* Display a passive message in the map, if needed */
627   if(passive_message_timer.started())
628     context.draw_text(gold_text, passive_message, 
629             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
630             CENTER_ALLIGN, LAYER_FOREGROUND1);
631
632   context.pop_transform();
633 }
634
635 void
636 WorldMap::setup()
637 {
638   sound_manager->play_music(music);
639   Menu::set_current(NULL);
640
641   current_ = this;
642   load_state();
643 }
644
645 static void store_float(HSQUIRRELVM vm, const char* name, float val)
646 {
647   sq_pushstring(vm, name, -1);
648   sq_pushfloat(vm, val);
649   if(SQ_FAILED(sq_createslot(vm, -3)))
650     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
651 }
652
653 /*
654 static void store_int(HSQUIRRELVM vm, const char* name, int val)
655 {
656   sq_pushstring(vm, name, -1);
657   sq_pushinteger(vm, val);
658   if(SQ_FAILED(sq_createslot(vm, -3)))
659     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
660 }
661 */
662
663 static void store_string(HSQUIRRELVM vm, const char* name, const std::string& val)
664 {
665   sq_pushstring(vm, name, -1);
666   sq_pushstring(vm, val.c_str(), val.length());
667   if(SQ_FAILED(sq_createslot(vm, -3)))
668     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
669 }
670
671 static void store_bool(HSQUIRRELVM vm, const char* name, bool val)
672 {
673   sq_pushstring(vm, name, -1);
674   sq_pushbool(vm, val ? SQTrue : SQFalse);
675   if(SQ_FAILED(sq_createslot(vm, -3)))
676     throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
677 }
678
679 static float read_float(HSQUIRRELVM vm, const char* name)
680 {
681   sq_pushstring(vm, name, -1);
682   if(SQ_FAILED(sq_get(vm, -2))) {
683     std::ostringstream msg;
684     msg << "Couldn't get float value for '" << name << "' from table";
685     throw Scripting::SquirrelError(vm, msg.str());
686   }
687   
688   float result;
689   if(SQ_FAILED(sq_getfloat(vm, -1, &result))) {
690     std::ostringstream msg;
691     msg << "Couldn't get float value for '" << name << "' from table";
692     throw Scripting::SquirrelError(vm, msg.str());
693   }
694   sq_pop(vm, 1);
695
696   return result;
697 }
698
699 static std::string read_string(HSQUIRRELVM vm, const char* name)
700 {
701   sq_pushstring(vm, name, -1);
702   if(SQ_FAILED(sq_get(vm, -2))) {
703     std::ostringstream msg;
704     msg << "Couldn't get string value for '" << name << "' from table";
705     throw Scripting::SquirrelError(vm, msg.str());
706   }
707   
708   const char* result;
709   if(SQ_FAILED(sq_getstring(vm, -1, &result))) {
710     std::ostringstream msg;
711     msg << "Couldn't get string value for '" << name << "' from table";
712     throw Scripting::SquirrelError(vm, msg.str());
713   }
714   sq_pop(vm, 1);
715
716   return std::string(result);
717 }
718
719 static bool read_bool(HSQUIRRELVM vm, const char* name)
720 {
721   sq_pushstring(vm, name, -1);
722   if(SQ_FAILED(sq_get(vm, -2))) {
723     std::ostringstream msg;
724     msg << "Couldn't get bool value for '" << name << "' from table";
725     throw Scripting::SquirrelError(vm, msg.str());
726   } 
727   
728   SQBool result;
729   if(SQ_FAILED(sq_getbool(vm, -1, &result))) {
730     std::ostringstream msg;
731     msg << "Couldn't get bool value for '" << name << "' from table";
732     throw Scripting::SquirrelError(vm, msg.str());
733   }
734   sq_pop(vm, 1);
735
736   return result == SQTrue;
737 }
738
739 void
740 WorldMap::save_state()
741 {
742   HSQUIRRELVM vm = ScriptManager::instance->get_vm();
743   int oldtop = sq_gettop(vm);
744
745   try {
746     // get state table
747     sq_pushroottable(vm);
748     sq_pushstring(vm, "state", -1);
749     if(SQ_FAILED(sq_get(vm, -2)))
750       throw Scripting::SquirrelError(vm, "Couldn't get state table");
751
752     // get or create worlds table
753     sq_pushstring(vm, "worlds", -1);
754     if(SQ_FAILED(sq_get(vm, -2))) {
755       sq_pushstring(vm, "worlds", -1);
756       sq_newtable(vm);
757       if(SQ_FAILED(sq_createslot(vm, -3)))
758         throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
759
760       sq_pushstring(vm, "worlds", -1);
761       if(SQ_FAILED(sq_get(vm, -2)))
762         throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
763     }
764     
765     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
766     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
767       sq_pop(vm, 1);
768
769     // construct new table for this worldmap
770     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
771     sq_newtable(vm);
772
773     // store tux
774     sq_pushstring(vm, "tux", -1);
775     sq_newtable(vm);
776     
777     store_float(vm, "x", tux->get_tile_pos().x);
778     store_float(vm, "y", tux->get_tile_pos().y);
779     store_string(vm, "back", direction_to_string(tux->back_direction));
780
781     sq_createslot(vm, -3);
782     
783     // levels...
784     sq_pushstring(vm, "levels", -1);
785     sq_newtable(vm);
786
787     for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
788       Level* level = *i;
789       
790       if (level->solved) {
791         sq_pushstring(vm, level->name.c_str(), -1);
792         sq_newtable(vm);
793
794         store_bool(vm, "solved", true);            
795         // TODO write statistics
796         // i->statistics.write(writer);
797
798         sq_createslot(vm, -3);
799       }
800     }
801     
802     sq_createslot(vm, -3);
803
804     // push world into worlds table
805     sq_createslot(vm, -3);
806   } catch(std::exception& e) {
807     sq_settop(vm, oldtop);
808   }
809
810   sq_settop(vm, oldtop);
811 }
812
813 void
814 WorldMap::load_state()
815 {
816   HSQUIRRELVM vm = ScriptManager::instance->get_vm();
817   int oldtop = sq_gettop(vm);
818  
819   try {
820     // get state table
821     sq_pushroottable(vm);
822     sq_pushstring(vm, "state", -1);
823     if(SQ_FAILED(sq_get(vm, -2)))
824       throw Scripting::SquirrelError(vm, "Couldn't get state table");
825
826     // get worlds table
827     sq_pushstring(vm, "worlds", -1);
828     if(SQ_FAILED(sq_get(vm, -2)))
829       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
830
831     // get table for our world
832     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
833     if(SQ_FAILED(sq_get(vm, -2)))
834       throw Scripting::SquirrelError(vm, "Couldn't get state.world.mapfilename");
835
836     // load tux
837     sq_pushstring(vm, "tux", -1);
838     if(SQ_FAILED(sq_get(vm, -2)))
839       throw Scripting::SquirrelError(vm, "Couldn't get tux");
840
841     Vector p;
842     p.x = read_float(vm, "x");
843     p.y = read_float(vm, "y");
844     std::string back_str = read_string(vm, "back");
845     tux->back_direction = string_to_direction(back_str);
846     tux->set_tile_pos(p);
847
848     sq_pop(vm, 1);
849
850     // load levels
851     sq_pushstring(vm, "levels", -1);
852     if(SQ_FAILED(sq_get(vm, -2)))
853       throw Scripting::SquirrelError(vm, "Couldn't get levels");
854
855     for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
856       Level* level = *i;
857       sq_pushstring(vm, level->name.c_str(), -1);
858       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
859         level->solved = read_bool(vm, "solved");
860         level->sprite->set_action(level->solved ? "solved" : "default");
861         // i->statistics.parse(*level);
862         sq_pop(vm, 1);
863       }
864     }
865     sq_pop(vm, 1);
866
867   } catch(std::exception& e) {
868     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
869   }
870   sq_settop(vm, oldtop);
871 }
872
873 size_t
874 WorldMap::level_count()
875 {
876   return levels.size();
877 }
878
879 size_t
880 WorldMap::solved_level_count()
881 {
882   size_t count = 0;
883   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
884     Level* level = *i;
885     
886     if(level->solved)
887       count++;
888   }
889
890   return count;
891 }
892     
893 } // namespace WorldMapNS