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