- committed patch from Richard Smith
[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; static_cast<unsigned int>(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::Level* level = worldmap->at_level();
313
314           // We got a new direction, so lets start walking when possible
315           Vector next_tile;
316           if ((!level || level->solved)
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 ||
357              (special_tile && !special_tile->passive_message) ||
358               worldmap->at_level())
359             {
360               if(special_tile && !special_tile->map_message.empty() &&
361                 !special_tile->passive_message)
362                 worldmap->passive_message_timer.stop();
363               stop();
364             }
365           else
366             {
367               if (worldmap->at(tile_pos)->auto_walk || direction != input_direction)
368                 { // Turn to a new direction
369                   Tile* tile = worldmap->at(tile_pos);
370
371                   if(direction != input_direction && 
372                      ((tile->north && input_direction == D_NORTH) ||
373                      (tile->south && input_direction == D_SOUTH) ||
374                      (tile->east && input_direction == D_EAST) ||
375                      (tile->west && input_direction == D_WEST)))
376                     {  // player has changed direction during auto-movement
377                     direction = input_direction;
378                     back_direction = reverse_dir(direction);
379                     }
380                   else if(direction != input_direction)
381                     {  // player has changed to impossible tile
382                       back_direction = reverse_dir(direction);
383                       stop();
384                     }
385                   else
386                     {
387                     Direction dir = D_NONE;
388                   
389                     if (tile->north && back_direction != D_NORTH)
390                       dir = D_NORTH;
391                     else if (tile->south && back_direction != D_SOUTH)
392                       dir = D_SOUTH;
393                     else if (tile->east && back_direction != D_EAST)
394                       dir = D_EAST;
395                     else if (tile->west && back_direction != D_WEST)
396                       dir = D_WEST;
397
398                     if (dir != D_NONE)
399                       {
400                       direction = dir;
401                       input_direction = direction;
402                       back_direction = reverse_dir(direction);
403                       }
404                     else
405                       {
406                       // Should never be reached if tiledata is good
407                       stop();
408                       return;
409                       }
410                     }
411                   }
412
413               // Walk automatically to the next tile
414               if(direction != D_NONE)
415                 {
416                 Vector next_tile;
417                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
418                   {
419                   tile_pos = next_tile;
420                   }
421                 else
422                   {
423                   puts("Tilemap data is buggy");
424                   stop();
425                   }
426                 }
427             }
428         }
429     }
430 }
431
432 //---------------------------------------------------------------------------
433 Tile::Tile()
434 {
435 }
436
437 Tile::~Tile()
438 {
439   for(std::vector<Surface*>::iterator i = images.begin(); i != images.end(); i++)
440     delete *i;
441 }
442
443
444 void
445 Tile::draw(DrawingContext& context, Vector pos)
446 {
447   // same code as from tile_manager.cpp draw_tile()
448
449   if(!images.size())
450     return;
451
452   if(images.size() > 1)
453     {
454     size_t frame 
455       = ((global_frame_counter*25) / anim_speed) % images.size();
456
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   tux = new Tux(this);
479   
480   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", true);
481   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", true);
482   messagedot   = new Surface(datadir +  "/images/worldmap/messagedot.png", true);
483   teleporterdot   = new Surface(datadir +  "/images/worldmap/teleporterdot.png", true);
484
485   enter_level = false;
486
487   name = "<no title>";
488   music = "SALCON.MOD";
489
490   global_frame_counter = 0;
491   frame_timer.init(true);
492
493   total_stats.reset();
494 }
495
496 WorldMap::~WorldMap()
497 {
498   delete tux;
499   delete tile_manager;
500
501   delete leveldot_green;
502   delete leveldot_red;
503   delete messagedot;
504   delete teleporterdot;
505 }
506
507 // Don't forget to set map_filename before calling this
508 void
509 WorldMap::load_map()
510 {
511   lisp_object_t* root_obj = lisp_read_from_file(datadir + "/levels/worldmap/" + map_filename);
512   if (!root_obj)
513     Termination::abort("Couldn't load file", datadir + "/levels/worldmap/" + map_filename);
514
515   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
516     {
517       lisp_object_t* cur = lisp_cdr(root_obj);
518
519       while(!lisp_nil_p(cur))
520         {
521           lisp_object_t* element = lisp_car(cur);
522
523           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
524             {
525               LispReader reader(lisp_cdr(element));
526               reader.read_int("width",  width);
527               reader.read_int("height", height);
528               reader.read_int_vector("data", tilemap);
529             }
530           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
531             {
532               LispReader reader(lisp_cdr(element));
533               reader.read_string("name", name, true);
534               reader.read_string("music", music);
535               reader.read_int("start_pos_x", start_x);
536               reader.read_int("start_pos_y", start_y);
537             }
538           else if (strcmp(lisp_symbol(lisp_car(element)), "special-tiles") == 0 ||
539                    strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
540             {
541               lisp_object_t* cur = lisp_cdr(element);
542               
543               while(!lisp_nil_p(cur))
544                 {
545                   lisp_object_t* element = lisp_car(cur);
546
547                   if (strcmp(lisp_symbol(lisp_car(element)), "special-tile") == 0)
548                     {
549                       SpecialTile special_tile;
550                       LispReader reader(lisp_cdr(element));
551                       
552                       reader.read_float("x", special_tile.pos.x);
553                       reader.read_float("y", special_tile.pos.y);
554
555                       special_tile.map_message.erase();
556                       reader.read_string("map-message", special_tile.map_message);
557                       special_tile.passive_message = false;
558                       reader.read_bool("passive-message", special_tile.passive_message);
559
560                       special_tile.teleport_dest = Vector(-1,-1);
561                       reader.read_float("teleport-to-x", special_tile.teleport_dest.x);
562                       reader.read_float("teleport-to-y", special_tile.teleport_dest.y);
563
564                       special_tile.invisible = false;
565                       reader.read_bool("invisible-tile", special_tile.invisible);
566
567                       special_tile.apply_action_north = special_tile.apply_action_south =
568                           special_tile.apply_action_east = special_tile.apply_action_west =
569                           true;
570
571                       std::string apply_direction;
572                       reader.read_string("apply-to-direction", apply_direction);
573                       if(!apply_direction.empty())
574                         {
575                         special_tile.apply_action_north = special_tile.apply_action_south =
576                             special_tile.apply_action_east = special_tile.apply_action_west =
577                             false;
578                         if(apply_direction.find("north") != std::string::npos)
579                           special_tile.apply_action_north = true;
580                         if(apply_direction.find("south") != std::string::npos)
581                           special_tile.apply_action_south = true;
582                         if(apply_direction.find("east") != std::string::npos)
583                           special_tile.apply_action_east = true;
584                         if(apply_direction.find("west") != std::string::npos)
585                           special_tile.apply_action_west = true;
586                         }
587
588                       special_tiles.push_back(special_tile);
589                     }
590
591                   else if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
592                     {
593                       Level level;
594                       LispReader reader(lisp_cdr(element));
595                       level.solved = false;
596                       
597                       level.north = true;
598                       level.east  = true;
599                       level.south = true;
600                       level.west  = true;
601
602                       reader.read_string("extro-filename", level.extro_filename);
603                       reader.read_string("next-worldmap", level.next_worldmap);
604
605                       level.quit_worldmap = false;
606                       reader.read_bool("quit-worldmap", level.quit_worldmap);
607
608                       reader.read_string("name", level.name, true);
609                       reader.read_float("x", level.pos.x);
610                       reader.read_float("y", level.pos.y);
611
612                       level.auto_path = true;
613                       reader.read_bool("auto-path", level.auto_path);
614
615                       level.vertical_flip = false;
616                       reader.read_bool("vertical-flip", level.vertical_flip);
617
618                       levels.push_back(level);
619                     }
620                   
621                   cur = lisp_cdr(cur);      
622                 }
623             }
624           else
625             {
626               
627             }
628           
629           cur = lisp_cdr(cur);
630         }
631     }
632
633     lisp_free(root_obj);
634
635     delete tux;
636     tux = new Tux(this);
637 }
638
639 void WorldMap::get_level_title(Level& level)
640 {
641   /** get special_tile's title */
642   level.title = "<no title>";
643
644   LispReader* reader = LispReader::load(datadir + "/levels/" + level.name, "supertux-level");
645   if(!reader)
646     {
647     std::cerr << "Error: Could not open level file. Ignoring...\n";
648     return;
649     }
650
651   reader->read_string("name", level.title, true);
652   delete reader;
653 }
654
655 void WorldMap::calculate_total_stats()
656 {
657   total_stats.reset();
658   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
659     {
660     if (i->solved)
661       {
662       total_stats += i->statistics;
663       }
664     }
665 }
666
667 void
668 WorldMap::on_escape_press()
669 {
670   // Show or hide the menu
671   if(!Menu::current())
672     {
673     Menu::set_current(worldmap_menu); 
674     tux->set_direction(D_NONE);  // stop tux movement when menu is called
675     }
676   else
677     Menu::set_current(0); 
678 }
679
680 void
681 WorldMap::get_input()
682 {
683   enter_level = false;
684    
685   SDL_Event event;
686   while (SDL_PollEvent(&event))
687     {
688       if (Menu::current())
689         {
690           Menu::current()->event(event);
691         }
692       else
693         {
694           switch(event.type)
695             {
696             case SDL_QUIT:
697               Termination::abort("Received window close", "");
698               break;
699           
700             case SDL_KEYDOWN:
701               switch(event.key.keysym.sym)
702                 {
703                 case SDLK_ESCAPE:
704                   on_escape_press();
705                   break;
706                 case SDLK_LCTRL:
707                 case SDLK_RETURN:
708                   enter_level = true;
709                   break;
710
711                 case SDLK_LEFT:
712                   tux->set_direction(D_WEST);
713                   break;
714                 case SDLK_RIGHT:
715                   tux->set_direction(D_EAST);
716                   break;
717                 case SDLK_UP:
718                   tux->set_direction(D_NORTH);
719                   break;
720                 case SDLK_DOWN:
721                   tux->set_direction(D_SOUTH);
722                   break;
723
724                 default:
725                   break;
726                 }
727               break;
728
729             case SDL_JOYHATMOTION:
730               if(event.jhat.value & SDL_HAT_UP) {
731                 tux->set_direction(D_NORTH);
732               } else if(event.jhat.value & SDL_HAT_DOWN) {
733                 tux->set_direction(D_SOUTH);
734               } else if(event.jhat.value & SDL_HAT_LEFT) {
735                 tux->set_direction(D_WEST);
736               } else if(event.jhat.value & SDL_HAT_RIGHT) {
737                 tux->set_direction(D_EAST);
738               }
739               break;
740           
741             case SDL_JOYAXISMOTION:
742               if (event.jaxis.axis == joystick_keymap.x_axis)
743                 {
744                   if (event.jaxis.value < -joystick_keymap.dead_zone)
745                     tux->set_direction(D_WEST);
746                   else if (event.jaxis.value > joystick_keymap.dead_zone)
747                     tux->set_direction(D_EAST);
748                 }
749               else if (event.jaxis.axis == joystick_keymap.y_axis)
750                 {
751                   if (event.jaxis.value > joystick_keymap.dead_zone)
752                     tux->set_direction(D_SOUTH);
753                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
754                     tux->set_direction(D_NORTH);
755                 }
756               break;
757
758             case SDL_JOYBUTTONDOWN:
759               if (event.jbutton.button == joystick_keymap.b_button)
760                 enter_level = true;
761               else if (event.jbutton.button == joystick_keymap.start_button)
762                 on_escape_press();
763               break;
764
765             default:
766               break;
767             }
768         }
769     }
770 }
771
772 Vector
773 WorldMap::get_next_tile(Vector pos, Direction direction)
774 {
775   switch(direction)
776     {
777     case D_WEST:
778       pos.x -= 1;
779       break;
780     case D_EAST:
781       pos.x += 1;
782       break;
783     case D_NORTH:
784       pos.y -= 1;
785       break;
786     case D_SOUTH:
787       pos.y += 1;
788       break;
789     case D_NONE:
790       break;
791     }
792   return pos;
793 }
794
795 bool
796 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
797 {
798   *new_pos = get_next_tile(old_pos, direction);
799
800   if (!(new_pos->x >= 0 && new_pos->x < width
801         && new_pos->y >= 0 && new_pos->y < height))
802     { // New position is outsite the tilemap
803       return false;
804     }
805   else if(at(*new_pos)->one_way != BOTH_WAYS)
806     {
807 std::cerr << "one way only\n";
808       if((at(*new_pos)->one_way == NORTH_SOUTH_WAY && direction != D_SOUTH) ||
809          (at(*new_pos)->one_way == SOUTH_NORTH_WAY && direction != D_NORTH) ||
810          (at(*new_pos)->one_way == EAST_WEST_WAY && direction != D_WEST) ||
811          (at(*new_pos)->one_way == WEST_EAST_WAY && direction != D_EAST))
812         return false;
813       return true;
814     }
815   else
816     { // Check if we the tile allows us to go to new_pos
817       switch(direction)
818         {
819         case D_WEST:
820           return (at(old_pos)->west && at(*new_pos)->east);
821
822         case D_EAST:
823           return (at(old_pos)->east && at(*new_pos)->west);
824
825         case D_NORTH:
826           return (at(old_pos)->north && at(*new_pos)->south);
827
828         case D_SOUTH:
829           return (at(old_pos)->south && at(*new_pos)->north);
830
831         case D_NONE:
832           assert(!"path_ok() can't work if direction is NONE");
833         }
834       return false;
835     }
836 }
837
838 void
839 WorldMap::update(float delta)
840 {
841   if(!frame_timer.check())
842     {
843     frame_timer.start(25);
844     global_frame_counter++;
845     }
846
847   if (enter_level && !tux->is_moving())
848     {
849       /* Check special tile action */
850       SpecialTile* special_tile = at_special_tile();
851       if(special_tile)
852         {
853         if (special_tile->teleport_dest != Vector(-1,-1))
854           {
855           // TODO: an animation, camera scrolling or a fading would be a nice touch
856           SoundManager::get()->play_sound(IDToSound(SND_WARP));
857           tux->back_direction = D_NONE;
858           tux->set_tile_pos(special_tile->teleport_dest);
859           SDL_Delay(1000);
860           }
861         }
862
863       /* Check level action */
864       bool level_finished = true;
865       Level* level = at_level();
866       if (!level)
867         {
868         std::cout << "No level to enter at: "
869           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
870         return;
871         }
872
873
874           if (level->pos == tux->get_tile_pos())
875             {
876               PlayerStatus old_player_status = player_status;
877
878               std::cout << "Enter the current level: " << level->name << std::endl;
879               // do a shriking fade to the level
880               shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),(level->pos.y*32 + 16
881                       + offset.y)), 500);
882               GameSession session(level->name,
883                                   ST_GL_LOAD_LEVEL_FILE, level->vertical_flip,
884                                   &level->statistics);
885
886               switch (session.run())
887                 {
888                 case GameSession::ES_LEVEL_FINISHED:
889                   {
890                     level_finished = true;
891                     bool old_level_state = level->solved;
892                     level->solved = true;
893
894                     // deal with statistics
895                     level->statistics.merge(global_stats);
896                     calculate_total_stats();
897
898                     if (session.get_current_sector()->player->got_power !=
899                           session.get_current_sector()->player->NONE_POWER)
900                       player_status.bonus = PlayerStatus::FLOWER_BONUS;
901                     else if (session.get_current_sector()->player->size == BIG)
902                       player_status.bonus = PlayerStatus::GROWUP_BONUS;
903                     else
904                       player_status.bonus = PlayerStatus::NO_BONUS;
905
906                     if (old_level_state != level->solved && level->auto_path)
907                       { // Try to detect the next direction to which we should walk
908                         // FIXME: Mostly a hack
909                         Direction dir = D_NONE;
910                     
911                         Tile* tile = at(tux->get_tile_pos());
912
913                         if (tile->north && tux->back_direction != D_NORTH)
914                           dir = D_NORTH;
915                         else if (tile->south && tux->back_direction != D_SOUTH)
916                           dir = D_SOUTH;
917                         else if (tile->east && tux->back_direction != D_EAST)
918                           dir = D_EAST;
919                         else if (tile->west && tux->back_direction != D_WEST)
920                           dir = D_WEST;
921
922                         if (dir != D_NONE)
923                           {
924                             tux->set_direction(dir);
925                             //tux->update(delta);
926                           }
927
928                         std::cout << "Walk to dir: " << dir << std::endl;
929                       }
930                   }
931
932                   break;
933                 case GameSession::ES_LEVEL_ABORT:
934                   level_finished = false;
935                   /* In case the player's abort the level, keep it using the old
936                       status. But the minimum lives and no bonus. */
937                   player_status.distros = old_player_status.distros;
938                   player_status.lives = std::min(old_player_status.lives, player_status.lives);
939                   player_status.bonus = player_status.NO_BONUS;
940
941                   break;
942                 case GameSession::ES_GAME_OVER:
943                   {
944                   level_finished = false;
945                   /* draw an end screen */
946                   /* TODO: in the future, this should make a dialog a la SuperMario, asking
947                   if the player wants to restart the world map with no score and from
948                   level 1 */
949                   char str[80];
950
951                   DrawingContext context;
952                   context.draw_gradient(Color (200,240,220), Color(200,200,220),
953                       LAYER_BACKGROUND0);
954
955                   context.draw_text(blue_text, _("GAMEOVER"), 
956                       Vector(screen->w/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
957
958                   sprintf(str, _("COINS: %d"), player_status.distros);
959                   context.draw_text(gold_text, str,
960                       Vector(screen->w/2, screen->w - 32), CENTER_ALLIGN, LAYER_FOREGROUND1);
961
962                   total_stats.draw_message_info(context, _("Total Statistics"));
963
964                   context.do_drawing();
965   
966                   SDL_Event event;
967                   wait_for_event(event,2000,6000,true);
968
969                   quit = true;
970                   player_status.reset();
971                   break;
972                   }
973                 case GameSession::ES_NONE:
974                   assert(false);
975                   // Should never be reached 
976                   break;
977                 }
978
979               SoundManager::get()->play_music(song);
980               Menu::set_current(0);
981               if (!savegame_file.empty())
982                 savegame(savegame_file);
983             }
984       /* The porpose of the next checking is that if the player lost
985          the level (in case there is one), don't show anything */
986       if(level_finished)
987         {
988         if (!level->extro_filename.empty())
989           {
990           // Display a text file
991           display_text_file(level->extro_filename, SCROLL_SPEED_MESSAGE, white_big_text , white_text, white_small_text, blue_text );
992           }
993
994         if (!level->next_worldmap.empty())
995           {
996           // Load given worldmap
997           loadmap(level->next_worldmap);
998           }
999         if (level->quit_worldmap)
1000           quit = true;
1001         }
1002     }
1003   else
1004     {
1005       tux->action(delta);
1006 //      tux->set_direction(input_direction);
1007     }
1008   
1009   Menu* menu = Menu::current();
1010   if(menu)
1011     {
1012       menu->action();
1013
1014       if(menu == worldmap_menu)
1015         {
1016           switch (worldmap_menu->check())
1017             {
1018             case MNID_RETURNWORLDMAP: // Return to game
1019               break;
1020             case MNID_QUITWORLDMAP: // Quit Worldmap
1021               quit = true;
1022               break;
1023             }
1024         }
1025       else if(menu == options_menu)
1026         {
1027           process_options_menu();
1028         }
1029     }
1030 }
1031
1032 Tile*
1033 WorldMap::at(Vector p)
1034 {
1035   assert(p.x >= 0 
1036          && p.x < width
1037          && p.y >= 0
1038          && p.y < height);
1039
1040   int x = int(p.x);
1041   int y = int(p.y);
1042   return tile_manager->get(tilemap[width * y + x]);
1043 }
1044
1045 WorldMap::Level*
1046 WorldMap::at_level()
1047 {
1048   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1049     {
1050       if (i->pos == tux->get_tile_pos())
1051         return &*i; 
1052     }
1053
1054   return 0;
1055 }
1056
1057 WorldMap::SpecialTile*
1058 WorldMap::at_special_tile()
1059 {
1060   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1061     {
1062       if (i->pos == tux->get_tile_pos())
1063         return &*i; 
1064     }
1065
1066   return 0;
1067 }
1068
1069
1070 void
1071 WorldMap::draw(DrawingContext& context, const Vector& offset)
1072 {
1073   for(int y = 0; y < height; ++y)
1074     for(int x = 0; x < width; ++x)
1075       {
1076         Tile* tile = at(Vector(x, y));
1077         tile->draw(context, Vector(x*32 + offset.x, y*32 + offset.y));
1078       }
1079
1080   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1081     {
1082       if (i->solved)
1083         context.draw_surface(leveldot_green,
1084             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1085       else
1086         context.draw_surface(leveldot_red,
1087             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1088     }
1089
1090   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1091     {
1092       if(i->invisible)
1093         continue;
1094
1095       if (i->teleport_dest != Vector(-1, -1))
1096         context.draw_surface(teleporterdot,
1097                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1098
1099       else if (!i->map_message.empty() && !i->passive_message)
1100         context.draw_surface(messagedot,
1101                 Vector(i->pos.x*32 + offset.x, i->pos.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(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1146         {
1147           if (i->pos == tux->get_tile_pos())
1148             {
1149               if(i->title == "")
1150                 get_level_title(*i);
1151
1152               context.draw_text(white_text, i->title, 
1153                   Vector(screen->w/2,
1154                          screen->h - white_text->get_height() - 30),
1155                   CENTER_ALLIGN, LAYER_FOREGROUND1);
1156
1157               i->statistics.draw_worldmap_info(context);
1158               break;
1159             }
1160         }
1161       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1162         {
1163           if (i->pos == tux->get_tile_pos())
1164             {
1165                /* Display an in-map message in the map, if any as been selected */
1166               if(!i->map_message.empty() && !i->passive_message)
1167                 context.draw_text(gold_text, i->map_message, 
1168                     Vector(screen->w/2,
1169                            screen->h - white_text->get_height() - 60),
1170                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1171               break;
1172             }
1173         }
1174     }
1175   /* Display a passive message in the map, if needed */
1176   if(passive_message_timer.check())
1177     context.draw_text(gold_text, passive_message, 
1178             Vector(screen->w/2, screen->h - white_text->get_height() - 60),
1179             CENTER_ALLIGN, LAYER_FOREGROUND1);
1180 }
1181
1182 void
1183 WorldMap::display()
1184 {
1185   Menu::set_current(0);
1186
1187   quit = false;
1188
1189   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1190   SoundManager::get()->play_music(song);
1191
1192   FrameRate frame_rate(10);
1193   frame_rate.set_frame_limit(false);
1194
1195   frame_rate.start();
1196
1197   DrawingContext context;
1198   while(!quit)
1199     {
1200       float delta = frame_rate.get();
1201
1202       delta *= 1.3f;
1203
1204       if (delta > 10.0f)
1205         delta = .3f;
1206         
1207       frame_rate.update();
1208
1209       Vector tux_pos = tux->get_pos();
1210       if (1)
1211         {
1212           offset.x = -tux_pos.x + screen->w/2;
1213           offset.y = -tux_pos.y + screen->h/2;
1214
1215           if (offset.x > 0) offset.x = 0;
1216           if (offset.y > 0) offset.y = 0;
1217
1218           if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
1219           if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
1220         } 
1221
1222       draw(context, offset);
1223       get_input();
1224       update(delta);
1225       
1226       if(Menu::current())
1227         {
1228           Menu::current()->draw(context);
1229           mouse_cursor->draw(context);
1230         }
1231
1232       context.do_drawing();
1233
1234       SDL_Delay(20);
1235     }
1236 }
1237
1238 void
1239 WorldMap::savegame(const std::string& filename)
1240 {
1241   if(filename == "")
1242     return;
1243
1244   std::cout << "savegame: " << filename << std::endl;
1245
1246    std::ofstream file(filename.c_str(), std::ios::out);
1247    LispWriter* writer = new LispWriter(file);
1248
1249   int nb_solved_levels = 0, total_levels = 0;
1250   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1251     {
1252       ++total_levels;
1253       if (i->solved)
1254         ++nb_solved_levels;
1255     }
1256   char nb_solved_levels_str[80], total_levels_str[80];
1257   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1258   sprintf(total_levels_str, "%d", total_levels);
1259
1260   writer->write_comment("Worldmap save file");
1261
1262   writer->start_list("supertux-savegame");
1263
1264   writer->write_int("version", 1);
1265   writer->write_string("title", std::string(name + " - " + nb_solved_levels_str + "/" + total_levels_str));
1266   writer->write_string("map", map_filename);
1267   writer->write_int("lives", player_status.lives);
1268   writer->write_int("distros", player_status.lives);
1269
1270   writer->start_list("tux");
1271
1272   writer->write_float("x", tux->get_tile_pos().x);
1273   writer->write_float("y", tux->get_tile_pos().y);
1274   writer->write_string("back", direction_to_string(tux->back_direction));
1275   writer->write_string("bonus", bonus_to_string(player_status.bonus));
1276
1277   writer->end_list("tux");
1278
1279   writer->start_list("levels");
1280
1281   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1282     {
1283       if (i->solved)
1284         {
1285         writer->start_list("level");
1286
1287         writer->write_string("name", i->name);
1288         writer->write_bool("solved", true);
1289         i->statistics.write(*writer);
1290
1291         writer->end_list("level");
1292         }
1293     }  
1294
1295   writer->end_list("levels");
1296
1297   writer->end_list("supertux-savegame");
1298 }
1299
1300 void
1301 WorldMap::loadgame(const std::string& filename)
1302 {
1303   std::cout << "loadgame: " << filename << std::endl;
1304   savegame_file = filename;
1305
1306   if (access(filename.c_str(), F_OK) != 0)
1307     {
1308     load_map();
1309
1310     player_status.reset();
1311
1312     return;
1313     }
1314   
1315   lisp_object_t* savegame = lisp_read_from_file(filename);
1316   if (!savegame)
1317     {
1318       std::cout << "WorldMap:loadgame: File not found: " << filename << std::endl;
1319       load_map();
1320       return;
1321     }
1322
1323   lisp_object_t* cur = savegame;
1324
1325   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
1326     {
1327     load_map();
1328     return;
1329     }
1330
1331   cur = lisp_cdr(cur);
1332   LispReader reader(cur);
1333
1334   /* Get the Map filename and then load it before setting level settings */
1335   std::string cur_map_filename = map_filename;
1336   reader.read_string("map", map_filename);
1337 //  if(cur_map_filename != map_filename)
1338     load_map(); 
1339
1340   reader.read_int("lives", player_status.lives);
1341   reader.read_int("distros", player_status.distros);
1342
1343   if (player_status.lives < 0)
1344     player_status.lives = START_LIVES;
1345
1346   lisp_object_t* tux_cur = 0;
1347   if (reader.read_lisp("tux", tux_cur))
1348     {
1349       Vector p;
1350       std::string back_str = "none";
1351       std::string bonus_str = "none";
1352
1353       LispReader tux_reader(tux_cur);
1354       tux_reader.read_float("x", p.x);
1355       tux_reader.read_float("y", p.y);
1356       tux_reader.read_string("back", back_str);
1357       tux_reader.read_string("bonus", bonus_str);
1358       
1359       player_status.bonus = string_to_bonus(bonus_str);
1360       tux->back_direction = string_to_direction(back_str);      
1361       tux->set_tile_pos(p);
1362     }
1363
1364   lisp_object_t* level_cur = 0;
1365   if (reader.read_lisp("levels", level_cur))
1366     {
1367       while(level_cur)
1368         {
1369           lisp_object_t* sym  = lisp_car(lisp_car(level_cur));
1370           lisp_object_t* data = lisp_cdr(lisp_car(level_cur));
1371
1372           if (strcmp(lisp_symbol(sym), "level") == 0)
1373             {
1374               std::string name;
1375               bool solved = false;
1376
1377               LispReader level_reader(data);
1378               level_reader.read_string("name", name);
1379               level_reader.read_bool("solved", solved);
1380
1381               for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1382                 {
1383                   if (name == i->name)
1384                     {
1385                     i->solved = solved;
1386                     i->statistics.parse(level_reader);
1387                     break;
1388                     }
1389                 }
1390             }
1391
1392           level_cur = lisp_cdr(level_cur);
1393         }
1394     }
1395  
1396   lisp_free(savegame);
1397
1398   calculate_total_stats();
1399 }
1400
1401 void
1402 WorldMap::loadmap(const std::string& filename)
1403 {
1404   savegame_file = "";
1405   map_filename = filename;
1406   load_map();
1407 }
1408
1409 } // namespace WorldMapNS
1410
1411 /* Local Variables: */
1412 /* mode:c++ */
1413 /* End: */
1414