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