257cbc83d55cc380d16f62808d7c7a4b1b356e0d
[supertux.git] / src / worldmap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <iostream>
22 #include <fstream>
23 #include <vector>
24 #include <cassert>
25 #include <stdexcept>
26 #include <sstream>
27 #include <unistd.h>
28 #include <physfs.h>
29
30 #include "gettext.hpp"
31 #include "video/surface.hpp"
32 #include "video/screen.hpp"
33 #include "video/drawing_context.hpp"
34 #include "sprite/sprite_manager.hpp"
35 #include "audio/sound_manager.hpp"
36 #include "lisp/parser.hpp"
37 #include "lisp/lisp.hpp"
38 #include "lisp/list_iterator.hpp"
39 #include "lisp/writer.hpp"
40 #include "game_session.hpp"
41 #include "sector.hpp"
42 #include "worldmap.hpp"
43 #include "resources.hpp"
44 #include "misc.hpp"
45 #include "player_status.hpp"
46 #include "textscroller.hpp"
47 #include "main.hpp"
48 #include "spawn_point.hpp"
49 #include "file_system.hpp"
50 #include "gui/menu.hpp"
51 #include "gui/mousecursor.hpp"
52 #include "control/joystickkeyboardcontroller.hpp"
53 #include "object/background.hpp"
54 #include "object/tilemap.hpp"
55 #include "scripting/script_interpreter.hpp"
56 #include "exceptions.hpp"
57
58 Menu* worldmap_menu  = 0;
59
60 static const float TUXSPEED = 200;
61 static const float map_message_TIME = 2.8;
62
63 namespace WorldMapNS {
64
65 Direction reverse_dir(Direction direction)
66 {
67   switch(direction)
68     {
69     case D_WEST:
70       return D_EAST;
71     case D_EAST:
72       return D_WEST;
73     case D_NORTH:
74       return D_SOUTH;
75     case D_SOUTH:
76       return D_NORTH;
77     case D_NONE:
78       return D_NONE;
79     }
80   return D_NONE;
81 }
82
83 std::string
84 direction_to_string(Direction direction)
85 {
86   switch(direction)
87     {
88     case D_WEST:
89       return "west";
90     case D_EAST:
91       return "east";
92     case D_NORTH:
93       return "north";
94     case D_SOUTH:
95       return "south";
96     default:
97       return "none";
98     }
99 }
100
101 Direction
102 string_to_direction(const std::string& directory)
103 {
104   if (directory == "west")
105     return D_WEST;
106   else if (directory == "east")
107     return D_EAST;
108   else if (directory == "north")
109     return D_NORTH;
110   else if (directory == "south")
111     return D_SOUTH;
112   else
113     return D_NONE;
114 }
115
116 //---------------------------------------------------------------------------
117
118 Tux::Tux(WorldMap* worldmap_)
119   : worldmap(worldmap_)
120 {
121   tux_sprite = sprite_manager->create("worldmaptux");
122   
123   offset = 0;
124   moving = false;
125   direction = D_NONE;
126   input_direction = D_NONE;
127 }
128
129 Tux::~Tux()
130 {
131   delete tux_sprite;
132 }
133
134 void
135 Tux::draw(DrawingContext& context)
136 {
137   switch (player_status->bonus) {
138     case GROWUP_BONUS:
139       tux_sprite->set_action("large");
140       break;
141     case FIRE_BONUS:
142       tux_sprite->set_action("fire");
143       break;
144     case NO_BONUS:
145       tux_sprite->set_action("small");
146       break;
147     default:
148 #ifdef DEBUG
149       std::cerr << "Bonus type not handled in worldmap.\n";
150 #endif
151       tux_sprite->set_action("large");
152       break;
153   }
154
155   tux_sprite->draw(context, get_pos(), LAYER_OBJECTS);
156 }
157
158
159 Vector
160 Tux::get_pos()
161 {
162   float x = tile_pos.x * 32;
163   float y = tile_pos.y * 32;
164
165   switch(direction)
166     {
167     case D_WEST:
168       x -= offset - 32;
169       break;
170     case D_EAST:
171       x += offset - 32;
172       break;
173     case D_NORTH:
174       y -= offset - 32;
175       break;
176     case D_SOUTH:
177       y += offset - 32;
178       break;
179     case D_NONE:
180       break;
181     }
182   
183   return Vector(x, y);
184 }
185
186 void
187 Tux::stop()
188 {
189   offset = 0;
190   direction = D_NONE;
191   input_direction = D_NONE;
192   moving = false;
193 }
194
195 void
196 Tux::set_direction(Direction dir)
197 {
198   input_direction = dir;
199 }
200
201 void
202 Tux::update(float delta)
203 {
204   // check controller
205   if(main_controller->pressed(Controller::UP))
206     input_direction = D_NORTH;
207   else if(main_controller->pressed(Controller::DOWN))
208     input_direction = D_SOUTH;
209   else if(main_controller->pressed(Controller::LEFT))
210     input_direction = D_WEST;
211   else if(main_controller->pressed(Controller::RIGHT))
212     input_direction = D_EAST;
213
214   if(!moving)
215     {
216       if (input_direction != D_NONE)
217         { 
218           WorldMap::Level* level = worldmap->at_level();
219
220           // We got a new direction, so lets start walking when possible
221           Vector next_tile;
222           if ((!level || level->solved)
223               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
224             {
225               tile_pos = next_tile;
226               moving = true;
227               direction = input_direction;
228               back_direction = reverse_dir(direction);
229             }
230           else if (input_direction == back_direction)
231             {
232               moving = true;
233               direction = input_direction;
234               tile_pos = worldmap->get_next_tile(tile_pos, direction);
235               back_direction = reverse_dir(direction);
236             }
237         }
238     }
239   else
240     {
241       // Let tux walk
242       offset += TUXSPEED * delta;
243
244       if (offset > 32)
245         { // We reached the next tile, so we check what to do now
246           offset -= 32;
247
248           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
249           if(special_tile && special_tile->passive_message)
250             {  // direction and the apply_action_ are opposites, since they "see"
251                // directions in a different way
252             if((direction == D_NORTH && special_tile->apply_action_south) ||
253                (direction == D_SOUTH && special_tile->apply_action_north) ||
254                (direction == D_WEST && special_tile->apply_action_east) ||
255                (direction == D_EAST && special_tile->apply_action_west))
256               {
257               worldmap->passive_message = special_tile->map_message;
258               worldmap->passive_message_timer.start(map_message_TIME);
259               }
260             }
261
262           if (worldmap->at(tile_pos)->getData() & Tile::WORLDMAP_STOP ||
263              (special_tile && !special_tile->passive_message) ||
264               worldmap->at_level())
265             {
266               if(special_tile && !special_tile->map_message.empty() &&
267                 !special_tile->passive_message)
268                 worldmap->passive_message_timer.start(0);
269               stop();
270             }
271           else
272             {
273               const Tile* tile = worldmap->at(tile_pos);
274               if (direction != input_direction)
275                 { 
276                   // Turn to a new direction
277                   const Tile* tile = worldmap->at(tile_pos);
278
279                   if((tile->getData() & Tile::WORLDMAP_NORTH 
280                       && input_direction == D_NORTH) ||
281                      (tile->getData() & Tile::WORLDMAP_SOUTH
282                       && input_direction == D_SOUTH) ||
283                      (tile->getData() & Tile::WORLDMAP_EAST
284                       && input_direction == D_EAST) ||
285                      (tile->getData() & Tile::WORLDMAP_WEST
286                       && input_direction == D_WEST))
287                     {  // player has changed direction during auto-movement
288                       direction = input_direction;
289                       back_direction = reverse_dir(direction);
290                     }
291                   else
292                     {  // player has changed to impossible tile
293                       back_direction = reverse_dir(direction);
294                       stop();
295                     }
296                 }
297               else
298                 {
299                 Direction dir = D_NONE;
300               
301                 if (tile->getData() & Tile::WORLDMAP_NORTH
302                     && back_direction != D_NORTH)
303                   dir = D_NORTH;
304                 else if (tile->getData() & Tile::WORLDMAP_SOUTH
305                     && back_direction != D_SOUTH)
306                   dir = D_SOUTH;
307                 else if (tile->getData() & Tile::WORLDMAP_EAST
308                     && back_direction != D_EAST)
309                   dir = D_EAST;
310                 else if (tile->getData() & Tile::WORLDMAP_WEST
311                     && back_direction != D_WEST)
312                   dir = D_WEST;
313
314                 if (dir != D_NONE)
315                   {
316                   direction = dir;
317                   input_direction = direction;
318                   back_direction = reverse_dir(direction);
319                   }
320                 else
321                   {
322                   // Should never be reached if tiledata is good
323                   stop();
324                   return;
325                   }
326                 }
327
328               // Walk automatically to the next tile
329               if(direction != D_NONE)
330                 {
331                 Vector next_tile;
332                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
333                   {
334                   tile_pos = next_tile;
335                   }
336                 else
337                   {
338                   puts("Tilemap data is buggy");
339                   stop();
340                   }
341                 }
342             }
343         }
344     }
345 }
346
347 //---------------------------------------------------------------------------
348
349 WorldMap::WorldMap()
350   : tux(0), solids(0)
351 {
352   tile_manager = new TileManager("images/worldmap.strf");
353   
354   tux = new Tux(this);
355   add_object(tux);
356     
357   messagedot = new Surface("images/worldmap/common/messagedot.png");
358   teleporterdot = new Surface("images/worldmap/common/teleporterdot.png");
359
360   name = "<no title>";
361   music = "salcon.ogg";
362   intro_displayed = false;
363
364   total_stats.reset();
365 }
366
367 WorldMap::~WorldMap()
368 {
369   clear_objects();
370   for(SpawnPoints::iterator i = spawn_points.begin();
371       i != spawn_points.end(); ++i) {
372     delete *i;
373   }
374   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
375     Level& level = *i;
376     delete level.sprite;
377   }
378   
379   delete tile_manager;
380
381   delete messagedot;
382   delete teleporterdot;
383 }
384
385 void
386 WorldMap::add_object(GameObject* object)
387 {
388   TileMap* tilemap = dynamic_cast<TileMap*> (object);
389   if(tilemap != 0 && tilemap->is_solid()) {
390     solids = tilemap;
391   }
392
393   game_objects.push_back(object);
394 }
395
396 void
397 WorldMap::clear_objects()
398 {
399   for(GameObjects::iterator i = game_objects.begin();
400       i != game_objects.end(); ++i)
401     delete *i;
402   game_objects.clear();
403   solids = 0;
404   tux = new Tux(this);
405   add_object(tux);
406 }
407
408 // Don't forget to set map_filename before calling this
409 void
410 WorldMap::load_map()
411 {
412   levels_path = FileSystem::dirname(map_filename);
413
414   try {
415     lisp::Parser parser;
416     std::auto_ptr<lisp::Lisp> root (parser.parse(map_filename));
417
418     const lisp::Lisp* lisp = root->get_lisp("supertux-worldmap");
419     if(!lisp)
420       throw std::runtime_error("file isn't a supertux-worldmap file.");
421
422     clear_objects();
423     lisp::ListIterator iter(lisp);
424     while(iter.next()) {
425       if(iter.item() == "tilemap") {
426         add_object(new TileMap(*(iter.lisp()), tile_manager));
427       } else if(iter.item() == "background") {
428         add_object(new Background(*(iter.lisp())));
429       } else if(iter.item() == "properties") {
430         const lisp::Lisp* props = iter.lisp();
431         props->get("name", name);
432         props->get("music", music);
433       } else if(iter.item() == "intro-script") {
434         iter.value()->get(intro_script);
435       } else if(iter.item() == "spawnpoint") {
436         SpawnPoint* sp = new SpawnPoint(iter.lisp());
437         spawn_points.push_back(sp);
438       } else if(iter.item() == "level") {
439         parse_level_tile(iter.lisp());
440       } else if(iter.item() == "special-tile") {
441         parse_special_tile(iter.lisp());
442       } else {
443         std::cerr << "Unknown token '" << iter.item() << "' in worldmap.\n";
444       }
445     }
446     if(solids == 0)
447       throw std::runtime_error("No solid tilemap specified");
448
449     // search for main spawnpoint
450     for(SpawnPoints::iterator i = spawn_points.begin();
451         i != spawn_points.end(); ++i) {
452       SpawnPoint* sp = *i;
453       if(sp->name == "main") {
454         Vector p = sp->pos;
455         tux->set_tile_pos(p);
456         break;
457       }
458     }
459
460   } catch(std::exception& e) {
461     std::stringstream msg;
462     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
463       e.what();
464     throw std::runtime_error(msg.str());
465   }
466 }
467
468 void
469 WorldMap::parse_special_tile(const lisp::Lisp* lisp)
470 {
471   SpecialTile special_tile;
472   
473   lisp->get("x", special_tile.pos.x);
474   lisp->get("y", special_tile.pos.y);
475   lisp->get("map-message", special_tile.map_message);
476   special_tile.passive_message = false;
477   lisp->get("passive-message", special_tile.passive_message);
478   special_tile.teleport_dest = Vector(-1,-1);
479   lisp->get("teleport-to-x", special_tile.teleport_dest.x);
480   lisp->get("teleport-to-y", special_tile.teleport_dest.y);
481   special_tile.invisible = false;
482   lisp->get("invisible-tile", special_tile.invisible);
483
484   special_tile.apply_action_north = true;
485   special_tile.apply_action_south = true;
486   special_tile.apply_action_east = true;
487   special_tile.apply_action_west = true;
488
489   std::string apply_direction;
490   lisp->get("apply-to-direction", apply_direction);
491   if(!apply_direction.empty()) {
492     special_tile.apply_action_north = false;
493     special_tile.apply_action_south = false;
494     special_tile.apply_action_east = false;
495     special_tile.apply_action_west = false;
496     if(apply_direction.find("north") != std::string::npos)
497       special_tile.apply_action_north = true;
498     if(apply_direction.find("south") != std::string::npos)
499       special_tile.apply_action_south = true;
500     if(apply_direction.find("east") != std::string::npos)
501       special_tile.apply_action_east = true;
502     if(apply_direction.find("west") != std::string::npos)
503       special_tile.apply_action_west = true;
504   }
505   
506   special_tiles.push_back(special_tile);
507 }
508
509 void
510 WorldMap::parse_level_tile(const lisp::Lisp* level_lisp)
511 {
512   Level level;
513
514   level.solved = false;
515                   
516   level.north = true;
517   level.east  = true;
518   level.south = true;
519   level.west  = true;
520
521   std::string sprite = "images/worldmap/common/leveldot.sprite";
522   level_lisp->get("sprite", sprite);
523   level.sprite = sprite_manager->create(sprite);
524
525   level_lisp->get("extro-script", level.extro_script);
526   level_lisp->get("next-worldmap", level.next_worldmap);
527
528   level.quit_worldmap = false;
529   level_lisp->get("quit-worldmap", level.quit_worldmap);
530
531   level_lisp->get("name", level.name);
532   level_lisp->get("x", level.pos.x);
533   level_lisp->get("y", level.pos.y);
534
535   level.auto_path = true;
536   level_lisp->get("auto-path", level.auto_path);
537
538   level.vertical_flip = false;
539   level_lisp->get("vertical-flip", level.vertical_flip);
540
541   levels.push_back(level);
542 }
543
544 void
545 WorldMap::get_level_title(Level& level)
546 {
547   /** get special_tile's title */
548   level.title = "<no title>";
549
550   try {
551     lisp::Parser parser;
552     std::auto_ptr<lisp::Lisp> root (parser.parse(levels_path + level.name));
553
554     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
555     if(!level_lisp)
556       return;
557     
558     level_lisp->get("name", level.title);
559   } catch(std::exception& e) {
560     std::cerr << "Problem when reading leveltitle: " << e.what() << "\n";
561     return;
562   }
563 }
564
565 void WorldMap::calculate_total_stats()
566 {
567   total_stats.reset();
568   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
569     {
570     if (i->solved)
571       {
572       total_stats += i->statistics;
573       }
574     }
575 }
576
577 void
578 WorldMap::on_escape_press()
579 {
580   // Show or hide the menu
581   if(!Menu::current()) {
582     Menu::set_current(worldmap_menu);
583     tux->set_direction(D_NONE);  // stop tux movement when menu is called
584   } else {
585     Menu::set_current(0);
586   }
587 }
588
589 void
590 WorldMap::get_input()
591 {
592   main_controller->update();
593
594   SDL_Event event;
595   while (SDL_PollEvent(&event)) {
596     if (Menu::current())
597       Menu::current()->event(event);
598     main_controller->process_event(event);
599     if(event.type == SDL_QUIT)
600       throw graceful_shutdown();
601   }
602 }
603
604 Vector
605 WorldMap::get_next_tile(Vector pos, Direction direction)
606 {
607   switch(direction) {
608     case D_WEST:
609       pos.x -= 1;
610       break;
611     case D_EAST:
612       pos.x += 1;
613       break;
614     case D_NORTH:
615       pos.y -= 1;
616       break;
617     case D_SOUTH:
618       pos.y += 1;
619       break;
620     case D_NONE:
621       break;
622   }
623   return pos;
624 }
625
626 bool
627 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
628 {
629   *new_pos = get_next_tile(old_pos, direction);
630
631   if (!(new_pos->x >= 0 && new_pos->x < solids->get_width()
632         && new_pos->y >= 0 && new_pos->y < solids->get_height()))
633     { // New position is outsite the tilemap
634       return false;
635     }
636   else
637     { // Check if the tile allows us to go to new_pos
638       switch(direction)
639         {
640         case D_WEST:
641           return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
642               && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
643
644         case D_EAST:
645           return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
646               && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
647
648         case D_NORTH:
649           return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
650               && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
651
652         case D_SOUTH:
653           return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
654               && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
655
656         case D_NONE:
657           assert(!"path_ok() can't work if direction is NONE");
658         }
659       return false;
660     }
661 }
662
663 void
664 WorldMap::update(float delta)
665 {
666   Menu* menu = Menu::current();
667   if(menu) {
668     menu->update();
669
670     if(menu == worldmap_menu) {
671       switch (worldmap_menu->check())
672       {
673         case MNID_RETURNWORLDMAP: // Return to game  
674           Menu::set_current(0);
675           break;
676         case MNID_QUITWORLDMAP: // Quit Worldmap
677           quit = true;                               
678           break;
679       }
680     } else if(menu == options_menu) {
681       process_options_menu();
682     }
683
684     return;
685   }
686
687   // update GameObjects
688   for(GameObjects::iterator i = game_objects.begin();
689       i != game_objects.end(); ++i) {
690     GameObject* object = *i;
691     object->update(delta);
692   }
693   // remove old GameObjects
694   for(GameObjects::iterator i = game_objects.begin();
695       i != game_objects.end(); ) {
696     GameObject* object = *i;
697     if(!object->is_valid()) {
698       delete object;
699       i = game_objects.erase(i);
700     } else {
701       ++i;
702     }
703   }
704   
705   bool enter_level = false;
706   if(main_controller->pressed(Controller::ACTION)
707       || main_controller->pressed(Controller::JUMP)
708       || main_controller->pressed(Controller::MENU_SELECT))
709     enter_level = true;
710   if(main_controller->pressed(Controller::PAUSE_MENU))
711     on_escape_press();
712   
713   if (enter_level && !tux->is_moving())
714     {
715       /* Check special tile action */
716       SpecialTile* special_tile = at_special_tile();
717       if(special_tile)
718         {
719         if (special_tile->teleport_dest != Vector(-1,-1))
720           {
721           // TODO: an animation, camera scrolling or a fading would be a nice touch
722           sound_manager->play("sounds/warp.wav");
723           tux->back_direction = D_NONE;
724           tux->set_tile_pos(special_tile->teleport_dest);
725           SDL_Delay(1000);
726           }
727         }
728
729       /* Check level action */
730       bool level_finished = true;
731       Level* level = at_level();
732       if (!level)
733         {
734         std::cout << "No level to enter at: "
735           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y
736           << std::endl;
737         return;
738         }
739
740
741       if (level->pos == tux->get_tile_pos())
742         {
743           sound_manager->stop_music();
744           PlayerStatus old_player_status;
745           old_player_status = *player_status;
746
747           // do a shriking fade to the level
748           shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
749                              (level->pos.y*32 + 16 + offset.y)), 500);
750           GameSession session(levels_path + level->name,
751                               ST_GL_LOAD_LEVEL_FILE, &level->statistics);
752
753           switch (session.run())
754             {
755             case GameSession::ES_LEVEL_FINISHED:
756               {
757                 level_finished = true;
758                 bool old_level_state = level->solved;
759                 level->solved = true;
760                 level->sprite->set_action("solved");
761
762                 // deal with statistics
763                 level->statistics.merge(global_stats);
764                 calculate_total_stats();
765
766                 if (old_level_state != level->solved && level->auto_path)
767                   { // Try to detect the next direction to which we should walk
768                     // FIXME: Mostly a hack
769                     Direction dir = D_NONE;
770                 
771                     const Tile* tile = at(tux->get_tile_pos());
772
773                     if (tile->getData() & Tile::WORLDMAP_NORTH
774                         && tux->back_direction != D_NORTH)
775                       dir = D_NORTH;
776                     else if (tile->getData() & Tile::WORLDMAP_SOUTH
777                         && tux->back_direction != D_SOUTH)
778                       dir = D_SOUTH;
779                     else if (tile->getData() & Tile::WORLDMAP_EAST
780                         && tux->back_direction != D_EAST)
781                       dir = D_EAST;
782                     else if (tile->getData() & Tile::WORLDMAP_WEST
783                         && tux->back_direction != D_WEST)
784                       dir = D_WEST;
785
786                     if (dir != D_NONE)
787                       {
788                         tux->set_direction(dir);
789                       }
790                   }
791               }
792
793               break;
794             case GameSession::ES_LEVEL_ABORT:
795               level_finished = false;
796               /* In case the player's abort the level, keep it using the old
797                   status. But the minimum lives and no bonus. */
798               player_status->coins = old_player_status.coins;
799               player_status->lives = std::min(old_player_status.lives, player_status->lives);
800               player_status->bonus = NO_BONUS;
801
802               break;
803             case GameSession::ES_GAME_OVER:
804               {
805               level_finished = false;
806               /* draw an end screen */
807               /* TODO: in the future, this should make a dialog a la SuperMario, asking
808               if the player wants to restart the world map with no score and from
809               level 1 */
810               char str[80];
811
812               DrawingContext context;
813               context.draw_gradient(Color (200,240,220), Color(200,200,220),
814                   LAYER_BACKGROUND0);
815
816               context.draw_text(blue_text, _("GAMEOVER"), 
817                   Vector(SCREEN_WIDTH/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
818
819               sprintf(str, _("COINS: %d"), player_status->coins);
820               context.draw_text(gold_text, str,
821                   Vector(SCREEN_WIDTH/2, SCREEN_WIDTH - 32), CENTER_ALLIGN,
822                   LAYER_FOREGROUND1);
823
824               total_stats.draw_message_info(context, _("Total Statistics"));
825
826               context.do_drawing();
827
828               wait_for_event(2.0, 6.0);
829
830               quit = true;
831               player_status->reset();
832               break;
833               }
834             case GameSession::ES_NONE:
835               assert(false);
836               // Should never be reached 
837               break;
838             }
839
840           sound_manager->play_music(std::string("music/") + music);
841           Menu::set_current(0);
842           if (!savegame_file.empty())
843             savegame(savegame_file);
844         }
845       /* The porpose of the next checking is that if the player lost
846          the level (in case there is one), don't show anything */
847       if(level_finished) {
848         if (level->extro_script != "") {
849           try {
850             std::auto_ptr<ScriptInterpreter> interpreter 
851               (new ScriptInterpreter(levels_path));
852             std::istringstream in(level->extro_script);
853             interpreter->run_script(in, "level-extro-script");
854             add_object(interpreter.release());
855           } catch(std::exception& e) {
856             std::cerr << "Couldn't run level-extro-script:" << e.what() << "\n";
857           }
858         }
859
860         if (!level->next_worldmap.empty())
861           {
862           // Load given worldmap
863           loadmap(level->next_worldmap);
864           }
865         if (level->quit_worldmap)
866           quit = true;
867         }
868     }
869   else
870     {
871 //      tux->set_direction(input_direction);
872     }
873 }
874
875 const Tile*
876 WorldMap::at(Vector p)
877 {
878   return solids->get_tile((int) p.x, (int) p.y);
879 }
880
881 WorldMap::Level*
882 WorldMap::at_level()
883 {
884   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
885     {
886       if (i->pos == tux->get_tile_pos())
887         return &*i; 
888     }
889
890   return 0;
891 }
892
893 WorldMap::SpecialTile*
894 WorldMap::at_special_tile()
895 {
896   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
897     {
898       if (i->pos == tux->get_tile_pos())
899         return &*i; 
900     }
901
902   return 0;
903 }
904
905 void
906 WorldMap::draw(DrawingContext& context)
907 {
908   for(GameObjects::iterator i = game_objects.begin();
909       i != game_objects.end(); ++i) {
910     GameObject* object = *i;
911     object->draw(context);
912   }
913   
914   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
915     {
916       const Level& level = *i;
917       level.sprite->draw(context, level.pos*32 + Vector(16, 16), LAYER_TILES+1);
918     }
919
920   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
921     {
922       if(i->invisible)
923         continue;
924
925       if (i->teleport_dest != Vector(-1, -1))
926         context.draw_surface(teleporterdot,
927                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
928
929       else if (!i->map_message.empty() && !i->passive_message)
930         context.draw_surface(messagedot,
931                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
932     }
933
934   draw_status(context);
935 }
936
937 void
938 WorldMap::draw_status(DrawingContext& context)
939 {
940   context.push_transform();
941   context.set_translation(Vector(0, 0));
942  
943   player_status->draw(context);
944
945   if (!tux->is_moving())
946     {
947       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
948         {
949           if (i->pos == tux->get_tile_pos())
950             {
951               if(i->title == "")
952                 get_level_title(*i);
953
954               context.draw_text(white_text, i->title, 
955                   Vector(SCREEN_WIDTH/2,
956                          SCREEN_HEIGHT - white_text->get_height() - 30),
957                   CENTER_ALLIGN, LAYER_FOREGROUND1);
958
959               i->statistics.draw_worldmap_info(context);
960               break;
961             }
962         }
963       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
964         {
965           if (i->pos == tux->get_tile_pos())
966             {
967                /* Display an in-map message in the map, if any as been selected */
968               if(!i->map_message.empty() && !i->passive_message)
969                 context.draw_text(gold_text, i->map_message, 
970                     Vector(SCREEN_WIDTH/2,
971                            SCREEN_HEIGHT - white_text->get_height() - 60),
972                     CENTER_ALLIGN, LAYER_FOREGROUND1);
973               break;
974             }
975         }
976     }
977   /* Display a passive message in the map, if needed */
978   if(passive_message_timer.started())
979     context.draw_text(gold_text, passive_message, 
980             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
981             CENTER_ALLIGN, LAYER_FOREGROUND1);
982
983   context.pop_transform();
984 }
985
986 void
987 WorldMap::display()
988 {
989   Menu::set_current(0);
990
991   quit = false;
992
993   sound_manager->play_music(std::string("music/") + music);
994
995   if(!intro_displayed && intro_script != "") {
996     try {
997       std::auto_ptr<ScriptInterpreter> interpreter 
998         (new ScriptInterpreter(levels_path));
999       std::istringstream in(intro_script);
1000       interpreter->run_script(in, "worldmap-intro-script");
1001       add_object(interpreter.release());
1002     } catch(std::exception& e) {
1003       std::cerr << "Couldn't execute worldmap-intro-script: "
1004         << e.what() << "\n";
1005     }
1006                                            
1007     intro_displayed = true;
1008   }
1009
1010   Uint32 lastticks = SDL_GetTicks();
1011   DrawingContext context;
1012   while(!quit) {
1013     Uint32 ticks = SDL_GetTicks();
1014     float elapsed_time = float(ticks - lastticks) / 1000;
1015     game_time += elapsed_time;
1016     lastticks = ticks;
1017     
1018     // 40 fps minimum // TODO use same code as in GameSession here
1019     if(elapsed_time > .025)
1020       elapsed_time = .025;
1021     
1022     Vector tux_pos = tux->get_pos();
1023     offset.x = tux_pos.x - SCREEN_WIDTH/2;
1024     offset.y = tux_pos.y - SCREEN_HEIGHT/2;
1025
1026     if (offset.x < 0)
1027       offset.x = 0;
1028     if (offset.y < 0)
1029       offset.y = 0;
1030
1031     if (offset.x > solids->get_width()*32 - SCREEN_WIDTH)
1032       offset.x = solids->get_width()*32 - SCREEN_WIDTH;
1033     if (offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
1034       offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
1035
1036     context.push_transform();
1037     context.set_translation(offset);
1038     draw(context);
1039     context.pop_transform();
1040     get_input();
1041     update(elapsed_time);
1042     sound_manager->update();
1043       
1044     if(Menu::current()) {
1045       Menu::current()->draw(context);
1046     }
1047
1048     context.do_drawing();
1049   }
1050 }
1051
1052 void
1053 WorldMap::savegame(const std::string& filename)
1054 {
1055   if(filename == "")
1056     return;
1057
1058   std::string dir = FileSystem::dirname(filename);
1059   if(PHYSFS_exists(dir.c_str()) == 0 && PHYSFS_mkdir(dir.c_str()) == 0) {
1060     std::ostringstream msg;
1061     msg << "Couldn't create directory '" << dir << "' for savegame:"
1062         << PHYSFS_getLastError();
1063     throw std::runtime_error(msg.str());
1064   }
1065   if(!PHYSFS_isDirectory(dir.c_str())) {
1066     std::ostringstream msg;
1067     msg << "'" << dir << "' is not a directory.";
1068     throw std::runtime_error(msg.str());
1069   }
1070   
1071   lisp::Writer writer(filename);
1072
1073   int nb_solved_levels = 0, total_levels = 0;
1074   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
1075     ++total_levels;
1076     if (i->solved)
1077       ++nb_solved_levels;
1078   }
1079   char nb_solved_levels_str[80], total_levels_str[80];
1080   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1081   sprintf(total_levels_str, "%d", total_levels);
1082
1083   writer.write_comment("Worldmap save file");
1084
1085   writer.start_list("supertux-savegame");
1086
1087   writer.write_int("version", 1);
1088   writer.write_string("title",
1089       std::string(name + " - " + nb_solved_levels_str+"/"+total_levels_str));
1090   writer.write_string("map", map_filename);
1091   writer.write_bool("intro-displayed", intro_displayed);
1092
1093   writer.start_list("tux");
1094
1095   writer.write_float("x", tux->get_tile_pos().x);
1096   writer.write_float("y", tux->get_tile_pos().y);
1097   writer.write_string("back", direction_to_string(tux->back_direction));
1098   player_status->write(writer);
1099   writer.write_string("back", direction_to_string(tux->back_direction));
1100
1101   writer.end_list("tux");
1102
1103   writer.start_list("levels");
1104
1105   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1106     {
1107       if (i->solved)
1108         {
1109         writer.start_list("level");
1110
1111         writer.write_string("name", i->name);
1112         writer.write_bool("solved", true);
1113         i->statistics.write(writer);
1114
1115         writer.end_list("level");
1116         }
1117     }  
1118
1119   writer.end_list("levels");
1120
1121   writer.end_list("supertux-savegame");
1122 }
1123
1124 void
1125 WorldMap::loadgame(const std::string& filename)
1126 {
1127   std::cout << "loadgame: " << filename << std::endl;
1128   savegame_file = filename;
1129   
1130   if (PHYSFS_exists(filename.c_str())) // savegame exists
1131   {
1132     try {
1133       lisp::Parser parser;
1134       
1135       std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
1136     
1137       const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
1138       if(!savegame)
1139         throw std::runtime_error("File is not a supertux-savegame file.");
1140
1141       /* Get the Map filename and then load it before setting level settings */
1142       std::string cur_map_filename = map_filename;
1143       savegame->get("map", map_filename);
1144       load_map(); 
1145
1146       savegame->get("intro-displayed", intro_displayed);
1147       savegame->get("lives", player_status->lives);
1148       savegame->get("coins", player_status->coins);
1149       savegame->get("max-score-multiplier", player_status->max_score_multiplier);
1150       if (player_status->lives < 0)
1151       player_status->reset();
1152
1153       const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
1154       if(tux)
1155       {
1156         Vector p;
1157         std::string back_str = "none";
1158
1159         tux_lisp->get("x", p.x);
1160         tux_lisp->get("y", p.y);
1161         tux_lisp->get("back", back_str);
1162           player_status->read(*tux_lisp);
1163       
1164         tux->back_direction = string_to_direction(back_str);      
1165         tux->set_tile_pos(p);
1166       }
1167
1168       const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
1169       if(levels_lisp) {
1170         lisp::ListIterator iter(levels_lisp);
1171         while(iter.next()) {
1172           if(iter.item() == "level") {
1173             std::string name;
1174             bool solved = false;
1175
1176             const lisp::Lisp* level = iter.lisp();
1177             level->get("name", name);
1178             level->get("solved", solved);
1179
1180             for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1181             {
1182               if (name == i->name)
1183               {
1184                 i->solved = solved;
1185                 i->sprite->set_action(solved ? "solved" : "default");
1186                 i->statistics.parse(*level);
1187                 break;
1188               }
1189             }
1190           } else {
1191             std::cerr << "Unknown token '" << iter.item() 
1192                       << "' in levels block in worldmap.\n";
1193           }
1194         }
1195       }
1196     } catch(std::exception& e) {
1197       std::cerr << "Problem loading game '" << filename << "': " << e.what() 
1198                 << "\n";
1199       load_map();
1200       player_status->reset();
1201     }
1202   }
1203   else
1204   {
1205         load_map();
1206     player_status->reset();
1207   }
1208
1209   calculate_total_stats();
1210 }
1211
1212 void
1213 WorldMap::loadmap(const std::string& filename)
1214 {
1215   savegame_file = "";
1216   map_filename = filename;
1217   load_map();
1218 }
1219
1220 } // namespace WorldMapNS