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