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