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