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