82c1d6216c14e56c03462ef6ca977caede32929e
[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 <fstream>
27 #include "globals.h"
28 #include "setup.h"
29 #include "screen.h"
30 #include "level.h"
31 #include "physic.h"
32 #include "scene.h"
33 #include "tile.h"
34 #include "lispreader.h"
35 #include "resources.h"
36 #include "music_manager.h"
37 #include "gameobjs.h"
38 #include "world.h"
39 #include "lispwriter.h"
40
41 using namespace std;
42
43 LevelSubset::LevelSubset()
44     : image(0), levels(0)
45 {
46 }
47
48 LevelSubset::~LevelSubset()
49 {
50   delete image;
51 }
52
53 void LevelSubset::create(const std::string& subset_name)
54 {
55   Level new_lev;
56   LevelSubset new_subset;
57   new_subset.name = subset_name;
58   new_subset.title = "Unknown Title";
59   new_subset.description = "No description so far.";
60   new_subset.save();
61   new_lev.init_defaults();
62   new_lev.save(subset_name, 1, 0);
63 }
64
65 void LevelSubset::parse (lisp_object_t* cursor)
66 {
67   while(!lisp_nil_p(cursor))
68     {
69       lisp_object_t* cur = lisp_car(cursor);
70       char *s;
71
72       if (!lisp_cons_p(cur) || !lisp_symbol_p (lisp_car(cur)))
73         {
74           printf("Not good");
75         }
76       else
77         {
78           if (strcmp(lisp_symbol(lisp_car(cur)), "title") == 0)
79             {
80               if(( s = lisp_string(lisp_car(lisp_cdr(cur)))) != NULL)
81                 {
82                   title = s;
83                 }
84             }
85           else if (strcmp(lisp_symbol(lisp_car(cur)), "description") == 0)
86             {
87               if(( s = lisp_string(lisp_car(lisp_cdr(cur)))) != NULL)
88                 {
89                   description = s;
90                 }
91             }
92         }
93       cursor = lisp_cdr (cursor);
94     }
95 }
96
97 void LevelSubset::load(char *subset)
98 {
99   FILE* fi;
100   char filename[1024];
101   char str[1024];
102   int i;
103   lisp_object_t* root_obj = 0;
104
105   name = subset;
106
107   snprintf(filename, 1024, "%s/levels/%s/info", st_dir, subset);
108   if(!faccessible(filename))
109     snprintf(filename, 1024, "%s/levels/%s/info", datadir.c_str(), subset);
110   if(faccessible(filename))
111     {
112       fi = fopen(filename, "r");
113       if (fi == NULL)
114         {
115           perror(filename);
116         }
117       lisp_stream_t stream;
118       lisp_stream_init_file (&stream, fi);
119       root_obj = lisp_read (&stream);
120
121       if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
122         {
123           printf("World: Parse Error in file %s", filename);
124         }
125
126       lisp_object_t* cur = lisp_car(root_obj);
127
128       if (!lisp_symbol_p (cur))
129         {
130           printf("World: Read error in %s",filename);
131         }
132
133       if (strcmp(lisp_symbol(cur), "supertux-level-subset") == 0)
134         {
135           parse(lisp_cdr(root_obj));
136
137         }
138
139       lisp_free(root_obj);
140       fclose(fi);
141
142       snprintf(str, 1024, "%s.png", filename);
143       if(faccessible(str))
144         {
145           delete image;
146           image = new Surface(str,IGNORE_ALPHA);
147         }
148       else
149         {
150           snprintf(filename, 1024, "%s/images/status/level-subset-info.png", datadir.c_str());
151           delete image;
152           image = new Surface(filename,IGNORE_ALPHA);
153         }
154     }
155
156   for(i=1; i != -1; ++i)
157     {
158       /* Get the number of levels in this subset */
159       snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset,i);
160       if(!faccessible(filename))
161         {
162           snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset,i);
163           if(!faccessible(filename))
164             break;
165         }
166     }
167   levels = --i;
168 }
169
170 void LevelSubset::save()
171 {
172   FILE* fi;
173   string filename;
174
175   /* Save data file: */
176   filename = "/levels/" + name + "/";
177
178   fcreatedir(filename.c_str());
179   filename = string(st_dir) + "/levels/" + name + "/info";
180   if(!fwriteable(filename.c_str()))
181     filename = datadir + "/levels/" + name + "/info";
182   if(fwriteable(filename.c_str()))
183     {
184       fi = fopen(filename.c_str(), "w");
185       if (fi == NULL)
186         {
187           perror(filename.c_str());
188         }
189
190       /* Write header: */
191       fprintf(fi,";SuperTux-Level-Subset\n");
192       fprintf(fi,"(supertux-level-subset\n");
193
194       /* Save title info: */
195       fprintf(fi,"  (title \"%s\")\n", title.c_str());
196
197       /* Save the description: */
198       fprintf(fi,"  (description \"%s\")\n", description.c_str());
199
200       fprintf( fi,")");
201       fclose(fi);
202
203     }
204 }
205
206 Level::Level()
207   : img_bkgd(0)
208 {
209   init_defaults();
210 }
211
212 Level::~Level()
213 {
214   delete img_bkgd;
215 }
216
217 void
218 Level::init_defaults()
219 {
220   name       = "UnNamed";
221   author     = "UnNamed";
222   song_title = "Mortimers_chipdisko.mod";
223   bkgd_image = "arctis.jpg";
224   width      = 0;
225   height     = 0;
226   start_pos.x = 100;
227   start_pos.y = 170;
228   time_left  = 100;
229   gravity    = 10.;
230   back_scrolling = false;
231   hor_autoscroll_speed = 0;
232   bkgd_speed = 50;
233   bkgd_top.red   = 0;
234   bkgd_top.green = 0;
235   bkgd_top.blue  = 0;
236   bkgd_bottom.red   = 255;
237   bkgd_bottom.green = 255;
238   bkgd_bottom.blue  = 255;
239
240   resize(21, 19);
241 }
242
243 int
244 Level::load(const std::string& subset, int level, World* world)
245 {
246   char filename[1024];
247
248   // Load data file:
249   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset.c_str(), level);
250   if(!faccessible(filename))
251     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset.c_str(), level);
252
253   return load(filename, world);
254 }
255
256 int 
257 Level::load(const std::string& filename, World* world)
258 {
259   lisp_object_t* root_obj = lisp_read_from_file(filename);
260   if (!root_obj)
261     {
262       std::cout << "Level: Couldn't load file: " << filename << std::endl;
263       return -1;
264     }
265
266   if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
267     {
268       printf("World: Parse Error in file %s", filename.c_str());
269       return -1;
270     }
271
272   int version = 0;
273   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-level") == 0)
274     {
275       LispReader reader(lisp_cdr(root_obj));
276       version = 0;
277       reader.read_int("version",  &version);
278       if(!reader.read_int("width",  &width))
279         st_abort("No width specified for level.", "");
280       if (!reader.read_float("start_pos_x", &start_pos.x)) start_pos.x = 100;
281       if (!reader.read_float("start_pos_y", &start_pos.y)) start_pos.y = 170;
282       time_left = 500;
283       if(!reader.read_int("time",  &time_left)) {
284         printf("Warning no time specified for level.\n");
285       }
286       
287       height = 15;
288       reader.read_int("height",  &height);
289       
290       back_scrolling = false;
291       reader.read_bool("back_scrolling",  &back_scrolling);
292
293       hor_autoscroll_speed = 0;
294       reader.read_float("hor_autoscroll_speed",  &hor_autoscroll_speed);
295       
296       bkgd_speed = 50;
297       reader.read_int("bkgd_speed",  &bkgd_speed);
298
299       
300       bkgd_top.red = bkgd_top.green = bkgd_top.blue = 0;
301       reader.read_int("bkgd_red_top",  &bkgd_top.red);
302       reader.read_int("bkgd_green_top",  &bkgd_top.green);
303       reader.read_int("bkgd_blue_top",  &bkgd_top.blue);
304
305       bkgd_bottom.red = bkgd_bottom.green = bkgd_bottom.blue = 0;
306       reader.read_int("bkgd_red_bottom",  &bkgd_bottom.red);
307       reader.read_int("bkgd_green_bottom",  &bkgd_bottom.green);
308       reader.read_int("bkgd_blue_bottom",  &bkgd_bottom.blue);
309
310       gravity = 10;
311       reader.read_float("gravity",  &gravity);
312       name = "Noname";
313       reader.read_string("name",  &name);
314       author = "unknown author";
315       reader.read_string("author", &author);
316       song_title = "";
317       reader.read_string("music",  &song_title);
318       bkgd_image = "";
319       reader.read_string("background",  &bkgd_image);
320       particle_system = "";
321       reader.read_string("particle_system", &particle_system);
322
323       reader.read_int_vector("background-tm",  &bg_tiles);
324       if(int(bg_tiles.size()) != width * height)
325         st_abort("Wrong size of backgroundtilemap", "");
326
327       if (!reader.read_int_vector("interactive-tm", &ia_tiles))
328         reader.read_int_vector("tilemap", &ia_tiles);
329       if(int(ia_tiles.size()) != width * height)
330         st_abort("Wrong size of interactivetilemap", "");      
331
332       reader.read_int_vector("foreground-tm",  &fg_tiles);
333       if(int(fg_tiles.size()) != width * height)
334         st_abort("Wrong size of foregroundtilemap", "");      
335
336       { // Read ResetPoints
337         lisp_object_t* cur = 0;
338         if (reader.read_lisp("reset-points",  &cur))
339           {
340             while (!lisp_nil_p(cur))
341               {
342                 lisp_object_t* data = lisp_car(cur);
343
344                 ResetPoint pos;
345
346                 LispReader reader(lisp_cdr(data));
347                 if (reader.read_int("x", &pos.x)
348                     && reader.read_int("y", &pos.y))
349                   {
350                     reset_points.push_back(pos);
351                   }
352
353                 cur = lisp_cdr(cur);
354               }
355           }
356       }
357
358       { // Read Objects
359         lisp_object_t* cur = 0;
360         if (reader.read_lisp("objects",  &cur))
361           {
362             if(world)
363               world->parse_objects(cur);
364           }
365       }
366
367       { // Read Camera
368         lisp_object_t* cur = 0;
369         if (reader.read_lisp("camera", &cur))
370           {
371             LispReader reader(cur);
372             if(world)
373               world->camera->read(reader);
374           }
375       }
376     }
377
378   lisp_free(root_obj);
379   return 0;
380 }
381
382 /* Save data for level: */
383
384 void 
385 Level::save(const std::string& subset, int level, World* world)
386 {
387   char filename[1024];
388   char str[80];
389
390   /* Save data file: */
391   sprintf(str, "/levels/%s/", subset.c_str());
392   fcreatedir(str);
393   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset.c_str(),
394       level);
395   if(!fwriteable(filename))
396     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(),
397         subset.c_str(), level);
398
399   std::ofstream out(filename);
400   if(!out.good()) {
401     st_abort("Couldn't write file.", filename);
402   }
403   LispWriter writer(out);
404
405   /* Write header: */
406   writer.write_comment("SuperTux level made using the built-in leveleditor");
407   writer.start_list("supertux-level");
408
409   writer.write_int("version", 1);
410   writer.write_string("name", name);
411   writer.write_string("author", author);
412   writer.write_string("music", song_title);
413   writer.write_string("background", bkgd_image);
414   writer.write_string("particle_system", particle_system);
415   writer.write_int("bkgd_speed", bkgd_speed);
416   writer.write_int("bkgd_red_top", bkgd_top.red);
417   writer.write_int("bkgd_green_top", bkgd_top.green);
418   writer.write_int("bkgd_blue_top", bkgd_top.blue);
419   writer.write_int("bkgd_red_bottom", bkgd_bottom.red);
420   writer.write_int("bkgd_green_bottom", bkgd_bottom.green);
421   writer.write_int("bkgd_blue_bottom", bkgd_bottom.blue);
422   writer.write_int("time", time_left);
423   writer.write_int("width", width);
424   writer.write_int("height", height);
425   writer.write_bool("back_scrolling", back_scrolling);
426   writer.write_float("hor_autoscroll_speed", hor_autoscroll_speed);
427   writer.write_float("gravity", gravity);
428
429   writer.write_int_vector("background-tm", bg_tiles);
430   writer.write_int_vector("interactive-tm", ia_tiles);
431   writer.write_int_vector("foreground-tm", fg_tiles);
432
433   writer.start_list("reset-points");
434   for(std::vector<ResetPoint>::iterator i = reset_points.begin();
435       i != reset_points.end(); ++i) {
436     writer.start_list("point");
437     writer.write_int("x", i->x);
438     writer.write_int("y", i->y);
439     writer.end_list("point");
440   }
441   writer.end_list("reset-points");
442
443   // write objects
444   writer.start_list("objects");
445   // pick all objects that can be written into a levelfile
446   for(std::vector<GameObject*>::iterator it = world->gameobjects.begin();
447       it != world->gameobjects.end(); ++it) {
448     Serializable* serializable = dynamic_cast<Serializable*> (*it);
449     if(serializable)
450       serializable->write(writer);
451   }
452   writer.end_list("objects");
453
454   writer.end_list("supertux-level");
455   out.close();
456 }
457
458 /* Unload data for this level: */
459 void
460 Level::cleanup()
461 {
462   bg_tiles.clear();
463   ia_tiles.clear();
464   fg_tiles.clear();
465
466   reset_points.clear();
467   name = "";
468   author = "";
469   song_title = "";
470   bkgd_image = "";
471 }
472
473 void 
474 Level::load_gfx()
475 {
476   if(!bkgd_image.empty())
477     {
478       char fname[1024];
479       snprintf(fname, 1024, "%s/background/%s", st_dir, bkgd_image.c_str());
480       if(!faccessible(fname))
481         snprintf(fname, 1024, "%s/images/background/%s", datadir.c_str(), bkgd_image.c_str());
482       delete img_bkgd;
483       img_bkgd = new Surface(fname, IGNORE_ALPHA);
484     }
485   else
486     {
487       delete img_bkgd;
488       img_bkgd = 0;
489     }
490 }
491
492 /* Load a level-specific graphic... */
493 void Level::load_image(Surface** ptexture, string theme,const  char * file, int use_alpha)
494 {
495   char fname[1024];
496
497   snprintf(fname, 1024, "%s/themes/%s/%s", st_dir, theme.c_str(), file);
498   if(!faccessible(fname))
499     snprintf(fname, 1024, "%s/images/themes/%s/%s", datadir.c_str(), theme.c_str(), file);
500
501   *ptexture = new Surface(fname, use_alpha);
502 }
503
504 /* Change the size of a level */
505 void 
506 Level::resize(int new_width, int new_height)
507 {
508   if(new_width < width) {
509     // remap tiles for new width
510     for(int y = 0; y < height && y < new_height; ++y) {
511       for(int x = 0; x < new_width; ++x) {
512         ia_tiles[y * new_width + x] = ia_tiles[y * width + x];
513         bg_tiles[y * new_width + x] = bg_tiles[y * width + x];
514         fg_tiles[y * new_width + x] = fg_tiles[y * width + x];
515       }
516     }
517   }
518
519   ia_tiles.resize(new_width * new_height);
520   bg_tiles.resize(new_width * new_height);
521   fg_tiles.resize(new_width * new_height); 
522
523   if(new_width > width) {
524     // remap tiles
525     for(int y = std::min(height, new_height)-1; y >= 0; --y) {
526       for(int x = new_width-1; x >= 0; --x) {
527         if(x >= width) {
528           ia_tiles[y * new_width + x] = 0;
529           bg_tiles[y * new_width + x] = 0;
530           fg_tiles[y * new_width + x] = 0;
531         } else {
532           ia_tiles[y * new_width + x] = ia_tiles[y * width + x];
533           bg_tiles[y * new_width + x] = bg_tiles[y * width + x];
534           fg_tiles[y * new_width + x] = fg_tiles[y * width + x];
535         }
536       }
537     }
538   }
539
540   height = new_height;
541   width = new_width;
542 }
543
544 void
545 Level::change(float x, float y, int tm, unsigned int c)
546 {
547   int yy = ((int)y / 32);
548   int xx = ((int)x / 32);
549
550   if (yy >= 0 && yy < height && xx >= 0 && xx <= width)
551     {
552       switch(tm)
553         {
554         case TM_BG:
555           bg_tiles[yy * width + xx] = c;
556           break;
557         case TM_IA:
558           ia_tiles[yy * width + xx] = c;
559           break;
560         case TM_FG:
561           fg_tiles[yy * width + xx] = c;
562           break;
563         }
564     }
565 }
566
567 void
568 Level::load_song()
569 {
570   char* song_path;
571   char* song_subtitle;
572
573   level_song = music_manager->load_music(datadir + "/music/" + song_title);
574
575   song_path = (char *) malloc(sizeof(char) * datadir.length() +
576                               strlen(song_title.c_str()) + 8 + 5);
577   song_subtitle = strdup(song_title.c_str());
578   strcpy(strstr(song_subtitle, "."), "\0");
579   sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(), 
580           song_subtitle, strstr(song_title.c_str(), "."));
581   if(!music_manager->exists_music(song_path)) {
582     level_song_fast = level_song;
583   } else {
584     level_song_fast = music_manager->load_music(song_path);
585   }
586   free(song_subtitle);
587   free(song_path);
588 }
589
590 MusicRef
591 Level::get_level_music()
592 {
593   return level_song;
594 }
595
596 MusicRef
597 Level::get_level_music_fast()
598 {
599   return level_song_fast;
600 }
601
602 unsigned int 
603 Level::gettileid(float x, float y) const
604 {
605   int xx, yy;
606   unsigned int c;
607
608   yy = ((int)y / 32);
609   xx = ((int)x / 32);
610
611   if (yy >= 0 && yy < height && xx >= 0 && xx <= width)
612     c = ia_tiles[yy * width + xx];
613   else
614     c = 0;
615
616   return c;
617 }
618
619 unsigned int
620 Level::get_tile_at(int x, int y) const
621 {
622   if(x < 0 || x >= width || y < 0 || y >= height)
623     return 0;
624   
625   return ia_tiles[y * width + x];
626 }
627
628 /* EOF */