add replay file extension (fixes #42)
[neverball] / ball / demo.c
1 /*   
2  * Copyright (C) 2003 Robert Kooima
3  *
4  * NEVERBALL is  free software; you can redistribute  it and/or modify
5  * it under the  terms of the GNU General  Public License as published
6  * by the Free  Software Foundation; either version 2  of the License,
7  * or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT  ANY  WARRANTY;  without   even  the  implied  warranty  of
11  * MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
12  * General Public License for more details.
13  */
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <time.h>
19
20 #ifndef _WIN32
21 #include <unistd.h>
22 #endif
23
24 #include "demo.h"
25 #include "game.h"
26 #include "audio.h"
27 #include "solid.h"
28 #include "config.h"
29 #include "binary.h"
30
31 /*---------------------------------------------------------------------------*/
32
33 #define MAGIC     0x4E425251 /* Replay file magic number (should not change) */
34 #define OLD_MAGIC 0x4E425250 /* Replay file magic number for neverball 1.4.0 */
35 #define REPLAY_VERSION  1    /* Replay file format version (can change)      */
36
37 #define DEMO_FPS_CAP 200 /* FPS replay limit, keeps size down on monster systems */
38
39 static FILE *demo_fp;
40
41 static struct demo demos[MAXDEMO]; /* Array of scanned demos */
42
43 static int count; /* number of scanned demos */
44
45 /*---------------------------------------------------------------------------*/
46
47 void demo_dump_info(const struct demo * d)
48 /* This function dump the info of a demo structure*/
49 {
50     printf(_("Name:         %s\n"
51            "File:         %s\n"
52            "NB Version:   %s\n"
53            "Time:         %d\n"
54            "Coins:        %d\n"
55            "Mode:         %d\n"
56            "State:        %d\n"
57            "Date:         %s"
58            "Player:       %s\n"
59            "Shot:         %s\n"
60            "Level:        %s\n"
61            "  Back:       %s\n"
62            "  Grad:       %s\n"
63            "  Song:       %s\n"
64            "Time:         %d\n"
65            "Goal:         %d\n"
66            "Score:        %d\n"
67            "Balls:        %d\n"
68            "Total Time:   %d\n"),
69            d->name, d->filename,
70            d->nb_version,
71            d->timer, d->coins, d->mode, d->state, ctime(&d->date),
72            d->player,
73            d->shot, d->file, d->back, d->grad, d->song,
74            d->time, d->goal, d->score, d->balls, d->times);
75 }
76
77 FILE * demo_header_read(const char * filename, struct demo * d)
78 /* Open a demo file, fill the demo information structure
79  * If success, return the file pointer positioned after the header
80  * If fail, return null 
81  */
82 {
83     FILE *fp;
84     char *basename;
85     char buf[MAXSTR];
86     
87     if ((fp = fopen(filename, FMODE_RB)))
88     {
89         int magic;
90         int version;
91         int t;
92
93         get_index(fp, &magic);
94         get_index(fp, &version);
95         get_index(fp, &t);  /* if time is 0, it's mean the replay wat not finished */
96
97         if (magic == MAGIC && version == REPLAY_VERSION && t)
98         {
99             d->timer = t;
100             strncpy(d->filename, filename, PATHMAX);
101             
102             /* Remove the directory delimiter */
103 #ifdef _WIN32
104             basename = strrchr(filename, '\\');
105 #else
106             basename = strrchr(filename, '/');
107 #endif
108             
109             if (basename != NULL)
110                 strncpy(buf, basename+1, MAXSTR);
111             else
112                 strncpy(buf, filename, MAXSTR);
113             
114             /* Remove the extension */
115             t = strlen(buf) - strlen(REPLAY_EXT);
116             if ((t > 1) && (strcmp(buf+t, REPLAY_EXT) == 0))
117                 buf[t] = '\0';
118             strncpy(d->name, buf, MAXNAM);
119             d->name[MAXNAM-1]= '\0';
120             
121             get_index (fp, &d->coins);
122             get_index (fp, &d->state);
123             get_index (fp, &d->mode);
124             get_index (fp, (int*)&d->date);
125             get_string(fp, d->player, MAXNAM);
126             get_string(fp, d->shot,   PATHMAX);
127             get_string(fp, d->file,   PATHMAX);
128             get_string(fp, d->back,   PATHMAX);
129             get_string(fp, d->grad,   PATHMAX);
130             get_string(fp, d->song,   PATHMAX);
131             get_index (fp, &d->time);
132             get_index (fp, &d->goal);
133             get_index (fp, &d->score);
134             get_index (fp, &d->balls);
135             get_index (fp, &d->times);
136             get_string(fp, d->nb_version, 20);
137
138             return fp;
139         }
140         fclose(fp);
141     }
142     return NULL;
143 }
144
145 static FILE * demo_header_write(struct demo * d)
146 /* Create a new demo file, write the demo information structure
147  * If success, return the file pointer positioned after the header
148  * If fail, return null
149  * */
150 {
151     int magic = MAGIC;
152     int version = REPLAY_VERSION;
153     int zero  = 0;
154     FILE *fp;
155     
156     if (d->filename && (fp = fopen(d->filename, FMODE_WB)))
157     {
158         put_index (fp, &magic);
159         put_index (fp, &version);
160         put_index (fp, &zero);
161         put_index (fp, &zero);
162         put_index (fp, &zero);
163         put_index (fp, &d->mode);
164         put_index (fp, (int*)&d->date);
165         put_string(fp, d->player);
166         put_string(fp, d->shot);
167         put_string(fp, d->file);
168         put_string(fp, d->back);
169         put_string(fp, d->grad);
170         put_string(fp, d->song);
171         put_index (fp, &d->time);
172         put_index (fp, &d->goal);
173         put_index (fp, &d->score);
174         put_index (fp, &d->balls);
175         put_index (fp, &d->times);
176         put_string(fp, VERSION);
177
178         return fp;
179     }
180     return NULL;
181 }
182
183 void demo_header_stop(FILE * fp, int coins, int timer, int state)
184     /* Update the demo header using the final level state. */
185 {
186     long pos = ftell(fp);
187     fseek(fp, 8, SEEK_SET);
188     put_index(fp, &timer);
189     put_index(fp, &coins);
190     put_index(fp, &state);
191     fseek(fp, pos, SEEK_SET);
192 }
193         
194 /*---------------------------------------------------------------------------*/
195
196 static void demo_scan_file(const char * filename)
197 /* Scan a other file (used by demo_scan */
198 {
199     FILE *fp;
200     if ((fp = demo_header_read(config_user(filename), &demos[count])))
201     {
202         count++;
203         fclose(fp);
204     }
205 }
206
207 #ifdef _WIN32
208
209 int demo_scan(void)
210 {
211     WIN32_FIND_DATA d;
212     HANDLE h;
213
214     count = 0;
215
216     /* Scan the user directory for files. */
217
218     if ((h = FindFirstFile(config_user("*"), &d)) != INVALID_HANDLE_VALUE)
219     {
220         do
221             demo_scan_file(d.cFileName);
222         while (count < MAXDEMO && FindNextFile(h, &d));
223
224         FindClose(h);
225     }
226     return count;
227 }
228
229 #else /* _WIN32 */
230 #include <dirent.h>
231
232 int demo_scan(void)
233 {
234     struct dirent *ent;
235     DIR  *dp;
236
237     count = 0;
238
239     /* Scan the user directory for files. */
240
241     if ((dp = opendir(config_user(""))))
242     {
243         while (count < MAXDEMO && (ent = readdir(dp)))
244             demo_scan_file(ent->d_name);
245
246         closedir(dp);
247     }
248     return count;
249 }
250 #endif /* _WIN32 */
251
252 const char *demo_pick(void)
253 {
254     int n = demo_scan();
255
256     return (n > 0) ? demos[(rand() >> 4) % n].filename : NULL;
257 }
258
259 const struct demo *get_demo(int i)
260 {
261     return (0 <= i && i < count) ? &demos[i] : NULL;
262 }
263
264 const char * date_to_str(time_t i)
265 {
266     static char str[MAXSTR];
267     struct tm * tm = localtime(&i);
268     strftime (str, MAXSTR, "%c", tm);
269     return str;
270 }
271
272 /*---------------------------------------------------------------------------*/
273
274 int demo_exists(char *name)
275 {
276     FILE *fp;
277
278     if ((fp = fopen(config_user(name), "r")))
279     {
280         fclose(fp);
281         return 1;
282     }
283     return 0;
284 }
285
286 void demo_unique(char *name)
287 {
288     int i;
289
290     /* Generate a unique name for a new replay save. */
291
292     for (i = 1; i < 100; i++)
293     {
294         sprintf(name, _("replay%02d"), i);
295
296         if (!demo_exists(name))
297             return;
298     }
299 }
300
301 /*---------------------------------------------------------------------------*/
302
303 int demo_play_init(const char *name,
304                    const struct level * level,
305                    const struct level_game * lg)
306 {
307     struct demo demo;
308
309     /* file structure */
310     strncpy(demo.name, name, MAXNAM);
311     strncpy(demo.filename, config_user(name), PATHMAX);
312     demo.time = demo.coins = demo.state = 0;
313     demo.mode = lg->mode;
314     demo.date = time(NULL);
315     config_get_s(CONFIG_PLAYER, demo.player, MAXNAM);
316     strncpy(demo.shot, level->shot, PATHMAX);
317     strncpy(demo.file, level->file, PATHMAX);
318     strncpy(demo.back, level->back, PATHMAX);
319     strncpy(demo.grad, level->grad, PATHMAX);
320     strncpy(demo.song, level->song, PATHMAX);
321     demo.time  = lg->time;
322     demo.goal  = lg->goal;
323     demo.score = lg->score;
324     demo.balls = lg->balls;
325     demo.times = lg->times;
326
327     demo_fp = demo_header_write(&demo);
328     if (demo_fp == NULL)
329         return 0;
330     else
331     {
332         audio_music_fade_to(2.0f, level->song);
333         return game_init(level, lg->time, lg->goal);
334     }
335 }
336
337 void demo_play_step(float dt)
338 {
339     static float fps_track = 0.0f;
340     static float fps_cap   = 1.0f / (float) DEMO_FPS_CAP;
341
342     if (demo_fp)
343     {
344         fps_track += dt;
345         if (fps_track > fps_cap)
346         {            
347             put_float(demo_fp, &fps_track);
348             put_game_state(demo_fp); 
349             fps_track = 0.0f;
350         }
351     }
352 }
353
354 void demo_play_stop(const struct level_game *lg)
355 /* Update the demo header using the final level state. */
356 {
357     if (demo_fp)
358     {
359         demo_header_stop(demo_fp, lg->coins, lg->timer, lg->state);
360         fclose(demo_fp);
361         demo_fp = NULL;
362     }
363 }
364
365 int demo_play_saved(void)
366 {
367     return demo_exists(USER_REPLAY_FILE);
368 }
369
370 void demo_play_save(const char *name)
371 {
372     char src[PATHMAX];
373     char dst[PATHMAX];
374
375     if (name && demo_exists(USER_REPLAY_FILE) && strcmp(name, USER_REPLAY_FILE) != 0)
376     {
377         strncpy(src, config_user(USER_REPLAY_FILE), PATHMAX);
378         strncpy(dst, config_user(name),             PATHMAX);
379         strcat(dst, REPLAY_EXT);
380
381         rename(src, dst);
382     }
383 }
384
385 /*---------------------------------------------------------------------------*/
386
387 static int demo_load_level(const struct demo * demo, struct level * level)
388 /* Load the level of the demo and fill the level structure */
389 {
390     strcpy(level->file, demo->file);
391     strcpy(level->back, demo->back);
392     strcpy(level->grad, demo->grad);
393     strcpy(level->shot, demo->shot);
394     strcpy(level->song, demo->song);
395     level->time = demo->time;
396     level->goal = demo->goal;
397     return 1;
398 }
399
400 static struct demo  demo_replay;       /* The current demo */
401 static struct level demo_level_replay; /* The current level demo-ed*/
402
403 const struct demo * curr_demo_replay(void)
404 {
405     return &demo_replay;
406 }
407
408
409 int demo_replay_init(const char *name, struct level_game *lg)
410 /* Internally load a replay an fill the lg structure (if not NULL) */
411 {
412     if ((demo_fp = demo_header_read(name, &demo_replay)))
413     {
414         demo_load_level(&demo_replay, &demo_level_replay);
415         
416         if (lg)
417         {
418             lg->mode       = demo_replay.mode;
419             lg->score      = demo_replay.score;
420             lg->times      = demo_replay.times;
421             lg->time       = demo_replay.time;
422             lg->goal       = demo_replay.goal;
423             
424             /* A normal replay demo */
425             audio_music_fade_to(0.5f, demo_replay.song);
426             return game_init(&demo_level_replay, demo_replay.time, demo_replay.goal);
427         }
428         else /* A title screen demo */
429             return game_init(&demo_level_replay, demo_replay.time, 0);
430     }
431     
432     return 0;
433 }
434
435 int demo_replay_step(float *dt)
436 {
437     const float g[3] = { 0.0f, -9.8f, 0.0f };
438
439     if (demo_fp)
440     {
441         get_float(demo_fp, dt);
442
443         if (feof(demo_fp) == 0)
444         {
445             /* Play out current game state for particles, clock, etc. */
446
447             game_step(g, *dt, 1);
448
449             /* Load real current game state from file. */
450             
451             if (get_game_state(demo_fp))
452                 return 1;
453         }
454     }
455     return 0;
456 }
457
458 void demo_replay_stop(int d)
459 {
460     if (demo_fp)
461     {
462         fclose(demo_fp);
463         demo_fp = NULL;
464
465         if (d) unlink(demo_replay.filename);
466     }
467 }
468
469 void demo_replay_dump_info(void)
470 {
471     demo_dump_info(&demo_replay);
472 }
473
474 /*---------------------------------------------------------------------------*/