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