485e5e82d301e9d68206fa693d94546f7c473065
[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   bkgd_speed = 50;
231   bkgd_top.red   = 0;
232   bkgd_top.green = 0;
233   bkgd_top.blue  = 0;
234   bkgd_bottom.red   = 255;
235   bkgd_bottom.green = 255;
236   bkgd_bottom.blue  = 255;
237
238   resize(21, 19);
239 }
240
241 int
242 Level::load(const std::string& subset, int level, World* world)
243 {
244   char filename[1024];
245
246   // Load data file:
247   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset.c_str(), level);
248   if(!faccessible(filename))
249     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset.c_str(), level);
250
251   return load(filename, world);
252 }
253
254 int 
255 Level::load(const std::string& filename, World* world)
256 {
257   lisp_object_t* root_obj = lisp_read_from_file(filename);
258   if (!root_obj)
259     {
260       std::cout << "Level: Couldn't load file: " << filename << std::endl;
261       return -1;
262     }
263
264   if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
265     {
266       lisp_free(root_obj);
267       std::cout << "World: Parse Error in file '" << filename
268                 << "'.\n";
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       if(!reader.read_int("height",  &height)) {
289         printf("Warning: no height specified for level.\n");
290       }
291       
292       bkgd_speed = 50;
293       reader.read_int("bkgd_speed",  &bkgd_speed);
294       
295       bkgd_top.red = bkgd_top.green = bkgd_top.blue = 0;
296       reader.read_int("bkgd_red_top",  &bkgd_top.red);
297       reader.read_int("bkgd_green_top",  &bkgd_top.green);
298       reader.read_int("bkgd_blue_top",  &bkgd_top.blue);
299
300       bkgd_bottom.red = bkgd_bottom.green = bkgd_bottom.blue = 0;
301       reader.read_int("bkgd_red_bottom",  &bkgd_bottom.red);
302       reader.read_int("bkgd_green_bottom",  &bkgd_bottom.green);
303       reader.read_int("bkgd_blue_bottom",  &bkgd_bottom.blue);
304
305       gravity = 10;
306       reader.read_float("gravity",  &gravity);
307       name = "Noname";
308       reader.read_string("name",  &name);
309       author = "unknown author";
310       reader.read_string("author", &author);
311       song_title = "";
312       reader.read_string("music",  &song_title);
313       bkgd_image = "";
314       reader.read_string("background",  &bkgd_image);
315       particle_system = "";
316       reader.read_string("particle_system", &particle_system);
317
318       reader.read_int_vector("background-tm",  &bg_tiles);
319       if(int(bg_tiles.size()) != width * height)
320         st_abort("Wrong size of backgroundtilemap", "");
321
322       if (!reader.read_int_vector("interactive-tm", &ia_tiles))
323         reader.read_int_vector("tilemap", &ia_tiles);
324       if(int(ia_tiles.size()) != width * height)
325         st_abort("Wrong size of interactivetilemap", "");      
326
327       reader.read_int_vector("foreground-tm",  &fg_tiles);
328       if(int(fg_tiles.size()) != width * height)
329         st_abort("Wrong size of foregroundtilemap", "");      
330
331       { // Read ResetPoints
332         lisp_object_t* cur = 0;
333         if (reader.read_lisp("reset-points",  &cur))
334           {
335             while (!lisp_nil_p(cur))
336               {
337                 lisp_object_t* data = lisp_car(cur);
338
339                 ResetPoint pos;
340
341                 LispReader reader(lisp_cdr(data));
342                 if (reader.read_int("x", &pos.x)
343                     && reader.read_int("y", &pos.y))
344                   {
345                     reset_points.push_back(pos);
346                   }
347
348                 cur = lisp_cdr(cur);
349               }
350           }
351       }
352
353       { // Read Objects
354         lisp_object_t* cur = 0;
355         if (reader.read_lisp("objects",  &cur))
356           {
357             if(world)
358               world->parse_objects(cur);
359           }
360       }
361
362       { // Read Camera
363         lisp_object_t* cur = 0;
364         if (reader.read_lisp("camera", &cur))
365           {
366             LispReader reader(cur);
367             if(world) {
368               world->camera->read(reader);
369             }
370           }
371       }
372     }
373
374   lisp_free(root_obj);
375   return 0;
376 }
377
378 /* Save data for level: */
379
380 void 
381 Level::save(const std::string& subset, int level, World* world)
382 {
383   char filename[1024];
384   char str[80];
385
386   /* Save data file: */
387   snprintf(str, sizeof(str), "/levels/%s/", subset.c_str());
388   fcreatedir(str);
389   snprintf(filename, sizeof(filename),
390       "%s/levels/%s/level%d.stl", st_dir, subset.c_str(), level);
391   if(!fwriteable(filename))
392     snprintf(filename, sizeof(filename), "%s/levels/%s/level%d.stl",
393         datadir.c_str(), subset.c_str(), level);
394
395   std::ofstream out(filename);
396   if(!out.good()) {
397     st_abort("Couldn't write file.", filename);
398   }
399   LispWriter writer(out);
400
401   /* Write header: */
402   writer.write_comment("SuperTux level made using the built-in leveleditor");
403   writer.start_list("supertux-level");
404
405   writer.write_int("version", 1);
406   writer.write_string("name", name);
407   writer.write_string("author", author);
408   writer.write_string("music", song_title);
409   writer.write_string("background", bkgd_image);
410   writer.write_string("particle_system", particle_system);
411   writer.write_int("bkgd_speed", bkgd_speed);
412   writer.write_int("bkgd_red_top", bkgd_top.red);
413   writer.write_int("bkgd_green_top", bkgd_top.green);
414   writer.write_int("bkgd_blue_top", bkgd_top.blue);
415   writer.write_int("bkgd_red_bottom", bkgd_bottom.red);
416   writer.write_int("bkgd_green_bottom", bkgd_bottom.green);
417   writer.write_int("bkgd_blue_bottom", bkgd_bottom.blue);
418   writer.write_int("time", time_left);
419   writer.write_int("width", width);
420   writer.write_int("height", height);
421   writer.write_float("gravity", gravity);
422
423   writer.write_int_vector("background-tm", bg_tiles);
424   writer.write_int_vector("interactive-tm", ia_tiles);
425   writer.write_int_vector("foreground-tm", fg_tiles);
426
427   writer.start_list("reset-points");
428   for(std::vector<ResetPoint>::iterator i = reset_points.begin();
429       i != reset_points.end(); ++i) {
430     writer.start_list("point");
431     writer.write_int("x", i->x);
432     writer.write_int("y", i->y);
433     writer.end_list("point");
434   }
435   writer.end_list("reset-points");
436
437   // write objects
438   writer.start_list("objects");
439   // pick all objects that can be written into a levelfile
440   for(std::vector<GameObject*>::iterator it = world->gameobjects.begin();
441       it != world->gameobjects.end(); ++it) {
442     Serializable* serializable = dynamic_cast<Serializable*> (*it);
443     if(serializable)
444       serializable->write(writer);
445   }
446   writer.end_list("objects");
447
448   writer.end_list("supertux-level");
449   out.close();
450 }
451
452 /* Unload data for this level: */
453 void
454 Level::cleanup()
455 {
456   bg_tiles.clear();
457   ia_tiles.clear();
458   fg_tiles.clear();
459
460   reset_points.clear();
461   name = "";
462   author = "";
463   song_title = "";
464   bkgd_image = "";
465 }
466
467 void 
468 Level::load_gfx()
469 {
470   if(!bkgd_image.empty())
471     {
472       char fname[1024];
473       snprintf(fname, 1024, "%s/background/%s", st_dir, bkgd_image.c_str());
474       if(!faccessible(fname))
475         snprintf(fname, 1024, "%s/images/background/%s", datadir.c_str(), bkgd_image.c_str());
476       delete img_bkgd;
477       img_bkgd = new Surface(fname, IGNORE_ALPHA);
478     }
479   else
480     {
481       delete img_bkgd;
482       img_bkgd = 0;
483     }
484 }
485
486 /* Load a level-specific graphic... */
487 void Level::load_image(Surface** ptexture, string theme,const  char * file, int use_alpha)
488 {
489   char fname[1024];
490
491   snprintf(fname, 1024, "%s/themes/%s/%s", st_dir, theme.c_str(), file);
492   if(!faccessible(fname))
493     snprintf(fname, 1024, "%s/images/themes/%s/%s", datadir.c_str(), theme.c_str(), file);
494
495   *ptexture = new Surface(fname, use_alpha);
496 }
497
498 /* Change the size of a level */
499 void 
500 Level::resize(int new_width, int new_height)
501 {
502   if(new_width < width) {
503     // remap tiles for new width
504     for(int y = 0; y < height && y < new_height; ++y) {
505       for(int x = 0; x < new_width; ++x) {
506         ia_tiles[y * new_width + x] = ia_tiles[y * width + x];
507         bg_tiles[y * new_width + x] = bg_tiles[y * width + x];
508         fg_tiles[y * new_width + x] = fg_tiles[y * width + x];
509       }
510     }
511   }
512
513   ia_tiles.resize(new_width * new_height);
514   bg_tiles.resize(new_width * new_height);
515   fg_tiles.resize(new_width * new_height); 
516
517   if(new_width > width) {
518     // remap tiles
519     for(int y = std::min(height, new_height)-1; y >= 0; --y) {
520       for(int x = new_width-1; x >= 0; --x) {
521         if(x >= width) {
522           ia_tiles[y * new_width + x] = 0;
523           bg_tiles[y * new_width + x] = 0;
524           fg_tiles[y * new_width + x] = 0;
525         } else {
526           ia_tiles[y * new_width + x] = ia_tiles[y * width + x];
527           bg_tiles[y * new_width + x] = bg_tiles[y * width + x];
528           fg_tiles[y * new_width + x] = fg_tiles[y * width + x];
529         }
530       }
531     }
532   }
533
534   height = new_height;
535   width = new_width;
536 }
537
538 void
539 Level::change(float x, float y, int tm, unsigned int c)
540 {
541   int yy = ((int)y / 32);
542   int xx = ((int)x / 32);
543
544   if (yy >= 0 && yy < height && xx >= 0 && xx <= width)
545     {
546       switch(tm)
547         {
548         case TM_BG:
549           bg_tiles[yy * width + xx] = c;
550           break;
551         case TM_IA:
552           ia_tiles[yy * width + xx] = c;
553           break;
554         case TM_FG:
555           fg_tiles[yy * width + xx] = c;
556           break;
557         }
558     }
559 }
560
561 void
562 Level::load_song()
563 {
564   char* song_path;
565   char* song_subtitle;
566
567   level_song = music_manager->load_music(datadir + "/music/" + song_title);
568
569   song_path = (char *) malloc(sizeof(char) * datadir.length() +
570                               strlen(song_title.c_str()) + 8 + 5);
571   song_subtitle = strdup(song_title.c_str());
572   strcpy(strstr(song_subtitle, "."), "\0");
573   sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(), 
574           song_subtitle, strstr(song_title.c_str(), "."));
575   if(!music_manager->exists_music(song_path)) {
576     level_song_fast = level_song;
577   } else {
578     level_song_fast = music_manager->load_music(song_path);
579   }
580   free(song_subtitle);
581   free(song_path);
582 }
583
584 MusicRef
585 Level::get_level_music()
586 {
587   return level_song;
588 }
589
590 MusicRef
591 Level::get_level_music_fast()
592 {
593   return level_song_fast;
594 }
595
596 unsigned int 
597 Level::gettileid(float x, float y) const
598 {
599   int xx, yy;
600   unsigned int c;
601
602   yy = ((int)y / 32);
603   xx = ((int)x / 32);
604
605   if (yy >= 0 && yy < height && xx >= 0 && xx <= width)
606     c = ia_tiles[yy * width + xx];
607   else
608     c = 0;
609
610   return c;
611 }
612
613 unsigned int
614 Level::get_tile_at(int x, int y) const
615 {
616   if(x < 0 || x >= width || y < 0 || y >= height)
617     return 0;
618   
619   return ia_tiles[y * width + x];
620 }
621
622 /* EOF */