rewrote/refactored tileset handling, tilesets are now properly shared and only part...
[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.hpp"
40 #include "sprite/sprite_manager.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/list_iterator.hpp"
45 #include "lisp/writer.hpp"
46 #include "game_session.hpp"
47 #include "sector.hpp"
48 #include "worldmap.hpp"
49 #include "resources.hpp"
50 #include "log.hpp"
51 #include "world.hpp"
52 #include "player_status.hpp"
53 #include "textscroller.hpp"
54 #include "main.hpp"
55 #include "spawn_point.hpp"
56 #include "file_system.hpp"
57 #include "tile_manager.hpp"
58 #include "tile_set.hpp"
59 #include "gui/menu.hpp"
60 #include "gui/mousecursor.hpp"
61 #include "control/joystickkeyboardcontroller.hpp"
62 #include "object/background.hpp"
63 #include "object/tilemap.hpp"
64 #include "options_menu.hpp"
65 #include "scripting/squirrel_error.hpp"
66 #include "scripting/squirrel_util.hpp"
67 #include "worldmap/level.hpp"
68 #include "worldmap/special_tile.hpp"
69 #include "worldmap/tux.hpp"
70 #include "worldmap/sprite_change.hpp"
71
72 namespace WorldMapNS {
73
74 enum WorldMapMenuIDs {
75   MNID_RETURNWORLDMAP,
76   MNID_QUITWORLDMAP
77 };
78
79 WorldMap* WorldMap::current_ = NULL;
80
81 Direction reverse_dir(Direction direction)
82 {
83   switch(direction)
84     {
85     case D_WEST:
86       return D_EAST;
87     case D_EAST:
88       return D_WEST;
89     case D_NORTH:
90       return D_SOUTH;
91     case D_SOUTH:
92       return D_NORTH;
93     case D_NONE:
94       return D_NONE;
95     }
96   return D_NONE;
97 }
98
99 std::string
100 direction_to_string(Direction direction)
101 {
102   switch(direction)
103     {
104     case D_WEST:
105       return "west";
106     case D_EAST:
107       return "east";
108     case D_NORTH:
109       return "north";
110     case D_SOUTH:
111       return "south";
112     default:
113       return "none";
114     }
115 }
116
117 Direction
118 string_to_direction(const std::string& directory)
119 {
120   if (directory == "west")
121     return D_WEST;
122   else if (directory == "east")
123     return D_EAST;
124   else if (directory == "north")
125     return D_NORTH;
126   else if (directory == "south")
127     return D_SOUTH;
128   else if (directory == "none")
129     return D_NONE;
130   else {
131     log_warning << "unknown direction: \"" << directory << "\"" << std::endl;
132     return D_NONE;
133   }
134 }
135
136 //---------------------------------------------------------------------------
137
138 WorldMap::WorldMap(const std::string& filename, const std::string& force_spawnpoint)
139   : tux(0), tileset(NULL), free_tileset(false),
140     ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), force_spawnpoint(force_spawnpoint),
141     in_level(false)
142 {
143   tux = new Tux(this);
144   add_object(tux);
145
146   name = "<no title>";
147   music = "music/salcon.ogg";
148
149   total_stats.reset();
150
151   worldmap_menu.reset(new Menu());
152   worldmap_menu->add_label(_("Pause"));
153   worldmap_menu->add_hl();
154   worldmap_menu->add_entry(MNID_RETURNWORLDMAP, _("Continue"));
155   worldmap_menu->add_submenu(_("Options"), get_options_menu());
156   worldmap_menu->add_hl();
157   worldmap_menu->add_entry(MNID_QUITWORLDMAP, _("Quit World"));
158
159   // create a new squirrel table for the worldmap
160   using namespace Scripting;
161
162   sq_collectgarbage(global_vm);
163   sq_newtable(global_vm);
164   sq_pushroottable(global_vm);
165   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
166     throw Scripting::SquirrelError(global_vm, "Couldn't set worldmap_table delegate");
167
168   sq_resetobject(&worldmap_table);
169   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &worldmap_table)))
170     throw Scripting::SquirrelError(global_vm, "Couldn't get table from stack");
171
172   sq_addref(global_vm, &worldmap_table);
173   sq_pop(global_vm, 1);
174
175   sound_manager->preload("sounds/warp.wav");
176   
177   // load worldmap objects
178   load(filename);
179 }
180
181 WorldMap::~WorldMap()
182 {
183   using namespace Scripting;
184
185   if(free_tileset)
186     delete tileset;
187
188   for(GameObjects::iterator i = game_objects.begin();
189       i != game_objects.end(); ++i) {
190     GameObject* object = *i;
191     try_unexpose(object);
192     object->unref();
193   }
194
195   for(SpawnPoints::iterator i = spawn_points.begin();
196       i != spawn_points.end(); ++i) {
197     delete *i;
198   }
199
200   for(ScriptList::iterator i = scripts.begin();
201       i != scripts.end(); ++i) {
202     HSQOBJECT& object = *i;
203     sq_release(global_vm, &object);
204   }
205   sq_release(global_vm, &worldmap_table);
206
207   sq_collectgarbage(global_vm);
208
209   if(current_ == this)
210     current_ = NULL;
211 }
212
213 void
214 WorldMap::add_object(GameObject* object)
215 {
216   TileMap* tilemap = dynamic_cast<TileMap*> (object);
217   if(tilemap != 0 && tilemap->is_solid()) {
218     solid_tilemaps.push_back(tilemap);
219   }
220
221   object->ref();
222   try_expose(object);
223   game_objects.push_back(object);
224 }
225
226 void
227 WorldMap::try_expose(GameObject* object)
228 {
229   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
230   if(interface != NULL) {
231     HSQUIRRELVM vm = Scripting::global_vm;
232     sq_pushobject(vm, worldmap_table);
233     interface->expose(vm, -1);
234     sq_pop(vm, 1);
235   }
236 }
237
238 void
239 WorldMap::try_unexpose(GameObject* object)
240 {
241   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
242   if(interface != NULL) {
243     HSQUIRRELVM vm = Scripting::global_vm;
244     SQInteger oldtop = sq_gettop(vm);
245     sq_pushobject(vm, worldmap_table);
246     try {
247       interface->unexpose(vm, -1);
248     } catch(std::exception& e) {
249       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
250     }
251     sq_settop(vm, oldtop);
252   }
253 }
254
255 void
256 WorldMap::move_to_spawnpoint(const std::string& spawnpoint)
257 {
258   for(SpawnPoints::iterator i = spawn_points.begin(); i != spawn_points.end(); ++i) {
259     SpawnPoint* sp = *i;
260     if(sp->name == spawnpoint) {
261       Vector p = sp->pos;
262       tux->set_tile_pos(p);
263       tux->set_direction(sp->auto_dir);
264       return;
265     }
266   }
267   log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
268   if (spawnpoint != "main") {
269     move_to_spawnpoint("main");
270   }
271 }
272
273 void
274 WorldMap::change(const std::string& filename, const std::string& force_spawnpoint)
275 {
276   main_loop->exit_screen();
277   main_loop->push_screen(new WorldMap(filename, force_spawnpoint));
278 }
279
280 void
281 WorldMap::load(const std::string& filename)
282 {
283   map_filename = filename;
284   levels_path = FileSystem::dirname(map_filename);
285
286   try {
287     lisp::Parser parser;
288     const lisp::Lisp* root = parser.parse(map_filename);
289
290     const lisp::Lisp* level = root->get_lisp("supertux-level");
291     if(level == NULL)
292       throw std::runtime_error("file isn't a supertux-level file.");
293
294     level->get("name", name);
295
296     const lisp::Lisp* sector = level->get_lisp("sector");
297     if(!sector)
298       throw std::runtime_error("No sector sepcified in worldmap file.");
299
300     const lisp::Lisp* tilesets_lisp = level->get_lisp("tilesets");
301     if(tilesets_lisp != NULL) {
302       tileset      = tile_manager->parse_tileset_definition(*tilesets_lisp);
303       free_tileset = true;
304     }
305     std::string tileset_name;
306     if(level->get("tileset", tileset_name)) {
307       if(tileset != NULL) {
308         log_warning << "multiple tilesets specified in level" << std::endl;
309       } else {
310         tileset = tile_manager->get_tileset(tileset_name);
311       }
312     }
313     /* load default tileset */
314     if(tileset == NULL) {
315       tileset = tile_manager->get_tileset("images/worldmap.strf");
316     }
317     current_tileset = tileset;
318
319     lisp::ListIterator iter(sector);
320     while(iter.next()) {
321       if(iter.item() == "tilemap") {
322         add_object(new TileMap(*(iter.lisp())));
323       } else if(iter.item() == "background") {
324         add_object(new Background(*(iter.lisp())));
325       } else if(iter.item() == "music") {
326         iter.value()->get(music);
327       } else if(iter.item() == "init-script") {
328         iter.value()->get(init_script);
329       } else if(iter.item() == "worldmap-spawnpoint") {
330         SpawnPoint* sp = new SpawnPoint(iter.lisp());
331         spawn_points.push_back(sp);
332       } else if(iter.item() == "level") {
333         LevelTile* level = new LevelTile(levels_path, iter.lisp());
334         levels.push_back(level);
335         add_object(level);
336       } else if(iter.item() == "special-tile") {
337         SpecialTile* special_tile = new SpecialTile(iter.lisp());
338         special_tiles.push_back(special_tile);
339         add_object(special_tile);
340       } else if(iter.item() == "sprite-change") {
341         SpriteChange* sprite_change = new SpriteChange(iter.lisp());
342         sprite_changes.push_back(sprite_change);
343         add_object(sprite_change);
344       } else if(iter.item() == "teleporter") {
345         Teleporter* teleporter = new Teleporter(iter.lisp());
346         teleporters.push_back(teleporter);
347         add_object(teleporter);
348       } else if(iter.item() == "ambient-light") {
349         std::vector<float> vColor;
350         sector->get_vector( "ambient-light", vColor );
351         if(vColor.size() < 3) {
352           log_warning << "(ambient-light) requires a color as argument" << std::endl;
353         } else {
354           ambient_light = Color( vColor );
355         }
356       } else if(iter.item() == "name") {
357         // skip
358       } else {
359         log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
360       }
361     }
362     current_tileset = NULL;
363
364     if(solid_tilemaps.size() == 0)
365       throw std::runtime_error("No solid tilemap specified");
366
367     move_to_spawnpoint("main");
368
369   } catch(std::exception& e) {
370     std::stringstream msg;
371     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
372       e.what();
373     throw std::runtime_error(msg.str());
374   }
375 }
376
377 void
378 WorldMap::get_level_title(LevelTile& level)
379 {
380   /** get special_tile's title */
381   level.title = "<no title>";
382
383   try {
384     lisp::Parser parser;
385     const lisp::Lisp* root = parser.parse(levels_path + level.get_name());
386
387     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
388     if(!level_lisp)
389       return;
390
391     level_lisp->get("name", level.title);
392   } catch(std::exception& e) {
393     log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
394     return;
395   }
396 }
397
398 void WorldMap::calculate_total_stats()
399 {
400   total_stats.zero();
401   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
402     LevelTile* level = *i;
403     if (level->solved) {
404       total_stats += level->statistics;
405     }
406   }
407 }
408
409 void
410 WorldMap::on_escape_press()
411 {
412   // Show or hide the menu
413   if(!Menu::current()) {
414     Menu::set_current(worldmap_menu.get());
415     tux->set_direction(D_NONE);  // stop tux movement when menu is called
416   } else {
417     Menu::set_current(NULL);
418   }
419 }
420
421 Vector
422 WorldMap::get_next_tile(Vector pos, Direction direction)
423 {
424   switch(direction) {
425     case D_WEST:
426       pos.x -= 1;
427       break;
428     case D_EAST:
429       pos.x += 1;
430       break;
431     case D_NORTH:
432       pos.y -= 1;
433       break;
434     case D_SOUTH:
435       pos.y += 1;
436       break;
437     case D_NONE:
438       break;
439   }
440   return pos;
441 }
442
443 bool
444 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
445 {
446   *new_pos = get_next_tile(old_pos, direction);
447
448   if (!(new_pos->x >= 0 && new_pos->x < get_width()
449         && new_pos->y >= 0 && new_pos->y < get_height()))
450     { // New position is outsite the tilemap
451       return false;
452     }
453   else
454     { // Check if the tile allows us to go to new_pos
455       int old_tile_data = tile_data_at(old_pos);
456       int new_tile_data = tile_data_at(*new_pos);
457       switch(direction)
458         {
459         case D_WEST:
460           return (old_tile_data & Tile::WORLDMAP_WEST
461               && new_tile_data & Tile::WORLDMAP_EAST);
462
463         case D_EAST:
464           return (old_tile_data & Tile::WORLDMAP_EAST
465               && new_tile_data & Tile::WORLDMAP_WEST);
466
467         case D_NORTH:
468           return (old_tile_data & Tile::WORLDMAP_NORTH
469               && new_tile_data & Tile::WORLDMAP_SOUTH);
470
471         case D_SOUTH:
472           return (old_tile_data & Tile::WORLDMAP_SOUTH
473               && new_tile_data & Tile::WORLDMAP_NORTH);
474
475         case D_NONE:
476           assert(!"path_ok() can't walk if direction is NONE");
477         }
478       return false;
479     }
480 }
481
482 void
483 WorldMap::finished_level(Level* gamelevel)
484 {
485   // TODO use Level* parameter here?
486   LevelTile* level = at_level();
487
488   bool old_level_state = level->solved;
489   level->solved = true;
490   level->sprite->set_action("solved");
491
492   // deal with statistics
493   level->statistics.merge(gamelevel->stats);
494   calculate_total_stats();
495
496   save_state();
497
498   if (old_level_state != level->solved) {
499     // Try to detect the next direction to which we should walk
500     // FIXME: Mostly a hack
501     Direction dir = D_NONE;
502
503     int dirdata = available_directions_at(tux->get_tile_pos());
504     // first, test for crossroads
505     if (dirdata == Tile::WORLDMAP_CNSE ||
506                 dirdata == Tile::WORLDMAP_CNSW ||
507                 dirdata == Tile::WORLDMAP_CNEW ||
508                 dirdata == Tile::WORLDMAP_CSEW ||
509                 dirdata == Tile::WORLDMAP_CNSEW)
510       dir = D_NONE;
511     else if (dirdata & Tile::WORLDMAP_NORTH
512         && tux->back_direction != D_NORTH)
513       dir = D_NORTH;
514     else if (dirdata & Tile::WORLDMAP_SOUTH
515         && tux->back_direction != D_SOUTH)
516       dir = D_SOUTH;
517     else if (dirdata & Tile::WORLDMAP_EAST
518         && tux->back_direction != D_EAST)
519       dir = D_EAST;
520     else if (dirdata & Tile::WORLDMAP_WEST
521         && tux->back_direction != D_WEST)
522       dir = D_WEST;
523
524     if (dir != D_NONE) {
525       tux->set_direction(dir);
526     }
527   }
528
529   if (level->extro_script != "") {
530     try {
531       std::istringstream in(level->extro_script);
532       run_script(in, "worldmap:extro_script");
533     } catch(std::exception& e) {
534       log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
535     }
536   }
537 }
538
539 void
540 WorldMap::update(float delta)
541 {
542   if(!in_level) {
543     Menu* menu = Menu::current();
544     if(menu != NULL) {
545       menu->update();
546
547       if(menu == worldmap_menu.get()) {
548         switch (worldmap_menu->check())
549         {
550           case MNID_RETURNWORLDMAP: // Return to game
551             Menu::set_current(0);
552             break;
553           case MNID_QUITWORLDMAP: // Quit Worldmap
554             main_loop->exit_screen();
555             break;
556         }
557       }
558
559       return;
560     }
561
562     // update GameObjects
563     for(size_t i = 0; i < game_objects.size(); ++i) {
564       GameObject* object = game_objects[i];
565       object->update(delta);
566     }
567
568     // remove old GameObjects
569     for(GameObjects::iterator i = game_objects.begin();
570         i != game_objects.end(); ) {
571       GameObject* object = *i;
572       if(!object->is_valid()) {
573         try_unexpose(object);
574         object->unref();
575         i = game_objects.erase(i);
576       } else {
577         ++i;
578       }
579     }
580
581     /* update solid_tilemaps list */
582     //FIXME: this could be more efficient
583     solid_tilemaps.clear();
584     for(std::vector<GameObject*>::iterator i = game_objects.begin();
585         i != game_objects.end(); ++i)
586     {
587       TileMap* tm = dynamic_cast<TileMap*>(*i);
588       if (!tm) continue;
589       if (tm->is_solid()) solid_tilemaps.push_back(tm);
590     }
591
592     // position "camera"
593     Vector tux_pos = tux->get_pos();
594     camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
595     camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
596
597     if (camera_offset.x < 0)
598       camera_offset.x = 0;
599     if (camera_offset.y < 0)
600       camera_offset.y = 0;
601
602     if (camera_offset.x > (int)get_width()*32 - SCREEN_WIDTH)
603       camera_offset.x = (int)get_width()*32 - SCREEN_WIDTH;
604     if (camera_offset.y > (int)get_height()*32 - SCREEN_HEIGHT)
605       camera_offset.y = (int)get_height()*32 - SCREEN_HEIGHT;
606
607     if (int(get_width()*32) < SCREEN_WIDTH)
608       camera_offset.x = get_width()*16.0 - SCREEN_WIDTH/2.0;
609     if (int(get_height()*32) < SCREEN_HEIGHT)
610       camera_offset.y = get_height()*16.0 - SCREEN_HEIGHT/2.0;
611
612     // handle input
613     bool enter_level = false;
614     if(main_controller->pressed(Controller::ACTION)
615         || main_controller->pressed(Controller::JUMP)
616         || main_controller->pressed(Controller::MENU_SELECT)) {
617       /* some people define UP and JUMP on the same key... */
618       if(!main_controller->pressed(Controller::UP))
619             enter_level = true;
620         }
621     if(main_controller->pressed(Controller::PAUSE_MENU))
622       on_escape_press();
623
624     // check for teleporters
625     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
626     if (teleporter && (teleporter->automatic || (enter_level && (!tux->is_moving())))) {
627       enter_level = false;
628       if (teleporter->worldmap != "") {
629         change(teleporter->worldmap, teleporter->spawnpoint);
630       } else {
631         // TODO: an animation, camera scrolling or a fading would be a nice touch
632         sound_manager->play("sounds/warp.wav");
633         tux->back_direction = D_NONE;
634         move_to_spawnpoint(teleporter->spawnpoint);
635       }
636     }
637
638     // check for auto-play levels
639     LevelTile* level = at_level();
640     if (level && (level->auto_play) && (!level->solved) && (!tux->is_moving())) {
641       enter_level = true;
642     }
643
644     if (enter_level && !tux->is_moving())
645       {
646         /* Check level action */
647         LevelTile* level = at_level();
648         if (!level) {
649           //Respawn if player on a tile with no level and nowhere to go.
650           int tile_data = tile_data_at(tux->get_tile_pos());
651           if(!( tile_data & ( Tile::WORLDMAP_NORTH |  Tile::WORLDMAP_SOUTH | Tile::WORLDMAP_WEST | Tile::WORLDMAP_EAST ))){
652             log_warning << "Player at illegal position " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << " respawning." << std::endl;
653             move_to_spawnpoint("main");
654             return;
655           }
656           log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
657           return;
658         }
659
660         if (level->pos == tux->get_tile_pos()) {
661           try {
662             Vector shrinkpos = Vector(level->pos.x*32 + 16 - camera_offset.x,
663                                       level->pos.y*32 + 16 - camera_offset.y);
664             std::string levelfile = levels_path + level->get_name();
665
666             // update state and savegame
667             save_state();
668
669             main_loop->push_screen(new GameSession(levelfile, &level->statistics),
670                                    new ShrinkFade(shrinkpos, 0.5));
671             in_level = true;
672           } catch(std::exception& e) {
673             log_fatal << "Couldn't load level: " << e.what() << std::endl;
674           }
675         }
676       }
677     else
678       {
679   //      tux->set_direction(input_direction);
680       }
681   }
682 }
683
684 int
685 WorldMap::tile_data_at(Vector p)
686 {
687   int dirs = 0;
688
689   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
690     TileMap* tilemap = *i;
691     const Tile* tile = tilemap->get_tile((int)p.x, (int)p.y);
692     int dirdata = tile->getData();
693     dirs |= dirdata;
694   }
695
696   return dirs;
697 }
698
699 int
700 WorldMap::available_directions_at(Vector p)
701 {
702   return tile_data_at(p) & Tile::WORLDMAP_DIR_MASK;
703 }
704
705 LevelTile*
706 WorldMap::at_level()
707 {
708   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
709     LevelTile* level = *i;
710     if (level->pos == tux->get_tile_pos())
711       return level;
712   }
713
714   return NULL;
715 }
716
717 SpecialTile*
718 WorldMap::at_special_tile()
719 {
720   for(SpecialTiles::iterator i = special_tiles.begin();
721       i != special_tiles.end(); ++i) {
722     SpecialTile* special_tile = *i;
723     if (special_tile->pos == tux->get_tile_pos())
724       return special_tile;
725   }
726
727   return NULL;
728 }
729
730 SpriteChange*
731 WorldMap::at_sprite_change(const Vector& pos)
732 {
733   for(SpriteChanges::iterator i = sprite_changes.begin();
734       i != sprite_changes.end(); ++i) {
735     SpriteChange* sprite_change = *i;
736     if(sprite_change->pos == pos)
737       return sprite_change;
738   }
739
740   return NULL;
741 }
742
743 Teleporter*
744 WorldMap::at_teleporter(const Vector& pos)
745 {
746   for(std::vector<Teleporter*>::iterator i = teleporters.begin(); i != teleporters.end(); ++i) {
747     Teleporter* teleporter = *i;
748     if(teleporter->pos == pos) return teleporter;
749   }
750
751   return NULL;
752 }
753
754 void
755 WorldMap::draw(DrawingContext& context)
756 {
757   if (int(get_width()*32) < SCREEN_WIDTH || int(get_height()*32) < SCREEN_HEIGHT)
758     context.draw_filled_rect(Vector(0, 0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
759       Color(0.0f, 0.0f, 0.0f, 1.0f), LAYER_BACKGROUND0);
760
761   context.set_ambient_color( ambient_light );
762   context.push_transform();
763   context.set_translation(camera_offset);
764
765   for(GameObjects::iterator i = game_objects.begin();
766       i != game_objects.end(); ++i) {
767     GameObject* object = *i;
768     object->draw(context);
769   }
770
771 /*
772   // FIXME: make this a runtime switch similar to draw_collrects/show_collrects?
773   // draw visual indication of possible walk directions
774   static int flipme = 0; 
775   if (flipme++ & 0x04)
776   for (int x = 0; x < get_width(); x++) {
777     for (int y = 0; y < get_height(); y++) {
778       int data = tile_data_at(Vector(x,y));
779       int px = x * 32;
780       int py = y * 32;
781       const int W = 4;
782       if (data & Tile::WORLDMAP_NORTH)    context.draw_filled_rect(Rect(px + 16-W, py       , px + 16+W, py + 16-W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
783       if (data & Tile::WORLDMAP_SOUTH)    context.draw_filled_rect(Rect(px + 16-W, py + 16+W, px + 16+W, py + 32  ), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
784       if (data & Tile::WORLDMAP_EAST)     context.draw_filled_rect(Rect(px + 16+W, py + 16-W, px + 32  , py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
785       if (data & Tile::WORLDMAP_WEST)     context.draw_filled_rect(Rect(px       , py + 16-W, px + 16-W, py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
786       if (data & Tile::WORLDMAP_DIR_MASK) context.draw_filled_rect(Rect(px + 16-W, py + 16-W, px + 16+W, py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
787       if (data & Tile::WORLDMAP_STOP)     context.draw_filled_rect(Rect(px + 4   , py + 4   , px + 28  , py + 28  ), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
788     }
789   }
790 */
791
792   draw_status(context);
793   context.pop_transform();
794 }
795
796 void
797 WorldMap::draw_status(DrawingContext& context)
798 {
799   context.push_transform();
800   context.set_translation(Vector(0, 0));
801
802   player_status->draw(context);
803
804   if (!tux->is_moving()) {
805     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
806       LevelTile* level = *i;
807
808       if (level->pos == tux->get_tile_pos()) {
809         if(level->title == "")
810           get_level_title(*level);
811
812         context.draw_text(white_text, level->title,
813                           Vector(SCREEN_WIDTH/2,
814                                  SCREEN_HEIGHT - white_text->get_height() - 30),
815                           ALIGN_CENTER, LAYER_FOREGROUND1);
816
817         // if level is solved, draw level picture behind stats
818         /*
819         if (level->solved) {
820           if (const Surface* picture = level->get_picture()) {
821             Vector pos = Vector(SCREEN_WIDTH - picture->get_width(), SCREEN_HEIGHT - picture->get_height());
822             context.push_transform();
823             context.set_alpha(0.5);
824             context.draw_surface(picture, pos, LAYER_FOREGROUND1-1);
825             context.pop_transform();
826           }
827         }
828         */
829
830         level->statistics.draw_worldmap_info(context);
831         break;
832       }
833     }
834
835     for(SpecialTiles::iterator i = special_tiles.begin();
836         i != special_tiles.end(); ++i) {
837       SpecialTile* special_tile = *i;
838
839       if (special_tile->pos == tux->get_tile_pos()) {
840         /* Display an in-map message in the map, if any as been selected */
841         if(!special_tile->map_message.empty() && !special_tile->passive_message)
842           context.draw_text(gold_text, special_tile->map_message,
843               Vector(SCREEN_WIDTH/2,
844                 SCREEN_HEIGHT - white_text->get_height() - 60),
845               ALIGN_CENTER, LAYER_FOREGROUND1);
846         break;
847       }
848     }
849
850     // display teleporter messages
851     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
852     if (teleporter && (teleporter->message != "")) {
853       Vector pos = Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 30);
854       context.draw_text(white_text, teleporter->message, pos, ALIGN_CENTER, LAYER_FOREGROUND1);
855     }
856
857   }
858
859   /* Display a passive message in the map, if needed */
860   if(passive_message_timer.started())
861     context.draw_text(gold_text, passive_message,
862             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
863             ALIGN_CENTER, LAYER_FOREGROUND1);
864
865   context.pop_transform();
866 }
867
868 void
869 WorldMap::setup()
870 {
871   sound_manager->play_music(music);
872   Menu::set_current(NULL);
873
874   current_ = this;
875   load_state();
876
877   // if force_spawnpoint was set, move Tux there, then clear force_spawnpoint
878   if (force_spawnpoint != "") {
879     move_to_spawnpoint(force_spawnpoint);
880     force_spawnpoint = "";
881   }
882
883   tux->setup();
884
885   // register worldmap_table as worldmap in scripting
886   using namespace Scripting;
887
888   sq_pushroottable(global_vm);
889   sq_pushstring(global_vm, "worldmap", -1);
890   sq_pushobject(global_vm, worldmap_table);
891   if(SQ_FAILED(sq_createslot(global_vm, -3)))
892     throw SquirrelError(global_vm, "Couldn't set worldmap in roottable");
893   sq_pop(global_vm, 1);
894
895   if(init_script != "") {
896     std::istringstream in(init_script);
897     run_script(in, "WorldMap::init");
898   }
899 }
900
901 void
902 WorldMap::leave()
903 {
904   using namespace Scripting;
905
906   // save state of world and player
907   save_state();
908
909   // remove worldmap_table from roottable
910   sq_pushroottable(global_vm);
911   sq_pushstring(global_vm, "worldmap", -1);
912   if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
913     throw SquirrelError(global_vm, "Couldn't unset worldmap in roottable");
914   sq_pop(global_vm, 1);
915 }
916
917 void
918 WorldMap::save_state()
919 {
920   using namespace Scripting;
921
922   HSQUIRRELVM vm = global_vm;
923   int oldtop = sq_gettop(vm);
924
925   try {
926     // get state table
927     sq_pushroottable(vm);
928     sq_pushstring(vm, "state", -1);
929     if(SQ_FAILED(sq_get(vm, -2)))
930       throw Scripting::SquirrelError(vm, "Couldn't get state table");
931
932     // get or create worlds table
933     sq_pushstring(vm, "worlds", -1);
934     if(SQ_FAILED(sq_get(vm, -2))) {
935       sq_pushstring(vm, "worlds", -1);
936       sq_newtable(vm);
937       if(SQ_FAILED(sq_createslot(vm, -3)))
938         throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
939
940       sq_pushstring(vm, "worlds", -1);
941       if(SQ_FAILED(sq_get(vm, -2)))
942         throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
943     }
944
945     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
946     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
947       sq_pop(vm, 1);
948
949     // construct new table for this worldmap
950     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
951     sq_newtable(vm);
952
953     // store tux
954     sq_pushstring(vm, "tux", -1);
955     sq_newtable(vm);
956
957     store_float(vm, "x", tux->get_tile_pos().x);
958     store_float(vm, "y", tux->get_tile_pos().y);
959     store_string(vm, "back", direction_to_string(tux->back_direction));
960
961     sq_createslot(vm, -3);
962
963     // levels...
964     sq_pushstring(vm, "levels", -1);
965     sq_newtable(vm);
966
967     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
968       LevelTile* level = *i;
969
970           sq_pushstring(vm, level->get_name().c_str(), -1);
971           sq_newtable(vm);
972
973           store_bool(vm, "solved", level->solved);
974           level->statistics.serialize_to_squirrel(vm);
975
976           sq_createslot(vm, -3);
977     }
978
979     sq_createslot(vm, -3);
980
981     // overall statistics...
982     total_stats.serialize_to_squirrel(vm);
983
984     // push world into worlds table
985     sq_createslot(vm, -3);
986   } catch(std::exception& ) {
987     sq_settop(vm, oldtop);
988   }
989
990   sq_settop(vm, oldtop);
991
992   if(World::current() != NULL)
993     World::current()->save_state();
994 }
995
996 void
997 WorldMap::load_state()
998 {
999   using namespace Scripting;
1000
1001   HSQUIRRELVM vm = global_vm;
1002   int oldtop = sq_gettop(vm);
1003
1004   try {
1005     // get state table
1006     sq_pushroottable(vm);
1007     sq_pushstring(vm, "state", -1);
1008     if(SQ_FAILED(sq_get(vm, -2)))
1009       throw Scripting::SquirrelError(vm, "Couldn't get state table");
1010
1011     // get worlds table
1012     sq_pushstring(vm, "worlds", -1);
1013     if(SQ_FAILED(sq_get(vm, -2)))
1014       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
1015
1016     // get table for our world
1017     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1018     if(SQ_FAILED(sq_get(vm, -2)))
1019       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds.mapfilename");
1020
1021     // load tux
1022     sq_pushstring(vm, "tux", -1);
1023     if(SQ_FAILED(sq_get(vm, -2)))
1024       throw Scripting::SquirrelError(vm, "Couldn't get tux");
1025
1026     Vector p;
1027     p.x = read_float(vm, "x");
1028     p.y = read_float(vm, "y");
1029     std::string back_str = read_string(vm, "back");
1030     tux->back_direction = string_to_direction(back_str);
1031     tux->set_tile_pos(p);
1032
1033     sq_pop(vm, 1);
1034
1035     // load levels
1036     sq_pushstring(vm, "levels", -1);
1037     if(SQ_FAILED(sq_get(vm, -2)))
1038       throw Scripting::SquirrelError(vm, "Couldn't get levels");
1039
1040     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1041       LevelTile* level = *i;
1042       sq_pushstring(vm, level->get_name().c_str(), -1);
1043       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
1044         level->solved = read_bool(vm, "solved");
1045         level->sprite->set_action(level->solved ? "solved" : "default");
1046         level->statistics.unserialize_from_squirrel(vm);
1047         sq_pop(vm, 1);
1048       }
1049     }
1050
1051     // leave state table
1052     sq_pop(vm, 1);
1053
1054     // load overall statistics
1055     total_stats.unserialize_from_squirrel(vm);
1056
1057   } catch(std::exception& e) {
1058     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
1059   }
1060   sq_settop(vm, oldtop);
1061
1062   in_level = false;
1063 }
1064
1065 size_t
1066 WorldMap::level_count()
1067 {
1068   return levels.size();
1069 }
1070
1071 size_t
1072 WorldMap::solved_level_count()
1073 {
1074   size_t count = 0;
1075   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1076     LevelTile* level = *i;
1077
1078     if(level->solved)
1079       count++;
1080   }
1081
1082   return count;
1083 }
1084
1085 HSQUIRRELVM
1086 WorldMap::run_script(std::istream& in, const std::string& sourcename)
1087 {
1088   using namespace Scripting;
1089
1090   // garbage collect thread list
1091   for(ScriptList::iterator i = scripts.begin();
1092       i != scripts.end(); ) {
1093     HSQOBJECT& object = *i;
1094     HSQUIRRELVM vm = object_to_vm(object);
1095
1096     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
1097       sq_release(global_vm, &object);
1098       i = scripts.erase(i);
1099       continue;
1100     }
1101
1102     ++i;
1103   }
1104
1105   HSQOBJECT object = create_thread(global_vm);
1106   scripts.push_back(object);
1107
1108   HSQUIRRELVM vm = object_to_vm(object);
1109
1110   // set worldmap_table as roottable for the thread
1111   sq_pushobject(vm, worldmap_table);
1112   sq_setroottable(vm);
1113
1114   compile_and_run(vm, in, sourcename);
1115
1116   return vm;
1117 }
1118
1119 float
1120 WorldMap::get_width() const
1121 {
1122   float width = 0;
1123   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1124     TileMap* solids = *i;
1125     if (solids->get_width() > width) width = solids->get_width();
1126   }
1127   return width;
1128 }
1129
1130 float
1131 WorldMap::get_height() const
1132 {
1133   float height = 0;
1134   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1135     TileMap* solids = *i;
1136     if (solids->get_height() > height) height = solids->get_height();
1137   }
1138   return height;
1139 }
1140
1141 } // namespace WorldMapNS