d5e3e722f56c93bdb0f1aef945f3f292a78da58d
[supertux.git] / src / level.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2004 SuperTux Development Team, see AUTHORS for details
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
19 //  02111-1307, USA.
20
21 #include <map>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <iostream>
26 #include "globals.h"
27 #include "setup.h"
28 #include "screen.h"
29 #include "level.h"
30 #include "physic.h"
31 #include "scene.h"
32 #include "tile.h"
33 #include "lispreader.h"
34 #include "resources.h"
35 #include "music_manager.h"
36
37 using namespace std;
38
39 LevelSubset::LevelSubset()
40     : image(0), levels(0)
41 {
42 }
43
44 LevelSubset::~LevelSubset()
45 {
46     delete image;
47 }
48
49 void LevelSubset::create(const std::string& subset_name)
50 {
51   Level new_lev;
52   LevelSubset new_subset;
53   new_subset.name = subset_name;
54   new_subset.title = "Unknown Title";
55   new_subset.description = "No description so far.";
56   new_subset.save();
57   new_lev.init_defaults();
58   new_lev.save(subset_name, 1);
59 }
60
61 void LevelSubset::parse (lisp_object_t* cursor)
62 {
63   while(!lisp_nil_p(cursor))
64     {
65       lisp_object_t* cur = lisp_car(cursor);
66       char *s;
67
68       if (!lisp_cons_p(cur) || !lisp_symbol_p (lisp_car(cur)))
69         {
70           printf("Not good");
71         }
72       else
73         {
74           if (strcmp(lisp_symbol(lisp_car(cur)), "title") == 0)
75             {
76               if(( s = lisp_string(lisp_car(lisp_cdr(cur)))) != NULL)
77                 {
78                   title = s;
79                 }
80             }
81           else if (strcmp(lisp_symbol(lisp_car(cur)), "description") == 0)
82             {
83               if(( s = lisp_string(lisp_car(lisp_cdr(cur)))) != NULL)
84                 {
85                   description = s;
86                 }
87             }
88         }
89       cursor = lisp_cdr (cursor);
90     }
91 }
92
93 void LevelSubset::load(char *subset)
94 {
95   FILE* fi;
96   char filename[1024];
97   char str[1024];
98   int i;
99   lisp_object_t* root_obj = 0;
100
101   name = subset;
102
103   snprintf(filename, 1024, "%s/levels/%s/info", st_dir, subset);
104   if(!faccessible(filename))
105     snprintf(filename, 1024, "%s/levels/%s/info", datadir.c_str(), subset);
106   if(faccessible(filename))
107     {
108       fi = fopen(filename, "r");
109       if (fi == NULL)
110         {
111           perror(filename);
112         }
113       lisp_stream_t stream;
114       lisp_stream_init_file (&stream, fi);
115       root_obj = lisp_read (&stream);
116
117       if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
118         {
119           printf("World: Parse Error in file %s", filename);
120         }
121
122       lisp_object_t* cur = lisp_car(root_obj);
123
124       if (!lisp_symbol_p (cur))
125         {
126           printf("World: Read error in %s",filename);
127         }
128
129       if (strcmp(lisp_symbol(cur), "supertux-level-subset") == 0)
130         {
131           parse(lisp_cdr(root_obj));
132
133         }
134
135       lisp_free(root_obj);
136       fclose(fi);
137
138       snprintf(str, 1024, "%s.png", filename);
139       if(faccessible(str))
140         {
141           delete image;
142           image = new Surface(str,IGNORE_ALPHA);
143         }
144       else
145         {
146           snprintf(filename, 1024, "%s/images/status/level-subset-info.png", datadir.c_str());
147           delete image;
148           image = new Surface(filename,IGNORE_ALPHA);
149         }
150     }
151
152   for(i=1; i != -1; ++i)
153     {
154       /* Get the number of levels in this subset */
155       snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset,i);
156       if(!faccessible(filename))
157         {
158           snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset,i);
159           if(!faccessible(filename))
160             break;
161         }
162     }
163   levels = --i;
164 }
165
166 void LevelSubset::save()
167 {
168   FILE* fi;
169   string filename;
170
171   /* Save data file: */
172   filename = "/levels/" + name + "/";
173
174   fcreatedir(filename.c_str());
175   filename = string(st_dir) + "/levels/" + name + "/info";
176   if(!fwriteable(filename.c_str()))
177     filename = datadir + "/levels/" + name + "/info";
178   if(fwriteable(filename.c_str()))
179     {
180       fi = fopen(filename.c_str(), "w");
181       if (fi == NULL)
182         {
183           perror(filename.c_str());
184         }
185
186       /* Write header: */
187       fprintf(fi,";SuperTux-Level-Subset\n");
188       fprintf(fi,"(supertux-level-subset\n");
189
190       /* Save title info: */
191       fprintf(fi,"  (title \"%s\")\n", title.c_str());
192
193       /* Save the description: */
194       fprintf(fi,"  (description \"%s\")\n", description.c_str());
195
196       fprintf( fi,")");
197       fclose(fi);
198
199     }
200 }
201
202 Level::Level()
203   : img_bkgd(0)
204 {
205   init_defaults();
206 }
207
208 Level::Level(const std::string& subset, int level)
209   : img_bkgd(0)
210 {
211   if(load(subset, level) < 0)
212     st_abort("Couldn't load level from subset", subset.c_str());
213 }
214
215 Level::Level(const std::string& filename)
216   : img_bkgd(0)
217 {
218   if(load(filename) < 0)
219     st_abort("Couldn't load level " , filename.c_str());
220 }
221
222 Level::~Level()
223 {
224   free_gfx();
225 }
226
227 void
228 Level::init_defaults()
229 {
230   name       = "UnNamed";
231   author     = "UnNamed";
232   theme      = "antarctica";
233   song_title = "Mortimers_chipdisko.mod";
234   bkgd_image = "arctis.png";
235   width      = 21;
236   start_pos_x = 100;
237   start_pos_y = 170;
238   time_left  = 100;
239   gravity    = 10.;
240   bkgd_top.red   = 0;
241   bkgd_top.green = 0;
242   bkgd_top.blue  = 0;
243   bkgd_bottom.red   = 255;
244   bkgd_bottom.green = 255;
245   bkgd_bottom.blue  = 255;
246
247   for(int i = 0; i < 15; ++i)
248     {
249       ia_tiles[i].resize(width+1, 0);
250       ia_tiles[i][width] = (unsigned int) '\0';
251
252       for(int y = 0; y < width; ++y)
253         ia_tiles[i][y] = 0;
254
255       bg_tiles[i].resize(width+1, 0);
256       bg_tiles[i][width] = (unsigned int) '\0';
257       for(int y = 0; y < width; ++y)
258         bg_tiles[i][y] = 0;
259
260       fg_tiles[i].resize(width+1, 0);
261       fg_tiles[i][width] = (unsigned int) '\0';
262       for(int y = 0; y < width; ++y)
263         fg_tiles[i][y] = 0;
264     }
265 }
266
267 int
268 Level::load(const std::string& subset, int level)
269 {
270   char filename[1024];
271
272   // Load data file:
273   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset.c_str(), level);
274   if(!faccessible(filename))
275     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset.c_str(), level);
276
277   return load(filename);
278 }
279
280 int 
281 Level::load(const std::string& filename)
282 {
283   lisp_object_t* root_obj = lisp_read_from_file(filename);
284   if (!root_obj)
285     {
286       std::cout << "Level: Couldn't load file: " << filename << std::endl;
287       return -1;
288     }
289
290   if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
291     {
292       printf("World: Parse Error in file %s", filename.c_str());
293       return -1;
294     }
295
296   vector<int> ia_tm;
297   vector<int> bg_tm;
298   vector<int> fg_tm;
299
300   int version = 0;
301   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-level") == 0)
302     {
303       LispReader reader(lisp_cdr(root_obj));
304       version = 0;
305       reader.read_int("version",  &version);
306       if(!reader.read_int("width",  &width))
307         st_abort("No width specified for level.", "");
308       if (!reader.read_int("start_pos_x", &start_pos_x)) start_pos_x = 100;
309       if (!reader.read_int("start_pos_y", &start_pos_y)) start_pos_y = 170;
310       time_left = 500;
311       if(!reader.read_int("time",  &time_left)) {
312         printf("Warning no time specified for level.\n");
313       }
314
315       bkgd_top.red = bkgd_top.green = bkgd_top.blue = 0;
316       reader.read_int("bkgd_red_top",  &bkgd_top.red);
317       reader.read_int("bkgd_green_top",  &bkgd_top.green);
318       reader.read_int("bkgd_blue_top",  &bkgd_top.blue);
319
320       bkgd_bottom.red = bkgd_bottom.green = bkgd_bottom.blue = 0;
321       reader.read_int("bkgd_red_bottom",  &bkgd_bottom.red);
322       reader.read_int("bkgd_green_bottom",  &bkgd_bottom.green);
323       reader.read_int("bkgd_blue_bottom",  &bkgd_bottom.blue);
324
325       gravity = 10;
326       reader.read_float("gravity",  &gravity);
327       name = "Noname";
328       reader.read_string("name",  &name);
329       author = "unknown author";
330       reader.read_string("author", &author);
331       if(!reader.read_string("theme",  &theme))
332         st_abort("No theme specified in level file", "");
333       song_title = "";
334       reader.read_string("music",  &song_title);
335       bkgd_image = "";
336       reader.read_string("background",  &bkgd_image);
337       particle_system = "";
338       reader.read_string("particle_system", &particle_system);
339
340       reader.read_int_vector("background-tm",  &bg_tm);
341
342       if (!reader.read_int_vector("interactive-tm", &ia_tm))
343         reader.read_int_vector("tilemap", &ia_tm);
344
345       reader.read_int_vector("foreground-tm",  &fg_tm);
346
347       { // Read ResetPoints
348         lisp_object_t* cur = 0;
349         if (reader.read_lisp("reset-points",  &cur))
350           {
351             while (!lisp_nil_p(cur))
352               {
353                 lisp_object_t* data = lisp_car(cur);
354
355                 ResetPoint pos;
356
357                 LispReader reader(lisp_cdr(data));
358                 if (reader.read_int("x", &pos.x)
359                     && reader.read_int("y", &pos.y))
360                   {
361                     reset_points.push_back(pos);
362                   }
363
364                 cur = lisp_cdr(cur);
365               }
366           }
367       }
368
369       { // Read BadGuys
370         lisp_object_t* cur = 0;
371         if (reader.read_lisp("objects",  &cur))
372           {
373             while (!lisp_nil_p(cur))
374               {
375                 lisp_object_t* data = lisp_car(cur);
376
377                 BadGuyData bg_data;
378                 bg_data.kind = badguykind_from_string(lisp_symbol(lisp_car(data)));
379                 LispReader reader(lisp_cdr(data));
380                 reader.read_int("x", &bg_data.x);
381                 reader.read_int("y", &bg_data.y);
382                 reader.read_bool("stay-on-platform", &bg_data.stay_on_platform);
383
384                 badguy_data.push_back(bg_data);
385
386                 cur = lisp_cdr(cur);
387               }
388           }
389       }
390
391       // Convert old levels to the new tile numbers
392       if (version == 0)
393         {
394           std::map<char, int> transtable;
395           transtable['.'] = 0;
396           transtable['x'] = 104;
397           transtable['X'] = 77;
398           transtable['y'] = 78;
399           transtable['Y'] = 105;
400           transtable['A'] = 83;
401           transtable['B'] = 102;
402           transtable['!'] = 103;
403           transtable['a'] = 84;
404           transtable['C'] = 85;
405           transtable['D'] = 86;
406           transtable['E'] = 87;
407           transtable['F'] = 88;
408           transtable['c'] = 89;
409           transtable['d'] = 90;
410           transtable['e'] = 91;
411           transtable['f'] = 92;
412
413           transtable['G'] = 93;
414           transtable['H'] = 94;
415           transtable['I'] = 95;
416           transtable['J'] = 96;
417
418           transtable['g'] = 97;
419           transtable['h'] = 98;
420           transtable['i'] = 99;
421           transtable['j'] = 100
422                             ;
423           transtable['#'] = 11;
424           transtable['['] = 13;
425           transtable['='] = 14;
426           transtable[']'] = 15;
427           transtable['$'] = 82;
428           transtable['^'] = 76;
429           transtable['*'] = 80;
430           transtable['|'] = 79;
431           transtable['\\'] = 81;
432           transtable['&'] = 75;
433
434           int x = 0;
435           int y = 0;
436           for(std::vector<int>::iterator i = ia_tm.begin(); i != ia_tm.end(); ++i)
437             {
438               if (*i == '0' || *i == '1' || *i == '2')
439                 {
440                   badguy_data.push_back(BadGuyData(static_cast<BadGuyKind>(*i-'0'),
441                                                    x*32, y*32, false));
442                   *i = 0;
443                 }
444               else
445                 {
446                   std::map<char, int>::iterator j = transtable.find(*i);
447                   if (j != transtable.end())
448                     *i = j->second;
449                   else
450                     printf("Error: conversion will fail, unsupported char: '%c' (%d)\n", *i, *i);
451                 }
452               ++x;
453               if (x >= width)
454                 {
455                   x = 0;
456                   ++y;
457                 }
458             }
459         }
460     }
461
462   for(int i = 0; i < 15; ++i)
463     {
464       ia_tiles[i].resize(width + 1, 0);
465       bg_tiles[i].resize(width + 1, 0);
466       fg_tiles[i].resize(width + 1, 0);
467     }
468
469   int i = 0;
470   int j = 0;
471   for(vector<int>::iterator it = ia_tm.begin(); it != ia_tm.end(); ++it, ++i)
472     {
473       ia_tiles[j][i] = (*it);
474       if(i == width - 1)
475         {
476           i = -1;
477           ++j;
478         }
479     }
480
481   i = j = 0;
482   for(vector<int>::iterator it = bg_tm.begin(); it != bg_tm.end(); ++it, ++i)
483     {
484
485       bg_tiles[j][i] = (*it);
486       if(i == width - 1)
487         {
488           i = -1;
489           ++j;
490         }
491     }
492
493   i = j = 0;
494   for(vector<int>::iterator it = fg_tm.begin(); it != fg_tm.end(); ++it, ++i)
495     {
496
497       fg_tiles[j][i] = (*it);
498       if(i == width - 1)
499         {
500           i = -1;
501           ++j;
502         }
503     }
504
505   lisp_free(root_obj);
506   return 0;
507 }
508
509 /* Save data for level: */
510
511 void 
512 Level::save(const std::string& subset, int level)
513 {
514   char filename[1024];
515   char str[80];
516
517   /* Save data file: */
518   sprintf(str, "/levels/%s/", subset.c_str());
519   fcreatedir(str);
520   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset.c_str(),
521       level);
522   if(!fwriteable(filename))
523     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(),
524         subset.c_str(), level);
525
526   FILE * fi = fopen(filename, "w");
527   if (fi == NULL)
528     {
529       perror(filename);
530       st_shutdown();
531       exit(-1);
532     }
533
534
535   /* Write header: */
536   fprintf(fi,";SuperTux-Level\n");
537   fprintf(fi,"(supertux-level\n");
538
539   fprintf(fi,"  (version %d)\n", 1);
540   fprintf(fi,"  (name \"%s\")\n", name.c_str());
541   fprintf(fi,"  (author \"%s\")\n", author.c_str());
542   fprintf(fi,"  (theme \"%s\")\n", theme.c_str());
543   fprintf(fi,"  (music \"%s\")\n", song_title.c_str());
544   fprintf(fi,"  (background \"%s\")\n", bkgd_image.c_str());
545   fprintf(fi,"  (particle_system \"%s\")\n", particle_system.c_str());
546   fprintf(fi,"  (bkgd_red_top %d)\n", bkgd_top.red);
547   fprintf(fi,"  (bkgd_green_top %d)\n", bkgd_top.green);
548   fprintf(fi,"  (bkgd_blue_top %d)\n", bkgd_top.blue);
549   fprintf(fi,"  (bkgd_red_bottom %d)\n", bkgd_bottom.red);
550   fprintf(fi,"  (bkgd_green_bottom %d)\n", bkgd_bottom.green);
551   fprintf(fi,"  (bkgd_blue_bottom %d)\n", bkgd_bottom.blue);
552   fprintf(fi,"  (time %d)\n", time_left);
553   fprintf(fi,"  (width %d)\n", width);
554   fprintf(fi,"  (gravity %2.1f)\n", gravity);
555   fprintf(fi,"  (background-tm ");
556
557   for(int y = 0; y < 15; ++y)
558     {
559       for(int i = 0; i < width; ++i)
560         fprintf(fi," %d ", bg_tiles[y][i]);
561     }
562
563   fprintf( fi,")\n");
564   fprintf(fi,"  (interactive-tm ");
565
566   for(int y = 0; y < 15; ++y)
567     {
568       for(int i = 0; i < width; ++i)
569         fprintf(fi," %d ", ia_tiles[y][i]);
570     }
571
572   fprintf( fi,")\n");
573   fprintf(fi,"  (foreground-tm ");
574
575   for(int y = 0; y < 15; ++y)
576     {
577       for(int i = 0; i < width; ++i)
578         fprintf(fi," %d ", fg_tiles[y][i]);
579     }
580
581   fprintf( fi,")\n");
582
583   fprintf( fi,"(reset-points\n");
584   for(std::vector<ResetPoint>::iterator i = reset_points.begin();
585       i != reset_points.end(); ++i)
586     fprintf( fi,"(point (x %d) (y %d))\n",i->x, i->y);
587   fprintf( fi,")\n");
588
589   fprintf( fi,"(objects\n");
590
591   for(std::vector<BadGuyData>::iterator it = badguy_data.begin();
592       it != badguy_data.end();
593       ++it)
594     fprintf( fi,"(%s (x %d) (y %d) (stay-on-platform %s))\n",
595              badguykind_to_string((*it).kind).c_str(),(*it).x,(*it).y,
596              it->stay_on_platform ? "#t" : "#f");
597
598   fprintf( fi,")\n");
599
600   fprintf( fi,")\n");
601
602   fclose(fi);
603 }
604
605
606 /* Unload data for this level: */
607
608 void
609 Level::cleanup()
610 {
611   for(int i=0; i < 15; ++i)
612     {
613       bg_tiles[i].clear();
614       ia_tiles[i].clear();
615       fg_tiles[i].clear();
616     }
617
618   reset_points.clear();
619   name.clear();
620   author.clear();
621   theme.clear();
622   song_title.clear();
623   bkgd_image.clear();
624
625   badguy_data.clear();
626 }
627
628 void 
629 Level::load_gfx()
630 {
631   if(!bkgd_image.empty())
632     {
633       char fname[1024];
634       snprintf(fname, 1024, "%s/background/%s", st_dir, bkgd_image.c_str());
635       if(!faccessible(fname))
636         snprintf(fname, 1024, "%s/images/background/%s", datadir.c_str(), bkgd_image.c_str());
637       img_bkgd = new Surface(fname, IGNORE_ALPHA);
638     }
639   else
640     {
641       img_bkgd = 0;
642     }
643 }
644
645 void
646 Level::free_gfx()
647 {
648   delete img_bkgd;
649 }
650
651 /* Load a level-specific graphic... */
652 void
653 Level::load_image(Surface** ptexture, string theme,const  char * file, int use_alpha)
654 {
655   char fname[1024];
656
657   snprintf(fname, 1024, "%s/themes/%s/%s", st_dir, theme.c_str(), file);
658   if(!faccessible(fname))
659     snprintf(fname, 1024, "%s/images/themes/%s/%s", datadir.c_str(), theme.c_str(), file);
660
661   *ptexture = new Surface(fname, use_alpha);
662 }
663
664 /* Change the size of a level (width) */
665 void 
666 Level::change_size (int new_width)
667 {
668   if(new_width < 21)
669     new_width = 21;
670
671   for(int y = 0; y < 15; ++y)
672     {
673       ia_tiles[y].resize(new_width, 0);
674       bg_tiles[y].resize(new_width, 0);
675       fg_tiles[y].resize(new_width, 0);
676     }
677
678   width = new_width;
679 }
680
681 void
682 Level::change(float x, float y, int tm, unsigned int c)
683 {
684   int yy = ((int)y / 32);
685   int xx = ((int)x / 32);
686
687   if (yy >= 0 && yy < 15 && xx >= 0 && xx <= width)
688     {
689       switch(tm)
690         {
691         case TM_BG:
692           bg_tiles[yy][xx] = c;
693           break;
694         case TM_IA:
695           ia_tiles[yy][xx] = c;
696           break;
697         case TM_FG:
698           fg_tiles[yy][xx] = c;
699           break;
700         }
701     }
702 }
703
704 void
705 Level::load_song()
706 {
707   char* song_path;
708   char* song_subtitle;
709
710   level_song = music_manager->load_music(datadir + "/music/" + song_title);
711
712   song_path = (char *) malloc(sizeof(char) * datadir.length() +
713                               strlen(song_title.c_str()) + 8 + 5);
714   song_subtitle = strdup(song_title.c_str());
715   strcpy(strstr(song_subtitle, "."), "\0");
716   sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(), 
717           song_subtitle, strstr(song_title.c_str(), "."));
718   if(!music_manager->exists_music(song_path)) {
719     level_song_fast = level_song;
720   } else {
721     level_song_fast = music_manager->load_music(song_path);
722   }
723   free(song_subtitle);
724   free(song_path);
725 }
726
727 MusicRef
728 Level::get_level_music()
729 {
730   return level_song;
731 }
732
733 MusicRef
734 Level::get_level_music_fast()
735 {
736   return level_song_fast;
737 }
738
739 unsigned int 
740 Level::gettileid(float x, float y) const
741 {
742   int xx, yy;
743   unsigned int c;
744
745   yy = ((int)y / 32);
746   xx = ((int)x / 32);
747
748   if (yy >= 0 && yy < 15 && xx >= 0 && xx <= width)
749     c = ia_tiles[yy][xx];
750   else
751     c = 0;
752
753   return c;
754 }
755
756 unsigned int
757 Level::get_tile_at(int x, int y) const
758 {
759   if(x < 0 || x > width || y < 0 || y > 14)
760     return 0;
761   
762   return ia_tiles[y][x];
763 }
764
765 /* EOF */