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