d93c6632a97e7f2112db654aec44c700f6987b6a
[rocksndiamonds.git] / src / tape.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // tape.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "tape.h"
15 #include "init.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "files.h"
19 #include "network.h"
20 #include "anim.h"
21
22 #define DEBUG_TAPE_WHEN_PLAYING                 FALSE
23
24 // tape button identifiers
25 #define TAPE_CTRL_ID_EJECT                      0
26 #define TAPE_CTRL_ID_EXTRA                      1
27 #define TAPE_CTRL_ID_STOP                       2
28 #define TAPE_CTRL_ID_PAUSE                      3
29 #define TAPE_CTRL_ID_RECORD                     4
30 #define TAPE_CTRL_ID_PLAY                       5
31 #define TAPE_CTRL_ID_INSERT_SOLUTION            6
32 #define TAPE_CTRL_ID_PLAY_SOLUTION              7
33
34 #define NUM_TAPE_BUTTONS                        8
35
36 // values for tape handling
37 #define TAPE_PAUSE_SECONDS_BEFORE_DEATH         5
38 #define TAPE_MIN_SECONDS_FOR_UNDO_BUFFER        20
39
40 // forward declaration for internal use
41 static void HandleTapeButtons(struct GadgetInfo *);
42 static void TapeStopWarpForward(void);
43 static float GetTapeLengthSecondsFloat(void);
44 static void CopyTapeToUndoBuffer(void);
45
46 static struct GadgetInfo *tape_gadget[NUM_TAPE_BUTTONS];
47 static struct TapeInfo tape_undo_buffer;
48
49
50 // ============================================================================
51 // video tape definitions
52 // ============================================================================
53
54 #define VIDEO_INFO_OFF                  (VIDEO_STATE_DATE_OFF   |       \
55                                          VIDEO_STATE_TIME_OFF   |       \
56                                          VIDEO_STATE_FRAME_OFF)
57 #define VIDEO_STATE_OFF                 (VIDEO_STATE_PLAY_OFF   |       \
58                                          VIDEO_STATE_REC_OFF    |       \
59                                          VIDEO_STATE_PAUSE_OFF  |       \
60                                          VIDEO_STATE_FFWD_OFF   |       \
61                                          VIDEO_STATE_WARP_OFF   |       \
62                                          VIDEO_STATE_WARP2_OFF  |       \
63                                          VIDEO_STATE_PBEND_OFF  |       \
64                                          VIDEO_STATE_1STEP_OFF)
65 #define VIDEO_PRESS_OFF                 (VIDEO_PRESS_PLAY_OFF   |       \
66                                          VIDEO_PRESS_REC_OFF    |       \
67                                          VIDEO_PRESS_PAUSE_OFF  |       \
68                                          VIDEO_PRESS_STOP_OFF   |       \
69                                          VIDEO_PRESS_EJECT_OFF)
70 #define VIDEO_ALL_OFF                   (VIDEO_INFO_OFF         |       \
71                                          VIDEO_STATE_OFF        |       \
72                                          VIDEO_PRESS_OFF)
73
74 #define VIDEO_INFO_ON                   (VIDEO_STATE_DATE_ON    |       \
75                                          VIDEO_STATE_TIME_ON    |       \
76                                          VIDEO_STATE_FRAME_ON)
77 #define VIDEO_STATE_ON                  (VIDEO_STATE_PLAY_ON    |       \
78                                          VIDEO_STATE_REC_ON     |       \
79                                          VIDEO_STATE_PAUSE_ON   |       \
80                                          VIDEO_STATE_FFWD_ON    |       \
81                                          VIDEO_STATE_WARP_ON    |       \
82                                          VIDEO_STATE_WARP2_ON   |       \
83                                          VIDEO_STATE_PBEND_ON   |       \
84                                          VIDEO_STATE_1STEP_ON)
85 #define VIDEO_PRESS_ON                  (VIDEO_PRESS_PLAY_ON    |       \
86                                          VIDEO_PRESS_REC_ON     |       \
87                                          VIDEO_PRESS_PAUSE_ON   |       \
88                                          VIDEO_PRESS_STOP_ON    |       \
89                                          VIDEO_PRESS_EJECT_ON)
90 #define VIDEO_ALL_ON                    (VIDEO_INFO_ON          |       \
91                                          VIDEO_STATE_ON         |       \
92                                          VIDEO_PRESS_ON)
93
94 #define VIDEO_INFO                      (VIDEO_INFO_ON | VIDEO_INFO_OFF)
95 #define VIDEO_STATE                     (VIDEO_STATE_ON | VIDEO_STATE_OFF)
96 #define VIDEO_PRESS                     (VIDEO_PRESS_ON | VIDEO_PRESS_OFF)
97 #define VIDEO_ALL                       (VIDEO_ALL_ON | VIDEO_ALL_OFF)
98
99 #define NUM_TAPE_FUNCTIONS              11
100 #define NUM_TAPE_FUNCTION_PARTS         2
101 #define NUM_TAPE_FUNCTION_STATES        2
102
103
104 // ============================================================================
105 // video display functions
106 // ============================================================================
107
108 static void DrawVideoDisplay_Graphics(unsigned int state, unsigned int value)
109 {
110   int i, j, k;
111
112   static struct
113   {
114     int graphic;
115     struct XY *pos;
116   }
117   video_pos[NUM_TAPE_FUNCTIONS][NUM_TAPE_FUNCTION_PARTS] =
118   {
119     {
120       { IMG_GFX_TAPE_LABEL_PLAY,                &tape.label.play        },
121       { IMG_GFX_TAPE_SYMBOL_PLAY,               &tape.symbol.play       },
122     },
123     {
124       { IMG_GFX_TAPE_LABEL_RECORD,              &tape.label.record      },
125       { IMG_GFX_TAPE_SYMBOL_RECORD,             &tape.symbol.record     },
126     },
127     {
128       { IMG_GFX_TAPE_LABEL_PAUSE,               &tape.label.pause       },
129       { IMG_GFX_TAPE_SYMBOL_PAUSE,              &tape.symbol.pause      },
130     },
131     {
132       { IMG_GFX_TAPE_LABEL_DATE,                &tape.label.date        },
133       { -1,                                     NULL                    },
134     },
135     {
136       { IMG_GFX_TAPE_LABEL_TIME,                &tape.label.time        },
137       { -1,                                     NULL                    },
138     },
139     {
140       // (no label for displaying optional frame)
141       { -1,                                     NULL                    },
142       { -1,                                     NULL                    },
143     },
144     {
145       { IMG_GFX_TAPE_LABEL_FAST_FORWARD,        &tape.label.fast_forward  },
146       { IMG_GFX_TAPE_SYMBOL_FAST_FORWARD,       &tape.symbol.fast_forward },
147     },
148     {
149       { IMG_GFX_TAPE_LABEL_WARP_FORWARD,        &tape.label.warp_forward  },
150       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD,       &tape.symbol.warp_forward },
151     },
152     {
153       { IMG_GFX_TAPE_LABEL_WARP_FORWARD_BLIND,  &tape.label.warp_forward_blind},
154       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD_BLIND, &tape.symbol.warp_forward_blind},
155     },
156     {
157       { IMG_GFX_TAPE_LABEL_PAUSE_BEFORE_END,    &tape.label.pause_before_end  },
158       { IMG_GFX_TAPE_SYMBOL_PAUSE_BEFORE_END,   &tape.symbol.pause_before_end },
159     },
160     {
161       { IMG_GFX_TAPE_LABEL_SINGLE_STEP,         &tape.label.single_step  },
162       { IMG_GFX_TAPE_SYMBOL_SINGLE_STEP,        &tape.symbol.single_step },
163     },
164   };
165
166   for (k = 0; k < NUM_TAPE_FUNCTION_STATES; k++)        // on or off states
167   {
168     for (i = 0; i < NUM_TAPE_FUNCTIONS; i++)            // record, play, ...
169     {
170       for (j = 0; j < NUM_TAPE_FUNCTION_PARTS; j++)     // label or symbol
171       {
172         int graphic = video_pos[i][j].graphic;
173         struct XY *pos = video_pos[i][j].pos;
174
175         if (graphic == -1 ||
176             pos->x == -1 ||
177             pos->y == -1)
178           continue;
179
180         if (state & (1 << (i * 2 + k)))
181         {
182           struct GraphicInfo *gfx_bg = &graphic_info[IMG_BACKGROUND_TAPE];
183           struct GraphicInfo *gfx = &graphic_info[graphic];
184           Bitmap *gd_bitmap;
185           int gd_x, gd_y;
186           int skip_value =
187             (j == 0 ? VIDEO_DISPLAY_SYMBOL_ONLY : VIDEO_DISPLAY_LABEL_ONLY);
188
189           if (value == skip_value)
190             continue;
191
192           if (k == 1)           // on
193           {
194             gd_bitmap = gfx->bitmap;
195             gd_x = gfx->src_x;
196             gd_y = gfx->src_y;
197           }
198           else                  // off
199           {
200             gd_bitmap = gfx_bg->bitmap;
201             gd_x = gfx_bg->src_x + pos->x;
202             gd_y = gfx_bg->src_y + pos->y;
203           }
204
205           // some tape graphics may be undefined -- only draw if defined
206           if (gd_bitmap != NULL)
207             BlitBitmap(gd_bitmap, drawto, gd_x, gd_y, gfx->width, gfx->height,
208                        VX + pos->x, VY + pos->y);
209
210           redraw_mask |= REDRAW_DOOR_2;
211         }
212       }
213     }
214   }
215 }
216
217
218 #define DATETIME_NONE                   (0)
219
220 #define DATETIME_DATE_YYYY              (1 << 0)
221 #define DATETIME_DATE_YY                (1 << 1)
222 #define DATETIME_DATE_MON               (1 << 2)
223 #define DATETIME_DATE_MM                (1 << 3)
224 #define DATETIME_DATE_DD                (1 << 4)
225
226 #define DATETIME_TIME_HH                (1 << 5)
227 #define DATETIME_TIME_MIN               (1 << 6)
228 #define DATETIME_TIME_MM                (1 << 7)
229 #define DATETIME_TIME_SS                (1 << 8)
230
231 #define DATETIME_FRAME                  (1 << 9)
232
233 #define DATETIME_XOFFSET_1              (1 << 10)
234 #define DATETIME_XOFFSET_2              (1 << 11)
235
236 #define DATETIME_DATE                   (DATETIME_DATE_YYYY     |       \
237                                          DATETIME_DATE_YY       |       \
238                                          DATETIME_DATE_MON      |       \
239                                          DATETIME_DATE_MM       |       \
240                                          DATETIME_DATE_DD)
241
242 #define DATETIME_TIME                   (DATETIME_TIME_HH       |       \
243                                          DATETIME_TIME_MIN      |       \
244                                          DATETIME_TIME_MM       |       \
245                                          DATETIME_TIME_SS)
246
247 #define MAX_DATETIME_STRING_SIZE        32
248
249 static void DrawVideoDisplay_DateTime(unsigned int state, unsigned int value)
250 {
251   int i;
252
253   static char *month_shortnames[] =
254   {
255     "JAN",
256     "FEB",
257     "MAR",
258     "APR",
259     "MAY",
260     "JUN",
261     "JUL",
262     "AUG",
263     "SEP",
264     "OCT",
265     "NOV",
266     "DEC"
267   };
268
269   static struct
270   {
271     struct TextPosInfo *pos;
272     int type;
273   }
274   datetime_info[] =
275   {
276     { &tape.text.date,          DATETIME_DATE_DD                        },
277     { &tape.text.date,          DATETIME_DATE_MON | DATETIME_XOFFSET_1  },
278     { &tape.text.date,          DATETIME_DATE_YY  | DATETIME_XOFFSET_2  },
279     { &tape.text.date_yyyy,     DATETIME_DATE_YYYY                      },
280     { &tape.text.date_yy,       DATETIME_DATE_YY                        },
281     { &tape.text.date_mon,      DATETIME_DATE_MON                       },
282     { &tape.text.date_mm,       DATETIME_DATE_MM                        },
283     { &tape.text.date_dd,       DATETIME_DATE_DD                        },
284
285     { &tape.text.time,          DATETIME_TIME_MIN                       },
286     { &tape.text.time,          DATETIME_TIME_SS  | DATETIME_XOFFSET_1  },
287     { &tape.text.time_hh,       DATETIME_TIME_HH                        },
288     { &tape.text.time_mm,       DATETIME_TIME_MM                        },
289     { &tape.text.time_ss,       DATETIME_TIME_SS                        },
290
291     { &tape.text.frame,         DATETIME_FRAME                          },
292
293     { NULL,                     DATETIME_NONE                           },
294   };
295
296   for (i = 0; datetime_info[i].pos != NULL; i++)
297   {
298     struct TextPosInfo *pos = datetime_info[i].pos;
299     int type = datetime_info[i].type;
300     int xpos, ypos;
301
302     if (pos->x == -1 &&
303         pos->y == -1)
304       continue;
305
306     xpos = VX + pos->x + (type & DATETIME_XOFFSET_1 ? pos->xoffset  :
307                           type & DATETIME_XOFFSET_2 ? pos->xoffset2 : 0);
308     ypos = VY + pos->y;
309
310     if ((type & DATETIME_DATE) && (state & VIDEO_STATE_DATE_ON))
311     {
312       char s[MAX_DATETIME_STRING_SIZE];
313       int year2 = value / 10000;
314       int year4 = (year2 < 70 ? 2000 + year2 : 1900 + year2);
315       int month_index_raw = (value / 100) % 100;
316       int month_index = month_index_raw % 12;   // prevent invalid index
317       int month = month_index + 1;
318       int day = value % 100;
319
320       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
321                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
322                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
323                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
324                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
325
326       DrawText(xpos, ypos, s, pos->font);
327     }
328     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
329     {
330       char s[MAX_DATETIME_STRING_SIZE];
331       int hh = (value / 3600) % 100;
332       int min = value / 60;
333       int mm = (value / 60) % 60;
334       int ss = value % 60;
335
336       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
337                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
338                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
339                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
340
341       DrawText(xpos, ypos, s, pos->font);
342     }
343     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
344     {
345       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
346     }
347   }
348 }
349
350 void DrawVideoDisplay(unsigned int state, unsigned int value)
351 {
352   DrawVideoDisplay_Graphics(state, value);
353   DrawVideoDisplay_DateTime(state, value);
354 }
355
356 static void DrawVideoDisplayLabel(unsigned int state)
357 {
358   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
359 }
360
361 static void DrawVideoDisplaySymbol(unsigned int state)
362 {
363   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
364 }
365
366 static void DrawVideoDisplayCurrentState(void)
367 {
368   int state = 0;
369
370   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
371
372   if (tape.pausing)
373     state |= VIDEO_STATE_PAUSE_ON;
374
375   if (tape.recording)
376   {
377     state |= VIDEO_STATE_REC_ON;
378
379     if (tape.single_step)
380       state |= VIDEO_STATE_1STEP_ON;
381   }
382   else if (tape.playing)
383   {
384     state |= VIDEO_STATE_PLAY_ON;
385
386     if (!tape.pausing)
387     {
388       if (tape.deactivate_display)
389         state |= VIDEO_STATE_WARP2_ON;
390       else if (tape.warp_forward)
391         state |= VIDEO_STATE_WARP_ON;
392       else if (tape.fast_forward)
393         state |= VIDEO_STATE_FFWD_ON;
394
395       if (tape.pause_before_end)
396         state |= VIDEO_STATE_PBEND_ON;
397     }
398   }
399
400   // draw labels and symbols separately to prevent labels overlapping symbols
401   DrawVideoDisplayLabel(state);
402   DrawVideoDisplaySymbol(state);
403 }
404
405 void DrawCompleteVideoDisplay(void)
406 {
407   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
408
409   // draw tape background
410   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
411              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
412
413   // draw tape buttons (forced)
414   RedrawOrRemapTapeButtons();
415
416   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
417
418   if (tape.recording)
419   {
420     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
421     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
422     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
423     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
424
425     if (tape.pausing)
426       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
427   }
428   else if (tape.playing)
429   {
430     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
431     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
432     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
433     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
434
435     if (tape.pausing)
436       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
437   }
438   else if (tape.date && tape.length)
439   {
440     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
441     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
442     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
443   }
444
445   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
446              0, 0);
447 }
448
449 void TapeDeactivateDisplayOn(void)
450 {
451   SetDrawDeactivationMask(REDRAW_FIELD);
452   audio.sound_deactivated = TRUE;
453 }
454
455 void TapeDeactivateDisplayOff(boolean redraw_display)
456 {
457   SetDrawDeactivationMask(REDRAW_NONE);
458   audio.sound_deactivated = FALSE;
459
460   if (redraw_display)
461   {
462     RedrawPlayfield();
463
464     UpdateGameDoorValues();
465     DrawGameDoorValues();
466   }
467 }
468
469
470 // ============================================================================
471 // tape logging functions
472 // ============================================================================
473
474 struct AutoPlayInfo
475 {
476   LevelDirTree *leveldir;
477   boolean all_levelsets;
478   int last_level_nr;
479   int level_nr;
480   int num_levels_played;
481   int num_levels_solved;
482   int num_tapes_patched;
483   int num_tape_missing;
484   boolean level_failed[MAX_TAPES_PER_SET];
485   char *tape_filename;
486 };
487
488 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
489
490 static void PrintTapeReplayHeader(struct AutoPlayInfo *autoplay)
491 {
492   PrintLine("=", 79);
493
494   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
495     Print("Automatically fixing level tapes\n");
496   else if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
497     Print("Automatically uploading level tapes\n");
498   else
499     Print("Automatically playing level tapes\n");
500
501   PrintLine("-", 79);
502   Print("Level series identifier: '%s'\n", autoplay->leveldir->identifier);
503   Print("Level series name:       '%s'\n", autoplay->leveldir->name);
504   Print("Level series author:     '%s'\n", autoplay->leveldir->author);
505   Print("Number of levels:        %d\n",   autoplay->leveldir->levels);
506   PrintLine("=", 79);
507   Print("\n");
508
509   DrawInitTextItem(autoplay->leveldir->name);
510 }
511
512 static void PrintTapeReplayProgress(boolean replay_finished)
513 {
514   static unsigned int counter_last = -1;
515   unsigned int counter = Counter();
516   unsigned int counter_seconds  = counter / 1000;
517
518   if (!replay_finished)
519   {
520     unsigned int counter_delay = 50;
521
522     if (counter > counter_last + counter_delay)
523     {
524       PrintNoLog("\r");
525       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
526                  level_nr,  tape_patch_info,
527                  tape.length_seconds / 60, tape.length_seconds % 60,
528                  TapeTime / 60, TapeTime % 60);
529
530       counter_last = counter;
531     }
532   }
533   else
534   {
535     float tape_length_seconds = GetTapeLengthSecondsFloat();
536
537     PrintNoLog("\r");
538     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
539           level_nr, tape_patch_info,
540           tape.length_seconds / 60, tape.length_seconds % 60,
541           counter_seconds / 60, counter_seconds % 60, counter % 1000,
542           (float)counter / tape_length_seconds / 10,
543           tape.auto_play_level_fixed ? "solved and fixed" :
544           tape.auto_play_level_solved ? "solved" :
545           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
546           "NOT SOLVED");
547
548     counter_last = -1;
549   }
550 }
551
552 static void PrintTapeReplaySummary(struct AutoPlayInfo *autoplay)
553 {
554   char *autoplay_status =
555     (autoplay->num_levels_played == autoplay->num_levels_solved &&
556      autoplay->num_levels_played > 0 ? " OK " : "WARN");
557   int autoplay_percent =
558     (autoplay->num_levels_played ?
559      autoplay->num_levels_solved * 100 / autoplay->num_levels_played : 0);
560   int i;
561
562   Print("\n");
563   PrintLine("=", 79);
564   Print("Number of levels played: %d\n", autoplay->num_levels_played);
565   Print("Number of levels solved: %d (%d%%)\n", autoplay->num_levels_solved,
566         (autoplay->num_levels_played ?
567          autoplay->num_levels_solved * 100 / autoplay->num_levels_played : 0));
568   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
569     Print("Number of tapes fixed: %d\n", autoplay->num_tapes_patched);
570   PrintLine("-", 79);
571   Print("Summary (for automatic parsing by scripts):\n");
572
573   if (autoplay->tape_filename)
574   {
575     Print("TAPEFILE [%s] '%s', %d, %d, %d",
576           autoplay_status,
577           autoplay->leveldir->identifier,
578           autoplay->last_level_nr,
579           game.score_final,
580           game.score_time_final);
581   }
582   else
583   {
584     Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
585           autoplay_status,
586           autoplay->leveldir->identifier,
587           autoplay->num_levels_solved,
588           autoplay->num_levels_played,
589           autoplay_percent);
590
591     if (autoplay->num_levels_played != autoplay->num_levels_solved)
592     {
593       Print(", FAILED:");
594       for (i = 0; i < MAX_TAPES_PER_SET; i++)
595         if (autoplay->level_failed[i])
596           Print(" %03d", i);
597     }
598   }
599
600   Print("\n");
601   PrintLine("=", 79);
602 }
603
604 static FILE *tape_log_file;
605
606 static void OpenTapeLogfile(void)
607 {
608   if (!(tape_log_file = fopen(options.tape_log_filename, MODE_WRITE)))
609     Warn("cannot write tape logfile '%s'", options.tape_log_filename);
610 }
611
612 static void WriteTapeLogfile(byte action[MAX_TAPE_ACTIONS])
613 {
614   int i;
615
616   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
617     putFile8Bit(tape_log_file, action[i]);
618 }
619
620 static void CloseTapeLogfile(void)
621 {
622   fclose(tape_log_file);
623 }
624
625
626 // ============================================================================
627 // tape control functions
628 // ============================================================================
629
630 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
631 {
632   struct tm *lt = localtime(&epoch_seconds);
633
634   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
635 }
636
637 void TapeSetDateFromNow(void)
638 {
639   TapeSetDateFromEpochSeconds(time(NULL));
640 }
641
642 void TapeErase(void)
643 {
644   int i;
645
646   CopyTapeToUndoBuffer();
647
648   tape.counter = 0;
649   tape.length = 0;
650   tape.length_frames = 0;
651   tape.length_seconds = 0;
652
653   tape.score_tape_basename[0] = '\0';
654
655   if (leveldir_current)
656   {
657     strncpy(tape.level_identifier, leveldir_current->identifier,
658             MAX_FILENAME_LEN);
659     tape.level_identifier[MAX_FILENAME_LEN] = '\0';
660   }
661
662   tape.level_nr = level_nr;
663   tape.pos[tape.counter].delay = 0;
664   tape.changed = TRUE;
665
666   tape.random_seed = InitRND(level.random_seed);
667
668   tape.file_version = FILE_VERSION_ACTUAL;
669   tape.game_version = GAME_VERSION_ACTUAL;
670   tape.engine_version = level.game_version;
671
672   tape.property_bits = TAPE_PROPERTY_NONE;
673
674   TapeSetDateFromNow();
675
676   for (i = 0; i < MAX_PLAYERS; i++)
677     tape.player_participates[i] = FALSE;
678
679   tape.centered_player_nr_next = -1;
680   tape.set_centered_player = FALSE;
681
682   // set flags for game actions to default values (may be overwritten later)
683   tape.use_key_actions = TRUE;
684   tape.use_mouse_actions = FALSE;
685 }
686
687 static void TapeRewind(void)
688 {
689   tape.counter = 0;
690   tape.delay_played = 0;
691   tape.pause_before_end = FALSE;
692   tape.recording = FALSE;
693   tape.playing = FALSE;
694   tape.fast_forward = FALSE;
695   tape.warp_forward = FALSE;
696   tape.deactivate_display = FALSE;
697   tape.auto_play = (global.autoplay_leveldir != NULL);
698   tape.auto_play_level_solved = FALSE;
699   tape.auto_play_level_fixed = FALSE;
700   tape.auto_play_level_not_fixable = FALSE;
701   tape.quick_resume = FALSE;
702   tape.single_step = FALSE;
703
704   tape.centered_player_nr_next = -1;
705   tape.set_centered_player = FALSE;
706
707   InitRND(tape.random_seed);
708 }
709
710 static void TapeSetRandomSeed(int random_seed)
711 {
712   tape.random_seed = InitRND(random_seed);
713 }
714
715 void TapeStartRecording(int random_seed)
716 {
717   if (!TAPE_IS_STOPPED(tape))
718     TapeStop();
719
720   TapeErase();
721   TapeRewind();
722   TapeSetRandomSeed(random_seed);
723
724   tape.recording = TRUE;
725
726   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
727   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
728   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
729   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
730
731   MapTapeWarpButton();
732
733   SetDrawDeactivationMask(REDRAW_NONE);
734   audio.sound_deactivated = FALSE;
735
736   // required here to update video display if tape door is closed
737   if (GetDoorState() & DOOR_CLOSE_2)
738     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
739 }
740
741 static void TapeStartGameRecording(void)
742 {
743   StartGameActions(network.enabled, TRUE, level.random_seed);
744 }
745
746 static void TapeAppendRecording(void)
747 {
748   if (!tape.playing || !tape.pausing)
749     return;
750
751   // stop playing
752   tape.playing = FALSE;
753   tape.fast_forward = FALSE;
754   tape.warp_forward = FALSE;
755   tape.pause_before_end = FALSE;
756   tape.deactivate_display = FALSE;
757
758   // start recording
759   tape.recording = TRUE;
760   tape.changed = TRUE;
761
762   // set current delay (for last played move)
763   tape.pos[tape.counter].delay = tape.delay_played;
764
765   tape.property_bits |= TAPE_PROPERTY_REPLAYED;
766
767   // set current date
768   TapeSetDateFromNow();
769
770   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
771   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
772
773   UpdateAndDisplayGameControlValues();
774 }
775
776 void TapeHaltRecording(void)
777 {
778   tape.counter++;
779
780   // initialize delay for next tape entry (to be able to continue recording)
781   if (tape.counter < MAX_TAPE_LEN)
782     tape.pos[tape.counter].delay = 0;
783
784   tape.length = tape.counter;
785   tape.length_frames = GetTapeLengthFrames();
786   tape.length_seconds = GetTapeLengthSeconds();
787 }
788
789 void TapeStopRecording(void)
790 {
791   if (tape.recording)
792     TapeHaltRecording();
793
794   tape.recording = FALSE;
795   tape.pausing = FALSE;
796
797   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
798   MapTapeEjectButton();
799 }
800
801 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
802 {
803   int i;
804
805   if (tape.pos[tape.counter].delay > 0)         // already stored action
806   {
807     boolean changed_events = FALSE;
808
809     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
810       if (tape.pos[tape.counter].action[i] != action[i])
811         changed_events = TRUE;
812
813     if (changed_events || tape.pos[tape.counter].delay >= 255)
814     {
815       if (tape.counter >= MAX_TAPE_LEN - 1)
816         return FALSE;
817
818       tape.counter++;
819       tape.pos[tape.counter].delay = 0;
820     }
821     else
822       tape.pos[tape.counter].delay++;
823   }
824
825   if (tape.pos[tape.counter].delay == 0)        // store new action
826   {
827     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
828       tape.pos[tape.counter].action[i] = action[i];
829
830     tape.pos[tape.counter].delay++;
831   }
832
833   return TRUE;
834 }
835
836 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
837 {
838   byte action[MAX_TAPE_ACTIONS];
839   int i;
840
841   if (!tape.recording)          // (record action even when tape is paused)
842     return;
843
844   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
845     action[i] = action_raw[i];
846
847   if (tape.use_key_actions && tape.set_centered_player)
848   {
849     for (i = 0; i < MAX_PLAYERS; i++)
850       if (tape.centered_player_nr_next == i ||
851           tape.centered_player_nr_next == -1)
852         action[i] |= KEY_SET_FOCUS;
853
854     tape.set_centered_player = FALSE;
855   }
856
857   if (GameFrameDelay != GAME_FRAME_DELAY)
858     tape.property_bits |= TAPE_PROPERTY_GAME_SPEED;
859
860   if (setup.small_game_graphics || SCR_FIELDX >= 2 * SCR_FIELDX_DEFAULT)
861     tape.property_bits |= TAPE_PROPERTY_SMALL_GRAPHICS;
862
863   if (!TapeAddAction(action))
864     TapeStopRecording();
865 }
866
867 void TapeTogglePause(boolean toggle_mode)
868 {
869   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
870   {
871     // continue playing in normal mode
872     tape.fast_forward = FALSE;
873     tape.warp_forward = FALSE;
874     tape.deactivate_display = FALSE;
875
876     tape.pause_before_end = FALSE;
877   }
878
879   tape.pausing = !tape.pausing;
880
881   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
882     tape.single_step = FALSE;
883
884   if (tape.single_step)
885     tape.property_bits |= TAPE_PROPERTY_SINGLE_STEP;
886
887   if (tape.pausing)
888     tape.property_bits |= TAPE_PROPERTY_PAUSE_MODE;
889
890   DrawVideoDisplayCurrentState();
891
892   if (tape.deactivate_display)
893   {
894     if (tape.pausing)
895       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
896     else
897       TapeDeactivateDisplayOn();
898   }
899
900   if (tape.quick_resume)
901   {
902     tape.quick_resume = FALSE;
903
904     TapeStopWarpForward();
905     TapeAppendRecording();
906
907     if (!CheckEngineSnapshotSingle())
908       SaveEngineSnapshotSingle();
909
910     // restart step/move snapshots after quick loading tape
911     SaveEngineSnapshotToListInitial();
912
913     // do not map undo/redo buttons after quick loading tape
914     return;
915   }
916
917   if (game_status == GAME_MODE_PLAYING)
918   {
919     if (setup.show_load_save_buttons &&
920         setup.show_undo_redo_buttons &&
921         CheckEngineSnapshotList())
922     {
923       if (tape.pausing)
924         MapUndoRedoButtons();
925       else if (!tape.single_step)
926         MapLoadSaveButtons();
927     }
928
929     ModifyPauseButtons();
930   }
931 }
932
933 void TapeStartPlaying(void)
934 {
935   if (TAPE_IS_EMPTY(tape))
936     return;
937
938   if (!TAPE_IS_STOPPED(tape))
939     TapeStop();
940
941   TapeRewind();
942
943   tape.playing = TRUE;
944
945   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
946   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
947   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
948   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
949
950   MapTapeWarpButton();
951
952   SetDrawDeactivationMask(REDRAW_NONE);
953   audio.sound_deactivated = FALSE;
954 }
955
956 static void TapeStartGamePlaying(void)
957 {
958   TapeStartPlaying();
959
960   InitGame();
961 }
962
963 void TapeStopPlaying(void)
964 {
965   tape.playing = FALSE;
966   tape.pausing = FALSE;
967
968   if (tape.warp_forward)
969     TapeStopWarpForward();
970
971   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
972   MapTapeEjectButton();
973 }
974
975 byte *TapePlayAction(void)
976 {
977   int update_delay = FRAMES_PER_SECOND / 2;
978   boolean update_video_display = (FrameCounter % update_delay == 0);
979   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
980   static byte action[MAX_TAPE_ACTIONS];
981   int i;
982
983   if (!tape.playing || tape.pausing)
984     return NULL;
985
986   if (tape.pause_before_end)  // stop some seconds before end of tape
987   {
988     if (TapeTime > (int)tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
989     {
990       TapeStopWarpForward();
991       TapeTogglePause(TAPE_TOGGLE_MANUAL);
992
993       return NULL;
994     }
995   }
996
997   if (tape.counter >= tape.length)      // end of tape reached
998   {
999     if (tape.warp_forward && !tape.auto_play)
1000     {
1001       TapeStopWarpForward();
1002       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1003     }
1004     else
1005     {
1006       TapeStop();
1007     }
1008
1009     return NULL;
1010   }
1011
1012   if (update_video_display && !tape.deactivate_display)
1013   {
1014     int state = 0;
1015
1016     if (tape.warp_forward)
1017       state |= VIDEO_STATE_WARP(update_draw_label_on);
1018     else if (tape.fast_forward)
1019       state |= VIDEO_STATE_FFWD(update_draw_label_on);
1020
1021     if (tape.pause_before_end)
1022       state |= VIDEO_STATE_PBEND(update_draw_label_on);
1023
1024     // draw labels and symbols separately to prevent labels overlapping symbols
1025     DrawVideoDisplayLabel(state);
1026     DrawVideoDisplaySymbol(state);
1027   }
1028
1029   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1030     action[i] = tape.pos[tape.counter].action[i];
1031
1032 #if DEBUG_TAPE_WHEN_PLAYING
1033   DebugContinued("", "%05d", FrameCounter);
1034   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1035     DebugContinued("", "   %08x", action[i]);
1036   DebugContinued("tape:play", "\n");
1037 #endif
1038
1039   tape.set_centered_player = FALSE;
1040   tape.centered_player_nr_next = -999;
1041
1042   if (tape.use_key_actions)
1043   {
1044     for (i = 0; i < MAX_PLAYERS; i++)
1045     {
1046       if (action[i] & KEY_SET_FOCUS)
1047       {
1048         tape.set_centered_player = TRUE;
1049         tape.centered_player_nr_next =
1050           (tape.centered_player_nr_next == -999 ? i : -1);
1051       }
1052
1053       action[i] &= ~KEY_SET_FOCUS;
1054     }
1055   }
1056
1057   tape.delay_played++;
1058   if (tape.delay_played >= tape.pos[tape.counter].delay)
1059   {
1060     tape.counter++;
1061     tape.delay_played = 0;
1062   }
1063
1064   if (tape.auto_play)
1065     PrintTapeReplayProgress(FALSE);
1066
1067   if (options.tape_log_filename != NULL)
1068     WriteTapeLogfile(action);
1069
1070   return action;
1071 }
1072
1073 void TapeStop(void)
1074 {
1075   if (tape.pausing)
1076     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1077
1078   TapeStopRecording();
1079   TapeStopPlaying();
1080
1081   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
1082
1083   if (tape.date && tape.length)
1084   {
1085     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
1086     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
1087     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
1088   }
1089 }
1090
1091 static void TapeStopGameOrTape(boolean stop_game)
1092 {
1093   if (!tape.playing && stop_game)
1094     RequestQuitGame(FALSE);
1095   else
1096     TapeStop();
1097 }
1098
1099 void TapeStopGame(void)
1100 {
1101   if (game_status == GAME_MODE_MAIN)
1102     return;
1103
1104   TapeStopGameOrTape(TRUE);
1105 }
1106
1107 void TapeStopTape(void)
1108 {
1109   TapeStopGameOrTape(FALSE);
1110 }
1111
1112 unsigned int GetTapeLengthFrames(void)
1113 {
1114   unsigned int tape_length_frames = 0;
1115   int i;
1116
1117   if (TAPE_IS_EMPTY(tape))
1118     return 0;
1119
1120   for (i = 0; i < tape.length; i++)
1121     tape_length_frames += tape.pos[i].delay;
1122
1123   return tape_length_frames;
1124 }
1125
1126 unsigned int GetTapeLengthSeconds(void)
1127 {
1128   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1129 }
1130
1131 static float GetTapeLengthSecondsFloat(void)
1132 {
1133   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1134 }
1135
1136 static void TapeStartWarpForward(int mode)
1137 {
1138   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1139   tape.warp_forward = (mode & AUTOPLAY_WARP);
1140   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1141
1142   tape.pausing = FALSE;
1143
1144   if (tape.deactivate_display)
1145     TapeDeactivateDisplayOn();
1146
1147   DrawVideoDisplayCurrentState();
1148 }
1149
1150 static void TapeStopWarpForward(void)
1151 {
1152   tape.fast_forward = FALSE;
1153   tape.warp_forward = FALSE;
1154   tape.deactivate_display = FALSE;
1155
1156   tape.pause_before_end = FALSE;
1157
1158   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1159
1160   DrawVideoDisplayCurrentState();
1161 }
1162
1163 static void TapeSingleStep(void)
1164 {
1165   if (network.enabled)
1166     return;
1167
1168   if (!tape.pausing)
1169     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1170
1171   tape.single_step = !tape.single_step;
1172
1173   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1174 }
1175
1176 void TapeQuickSave(void)
1177 {
1178   if (game_status == GAME_MODE_MAIN)
1179   {
1180     Request("No game that can be saved!", REQ_CONFIRM);
1181
1182     return;
1183   }
1184
1185   if (game_status != GAME_MODE_PLAYING)
1186     return;
1187
1188   if (tape.recording)
1189     TapeHaltRecording();        // prepare tape for saving on-the-fly
1190
1191   if (TAPE_IS_EMPTY(tape))
1192   {
1193     Request("No tape that can be saved!", REQ_CONFIRM);
1194
1195     return;
1196   }
1197
1198   tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1199
1200   if (SaveTapeChecked(tape.level_nr))
1201     SaveEngineSnapshotSingle();
1202 }
1203
1204 void TapeQuickLoad(void)
1205 {
1206   char *filename = getTapeFilename(level_nr);
1207
1208   if (!fileExists(filename))
1209   {
1210     Request("No tape for this level!", REQ_CONFIRM);
1211
1212     return;
1213   }
1214
1215   if (tape.recording && !Request("Stop recording and load tape?",
1216                                  REQ_ASK | REQ_STAY_CLOSED))
1217   {
1218     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1219
1220     return;
1221   }
1222
1223   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1224     return;
1225
1226   if (CheckEngineSnapshotSingle())
1227   {
1228     TapeStartGamePlaying();
1229
1230     LoadEngineSnapshotSingle();
1231
1232     DrawCompleteVideoDisplay();
1233
1234     tape.playing = TRUE;
1235     tape.pausing = TRUE;
1236
1237     TapeStopWarpForward();
1238     TapeAppendRecording();
1239
1240     // restart step/move snapshots after quick loading tape
1241     SaveEngineSnapshotToListInitial();
1242
1243     if (FrameCounter > 0)
1244       return;
1245   }
1246
1247   TapeStop();
1248   TapeErase();
1249
1250   LoadTape(level_nr);
1251
1252   if (!TAPE_IS_EMPTY(tape))
1253   {
1254     TapeStartGamePlaying();
1255     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1256
1257     tape.quick_resume = TRUE;
1258     tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1259   }
1260   else  // this should not happen (basically checked above)
1261   {
1262     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1263
1264     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1265   }
1266 }
1267
1268 static boolean checkRestartGame(char *message)
1269 {
1270   if (game_status == GAME_MODE_MAIN)
1271     return TRUE;
1272
1273   if (!hasStartedNetworkGame())
1274     return FALSE;
1275
1276   if (level_editor_test_game)
1277     return TRUE;
1278
1279   if (game.all_players_gone)
1280     return TRUE;
1281
1282   if (!setup.ask_on_quit_game)
1283     return TRUE;
1284
1285   if (Request(message, REQ_ASK | REQ_STAY_CLOSED))
1286     return TRUE;
1287
1288   OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1289
1290   return FALSE;
1291 }
1292
1293 void TapeRestartGame(void)
1294 {
1295   if (!checkRestartGame("Restart game?"))
1296     return;
1297
1298   StartGameActions(network.enabled, setup.autorecord, level.random_seed);
1299 }
1300
1301 void TapeReplayAndPauseBeforeEnd(void)
1302 {
1303   if (TAPE_IS_EMPTY(tape) && !tape.recording)
1304   {
1305     Request("No tape for this level!", REQ_CONFIRM);
1306
1307     return;
1308   }
1309
1310   if (!checkRestartGame("Replay game and pause before end?"))
1311     return;
1312
1313   TapeStop();
1314   TapeStartGamePlaying();
1315   TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1316
1317   tape.pause_before_end = TRUE;
1318   tape.quick_resume = TRUE;
1319 }
1320
1321 boolean hasSolutionTape(void)
1322 {
1323   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1324   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1325                             level.native_sp_level->demo.is_available);
1326
1327   return (tape_file_exists || level_has_tape);
1328 }
1329
1330 boolean InsertSolutionTape(void)
1331 {
1332   if (!hasSolutionTape())
1333   {
1334     Request("No solution tape for this level!", REQ_CONFIRM);
1335
1336     return FALSE;
1337   }
1338
1339   if (!TAPE_IS_STOPPED(tape))
1340     TapeStop();
1341
1342   // if tape recorder already contains a tape, remove it without asking
1343   TapeErase();
1344
1345   LoadSolutionTape(level_nr);
1346
1347   DrawCompleteVideoDisplay();
1348
1349   if (TAPE_IS_EMPTY(tape))
1350   {
1351     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1352
1353     return FALSE;
1354   }
1355
1356   return TRUE;
1357 }
1358
1359 boolean PlaySolutionTape(void)
1360 {
1361   if (!InsertSolutionTape())
1362     return FALSE;
1363
1364   TapeStartGamePlaying();
1365
1366   return TRUE;
1367 }
1368
1369 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1370 {
1371   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1372           t1->level_nr == t2->level_nr);
1373 }
1374
1375 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1376 {
1377   *tape_to = *tape_from;
1378 }
1379
1380 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1381 {
1382   struct TapeInfo tmp = *t1;
1383
1384   *t1 = *t2;
1385   *t2 = tmp;
1386 }
1387
1388 static void CopyTapeToUndoBuffer(void)
1389 {
1390   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1391   // or if the last undo tape is from a different level set or level number
1392   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1393       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1394       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1395   {
1396     CopyTape(&tape, &tape_undo_buffer);
1397   }
1398 }
1399
1400 void UndoTape(void)
1401 {
1402   // only undo tapes from same level set and with same level number
1403   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1404     return;
1405
1406   if (!TAPE_IS_STOPPED(tape))
1407     TapeStop();
1408
1409   // swap last recorded tape with undo buffer, so undo can be reversed
1410   SwapTapes(&tape, &tape_undo_buffer);
1411
1412   DrawCompleteVideoDisplay();
1413 }
1414
1415 void FixTape_ForceSinglePlayer(void)
1416 {
1417   int i;
1418
1419   /* fix single-player tapes that contain player input for more than one
1420      player (due to a bug in 3.3.1.2 and earlier versions), which results
1421      in playing levels with more than one player in multi-player mode,
1422      even though the tape was originally recorded in single-player mode */
1423
1424   // remove player input actions for all players but the first one
1425   for (i = 1; i < MAX_PLAYERS; i++)
1426     tape.player_participates[i] = FALSE;
1427
1428   tape.changed = TRUE;
1429 }
1430
1431
1432 // ----------------------------------------------------------------------------
1433 // tape autoplay functions
1434 // ----------------------------------------------------------------------------
1435
1436 static TreeInfo *getNextValidAutoPlayEntry(TreeInfo *node)
1437 {
1438   node = getNextValidTreeInfoEntry(node);
1439
1440   while (node && node->is_copy)
1441     node = getNextValidTreeInfoEntry(node);
1442
1443   return node;
1444 }
1445
1446 static TreeInfo *getFirstValidAutoPlayEntry(TreeInfo *node)
1447 {
1448   node = getFirstValidTreeInfoEntry(node);
1449
1450   if (node && node->is_copy)
1451     return getNextValidAutoPlayEntry(node);
1452
1453   return node;
1454 }
1455
1456 static void AutoPlayTapes_SetScoreEntry(int score, int time)
1457 {
1458   char *name = (options.mytapes ? setup.player_name : options.player_name);
1459
1460   // set unique basename for score tape (for uploading to score server)
1461   strcpy(tape.score_tape_basename, getScoreTapeBasename(name));
1462
1463   // store score in first score entry
1464   scores.last_added = 0;
1465
1466   struct ScoreEntry *entry = &scores.entry[scores.last_added];
1467
1468   strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1469   strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1470
1471   entry->score = score;
1472   entry->time = time;
1473
1474   PrintNoLog("- uploading score tape to score server ... ");
1475
1476   server_scores.uploaded = FALSE;
1477 }
1478
1479 static boolean AutoPlayTapes_WaitForUpload(void)
1480 {
1481   unsigned int upload_delay = 0;
1482   unsigned int upload_delay_value = 10000;
1483
1484   ResetDelayCounter(&upload_delay);
1485
1486   // wait for score tape to be successfully uploaded (and fail on timeout)
1487   while (!server_scores.uploaded)
1488   {
1489     if (DelayReached(&upload_delay, upload_delay_value))
1490     {
1491       PrintNoLog("\r");
1492       Print("- uploading score tape to score server - TIMEOUT.\n");
1493
1494       if (program.headless)
1495         Fail("cannot upload score tape to score server");
1496
1497       return FALSE;
1498     }
1499
1500     UPDATE_BUSY_STATE();
1501
1502     Delay(20);
1503   }
1504
1505   PrintNoLog("\r");
1506   Print("- uploading score tape to score server - uploaded.\n");
1507
1508   return TRUE;
1509 }
1510
1511 static int AutoPlayTapesExt(boolean initialize)
1512 {
1513   static struct AutoPlayInfo autoplay;
1514   static int num_tapes = 0;
1515   static int patch_nr = 0;
1516   static char *patch_name[] =
1517   {
1518     "original tape",
1519     "em_random_bug",
1520     "screen_34x34",
1521
1522     NULL
1523   };
1524   static int patch_version_first[] =
1525   {
1526     VERSION_IDENT(0,0,0,0),
1527     VERSION_IDENT(3,3,1,0),
1528     VERSION_IDENT(0,0,0,0),
1529
1530     -1
1531   };
1532   static int patch_version_last[] =
1533   {
1534     VERSION_IDENT(9,9,9,9),
1535     VERSION_IDENT(4,0,1,1),
1536     VERSION_IDENT(4,2,2,0),
1537
1538     -1
1539   };
1540   static byte patch_property_bit[] =
1541   {
1542     TAPE_PROPERTY_NONE,
1543     TAPE_PROPERTY_EM_RANDOM_BUG,
1544     TAPE_PROPERTY_NONE,
1545
1546     -1
1547   };
1548   LevelDirTree *leveldir_current_last = leveldir_current;
1549   boolean init_level_set = FALSE;
1550   int level_nr_last = level_nr;
1551   int i;
1552
1553   if (!initialize)
1554   {
1555     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1556     {
1557       if (tape.auto_play_level_solved)
1558       {
1559         if (patch_nr > 0)
1560         {
1561           // level solved by patched tape -- save fixed tape
1562           char *filename = getTapeFilename(level_nr);
1563           char *filename_orig = getStringCat2(filename, ".orig");
1564
1565           // create backup from old tape, if not yet existing
1566           if (!fileExists(filename_orig))
1567             rename(filename, filename_orig);
1568
1569           SaveTapeToFilename(filename);
1570
1571           tape.auto_play_level_fixed = TRUE;
1572           autoplay.num_tapes_patched++;
1573         }
1574
1575         // continue with next tape
1576         patch_nr = 0;
1577       }
1578       else if (patch_name[patch_nr + 1] != NULL)
1579       {
1580         // level not solved by patched tape -- continue with next patch
1581         patch_nr++;
1582       }
1583       else
1584       {
1585         // level not solved by any patched tape -- continue with next tape
1586         tape.auto_play_level_not_fixable = TRUE;
1587         patch_nr = 0;
1588       }
1589     }
1590
1591     // just finished auto-playing tape
1592     PrintTapeReplayProgress(TRUE);
1593
1594     if (options.tape_log_filename != NULL)
1595       CloseTapeLogfile();
1596
1597     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1598         tape.auto_play_level_solved)
1599     {
1600       AutoPlayTapes_SetScoreEntry(game.score_final, game.score_time_final);
1601
1602       if (leveldir_current)
1603       {
1604         // the tape's level set identifier may differ from current level set
1605         strncpy(tape.level_identifier, leveldir_current->identifier,
1606                 MAX_FILENAME_LEN);
1607         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1608
1609         // the tape's level number may differ from current level number
1610         tape.level_nr = level_nr;
1611       }
1612
1613       // save score tape to upload to server; may be required for some reasons:
1614       // * level set identifier in solution tapes may differ from level set
1615       // * level set identifier is missing (old-style tape without INFO chunk)
1616       // * solution tape may have native format (like Supaplex solution files)
1617
1618       SaveScoreTape(level_nr);
1619       SaveServerScore(level_nr, TRUE);
1620
1621       AutoPlayTapes_WaitForUpload();
1622     }
1623
1624     if (patch_nr == 0)
1625       autoplay.num_levels_played++;
1626
1627     if (tape.auto_play_level_solved)
1628       autoplay.num_levels_solved++;
1629
1630     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1631       autoplay.level_failed[level_nr] = !tape.auto_play_level_solved;
1632   }
1633   else
1634   {
1635     if (strEqual(global.autoplay_leveldir, "ALL"))
1636     {
1637       autoplay.all_levelsets = TRUE;
1638
1639       // tape mass-uploading only allowed for private tapes
1640       if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1641         options.mytapes = TRUE;
1642     }
1643
1644     if ((global.autoplay_mode == AUTOPLAY_MODE_SAVE ||
1645          global.autoplay_mode == AUTOPLAY_MODE_UPLOAD) &&
1646         !options.mytapes &&
1647         options.player_name == NULL)
1648     {
1649       Fail("specify player name when uploading solution tapes");
1650     }
1651
1652     if (global.autoplay_mode != AUTOPLAY_MODE_UPLOAD)
1653       DrawCompleteVideoDisplay();
1654
1655     if (program.headless)
1656     {
1657       audio.sound_enabled = FALSE;
1658       setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1659     }
1660
1661     if (strSuffix(global.autoplay_leveldir, ".tape"))
1662     {
1663       autoplay.tape_filename = global.autoplay_leveldir;
1664
1665       if (!fileExists(autoplay.tape_filename))
1666         Fail("tape file '%s' does not exist", autoplay.tape_filename);
1667
1668       LoadTapeFromFilename(autoplay.tape_filename);
1669
1670       if (tape.no_valid_file)
1671         Fail("cannot load tape file '%s'", autoplay.tape_filename);
1672
1673       if (tape.no_info_chunk && !options.identifier)
1674         Fail("cannot get levelset from tape file '%s'", autoplay.tape_filename);
1675
1676       if (tape.no_info_chunk && !options.level_nr)
1677         Fail("cannot get level nr from tape file '%s'", autoplay.tape_filename);
1678
1679       global.autoplay_leveldir = tape.level_identifier;
1680
1681       if (options.identifier != NULL)
1682         global.autoplay_leveldir = options.identifier;
1683
1684       if (options.level_nr != NULL)
1685         tape.level_nr = atoi(options.level_nr);
1686
1687       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1688         global.autoplay_level[tape.level_nr] = TRUE;
1689
1690       global.autoplay_all = FALSE;
1691       options.mytapes = FALSE;
1692     }
1693
1694     if (autoplay.all_levelsets)
1695     {
1696       // start auto-playing first level set
1697       autoplay.leveldir = getFirstValidAutoPlayEntry(leveldir_first);
1698     }
1699     else
1700     {
1701       // auto-play selected level set
1702       autoplay.leveldir = getTreeInfoFromIdentifier(leveldir_first,
1703                                                     global.autoplay_leveldir);
1704     }
1705
1706     if (autoplay.leveldir == NULL)
1707       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1708
1709     // only private tapes may be modified
1710     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1711       options.mytapes = TRUE;
1712
1713     // set timestamp for batch tape upload
1714     global.autoplay_time = time(NULL);
1715
1716     num_tapes = 0;
1717
1718     init_level_set = TRUE;
1719   }
1720
1721   while (1)
1722   {
1723     if (init_level_set)
1724     {
1725       leveldir_current = autoplay.leveldir;
1726
1727       if (autoplay.leveldir->first_level < 0)
1728         autoplay.leveldir->first_level = 0;
1729       if (autoplay.leveldir->last_level >= MAX_TAPES_PER_SET)
1730         autoplay.leveldir->last_level = MAX_TAPES_PER_SET - 1;
1731
1732       autoplay.level_nr = autoplay.leveldir->first_level;
1733
1734       autoplay.num_levels_played = 0;
1735       autoplay.num_levels_solved = 0;
1736       autoplay.num_tapes_patched = 0;
1737       autoplay.num_tape_missing = 0;
1738
1739       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1740         autoplay.level_failed[i] = FALSE;
1741
1742       PrintTapeReplayHeader(&autoplay);
1743
1744       init_level_set = FALSE;
1745     }
1746
1747     if (autoplay.all_levelsets && global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1748     {
1749       boolean skip_levelset = FALSE;
1750
1751       if (!directoryExists(getTapeDir(autoplay.leveldir->subdir)))
1752       {
1753         Print("No tape directory for this level set found -- skipping.\n");
1754
1755         skip_levelset = TRUE;
1756       }
1757
1758       if (CheckTapeDirectoryUploadsComplete(autoplay.leveldir->subdir))
1759       {
1760         Print("All tapes for this level set already uploaded -- skipping.\n");
1761
1762         skip_levelset = TRUE;
1763       }
1764
1765       if (skip_levelset)
1766       {
1767         PrintTapeReplaySummary(&autoplay);
1768
1769         // continue with next level set
1770         autoplay.leveldir = getNextValidAutoPlayEntry(autoplay.leveldir);
1771
1772         // all level sets processed
1773         if (autoplay.leveldir == NULL)
1774           break;
1775
1776         init_level_set = TRUE;
1777
1778         continue;
1779       }
1780     }
1781
1782     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1783       level_nr = autoplay.level_nr++;
1784
1785     UPDATE_BUSY_STATE();
1786
1787     // check if all tapes for this level set have been processed
1788     if (level_nr > autoplay.leveldir->last_level)
1789     {
1790       PrintTapeReplaySummary(&autoplay);
1791
1792       if (!autoplay.all_levelsets)
1793         break;
1794
1795       if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1796         MarkTapeDirectoryUploadsAsComplete(autoplay.leveldir->subdir);
1797
1798       // continue with next level set
1799       autoplay.leveldir = getNextValidAutoPlayEntry(autoplay.leveldir);
1800
1801       // all level sets processed
1802       if (autoplay.leveldir == NULL)
1803         break;
1804
1805       init_level_set = TRUE;
1806
1807       continue;
1808     }
1809
1810     // set patch info (required for progress output)
1811     strcpy(tape_patch_info, "");
1812     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1813       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1814                patch_name[patch_nr]);
1815
1816     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1817       continue;
1818
1819     // speed things up in case of missing private tapes (skip loading level)
1820     if (options.mytapes && !fileExists(getTapeFilename(level_nr)))
1821     {
1822       autoplay.num_tape_missing++;
1823
1824       Print("Tape %03d: (no tape found)\n", level_nr);
1825
1826       continue;
1827     }
1828
1829     TapeErase();
1830     TapeRewind();       // needed to reset "tape.auto_play_level_solved"
1831
1832     LoadLevel(level_nr);
1833
1834     if (level.no_level_file || level.no_valid_file)
1835     {
1836       Print("Tape %03d: (no level found)\n", level_nr);
1837
1838       continue;
1839     }
1840
1841 #if 0
1842     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1843     Print("Tape %03d: (only testing level)\n", level_nr);
1844     continue;
1845 #endif
1846
1847     if (autoplay.tape_filename)
1848       LoadTapeFromFilename(autoplay.tape_filename);
1849     else if (options.mytapes)
1850       LoadTape(level_nr);
1851     else
1852       LoadSolutionTape(level_nr);
1853
1854     if (tape.no_valid_file)
1855     {
1856       autoplay.num_tape_missing++;
1857
1858       Print("Tape %03d: (no tape found)\n", level_nr);
1859
1860       continue;
1861     }
1862
1863     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1864     {
1865       boolean skip_patch = FALSE;
1866
1867       if (tape.engine_version < patch_version_first[patch_nr] ||
1868           tape.engine_version > patch_version_last[patch_nr])
1869       {
1870         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1871               level_nr,  tape_patch_info,
1872               tape.length_seconds / 60, tape.length_seconds % 60,
1873               "not suitable for version",
1874               (tape.engine_version / 1000000) % 100,
1875               (tape.engine_version / 10000  ) % 100,
1876               (tape.engine_version / 100    ) % 100,
1877               (tape.engine_version          ) % 100);
1878
1879         skip_patch = TRUE;
1880       }
1881
1882       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1883           tape.num_participating_players == 1)
1884       {
1885         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1886               level_nr,  tape_patch_info,
1887               tape.length_seconds / 60, tape.length_seconds % 60,
1888               "not suitable for single player tapes");
1889
1890         skip_patch = TRUE;
1891       }
1892
1893       if (skip_patch)
1894       {
1895         if (patch_name[patch_nr + 1] != NULL)
1896         {
1897           // continue with next patch
1898           patch_nr++;
1899         }
1900         else
1901         {
1902           // continue with next tape
1903           patch_nr = 0;
1904         }
1905
1906         continue;
1907       }
1908
1909       if (strEqual(patch_name[patch_nr], "screen_34x34"))
1910       {
1911         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
1912         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
1913       }
1914       else
1915       {
1916         tape.property_bits |= patch_property_bit[patch_nr];
1917       }
1918     }
1919
1920     num_tapes++;
1921
1922     if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1923     {
1924       boolean use_temporary_tape_file = FALSE;
1925
1926       Print("Tape %03d:\n", level_nr);
1927
1928       AutoPlayTapes_SetScoreEntry(0, 0);
1929
1930       if (autoplay.tape_filename == NULL)
1931       {
1932         autoplay.tape_filename = (options.mytapes ? getTapeFilename(level_nr) :
1933                                   getDefaultSolutionTapeFilename(level_nr));
1934
1935         if (!fileExists(autoplay.tape_filename))
1936         {
1937           // non-standard or incorrect solution tape -- save to temporary file
1938           autoplay.tape_filename = getTemporaryTapeFilename();
1939
1940           SaveTapeToFilename(autoplay.tape_filename);
1941
1942           use_temporary_tape_file = TRUE;
1943         }
1944       }
1945
1946       SaveServerScoreFromFile(level_nr, TRUE, autoplay.tape_filename);
1947
1948       boolean success = AutoPlayTapes_WaitForUpload();
1949
1950       if (use_temporary_tape_file)
1951         unlink(autoplay.tape_filename);
1952
1953       // required for uploading multiple tapes
1954       autoplay.tape_filename = NULL;
1955
1956       if (!success)
1957       {
1958         num_tapes = -num_tapes;
1959
1960         break;
1961       }
1962
1963       continue;
1964     }
1965
1966     InitCounter();
1967
1968     if (options.tape_log_filename != NULL)
1969       OpenTapeLogfile();
1970
1971     TapeStartGamePlaying();
1972     TapeStartWarpForward(global.autoplay_mode);
1973
1974     autoplay.last_level_nr = level_nr;
1975
1976     return num_tapes;
1977   }
1978
1979   if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1980   {
1981     Print("\n");
1982     PrintLine("=", 79);
1983
1984     if (num_tapes >= 0)
1985       Print("SUMMARY: %d tapes uploaded.\n", num_tapes);
1986     else
1987       Print("SUMMARY: Uploading tapes failed.\n");
1988
1989     PrintLine("=", 79);
1990   }
1991
1992   // clear timestamp for batch tape upload (required after interactive upload)
1993   global.autoplay_time = 0;
1994
1995   // exit if running headless or if visually auto-playing tapes
1996   if (program.headless || global.autoplay_mode != AUTOPLAY_MODE_UPLOAD)
1997     CloseAllAndExit(0);
1998
1999   // when running interactively, restore last selected level set and number
2000   leveldir_current = leveldir_current_last;
2001   level_nr = level_nr_last;
2002
2003   return num_tapes;
2004 }
2005
2006 int AutoPlayTapes(void)
2007 {
2008   return AutoPlayTapesExt(TRUE);
2009 }
2010
2011 int AutoPlayTapesContinue(void)
2012 {
2013   return AutoPlayTapesExt(FALSE);
2014 }
2015
2016
2017 // ----------------------------------------------------------------------------
2018 // tape patch functions
2019 // ----------------------------------------------------------------------------
2020
2021 static boolean PatchTape(struct TapeInfo *tape, char *mode)
2022 {
2023   Print("[%d.%d.%d.%d]: ",
2024         (tape->engine_version / 1000000) % 100,
2025         (tape->engine_version / 10000  ) % 100,
2026         (tape->engine_version / 100    ) % 100,
2027         (tape->engine_version          ) % 100);
2028
2029   if (strEqual(mode, "info"))
2030   {
2031     Print("property bits == 0x%02x\n", tape->property_bits);
2032
2033     return FALSE;
2034   }
2035
2036   boolean unpatch_tape = FALSE;
2037   boolean use_property_bit = FALSE;
2038   byte property_bitmask = 0;
2039
2040   if (strSuffix(mode, ":0") ||
2041       strSuffix(mode, ":off") ||
2042       strSuffix(mode, ":clear"))
2043     unpatch_tape = TRUE;
2044
2045   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
2046   {
2047     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
2048     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
2049         tape->engine_version >= VERSION_IDENT(4,0,1,2))
2050     {
2051       Print("This tape version cannot be patched against EM random bug!\n");
2052
2053       return FALSE;
2054     }
2055
2056     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
2057
2058     use_property_bit = TRUE;
2059   }
2060   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
2061   {
2062     // this bug only affects team mode tapes
2063     if (tape->num_participating_players == 1)
2064     {
2065       Print("Only team mode tapes can be patched against screen size bug!\n");
2066
2067       return FALSE;
2068     }
2069
2070     // this bug (that always existed before) was fixed in version 4.2.2.1
2071     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
2072     {
2073       Print("This tape version cannot be patched against screen size bug!\n");
2074
2075       return FALSE;
2076     }
2077
2078     int factor = (unpatch_tape ? 1 : 2);
2079     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
2080     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
2081
2082     if (scr_fieldx_new == tape->scr_fieldx &&
2083         scr_fieldy_new == tape->scr_fieldy)
2084     {
2085       Print("Tape already patched for '%s'!\n", mode);
2086
2087       return FALSE;
2088     }
2089
2090     tape->scr_fieldx = scr_fieldx_new;
2091     tape->scr_fieldy = scr_fieldy_new;
2092   }
2093   else
2094   {
2095     Print("Unknown patch mode '%s'!\n", mode);
2096
2097     return FALSE;
2098   }
2099
2100   // patching tapes using property bits may be used for several patch modes
2101   if (use_property_bit)
2102   {
2103     byte property_bits = tape->property_bits;
2104     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
2105
2106     if (set_property_bit)
2107       property_bits |= property_bitmask;
2108     else
2109       property_bits &= ~property_bitmask;
2110
2111     if (property_bits == tape->property_bits)
2112     {
2113       Print("Tape already patched for '%s'!\n", mode);
2114
2115       return FALSE;
2116     }
2117
2118     tape->property_bits = property_bits;
2119   }
2120
2121   Print("Patching for '%s' ... ", mode);
2122
2123   return TRUE;
2124 }
2125
2126 void PatchTapes(void)
2127 {
2128   static LevelDirTree *patchtapes_leveldir = NULL;
2129   static int num_tapes_found = 0;
2130   static int num_tapes_patched = 0;
2131   char *mode = global.patchtapes_mode;
2132   int i;
2133
2134   if (strEqual(mode, "help"))
2135   {
2136     PrintLine("=", 79);
2137     Print("Supported patch modes:\n");
2138     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
2139     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
2140     PrintLine("-", 79);
2141     Print("Supported modifiers:\n");
2142     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
2143     PrintLine("=", 79);
2144
2145     CloseAllAndExit(0);
2146   }
2147
2148   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
2149                                                   global.patchtapes_leveldir);
2150
2151   if (patchtapes_leveldir == NULL)
2152     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
2153
2154   leveldir_current = patchtapes_leveldir;
2155
2156   if (patchtapes_leveldir->first_level < 0)
2157     patchtapes_leveldir->first_level = 0;
2158   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
2159     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
2160
2161   PrintLine("=", 79);
2162   Print("Patching level tapes for patch mode '%s'\n", mode);
2163   PrintLine("-", 79);
2164   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
2165   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
2166   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
2167   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
2168   PrintLine("=", 79);
2169   Print("\n");
2170
2171   int first_level = patchtapes_leveldir->first_level;
2172   int last_level = patchtapes_leveldir->last_level;
2173
2174   for (i = first_level; i <= last_level; i++)
2175   {
2176     if (!global.patchtapes_all && !global.patchtapes_level[i])
2177       continue;
2178
2179     Print("Tape %03d: ", i);
2180
2181     TapeErase();
2182     LoadTape(i);
2183
2184     if (tape.no_valid_file)
2185     {
2186       Print("(no tape found)\n");
2187
2188       continue;
2189     }
2190
2191     num_tapes_found++;
2192
2193     if (PatchTape(&tape, mode))
2194     {
2195       char *filename = getTapeFilename(i);
2196       char *filename_orig = getStringCat2(filename, ".orig");
2197
2198       if (!fileExists(filename_orig))
2199         rename(filename, filename_orig);
2200
2201       SaveTapeToFilename(filename);
2202
2203       Print("patched tape saved.\n");
2204
2205       num_tapes_patched++;
2206     }
2207   }
2208
2209   Print("\n");
2210   PrintLine("=", 79);
2211   Print("Number of tapes found: %d\n", num_tapes_found);
2212   Print("Number of tapes patched: %d\n", num_tapes_patched);
2213   PrintLine("=", 79);
2214
2215   CloseAllAndExit(0);
2216 }
2217
2218
2219 // ---------- new tape button stuff -------------------------------------------
2220
2221 static struct
2222 {
2223   int graphic;
2224   struct XY *pos;
2225   int gadget_id;
2226   char *infotext;
2227 } tapebutton_info[NUM_TAPE_BUTTONS] =
2228 {
2229   {
2230     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
2231     TAPE_CTRL_ID_EJECT,                 "eject tape"
2232   },
2233   {
2234     // (same position as "eject" button)
2235     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
2236     TAPE_CTRL_ID_EXTRA,                 "extra functions"
2237   },
2238   {
2239     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
2240     TAPE_CTRL_ID_STOP,                  "stop tape"
2241   },
2242   {
2243     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
2244     TAPE_CTRL_ID_PAUSE,                 "pause tape"
2245   },
2246   {
2247     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
2248     TAPE_CTRL_ID_RECORD,                "record tape"
2249   },
2250   {
2251     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
2252     TAPE_CTRL_ID_PLAY,                  "play tape"
2253   },
2254   {
2255     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
2256     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
2257   },
2258   {
2259     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
2260     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
2261   }
2262 };
2263
2264 void CreateTapeButtons(void)
2265 {
2266   int i;
2267
2268   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2269   {
2270     int graphic = tapebutton_info[i].graphic;
2271     struct GraphicInfo *gfx = &graphic_info[graphic];
2272     struct XY *pos = tapebutton_info[i].pos;
2273     struct GadgetInfo *gi;
2274     int gd_x = gfx->src_x;
2275     int gd_y = gfx->src_y;
2276     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
2277     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
2278     int id = i;
2279
2280     gi = CreateGadget(GDI_CUSTOM_ID, id,
2281                       GDI_IMAGE_ID, graphic,
2282                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
2283                       GDI_X, VX + pos->x,
2284                       GDI_Y, VY + pos->y,
2285                       GDI_WIDTH, gfx->width,
2286                       GDI_HEIGHT, gfx->height,
2287                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
2288                       GDI_STATE, GD_BUTTON_UNPRESSED,
2289                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
2290                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
2291                       GDI_DIRECT_DRAW, FALSE,
2292                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
2293                       GDI_CALLBACK_ACTION, HandleTapeButtons,
2294                       GDI_END);
2295
2296     if (gi == NULL)
2297       Fail("cannot create gadget");
2298
2299     tape_gadget[id] = gi;
2300   }
2301 }
2302
2303 void FreeTapeButtons(void)
2304 {
2305   int i;
2306
2307   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2308     FreeGadget(tape_gadget[i]);
2309 }
2310
2311 void MapTapeEjectButton(void)
2312 {
2313   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2314   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2315 }
2316
2317 void MapTapeWarpButton(void)
2318 {
2319   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2320   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2321 }
2322
2323 void MapTapeButtons(void)
2324 {
2325   int i;
2326
2327   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2328     if (i != TAPE_CTRL_ID_EXTRA)
2329       MapGadget(tape_gadget[i]);
2330
2331   if (tape.recording || tape.playing)
2332     MapTapeWarpButton();
2333
2334   if (tape.show_game_buttons)
2335     MapGameButtonsOnTape();
2336 }
2337
2338 void UnmapTapeButtons(void)
2339 {
2340   int i;
2341
2342   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2343     UnmapGadget(tape_gadget[i]);
2344
2345   if (tape.show_game_buttons)
2346     UnmapGameButtonsOnTape();
2347 }
2348
2349 void RedrawTapeButtons(void)
2350 {
2351   int i;
2352
2353   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2354     RedrawGadget(tape_gadget[i]);
2355
2356   if (tape.show_game_buttons)
2357     RedrawGameButtonsOnTape();
2358 }
2359
2360 void RedrawOrRemapTapeButtons(void)
2361 {
2362   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
2363   {
2364     // tape buttons already mapped
2365     RedrawTapeButtons();
2366   }
2367   else
2368   {
2369     UnmapTapeButtons();
2370     MapTapeButtons();
2371   }
2372 }
2373
2374 static void HandleTapeButtonsExt(int id)
2375 {
2376   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
2377     return;
2378
2379   switch (id)
2380   {
2381     case TAPE_CTRL_ID_EJECT:
2382       TapeStop();
2383
2384       if (TAPE_IS_EMPTY(tape))
2385       {
2386         LoadTape(level_nr);
2387
2388         if (TAPE_IS_EMPTY(tape))
2389           Request("No tape for this level!", REQ_CONFIRM);
2390       }
2391       else
2392       {
2393         if (tape.changed)
2394           SaveTapeChecked(level_nr);
2395
2396         TapeErase();
2397       }
2398
2399       DrawCompleteVideoDisplay();
2400       break;
2401
2402     case TAPE_CTRL_ID_EXTRA:
2403       if (tape.playing)
2404       {
2405         tape.pause_before_end = !tape.pause_before_end;
2406
2407         DrawVideoDisplayCurrentState();
2408       }
2409       else if (tape.recording)
2410       {
2411         TapeSingleStep();
2412       }
2413
2414       break;
2415
2416     case TAPE_CTRL_ID_STOP:
2417       TapeStopTape();
2418
2419       break;
2420
2421     case TAPE_CTRL_ID_PAUSE:
2422       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2423
2424       break;
2425
2426     case TAPE_CTRL_ID_RECORD:
2427       if (TAPE_IS_STOPPED(tape))
2428       {
2429         TapeStartGameRecording();
2430       }
2431       else if (tape.pausing)
2432       {
2433         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2434           TapeAppendRecording();
2435         else
2436           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2437       }
2438
2439       break;
2440
2441     case TAPE_CTRL_ID_PLAY:
2442       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2443       {
2444         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2445
2446         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2447       }
2448
2449       if (TAPE_IS_EMPTY(tape))
2450         break;
2451
2452       if (TAPE_IS_STOPPED(tape))
2453       {
2454         TapeStartGamePlaying();
2455       }
2456       else if (tape.playing)
2457       {
2458         if (tape.pausing)                       // PAUSE -> PLAY
2459         {
2460           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2461         }
2462         else if (!tape.fast_forward)            // PLAY -> FFWD
2463         {
2464           tape.fast_forward = TRUE;
2465         }
2466         else if (!tape.warp_forward)            // FFWD -> WARP
2467         {
2468           tape.warp_forward = TRUE;
2469         }
2470         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2471         {
2472           tape.deactivate_display = TRUE;
2473
2474           TapeDeactivateDisplayOn();
2475         }
2476         else                                    // WARP BLIND -> PLAY
2477         {
2478           tape.fast_forward = FALSE;
2479           tape.warp_forward = FALSE;
2480           tape.deactivate_display = FALSE;
2481
2482           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2483         }
2484
2485         DrawVideoDisplayCurrentState();
2486       }
2487
2488       break;
2489
2490     case TAPE_CTRL_ID_INSERT_SOLUTION:
2491       InsertSolutionTape();
2492
2493       break;
2494
2495     case TAPE_CTRL_ID_PLAY_SOLUTION:
2496       PlaySolutionTape();
2497
2498       break;
2499
2500     default:
2501       break;
2502   }
2503 }
2504
2505 static void HandleTapeButtons(struct GadgetInfo *gi)
2506 {
2507   HandleTapeButtonsExt(gi->custom_id);
2508 }
2509
2510 void HandleTapeButtonKeys(Key key)
2511 {
2512   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2513   boolean extra_button_is_active = !eject_button_is_active;
2514
2515   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2516     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2517   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2518     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2519   else if (key == setup.shortcut.tape_stop)
2520     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2521   else if (key == setup.shortcut.tape_pause)
2522     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2523   else if (key == setup.shortcut.tape_record)
2524     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2525   else if (key == setup.shortcut.tape_play)
2526     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2527 }