Added support for tile animation on worldmap.
[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
20 #include <iostream>
21 #include <fstream>
22 #include <vector>
23 #include <cassert>
24 #include <unistd.h>
25
26 #include "app/globals.h"
27 #include "video/surface.h"
28 #include "video/screen.h"
29 #include "video/drawing_context.h"
30 #include "utils/lispreader.h"
31 #include "utils/lispwriter.h"
32 #include "special/frame_rate.h"
33 #include "gameloop.h"
34 #include "app/setup.h"
35 #include "sector.h"
36 #include "worldmap.h"
37 #include "audio/sound_manager.h"
38 #include "resources.h"
39 #include "app/gettext.h"
40 #include "misc.h"
41
42 #define map_message_TIME 2800
43
44 Menu* worldmap_menu  = 0;
45
46 namespace WorldMapNS {
47
48 Direction reverse_dir(Direction direction)
49 {
50   switch(direction)
51     {
52     case D_WEST:
53       return D_EAST;
54     case D_EAST:
55       return D_WEST;
56     case D_NORTH:
57       return D_SOUTH;
58     case D_SOUTH:
59       return D_NORTH;
60     case D_NONE:
61       return D_NONE;
62     }
63   return D_NONE;
64 }
65
66 std::string
67 direction_to_string(Direction direction)
68 {
69   switch(direction)
70     {
71     case D_WEST:
72       return "west";
73     case D_EAST:
74       return "east";
75     case D_NORTH:
76       return "north";
77     case D_SOUTH:
78       return "south";
79     default:
80       return "none";
81     }
82 }
83
84 Direction
85 string_to_direction(const std::string& directory)
86 {
87   if (directory == "west")
88     return D_WEST;
89   else if (directory == "east")
90     return D_EAST;
91   else if (directory == "north")
92     return D_NORTH;
93   else if (directory == "south")
94     return D_SOUTH;
95   else
96     return D_NONE;
97 }
98
99 TileManager::TileManager()
100 {
101   std::string stwt_filename = datadir +  "/images/worldmap/antarctica.stwt";
102   lisp_object_t* root_obj = lisp_read_from_file(stwt_filename);
103  
104   if (!root_obj)
105     Termination::abort("Couldn't load file", stwt_filename);
106
107   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap-tiles") == 0)
108     {
109       lisp_object_t* cur = lisp_cdr(root_obj);
110
111       while(!lisp_nil_p(cur))
112         {
113           lisp_object_t* element = lisp_car(cur);
114
115           if (strcmp(lisp_symbol(lisp_car(element)), "tile") == 0)
116             {
117               int id = 0;
118
119               Tile* tile = new Tile;             
120               tile->north = tile->east = tile->south = tile->west = true;
121               tile->stop  = true;
122               tile->auto_walk = false;
123
124               LispReader reader(lisp_cdr(element));
125               reader.read_int("id", id);
126
127               std::string temp;
128               reader.read_string("possible-directions", temp);
129               if(!temp.empty())
130                 {
131                 tile->north = tile->east = tile->south = tile->west = false;
132                 if(temp.find("north") != std::string::npos)
133                   tile->north = true;
134                 if(temp.find("south") != std::string::npos)
135                   tile->south = true;
136                 if(temp.find("east") != std::string::npos)
137                   tile->east = true;
138                 if(temp.find("west") != std::string::npos)
139                   tile->west = true;
140                 }
141
142               /* For backward compatibility */
143               reader.read_bool("north", tile->north);
144               reader.read_bool("south", tile->south);
145               reader.read_bool("west",  tile->west);
146               reader.read_bool("east",  tile->east);
147
148               reader.read_bool("stop",  tile->stop);
149               reader.read_bool("auto-walk",  tile->auto_walk);
150
151               reader.read_string("one-way", temp);
152               tile->one_way = BOTH_WAYS;
153               if(!temp.empty())
154                 {
155                 if(temp == "north-south")
156                   tile->one_way = NORTH_SOUTH_WAY;
157                 else if(temp == "south-north")
158                   tile->one_way = SOUTH_NORTH_WAY;
159                 else if(temp == "east-west")
160                   tile->one_way = EAST_WEST_WAY;
161                 else if(temp == "west-east")
162                   tile->one_way = WEST_EAST_WAY;
163                 }
164
165               std::vector<std::string> filenames;
166               reader.read_string_vector("image", filenames);
167
168               if(filenames.size() == 0)
169                 std::cerr << "Warning: no image specified for tile " << id
170                           << ".\nIgnoring...\n" << std::endl;
171
172               for(int i = 0; i < filenames.size(); i++)
173                 {
174                 Surface* image = new Surface(
175                          datadir +  "/images/worldmap/" + filenames[i], true);
176                 tile->images.push_back(image);
177                 }
178
179               tile->anim_speed = 25;
180               reader.read_int("anim-speed", tile->anim_speed);
181
182
183               if (id >= int(tiles.size()))
184                 tiles.resize(id+1);
185
186               tiles[id] = tile;
187             }
188           else
189             {
190               puts("Unhandled symbol");
191             }
192
193           cur = lisp_cdr(cur);
194         }
195     }
196   else
197     {
198       assert(0);
199     }
200
201   lisp_free(root_obj);
202 }
203
204 TileManager::~TileManager()
205 {
206   for(std::vector<Tile*>::iterator i = tiles.begin(); i != tiles.end(); ++i)
207     delete *i;
208 }
209
210 Tile*
211 TileManager::get(int i)
212 {
213   assert(i >=0 && i < int(tiles.size()));
214   return tiles[i];
215 }
216
217 //---------------------------------------------------------------------------
218
219 Tux::Tux(WorldMap* worldmap_)
220   : worldmap(worldmap_)
221 {
222   largetux_sprite = new Surface(datadir +  "/images/worldmap/tux.png", true);
223   firetux_sprite = new Surface(datadir +  "/images/worldmap/firetux.png", true);
224   smalltux_sprite = new Surface(datadir +  "/images/worldmap/smalltux.png", true);
225
226   offset = 0;
227   moving = false;
228   tile_pos.x = worldmap->get_start_x();
229   tile_pos.y = worldmap->get_start_y();
230   direction = D_NONE;
231   input_direction = D_NONE;
232 }
233
234 Tux::~Tux()
235 {
236   delete smalltux_sprite;
237   delete firetux_sprite;
238   delete largetux_sprite;
239 }
240
241 void
242 Tux::draw(DrawingContext& context, const Vector& offset)
243 {
244   Vector pos = get_pos();
245   switch (player_status.bonus)
246     {
247     case PlayerStatus::GROWUP_BONUS:
248       context.draw_surface(largetux_sprite,
249           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
250       break;
251     case PlayerStatus::FLOWER_BONUS:
252       context.draw_surface(firetux_sprite,
253           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
254       break;
255     case PlayerStatus::NO_BONUS:
256       context.draw_surface(smalltux_sprite,
257           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
258       break;
259     }
260 }
261
262
263 Vector
264 Tux::get_pos()
265 {
266   float x = tile_pos.x * 32;
267   float y = tile_pos.y * 32;
268
269   switch(direction)
270     {
271     case D_WEST:
272       x -= offset - 32;
273       break;
274     case D_EAST:
275       x += offset - 32;
276       break;
277     case D_NORTH:
278       y -= offset - 32;
279       break;
280     case D_SOUTH:
281       y += offset - 32;
282       break;
283     case D_NONE:
284       break;
285     }
286   
287   return Vector((int)x, (int)y); 
288 }
289
290 void
291 Tux::stop()
292 {
293   offset = 0;
294   direction = D_NONE;
295   input_direction = D_NONE;
296   moving = false;
297 }
298
299 void
300 Tux::set_direction(Direction dir)
301 {
302 input_direction = dir;
303 }
304
305 void
306 Tux::action(float delta)
307 {
308   if (!moving)
309     {
310       if (input_direction != D_NONE)
311         { 
312           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
313
314           // We got a new direction, so lets start walking when possible
315           Vector next_tile;
316           if ((!special_tile || special_tile->solved || special_tile->level_name.empty())
317               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
318             {
319               tile_pos = next_tile;
320               moving = true;
321               direction = input_direction;
322               back_direction = reverse_dir(direction);
323             }
324           else if (input_direction == back_direction)
325             {
326               moving = true;
327               direction = input_direction;
328               tile_pos = worldmap->get_next_tile(tile_pos, direction);
329               back_direction = reverse_dir(direction);
330             }
331         }
332     }
333   else
334     {
335       // Let tux walk a few pixels (20 pixel/sec)
336       offset += 20.0f * delta;
337
338       if (offset > 32)
339         { // We reached the next tile, so we check what to do now
340           offset -= 32;
341
342           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
343           if(special_tile && special_tile->passive_message)
344             {  // direction and the apply_action_ are opposites, since they "see"
345                // directions in a different way
346             if((direction == D_NORTH && special_tile->apply_action_south) ||
347                (direction == D_SOUTH && special_tile->apply_action_north) ||
348                (direction == D_WEST && special_tile->apply_action_east) ||
349                (direction == D_EAST && special_tile->apply_action_west))
350               {
351               worldmap->passive_message = special_tile->map_message;
352               worldmap->passive_message_timer.start(map_message_TIME);
353               }
354             }
355
356           if (worldmap->at(tile_pos)->stop || (special_tile && 
357               !special_tile->passive_message))
358             {
359               if(special_tile && !special_tile->map_message.empty() &&
360                 !special_tile->passive_message)
361                 worldmap->passive_message_timer.stop();
362               stop();
363             }
364           else
365             {
366               if (worldmap->at(tile_pos)->auto_walk || direction != input_direction)
367                 { // Turn to a new direction
368                   Tile* tile = worldmap->at(tile_pos);
369
370                   if(direction != input_direction && 
371                      ((tile->north && input_direction == D_NORTH) ||
372                      (tile->south && input_direction == D_SOUTH) ||
373                      (tile->east && input_direction == D_EAST) ||
374                      (tile->west && input_direction == D_WEST)))
375                     {  // player has changed direction during auto-movement
376                     direction = input_direction;
377                     back_direction = reverse_dir(direction);
378                     }
379                   else if(direction != input_direction)
380                     {  // player has changed to impossible tile
381                       back_direction = reverse_dir(direction);
382                       stop();
383                     }
384                   else
385                     {
386                     Direction dir = D_NONE;
387                   
388                     if (tile->north && back_direction != D_NORTH)
389                       dir = D_NORTH;
390                     else if (tile->south && back_direction != D_SOUTH)
391                       dir = D_SOUTH;
392                     else if (tile->east && back_direction != D_EAST)
393                       dir = D_EAST;
394                     else if (tile->west && back_direction != D_WEST)
395                       dir = D_WEST;
396
397                     if (dir != D_NONE)
398                       {
399                       direction = dir;
400                       input_direction = direction;
401                       back_direction = reverse_dir(direction);
402                       }
403                     else
404                       {
405                       // Should never be reached if tiledata is good
406                       stop();
407                       return;
408                       }
409                     }
410                   }
411
412               // Walk automatically to the next tile
413               if(direction != D_NONE)
414                 {
415                 Vector next_tile;
416                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
417                   {
418                   tile_pos = next_tile;
419                   }
420                 else
421                   {
422                   puts("Tilemap data is buggy");
423                   stop();
424                   }
425                 }
426             }
427         }
428     }
429 }
430
431 //---------------------------------------------------------------------------
432 Tile::Tile()
433 {
434 }
435
436 Tile::~Tile()
437 {
438   for(std::vector<Surface*>::iterator i = images.begin(); i != images.end(); i++)
439     delete *i;
440 }
441
442
443 void
444 Tile::draw(DrawingContext& context, Vector pos)
445 {
446   // same code as from tile_manager.cpp draw_tile()
447
448   if(!images.size())
449     return;
450
451   if(images.size() > 1)
452     {
453     size_t frame 
454       = ((global_frame_counter*25) / anim_speed) % images.size();
455
456 std::cerr << "frame: " << frame << std::endl;
457     context.draw_surface(images[frame], pos, LAYER_TILES);
458     }
459   else if (images.size() == 1)
460     {
461     context.draw_surface(images[0], pos, LAYER_TILES);
462     }
463 }
464
465 //---------------------------------------------------------------------------
466
467 WorldMap::WorldMap()
468 {
469   tile_manager = new TileManager();
470   //tux = new Tux(this);
471   
472   width  = 20;
473   height = 15;
474   
475   start_x = 4;
476   start_y = 5;
477   
478   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", true);
479   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", true);
480   messagedot   = new Surface(datadir +  "/images/worldmap/messagedot.png", true);
481   teleporterdot   = new Surface(datadir +  "/images/worldmap/teleporterdot.png", true);
482
483   enter_level = false;
484
485   name = "<no title>";
486   music = "SALCON.MOD";
487
488   global_frame_counter = 0;
489   frame_timer.init(true);
490
491   total_stats.reset();
492 }
493
494 WorldMap::~WorldMap()
495 {
496   delete tux;
497   delete tile_manager;
498
499   delete leveldot_green;
500   delete leveldot_red;
501   delete messagedot;
502   delete teleporterdot;
503 }
504
505 // Don't forget to set map_filename before calling this
506 void
507 WorldMap::load_map()
508 {
509   lisp_object_t* root_obj = lisp_read_from_file(datadir + "/levels/worldmap/" + map_filename);
510   if (!root_obj)
511     Termination::abort("Couldn't load file", datadir + "/levels/worldmap/" + map_filename);
512
513   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
514     {
515       lisp_object_t* cur = lisp_cdr(root_obj);
516
517       while(!lisp_nil_p(cur))
518         {
519           lisp_object_t* element = lisp_car(cur);
520
521           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
522             {
523               LispReader reader(lisp_cdr(element));
524               reader.read_int("width",  width);
525               reader.read_int("height", height);
526               reader.read_int_vector("data", tilemap);
527             }
528           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
529             {
530               LispReader reader(lisp_cdr(element));
531               reader.read_string("name", name, true);
532               reader.read_string("music", music);
533               reader.read_int("start_pos_x", start_x);
534               reader.read_int("start_pos_y", start_y);
535             }
536           else if (strcmp(lisp_symbol(lisp_car(element)), "special-tiles") == 0 ||
537                    strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
538             {
539               lisp_object_t* cur = lisp_cdr(element);
540               
541               while(!lisp_nil_p(cur))
542                 {
543                   lisp_object_t* element = lisp_car(cur);
544
545                   if (strcmp(lisp_symbol(lisp_car(element)), "special-tile") == 0)
546                     {
547                       SpecialTile special_tile;
548                       LispReader reader(lisp_cdr(element));
549                       special_tile.solved = false;
550                       
551                       special_tile.north = true;
552                       special_tile.east  = true;
553                       special_tile.south = true;
554                       special_tile.west  = true;
555
556                       reader.read_int("x", special_tile.x);
557                       reader.read_int("y", special_tile.y);
558                       reader.read_string("level", special_tile.level_name, false);
559
560                       special_tile.vertical_flip = false;
561                       reader.read_bool("vertical-flip", special_tile.vertical_flip);
562
563                       special_tile.map_message.erase();
564                       reader.read_string("map-message", special_tile.map_message);
565                       special_tile.passive_message = false;
566                       reader.read_bool("passive-message", special_tile.passive_message);
567
568                       special_tile.teleport_dest_x = special_tile.teleport_dest_y = -1;
569                       reader.read_int("teleport-to-x", special_tile.teleport_dest_x);
570                       reader.read_int("teleport-to-y", special_tile.teleport_dest_y);
571
572                       special_tile.invisible = false;
573                       reader.read_bool("invisible-tile", special_tile.invisible);
574
575                       special_tile.apply_action_north = special_tile.apply_action_south =
576                           special_tile.apply_action_east = special_tile.apply_action_west =
577                           true;
578                       std::string apply_direction;
579                       reader.read_string("apply-to-direction", apply_direction);
580                       if(!apply_direction.empty())
581                         {
582                         special_tile.apply_action_north = special_tile.apply_action_south =
583                             special_tile.apply_action_east = special_tile.apply_action_west =
584                             false;
585                         if(apply_direction.find("north") != std::string::npos)
586                           special_tile.apply_action_north = true;
587                         if(apply_direction.find("south") != std::string::npos)
588                           special_tile.apply_action_south = true;
589                         if(apply_direction.find("east") != std::string::npos)
590                           special_tile.apply_action_east = true;
591                         if(apply_direction.find("west") != std::string::npos)
592                           special_tile.apply_action_west = true;
593                         }
594
595                       reader.read_string("extro-filename", special_tile.extro_filename);
596                       reader.read_string("next-world", special_tile.next_worldmap);
597                       special_tile.quit_worldmap = false;
598                       reader.read_bool("exit-game", special_tile.quit_worldmap);
599
600                       special_tile.auto_path = true;
601                       reader.read_bool("auto-path", special_tile.auto_path);
602
603                       special_tiles.push_back(special_tile);
604                     }
605
606                   /* Kept for backward compability */
607                   else if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
608                     {
609                       SpecialTile special_tile;
610                       LispReader reader(lisp_cdr(element));
611                       special_tile.solved = false;
612                       
613                       special_tile.north = true;
614                       special_tile.east  = true;
615                       special_tile.south = true;
616                       special_tile.west  = true;
617
618                       special_tile.invisible = false;
619
620                       special_tile.apply_action_north = special_tile.apply_action_south =
621                           special_tile.apply_action_east = special_tile.apply_action_west =
622                           true;
623                       special_tile.vertical_flip = false;
624                       special_tile.teleport_dest_x = special_tile.teleport_dest_y = -1;
625
626                       reader.read_string("extro-filename", special_tile.extro_filename);
627                       if(!special_tile.extro_filename.empty())
628                         special_tile.quit_worldmap = true;
629                       reader.read_string("name", special_tile.level_name, true);
630                       reader.read_int("x", special_tile.x);
631                       reader.read_int("y", special_tile.y);
632
633
634                       special_tiles.push_back(special_tile);
635                     }
636                   
637                   cur = lisp_cdr(cur);      
638                 }
639             }
640           else
641             {
642               
643             }
644           
645           cur = lisp_cdr(cur);
646         }
647     }
648
649     lisp_free(root_obj);
650     tux = new Tux(this);
651 }
652
653 void WorldMap::get_level_title(SpecialTile& special_tile)
654 {
655   /** get special_tile's title */
656   special_tile.title = "<no title>";
657
658   LispReader* reader = LispReader::load(datadir + "/levels/" + special_tile.level_name, "supertux-level");
659   if(!reader)
660     {
661     std::cerr << "Error: Could not open level file. Ignoring...\n";
662     return;
663     }
664
665   reader->read_string("name", special_tile.title, true);
666   delete reader;
667 }
668
669 void WorldMap::calculate_total_stats()
670 {
671   total_stats.reset();
672   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
673     {
674     if (!i->level_name.empty() && i->solved)
675       {
676       total_stats += i->statistics;
677       }
678     }
679 }
680
681 void
682 WorldMap::on_escape_press()
683 {
684   // Show or hide the menu
685   if(!Menu::current())
686     {
687     Menu::set_current(worldmap_menu); 
688     tux->set_direction(D_NONE);  // stop tux movement when menu is called
689     }
690   else
691     Menu::set_current(0); 
692 }
693
694 void
695 WorldMap::get_input()
696 {
697   enter_level = false;
698    
699   SDL_Event event;
700   while (SDL_PollEvent(&event))
701     {
702       if (Menu::current())
703         {
704           Menu::current()->event(event);
705         }
706       else
707         {
708           switch(event.type)
709             {
710             case SDL_QUIT:
711               Termination::abort("Received window close", "");
712               break;
713           
714             case SDL_KEYDOWN:
715               switch(event.key.keysym.sym)
716                 {
717                 case SDLK_ESCAPE:
718                   on_escape_press();
719                   break;
720                 case SDLK_LCTRL:
721                 case SDLK_RETURN:
722                   enter_level = true;
723                   break;
724
725                 case SDLK_LEFT:
726                   tux->set_direction(D_WEST);
727                   break;
728                 case SDLK_RIGHT:
729                   tux->set_direction(D_EAST);
730                   break;
731                 case SDLK_UP:
732                   tux->set_direction(D_NORTH);
733                   break;
734                 case SDLK_DOWN:
735                   tux->set_direction(D_SOUTH);
736                   break;
737
738                 default:
739                   break;
740                 }
741               break;
742
743             case SDL_JOYHATMOTION:
744               if(event.jhat.value & SDL_HAT_UP) {
745                 tux->set_direction(D_NORTH);
746               } else if(event.jhat.value & SDL_HAT_DOWN) {
747                 tux->set_direction(D_SOUTH);
748               } else if(event.jhat.value & SDL_HAT_LEFT) {
749                 tux->set_direction(D_WEST);
750               } else if(event.jhat.value & SDL_HAT_RIGHT) {
751                 tux->set_direction(D_EAST);
752               }
753               break;
754           
755             case SDL_JOYAXISMOTION:
756               if (event.jaxis.axis == joystick_keymap.x_axis)
757                 {
758                   if (event.jaxis.value < -joystick_keymap.dead_zone)
759                     tux->set_direction(D_WEST);
760                   else if (event.jaxis.value > joystick_keymap.dead_zone)
761                     tux->set_direction(D_EAST);
762                 }
763               else if (event.jaxis.axis == joystick_keymap.y_axis)
764                 {
765                   if (event.jaxis.value > joystick_keymap.dead_zone)
766                     tux->set_direction(D_SOUTH);
767                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
768                     tux->set_direction(D_NORTH);
769                 }
770               break;
771
772             case SDL_JOYBUTTONDOWN:
773               if (event.jbutton.button == joystick_keymap.b_button)
774                 enter_level = true;
775               else if (event.jbutton.button == joystick_keymap.start_button)
776                 on_escape_press();
777               break;
778
779             default:
780               break;
781             }
782         }
783     }
784 }
785
786 Vector
787 WorldMap::get_next_tile(Vector pos, Direction direction)
788 {
789   switch(direction)
790     {
791     case D_WEST:
792       pos.x -= 1;
793       break;
794     case D_EAST:
795       pos.x += 1;
796       break;
797     case D_NORTH:
798       pos.y -= 1;
799       break;
800     case D_SOUTH:
801       pos.y += 1;
802       break;
803     case D_NONE:
804       break;
805     }
806   return pos;
807 }
808
809 bool
810 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
811 {
812   *new_pos = get_next_tile(old_pos, direction);
813
814   if (!(new_pos->x >= 0 && new_pos->x < width
815         && new_pos->y >= 0 && new_pos->y < height))
816     { // New position is outsite the tilemap
817       return false;
818     }
819   else if(at(*new_pos)->one_way != BOTH_WAYS)
820     {
821 std::cerr << "one way only\n";
822       if((at(*new_pos)->one_way == NORTH_SOUTH_WAY && direction != D_SOUTH) ||
823          (at(*new_pos)->one_way == SOUTH_NORTH_WAY && direction != D_NORTH) ||
824          (at(*new_pos)->one_way == EAST_WEST_WAY && direction != D_WEST) ||
825          (at(*new_pos)->one_way == WEST_EAST_WAY && direction != D_EAST))
826         return false;
827       return true;
828     }
829   else
830     { // Check if we the tile allows us to go to new_pos
831       switch(direction)
832         {
833         case D_WEST:
834           return (at(old_pos)->west && at(*new_pos)->east);
835
836         case D_EAST:
837           return (at(old_pos)->east && at(*new_pos)->west);
838
839         case D_NORTH:
840           return (at(old_pos)->north && at(*new_pos)->south);
841
842         case D_SOUTH:
843           return (at(old_pos)->south && at(*new_pos)->north);
844
845         case D_NONE:
846           assert(!"path_ok() can't work if direction is NONE");
847         }
848       return false;
849     }
850 }
851
852 void
853 WorldMap::update(float delta)
854 {
855   if(!frame_timer.check())
856     {
857     frame_timer.start(25);
858     global_frame_counter++;
859     }
860
861   if (enter_level && !tux->is_moving())
862     {
863       bool level_finished = true;
864       SpecialTile* special_tile = at_special_tile();
865       if (!special_tile)
866         {
867         std::cout << "Nothing to enter at: "
868           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
869         return;
870         }
871
872
873       if(!special_tile->level_name.empty())
874         {
875           if (special_tile->x == tux->get_tile_pos().x && 
876               special_tile->y == tux->get_tile_pos().y)
877             {
878               PlayerStatus old_player_status = player_status;
879
880               std::cout << "Enter the current level: " << special_tile->level_name << std::endl;
881               // do a shriking fade to the special_tile
882               shrink_fade(Vector((special_tile->x*32 + 16 + offset.x),(special_tile->y*32 + 16
883                       + offset.y)), 500);
884               GameSession session(datadir +  "/levels/" + special_tile->level_name,
885                                   ST_GL_LOAD_LEVEL_FILE, special_tile->vertical_flip,
886                                   &special_tile->statistics);
887
888               switch (session.run())
889                 {
890                 case GameSession::ES_LEVEL_FINISHED:
891                   {
892                     level_finished = true;
893                     bool old_level_state = special_tile->solved;
894                     special_tile->solved = true;
895
896                     // deal with statistics
897                     special_tile->statistics.merge(global_stats);
898                     calculate_total_stats();
899
900                     if (session.get_current_sector()->player->got_power !=
901                           session.get_current_sector()->player->NONE_POWER)
902                       player_status.bonus = PlayerStatus::FLOWER_BONUS;
903                     else if (session.get_current_sector()->player->size == BIG)
904                       player_status.bonus = PlayerStatus::GROWUP_BONUS;
905                     else
906                       player_status.bonus = PlayerStatus::NO_BONUS;
907
908                     if (old_level_state != special_tile->solved && special_tile->auto_path)
909                       { // Try to detect the next direction to which we should walk
910                         // FIXME: Mostly a hack
911                         Direction dir = D_NONE;
912                     
913                         Tile* tile = at(tux->get_tile_pos());
914
915                         if (tile->north && tux->back_direction != D_NORTH)
916                           dir = D_NORTH;
917                         else if (tile->south && tux->back_direction != D_SOUTH)
918                           dir = D_SOUTH;
919                         else if (tile->east && tux->back_direction != D_EAST)
920                           dir = D_EAST;
921                         else if (tile->west && tux->back_direction != D_WEST)
922                           dir = D_WEST;
923
924                         if (dir != D_NONE)
925                           {
926                             tux->set_direction(dir);
927                             //tux->update(delta);
928                           }
929
930                         std::cout << "Walk to dir: " << dir << std::endl;
931                       }
932                   }
933
934                   break;
935                 case GameSession::ES_LEVEL_ABORT:
936                   level_finished = false;
937                   /* In case the player's abort the special_tile, keep it using the old
938                       status. But the minimum lives and no bonus. */
939                   player_status.distros = old_player_status.distros;
940                   player_status.lives = std::min(old_player_status.lives, player_status.lives);
941                   player_status.bonus = player_status.NO_BONUS;
942
943                   break;
944                 case GameSession::ES_GAME_OVER:
945                   {
946                   level_finished = false;
947                   /* draw an end screen */
948                   /* TODO: in the future, this should make a dialog a la SuperMario, asking
949                   if the player wants to restart the world map with no score and from
950                   level 1 */
951                   char str[80];
952
953                   DrawingContext context;
954                   context.draw_gradient(Color (200,240,220), Color(200,200,220),
955                       LAYER_BACKGROUND0);
956
957                   context.draw_text(blue_text, _("GAMEOVER"), 
958                       Vector(screen->w/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
959
960                   sprintf(str, _("COINS: %d"), player_status.distros);
961                   context.draw_text(gold_text, str,
962                       Vector(screen->w/2, screen->w - 32), CENTER_ALLIGN, LAYER_FOREGROUND1);
963
964                   total_stats.draw_message_info(context, _("Total Statistics"));
965
966                   context.do_drawing();
967   
968                   SDL_Event event;
969                   wait_for_event(event,2000,6000,true);
970
971                   quit = true;
972                   player_status.reset();
973                   break;
974                   }
975                 case GameSession::ES_NONE:
976                   assert(false);
977                   // Should never be reached 
978                   break;
979                 }
980
981               SoundManager::get()->play_music(song);
982               Menu::set_current(0);
983               if (!savegame_file.empty())
984                 savegame(savegame_file);
985             }
986         }
987       /* The porpose of the next checking is that if the player lost
988          the special_tile (in case there is one), don't show anything */
989       if(level_finished)
990         {
991         if (!special_tile->extro_filename.empty())
992           {
993           // Display a text file
994           display_text_file(special_tile->extro_filename, SCROLL_SPEED_MESSAGE, white_big_text , white_text, white_small_text, blue_text );
995           }
996         if (special_tile->teleport_dest_x != -1 && special_tile->teleport_dest_y != -1)
997           {
998           // TODO: an animation, camera scrolling or a fading would be a nice touch
999           SoundManager::get()->play_sound(IDToSound(SND_WARP));
1000           tux->back_direction = D_NONE;
1001           tux->set_tile_pos(Vector(special_tile->teleport_dest_x, special_tile->teleport_dest_y));
1002           SDL_Delay(1000);
1003           }
1004         if (!special_tile->next_worldmap.empty())
1005           {
1006           // Load given worldmap
1007           loadmap(special_tile->next_worldmap);
1008           }
1009         if (special_tile->quit_worldmap)
1010           quit = true;
1011         }
1012     }
1013   else
1014     {
1015       tux->action(delta);
1016 //      tux->set_direction(input_direction);
1017     }
1018   
1019   Menu* menu = Menu::current();
1020   if(menu)
1021     {
1022       menu->action();
1023
1024       if(menu == worldmap_menu)
1025         {
1026           switch (worldmap_menu->check())
1027             {
1028             case MNID_RETURNWORLDMAP: // Return to game
1029               break;
1030             case MNID_QUITWORLDMAP: // Quit Worldmap
1031               quit = true;
1032               break;
1033             }
1034         }
1035       else if(menu == options_menu)
1036         {
1037           process_options_menu();
1038         }
1039     }
1040 }
1041
1042 Tile*
1043 WorldMap::at(Vector p)
1044 {
1045   assert(p.x >= 0 
1046          && p.x < width
1047          && p.y >= 0
1048          && p.y < height);
1049
1050   int x = int(p.x);
1051   int y = int(p.y);
1052   return tile_manager->get(tilemap[width * y + x]);
1053 }
1054
1055 WorldMap::SpecialTile*
1056 WorldMap::at_special_tile()
1057 {
1058   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1059     {
1060       if (i->x == tux->get_tile_pos().x && 
1061           i->y == tux->get_tile_pos().y)
1062         return &*i; 
1063     }
1064
1065   return 0;
1066 }
1067
1068
1069 void
1070 WorldMap::draw(DrawingContext& context, const Vector& offset)
1071 {
1072   for(int y = 0; y < height; ++y)
1073     for(int x = 0; x < width; ++x)
1074       {
1075         Tile* tile = at(Vector(x, y));
1076         tile->draw(context, Vector(x*32 + offset.x, y*32 + offset.y));
1077       }
1078   
1079   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1080     {
1081       if(i->invisible)
1082         continue;
1083       if(i->level_name.empty())
1084         {
1085         if (i->teleport_dest_x != -1 && i->teleport_dest_y != -1)
1086           context.draw_surface(teleporterdot,
1087               Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1088
1089         else if (!i->map_message.empty() && !i->passive_message)
1090           context.draw_surface(messagedot,
1091               Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1092
1093         continue;
1094         }
1095
1096       if (i->solved)
1097         context.draw_surface(leveldot_green,
1098             Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1099       else
1100         context.draw_surface(leveldot_red,
1101             Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1102     }
1103
1104   tux->draw(context, offset);
1105   draw_status(context);
1106 }
1107
1108 void
1109 WorldMap::draw_status(DrawingContext& context)
1110 {
1111   char str[80];
1112   sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
1113
1114   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
1115   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
1116
1117   sprintf(str, "%d", player_status.distros);
1118   context.draw_text(white_text, _("COINS"), Vector(screen->w/2 - 16*5, 0),
1119       LEFT_ALLIGN, LAYER_FOREGROUND1);
1120   context.draw_text(gold_text, str, Vector(screen->w/2 + (16*5)/2, 0),
1121         LEFT_ALLIGN, LAYER_FOREGROUND1);
1122
1123   if (player_status.lives >= 5)
1124     {
1125       sprintf(str, "%dx", player_status.lives);
1126       context.draw_text(gold_text, str, 
1127           Vector(screen->w - gold_text->get_text_width(str) - tux_life->w, 0),
1128           LEFT_ALLIGN, LAYER_FOREGROUND1);
1129       context.draw_surface(tux_life, Vector(screen->w -
1130             gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
1131     }
1132   else
1133     {
1134       for(int i= 0; i < player_status.lives; ++i)
1135         context.draw_surface(tux_life,
1136             Vector(screen->w - tux_life->w*4 + (tux_life->w*i), 0),
1137             LAYER_FOREGROUND1);
1138     }
1139   context.draw_text(white_text, _("LIVES"),
1140       Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
1141       LEFT_ALLIGN, LAYER_FOREGROUND1);
1142
1143   if (!tux->is_moving())
1144     {
1145       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1146         {
1147           if (i->x == tux->get_tile_pos().x && 
1148               i->y == tux->get_tile_pos().y)
1149             {
1150               if(!i->level_name.empty())
1151                 {
1152                 if(i->title == "")
1153                   get_level_title(*i);
1154
1155                 context.draw_text(white_text, i->title, 
1156                     Vector(screen->w/2, screen->h - white_text->get_height() - 30),
1157                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1158
1159                 i->statistics.draw_worldmap_info(context);
1160                 }
1161
1162               /* Display an in-map message in the map, if any as been selected */
1163               if(!i->map_message.empty() && !i->passive_message)
1164                 context.draw_text(gold_text, i->map_message, 
1165                     Vector(screen->w/2, screen->h - white_text->get_height() - 60),
1166                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1167               break;
1168             }
1169         }
1170     }
1171   /* Display a passive message in the map, if needed */
1172   if(passive_message_timer.check())
1173     context.draw_text(gold_text, passive_message, 
1174             Vector(screen->w/2, screen->h - white_text->get_height() - 60),
1175             CENTER_ALLIGN, LAYER_FOREGROUND1);
1176 }
1177
1178 void
1179 WorldMap::display()
1180 {
1181   Menu::set_current(0);
1182
1183   quit = false;
1184
1185   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1186   SoundManager::get()->play_music(song);
1187
1188   FrameRate frame_rate(10);
1189   frame_rate.set_frame_limit(false);
1190
1191   frame_rate.start();
1192
1193   DrawingContext context;
1194   while(!quit)
1195     {
1196       float delta = frame_rate.get();
1197
1198       delta *= 1.3f;
1199
1200       if (delta > 10.0f)
1201         delta = .3f;
1202         
1203       frame_rate.update();
1204
1205       Vector tux_pos = tux->get_pos();
1206       if (1)
1207         {
1208           offset.x = -tux_pos.x + screen->w/2;
1209           offset.y = -tux_pos.y + screen->h/2;
1210
1211           if (offset.x > 0) offset.x = 0;
1212           if (offset.y > 0) offset.y = 0;
1213
1214           if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
1215           if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
1216         } 
1217
1218       draw(context, offset);
1219       get_input();
1220       update(delta);
1221       
1222       if(Menu::current())
1223         {
1224           Menu::current()->draw(context);
1225           mouse_cursor->draw(context);
1226         }
1227
1228       context.do_drawing();
1229
1230       SDL_Delay(20);
1231     }
1232 }
1233
1234 void
1235 WorldMap::savegame(const std::string& filename)
1236 {
1237   if(filename == "")
1238     return;
1239
1240   std::cout << "savegame: " << filename << std::endl;
1241
1242    std::ofstream file(filename.c_str(), std::ios::out);
1243    LispWriter* writer = new LispWriter(file);
1244
1245   int nb_solved_levels = 0, total_levels = 0;
1246   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1247     {
1248       if(!i->level_name.empty())
1249         ++total_levels;
1250       if (i->solved)
1251         ++nb_solved_levels;
1252     }
1253   char nb_solved_levels_str[80], total_levels_str[80];
1254   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1255   sprintf(total_levels_str, "%d", total_levels);
1256
1257   writer->write_comment("Worldmap save file");
1258
1259   writer->start_list("supertux-savegame");
1260
1261   writer->write_int("version", 1);
1262   writer->write_string("title", std::string(name + " - " + nb_solved_levels_str + "/" + total_levels_str));
1263   writer->write_string("map", map_filename);
1264   writer->write_int("lives", player_status.lives);
1265   writer->write_int("distros", player_status.lives);
1266
1267   writer->start_list("tux");
1268
1269   writer->write_float("x", tux->get_tile_pos().x);
1270   writer->write_float("y", tux->get_tile_pos().y);
1271   writer->write_string("back", direction_to_string(tux->back_direction));
1272   writer->write_string("bonus", bonus_to_string(player_status.bonus));
1273
1274   writer->end_list("tux");
1275
1276   writer->start_list("levels");
1277
1278   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1279     {
1280       if (i->solved && !i->level_name.empty())
1281         {
1282         writer->start_list("level");
1283
1284         writer->write_string("name", i->level_name);
1285         writer->write_bool("solved", true);
1286         i->statistics.write(*writer);
1287
1288         writer->end_list("level");
1289         }
1290     }  
1291
1292   writer->end_list("levels");
1293
1294   writer->end_list("supertux-savegame");
1295 }
1296
1297 void
1298 WorldMap::loadgame(const std::string& filename)
1299 {
1300   std::cout << "loadgame: " << filename << std::endl;
1301   savegame_file = filename;
1302
1303   if (access(filename.c_str(), F_OK) != 0)
1304     {
1305     load_map();
1306
1307     player_status.reset();
1308
1309     return;
1310     }
1311   
1312   lisp_object_t* savegame = lisp_read_from_file(filename);
1313   if (!savegame)
1314     {
1315       std::cout << "WorldMap:loadgame: File not found: " << filename << std::endl;
1316       load_map();
1317       return;
1318     }
1319
1320   lisp_object_t* cur = savegame;
1321
1322   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
1323     {
1324     load_map();
1325     return;
1326     }
1327
1328   cur = lisp_cdr(cur);
1329   LispReader reader(cur);
1330
1331   /* Get the Map filename and then load it before setting special_tile settings */
1332   std::string cur_map_filename = map_filename;
1333   reader.read_string("map", map_filename);
1334   if(cur_map_filename != map_filename)
1335     load_map(); 
1336
1337   reader.read_int("lives", player_status.lives);
1338   reader.read_int("distros", player_status.distros);
1339
1340   if (player_status.lives < 0)
1341     player_status.lives = START_LIVES;
1342
1343   lisp_object_t* tux_cur = 0;
1344   if (reader.read_lisp("tux", tux_cur))
1345     {
1346       Vector p;
1347       std::string back_str = "none";
1348       std::string bonus_str = "none";
1349
1350       LispReader tux_reader(tux_cur);
1351       tux_reader.read_float("x", p.x);
1352       tux_reader.read_float("y", p.y);
1353       tux_reader.read_string("back", back_str);
1354       tux_reader.read_string("bonus", bonus_str);
1355       
1356       player_status.bonus = string_to_bonus(bonus_str);
1357       tux->back_direction = string_to_direction(back_str);      
1358       tux->set_tile_pos(p);
1359     }
1360
1361   lisp_object_t* level_cur = 0;
1362   if (reader.read_lisp("levels", level_cur))
1363     {
1364       while(level_cur)
1365         {
1366           lisp_object_t* sym  = lisp_car(lisp_car(level_cur));
1367           lisp_object_t* data = lisp_cdr(lisp_car(level_cur));
1368
1369           if (strcmp(lisp_symbol(sym), "level") == 0)
1370             {
1371               std::string name;
1372               bool solved = false;
1373
1374               LispReader level_reader(data);
1375               level_reader.read_string("name", name);
1376               level_reader.read_bool("solved", solved);
1377
1378               for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1379                 {
1380                   if (name == i->level_name)
1381                     {
1382                     i->solved = solved;
1383                     i->statistics.parse(level_reader);
1384                     break;
1385                     }
1386                 }
1387             }
1388
1389           level_cur = lisp_cdr(level_cur);
1390         }
1391     }
1392  
1393   lisp_free(savegame);
1394
1395   calculate_total_stats();
1396 }
1397
1398 void
1399 WorldMap::loadmap(const std::string& filename)
1400 {
1401   savegame_file = "";
1402   map_filename = filename;
1403   load_map();
1404 }
1405
1406 } // namespace WorldMapNS
1407
1408 /* Local Variables: */
1409 /* mode:c++ */
1410 /* End: */
1411