changed most comments from C to C++ style for BD engine code
[rocksndiamonds.git] / src / game_bd / bd_caveset.c
1 /*
2  * Copyright (c) 2007, 2008, 2009, Czirkos Zoltan <cirix@fw.hu>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <sys/stat.h>
18
19 #include "main_bd.h"
20
21
22 // this stores the caves.
23 List *gd_caveset;
24
25 // the data of the caveset: name, highscore, max number of lives, etc.
26 GdCavesetData *gd_caveset_data;
27
28 // is set to true, when the caveset was edited since the last save.
29 boolean gd_caveset_edited;
30
31 // last selected-to-play cave
32 int gd_caveset_last_selected;
33 int gd_caveset_last_selected_level;
34
35 // list of possible extensions which can be opened
36 char *gd_caveset_extensions[] =
37 {
38   "*.gds",
39   "*.bd",
40   "*.bdr",
41   "*.brc",
42
43   NULL
44 };
45
46 #define CAVESET_OFFSET(property) (STRUCT_OFFSET(GdCavesetData, property))
47
48 const GdStructDescriptor gd_caveset_properties[] =
49 {
50   // default data
51   {"", GD_TAB, 0, N_("Caveset data")},
52   {"Name", GD_TYPE_STRING, 0, N_("Name"), CAVESET_OFFSET(name), 1, N_("Name of the game")},
53   {"Description", GD_TYPE_STRING, 0, N_("Description"), CAVESET_OFFSET(description), 1, N_("Some words about the game")},
54   {"Author", GD_TYPE_STRING, 0, N_("Author"), CAVESET_OFFSET(author), 1, N_("Name of author")},
55   {"Date", GD_TYPE_STRING, 0, N_("Date"), CAVESET_OFFSET(date), 1, N_("Date of creation")},
56   {"WWW", GD_TYPE_STRING, 0, N_("WWW"), CAVESET_OFFSET(www), 1, N_("Web page or e-mail address")},
57   {"Difficulty", GD_TYPE_STRING, 0, N_("Difficulty"), CAVESET_OFFSET(difficulty), 1, N_("Difficulty (informative)")},
58
59   {"Lives", GD_TYPE_INT, 0, N_("Initial lives"), CAVESET_OFFSET(initial_lives), 1, N_("Number of lives you get at game start."), 3, 9},
60   {"Lives", GD_TYPE_INT, 0, N_("Maximum lives"), CAVESET_OFFSET(maximum_lives), 1, N_("Maximum number of lives you can have by collecting bonus points."), 3, 99},
61   {"BonusLife", GD_TYPE_INT, 0, N_("Bonus life score"), CAVESET_OFFSET(bonus_life_score), 1, N_("Number of points to collect for a bonus life."), 100, 5000},
62
63   {"Story", GD_TYPE_LONGSTRING, 0, N_("Story"), CAVESET_OFFSET(story), 1, N_("Long description of the game.")},
64   {"Remark", GD_TYPE_LONGSTRING, 0, N_("Remark"), CAVESET_OFFSET(remark), 1, N_("Remark (informative).")},
65
66   {"TitleScreen", GD_TYPE_LONGSTRING, GD_DONT_SHOW_IN_EDITOR, N_("Title screen"), CAVESET_OFFSET(title_screen), 1, N_("Title screen image")},
67   {"TitleScreenScroll", GD_TYPE_LONGSTRING, GD_DONT_SHOW_IN_EDITOR, N_("Title screen, scrolling"), CAVESET_OFFSET(title_screen_scroll), 1, N_("Scrolling background for title screen image")},
68
69   {NULL},
70 };
71
72 static GdPropertyDefault caveset_defaults[] =
73 {
74   // default data
75   {CAVESET_OFFSET(initial_lives), 3},
76   {CAVESET_OFFSET(maximum_lives), 9},
77   {CAVESET_OFFSET(bonus_life_score), 500},
78
79   {-1},
80 };
81
82 GdCavesetData *gd_caveset_data_new(void)
83 {
84   GdCavesetData *data;
85
86   data = checked_calloc(sizeof(GdCavesetData));
87
88   gd_struct_set_defaults_from_array(data, gd_caveset_properties, caveset_defaults);
89
90   return data;
91 }
92
93 void gd_caveset_data_free(GdCavesetData *data)
94 {
95   int i;
96
97   // free strings
98   for (i = 0; gd_caveset_properties[i].identifier != NULL; i++)
99     if (gd_caveset_properties[i].type == GD_TYPE_LONGSTRING)
100       checked_free(STRUCT_MEMBER(char *, data, gd_caveset_properties[i].offset));
101
102   free(data);
103 }
104
105 // ============================================================================
106 // Misc caveset functions
107 // ============================================================================
108
109 // Clears all caves in the caveset. also to be called at application start
110 void gd_caveset_clear(void)
111 {
112   if (gd_caveset)
113   {
114     list_foreach(gd_caveset, (list_fn) gd_cave_free, NULL);
115     list_free(gd_caveset);
116     gd_caveset = NULL;
117   }
118
119   if (gd_caveset_data)
120   {
121     free(gd_caveset_data);
122     gd_caveset_data = NULL;
123   }
124
125   // always newly create this
126   // create pseudo cave containing default values
127   gd_caveset_data = gd_caveset_data_new();
128   gd_strcpy(gd_caveset_data->name, getCurrentLevelsetName());
129 }
130
131 // return number of caves currently in memory.
132 int gd_caveset_count(void)
133 {
134   return list_length(gd_caveset);
135 }
136
137 // return index of first selectable cave
138 static int caveset_first_selectable_cave_index(void)
139 {
140   List *iter;
141   int i;
142
143   for (i = 0, iter = gd_caveset; iter != NULL; i++, iter = iter->next)
144   {
145     GdCave *cave = (GdCave *)iter->data;
146
147     if (cave->selectable)
148       return i;
149   }
150
151   Warn("no selectable cave in caveset!");
152
153   // and return the first one.
154   return 0;
155 }
156
157 // return a cave identified by its index
158 GdCave *gd_return_nth_cave(const int cave)
159 {
160   return list_nth_data(gd_caveset, cave);
161 }
162
163 // get a selected cave from the loaded caveset (original, unmodified cave)
164 GdCave *gd_get_original_cave_from_caveset(const int cave)
165 {
166   // get specified cave from caveset already stored in memory
167   GdCave *original_cave = gd_return_nth_cave(cave);
168
169   return original_cave;
170 }
171
172 // get a selected cave from the loaded caveset (cave prepared for playing)
173 GdCave *gd_get_prepared_cave_from_caveset(const int cave, const int level)
174 {
175   // get specified cave from caveset already stored in memory
176   GdCave *original_cave = gd_return_nth_cave(cave);
177
178   // get prepared cave from original cave
179   GdCave *prepared_cave = gd_get_prepared_cave(original_cave, level);
180
181   return prepared_cave;
182 }
183
184 // get a cave prepared for playing from a given original, unmodified cave (with seed)
185 GdCave *gd_get_prepared_cave(const GdCave *original_cave, const int level)
186 {
187   // get rendered cave using the selected seed for playing
188   GdCave *prepared_cave = gd_cave_new_rendered(original_cave, level, game_bd.random_seed);
189
190   // initialize some cave variables (like player position)
191   gd_cave_setup_for_game(prepared_cave);
192
193   return prepared_cave;
194 }
195
196 // colors: 4: purple  3: ciklamen 2: orange 1: blue 0: green
197 static GdElement brc_import_table[] =
198 {
199   /* 0 */
200   O_SPACE, O_DIRT, O_BRICK, O_MAGIC_WALL, O_PRE_OUTBOX, O_OUTBOX, O_UNKNOWN, O_STEEL,
201   O_H_EXPANDING_WALL, O_H_EXPANDING_WALL /* scanned */, O_FIREFLY_1 /* scanned */, O_FIREFLY_1 /* scanned */, O_FIREFLY_1, O_FIREFLY_2, O_FIREFLY_3, O_FIREFLY_4,
202
203   /* 1 */
204   O_BUTTER_1 /* scanned */, O_BUTTER_1 /* scanned */, O_BUTTER_1, O_BUTTER_2, O_BUTTER_3, O_BUTTER_4, O_PLAYER, O_PLAYER /* scanned */,
205   O_STONE, O_STONE /* scanned */, O_STONE_F, O_STONE_F /* scanned */, O_DIAMOND, O_DIAMOND /* scanned */, O_DIAMOND_F, O_DIAMOND_F /* scanned */,
206
207   /* 2 */
208   O_NONE /* WILL_EXPLODE_THING */, O_EXPLODE_1, O_EXPLODE_2, O_EXPLODE_3, O_EXPLODE_4, O_EXPLODE_5, O_NONE /* WILL EXPLODE TO DIAMOND_THING */, O_PRE_DIA_1,
209   O_PRE_DIA_2, O_PRE_DIA_3, O_PRE_DIA_4, O_PRE_DIA_5, O_AMOEBA, O_AMOEBA /* scanned */, O_SLIME, O_NONE,
210
211   /* 3 */
212   O_CLOCK, O_NONE /* clock eaten */, O_INBOX, O_PRE_PL_1, O_PRE_PL_2, O_PRE_PL_3, O_NONE, O_NONE,
213   O_NONE, O_NONE, O_V_EXPANDING_WALL, O_NONE, O_VOODOO, O_UNKNOWN, O_EXPANDING_WALL, O_EXPANDING_WALL /* sc */,
214
215   /* 4 */
216   O_FALLING_WALL, O_FALLING_WALL_F, O_FALLING_WALL_F /* scanned */, O_UNKNOWN, O_ACID, O_ACID /* scanned */, O_NITRO_PACK, O_NITRO_PACK /* scanned */,
217   O_NITRO_PACK_F, O_NITRO_PACK_F /* scanned */, O_NONE, O_NONE, O_NONE, O_NONE, O_NONE, O_NONE,
218
219   /* 5 */
220   O_NONE /* bomb explosion utolso */, O_UNKNOWN, O_NONE /* solid bomb glued */, O_UNKNOWN, O_STONE_GLUED, O_UNKNOWN, O_DIAMOND_GLUED, O_UNKNOWN,
221   O_UNKNOWN, O_UNKNOWN, O_NONE, O_NONE, O_NONE, O_NONE, O_NONE, O_NONE,
222
223   /* 6 */
224   O_ALT_FIREFLY_1 /* scanned */, O_ALT_FIREFLY_1 /* scanned */, O_ALT_FIREFLY_1, O_ALT_FIREFLY_2, O_ALT_FIREFLY_3, O_ALT_FIREFLY_4, O_PLAYER_BOMB, O_PLAYER_BOMB /* scanned */,
225   O_BOMB, O_BOMB_TICK_1, O_BOMB_TICK_2, O_BOMB_TICK_3, O_BOMB_TICK_4, O_BOMB_TICK_5, O_BOMB_TICK_6, O_BOMB_TICK_7,
226
227   /* 7 */
228   O_BOMB_TICK_7, O_BOMB_EXPL_1, O_BOMB_EXPL_2, O_BOMB_EXPL_3, O_BOMB_EXPL_4, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN,
229   O_UNKNOWN, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN,
230 };
231
232 static GdElement brc_effect_table[] =
233 {
234   O_STEEL, O_DIRT, O_SPACE, O_STONE, O_STONE_F, O_STONE_GLUED, O_DIAMOND, O_DIAMOND_F, O_DIAMOND_GLUED, O_PRE_DIA_1,
235   O_PLAYER, O_PRE_PL_1, O_PLAYER_BOMB, O_PRE_OUTBOX, O_OUTBOX, O_FIREFLY_1, O_FIREFLY_2, O_FIREFLY_3, O_FIREFLY_4,
236   O_BUTTER_1, O_BUTTER_2, O_BUTTER_3, O_BUTTER_4, O_BRICK, O_MAGIC_WALL, O_H_EXPANDING_WALL, O_V_EXPANDING_WALL, O_EXPANDING_WALL,
237   O_FALLING_WALL, O_FALLING_WALL_F, O_AMOEBA, O_SLIME, O_ACID, O_VOODOO, O_CLOCK, O_BOMB, O_UNKNOWN, O_UNKNOWN, O_UNKNOWN,
238   O_ALT_FIREFLY_1, O_ALT_FIREFLY_2, O_ALT_FIREFLY_3, O_ALT_FIREFLY_4, O_ALT_BUTTER_1, O_ALT_BUTTER_2, O_ALT_BUTTER_3, O_ALT_BUTTER_4,
239   O_EXPLODE_1, O_BOMB_EXPL_1, O_UNKNOWN,
240 };
241
242 static GdColor brc_color_table[] =
243 {
244   0x518722, 0x3a96fa, 0xdb7618, 0xff3968,
245   0x9b5fff, 0x0ee06c, 0xc25ea6, 0xf54826,
246   0xf1ff26,
247 };
248
249 static GdColor brc_color_table_comp[] =
250 {
251   0x582287, 0xfa9d39, 0x187ddb, 0x38ffd1,
252   0xc1ff5e, 0xe00d81, 0x5dc27a, 0x27d3f5,
253   0x3526ff,
254 };
255
256 static GdElement brc_effect(byte byt)
257 {
258   if (byt >= ARRAY_SIZE(brc_effect_table))
259   {
260     Warn("invalid element identifier for brc effect: %02x", byt);
261
262     return O_UNKNOWN;
263   }
264
265   return brc_effect_table[byt];
266 }
267
268 static void brc_import(byte *data)
269 {
270   int x, y;
271   int level;
272
273   // we import 100 caves, and the put them in the correct order.
274   GdCave *imported[100];
275   boolean import_effect;
276
277   gd_caveset_clear();
278
279   // this is some kind of a version number
280   import_effect = FALSE;
281
282   switch (data[23])
283   {
284     case 0x0:
285       // nothing to do
286       break;
287
288     case 0xde:
289       // import effects
290       import_effect = TRUE;
291       break;
292
293     default:
294       Warn("unknown brc version %02x", data[23]);
295       break;
296   }
297
298   for (level = 0; level < 5; level++)
299   {
300     int cavenum;
301     int i;
302
303     for (cavenum = 0; cavenum < 20; cavenum++)
304     {
305       GdCave *cave;
306
307       // 5 levels, 20 caves, 24 bytes - max 40*2 properties for each cave
308       int c = 5 * 20 * 24;
309
310       int datapos = (cavenum * 5 +level) * 24 + 22;
311       int colind;
312
313       cave = gd_cave_new();
314       imported[level * 20 + cavenum] = cave;
315
316       if (cavenum < 16)
317         snprintf(cave->name, sizeof(GdString), "Cave %c/%d", 'A' + cavenum,
318                  level + 1);
319       else
320         snprintf(cave->name, sizeof(GdString), "Intermission %d/%d",
321                  cavenum - 15, level + 1);
322
323       // fixed intermission caves; are smaller.
324       if (cavenum >= 16)
325       {
326         cave->w = 20;
327         cave->h = 12;
328       }
329
330       cave->map = gd_cave_map_new(cave, GdElement);
331
332       for (y = 0; y < cave->h; y++)
333       {
334         for (x = 0; x < cave->w; x++)
335         {
336           byte import;
337
338           import = data[y + level * 24 + cavenum * 24 * 5 + x * 24 * 5 * 20];
339
340           // if (i == printcave) g_print("%2x", import);
341           if (import < ARRAY_SIZE(brc_import_table))
342             cave->map[y][x] = brc_import_table[import];
343           else
344             cave->map[y][x] = O_UNKNOWN;
345         }
346       }
347
348       for (i = 0; i < 5; i++)
349       {
350         cave->level_time[i]             = data[0 * c + datapos];
351         cave->level_diamonds[i]         = data[1 * c + datapos];
352         cave->level_magic_wall_time[i]  = data[4 * c + datapos];
353         cave->level_amoeba_time[i]      = data[5 * c + datapos];
354         cave->level_amoeba_threshold[i] = data[6 * c + datapos];
355
356         // bonus time: 100 was added, so it could also be negative
357         cave->level_bonus_time[i]      = (int)data[11 * c + datapos + 1] - 100;
358         cave->level_hatching_delay_frame[i] = data[10 * c + datapos];
359
360         // this was not set in boulder remake.
361         cave->level_speed[i] = 150;
362       }
363
364       cave->diamond_value = data[2 * c + datapos];
365       cave->extra_diamond_value = data[3 * c +datapos];
366
367       // BRC PROBABILITIES
368       /*
369         a typical code example:
370         46:if (random(slime*4)<4) and (tab[x,y+2] = 0) then
371         Begin tab[x,y]:=0;col[x,y+2]:=col[x,y];tab[x,y+2]:=27;mat[x,y+2]:=9;Voice4:=2;end;
372         where slime is the byte loaded from the file as it is.
373         pascal random function generates a random number between 0..limit-1,
374         inclusive, for random(limit).
375
376         so a random number between 0..limit*4-1 is generated.
377         for limit=1, 0..3, which is always < 4, so P=1.
378         for limit=2, 0..7, 0..7 is < 4 in P=50%.
379         for limit=3, 0..11, is < 4 in P=33%.
380         So the probability is exactly 100%/limit.
381         just make sure we do not divide by zero for some broken input.
382       */
383
384       if (data[7 * c + datapos] == 0)
385         Warn("amoeba growth cannot be zero, error at byte %d",
386              data[7 * c + datapos]);
387       else
388         cave->amoeba_growth_prob = 1E6 / data[7 * c + datapos] + 0.5; // 0.5 for rounding
389
390       if (data[8 * c + datapos] == 0)
391         Warn("amoeba growth cannot be zero, error at byte %d",
392              data[8 * c + datapos]);
393       else
394         cave->amoeba_fast_growth_prob = 1E6 / data[8 * c + datapos] + 0.5; // 0.5 for rounding
395
396       cave->slime_predictable = FALSE;
397
398       for (i = 0; i < 5; i++)
399         cave->level_slime_permeability[i] = 1E6 / data[9 * c + datapos] + 0.5;   // 0.5 for rounding
400
401       // probability -> *1E6
402       cave->acid_spread_ratio = 1E6 / data[10 * c + datapos] + 0.5;
403
404       // br only allowed values 1..8 in here, but works the same way. prob -> *1E6
405       cave->pushing_stone_prob = 1E6 / data[11 * c + datapos] + 0.5;
406
407       cave->magic_wall_stops_amoeba = (data[12 * c + datapos + 1] != 0);
408       cave->intermission = (cavenum >= 16 || data[14 * c + datapos + 1] != 0);
409
410       // colors
411       colind = data[31 * c + datapos] % ARRAY_SIZE(brc_color_table);
412       cave->colorb = 0x000000;    // fixed rgb black
413       cave->color0 = 0x000000;    // fixed rgb black
414       cave->color1 = brc_color_table[colind];
415       cave->color2 = brc_color_table_comp[colind];    // complement
416       cave->color3 = 0xffffff;    // white for brick
417       cave->color4 = 0xe5ad23;    // fixed for amoeba
418       cave->color5 = 0x8af713;    // fixed for slime
419
420       if (import_effect)
421       {
422         cave->amoeba_enclosed_effect = brc_effect(data[14 * c + datapos + 1]);
423         cave->amoeba_too_big_effect  = brc_effect(data[15 * c + datapos + 1]);
424         cave->explosion_effect       = brc_effect(data[16 * c + datapos + 1]);
425         cave->bomb_explosion_effect  = brc_effect(data[17 * c + datapos + 1]);
426
427         // 18 solid bomb explode to
428         cave->diamond_birth_effect    = brc_effect(data[19 * c + datapos + 1]);
429         cave->stone_bouncing_effect   = brc_effect(data[20 * c + datapos + 1]);
430         cave->diamond_bouncing_effect = brc_effect(data[21 * c + datapos + 1]);
431         cave->magic_diamond_to        = brc_effect(data[22 * c + datapos + 1]);
432         cave->acid_eats_this          = brc_effect(data[23 * c + datapos + 1]);
433
434         /*
435           slime eats:
436           (diamond,boulder,bomb),
437           (diamond,boulder),
438           (diamond,bomb),
439           (boulder,bomb)
440         */
441         cave->amoeba_enclosed_effect = brc_effect(data[14 * c + datapos + 1]);
442       }
443     }
444   }
445
446   // put them in the caveset - take correct order into consideration.
447   for (level = 0; level < 5; level++)
448   {
449     int cavenum;
450
451     for (cavenum = 0; cavenum < 20; cavenum++)
452     {
453       static const int reorder[] =
454       {
455         0, 1, 2, 3, 16, 4, 5, 6, 7, 17, 8, 9, 10, 11, 18, 12, 13, 14, 15, 19
456       };
457       GdCave *cave = imported[level * 20 + reorder[cavenum]];
458       boolean only_dirt;
459       int x, y;
460
461       // check if cave contains only dirt.
462       // that is an empty cave, and do not import.
463       only_dirt = TRUE;
464
465       for (y = 1; y < cave->h - 1 && only_dirt; y++)
466         for (x = 1; x < cave->w - 1 && only_dirt; x++)
467           if (cave->map[y][x] != O_DIRT)
468             only_dirt = FALSE;
469
470       // append to caveset or forget it.
471       if (!only_dirt)
472         gd_caveset = list_append(gd_caveset, cave);
473       else
474         gd_cave_free(cave);
475     }
476   }
477 }
478
479 static void caveset_name_set_from_filename(char *filename)
480 {
481   char *name;
482   char *c;
483
484   // make up a caveset name from the filename.
485   name = getBaseName(filename);
486   gd_strcpy(gd_caveset_data->name, name);
487   free(name);
488
489   // convert underscores to spaces
490   while ((c = strchr (gd_caveset_data->name, '_')) != NULL)
491     *c = ' ';
492
493   // remove extension
494   if ((c = strrchr (gd_caveset_data->name, '.')) != NULL)
495     *c = 0;
496 }
497
498 /*
499   Load caveset from file.
500   Loads the caveset from a file.
501
502   File type is autodetected by extension.
503   param filename: Name of file.
504   result: FALSE if failed
505 */
506 boolean gd_caveset_load_from_file(char *filename)
507 {
508   size_t length;
509   char *buf;
510   List *new_caveset;
511   struct stat st;
512   File *file;
513
514   if (stat(filename, &st) != 0)
515   {
516     Warn("cannot stat() file");
517
518     return FALSE;
519   }
520
521   if (st.st_size > 1048576)
522   {
523     Warn("file bigger than 1MiB, refusing to load");
524
525     return FALSE;
526   }
527
528   if (!(file = openFile(filename, MODE_READ)))
529   {
530     Warn("cannot open file '%s'", filename);
531
532     return FALSE;
533   }
534
535   buf = checked_malloc(st.st_size + 1);
536   length = readFile(file, buf, 1, st.st_size);
537   buf[length] = '\0';
538
539   closeFile(file);
540
541   if (length < st.st_size)
542   {
543     Warn("cannot read file '%s'", filename);
544
545     return FALSE;
546   }
547
548   if (strSuffix(filename, ".brc") ||
549       strSuffix(filename, ".BRC"))
550   {
551     // loading a boulder remake file
552     if (length != 96000)
553     {
554       Warn("BRC files must be 96000 bytes long");
555
556       return FALSE;
557     }
558   }
559
560   if (strSuffix(filename, ".brc") ||
561       strSuffix(filename, ".BRC"))
562   {
563     brc_import((byte *) buf);
564     gd_caveset_edited = FALSE;    // newly loaded cave is not edited
565     gd_caveset_last_selected = caveset_first_selectable_cave_index();
566     gd_caveset_last_selected_level = 0;
567     free(buf);
568     caveset_name_set_from_filename(filename);
569
570     return TRUE;
571   }
572
573   // BDCFF
574   if (gd_caveset_imported_get_format((byte *) buf) == GD_FORMAT_UNKNOWN)
575   {
576     // try to load as bdcff
577     boolean result;
578
579     // bdcff: start another function
580     result = gd_caveset_load_from_bdcff(buf);
581
582     // newly loaded file is not edited.
583     gd_caveset_edited = FALSE;
584
585     gd_caveset_last_selected = caveset_first_selectable_cave_index();
586     gd_caveset_last_selected_level = 0;
587     free(buf);
588
589     return result;
590   }
591
592   // try to load as a binary file, as we know the format
593   new_caveset = gd_caveset_import_from_buffer ((byte *) buf, length);
594   free(buf);
595
596   // if unable to load, exit here. error was reported by import_from_buffer()
597   if (!new_caveset)
598     return FALSE;
599
600   // no serious error :)
601
602   // only clear caveset here. if file read was unsuccessful, caveset remains in memory.
603   gd_caveset_clear();
604
605   gd_caveset = new_caveset;
606
607   // newly loaded cave is not edited
608   gd_caveset_edited = FALSE;
609
610   gd_caveset_last_selected = caveset_first_selectable_cave_index();
611   gd_caveset_last_selected_level = 0;
612   caveset_name_set_from_filename(filename);
613
614   return TRUE;
615 }
616
617 boolean gd_caveset_save_to_file(const char *filename)
618 {
619   GdPtrArray *saved = gd_caveset_save_to_bdcff();
620   boolean success;
621   File *file;
622   int i;
623
624   if ((file = openFile(filename, MODE_WRITE)) != NULL)
625   {
626     for (i = 0; i < saved->size; i++)
627     {
628       writeFile(file, saved->data[i], 1, strlen(saved->data[i]));
629       writeFile(file, "\n", 1, 1);
630     }
631
632     closeFile(file);
633
634     // remember that it is saved
635     gd_caveset_edited = FALSE;
636
637     success = TRUE;
638   }
639   else
640   {
641     Warn("cannot open file '%s'", filename);
642
643     success = FALSE;
644   }
645
646   gd_ptr_array_free(saved, TRUE);
647
648   return success;
649 }
650
651
652 int gd_cave_check_replays(GdCave *cave, boolean report, boolean remove, boolean repair)
653 {
654   List *riter;
655   int wrong = 0;
656
657   riter = cave->replays;
658   while (riter != NULL)
659   {
660     GdReplay *replay = (GdReplay *)riter->data;
661     unsigned int checksum;
662     GdCave *rendered;
663     List *next = riter->next;
664
665     rendered = gd_cave_new_rendered(cave, replay->level, replay->seed);
666     checksum = gd_cave_adler_checksum(rendered);
667     gd_cave_free(rendered);
668
669     replay->wrong_checksum = FALSE;
670
671     // count wrong ones... the checksum might be changed later to "repair"
672     if (replay->checksum != 0 && checksum != replay->checksum)
673       wrong++;
674
675     if (replay->checksum == 0 || repair)
676     {
677       // if no checksum found, add one. or if repair requested, overwrite old one.
678       replay->checksum = checksum;
679     }
680     else
681     {
682       // if has a checksum, compare with this one.
683       if (replay->checksum != checksum)
684       {
685         replay->wrong_checksum = TRUE;
686
687         if (report)
688           Warn("%s: replay played by %s at %s has wrong checksum",
689                cave->name, replay->player_name, replay->date);
690
691         if (remove)
692         {
693           // may remove
694           cave->replays = list_remove_link(cave->replays, riter);
695           gd_replay_free(replay);
696         }
697       }
698     }
699
700     // advance to next list item which we remembered. the current one might have been deleted
701     riter = next;
702   }
703
704   return wrong;
705 }
706
707 boolean gd_caveset_has_replays(void)
708 {
709   List *citer;
710
711   // for all caves
712   for (citer = gd_caveset; citer != NULL; citer = citer->next)
713   {
714     GdCave *cave = (GdCave *)citer->data;
715
716     if (cave->replays)
717       return TRUE;
718   }
719
720   // if neither of the caves had a replay,
721   return FALSE;
722 }