3 // SuperTux - A Jump'n Run
4 // Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 // Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License
9 // as published by the Free Software Foundation; either version 2
10 // of the License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
31 #include "worldmap.hpp"
33 #include "gettext.hpp"
35 #include "mainloop.hpp"
36 #include "shrinkfade.hpp"
37 #include "video/surface.hpp"
38 #include "video/drawing_context.hpp"
39 #include "sprite/sprite_manager.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "lisp/parser.hpp"
42 #include "lisp/lisp.hpp"
43 #include "lisp/list_iterator.hpp"
44 #include "lisp/writer.hpp"
45 #include "game_session.hpp"
47 #include "worldmap.hpp"
48 #include "resources.hpp"
51 #include "player_status.hpp"
52 #include "textscroller.hpp"
54 #include "spawn_point.hpp"
55 #include "file_system.hpp"
56 #include "gui/menu.hpp"
57 #include "gui/mousecursor.hpp"
58 #include "control/joystickkeyboardcontroller.hpp"
59 #include "object/background.hpp"
60 #include "object/tilemap.hpp"
61 #include "options_menu.hpp"
62 #include "scripting/squirrel_error.hpp"
63 #include "scripting/squirrel_util.hpp"
64 #include "worldmap/level.hpp"
65 #include "worldmap/special_tile.hpp"
66 #include "worldmap/tux.hpp"
67 #include "worldmap/sprite_change.hpp"
69 namespace WorldMapNS {
71 enum WorldMapMenuIDs {
76 WorldMap* WorldMap::current_ = NULL;
78 Direction reverse_dir(Direction direction)
97 direction_to_string(Direction direction)
115 string_to_direction(const std::string& directory)
117 if (directory == "west")
119 else if (directory == "east")
121 else if (directory == "north")
123 else if (directory == "south")
129 //---------------------------------------------------------------------------
131 WorldMap::WorldMap(const std::string& filename)
134 tile_manager.reset(new TileManager("images/worldmap.strf"));
140 music = "music/salcon.ogg";
144 worldmap_menu.reset(new Menu());
145 worldmap_menu->add_label(_("Pause"));
146 worldmap_menu->add_hl();
147 worldmap_menu->add_entry(MNID_RETURNWORLDMAP, _("Continue"));
148 worldmap_menu->add_submenu(_("Options"), get_options_menu());
149 worldmap_menu->add_hl();
150 worldmap_menu->add_entry(MNID_QUITWORLDMAP, _("Quit World"));
155 WorldMap::~WorldMap()
157 using namespace Scripting;
159 for(ScriptList::iterator i = scripts.begin();
160 i != scripts.end(); ++i) {
161 HSQOBJECT& object = *i;
162 sq_release(global_vm, &object);
168 for(GameObjects::iterator i = game_objects.begin();
169 i != game_objects.end(); ++i)
172 for(SpawnPoints::iterator i = spawn_points.begin();
173 i != spawn_points.end(); ++i) {
179 WorldMap::add_object(GameObject* object)
181 TileMap* tilemap = dynamic_cast<TileMap*> (object);
182 if(tilemap != 0 && tilemap->is_solid()) {
186 game_objects.push_back(object);
190 WorldMap::load(const std::string& filename)
192 map_filename = filename;
193 levels_path = FileSystem::dirname(map_filename);
197 std::auto_ptr<lisp::Lisp> root (parser.parse(map_filename));
199 const lisp::Lisp* lisp = root->get_lisp("supertux-level");
201 throw std::runtime_error("file isn't a supertux-level file.");
203 lisp->get("name", name);
205 const lisp::Lisp* sector = lisp->get_lisp("sector");
207 throw std::runtime_error("No sector sepcified in worldmap file.");
209 lisp::ListIterator iter(sector);
211 if(iter.item() == "tilemap") {
212 add_object(new TileMap(*(iter.lisp()), tile_manager.get()));
213 } else if(iter.item() == "background") {
214 add_object(new Background(*(iter.lisp())));
215 } else if(iter.item() == "music") {
216 iter.value()->get(music);
217 } else if(iter.item() == "worldmap-spawnpoint") {
218 SpawnPoint* sp = new SpawnPoint(iter.lisp());
219 spawn_points.push_back(sp);
220 } else if(iter.item() == "level") {
221 LevelTile* level = new LevelTile(levels_path, iter.lisp());
222 levels.push_back(level);
223 game_objects.push_back(level);
224 } else if(iter.item() == "special-tile") {
225 SpecialTile* special_tile = new SpecialTile(iter.lisp());
226 special_tiles.push_back(special_tile);
227 game_objects.push_back(special_tile);
228 } else if(iter.item() == "sprite-change") {
229 SpriteChange* sprite_change = new SpriteChange(iter.lisp());
230 sprite_changes.push_back(sprite_change);
231 game_objects.push_back(sprite_change);
232 } else if(iter.item() == "name") {
235 log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
239 throw std::runtime_error("No solid tilemap specified");
241 // search for main spawnpoint
242 for(SpawnPoints::iterator i = spawn_points.begin();
243 i != spawn_points.end(); ++i) {
245 if(sp->name == "main") {
247 tux->set_tile_pos(p);
252 } catch(std::exception& e) {
253 std::stringstream msg;
254 msg << "Problem when parsing worldmap '" << map_filename << "': " <<
256 throw std::runtime_error(msg.str());
261 WorldMap::get_level_title(LevelTile& level)
263 /** get special_tile's title */
264 level.title = "<no title>";
268 std::auto_ptr<lisp::Lisp> root (parser.parse(levels_path + level.name));
270 const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
274 level_lisp->get("name", level.title);
275 } catch(std::exception& e) {
276 log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
281 void WorldMap::calculate_total_stats()
284 for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
285 LevelTile* level = *i;
287 total_stats += level->statistics;
293 WorldMap::on_escape_press()
295 // Show or hide the menu
296 if(!Menu::current()) {
297 Menu::set_current(worldmap_menu.get());
298 tux->set_direction(D_NONE); // stop tux movement when menu is called
300 Menu::set_current(NULL);
305 WorldMap::get_next_tile(Vector pos, Direction direction)
327 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
329 *new_pos = get_next_tile(old_pos, direction);
331 if (!(new_pos->x >= 0 && new_pos->x < solids->get_width()
332 && new_pos->y >= 0 && new_pos->y < solids->get_height()))
333 { // New position is outsite the tilemap
337 { // Check if the tile allows us to go to new_pos
341 return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
342 && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
345 return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
346 && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
349 return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
350 && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
353 return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
354 && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
357 assert(!"path_ok() can't walk if direction is NONE");
364 WorldMap::finished_level(Level* gamelevel)
366 // TODO use Level* parameter here?
367 LevelTile* level = at_level();
369 bool old_level_state = level->solved;
370 level->solved = true;
371 level->sprite->set_action("solved");
373 // deal with statistics
374 level->statistics.merge(gamelevel->stats);
375 calculate_total_stats();
378 if(World::current() != NULL)
379 World::current()->save_state();
381 if (old_level_state != level->solved && level->auto_path) {
382 // Try to detect the next direction to which we should walk
383 // FIXME: Mostly a hack
384 Direction dir = D_NONE;
386 const Tile* tile = at(tux->get_tile_pos());
388 // first, test for crossroads
389 if (tile->getData() & Tile::WORLDMAP_CNSE || tile->getData() && Tile::WORLDMAP_CNSW
390 || tile->getData() & Tile::WORLDMAP_CNEW || tile->getData() && Tile::WORLDMAP_CSEW
391 || tile->getData() & Tile::WORLDMAP_CNSEW)
393 else if (tile->getData() & Tile::WORLDMAP_NORTH
394 && tux->back_direction != D_NORTH)
396 else if (tile->getData() & Tile::WORLDMAP_SOUTH
397 && tux->back_direction != D_SOUTH)
399 else if (tile->getData() & Tile::WORLDMAP_EAST
400 && tux->back_direction != D_EAST)
402 else if (tile->getData() & Tile::WORLDMAP_WEST
403 && tux->back_direction != D_WEST)
407 tux->set_direction(dir);
411 if (level->extro_script != "") {
413 std::istringstream in(level->extro_script);
414 run_script(in, "worldmap:extro_script");
415 } catch(std::exception& e) {
416 log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
422 WorldMap::update(float delta)
424 Menu* menu = Menu::current();
428 if(menu == worldmap_menu.get()) {
429 switch (worldmap_menu->check())
431 case MNID_RETURNWORLDMAP: // Return to game
432 Menu::set_current(0);
434 case MNID_QUITWORLDMAP: // Quit Worldmap
435 main_loop->exit_screen();
443 // update GameObjects
444 for(GameObjects::iterator i = game_objects.begin();
445 i != game_objects.end(); ++i) {
446 GameObject* object = *i;
447 object->update(delta);
450 // remove old GameObjects
451 for(GameObjects::iterator i = game_objects.begin();
452 i != game_objects.end(); ) {
453 GameObject* object = *i;
454 if(!object->is_valid()) {
456 i = game_objects.erase(i);
463 Vector tux_pos = tux->get_pos();
464 camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
465 camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
467 if (camera_offset.x < 0)
469 if (camera_offset.y < 0)
472 if (camera_offset.x > solids->get_width()*32 - SCREEN_WIDTH)
473 camera_offset.x = solids->get_width()*32 - SCREEN_WIDTH;
474 if (camera_offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
475 camera_offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
478 bool enter_level = false;
479 if(main_controller->pressed(Controller::ACTION)
480 || main_controller->pressed(Controller::JUMP)
481 || main_controller->pressed(Controller::MENU_SELECT))
483 if(main_controller->pressed(Controller::PAUSE_MENU))
486 if (enter_level && !tux->is_moving())
488 /* Check special tile action */
489 SpecialTile* special_tile = at_special_tile();
492 if (special_tile->teleport_dest != Vector(-1,-1))
494 // TODO: an animation, camera scrolling or a fading would be a nice touch
495 sound_manager->play("sounds/warp.wav");
496 tux->back_direction = D_NONE;
497 tux->set_tile_pos(special_tile->teleport_dest);
502 /* Check level action */
503 LevelTile* level = at_level();
505 log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
509 if (level->pos == tux->get_tile_pos()) {
511 Vector shrinkpos = Vector(level->pos.x*32 + 16 - camera_offset.x,
512 level->pos.y*32 + 16 - camera_offset.y);
513 std::string levelfile = levels_path + level->name;
514 main_loop->push_screen(new GameSession(levelfile, &level->statistics),
515 new ShrinkFade(shrinkpos, 0.5));
516 } catch(std::exception& e) {
517 log_fatal << "Couldn't load level: " << e.what() << std::endl;
523 // tux->set_direction(input_direction);
528 WorldMap::at(Vector p)
530 return solids->get_tile((int) p.x, (int) p.y);
536 for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
537 LevelTile* level = *i;
538 if (level->pos == tux->get_tile_pos())
546 WorldMap::at_special_tile()
548 for(SpecialTiles::iterator i = special_tiles.begin();
549 i != special_tiles.end(); ++i) {
550 SpecialTile* special_tile = *i;
551 if (special_tile->pos == tux->get_tile_pos())
559 WorldMap::at_sprite_change(const Vector& pos)
561 for(SpriteChanges::iterator i = sprite_changes.begin();
562 i != sprite_changes.end(); ++i) {
563 SpriteChange* sprite_change = *i;
564 if(sprite_change->pos == pos)
565 return sprite_change;
572 WorldMap::draw(DrawingContext& context)
574 context.push_transform();
575 context.set_translation(camera_offset);
577 for(GameObjects::iterator i = game_objects.begin();
578 i != game_objects.end(); ++i) {
579 GameObject* object = *i;
580 object->draw(context);
583 draw_status(context);
584 context.pop_transform();
588 WorldMap::draw_status(DrawingContext& context)
590 context.push_transform();
591 context.set_translation(Vector(0, 0));
593 player_status->draw(context);
595 if (!tux->is_moving()) {
596 for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
597 LevelTile* level = *i;
599 if (level->pos == tux->get_tile_pos()) {
600 if(level->title == "")
601 get_level_title(*level);
603 context.draw_text(white_text, level->title,
604 Vector(SCREEN_WIDTH/2,
605 SCREEN_HEIGHT - white_text->get_height() - 30),
606 CENTER_ALLIGN, LAYER_FOREGROUND1);
608 level->statistics.draw_worldmap_info(context);
613 for(SpecialTiles::iterator i = special_tiles.begin();
614 i != special_tiles.end(); ++i) {
615 SpecialTile* special_tile = *i;
617 if (special_tile->pos == tux->get_tile_pos()) {
618 /* Display an in-map message in the map, if any as been selected */
619 if(!special_tile->map_message.empty() && !special_tile->passive_message)
620 context.draw_text(gold_text, special_tile->map_message,
621 Vector(SCREEN_WIDTH/2,
622 SCREEN_HEIGHT - white_text->get_height() - 60),
623 CENTER_ALLIGN, LAYER_FOREGROUND1);
629 /* Display a passive message in the map, if needed */
630 if(passive_message_timer.started())
631 context.draw_text(gold_text, passive_message,
632 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
633 CENTER_ALLIGN, LAYER_FOREGROUND1);
635 context.pop_transform();
641 sound_manager->play_music(music);
642 Menu::set_current(NULL);
648 static void store_float(HSQUIRRELVM vm, const char* name, float val)
650 sq_pushstring(vm, name, -1);
651 sq_pushfloat(vm, val);
652 if(SQ_FAILED(sq_createslot(vm, -3)))
653 throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
657 static void store_int(HSQUIRRELVM vm, const char* name, int val)
659 sq_pushstring(vm, name, -1);
660 sq_pushinteger(vm, val);
661 if(SQ_FAILED(sq_createslot(vm, -3)))
662 throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
666 static void store_string(HSQUIRRELVM vm, const char* name, const std::string& val)
668 sq_pushstring(vm, name, -1);
669 sq_pushstring(vm, val.c_str(), val.length());
670 if(SQ_FAILED(sq_createslot(vm, -3)))
671 throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
674 static void store_bool(HSQUIRRELVM vm, const char* name, bool val)
676 sq_pushstring(vm, name, -1);
677 sq_pushbool(vm, val ? SQTrue : SQFalse);
678 if(SQ_FAILED(sq_createslot(vm, -3)))
679 throw Scripting::SquirrelError(vm, "Couldn't add float value to table");
682 static float read_float(HSQUIRRELVM vm, const char* name)
684 sq_pushstring(vm, name, -1);
685 if(SQ_FAILED(sq_get(vm, -2))) {
686 std::ostringstream msg;
687 msg << "Couldn't get float value for '" << name << "' from table";
688 throw Scripting::SquirrelError(vm, msg.str());
692 if(SQ_FAILED(sq_getfloat(vm, -1, &result))) {
693 std::ostringstream msg;
694 msg << "Couldn't get float value for '" << name << "' from table";
695 throw Scripting::SquirrelError(vm, msg.str());
702 static std::string read_string(HSQUIRRELVM vm, const char* name)
704 sq_pushstring(vm, name, -1);
705 if(SQ_FAILED(sq_get(vm, -2))) {
706 std::ostringstream msg;
707 msg << "Couldn't get string value for '" << name << "' from table";
708 throw Scripting::SquirrelError(vm, msg.str());
712 if(SQ_FAILED(sq_getstring(vm, -1, &result))) {
713 std::ostringstream msg;
714 msg << "Couldn't get string value for '" << name << "' from table";
715 throw Scripting::SquirrelError(vm, msg.str());
719 return std::string(result);
722 static bool read_bool(HSQUIRRELVM vm, const char* name)
724 sq_pushstring(vm, name, -1);
725 if(SQ_FAILED(sq_get(vm, -2))) {
726 std::ostringstream msg;
727 msg << "Couldn't get bool value for '" << name << "' from table";
728 throw Scripting::SquirrelError(vm, msg.str());
732 if(SQ_FAILED(sq_getbool(vm, -1, &result))) {
733 std::ostringstream msg;
734 msg << "Couldn't get bool value for '" << name << "' from table";
735 throw Scripting::SquirrelError(vm, msg.str());
739 return result == SQTrue;
743 WorldMap::save_state()
745 using namespace Scripting;
747 HSQUIRRELVM vm = global_vm;
748 int oldtop = sq_gettop(vm);
752 sq_pushroottable(vm);
753 sq_pushstring(vm, "state", -1);
754 if(SQ_FAILED(sq_get(vm, -2)))
755 throw Scripting::SquirrelError(vm, "Couldn't get state table");
757 // get or create worlds table
758 sq_pushstring(vm, "worlds", -1);
759 if(SQ_FAILED(sq_get(vm, -2))) {
760 sq_pushstring(vm, "worlds", -1);
762 if(SQ_FAILED(sq_createslot(vm, -3)))
763 throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
765 sq_pushstring(vm, "worlds", -1);
766 if(SQ_FAILED(sq_get(vm, -2)))
767 throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
770 sq_pushstring(vm, map_filename.c_str(), map_filename.length());
771 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
774 // construct new table for this worldmap
775 sq_pushstring(vm, map_filename.c_str(), map_filename.length());
779 sq_pushstring(vm, "tux", -1);
782 store_float(vm, "x", tux->get_tile_pos().x);
783 store_float(vm, "y", tux->get_tile_pos().y);
784 store_string(vm, "back", direction_to_string(tux->back_direction));
786 sq_createslot(vm, -3);
789 sq_pushstring(vm, "levels", -1);
792 for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
793 LevelTile* level = *i;
796 sq_pushstring(vm, level->name.c_str(), -1);
799 store_bool(vm, "solved", true);
800 // TODO write statistics
801 // i->statistics.write(writer);
803 sq_createslot(vm, -3);
807 sq_createslot(vm, -3);
809 // push world into worlds table
810 sq_createslot(vm, -3);
811 } catch(std::exception& e) {
812 sq_settop(vm, oldtop);
815 sq_settop(vm, oldtop);
819 WorldMap::load_state()
821 using namespace Scripting;
823 HSQUIRRELVM vm = global_vm;
824 int oldtop = sq_gettop(vm);
828 sq_pushroottable(vm);
829 sq_pushstring(vm, "state", -1);
830 if(SQ_FAILED(sq_get(vm, -2)))
831 throw Scripting::SquirrelError(vm, "Couldn't get state table");
834 sq_pushstring(vm, "worlds", -1);
835 if(SQ_FAILED(sq_get(vm, -2)))
836 throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
838 // get table for our world
839 sq_pushstring(vm, map_filename.c_str(), map_filename.length());
840 if(SQ_FAILED(sq_get(vm, -2)))
841 throw Scripting::SquirrelError(vm, "Couldn't get state.world.mapfilename");
844 sq_pushstring(vm, "tux", -1);
845 if(SQ_FAILED(sq_get(vm, -2)))
846 throw Scripting::SquirrelError(vm, "Couldn't get tux");
849 p.x = read_float(vm, "x");
850 p.y = read_float(vm, "y");
851 std::string back_str = read_string(vm, "back");
852 tux->back_direction = string_to_direction(back_str);
853 tux->set_tile_pos(p);
858 sq_pushstring(vm, "levels", -1);
859 if(SQ_FAILED(sq_get(vm, -2)))
860 throw Scripting::SquirrelError(vm, "Couldn't get levels");
862 for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
863 LevelTile* level = *i;
864 sq_pushstring(vm, level->name.c_str(), -1);
865 if(SQ_SUCCEEDED(sq_get(vm, -2))) {
866 level->solved = read_bool(vm, "solved");
867 level->sprite->set_action(level->solved ? "solved" : "default");
868 // i->statistics.parse(*level);
874 } catch(std::exception& e) {
875 log_debug << "Not loading worldmap state: " << e.what() << std::endl;
877 sq_settop(vm, oldtop);
881 WorldMap::level_count()
883 return levels.size();
887 WorldMap::solved_level_count()
890 for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
891 LevelTile* level = *i;
901 WorldMap::run_script(std::istream& in, const std::string& sourcename)
903 using namespace Scripting;
905 // garbage collect thread list
906 for(ScriptList::iterator i = scripts.begin();
907 i != scripts.end(); ) {
908 HSQOBJECT& object = *i;
909 HSQUIRRELVM vm = object_to_vm(object);
911 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
912 sq_release(global_vm, &object);
913 i = scripts.erase(i);
920 HSQOBJECT object = create_thread(global_vm);
921 scripts.push_back(object);
923 HSQUIRRELVM vm = object_to_vm(object);
925 compile_and_run(vm, in, sourcename);
930 } // namespace WorldMapNS