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