5033507342b4f8029d893737555ce8ccf5972cab
[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
668   tape.random_seed = InitRND(level.random_seed);
669
670   tape.file_version = FILE_VERSION_ACTUAL;
671   tape.game_version = GAME_VERSION_ACTUAL;
672   tape.engine_version = level.game_version;
673
674   tape.property_bits = TAPE_PROPERTY_NONE;
675
676   TapeSetDateFromNow();
677
678   for (i = 0; i < MAX_PLAYERS; i++)
679     tape.player_participates[i] = FALSE;
680
681   tape.centered_player_nr_next = -1;
682   tape.set_centered_player = FALSE;
683
684   // set flags for game actions to default values (may be overwritten later)
685   tape.use_key_actions = TRUE;
686   tape.use_mouse_actions = FALSE;
687 }
688
689 static void TapeRewind(void)
690 {
691   tape.counter = 0;
692   tape.delay_played = 0;
693   tape.pause_before_end = FALSE;
694   tape.recording = FALSE;
695   tape.playing = FALSE;
696   tape.fast_forward = FALSE;
697   tape.warp_forward = FALSE;
698   tape.deactivate_display = FALSE;
699   tape.auto_play = (global.autoplay_leveldir != NULL);
700   tape.auto_play_level_solved = FALSE;
701   tape.auto_play_level_fixed = FALSE;
702   tape.auto_play_level_not_fixable = FALSE;
703   tape.quick_resume = FALSE;
704   tape.single_step = FALSE;
705
706   tape.centered_player_nr_next = -1;
707   tape.set_centered_player = FALSE;
708
709   InitRND(tape.random_seed);
710 }
711
712 static void TapeSetRandomSeed(int random_seed)
713 {
714   tape.random_seed = InitRND(random_seed);
715 }
716
717 void TapeStartRecording(int random_seed)
718 {
719   if (!TAPE_IS_STOPPED(tape))
720     TapeStop();
721
722   TapeErase();
723   TapeRewind();
724   TapeSetRandomSeed(random_seed);
725
726   tape.recording = TRUE;
727
728   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
729   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
730   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
731   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
732
733   MapTapeWarpButton();
734
735   SetDrawDeactivationMask(REDRAW_NONE);
736   audio.sound_deactivated = FALSE;
737
738   // required here to update video display if tape door is closed
739   if (GetDoorState() & DOOR_CLOSE_2)
740     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
741 }
742
743 static void TapeStartGameRecording(void)
744 {
745   StartGameActions(network.enabled, TRUE, level.random_seed);
746 }
747
748 static void TapeAppendRecording(void)
749 {
750   if (!tape.playing || !tape.pausing)
751     return;
752
753   // stop playing
754   tape.playing = FALSE;
755   tape.fast_forward = FALSE;
756   tape.warp_forward = FALSE;
757   tape.pause_before_end = FALSE;
758   tape.deactivate_display = FALSE;
759
760   // start recording
761   tape.recording = TRUE;
762   tape.changed = TRUE;
763
764   // set current delay (for last played move)
765   tape.pos[tape.counter].delay = tape.delay_played;
766
767   tape.property_bits |= TAPE_PROPERTY_REPLAYED;
768
769   // set current date
770   TapeSetDateFromNow();
771
772   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
773   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
774
775   UpdateAndDisplayGameControlValues();
776 }
777
778 void TapeHaltRecording(void)
779 {
780   tape.counter++;
781
782   // initialize delay for next tape entry (to be able to continue recording)
783   if (tape.counter < MAX_TAPE_LEN)
784     tape.pos[tape.counter].delay = 0;
785
786   tape.length = tape.counter;
787   tape.length_frames = GetTapeLengthFrames();
788   tape.length_seconds = GetTapeLengthSeconds();
789 }
790
791 void TapeStopRecording(void)
792 {
793   if (tape.recording)
794     TapeHaltRecording();
795
796   tape.recording = FALSE;
797   tape.pausing = FALSE;
798
799   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
800   MapTapeEjectButton();
801 }
802
803 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
804 {
805   int i;
806
807   if (tape.pos[tape.counter].delay > 0)         // already stored action
808   {
809     boolean changed_events = FALSE;
810
811     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
812       if (tape.pos[tape.counter].action[i] != action[i])
813         changed_events = TRUE;
814
815     if (changed_events || tape.pos[tape.counter].delay >= 255)
816     {
817       if (tape.counter >= MAX_TAPE_LEN - 1)
818         return FALSE;
819
820       tape.counter++;
821       tape.pos[tape.counter].delay = 0;
822     }
823     else
824       tape.pos[tape.counter].delay++;
825   }
826
827   if (tape.pos[tape.counter].delay == 0)        // store new action
828   {
829     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
830       tape.pos[tape.counter].action[i] = action[i];
831
832     tape.pos[tape.counter].delay++;
833   }
834
835   return TRUE;
836 }
837
838 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
839 {
840   byte action[MAX_TAPE_ACTIONS];
841   int i;
842
843   if (!tape.recording)          // (record action even when tape is paused)
844     return;
845
846   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
847     action[i] = action_raw[i];
848
849   if (tape.use_key_actions && tape.set_centered_player)
850   {
851     for (i = 0; i < MAX_PLAYERS; i++)
852       if (tape.centered_player_nr_next == i ||
853           tape.centered_player_nr_next == -1)
854         action[i] |= KEY_SET_FOCUS;
855
856     tape.set_centered_player = FALSE;
857   }
858
859   if (GameFrameDelay != GAME_FRAME_DELAY)
860     tape.property_bits |= TAPE_PROPERTY_GAME_SPEED;
861
862   if (setup.small_game_graphics || SCR_FIELDX >= 2 * SCR_FIELDX_DEFAULT)
863     tape.property_bits |= TAPE_PROPERTY_SMALL_GRAPHICS;
864
865   if (!TapeAddAction(action))
866     TapeStopRecording();
867 }
868
869 void TapeTogglePause(boolean toggle_mode)
870 {
871   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
872   {
873     // continue playing in normal mode
874     tape.fast_forward = FALSE;
875     tape.warp_forward = FALSE;
876     tape.deactivate_display = FALSE;
877
878     tape.pause_before_end = FALSE;
879   }
880
881   tape.pausing = !tape.pausing;
882
883   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
884     tape.single_step = FALSE;
885
886   if (tape.single_step)
887     tape.property_bits |= TAPE_PROPERTY_SINGLE_STEP;
888
889   if (tape.pausing)
890     tape.property_bits |= TAPE_PROPERTY_PAUSE_MODE;
891
892   DrawVideoDisplayCurrentState();
893
894   if (tape.deactivate_display)
895   {
896     if (tape.pausing)
897       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
898     else
899       TapeDeactivateDisplayOn();
900   }
901
902   if (tape.quick_resume)
903   {
904     tape.quick_resume = FALSE;
905
906     TapeStopWarpForward();
907     TapeAppendRecording();
908
909     if (!CheckEngineSnapshotSingle())
910       SaveEngineSnapshotSingle();
911
912     // restart step/move snapshots after quick loading tape
913     SaveEngineSnapshotToListInitial();
914
915     // do not map undo/redo buttons after quick loading tape
916     return;
917   }
918
919   if (game_status == GAME_MODE_PLAYING)
920   {
921     if (setup.show_load_save_buttons &&
922         setup.show_undo_redo_buttons &&
923         CheckEngineSnapshotList())
924     {
925       if (tape.pausing)
926         MapUndoRedoButtons();
927       else if (!tape.single_step)
928         MapLoadSaveButtons();
929     }
930
931     ModifyPauseButtons();
932   }
933 }
934
935 void TapeStartPlaying(void)
936 {
937   if (TAPE_IS_EMPTY(tape))
938     return;
939
940   if (!TAPE_IS_STOPPED(tape))
941     TapeStop();
942
943   TapeRewind();
944
945   tape.playing = TRUE;
946
947   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
948   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
949   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
950   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
951
952   MapTapeWarpButton();
953
954   SetDrawDeactivationMask(REDRAW_NONE);
955   audio.sound_deactivated = FALSE;
956 }
957
958 static void TapeStartGamePlaying(void)
959 {
960   TapeStartPlaying();
961
962   InitGame();
963 }
964
965 void TapeStopPlaying(void)
966 {
967   tape.playing = FALSE;
968   tape.pausing = FALSE;
969
970   if (tape.warp_forward)
971     TapeStopWarpForward();
972
973   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
974   MapTapeEjectButton();
975 }
976
977 byte *TapePlayAction(void)
978 {
979   int update_delay = FRAMES_PER_SECOND / 2;
980   boolean update_video_display = (FrameCounter % update_delay == 0);
981   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
982   static byte action[MAX_TAPE_ACTIONS];
983   int i;
984
985   if (!tape.playing || tape.pausing)
986     return NULL;
987
988   if (tape.pause_before_end)  // stop some seconds before end of tape
989   {
990     if (TapeTime > (int)tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
991     {
992       TapeStopWarpForward();
993       TapeTogglePause(TAPE_TOGGLE_MANUAL);
994
995       return NULL;
996     }
997   }
998
999   if (tape.counter >= tape.length)      // end of tape reached
1000   {
1001     if (tape.warp_forward && !tape.auto_play)
1002     {
1003       TapeStopWarpForward();
1004       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1005     }
1006     else
1007     {
1008       TapeStop();
1009     }
1010
1011     return NULL;
1012   }
1013
1014   if (update_video_display && !tape.deactivate_display)
1015   {
1016     int state = 0;
1017
1018     if (tape.warp_forward)
1019       state |= VIDEO_STATE_WARP(update_draw_label_on);
1020     else if (tape.fast_forward)
1021       state |= VIDEO_STATE_FFWD(update_draw_label_on);
1022
1023     if (tape.pause_before_end)
1024       state |= VIDEO_STATE_PBEND(update_draw_label_on);
1025
1026     // draw labels and symbols separately to prevent labels overlapping symbols
1027     DrawVideoDisplayLabel(state);
1028     DrawVideoDisplaySymbol(state);
1029   }
1030
1031   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1032     action[i] = tape.pos[tape.counter].action[i];
1033
1034 #if DEBUG_TAPE_WHEN_PLAYING
1035   DebugContinued("", "%05d", FrameCounter);
1036   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
1037     DebugContinued("", "   %08x", action[i]);
1038   DebugContinued("tape:play", "\n");
1039 #endif
1040
1041   tape.set_centered_player = FALSE;
1042   tape.centered_player_nr_next = -999;
1043
1044   if (tape.use_key_actions)
1045   {
1046     for (i = 0; i < MAX_PLAYERS; i++)
1047     {
1048       if (action[i] & KEY_SET_FOCUS)
1049       {
1050         tape.set_centered_player = TRUE;
1051         tape.centered_player_nr_next =
1052           (tape.centered_player_nr_next == -999 ? i : -1);
1053       }
1054
1055       action[i] &= ~KEY_SET_FOCUS;
1056     }
1057   }
1058
1059   tape.delay_played++;
1060   if (tape.delay_played >= tape.pos[tape.counter].delay)
1061   {
1062     tape.counter++;
1063     tape.delay_played = 0;
1064   }
1065
1066   if (tape.auto_play)
1067     PrintTapeReplayProgress(FALSE);
1068
1069   if (options.tape_log_filename != NULL)
1070     WriteTapeLogfile(action);
1071
1072   return action;
1073 }
1074
1075 void TapeStop(void)
1076 {
1077   if (tape.pausing)
1078     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1079
1080   TapeStopRecording();
1081   TapeStopPlaying();
1082
1083   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
1084
1085   if (tape.date && tape.length)
1086   {
1087     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
1088     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
1089     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
1090   }
1091 }
1092
1093 static void TapeStopGameOrTape(boolean stop_game)
1094 {
1095   if (score_info_tape_play || (!tape.playing && stop_game))
1096     RequestQuitGame(FALSE);
1097   else
1098     TapeStop();
1099 }
1100
1101 void TapeStopGame(void)
1102 {
1103   if (game_status == GAME_MODE_MAIN)
1104     return;
1105
1106   TapeStopGameOrTape(TRUE);
1107 }
1108
1109 void TapeStopTape(void)
1110 {
1111   TapeStopGameOrTape(FALSE);
1112 }
1113
1114 unsigned int GetTapeLengthFrames(void)
1115 {
1116   unsigned int tape_length_frames = 0;
1117   int i;
1118
1119   if (TAPE_IS_EMPTY(tape))
1120     return 0;
1121
1122   for (i = 0; i < tape.length; i++)
1123     tape_length_frames += tape.pos[i].delay;
1124
1125   return tape_length_frames;
1126 }
1127
1128 unsigned int GetTapeLengthSeconds(void)
1129 {
1130   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1131 }
1132
1133 static float GetTapeLengthSecondsFloat(void)
1134 {
1135   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1136 }
1137
1138 static void TapeStartWarpForward(int mode)
1139 {
1140   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1141   tape.warp_forward = (mode & AUTOPLAY_WARP);
1142   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1143
1144   tape.pausing = FALSE;
1145
1146   if (tape.deactivate_display)
1147     TapeDeactivateDisplayOn();
1148
1149   DrawVideoDisplayCurrentState();
1150 }
1151
1152 static void TapeStopWarpForward(void)
1153 {
1154   tape.fast_forward = FALSE;
1155   tape.warp_forward = FALSE;
1156   tape.deactivate_display = FALSE;
1157
1158   tape.pause_before_end = FALSE;
1159
1160   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1161
1162   DrawVideoDisplayCurrentState();
1163 }
1164
1165 static void TapeSingleStep(void)
1166 {
1167   if (network.enabled)
1168     return;
1169
1170   if (!tape.pausing)
1171     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1172
1173   tape.single_step = !tape.single_step;
1174
1175   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1176 }
1177
1178 void TapeQuickSave(void)
1179 {
1180   if (game_status == GAME_MODE_MAIN)
1181   {
1182     Request("No game that can be saved!", REQ_CONFIRM);
1183
1184     return;
1185   }
1186
1187   if (game_status != GAME_MODE_PLAYING)
1188     return;
1189
1190   if (tape.recording)
1191     TapeHaltRecording();        // prepare tape for saving on-the-fly
1192
1193   if (TAPE_IS_EMPTY(tape))
1194   {
1195     Request("No tape that can be saved!", REQ_CONFIRM);
1196
1197     return;
1198   }
1199
1200   tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1201
1202   if (SaveTapeChecked(tape.level_nr))
1203     SaveEngineSnapshotSingle();
1204 }
1205
1206 void TapeQuickLoad(void)
1207 {
1208   char *filename = getTapeFilename(level_nr);
1209
1210   if (!fileExists(filename))
1211   {
1212     Request("No tape for this level!", REQ_CONFIRM);
1213
1214     return;
1215   }
1216
1217   if (tape.recording && !Request("Stop recording and load tape?",
1218                                  REQ_ASK | REQ_STAY_CLOSED))
1219   {
1220     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1221
1222     return;
1223   }
1224
1225   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1226     return;
1227
1228   if (CheckEngineSnapshotSingle())
1229   {
1230     TapeStartGamePlaying();
1231
1232     LoadEngineSnapshotSingle();
1233
1234     DrawCompleteVideoDisplay();
1235
1236     tape.playing = TRUE;
1237     tape.pausing = TRUE;
1238
1239     TapeStopWarpForward();
1240     TapeAppendRecording();
1241
1242     // restart step/move snapshots after quick loading tape
1243     SaveEngineSnapshotToListInitial();
1244
1245     if (FrameCounter > 0)
1246       return;
1247   }
1248
1249   TapeStop();
1250   TapeErase();
1251
1252   LoadTape(level_nr);
1253
1254   if (!TAPE_IS_EMPTY(tape))
1255   {
1256     TapeStartGamePlaying();
1257     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1258
1259     tape.quick_resume = TRUE;
1260     tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1261   }
1262   else  // this should not happen (basically checked above)
1263   {
1264     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1265
1266     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1267   }
1268 }
1269
1270 static boolean checkRestartGame(char *message)
1271 {
1272   if (game_status == GAME_MODE_MAIN)
1273     return TRUE;
1274
1275   if (!hasStartedNetworkGame())
1276     return FALSE;
1277
1278   if (level_editor_test_game)
1279     return TRUE;
1280
1281   if (game.all_players_gone)
1282     return TRUE;
1283
1284   if (!setup.ask_on_quit_game)
1285     return TRUE;
1286
1287   if (Request(message, REQ_ASK | REQ_STAY_CLOSED))
1288     return TRUE;
1289
1290   OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1291
1292   return FALSE;
1293 }
1294
1295 void TapeRestartGame(void)
1296 {
1297   if (score_info_tape_play)
1298   {
1299     TapeStartGamePlaying();
1300
1301     return;
1302   }
1303
1304   if (!checkRestartGame("Restart game?"))
1305     return;
1306
1307   StartGameActions(network.enabled, setup.autorecord, level.random_seed);
1308 }
1309
1310 void TapeReplayAndPauseBeforeEnd(void)
1311 {
1312   if (score_info_tape_play)
1313     return;
1314
1315   if (TAPE_IS_EMPTY(tape) && !tape.recording)
1316   {
1317     Request("No tape for this level!", REQ_CONFIRM);
1318
1319     return;
1320   }
1321
1322   if (!checkRestartGame("Replay game and pause before end?"))
1323     return;
1324
1325   TapeStop();
1326   TapeStartGamePlaying();
1327   TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1328
1329   tape.pause_before_end = TRUE;
1330   tape.quick_resume = TRUE;
1331 }
1332
1333 boolean hasSolutionTape(void)
1334 {
1335   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1336   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1337                             level.native_sp_level->demo.is_available);
1338
1339   return (tape_file_exists || level_has_tape);
1340 }
1341
1342 boolean InsertSolutionTape(void)
1343 {
1344   if (!hasSolutionTape())
1345   {
1346     Request("No solution tape for this level!", REQ_CONFIRM);
1347
1348     return FALSE;
1349   }
1350
1351   if (!TAPE_IS_STOPPED(tape))
1352     TapeStop();
1353
1354   // if tape recorder already contains a tape, remove it without asking
1355   TapeErase();
1356
1357   LoadSolutionTape(level_nr);
1358
1359   DrawCompleteVideoDisplay();
1360
1361   if (TAPE_IS_EMPTY(tape))
1362   {
1363     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1364
1365     return FALSE;
1366   }
1367
1368   return TRUE;
1369 }
1370
1371 boolean PlaySolutionTape(void)
1372 {
1373   if (!InsertSolutionTape())
1374     return FALSE;
1375
1376   TapeStartGamePlaying();
1377
1378   return TRUE;
1379 }
1380
1381 static boolean PlayScoreTape_WaitForDownload(void)
1382 {
1383   unsigned int download_delay = 0;
1384   unsigned int download_delay_value = 10000;
1385
1386   ResetDelayCounter(&download_delay);
1387
1388   // wait for score tape to be successfully downloaded (and fail on timeout)
1389   while (!server_scores.tape_downloaded)
1390   {
1391     if (DelayReached(&download_delay, download_delay_value))
1392       return FALSE;
1393
1394     UPDATE_BUSY_STATE_NOT_LOADING();
1395
1396     Delay(20);
1397   }
1398
1399   return TRUE;
1400 }
1401
1402 boolean PlayScoreTape(int entry_nr)
1403 {
1404   struct ScoreEntry *entry = &scores.entry[entry_nr];
1405   char *tape_filename = getScoreTapeFilename(entry->tape_basename, level_nr);
1406   boolean download_tape = (!fileExists(tape_filename));
1407
1408   if (download_tape && entry->id == -1)
1409   {
1410     FadeSkipNextFadeIn();
1411
1412     Request("Cannot find score tape!", REQ_CONFIRM);
1413
1414     return FALSE;
1415   }
1416
1417   server_scores.tape_downloaded = FALSE;
1418
1419   if (download_tape)
1420     ApiGetScoreTapeAsThread(level_nr, entry->id, entry->tape_basename);
1421
1422   SetGameStatus(GAME_MODE_PLAYING);
1423
1424   FadeOut(REDRAW_FIELD);
1425
1426   if (download_tape && !PlayScoreTape_WaitForDownload())
1427   {
1428     SetGameStatus(GAME_MODE_SCOREINFO);
1429     ClearField();
1430
1431     Request("Cannot download score tape from score server!", REQ_CONFIRM);
1432
1433     return FALSE;
1434   }
1435
1436   if (!TAPE_IS_STOPPED(tape))
1437     TapeStop();
1438
1439   // if tape recorder already contains a tape, remove it without asking
1440   TapeErase();
1441
1442   LoadScoreTape(entry->tape_basename, level_nr);
1443
1444   if (TAPE_IS_EMPTY(tape))
1445   {
1446     SetGameStatus(GAME_MODE_SCOREINFO);
1447     ClearField();
1448
1449     Request("Cannot load score tape for this level!", REQ_CONFIRM);
1450
1451     return FALSE;
1452   }
1453
1454   FadeSkipNextFadeOut();
1455
1456   TapeStartGamePlaying();
1457
1458   score_info_tape_play = TRUE;
1459
1460   return TRUE;
1461 }
1462
1463 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1464 {
1465   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1466           t1->level_nr == t2->level_nr);
1467 }
1468
1469 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1470 {
1471   *tape_to = *tape_from;
1472 }
1473
1474 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1475 {
1476   struct TapeInfo tmp = *t1;
1477
1478   *t1 = *t2;
1479   *t2 = tmp;
1480 }
1481
1482 static void CopyTapeToUndoBuffer(void)
1483 {
1484   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1485   // or if the last undo tape is from a different level set or level number
1486   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1487       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1488       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1489   {
1490     CopyTape(&tape, &tape_undo_buffer);
1491   }
1492 }
1493
1494 void UndoTape(void)
1495 {
1496   // only undo tapes from same level set and with same level number
1497   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1498     return;
1499
1500   if (!TAPE_IS_STOPPED(tape))
1501     TapeStop();
1502
1503   // swap last recorded tape with undo buffer, so undo can be reversed
1504   SwapTapes(&tape, &tape_undo_buffer);
1505
1506   DrawCompleteVideoDisplay();
1507 }
1508
1509 void FixTape_ForceSinglePlayer(void)
1510 {
1511   int i;
1512
1513   /* fix single-player tapes that contain player input for more than one
1514      player (due to a bug in 3.3.1.2 and earlier versions), which results
1515      in playing levels with more than one player in multi-player mode,
1516      even though the tape was originally recorded in single-player mode */
1517
1518   // remove player input actions for all players but the first one
1519   for (i = 1; i < MAX_PLAYERS; i++)
1520     tape.player_participates[i] = FALSE;
1521
1522   tape.changed = TRUE;
1523 }
1524
1525
1526 // ----------------------------------------------------------------------------
1527 // tape autoplay functions
1528 // ----------------------------------------------------------------------------
1529
1530 static TreeInfo *getNextValidAutoPlayEntry(TreeInfo *node)
1531 {
1532   node = getNextValidTreeInfoEntry(node);
1533
1534   while (node && node->is_copy)
1535     node = getNextValidTreeInfoEntry(node);
1536
1537   return node;
1538 }
1539
1540 static TreeInfo *getFirstValidAutoPlayEntry(TreeInfo *node)
1541 {
1542   node = getFirstValidTreeInfoEntry(node);
1543
1544   if (node && node->is_copy)
1545     return getNextValidAutoPlayEntry(node);
1546
1547   return node;
1548 }
1549
1550 static void AutoPlayTapes_SetScoreEntry(int score, int time)
1551 {
1552   char *name = (options.mytapes ? setup.player_name : options.player_name);
1553
1554   // set unique basename for score tape (for uploading to score server)
1555   strcpy(tape.score_tape_basename, getScoreTapeBasename(name));
1556
1557   // store score in first score entry
1558   scores.last_added = 0;
1559
1560   struct ScoreEntry *entry = &scores.entry[scores.last_added];
1561
1562   strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1563   strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1564
1565   entry->score = score;
1566   entry->time = time;
1567
1568   PrintNoLog("- uploading score tape to score server ... ");
1569
1570   server_scores.uploaded = FALSE;
1571 }
1572
1573 static boolean AutoPlayTapes_WaitForUpload(void)
1574 {
1575   unsigned int upload_delay = 0;
1576   unsigned int upload_delay_value = 10000;
1577
1578   ResetDelayCounter(&upload_delay);
1579
1580   // wait for score tape to be successfully uploaded (and fail on timeout)
1581   while (!server_scores.uploaded)
1582   {
1583     if (DelayReached(&upload_delay, upload_delay_value))
1584     {
1585       PrintNoLog("\r");
1586       Print("- uploading score tape to score server - TIMEOUT.\n");
1587
1588       if (program.headless)
1589         Fail("cannot upload score tape to score server");
1590
1591       return FALSE;
1592     }
1593
1594     UPDATE_BUSY_STATE();
1595
1596     Delay(20);
1597   }
1598
1599   PrintNoLog("\r");
1600   Print("- uploading score tape to score server - uploaded.\n");
1601
1602   return TRUE;
1603 }
1604
1605 static int AutoPlayTapesExt(boolean initialize)
1606 {
1607   static struct AutoPlayInfo autoplay;
1608   static int num_tapes = 0;
1609   static int patch_nr = 0;
1610   static char *patch_name[] =
1611   {
1612     "original tape",
1613     "em_random_bug",
1614     "screen_34x34",
1615
1616     NULL
1617   };
1618   static int patch_version_first[] =
1619   {
1620     VERSION_IDENT(0,0,0,0),
1621     VERSION_IDENT(3,3,1,0),
1622     VERSION_IDENT(0,0,0,0),
1623
1624     -1
1625   };
1626   static int patch_version_last[] =
1627   {
1628     VERSION_IDENT(9,9,9,9),
1629     VERSION_IDENT(4,0,1,1),
1630     VERSION_IDENT(4,2,2,0),
1631
1632     -1
1633   };
1634   static byte patch_property_bit[] =
1635   {
1636     TAPE_PROPERTY_NONE,
1637     TAPE_PROPERTY_EM_RANDOM_BUG,
1638     TAPE_PROPERTY_NONE,
1639
1640     -1
1641   };
1642   LevelDirTree *leveldir_current_last = leveldir_current;
1643   boolean init_level_set = FALSE;
1644   int level_nr_last = level_nr;
1645   int i;
1646
1647   if (!initialize)
1648   {
1649     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1650     {
1651       if (tape.auto_play_level_solved)
1652       {
1653         if (patch_nr > 0)
1654         {
1655           // level solved by patched tape -- save fixed tape
1656           char *filename = getTapeFilename(level_nr);
1657           char *filename_orig = getStringCat2(filename, ".orig");
1658
1659           // create backup from old tape, if not yet existing
1660           if (!fileExists(filename_orig))
1661             rename(filename, filename_orig);
1662
1663           SaveTapeToFilename(filename);
1664
1665           tape.auto_play_level_fixed = TRUE;
1666           autoplay.num_tapes_patched++;
1667         }
1668
1669         // continue with next tape
1670         patch_nr = 0;
1671       }
1672       else if (patch_name[patch_nr + 1] != NULL)
1673       {
1674         // level not solved by patched tape -- continue with next patch
1675         patch_nr++;
1676       }
1677       else
1678       {
1679         // level not solved by any patched tape -- continue with next tape
1680         tape.auto_play_level_not_fixable = TRUE;
1681         patch_nr = 0;
1682       }
1683     }
1684
1685     // just finished auto-playing tape
1686     PrintTapeReplayProgress(TRUE);
1687
1688     if (options.tape_log_filename != NULL)
1689       CloseTapeLogfile();
1690
1691     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1692         tape.auto_play_level_solved)
1693     {
1694       AutoPlayTapes_SetScoreEntry(game.score_final, game.score_time_final);
1695
1696       if (leveldir_current)
1697       {
1698         // the tape's level set identifier may differ from current level set
1699         strncpy(tape.level_identifier, leveldir_current->identifier,
1700                 MAX_FILENAME_LEN);
1701         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1702
1703         // the tape's level number may differ from current level number
1704         tape.level_nr = level_nr;
1705       }
1706
1707       // save score tape to upload to server; may be required for some reasons:
1708       // * level set identifier in solution tapes may differ from level set
1709       // * level set identifier is missing (old-style tape without INFO chunk)
1710       // * solution tape may have native format (like Supaplex solution files)
1711
1712       SaveScoreTape(level_nr);
1713       SaveServerScore(level_nr, TRUE);
1714
1715       AutoPlayTapes_WaitForUpload();
1716     }
1717
1718     if (patch_nr == 0)
1719       autoplay.num_levels_played++;
1720
1721     if (tape.auto_play_level_solved)
1722       autoplay.num_levels_solved++;
1723
1724     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1725       autoplay.level_failed[level_nr] = !tape.auto_play_level_solved;
1726   }
1727   else
1728   {
1729     if (strEqual(global.autoplay_leveldir, "ALL"))
1730     {
1731       autoplay.all_levelsets = TRUE;
1732
1733       // tape mass-uploading only allowed for private tapes
1734       if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1735         options.mytapes = TRUE;
1736     }
1737
1738     if ((global.autoplay_mode == AUTOPLAY_MODE_SAVE ||
1739          global.autoplay_mode == AUTOPLAY_MODE_UPLOAD) &&
1740         !options.mytapes &&
1741         options.player_name == NULL)
1742     {
1743       Fail("specify player name when uploading solution tapes");
1744     }
1745
1746     if (global.autoplay_mode != AUTOPLAY_MODE_UPLOAD)
1747       DrawCompleteVideoDisplay();
1748
1749     if (program.headless)
1750     {
1751       audio.sound_enabled = FALSE;
1752       setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1753     }
1754
1755     if (strSuffix(global.autoplay_leveldir, ".tape"))
1756     {
1757       autoplay.tape_filename = global.autoplay_leveldir;
1758
1759       if (!fileExists(autoplay.tape_filename))
1760         Fail("tape file '%s' does not exist", autoplay.tape_filename);
1761
1762       LoadTapeFromFilename(autoplay.tape_filename);
1763
1764       if (tape.no_valid_file)
1765         Fail("cannot load tape file '%s'", autoplay.tape_filename);
1766
1767       if (tape.no_info_chunk && !options.identifier)
1768         Fail("cannot get levelset from tape file '%s'", autoplay.tape_filename);
1769
1770       if (tape.no_info_chunk && !options.level_nr)
1771         Fail("cannot get level nr from tape file '%s'", autoplay.tape_filename);
1772
1773       global.autoplay_leveldir = tape.level_identifier;
1774
1775       if (options.identifier != NULL)
1776         global.autoplay_leveldir = options.identifier;
1777
1778       if (options.level_nr != NULL)
1779         tape.level_nr = atoi(options.level_nr);
1780
1781       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1782         global.autoplay_level[tape.level_nr] = TRUE;
1783
1784       global.autoplay_all = FALSE;
1785       options.mytapes = FALSE;
1786     }
1787
1788     if (autoplay.all_levelsets)
1789     {
1790       // start auto-playing first level set
1791       autoplay.leveldir = getFirstValidAutoPlayEntry(leveldir_first);
1792     }
1793     else
1794     {
1795       // auto-play selected level set
1796       autoplay.leveldir = getTreeInfoFromIdentifier(leveldir_first,
1797                                                     global.autoplay_leveldir);
1798     }
1799
1800     if (autoplay.leveldir == NULL)
1801       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1802
1803     // only private tapes may be modified
1804     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1805       options.mytapes = TRUE;
1806
1807     // set timestamp for batch tape upload
1808     global.autoplay_time = time(NULL);
1809
1810     num_tapes = 0;
1811
1812     init_level_set = TRUE;
1813   }
1814
1815   while (1)
1816   {
1817     if (init_level_set)
1818     {
1819       leveldir_current = autoplay.leveldir;
1820
1821       if (autoplay.leveldir->first_level < 0)
1822         autoplay.leveldir->first_level = 0;
1823       if (autoplay.leveldir->last_level >= MAX_TAPES_PER_SET)
1824         autoplay.leveldir->last_level = MAX_TAPES_PER_SET - 1;
1825
1826       autoplay.level_nr = autoplay.leveldir->first_level;
1827
1828       autoplay.num_levels_played = 0;
1829       autoplay.num_levels_solved = 0;
1830       autoplay.num_tapes_patched = 0;
1831       autoplay.num_tape_missing = 0;
1832
1833       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1834         autoplay.level_failed[i] = FALSE;
1835
1836       PrintTapeReplayHeader(&autoplay);
1837
1838       init_level_set = FALSE;
1839     }
1840
1841     if (autoplay.all_levelsets && global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1842     {
1843       boolean skip_levelset = FALSE;
1844
1845       if (!directoryExists(getTapeDir(autoplay.leveldir->subdir)))
1846       {
1847         Print("No tape directory for this level set found -- skipping.\n");
1848
1849         skip_levelset = TRUE;
1850       }
1851
1852       if (CheckTapeDirectoryUploadsComplete(autoplay.leveldir->subdir))
1853       {
1854         Print("All tapes for this level set already uploaded -- skipping.\n");
1855
1856         skip_levelset = TRUE;
1857       }
1858
1859       if (skip_levelset)
1860       {
1861         PrintTapeReplaySummary(&autoplay);
1862
1863         // continue with next level set
1864         autoplay.leveldir = getNextValidAutoPlayEntry(autoplay.leveldir);
1865
1866         // all level sets processed
1867         if (autoplay.leveldir == NULL)
1868           break;
1869
1870         init_level_set = TRUE;
1871
1872         continue;
1873       }
1874     }
1875
1876     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1877       level_nr = autoplay.level_nr++;
1878
1879     UPDATE_BUSY_STATE();
1880
1881     // check if all tapes for this level set have been processed
1882     if (level_nr > autoplay.leveldir->last_level)
1883     {
1884       PrintTapeReplaySummary(&autoplay);
1885
1886       if (!autoplay.all_levelsets)
1887         break;
1888
1889       if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1890         MarkTapeDirectoryUploadsAsComplete(autoplay.leveldir->subdir);
1891
1892       // continue with next level set
1893       autoplay.leveldir = getNextValidAutoPlayEntry(autoplay.leveldir);
1894
1895       // all level sets processed
1896       if (autoplay.leveldir == NULL)
1897         break;
1898
1899       init_level_set = TRUE;
1900
1901       continue;
1902     }
1903
1904     // set patch info (required for progress output)
1905     strcpy(tape_patch_info, "");
1906     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1907       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1908                patch_name[patch_nr]);
1909
1910     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1911       continue;
1912
1913     // speed things up in case of missing private tapes (skip loading level)
1914     if (options.mytapes && !fileExists(getTapeFilename(level_nr)))
1915     {
1916       autoplay.num_tape_missing++;
1917
1918       Print("Tape %03d: (no tape found)\n", level_nr);
1919
1920       continue;
1921     }
1922
1923     TapeErase();
1924     TapeRewind();       // needed to reset "tape.auto_play_level_solved"
1925
1926     LoadLevel(level_nr);
1927
1928     if (level.no_level_file || level.no_valid_file)
1929     {
1930       Print("Tape %03d: (no level found)\n", level_nr);
1931
1932       continue;
1933     }
1934
1935 #if 0
1936     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1937     Print("Tape %03d: (only testing level)\n", level_nr);
1938     continue;
1939 #endif
1940
1941     if (autoplay.tape_filename)
1942       LoadTapeFromFilename(autoplay.tape_filename);
1943     else if (options.mytapes)
1944       LoadTape(level_nr);
1945     else
1946       LoadSolutionTape(level_nr);
1947
1948     if (tape.no_valid_file)
1949     {
1950       autoplay.num_tape_missing++;
1951
1952       Print("Tape %03d: (no tape found)\n", level_nr);
1953
1954       continue;
1955     }
1956
1957     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1958     {
1959       boolean skip_patch = FALSE;
1960
1961       if (tape.engine_version < patch_version_first[patch_nr] ||
1962           tape.engine_version > patch_version_last[patch_nr])
1963       {
1964         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1965               level_nr,  tape_patch_info,
1966               tape.length_seconds / 60, tape.length_seconds % 60,
1967               "not suitable for version",
1968               (tape.engine_version / 1000000) % 100,
1969               (tape.engine_version / 10000  ) % 100,
1970               (tape.engine_version / 100    ) % 100,
1971               (tape.engine_version          ) % 100);
1972
1973         skip_patch = TRUE;
1974       }
1975
1976       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1977           tape.num_participating_players == 1)
1978       {
1979         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1980               level_nr,  tape_patch_info,
1981               tape.length_seconds / 60, tape.length_seconds % 60,
1982               "not suitable for single player tapes");
1983
1984         skip_patch = TRUE;
1985       }
1986
1987       if (skip_patch)
1988       {
1989         if (patch_name[patch_nr + 1] != NULL)
1990         {
1991           // continue with next patch
1992           patch_nr++;
1993         }
1994         else
1995         {
1996           // continue with next tape
1997           patch_nr = 0;
1998         }
1999
2000         continue;
2001       }
2002
2003       if (strEqual(patch_name[patch_nr], "screen_34x34"))
2004       {
2005         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
2006         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
2007       }
2008       else
2009       {
2010         tape.property_bits |= patch_property_bit[patch_nr];
2011       }
2012     }
2013
2014     num_tapes++;
2015
2016     if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
2017     {
2018       boolean use_temporary_tape_file = FALSE;
2019
2020       Print("Tape %03d:\n", level_nr);
2021
2022       AutoPlayTapes_SetScoreEntry(0, 0);
2023
2024       if (autoplay.tape_filename == NULL)
2025       {
2026         autoplay.tape_filename = (options.mytapes ? getTapeFilename(level_nr) :
2027                                   getDefaultSolutionTapeFilename(level_nr));
2028
2029         if (!fileExists(autoplay.tape_filename))
2030         {
2031           // non-standard or incorrect solution tape -- save to temporary file
2032           autoplay.tape_filename = getTemporaryTapeFilename();
2033
2034           SaveTapeToFilename(autoplay.tape_filename);
2035
2036           use_temporary_tape_file = TRUE;
2037         }
2038       }
2039
2040       SaveServerScoreFromFile(level_nr, TRUE, autoplay.tape_filename);
2041
2042       boolean success = AutoPlayTapes_WaitForUpload();
2043
2044       if (use_temporary_tape_file)
2045         unlink(autoplay.tape_filename);
2046
2047       // required for uploading multiple tapes
2048       autoplay.tape_filename = NULL;
2049
2050       if (!success)
2051       {
2052         num_tapes = -num_tapes;
2053
2054         break;
2055       }
2056
2057       continue;
2058     }
2059
2060     InitCounter();
2061
2062     if (options.tape_log_filename != NULL)
2063       OpenTapeLogfile();
2064
2065     TapeStartGamePlaying();
2066     TapeStartWarpForward(global.autoplay_mode);
2067
2068     autoplay.last_level_nr = level_nr;
2069
2070     return num_tapes;
2071   }
2072
2073   if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
2074   {
2075     Print("\n");
2076     PrintLine("=", 79);
2077
2078     if (num_tapes >= 0)
2079       Print("SUMMARY: %d tapes uploaded.\n", num_tapes);
2080     else
2081       Print("SUMMARY: Uploading tapes failed.\n");
2082
2083     PrintLine("=", 79);
2084   }
2085
2086   // clear timestamp for batch tape upload (required after interactive upload)
2087   global.autoplay_time = 0;
2088
2089   // exit if running headless or if visually auto-playing tapes
2090   if (program.headless || global.autoplay_mode != AUTOPLAY_MODE_UPLOAD)
2091     CloseAllAndExit(0);
2092
2093   // when running interactively, restore last selected level set and number
2094   leveldir_current = leveldir_current_last;
2095   level_nr = level_nr_last;
2096
2097   return num_tapes;
2098 }
2099
2100 int AutoPlayTapes(void)
2101 {
2102   return AutoPlayTapesExt(TRUE);
2103 }
2104
2105 int AutoPlayTapesContinue(void)
2106 {
2107   return AutoPlayTapesExt(FALSE);
2108 }
2109
2110
2111 // ----------------------------------------------------------------------------
2112 // tape patch functions
2113 // ----------------------------------------------------------------------------
2114
2115 static boolean PatchTape(struct TapeInfo *tape, char *mode)
2116 {
2117   Print("[%d.%d.%d.%d]: ",
2118         (tape->engine_version / 1000000) % 100,
2119         (tape->engine_version / 10000  ) % 100,
2120         (tape->engine_version / 100    ) % 100,
2121         (tape->engine_version          ) % 100);
2122
2123   if (strEqual(mode, "info"))
2124   {
2125     Print("property bits == 0x%02x\n", tape->property_bits);
2126
2127     return FALSE;
2128   }
2129
2130   boolean unpatch_tape = FALSE;
2131   boolean use_property_bit = FALSE;
2132   byte property_bitmask = 0;
2133
2134   if (strSuffix(mode, ":0") ||
2135       strSuffix(mode, ":off") ||
2136       strSuffix(mode, ":clear"))
2137     unpatch_tape = TRUE;
2138
2139   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
2140   {
2141     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
2142     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
2143         tape->engine_version >= VERSION_IDENT(4,0,1,2))
2144     {
2145       Print("This tape version cannot be patched against EM random bug!\n");
2146
2147       return FALSE;
2148     }
2149
2150     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
2151
2152     use_property_bit = TRUE;
2153   }
2154   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
2155   {
2156     // this bug only affects team mode tapes
2157     if (tape->num_participating_players == 1)
2158     {
2159       Print("Only team mode tapes can be patched against screen size bug!\n");
2160
2161       return FALSE;
2162     }
2163
2164     // this bug (that always existed before) was fixed in version 4.2.2.1
2165     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
2166     {
2167       Print("This tape version cannot be patched against screen size bug!\n");
2168
2169       return FALSE;
2170     }
2171
2172     int factor = (unpatch_tape ? 1 : 2);
2173     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
2174     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
2175
2176     if (scr_fieldx_new == tape->scr_fieldx &&
2177         scr_fieldy_new == tape->scr_fieldy)
2178     {
2179       Print("Tape already patched for '%s'!\n", mode);
2180
2181       return FALSE;
2182     }
2183
2184     tape->scr_fieldx = scr_fieldx_new;
2185     tape->scr_fieldy = scr_fieldy_new;
2186   }
2187   else
2188   {
2189     Print("Unknown patch mode '%s'!\n", mode);
2190
2191     return FALSE;
2192   }
2193
2194   // patching tapes using property bits may be used for several patch modes
2195   if (use_property_bit)
2196   {
2197     byte property_bits = tape->property_bits;
2198     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
2199
2200     if (set_property_bit)
2201       property_bits |= property_bitmask;
2202     else
2203       property_bits &= ~property_bitmask;
2204
2205     if (property_bits == tape->property_bits)
2206     {
2207       Print("Tape already patched for '%s'!\n", mode);
2208
2209       return FALSE;
2210     }
2211
2212     tape->property_bits = property_bits;
2213   }
2214
2215   Print("Patching for '%s' ... ", mode);
2216
2217   return TRUE;
2218 }
2219
2220 void PatchTapes(void)
2221 {
2222   static LevelDirTree *patchtapes_leveldir = NULL;
2223   static int num_tapes_found = 0;
2224   static int num_tapes_patched = 0;
2225   char *mode = global.patchtapes_mode;
2226   int i;
2227
2228   if (strEqual(mode, "help"))
2229   {
2230     PrintLine("=", 79);
2231     Print("Supported patch modes:\n");
2232     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
2233     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
2234     PrintLine("-", 79);
2235     Print("Supported modifiers:\n");
2236     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
2237     PrintLine("=", 79);
2238
2239     CloseAllAndExit(0);
2240   }
2241
2242   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
2243                                                   global.patchtapes_leveldir);
2244
2245   if (patchtapes_leveldir == NULL)
2246     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
2247
2248   leveldir_current = patchtapes_leveldir;
2249
2250   if (patchtapes_leveldir->first_level < 0)
2251     patchtapes_leveldir->first_level = 0;
2252   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
2253     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
2254
2255   PrintLine("=", 79);
2256   Print("Patching level tapes for patch mode '%s'\n", mode);
2257   PrintLine("-", 79);
2258   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
2259   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
2260   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
2261   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
2262   PrintLine("=", 79);
2263   Print("\n");
2264
2265   int first_level = patchtapes_leveldir->first_level;
2266   int last_level = patchtapes_leveldir->last_level;
2267
2268   for (i = first_level; i <= last_level; i++)
2269   {
2270     if (!global.patchtapes_all && !global.patchtapes_level[i])
2271       continue;
2272
2273     Print("Tape %03d: ", i);
2274
2275     TapeErase();
2276     LoadTape(i);
2277
2278     if (tape.no_valid_file)
2279     {
2280       Print("(no tape found)\n");
2281
2282       continue;
2283     }
2284
2285     num_tapes_found++;
2286
2287     if (PatchTape(&tape, mode))
2288     {
2289       char *filename = getTapeFilename(i);
2290       char *filename_orig = getStringCat2(filename, ".orig");
2291
2292       if (!fileExists(filename_orig))
2293         rename(filename, filename_orig);
2294
2295       SaveTapeToFilename(filename);
2296
2297       Print("patched tape saved.\n");
2298
2299       num_tapes_patched++;
2300     }
2301   }
2302
2303   Print("\n");
2304   PrintLine("=", 79);
2305   Print("Number of tapes found: %d\n", num_tapes_found);
2306   Print("Number of tapes patched: %d\n", num_tapes_patched);
2307   PrintLine("=", 79);
2308
2309   CloseAllAndExit(0);
2310 }
2311
2312
2313 // ---------- new tape button stuff -------------------------------------------
2314
2315 static struct
2316 {
2317   int graphic;
2318   struct XY *pos;
2319   int gadget_id;
2320   char *infotext;
2321 } tapebutton_info[NUM_TAPE_BUTTONS] =
2322 {
2323   {
2324     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
2325     TAPE_CTRL_ID_EJECT,                 "eject tape"
2326   },
2327   {
2328     // (same position as "eject" button)
2329     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
2330     TAPE_CTRL_ID_EXTRA,                 "extra functions"
2331   },
2332   {
2333     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
2334     TAPE_CTRL_ID_STOP,                  "stop tape"
2335   },
2336   {
2337     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
2338     TAPE_CTRL_ID_PAUSE,                 "pause tape"
2339   },
2340   {
2341     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
2342     TAPE_CTRL_ID_RECORD,                "record tape"
2343   },
2344   {
2345     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
2346     TAPE_CTRL_ID_PLAY,                  "play tape"
2347   },
2348   {
2349     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
2350     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
2351   },
2352   {
2353     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
2354     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
2355   }
2356 };
2357
2358 void CreateTapeButtons(void)
2359 {
2360   int i;
2361
2362   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2363   {
2364     int graphic = tapebutton_info[i].graphic;
2365     struct GraphicInfo *gfx = &graphic_info[graphic];
2366     struct XY *pos = tapebutton_info[i].pos;
2367     struct GadgetInfo *gi;
2368     int gd_x = gfx->src_x;
2369     int gd_y = gfx->src_y;
2370     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
2371     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
2372     int id = i;
2373
2374     gi = CreateGadget(GDI_CUSTOM_ID, id,
2375                       GDI_IMAGE_ID, graphic,
2376                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
2377                       GDI_X, VX + pos->x,
2378                       GDI_Y, VY + pos->y,
2379                       GDI_WIDTH, gfx->width,
2380                       GDI_HEIGHT, gfx->height,
2381                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
2382                       GDI_STATE, GD_BUTTON_UNPRESSED,
2383                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
2384                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
2385                       GDI_DIRECT_DRAW, FALSE,
2386                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
2387                       GDI_CALLBACK_ACTION, HandleTapeButtons,
2388                       GDI_END);
2389
2390     if (gi == NULL)
2391       Fail("cannot create gadget");
2392
2393     tape_gadget[id] = gi;
2394   }
2395 }
2396
2397 void FreeTapeButtons(void)
2398 {
2399   int i;
2400
2401   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2402     FreeGadget(tape_gadget[i]);
2403 }
2404
2405 void MapTapeEjectButton(void)
2406 {
2407   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2408   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2409 }
2410
2411 void MapTapeWarpButton(void)
2412 {
2413   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2414   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2415 }
2416
2417 void MapTapeButtons(void)
2418 {
2419   int i;
2420
2421   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2422     if (i != TAPE_CTRL_ID_EXTRA)
2423       MapGadget(tape_gadget[i]);
2424
2425   if (tape.recording || tape.playing)
2426     MapTapeWarpButton();
2427
2428   if (tape.show_game_buttons)
2429     MapGameButtonsOnTape();
2430 }
2431
2432 void UnmapTapeButtons(void)
2433 {
2434   int i;
2435
2436   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2437     UnmapGadget(tape_gadget[i]);
2438
2439   if (tape.show_game_buttons)
2440     UnmapGameButtonsOnTape();
2441 }
2442
2443 void RedrawTapeButtons(void)
2444 {
2445   int i;
2446
2447   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2448     RedrawGadget(tape_gadget[i]);
2449
2450   if (tape.show_game_buttons)
2451     RedrawGameButtonsOnTape();
2452 }
2453
2454 void RedrawOrRemapTapeButtons(void)
2455 {
2456   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
2457   {
2458     // tape buttons already mapped
2459     RedrawTapeButtons();
2460   }
2461   else
2462   {
2463     UnmapTapeButtons();
2464     MapTapeButtons();
2465   }
2466 }
2467
2468 static void HandleTapeButtonsExt(int id)
2469 {
2470   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
2471     return;
2472
2473   switch (id)
2474   {
2475     case TAPE_CTRL_ID_EJECT:
2476       TapeStop();
2477
2478       if (TAPE_IS_EMPTY(tape))
2479       {
2480         LoadTape(level_nr);
2481
2482         if (TAPE_IS_EMPTY(tape))
2483           Request("No tape for this level!", REQ_CONFIRM);
2484       }
2485       else
2486       {
2487         if (tape.changed)
2488           SaveTapeChecked(level_nr);
2489
2490         TapeErase();
2491       }
2492
2493       DrawCompleteVideoDisplay();
2494       break;
2495
2496     case TAPE_CTRL_ID_EXTRA:
2497       if (tape.playing)
2498       {
2499         tape.pause_before_end = !tape.pause_before_end;
2500
2501         DrawVideoDisplayCurrentState();
2502       }
2503       else if (tape.recording)
2504       {
2505         TapeSingleStep();
2506       }
2507
2508       break;
2509
2510     case TAPE_CTRL_ID_STOP:
2511       TapeStopTape();
2512
2513       break;
2514
2515     case TAPE_CTRL_ID_PAUSE:
2516       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2517
2518       break;
2519
2520     case TAPE_CTRL_ID_RECORD:
2521       if (TAPE_IS_STOPPED(tape))
2522       {
2523         TapeStartGameRecording();
2524       }
2525       else if (tape.pausing)
2526       {
2527         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2528           TapeAppendRecording();
2529         else
2530           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2531       }
2532
2533       break;
2534
2535     case TAPE_CTRL_ID_PLAY:
2536       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2537       {
2538         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2539
2540         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2541       }
2542
2543       if (TAPE_IS_EMPTY(tape))
2544         break;
2545
2546       if (TAPE_IS_STOPPED(tape))
2547       {
2548         TapeStartGamePlaying();
2549       }
2550       else if (tape.playing)
2551       {
2552         if (tape.pausing)                       // PAUSE -> PLAY
2553         {
2554           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2555         }
2556         else if (!tape.fast_forward)            // PLAY -> FFWD
2557         {
2558           tape.fast_forward = TRUE;
2559         }
2560         else if (!tape.warp_forward)            // FFWD -> WARP
2561         {
2562           tape.warp_forward = TRUE;
2563         }
2564         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2565         {
2566           tape.deactivate_display = TRUE;
2567
2568           TapeDeactivateDisplayOn();
2569         }
2570         else                                    // WARP BLIND -> PLAY
2571         {
2572           tape.fast_forward = FALSE;
2573           tape.warp_forward = FALSE;
2574           tape.deactivate_display = FALSE;
2575
2576           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2577         }
2578
2579         DrawVideoDisplayCurrentState();
2580       }
2581
2582       break;
2583
2584     case TAPE_CTRL_ID_INSERT_SOLUTION:
2585       InsertSolutionTape();
2586
2587       break;
2588
2589     case TAPE_CTRL_ID_PLAY_SOLUTION:
2590       PlaySolutionTape();
2591
2592       break;
2593
2594     default:
2595       break;
2596   }
2597 }
2598
2599 static void HandleTapeButtons(struct GadgetInfo *gi)
2600 {
2601   HandleTapeButtonsExt(gi->custom_id);
2602 }
2603
2604 void HandleTapeButtonKeys(Key key)
2605 {
2606   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2607   boolean extra_button_is_active = !eject_button_is_active;
2608
2609   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2610     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2611   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2612     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2613   else if (key == setup.shortcut.tape_stop)
2614     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2615   else if (key == setup.shortcut.tape_pause)
2616     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2617   else if (key == setup.shortcut.tape_record)
2618     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2619   else if (key == setup.shortcut.tape_play)
2620     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2621 }