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