added option to write tape log file (for high score server)
[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 = (value / 100) % 100;
316       int month = month_index + 1;
317       int day = value % 100;
318
319       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
320                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
321                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
322                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
323                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
324
325       DrawText(xpos, ypos, s, pos->font);
326     }
327     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
328     {
329       char s[MAX_DATETIME_STRING_SIZE];
330       int hh = (value / 3600) % 100;
331       int min = value / 60;
332       int mm = (value / 60) % 60;
333       int ss = value % 60;
334
335       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
336                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
337                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
338                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
339
340       DrawText(xpos, ypos, s, pos->font);
341     }
342     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
343     {
344       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
345     }
346   }
347 }
348
349 void DrawVideoDisplay(unsigned int state, unsigned int value)
350 {
351   DrawVideoDisplay_Graphics(state, value);
352   DrawVideoDisplay_DateTime(state, value);
353 }
354
355 static void DrawVideoDisplayLabel(unsigned int state)
356 {
357   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
358 }
359
360 static void DrawVideoDisplaySymbol(unsigned int state)
361 {
362   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
363 }
364
365 static void DrawVideoDisplayCurrentState(void)
366 {
367   int state = 0;
368
369   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
370
371   if (tape.pausing)
372     state |= VIDEO_STATE_PAUSE_ON;
373
374   if (tape.recording)
375   {
376     state |= VIDEO_STATE_REC_ON;
377
378     if (tape.single_step)
379       state |= VIDEO_STATE_1STEP_ON;
380   }
381   else if (tape.playing)
382   {
383     state |= VIDEO_STATE_PLAY_ON;
384
385     if (!tape.pausing)
386     {
387       if (tape.deactivate_display)
388         state |= VIDEO_STATE_WARP2_ON;
389       else if (tape.warp_forward)
390         state |= VIDEO_STATE_WARP_ON;
391       else if (tape.fast_forward)
392         state |= VIDEO_STATE_FFWD_ON;
393
394       if (tape.pause_before_end)
395         state |= VIDEO_STATE_PBEND_ON;
396     }
397   }
398
399   // draw labels and symbols separately to prevent labels overlapping symbols
400   DrawVideoDisplayLabel(state);
401   DrawVideoDisplaySymbol(state);
402 }
403
404 void DrawCompleteVideoDisplay(void)
405 {
406   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
407
408   // draw tape background
409   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
410              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
411
412   // draw tape buttons (forced)
413   RedrawOrRemapTapeButtons();
414
415   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
416
417   if (tape.recording)
418   {
419     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
420     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
421     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
422     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
423
424     if (tape.pausing)
425       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
426   }
427   else if (tape.playing)
428   {
429     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
430     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
431     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
432     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
433
434     if (tape.pausing)
435       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
436   }
437   else if (tape.date && tape.length)
438   {
439     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
440     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
441     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
442   }
443
444   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
445              0, 0);
446 }
447
448 void TapeDeactivateDisplayOn(void)
449 {
450   SetDrawDeactivationMask(REDRAW_FIELD);
451   audio.sound_deactivated = TRUE;
452 }
453
454 void TapeDeactivateDisplayOff(boolean redraw_display)
455 {
456   SetDrawDeactivationMask(REDRAW_NONE);
457   audio.sound_deactivated = FALSE;
458
459   if (redraw_display)
460   {
461     RedrawPlayfield();
462
463     UpdateGameDoorValues();
464     DrawGameDoorValues();
465   }
466 }
467
468
469 // ============================================================================
470 // tape logging functions
471 // ============================================================================
472
473 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
474
475 static void PrintTapeReplayProgress(boolean replay_finished)
476 {
477   static unsigned int counter_last = -1;
478   unsigned int counter = Counter();
479   unsigned int counter_seconds  = counter / 1000;
480
481   if (!replay_finished)
482   {
483     unsigned int counter_delay = 50;
484
485     if (counter > counter_last + counter_delay)
486     {
487       PrintNoLog("\r");
488       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
489                  level_nr,  tape_patch_info,
490                  tape.length_seconds / 60, tape.length_seconds % 60,
491                  TapeTime / 60, TapeTime % 60);
492
493       counter_last = counter;
494     }
495   }
496   else
497   {
498     float tape_length_seconds = GetTapeLengthSecondsFloat();
499
500     PrintNoLog("\r");
501     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
502           level_nr, tape_patch_info,
503           tape.length_seconds / 60, tape.length_seconds % 60,
504           counter_seconds / 60, counter_seconds % 60, counter % 1000,
505           (float)counter / tape_length_seconds / 10,
506           tape.auto_play_level_fixed ? "solved and fixed" :
507           tape.auto_play_level_solved ? "solved" :
508           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
509           "NOT SOLVED");
510
511     counter_last = -1;
512   }
513 }
514
515 static FILE *tape_log_file;
516
517 static void OpenTapeLogfile(void)
518 {
519   if (!(tape_log_file = fopen(options.tape_log_filename, MODE_WRITE)))
520     Warn("cannot write tape logfile '%s'", options.tape_log_filename);
521 }
522
523 static void WriteTapeLogfile(byte action[MAX_TAPE_ACTIONS])
524 {
525   int i;
526
527   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
528     putFile8Bit(tape_log_file, action[i]);
529 }
530
531 static void CloseTapeLogfile(void)
532 {
533   fclose(tape_log_file);
534 }
535
536
537 // ============================================================================
538 // tape control functions
539 // ============================================================================
540
541 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
542 {
543   struct tm *lt = localtime(&epoch_seconds);
544
545   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
546 }
547
548 void TapeSetDateFromNow(void)
549 {
550   TapeSetDateFromEpochSeconds(time(NULL));
551 }
552
553 void TapeErase(void)
554 {
555   int i;
556
557   CopyTapeToUndoBuffer();
558
559   tape.counter = 0;
560   tape.length = 0;
561   tape.length_frames = 0;
562   tape.length_seconds = 0;
563
564   tape.score_tape_basename[0] = '\0';
565
566   if (leveldir_current)
567   {
568     strncpy(tape.level_identifier, leveldir_current->identifier,
569             MAX_FILENAME_LEN);
570     tape.level_identifier[MAX_FILENAME_LEN] = '\0';
571   }
572
573   tape.level_nr = level_nr;
574   tape.pos[tape.counter].delay = 0;
575   tape.changed = TRUE;
576
577   tape.random_seed = InitRND(level.random_seed);
578
579   tape.file_version = FILE_VERSION_ACTUAL;
580   tape.game_version = GAME_VERSION_ACTUAL;
581   tape.engine_version = level.game_version;
582
583   TapeSetDateFromNow();
584
585   for (i = 0; i < MAX_PLAYERS; i++)
586     tape.player_participates[i] = FALSE;
587
588   tape.centered_player_nr_next = -1;
589   tape.set_centered_player = FALSE;
590
591   // set flags for game actions to default values (may be overwritten later)
592   tape.use_key_actions = TRUE;
593   tape.use_mouse_actions = FALSE;
594 }
595
596 static void TapeRewind(void)
597 {
598   tape.counter = 0;
599   tape.delay_played = 0;
600   tape.pause_before_end = FALSE;
601   tape.recording = FALSE;
602   tape.playing = FALSE;
603   tape.fast_forward = FALSE;
604   tape.warp_forward = FALSE;
605   tape.deactivate_display = FALSE;
606   tape.auto_play = (global.autoplay_leveldir != NULL);
607   tape.auto_play_level_solved = FALSE;
608   tape.auto_play_level_fixed = FALSE;
609   tape.auto_play_level_not_fixable = FALSE;
610   tape.quick_resume = FALSE;
611   tape.single_step = FALSE;
612
613   tape.centered_player_nr_next = -1;
614   tape.set_centered_player = FALSE;
615
616   InitRND(tape.random_seed);
617 }
618
619 static void TapeSetRandomSeed(int random_seed)
620 {
621   tape.random_seed = InitRND(random_seed);
622 }
623
624 void TapeStartRecording(int random_seed)
625 {
626   if (!TAPE_IS_STOPPED(tape))
627     TapeStop();
628
629   TapeErase();
630   TapeRewind();
631   TapeSetRandomSeed(random_seed);
632
633   tape.recording = TRUE;
634
635   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
636   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
637   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
638   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
639
640   MapTapeWarpButton();
641
642   SetDrawDeactivationMask(REDRAW_NONE);
643   audio.sound_deactivated = FALSE;
644
645   // required here to update video display if tape door is closed
646   if (GetDoorState() & DOOR_CLOSE_2)
647     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
648 }
649
650 static void TapeStartGameRecording(void)
651 {
652   StartGameActions(network.enabled, TRUE, level.random_seed);
653 }
654
655 static void TapeAppendRecording(void)
656 {
657   if (!tape.playing || !tape.pausing)
658     return;
659
660   // stop playing
661   tape.playing = FALSE;
662   tape.fast_forward = FALSE;
663   tape.warp_forward = FALSE;
664   tape.pause_before_end = FALSE;
665   tape.deactivate_display = FALSE;
666
667   // start recording
668   tape.recording = TRUE;
669   tape.changed = TRUE;
670
671   // set current delay (for last played move)
672   tape.pos[tape.counter].delay = tape.delay_played;
673
674   // set current date
675   TapeSetDateFromNow();
676
677   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
678   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
679
680   UpdateAndDisplayGameControlValues();
681 }
682
683 void TapeHaltRecording(void)
684 {
685   tape.counter++;
686
687   // initialize delay for next tape entry (to be able to continue recording)
688   if (tape.counter < MAX_TAPE_LEN)
689     tape.pos[tape.counter].delay = 0;
690
691   tape.length = tape.counter;
692   tape.length_frames = GetTapeLengthFrames();
693   tape.length_seconds = GetTapeLengthSeconds();
694 }
695
696 void TapeStopRecording(void)
697 {
698   if (tape.recording)
699     TapeHaltRecording();
700
701   tape.recording = FALSE;
702   tape.pausing = FALSE;
703
704   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
705   MapTapeEjectButton();
706 }
707
708 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
709 {
710   int i;
711
712   if (tape.pos[tape.counter].delay > 0)         // already stored action
713   {
714     boolean changed_events = FALSE;
715
716     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
717       if (tape.pos[tape.counter].action[i] != action[i])
718         changed_events = TRUE;
719
720     if (changed_events || tape.pos[tape.counter].delay >= 255)
721     {
722       if (tape.counter >= MAX_TAPE_LEN - 1)
723         return FALSE;
724
725       tape.counter++;
726       tape.pos[tape.counter].delay = 0;
727     }
728     else
729       tape.pos[tape.counter].delay++;
730   }
731
732   if (tape.pos[tape.counter].delay == 0)        // store new action
733   {
734     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
735       tape.pos[tape.counter].action[i] = action[i];
736
737     tape.pos[tape.counter].delay++;
738   }
739
740   return TRUE;
741 }
742
743 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
744 {
745   byte action[MAX_TAPE_ACTIONS];
746   int i;
747
748   if (!tape.recording)          // (record action even when tape is paused)
749     return;
750
751   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
752     action[i] = action_raw[i];
753
754   if (tape.use_key_actions && tape.set_centered_player)
755   {
756     for (i = 0; i < MAX_PLAYERS; i++)
757       if (tape.centered_player_nr_next == i ||
758           tape.centered_player_nr_next == -1)
759         action[i] |= KEY_SET_FOCUS;
760
761     tape.set_centered_player = FALSE;
762   }
763
764   if (!TapeAddAction(action))
765     TapeStopRecording();
766 }
767
768 void TapeTogglePause(boolean toggle_mode)
769 {
770   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
771   {
772     // continue playing in normal mode
773     tape.fast_forward = FALSE;
774     tape.warp_forward = FALSE;
775     tape.deactivate_display = FALSE;
776
777     tape.pause_before_end = FALSE;
778   }
779
780   tape.pausing = !tape.pausing;
781
782   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
783     tape.single_step = FALSE;
784
785   DrawVideoDisplayCurrentState();
786
787   if (tape.deactivate_display)
788   {
789     if (tape.pausing)
790       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
791     else
792       TapeDeactivateDisplayOn();
793   }
794
795   if (tape.quick_resume)
796   {
797     tape.quick_resume = FALSE;
798
799     TapeStopWarpForward();
800     TapeAppendRecording();
801
802     if (!CheckEngineSnapshotSingle())
803       SaveEngineSnapshotSingle();
804
805     // restart step/move snapshots after quick loading tape
806     SaveEngineSnapshotToListInitial();
807
808     // do not map undo/redo buttons after quick loading tape
809     return;
810   }
811
812   if (game_status == GAME_MODE_PLAYING)
813   {
814     if (setup.show_snapshot_buttons && CheckEngineSnapshotList())
815     {
816       if (tape.pausing)
817         MapUndoRedoButtons();
818       else if (!tape.single_step)
819         UnmapUndoRedoButtons();
820     }
821
822     ModifyPauseButtons();
823   }
824 }
825
826 void TapeStartPlaying(void)
827 {
828   if (TAPE_IS_EMPTY(tape))
829     return;
830
831   if (!TAPE_IS_STOPPED(tape))
832     TapeStop();
833
834   TapeRewind();
835
836   tape.playing = TRUE;
837
838   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
839   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
840   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
841   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
842
843   MapTapeWarpButton();
844
845   SetDrawDeactivationMask(REDRAW_NONE);
846   audio.sound_deactivated = FALSE;
847 }
848
849 static void TapeStartGamePlaying(void)
850 {
851   TapeStartPlaying();
852
853   InitGame();
854 }
855
856 void TapeStopPlaying(void)
857 {
858   tape.playing = FALSE;
859   tape.pausing = FALSE;
860
861   if (tape.warp_forward)
862     TapeStopWarpForward();
863
864   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
865   MapTapeEjectButton();
866 }
867
868 byte *TapePlayAction(void)
869 {
870   int update_delay = FRAMES_PER_SECOND / 2;
871   boolean update_video_display = (FrameCounter % update_delay == 0);
872   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
873   static byte action[MAX_TAPE_ACTIONS];
874   int i;
875
876   if (!tape.playing || tape.pausing)
877     return NULL;
878
879   if (tape.pause_before_end)  // stop some seconds before end of tape
880   {
881     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
882     {
883       TapeStopWarpForward();
884       TapeTogglePause(TAPE_TOGGLE_MANUAL);
885
886       return NULL;
887     }
888   }
889
890   if (tape.counter >= tape.length)      // end of tape reached
891   {
892     if (tape.warp_forward && !tape.auto_play)
893     {
894       TapeStopWarpForward();
895       TapeTogglePause(TAPE_TOGGLE_MANUAL);
896     }
897     else
898     {
899       TapeStop();
900     }
901
902     return NULL;
903   }
904
905   if (update_video_display && !tape.deactivate_display)
906   {
907     int state = 0;
908
909     if (tape.warp_forward)
910       state |= VIDEO_STATE_WARP(update_draw_label_on);
911     else if (tape.fast_forward)
912       state |= VIDEO_STATE_FFWD(update_draw_label_on);
913
914     if (tape.pause_before_end)
915       state |= VIDEO_STATE_PBEND(update_draw_label_on);
916
917     // draw labels and symbols separately to prevent labels overlapping symbols
918     DrawVideoDisplayLabel(state);
919     DrawVideoDisplaySymbol(state);
920   }
921
922   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
923     action[i] = tape.pos[tape.counter].action[i];
924
925 #if DEBUG_TAPE_WHEN_PLAYING
926   DebugContinued("", "%05d", FrameCounter);
927   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
928     DebugContinued("", "   %08x", action[i]);
929   DebugContinued("tape:play", "\n");
930 #endif
931
932   tape.set_centered_player = FALSE;
933   tape.centered_player_nr_next = -999;
934
935   if (tape.use_key_actions)
936   {
937     for (i = 0; i < MAX_PLAYERS; i++)
938     {
939       if (action[i] & KEY_SET_FOCUS)
940       {
941         tape.set_centered_player = TRUE;
942         tape.centered_player_nr_next =
943           (tape.centered_player_nr_next == -999 ? i : -1);
944       }
945
946       action[i] &= ~KEY_SET_FOCUS;
947     }
948   }
949
950   tape.delay_played++;
951   if (tape.delay_played >= tape.pos[tape.counter].delay)
952   {
953     tape.counter++;
954     tape.delay_played = 0;
955   }
956
957   if (tape.auto_play)
958     PrintTapeReplayProgress(FALSE);
959
960   if (options.tape_log_filename != NULL)
961     WriteTapeLogfile(action);
962
963   return action;
964 }
965
966 void TapeStop(void)
967 {
968   if (tape.pausing)
969     TapeTogglePause(TAPE_TOGGLE_MANUAL);
970
971   TapeStopRecording();
972   TapeStopPlaying();
973
974   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
975
976   if (tape.date && tape.length)
977   {
978     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
979     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
980     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
981   }
982 }
983
984 unsigned int GetTapeLengthFrames(void)
985 {
986   unsigned int tape_length_frames = 0;
987   int i;
988
989   if (TAPE_IS_EMPTY(tape))
990     return 0;
991
992   for (i = 0; i < tape.length; i++)
993     tape_length_frames += tape.pos[i].delay;
994
995   return tape_length_frames;
996 }
997
998 unsigned int GetTapeLengthSeconds(void)
999 {
1000   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1001 }
1002
1003 static float GetTapeLengthSecondsFloat(void)
1004 {
1005   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1006 }
1007
1008 static void TapeStartWarpForward(int mode)
1009 {
1010   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1011   tape.warp_forward = (mode & AUTOPLAY_WARP);
1012   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1013
1014   tape.pausing = FALSE;
1015
1016   if (tape.deactivate_display)
1017     TapeDeactivateDisplayOn();
1018
1019   DrawVideoDisplayCurrentState();
1020 }
1021
1022 static void TapeStopWarpForward(void)
1023 {
1024   tape.fast_forward = FALSE;
1025   tape.warp_forward = FALSE;
1026   tape.deactivate_display = FALSE;
1027
1028   tape.pause_before_end = FALSE;
1029
1030   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1031
1032   DrawVideoDisplayCurrentState();
1033 }
1034
1035 static void TapeSingleStep(void)
1036 {
1037   if (network.enabled)
1038     return;
1039
1040   if (!tape.pausing)
1041     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1042
1043   tape.single_step = !tape.single_step;
1044
1045   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1046 }
1047
1048 void TapeQuickSave(void)
1049 {
1050   if (game_status == GAME_MODE_MAIN)
1051   {
1052     Request("No game that can be saved!", REQ_CONFIRM);
1053
1054     return;
1055   }
1056
1057   if (game_status != GAME_MODE_PLAYING)
1058     return;
1059
1060   if (tape.recording)
1061     TapeHaltRecording();        // prepare tape for saving on-the-fly
1062
1063   if (TAPE_IS_EMPTY(tape))
1064   {
1065     Request("No tape that can be saved!", REQ_CONFIRM);
1066
1067     return;
1068   }
1069
1070   if (SaveTapeChecked(tape.level_nr))
1071     SaveEngineSnapshotSingle();
1072 }
1073
1074 void TapeQuickLoad(void)
1075 {
1076   char *filename = getTapeFilename(level_nr);
1077
1078   if (!fileExists(filename))
1079   {
1080     Request("No tape for this level!", REQ_CONFIRM);
1081
1082     return;
1083   }
1084
1085   if (tape.recording && !Request("Stop recording and load tape?",
1086                                  REQ_ASK | REQ_STAY_CLOSED))
1087   {
1088     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1089
1090     return;
1091   }
1092
1093   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1094     return;
1095
1096   if (CheckEngineSnapshotSingle())
1097   {
1098     TapeStartGamePlaying();
1099
1100     LoadEngineSnapshotSingle();
1101
1102     DrawCompleteVideoDisplay();
1103
1104     tape.playing = TRUE;
1105     tape.pausing = TRUE;
1106
1107     TapeStopWarpForward();
1108     TapeAppendRecording();
1109
1110     // restart step/move snapshots after quick loading tape
1111     SaveEngineSnapshotToListInitial();
1112
1113     if (FrameCounter > 0)
1114       return;
1115   }
1116
1117   TapeStop();
1118   TapeErase();
1119
1120   LoadTape(level_nr);
1121
1122   if (!TAPE_IS_EMPTY(tape))
1123   {
1124     TapeStartGamePlaying();
1125     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1126
1127     tape.quick_resume = TRUE;
1128   }
1129   else  // this should not happen (basically checked above)
1130   {
1131     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1132
1133     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1134   }
1135 }
1136
1137 boolean hasSolutionTape(void)
1138 {
1139   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1140   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1141                             level.native_sp_level->demo.is_available);
1142
1143   return (tape_file_exists || level_has_tape);
1144 }
1145
1146 boolean InsertSolutionTape(void)
1147 {
1148   if (!hasSolutionTape())
1149   {
1150     Request("No solution tape for this level!", REQ_CONFIRM);
1151
1152     return FALSE;
1153   }
1154
1155   if (!TAPE_IS_STOPPED(tape))
1156     TapeStop();
1157
1158   // if tape recorder already contains a tape, remove it without asking
1159   TapeErase();
1160
1161   LoadSolutionTape(level_nr);
1162
1163   DrawCompleteVideoDisplay();
1164
1165   if (TAPE_IS_EMPTY(tape))
1166   {
1167     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1168
1169     return FALSE;
1170   }
1171
1172   return TRUE;
1173 }
1174
1175 boolean PlaySolutionTape(void)
1176 {
1177   if (!InsertSolutionTape())
1178     return FALSE;
1179
1180   TapeStartGamePlaying();
1181
1182   return TRUE;
1183 }
1184
1185 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1186 {
1187   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1188           t1->level_nr == t2->level_nr);
1189 }
1190
1191 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1192 {
1193   *tape_to = *tape_from;
1194 }
1195
1196 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1197 {
1198   struct TapeInfo tmp = *t1;
1199
1200   *t1 = *t2;
1201   *t2 = tmp;
1202 }
1203
1204 static void CopyTapeToUndoBuffer(void)
1205 {
1206   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1207   // or if the last undo tape is from a different level set or level number
1208   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1209       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1210       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1211   {
1212     CopyTape(&tape, &tape_undo_buffer);
1213   }
1214 }
1215
1216 void UndoTape(void)
1217 {
1218   // only undo tapes from same level set and with same level number
1219   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1220     return;
1221
1222   if (!TAPE_IS_STOPPED(tape))
1223     TapeStop();
1224
1225   // swap last recorded tape with undo buffer, so undo can be reversed
1226   SwapTapes(&tape, &tape_undo_buffer);
1227
1228   DrawCompleteVideoDisplay();
1229 }
1230
1231 void FixTape_ForceSinglePlayer(void)
1232 {
1233   int i;
1234
1235   /* fix single-player tapes that contain player input for more than one
1236      player (due to a bug in 3.3.1.2 and earlier versions), which results
1237      in playing levels with more than one player in multi-player mode,
1238      even though the tape was originally recorded in single-player mode */
1239
1240   // remove player input actions for all players but the first one
1241   for (i = 1; i < MAX_PLAYERS; i++)
1242     tape.player_participates[i] = FALSE;
1243
1244   tape.changed = TRUE;
1245 }
1246
1247
1248 // ----------------------------------------------------------------------------
1249 // tape autoplay functions
1250 // ----------------------------------------------------------------------------
1251
1252 void AutoPlayTapes(void)
1253 {
1254   static LevelDirTree *autoplay_leveldir = NULL;
1255   static boolean autoplay_initialized = FALSE;
1256   static int autoplay_last_level_nr = -1;
1257   static int autoplay_level_nr = -1;
1258   static int num_levels_played = 0;
1259   static int num_levels_solved = 0;
1260   static int num_tapes_patched = 0;
1261   static int num_tape_missing = 0;
1262   static boolean level_failed[MAX_TAPES_PER_SET];
1263   static char *tape_filename = NULL;
1264   static int patch_nr = 0;
1265   static char *patch_name[] =
1266   {
1267     "original tape",
1268     "em_random_bug",
1269     "screen_34x34",
1270
1271     NULL
1272   };
1273   static int patch_version_first[] =
1274   {
1275     VERSION_IDENT(0,0,0,0),
1276     VERSION_IDENT(3,3,1,0),
1277     VERSION_IDENT(0,0,0,0),
1278
1279     -1
1280   };
1281   static int patch_version_last[] =
1282   {
1283     VERSION_IDENT(9,9,9,9),
1284     VERSION_IDENT(4,0,1,1),
1285     VERSION_IDENT(4,2,2,0),
1286
1287     -1
1288   };
1289   static byte patch_property_bit[] =
1290   {
1291     TAPE_PROPERTY_NONE,
1292     TAPE_PROPERTY_EM_RANDOM_BUG,
1293     TAPE_PROPERTY_NONE,
1294
1295     -1
1296   };
1297   int i;
1298
1299   if (autoplay_initialized)
1300   {
1301     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1302     {
1303       if (tape.auto_play_level_solved)
1304       {
1305         if (patch_nr > 0)
1306         {
1307           // level solved by patched tape -- save fixed tape
1308           char *filename = getTapeFilename(level_nr);
1309           char *filename_orig = getStringCat2(filename, ".orig");
1310
1311           // create backup from old tape, if not yet existing
1312           if (!fileExists(filename_orig))
1313             rename(filename, filename_orig);
1314
1315           SaveTapeToFilename(filename);
1316
1317           tape.auto_play_level_fixed = TRUE;
1318           num_tapes_patched++;
1319         }
1320
1321         // continue with next tape
1322         patch_nr = 0;
1323       }
1324       else if (patch_name[patch_nr + 1] != NULL)
1325       {
1326         // level not solved by patched tape -- continue with next patch
1327         patch_nr++;
1328       }
1329       else
1330       {
1331         // level not solved by any patched tape -- continue with next tape
1332         tape.auto_play_level_not_fixable = TRUE;
1333         patch_nr = 0;
1334       }
1335     }
1336
1337     // just finished auto-playing tape
1338     PrintTapeReplayProgress(TRUE);
1339
1340     if (options.tape_log_filename != NULL)
1341       CloseTapeLogfile();
1342
1343     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1344         tape.auto_play_level_solved)
1345     {
1346       // set unique basename for score tape (for uploading to score server)
1347       strcpy(tape.score_tape_basename, getScoreTapeBasename(setup.player_name));
1348
1349       // store score in first score entry
1350       scores.last_added = 0;
1351
1352       struct ScoreEntry *entry = &scores.entry[scores.last_added];
1353
1354       strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1355       strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1356
1357       entry->score = game.score_final;
1358       entry->time = game.score_time_final;
1359
1360       if (leveldir_current)
1361       {
1362         // the tape's level set identifier may differ from current level set
1363         strncpy(tape.level_identifier, leveldir_current->identifier,
1364                 MAX_FILENAME_LEN);
1365         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1366
1367         // the tape's level number may differ from current level number
1368         tape.level_nr = level_nr;
1369       }
1370
1371       PrintNoLog("- uploading score tape to score server ... ");
1372
1373       server_scores.uploaded = FALSE;
1374
1375       // temporarily save score tape (as the tape filename is unknown here)
1376       SaveScoreTape(level_nr);
1377       SaveServerScore(level_nr);
1378
1379       unsigned int upload_delay = 0;
1380       unsigned int upload_delay_value = 10000;
1381
1382       ResetDelayCounter(&upload_delay);
1383
1384       // wait for score tape to be successfully uploaded (and fail on timeout)
1385       while (!server_scores.uploaded)
1386       {
1387         if (DelayReached(&upload_delay, upload_delay_value))
1388         {
1389           PrintNoLog("\r");
1390           Print("- uploading score tape to score server - TIMEOUT.\n");
1391
1392           Fail("cannot upload score tape to score server");
1393         }
1394
1395         Delay(20);
1396       }
1397
1398       PrintNoLog("\r");
1399       Print("- uploading score tape to score server - uploaded.\n");
1400     }
1401
1402     if (patch_nr == 0)
1403       num_levels_played++;
1404
1405     if (tape.auto_play_level_solved)
1406       num_levels_solved++;
1407
1408     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1409       level_failed[level_nr] = !tape.auto_play_level_solved;
1410   }
1411   else
1412   {
1413     DrawCompleteVideoDisplay();
1414
1415     audio.sound_enabled = FALSE;
1416     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1417
1418     if (strSuffix(global.autoplay_leveldir, ".tape"))
1419     {
1420       tape_filename = global.autoplay_leveldir;
1421
1422       LoadTapeFromFilename(tape_filename);
1423
1424       global.autoplay_leveldir = tape.level_identifier;
1425
1426       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1427         global.autoplay_level[tape.level_nr] = TRUE;
1428
1429       global.autoplay_all = FALSE;
1430     }
1431
1432     autoplay_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1433                                                   global.autoplay_leveldir);
1434
1435     if (autoplay_leveldir == NULL)
1436       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1437
1438     leveldir_current = autoplay_leveldir;
1439
1440     if (autoplay_leveldir->first_level < 0)
1441       autoplay_leveldir->first_level = 0;
1442     if (autoplay_leveldir->last_level >= MAX_TAPES_PER_SET)
1443       autoplay_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1444
1445     autoplay_level_nr = autoplay_leveldir->first_level;
1446
1447     PrintLine("=", 79);
1448     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1449       Print("Automatically fixing level tapes\n");
1450     else
1451       Print("Automatically playing level tapes\n");
1452     PrintLine("-", 79);
1453     Print("Level series identifier: '%s'\n", autoplay_leveldir->identifier);
1454     Print("Level series name:       '%s'\n", autoplay_leveldir->name);
1455     Print("Level series author:     '%s'\n", autoplay_leveldir->author);
1456     Print("Number of levels:        %d\n",   autoplay_leveldir->levels);
1457     PrintLine("=", 79);
1458     Print("\n");
1459
1460     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1461       level_failed[i] = FALSE;
1462
1463     // only private tapes may be modified
1464     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1465       options.mytapes = TRUE;
1466
1467     autoplay_initialized = TRUE;
1468   }
1469
1470   while (1)
1471   {
1472     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1473       level_nr = autoplay_level_nr++;
1474
1475     if (level_nr > autoplay_leveldir->last_level)
1476       break;
1477
1478     // set patch info (required for progress output)
1479     strcpy(tape_patch_info, "");
1480     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1481       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1482                patch_name[patch_nr]);
1483
1484     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1485       continue;
1486
1487     TapeErase();
1488
1489     LoadLevel(level_nr);
1490
1491     if (level.no_level_file || level.no_valid_file)
1492     {
1493       Print("Tape %03d: (no level found)\n", level_nr);
1494
1495       continue;
1496     }
1497
1498 #if 0
1499     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1500     Print("Tape %03d: (only testing level)\n", level_nr);
1501     continue;
1502 #endif
1503
1504     if (tape_filename)
1505       LoadTapeFromFilename(tape_filename);
1506     else if (options.mytapes)
1507       LoadTape(level_nr);
1508     else
1509       LoadSolutionTape(level_nr);
1510
1511     if (tape.no_valid_file)
1512     {
1513       num_tape_missing++;
1514
1515       Print("Tape %03d: (no tape found)\n", level_nr);
1516
1517       continue;
1518     }
1519
1520     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1521     {
1522       boolean skip_patch = FALSE;
1523
1524       if (tape.engine_version < patch_version_first[patch_nr] ||
1525           tape.engine_version > patch_version_last[patch_nr])
1526       {
1527         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1528               level_nr,  tape_patch_info,
1529               tape.length_seconds / 60, tape.length_seconds % 60,
1530               "not suitable for version",
1531               (tape.engine_version / 1000000) % 100,
1532               (tape.engine_version / 10000  ) % 100,
1533               (tape.engine_version / 100    ) % 100,
1534               (tape.engine_version          ) % 100);
1535
1536         skip_patch = TRUE;
1537       }
1538
1539       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1540           tape.num_participating_players == 1)
1541       {
1542         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1543               level_nr,  tape_patch_info,
1544               tape.length_seconds / 60, tape.length_seconds % 60,
1545               "not suitable for single player tapes");
1546
1547         skip_patch = TRUE;
1548       }
1549
1550       if (skip_patch)
1551       {
1552         if (patch_name[patch_nr + 1] != NULL)
1553         {
1554           // continue with next patch
1555           patch_nr++;
1556         }
1557         else
1558         {
1559           // continue with next tape
1560           patch_nr = 0;
1561         }
1562
1563         continue;
1564       }
1565
1566       if (strEqual(patch_name[patch_nr], "screen_34x34"))
1567       {
1568         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
1569         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
1570       }
1571       else
1572       {
1573         tape.property_bits |= patch_property_bit[patch_nr];
1574       }
1575     }
1576
1577     InitCounter();
1578
1579     if (options.tape_log_filename != NULL)
1580       OpenTapeLogfile();
1581
1582     TapeStartGamePlaying();
1583     TapeStartWarpForward(global.autoplay_mode);
1584
1585     autoplay_last_level_nr = level_nr;
1586
1587     return;
1588   }
1589
1590   char *autoplay_status = (num_levels_played == num_levels_solved &&
1591                            num_levels_played > 0 ? " OK " : "WARN");
1592   int autoplay_percent = (num_levels_played ?
1593                           num_levels_solved * 100 / num_levels_played : 0);
1594
1595   Print("\n");
1596   PrintLine("=", 79);
1597   Print("Number of levels played: %d\n", num_levels_played);
1598   Print("Number of levels solved: %d (%d%%)\n", num_levels_solved,
1599         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1600   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1601     Print("Number of tapes fixed: %d\n", num_tapes_patched);
1602   PrintLine("-", 79);
1603   Print("Summary (for automatic parsing by scripts):\n");
1604
1605   if (tape_filename)
1606   {
1607     Print("TAPEFILE [%s] '%s', %d, %d, %d",
1608           autoplay_status,
1609           autoplay_leveldir->identifier,
1610           autoplay_last_level_nr,
1611           game.score_final,
1612           game.score_time_final);
1613   }
1614   else
1615   {
1616     Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
1617           autoplay_status,
1618           autoplay_leveldir->identifier,
1619           num_levels_solved,
1620           num_levels_played,
1621           autoplay_percent);
1622
1623     if (num_levels_played != num_levels_solved)
1624     {
1625       Print(", FAILED:");
1626       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1627         if (level_failed[i])
1628           Print(" %03d", i);
1629     }
1630   }
1631
1632   Print("\n");
1633   PrintLine("=", 79);
1634
1635   CloseAllAndExit(0);
1636 }
1637
1638
1639 // ----------------------------------------------------------------------------
1640 // tape patch functions
1641 // ----------------------------------------------------------------------------
1642
1643 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1644 {
1645   Print("[%d.%d.%d.%d]: ",
1646         (tape->engine_version / 1000000) % 100,
1647         (tape->engine_version / 10000  ) % 100,
1648         (tape->engine_version / 100    ) % 100,
1649         (tape->engine_version          ) % 100);
1650
1651   if (strEqual(mode, "info"))
1652   {
1653     Print("property bits == 0x%02x\n", tape->property_bits);
1654
1655     return FALSE;
1656   }
1657
1658   boolean unpatch_tape = FALSE;
1659   boolean use_property_bit = FALSE;
1660   byte property_bitmask = 0;
1661
1662   if (strSuffix(mode, ":0") ||
1663       strSuffix(mode, ":off") ||
1664       strSuffix(mode, ":clear"))
1665     unpatch_tape = TRUE;
1666
1667   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1668   {
1669     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1670     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1671         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1672     {
1673       Print("This tape version cannot be patched against EM random bug!\n");
1674
1675       return FALSE;
1676     }
1677
1678     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1679
1680     use_property_bit = TRUE;
1681   }
1682   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
1683   {
1684     // this bug only affects team mode tapes
1685     if (tape->num_participating_players == 1)
1686     {
1687       Print("Only team mode tapes can be patched against screen size bug!\n");
1688
1689       return FALSE;
1690     }
1691
1692     // this bug (that always existed before) was fixed in version 4.2.2.1
1693     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
1694     {
1695       Print("This tape version cannot be patched against screen size bug!\n");
1696
1697       return FALSE;
1698     }
1699
1700     int factor = (unpatch_tape ? 1 : 2);
1701     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
1702     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
1703
1704     if (scr_fieldx_new == tape->scr_fieldx &&
1705         scr_fieldy_new == tape->scr_fieldy)
1706     {
1707       Print("Tape already patched for '%s'!\n", mode);
1708
1709       return FALSE;
1710     }
1711
1712     tape->scr_fieldx = scr_fieldx_new;
1713     tape->scr_fieldy = scr_fieldy_new;
1714   }
1715   else
1716   {
1717     Print("Unknown patch mode '%s'!\n", mode);
1718
1719     return FALSE;
1720   }
1721
1722   // patching tapes using property bits may be used for several patch modes
1723   if (use_property_bit)
1724   {
1725     byte property_bits = tape->property_bits;
1726     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
1727
1728     if (set_property_bit)
1729       property_bits |= property_bitmask;
1730     else
1731       property_bits &= ~property_bitmask;
1732
1733     if (property_bits == tape->property_bits)
1734     {
1735       Print("Tape already patched for '%s'!\n", mode);
1736
1737       return FALSE;
1738     }
1739
1740     tape->property_bits = property_bits;
1741   }
1742
1743   Print("Patching for '%s' ... ", mode);
1744
1745   return TRUE;
1746 }
1747
1748 void PatchTapes(void)
1749 {
1750   static LevelDirTree *patchtapes_leveldir = NULL;
1751   static int num_tapes_found = 0;
1752   static int num_tapes_patched = 0;
1753   char *mode = global.patchtapes_mode;
1754   int i;
1755
1756   if (strEqual(mode, "help"))
1757   {
1758     PrintLine("=", 79);
1759     Print("Supported patch modes:\n");
1760     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1761     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
1762     PrintLine("-", 79);
1763     Print("Supported modifiers:\n");
1764     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1765     PrintLine("=", 79);
1766
1767     CloseAllAndExit(0);
1768   }
1769
1770   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1771                                                   global.patchtapes_leveldir);
1772
1773   if (patchtapes_leveldir == NULL)
1774     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
1775
1776   leveldir_current = patchtapes_leveldir;
1777
1778   if (patchtapes_leveldir->first_level < 0)
1779     patchtapes_leveldir->first_level = 0;
1780   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1781     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1782
1783   PrintLine("=", 79);
1784   Print("Patching level tapes for patch mode '%s'\n", mode);
1785   PrintLine("-", 79);
1786   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1787   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1788   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1789   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1790   PrintLine("=", 79);
1791   Print("\n");
1792
1793   int first_level = patchtapes_leveldir->first_level;
1794   int last_level = patchtapes_leveldir->last_level;
1795
1796   for (i = first_level; i <= last_level; i++)
1797   {
1798     if (!global.patchtapes_all && !global.patchtapes_level[i])
1799       continue;
1800
1801     Print("Tape %03d: ", i);
1802
1803     TapeErase();
1804     LoadTape(i);
1805
1806     if (tape.no_valid_file)
1807     {
1808       Print("(no tape found)\n");
1809
1810       continue;
1811     }
1812
1813     num_tapes_found++;
1814
1815     if (PatchTape(&tape, mode))
1816     {
1817       char *filename = getTapeFilename(i);
1818       char *filename_orig = getStringCat2(filename, ".orig");
1819
1820       if (!fileExists(filename_orig))
1821         rename(filename, filename_orig);
1822
1823       SaveTapeToFilename(filename);
1824
1825       Print("patched tape saved.\n");
1826
1827       num_tapes_patched++;
1828     }
1829   }
1830
1831   Print("\n");
1832   PrintLine("=", 79);
1833   Print("Number of tapes found: %d\n", num_tapes_found);
1834   Print("Number of tapes patched: %d\n", num_tapes_patched);
1835   PrintLine("=", 79);
1836
1837   CloseAllAndExit(0);
1838 }
1839
1840
1841 // ---------- new tape button stuff -------------------------------------------
1842
1843 static struct
1844 {
1845   int graphic;
1846   struct XY *pos;
1847   int gadget_id;
1848   char *infotext;
1849 } tapebutton_info[NUM_TAPE_BUTTONS] =
1850 {
1851   {
1852     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1853     TAPE_CTRL_ID_EJECT,                 "eject tape"
1854   },
1855   {
1856     // (same position as "eject" button)
1857     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1858     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1859   },
1860   {
1861     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1862     TAPE_CTRL_ID_STOP,                  "stop tape"
1863   },
1864   {
1865     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1866     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1867   },
1868   {
1869     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1870     TAPE_CTRL_ID_RECORD,                "record tape"
1871   },
1872   {
1873     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1874     TAPE_CTRL_ID_PLAY,                  "play tape"
1875   },
1876   {
1877     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1878     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
1879   },
1880   {
1881     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
1882     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
1883   }
1884 };
1885
1886 void CreateTapeButtons(void)
1887 {
1888   int i;
1889
1890   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1891   {
1892     int graphic = tapebutton_info[i].graphic;
1893     struct GraphicInfo *gfx = &graphic_info[graphic];
1894     struct XY *pos = tapebutton_info[i].pos;
1895     struct GadgetInfo *gi;
1896     int gd_x = gfx->src_x;
1897     int gd_y = gfx->src_y;
1898     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1899     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1900     int id = i;
1901
1902     gi = CreateGadget(GDI_CUSTOM_ID, id,
1903                       GDI_IMAGE_ID, graphic,
1904                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
1905                       GDI_X, VX + pos->x,
1906                       GDI_Y, VY + pos->y,
1907                       GDI_WIDTH, gfx->width,
1908                       GDI_HEIGHT, gfx->height,
1909                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
1910                       GDI_STATE, GD_BUTTON_UNPRESSED,
1911                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
1912                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
1913                       GDI_DIRECT_DRAW, FALSE,
1914                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
1915                       GDI_CALLBACK_ACTION, HandleTapeButtons,
1916                       GDI_END);
1917
1918     if (gi == NULL)
1919       Fail("cannot create gadget");
1920
1921     tape_gadget[id] = gi;
1922   }
1923 }
1924
1925 void FreeTapeButtons(void)
1926 {
1927   int i;
1928
1929   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1930     FreeGadget(tape_gadget[i]);
1931 }
1932
1933 void MapTapeEjectButton(void)
1934 {
1935   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1936   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1937 }
1938
1939 void MapTapeWarpButton(void)
1940 {
1941   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1942   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1943 }
1944
1945 void MapTapeButtons(void)
1946 {
1947   int i;
1948
1949   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1950     if (i != TAPE_CTRL_ID_EXTRA)
1951       MapGadget(tape_gadget[i]);
1952
1953   if (tape.recording || tape.playing)
1954     MapTapeWarpButton();
1955
1956   if (tape.show_game_buttons)
1957     MapGameButtonsOnTape();
1958 }
1959
1960 void UnmapTapeButtons(void)
1961 {
1962   int i;
1963
1964   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1965     UnmapGadget(tape_gadget[i]);
1966
1967   if (tape.show_game_buttons)
1968     UnmapGameButtonsOnTape();
1969 }
1970
1971 void RedrawTapeButtons(void)
1972 {
1973   int i;
1974
1975   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1976     RedrawGadget(tape_gadget[i]);
1977
1978   if (tape.show_game_buttons)
1979     RedrawGameButtonsOnTape();
1980 }
1981
1982 void RedrawOrRemapTapeButtons(void)
1983 {
1984   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
1985   {
1986     // tape buttons already mapped
1987     RedrawTapeButtons();
1988   }
1989   else
1990   {
1991     UnmapTapeButtons();
1992     MapTapeButtons();
1993   }
1994 }
1995
1996 static void HandleTapeButtonsExt(int id)
1997 {
1998   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
1999     return;
2000
2001   switch (id)
2002   {
2003     case TAPE_CTRL_ID_EJECT:
2004       TapeStop();
2005
2006       if (TAPE_IS_EMPTY(tape))
2007       {
2008         LoadTape(level_nr);
2009
2010         if (TAPE_IS_EMPTY(tape))
2011           Request("No tape for this level!", REQ_CONFIRM);
2012       }
2013       else
2014       {
2015         if (tape.changed)
2016           SaveTapeChecked(level_nr);
2017
2018         TapeErase();
2019       }
2020
2021       DrawCompleteVideoDisplay();
2022       break;
2023
2024     case TAPE_CTRL_ID_EXTRA:
2025       if (tape.playing)
2026       {
2027         tape.pause_before_end = !tape.pause_before_end;
2028
2029         DrawVideoDisplayCurrentState();
2030       }
2031       else if (tape.recording)
2032       {
2033         TapeSingleStep();
2034       }
2035
2036       break;
2037
2038     case TAPE_CTRL_ID_STOP:
2039       TapeStop();
2040
2041       break;
2042
2043     case TAPE_CTRL_ID_PAUSE:
2044       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2045
2046       break;
2047
2048     case TAPE_CTRL_ID_RECORD:
2049       if (TAPE_IS_STOPPED(tape))
2050       {
2051         TapeStartGameRecording();
2052       }
2053       else if (tape.pausing)
2054       {
2055         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2056           TapeAppendRecording();
2057         else
2058           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2059       }
2060
2061       break;
2062
2063     case TAPE_CTRL_ID_PLAY:
2064       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2065       {
2066         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2067
2068         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2069       }
2070
2071       if (TAPE_IS_EMPTY(tape))
2072         break;
2073
2074       if (TAPE_IS_STOPPED(tape))
2075       {
2076         TapeStartGamePlaying();
2077       }
2078       else if (tape.playing)
2079       {
2080         if (tape.pausing)                       // PAUSE -> PLAY
2081         {
2082           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2083         }
2084         else if (!tape.fast_forward)            // PLAY -> FFWD
2085         {
2086           tape.fast_forward = TRUE;
2087         }
2088         else if (!tape.warp_forward)            // FFWD -> WARP
2089         {
2090           tape.warp_forward = TRUE;
2091         }
2092         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2093         {
2094           tape.deactivate_display = TRUE;
2095
2096           TapeDeactivateDisplayOn();
2097         }
2098         else                                    // WARP BLIND -> PLAY
2099         {
2100           tape.fast_forward = FALSE;
2101           tape.warp_forward = FALSE;
2102           tape.deactivate_display = FALSE;
2103
2104           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2105         }
2106
2107         DrawVideoDisplayCurrentState();
2108       }
2109
2110       break;
2111
2112     case TAPE_CTRL_ID_INSERT_SOLUTION:
2113       InsertSolutionTape();
2114
2115       break;
2116
2117     case TAPE_CTRL_ID_PLAY_SOLUTION:
2118       PlaySolutionTape();
2119
2120       break;
2121
2122     default:
2123       break;
2124   }
2125 }
2126
2127 static void HandleTapeButtons(struct GadgetInfo *gi)
2128 {
2129   HandleTapeButtonsExt(gi->custom_id);
2130 }
2131
2132 void HandleTapeButtonKeys(Key key)
2133 {
2134   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2135   boolean extra_button_is_active = !eject_button_is_active;
2136
2137   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2138     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2139   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2140     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2141   else if (key == setup.shortcut.tape_stop)
2142     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2143   else if (key == setup.shortcut.tape_pause)
2144     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2145   else if (key == setup.shortcut.tape_record)
2146     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2147   else if (key == setup.shortcut.tape_play)
2148     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2149 }