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