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