renamed playfield variable
[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
39 // forward declaration for internal use
40 static void HandleTapeButtons(struct GadgetInfo *);
41 static void TapeStopWarpForward(void);
42 static float GetTapeLengthSecondsFloat(void);
43
44 static struct GadgetInfo *tape_gadget[NUM_TAPE_BUTTONS];
45
46
47 // ============================================================================
48 // video tape definitions
49 // ============================================================================
50
51 #define VIDEO_INFO_OFF                  (VIDEO_STATE_DATE_OFF   |       \
52                                          VIDEO_STATE_TIME_OFF   |       \
53                                          VIDEO_STATE_FRAME_OFF)
54 #define VIDEO_STATE_OFF                 (VIDEO_STATE_PLAY_OFF   |       \
55                                          VIDEO_STATE_REC_OFF    |       \
56                                          VIDEO_STATE_PAUSE_OFF  |       \
57                                          VIDEO_STATE_FFWD_OFF   |       \
58                                          VIDEO_STATE_WARP_OFF   |       \
59                                          VIDEO_STATE_WARP2_OFF  |       \
60                                          VIDEO_STATE_PBEND_OFF  |       \
61                                          VIDEO_STATE_1STEP_OFF)
62 #define VIDEO_PRESS_OFF                 (VIDEO_PRESS_PLAY_OFF   |       \
63                                          VIDEO_PRESS_REC_OFF    |       \
64                                          VIDEO_PRESS_PAUSE_OFF  |       \
65                                          VIDEO_PRESS_STOP_OFF   |       \
66                                          VIDEO_PRESS_EJECT_OFF)
67 #define VIDEO_ALL_OFF                   (VIDEO_INFO_OFF         |       \
68                                          VIDEO_STATE_OFF        |       \
69                                          VIDEO_PRESS_OFF)
70
71 #define VIDEO_INFO_ON                   (VIDEO_STATE_DATE_ON    |       \
72                                          VIDEO_STATE_TIME_ON    |       \
73                                          VIDEO_STATE_FRAME_ON)
74 #define VIDEO_STATE_ON                  (VIDEO_STATE_PLAY_ON    |       \
75                                          VIDEO_STATE_REC_ON     |       \
76                                          VIDEO_STATE_PAUSE_ON   |       \
77                                          VIDEO_STATE_FFWD_ON    |       \
78                                          VIDEO_STATE_WARP_ON    |       \
79                                          VIDEO_STATE_WARP2_ON   |       \
80                                          VIDEO_STATE_PBEND_ON   |       \
81                                          VIDEO_STATE_1STEP_ON)
82 #define VIDEO_PRESS_ON                  (VIDEO_PRESS_PLAY_ON    |       \
83                                          VIDEO_PRESS_REC_ON     |       \
84                                          VIDEO_PRESS_PAUSE_ON   |       \
85                                          VIDEO_PRESS_STOP_ON    |       \
86                                          VIDEO_PRESS_EJECT_ON)
87 #define VIDEO_ALL_ON                    (VIDEO_INFO_ON          |       \
88                                          VIDEO_STATE_ON         |       \
89                                          VIDEO_PRESS_ON)
90
91 #define VIDEO_INFO                      (VIDEO_INFO_ON | VIDEO_INFO_OFF)
92 #define VIDEO_STATE                     (VIDEO_STATE_ON | VIDEO_STATE_OFF)
93 #define VIDEO_PRESS                     (VIDEO_PRESS_ON | VIDEO_PRESS_OFF)
94 #define VIDEO_ALL                       (VIDEO_ALL_ON | VIDEO_ALL_OFF)
95
96 #define NUM_TAPE_FUNCTIONS              11
97 #define NUM_TAPE_FUNCTION_PARTS         2
98 #define NUM_TAPE_FUNCTION_STATES        2
99
100
101 // ============================================================================
102 // video display functions
103 // ============================================================================
104
105 static void DrawVideoDisplay_Graphics(unsigned int state, unsigned int value)
106 {
107   int i, j, k;
108
109   static struct
110   {
111     int graphic;
112     struct XY *pos;
113   }
114   video_pos[NUM_TAPE_FUNCTIONS][NUM_TAPE_FUNCTION_PARTS] =
115   {
116     {
117       { IMG_GFX_TAPE_LABEL_PLAY,                &tape.label.play        },
118       { IMG_GFX_TAPE_SYMBOL_PLAY,               &tape.symbol.play       },
119     },
120     {
121       { IMG_GFX_TAPE_LABEL_RECORD,              &tape.label.record      },
122       { IMG_GFX_TAPE_SYMBOL_RECORD,             &tape.symbol.record     },
123     },
124     {
125       { IMG_GFX_TAPE_LABEL_PAUSE,               &tape.label.pause       },
126       { IMG_GFX_TAPE_SYMBOL_PAUSE,              &tape.symbol.pause      },
127     },
128     {
129       { IMG_GFX_TAPE_LABEL_DATE,                &tape.label.date        },
130       { -1,                                     NULL                    },
131     },
132     {
133       { IMG_GFX_TAPE_LABEL_TIME,                &tape.label.time        },
134       { -1,                                     NULL                    },
135     },
136     {
137       // (no label for displaying optional frame)
138       { -1,                                     NULL                    },
139       { -1,                                     NULL                    },
140     },
141     {
142       { IMG_GFX_TAPE_LABEL_FAST_FORWARD,        &tape.label.fast_forward  },
143       { IMG_GFX_TAPE_SYMBOL_FAST_FORWARD,       &tape.symbol.fast_forward },
144     },
145     {
146       { IMG_GFX_TAPE_LABEL_WARP_FORWARD,        &tape.label.warp_forward  },
147       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD,       &tape.symbol.warp_forward },
148     },
149     {
150       { IMG_GFX_TAPE_LABEL_WARP_FORWARD_BLIND,  &tape.label.warp_forward_blind},
151       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD_BLIND, &tape.symbol.warp_forward_blind},
152     },
153     {
154       { IMG_GFX_TAPE_LABEL_PAUSE_BEFORE_END,    &tape.label.pause_before_end  },
155       { IMG_GFX_TAPE_SYMBOL_PAUSE_BEFORE_END,   &tape.symbol.pause_before_end },
156     },
157     {
158       { IMG_GFX_TAPE_LABEL_SINGLE_STEP,         &tape.label.single_step  },
159       { IMG_GFX_TAPE_SYMBOL_SINGLE_STEP,        &tape.symbol.single_step },
160     },
161   };
162
163   for (k = 0; k < NUM_TAPE_FUNCTION_STATES; k++)        // on or off states
164   {
165     for (i = 0; i < NUM_TAPE_FUNCTIONS; i++)            // record, play, ...
166     {
167       for (j = 0; j < NUM_TAPE_FUNCTION_PARTS; j++)     // label or symbol
168       {
169         int graphic = video_pos[i][j].graphic;
170         struct XY *pos = video_pos[i][j].pos;
171
172         if (graphic == -1 ||
173             pos->x == -1 ||
174             pos->y == -1)
175           continue;
176
177         if (state & (1 << (i * 2 + k)))
178         {
179           struct GraphicInfo *gfx_bg = &graphic_info[IMG_BACKGROUND_TAPE];
180           struct GraphicInfo *gfx = &graphic_info[graphic];
181           Bitmap *gd_bitmap;
182           int gd_x, gd_y;
183           int skip_value =
184             (j == 0 ? VIDEO_DISPLAY_SYMBOL_ONLY : VIDEO_DISPLAY_LABEL_ONLY);
185
186           if (value == skip_value)
187             continue;
188
189           if (k == 1)           // on
190           {
191             gd_bitmap = gfx->bitmap;
192             gd_x = gfx->src_x;
193             gd_y = gfx->src_y;
194           }
195           else                  // off
196           {
197             gd_bitmap = gfx_bg->bitmap;
198             gd_x = gfx_bg->src_x + pos->x;
199             gd_y = gfx_bg->src_y + pos->y;
200           }
201
202           // some tape graphics may be undefined -- only draw if defined
203           if (gd_bitmap != NULL)
204             BlitBitmap(gd_bitmap, drawto, gd_x, gd_y, gfx->width, gfx->height,
205                        VX + pos->x, VY + pos->y);
206
207           redraw_mask |= REDRAW_DOOR_2;
208         }
209       }
210     }
211   }
212 }
213
214
215 #define DATETIME_NONE                   (0)
216
217 #define DATETIME_DATE_YYYY              (1 << 0)
218 #define DATETIME_DATE_YY                (1 << 1)
219 #define DATETIME_DATE_MON               (1 << 2)
220 #define DATETIME_DATE_MM                (1 << 3)
221 #define DATETIME_DATE_DD                (1 << 4)
222
223 #define DATETIME_TIME_HH                (1 << 5)
224 #define DATETIME_TIME_MIN               (1 << 6)
225 #define DATETIME_TIME_MM                (1 << 7)
226 #define DATETIME_TIME_SS                (1 << 8)
227
228 #define DATETIME_FRAME                  (1 << 9)
229
230 #define DATETIME_XOFFSET_1              (1 << 10)
231 #define DATETIME_XOFFSET_2              (1 << 11)
232
233 #define DATETIME_DATE                   (DATETIME_DATE_YYYY     |       \
234                                          DATETIME_DATE_YY       |       \
235                                          DATETIME_DATE_MON      |       \
236                                          DATETIME_DATE_MM       |       \
237                                          DATETIME_DATE_DD)
238
239 #define DATETIME_TIME                   (DATETIME_TIME_HH       |       \
240                                          DATETIME_TIME_MIN      |       \
241                                          DATETIME_TIME_MM       |       \
242                                          DATETIME_TIME_SS)
243
244 #define MAX_DATETIME_STRING_SIZE        32
245
246 static void DrawVideoDisplay_DateTime(unsigned int state, unsigned int value)
247 {
248   int i;
249
250   static char *month_shortnames[] =
251   {
252     "JAN",
253     "FEB",
254     "MAR",
255     "APR",
256     "MAY",
257     "JUN",
258     "JUL",
259     "AUG",
260     "SEP",
261     "OCT",
262     "NOV",
263     "DEC"
264   };
265
266   static struct
267   {
268     struct TextPosInfo *pos;
269     int type;
270   }
271   datetime_info[] =
272   {
273     { &tape.text.date,          DATETIME_DATE_DD                        },
274     { &tape.text.date,          DATETIME_DATE_MON | DATETIME_XOFFSET_1  },
275     { &tape.text.date,          DATETIME_DATE_YY  | DATETIME_XOFFSET_2  },
276     { &tape.text.date_yyyy,     DATETIME_DATE_YYYY                      },
277     { &tape.text.date_yy,       DATETIME_DATE_YY                        },
278     { &tape.text.date_mon,      DATETIME_DATE_MON                       },
279     { &tape.text.date_mm,       DATETIME_DATE_MM                        },
280     { &tape.text.date_dd,       DATETIME_DATE_DD                        },
281
282     { &tape.text.time,          DATETIME_TIME_MIN                       },
283     { &tape.text.time,          DATETIME_TIME_SS  | DATETIME_XOFFSET_1  },
284     { &tape.text.time_hh,       DATETIME_TIME_HH                        },
285     { &tape.text.time_mm,       DATETIME_TIME_MM                        },
286     { &tape.text.time_ss,       DATETIME_TIME_SS                        },
287
288     { &tape.text.frame,         DATETIME_FRAME                          },
289
290     { NULL,                     DATETIME_NONE                           },
291   };
292
293   for (i = 0; datetime_info[i].pos != NULL; i++)
294   {
295     struct TextPosInfo *pos = datetime_info[i].pos;
296     int type = datetime_info[i].type;
297     int xpos, ypos;
298
299     if (pos->x == -1 &&
300         pos->y == -1)
301       continue;
302
303     xpos = VX + pos->x + (type & DATETIME_XOFFSET_1 ? pos->xoffset  :
304                           type & DATETIME_XOFFSET_2 ? pos->xoffset2 : 0);
305     ypos = VY + pos->y;
306
307     if ((type & DATETIME_DATE) && (state & VIDEO_STATE_DATE_ON))
308     {
309       char s[MAX_DATETIME_STRING_SIZE];
310       int year2 = value / 10000;
311       int year4 = (year2 < 70 ? 2000 + year2 : 1900 + year2);
312       int month_index = (value / 100) % 100;
313       int month = month_index + 1;
314       int day = value % 100;
315
316       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
317                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
318                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
319                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
320                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
321
322       DrawText(xpos, ypos, s, pos->font);
323     }
324     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
325     {
326       char s[MAX_DATETIME_STRING_SIZE];
327       int hh = (value / 3600) % 100;
328       int min = value / 60;
329       int mm = (value / 60) % 60;
330       int ss = value % 60;
331
332       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
333                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
334                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
335                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
336
337       DrawText(xpos, ypos, s, pos->font);
338     }
339     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
340     {
341       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
342     }
343   }
344 }
345
346 void DrawVideoDisplay(unsigned int state, unsigned int value)
347 {
348   DrawVideoDisplay_Graphics(state, value);
349   DrawVideoDisplay_DateTime(state, value);
350 }
351
352 static void DrawVideoDisplayLabel(unsigned int state)
353 {
354   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
355 }
356
357 static void DrawVideoDisplaySymbol(unsigned int state)
358 {
359   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
360 }
361
362 static void DrawVideoDisplayCurrentState(void)
363 {
364   int state = 0;
365
366   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
367
368   if (tape.pausing)
369     state |= VIDEO_STATE_PAUSE_ON;
370
371   if (tape.recording)
372   {
373     state |= VIDEO_STATE_REC_ON;
374
375     if (tape.single_step)
376       state |= VIDEO_STATE_1STEP_ON;
377   }
378   else if (tape.playing)
379   {
380     state |= VIDEO_STATE_PLAY_ON;
381
382     if (!tape.pausing)
383     {
384       if (tape.deactivate_display)
385         state |= VIDEO_STATE_WARP2_ON;
386       else if (tape.warp_forward)
387         state |= VIDEO_STATE_WARP_ON;
388       else if (tape.fast_forward)
389         state |= VIDEO_STATE_FFWD_ON;
390
391       if (tape.pause_before_end)
392         state |= VIDEO_STATE_PBEND_ON;
393     }
394   }
395
396   // draw labels and symbols separately to prevent labels overlapping symbols
397   DrawVideoDisplayLabel(state);
398   DrawVideoDisplaySymbol(state);
399 }
400
401 void DrawCompleteVideoDisplay(void)
402 {
403   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
404
405   // draw tape background
406   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
407              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
408
409   // draw tape buttons (forced)
410   RedrawOrRemapTapeButtons();
411
412   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
413
414   if (tape.recording)
415   {
416     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
417     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
418     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
419     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
420
421     if (tape.pausing)
422       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
423   }
424   else if (tape.playing)
425   {
426     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
427     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
428     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
429     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
430
431     if (tape.pausing)
432       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
433   }
434   else if (tape.date && tape.length)
435   {
436     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
437     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
438     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
439   }
440
441   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
442              0, 0);
443 }
444
445 void TapeDeactivateDisplayOn(void)
446 {
447   SetDrawDeactivationMask(REDRAW_FIELD);
448   audio.sound_deactivated = TRUE;
449 }
450
451 void TapeDeactivateDisplayOff(boolean redraw_display)
452 {
453   SetDrawDeactivationMask(REDRAW_NONE);
454   audio.sound_deactivated = FALSE;
455
456   if (redraw_display)
457   {
458     RedrawPlayfield();
459     DrawGameDoorValues();
460   }
461 }
462
463
464 // ============================================================================
465 // tape logging functions
466 // ============================================================================
467
468 static void PrintTapeReplayProgress(boolean replay_finished)
469 {
470   static unsigned int counter_last = -1;
471   unsigned int counter = Counter();
472   unsigned int counter_seconds  = counter / 1000;
473
474   if (!replay_finished)
475   {
476     unsigned int counter_delay = 50;
477
478     if (counter > counter_last + counter_delay)
479     {
480       PrintNoLog("\r");
481       PrintNoLog("Level %03d [%02d:%02d]: [%02d:%02d] - playing tape ... ",
482                  level_nr, tape.length_seconds / 60, tape.length_seconds % 60,
483                  TapeTime / 60, TapeTime % 60);
484
485       counter_last = counter;
486     }
487   }
488   else
489   {
490     float tape_length_seconds = GetTapeLengthSecondsFloat();
491
492     PrintNoLog("\r");
493     Print("Level %03d [%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
494           level_nr, tape.length_seconds / 60, tape.length_seconds % 60,
495           counter_seconds / 60, counter_seconds % 60, counter % 1000,
496           (float)counter / tape_length_seconds / 10,
497           tape.auto_play_level_solved ? "solved" : "NOT SOLVED");
498
499     counter_last = -1;
500   }
501 }
502
503
504 // ============================================================================
505 // tape control functions
506 // ============================================================================
507
508 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
509 {
510   struct tm *lt = localtime(&epoch_seconds);
511
512   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
513 }
514
515 void TapeSetDateFromNow(void)
516 {
517   TapeSetDateFromEpochSeconds(time(NULL));
518 }
519
520 void TapeErase(void)
521 {
522   int i;
523
524   tape.counter = 0;
525   tape.length = 0;
526   tape.length_frames = 0;
527   tape.length_seconds = 0;
528
529   if (leveldir_current)
530     setString(&tape.level_identifier, leveldir_current->identifier);
531
532   tape.level_nr = level_nr;
533   tape.pos[tape.counter].delay = 0;
534   tape.changed = TRUE;
535
536   tape.random_seed = InitRND(level.random_seed);
537
538   tape.file_version = FILE_VERSION_ACTUAL;
539   tape.game_version = GAME_VERSION_ACTUAL;
540   tape.engine_version = level.game_version;
541
542   TapeSetDateFromNow();
543
544   for (i = 0; i < MAX_PLAYERS; i++)
545     tape.player_participates[i] = FALSE;
546
547   tape.centered_player_nr_next = -1;
548   tape.set_centered_player = FALSE;
549
550   // set flags for game actions to default values (may be overwritten later)
551   tape.use_key_actions = TRUE;
552   tape.use_mouse_actions = FALSE;
553 }
554
555 static void TapeRewind(void)
556 {
557   tape.counter = 0;
558   tape.delay_played = 0;
559   tape.pause_before_end = FALSE;
560   tape.recording = FALSE;
561   tape.playing = FALSE;
562   tape.fast_forward = FALSE;
563   tape.warp_forward = FALSE;
564   tape.deactivate_display = FALSE;
565   tape.auto_play = (global.autoplay_leveldir != NULL);
566   tape.auto_play_level_solved = FALSE;
567   tape.quick_resume = FALSE;
568   tape.single_step = FALSE;
569
570   tape.centered_player_nr_next = -1;
571   tape.set_centered_player = FALSE;
572
573   InitRND(tape.random_seed);
574 }
575
576 static void TapeSetRandomSeed(int random_seed)
577 {
578   tape.random_seed = InitRND(random_seed);
579 }
580
581 void TapeStartRecording(int random_seed)
582 {
583   if (!TAPE_IS_STOPPED(tape))
584     TapeStop();
585
586   TapeErase();
587   TapeRewind();
588   TapeSetRandomSeed(random_seed);
589
590   tape.recording = TRUE;
591
592   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
593   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
594   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
595   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
596
597   MapTapeWarpButton();
598
599   SetDrawDeactivationMask(REDRAW_NONE);
600   audio.sound_deactivated = FALSE;
601
602   // required here to update video display if tape door is closed
603   if (GetDoorState() & DOOR_CLOSE_2)
604     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
605 }
606
607 static void TapeStartGameRecording(void)
608 {
609   StartGameActions(network.enabled, TRUE, level.random_seed);
610 }
611
612 static void TapeAppendRecording(void)
613 {
614   if (!tape.playing || !tape.pausing)
615     return;
616
617   // stop playing
618   tape.playing = FALSE;
619   tape.fast_forward = FALSE;
620   tape.warp_forward = FALSE;
621   tape.pause_before_end = FALSE;
622   tape.deactivate_display = FALSE;
623
624   // start recording
625   tape.recording = TRUE;
626   tape.changed = TRUE;
627
628   // set current delay (for last played move)
629   tape.pos[tape.counter].delay = tape.delay_played;
630
631   // set current date
632   TapeSetDateFromNow();
633
634   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
635   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
636
637   UpdateAndDisplayGameControlValues();
638 }
639
640 void TapeHaltRecording(void)
641 {
642   tape.counter++;
643
644   // initialize delay for next tape entry (to be able to continue recording)
645   if (tape.counter < MAX_TAPE_LEN)
646     tape.pos[tape.counter].delay = 0;
647
648   tape.length = tape.counter;
649   tape.length_frames = GetTapeLengthFrames();
650   tape.length_seconds = GetTapeLengthSeconds();
651 }
652
653 void TapeStopRecording(void)
654 {
655   if (tape.recording)
656     TapeHaltRecording();
657
658   tape.recording = FALSE;
659   tape.pausing = FALSE;
660
661   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
662   MapTapeEjectButton();
663 }
664
665 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
666 {
667   int i;
668
669   if (tape.pos[tape.counter].delay > 0)         // already stored action
670   {
671     boolean changed_events = FALSE;
672
673     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
674       if (tape.pos[tape.counter].action[i] != action[i])
675         changed_events = TRUE;
676
677     if (changed_events || tape.pos[tape.counter].delay >= 255)
678     {
679       if (tape.counter >= MAX_TAPE_LEN - 1)
680         return FALSE;
681
682       tape.counter++;
683       tape.pos[tape.counter].delay = 0;
684     }
685     else
686       tape.pos[tape.counter].delay++;
687   }
688
689   if (tape.pos[tape.counter].delay == 0)        // store new action
690   {
691     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
692       tape.pos[tape.counter].action[i] = action[i];
693
694     tape.pos[tape.counter].delay++;
695   }
696
697   return TRUE;
698 }
699
700 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
701 {
702   byte action[MAX_TAPE_ACTIONS];
703   int i;
704
705   if (!tape.recording)          // (record action even when tape is paused)
706     return;
707
708   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
709     action[i] = action_raw[i];
710
711   if (tape.use_key_actions && tape.set_centered_player)
712   {
713     for (i = 0; i < MAX_PLAYERS; i++)
714       if (tape.centered_player_nr_next == i ||
715           tape.centered_player_nr_next == -1)
716         action[i] |= KEY_SET_FOCUS;
717
718     tape.set_centered_player = FALSE;
719   }
720
721   if (!TapeAddAction(action))
722     TapeStopRecording();
723 }
724
725 void TapeTogglePause(boolean toggle_mode)
726 {
727   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
728   {
729     // continue playing in normal mode
730     tape.fast_forward = FALSE;
731     tape.warp_forward = FALSE;
732     tape.deactivate_display = FALSE;
733
734     tape.pause_before_end = FALSE;
735   }
736
737   tape.pausing = !tape.pausing;
738
739   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
740     tape.single_step = FALSE;
741
742   DrawVideoDisplayCurrentState();
743
744   if (tape.deactivate_display)
745   {
746     if (tape.pausing)
747       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
748     else
749       TapeDeactivateDisplayOn();
750   }
751
752   if (tape.quick_resume)
753   {
754     tape.quick_resume = FALSE;
755
756     TapeStopWarpForward();
757     TapeAppendRecording();
758
759     if (!CheckEngineSnapshotSingle())
760       SaveEngineSnapshotSingle();
761
762     // restart step/move snapshots after quick loading tape
763     SaveEngineSnapshotToListInitial();
764
765     // do not map undo/redo buttons after quick loading tape
766     return;
767   }
768
769   if (game_status == GAME_MODE_PLAYING)
770   {
771     if (setup.show_snapshot_buttons && CheckEngineSnapshotList())
772     {
773       if (tape.pausing)
774         MapUndoRedoButtons();
775       else if (!tape.single_step)
776         UnmapUndoRedoButtons();
777     }
778
779     ModifyPauseButtons();
780   }
781 }
782
783 void TapeStartPlaying(void)
784 {
785   if (TAPE_IS_EMPTY(tape))
786     return;
787
788   if (!TAPE_IS_STOPPED(tape))
789     TapeStop();
790
791   TapeRewind();
792
793   tape.playing = TRUE;
794
795   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
796   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
797   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
798   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
799
800   MapTapeWarpButton();
801
802   SetDrawDeactivationMask(REDRAW_NONE);
803   audio.sound_deactivated = FALSE;
804 }
805
806 static void TapeStartGamePlaying(void)
807 {
808   TapeStartPlaying();
809
810   InitGame();
811 }
812
813 void TapeStopPlaying(void)
814 {
815   tape.playing = FALSE;
816   tape.pausing = FALSE;
817
818   if (tape.warp_forward)
819     TapeStopWarpForward();
820
821   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
822   MapTapeEjectButton();
823 }
824
825 byte *TapePlayAction(void)
826 {
827   int update_delay = FRAMES_PER_SECOND / 2;
828   boolean update_video_display = (FrameCounter % update_delay == 0);
829   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
830   static byte action[MAX_TAPE_ACTIONS];
831   int i;
832
833   if (!tape.playing || tape.pausing)
834     return NULL;
835
836   if (tape.pause_before_end)  // stop some seconds before end of tape
837   {
838     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
839     {
840       TapeStopWarpForward();
841       TapeTogglePause(TAPE_TOGGLE_MANUAL);
842
843       return NULL;
844     }
845   }
846
847   if (tape.counter >= tape.length)      // end of tape reached
848   {
849     if (tape.warp_forward && !tape.auto_play)
850     {
851       TapeStopWarpForward();
852       TapeTogglePause(TAPE_TOGGLE_MANUAL);
853     }
854     else
855     {
856       TapeStop();
857     }
858
859     return NULL;
860   }
861
862   if (update_video_display && !tape.deactivate_display)
863   {
864     int state = 0;
865
866     if (tape.warp_forward)
867       state |= VIDEO_STATE_WARP(update_draw_label_on);
868     else if (tape.fast_forward)
869       state |= VIDEO_STATE_FFWD(update_draw_label_on);
870
871     if (tape.pause_before_end)
872       state |= VIDEO_STATE_PBEND(update_draw_label_on);
873
874     // draw labels and symbols separately to prevent labels overlapping symbols
875     DrawVideoDisplayLabel(state);
876     DrawVideoDisplaySymbol(state);
877   }
878
879   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
880     action[i] = tape.pos[tape.counter].action[i];
881
882 #if DEBUG_TAPE_WHEN_PLAYING
883   printf("%05d", FrameCounter);
884   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
885     printf("   %08x", action[i]);
886   printf("\n");
887 #endif
888
889   tape.set_centered_player = FALSE;
890   tape.centered_player_nr_next = -999;
891
892   if (tape.use_key_actions)
893   {
894     for (i = 0; i < MAX_PLAYERS; i++)
895     {
896       if (action[i] & KEY_SET_FOCUS)
897       {
898         tape.set_centered_player = TRUE;
899         tape.centered_player_nr_next =
900           (tape.centered_player_nr_next == -999 ? i : -1);
901       }
902
903       action[i] &= ~KEY_SET_FOCUS;
904     }
905   }
906
907   tape.delay_played++;
908   if (tape.delay_played >= tape.pos[tape.counter].delay)
909   {
910     tape.counter++;
911     tape.delay_played = 0;
912   }
913
914   if (tape.auto_play)
915     PrintTapeReplayProgress(FALSE);
916
917   return action;
918 }
919
920 void TapeStop(void)
921 {
922   if (tape.pausing)
923     TapeTogglePause(TAPE_TOGGLE_MANUAL);
924
925   TapeStopRecording();
926   TapeStopPlaying();
927
928   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
929
930   if (tape.date && tape.length)
931   {
932     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
933     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
934     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
935   }
936 }
937
938 unsigned int GetTapeLengthFrames(void)
939 {
940   unsigned int tape_length_frames = 0;
941   int i;
942
943   if (TAPE_IS_EMPTY(tape))
944     return(0);
945
946   for (i = 0; i < tape.length; i++)
947     tape_length_frames += tape.pos[i].delay;
948
949   return tape_length_frames;
950 }
951
952 unsigned int GetTapeLengthSeconds(void)
953 {
954   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
955 }
956
957 static float GetTapeLengthSecondsFloat(void)
958 {
959   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
960 }
961
962 static void TapeStartWarpForward(int mode)
963 {
964   tape.fast_forward = (mode & AUTOPLAY_FFWD);
965   tape.warp_forward = (mode & AUTOPLAY_WARP);
966   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
967
968   tape.pausing = FALSE;
969
970   if (tape.deactivate_display)
971     TapeDeactivateDisplayOn();
972
973   DrawVideoDisplayCurrentState();
974 }
975
976 static void TapeStopWarpForward(void)
977 {
978   tape.fast_forward = FALSE;
979   tape.warp_forward = FALSE;
980   tape.deactivate_display = FALSE;
981
982   tape.pause_before_end = FALSE;
983
984   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
985
986   DrawVideoDisplayCurrentState();
987 }
988
989 static void TapeSingleStep(void)
990 {
991   if (network.enabled)
992     return;
993
994   if (!tape.pausing)
995     TapeTogglePause(TAPE_TOGGLE_MANUAL);
996
997   tape.single_step = !tape.single_step;
998
999   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1000 }
1001
1002 void TapeQuickSave(void)
1003 {
1004   if (game_status == GAME_MODE_MAIN)
1005   {
1006     Request("No game that can be saved!", REQ_CONFIRM);
1007
1008     return;
1009   }
1010
1011   if (game_status != GAME_MODE_PLAYING)
1012     return;
1013
1014   if (tape.recording)
1015     TapeHaltRecording();        // prepare tape for saving on-the-fly
1016
1017   if (TAPE_IS_EMPTY(tape))
1018   {
1019     Request("No tape that can be saved!", REQ_CONFIRM);
1020
1021     return;
1022   }
1023
1024   if (SaveTapeChecked(tape.level_nr))
1025     SaveEngineSnapshotSingle();
1026 }
1027
1028 void TapeQuickLoad(void)
1029 {
1030   char *filename = getTapeFilename(level_nr);
1031
1032   if (!fileExists(filename))
1033   {
1034     Request("No tape for this level!", REQ_CONFIRM);
1035
1036     return;
1037   }
1038
1039   if (tape.recording && !Request("Stop recording and load tape?",
1040                                  REQ_ASK | REQ_STAY_CLOSED))
1041   {
1042     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1043
1044     return;
1045   }
1046
1047   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1048     return;
1049
1050   if (CheckEngineSnapshotSingle())
1051   {
1052     TapeStartGamePlaying();
1053
1054     LoadEngineSnapshotSingle();
1055
1056     DrawCompleteVideoDisplay();
1057
1058     tape.playing = TRUE;
1059     tape.pausing = TRUE;
1060
1061     TapeStopWarpForward();
1062     TapeAppendRecording();
1063
1064     // restart step/move snapshots after quick loading tape
1065     SaveEngineSnapshotToListInitial();
1066
1067     if (FrameCounter > 0)
1068       return;
1069   }
1070
1071   TapeStop();
1072   TapeErase();
1073
1074   LoadTape(level_nr);
1075
1076   if (!TAPE_IS_EMPTY(tape))
1077   {
1078     TapeStartGamePlaying();
1079     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1080
1081     tape.quick_resume = TRUE;
1082   }
1083   else  // this should not happen (basically checked above)
1084   {
1085     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1086
1087     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1088   }
1089 }
1090
1091 boolean hasSolutionTape(void)
1092 {
1093   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1094   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1095                             level.native_sp_level->demo.is_available);
1096
1097   return (tape_file_exists || level_has_tape);
1098 }
1099
1100 boolean InsertSolutionTape(void)
1101 {
1102   if (!hasSolutionTape())
1103   {
1104     Request("No solution tape for this level!", REQ_CONFIRM);
1105
1106     return FALSE;
1107   }
1108
1109   if (!TAPE_IS_STOPPED(tape))
1110     TapeStop();
1111
1112   // if tape recorder already contains a tape, remove it without asking
1113   TapeErase();
1114
1115   LoadSolutionTape(level_nr);
1116
1117   DrawCompleteVideoDisplay();
1118
1119   if (TAPE_IS_EMPTY(tape))
1120   {
1121     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1122
1123     return FALSE;
1124   }
1125
1126   return TRUE;
1127 }
1128
1129 boolean PlaySolutionTape(void)
1130 {
1131   if (!InsertSolutionTape())
1132     return FALSE;
1133
1134   TapeStartGamePlaying();
1135
1136   return TRUE;
1137 }
1138
1139
1140 // ----------------------------------------------------------------------------
1141 // tape autoplay functions
1142 // ----------------------------------------------------------------------------
1143
1144 void AutoPlayTape(void)
1145 {
1146   static LevelDirTree *autoplay_leveldir = NULL;
1147   static boolean autoplay_initialized = FALSE;
1148   static int autoplay_level_nr = -1;
1149   static int num_levels_played = 0;
1150   static int num_levels_solved = 0;
1151   static int num_tape_missing = 0;
1152   static boolean level_failed[MAX_TAPES_PER_SET];
1153   int i;
1154
1155   if (autoplay_initialized)
1156   {
1157     // just finished auto-playing tape
1158     PrintTapeReplayProgress(TRUE);
1159
1160     num_levels_played++;
1161
1162     if (tape.auto_play_level_solved)
1163       num_levels_solved++;
1164     else if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1165       level_failed[level_nr] = TRUE;
1166   }
1167   else
1168   {
1169     DrawCompleteVideoDisplay();
1170
1171     audio.sound_enabled = FALSE;
1172     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1173
1174     autoplay_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1175                                                   global.autoplay_leveldir);
1176
1177     if (autoplay_leveldir == NULL)
1178       Error(ERR_EXIT, "no such level identifier: '%s'",
1179             global.autoplay_leveldir);
1180
1181     leveldir_current = autoplay_leveldir;
1182
1183     if (autoplay_leveldir->first_level < 0)
1184       autoplay_leveldir->first_level = 0;
1185     if (autoplay_leveldir->last_level >= MAX_TAPES_PER_SET)
1186       autoplay_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1187
1188     autoplay_level_nr = autoplay_leveldir->first_level;
1189
1190     PrintLine("=", 79);
1191     Print("Automatically playing level tapes\n");
1192     PrintLine("-", 79);
1193     Print("Level series identifier: '%s'\n", autoplay_leveldir->identifier);
1194     Print("Level series name:       '%s'\n", autoplay_leveldir->name);
1195     Print("Level series author:     '%s'\n", autoplay_leveldir->author);
1196     Print("Number of levels:        %d\n",   autoplay_leveldir->levels);
1197     PrintLine("=", 79);
1198     Print("\n");
1199
1200     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1201       level_failed[i] = FALSE;
1202
1203     autoplay_initialized = TRUE;
1204   }
1205
1206   while (autoplay_level_nr <= autoplay_leveldir->last_level)
1207   {
1208     level_nr = autoplay_level_nr++;
1209
1210     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1211       continue;
1212
1213     TapeErase();
1214
1215     LoadLevel(level_nr);
1216
1217     if (level.no_level_file || level.no_valid_file)
1218     {
1219       Print("Level %03d: (no level)\n", level_nr);
1220
1221       continue;
1222     }
1223
1224 #if 0
1225     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1226     Print("Level %03d: (only testing level)\n", level_nr);
1227     continue;
1228 #endif
1229
1230     if (options.mytapes)
1231       LoadTape(level_nr);
1232     else
1233       LoadSolutionTape(level_nr);
1234
1235     if (tape.no_valid_file)
1236     {
1237       num_tape_missing++;
1238
1239       Print("Level %03d: (no tape)\n", level_nr);
1240
1241       continue;
1242     }
1243
1244     InitCounter();
1245
1246     TapeStartGamePlaying();
1247     TapeStartWarpForward(global.autoplay_mode);
1248
1249     return;
1250   }
1251
1252   Print("\n");
1253   PrintLine("=", 79);
1254   Print("Number of levels played: %d\n", num_levels_played);
1255   Print("Number of levels solved: %d (%d%%)\n", num_levels_solved,
1256         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1257   PrintLine("-", 79);
1258   Print("Summary (for automatic parsing by scripts):\n");
1259   Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
1260         (num_levels_played == num_levels_solved ? " OK " : "WARN"),
1261         autoplay_leveldir->identifier, num_levels_solved, num_levels_played,
1262         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1263
1264   if (num_levels_played != num_levels_solved)
1265   {
1266     Print(", FAILED:");
1267     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1268       if (level_failed[i])
1269         Print(" %03d", i);
1270   }
1271
1272   Print("\n");
1273   PrintLine("=", 79);
1274
1275   CloseAllAndExit(0);
1276 }
1277
1278
1279 // ----------------------------------------------------------------------------
1280 // tape patch functions
1281 // ----------------------------------------------------------------------------
1282
1283 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1284 {
1285   Print("[%d.%d.%d.%d]: ",
1286         (tape->engine_version / 1000000) % 100,
1287         (tape->engine_version / 10000  ) % 100,
1288         (tape->engine_version / 100    ) % 100,
1289         (tape->engine_version          ) % 100);
1290
1291   if (strEqual(mode, "info"))
1292   {
1293     Print("property bits == 0x%02x\n", tape->property_bits);
1294
1295     return FALSE;
1296   }
1297
1298   byte property_bits = tape->property_bits;
1299   byte property_bitmask = 0;
1300   boolean set_property_bit = TRUE;
1301
1302   if (strSuffix(mode, ":0") ||
1303       strSuffix(mode, ":off") ||
1304       strSuffix(mode, ":clear"))
1305     set_property_bit = FALSE;
1306
1307   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1308   {
1309     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1310     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1311         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1312     {
1313       Print("This tape version cannot be patched against EM random bug!\n");
1314
1315       return FALSE;
1316     }
1317
1318     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1319   }
1320   else
1321   {
1322     Print("Unknown patch mode '%s'!\n", mode);
1323
1324     return FALSE;
1325   }
1326
1327   if (set_property_bit)
1328     property_bits |= property_bitmask;
1329   else
1330     property_bits &= ~property_bitmask;
1331
1332   if (property_bits == tape->property_bits)
1333   {
1334     Print("Tape already patched for '%s'!\n", mode);
1335
1336     return FALSE;
1337   }
1338
1339   Print("Patching for '%s' ... ", mode);
1340
1341   tape->property_bits = property_bits;
1342
1343   return TRUE;
1344 }
1345
1346 void PatchTapes(void)
1347 {
1348   static LevelDirTree *patchtapes_leveldir = NULL;
1349   static int num_tapes_found = 0;
1350   static int num_tapes_patched = 0;
1351   char *mode = global.patchtapes_mode;
1352   int i;
1353
1354   if (strEqual(mode, "help"))
1355   {
1356     PrintLine("=", 79);
1357     Print("Supported patch modes:\n");
1358     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1359     PrintLine("-", 79);
1360     Print("Supported modifiers:\n");
1361     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1362     PrintLine("=", 79);
1363
1364     CloseAllAndExit(0);
1365   }
1366
1367   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1368                                                   global.patchtapes_leveldir);
1369
1370   if (patchtapes_leveldir == NULL)
1371     Error(ERR_EXIT, "no such level identifier: '%s'",
1372           global.patchtapes_leveldir);
1373
1374   leveldir_current = patchtapes_leveldir;
1375
1376   if (patchtapes_leveldir->first_level < 0)
1377     patchtapes_leveldir->first_level = 0;
1378   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1379     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1380
1381   PrintLine("=", 79);
1382   Print("Patching level tapes for patch mode '%s'\n", mode);
1383   PrintLine("-", 79);
1384   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1385   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1386   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1387   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1388   PrintLine("=", 79);
1389   Print("\n");
1390
1391   int first_level = patchtapes_leveldir->first_level;
1392   int last_level = patchtapes_leveldir->last_level;
1393
1394   for (i = first_level; i <= last_level; i++)
1395   {
1396     if (!global.patchtapes_all && !global.patchtapes_level[i])
1397       continue;
1398
1399     Print("Tape %03d: ", i);
1400
1401     TapeErase();
1402     LoadTape(i);
1403
1404     if (tape.no_valid_file)
1405     {
1406       Print("(not found)\n");
1407
1408       continue;
1409     }
1410
1411     num_tapes_found++;
1412
1413     if (PatchTape(&tape, mode))
1414     {
1415       char *filename = getTapeFilename(i);
1416       char *filename_orig = getStringCat2(filename, ".orig");
1417
1418       if (!fileExists(filename_orig))
1419         rename(filename, filename_orig);
1420
1421       SaveTapeToFilename(filename);
1422
1423       Print("patched tape saved.\n");
1424
1425       num_tapes_patched++;
1426     }
1427   }
1428
1429   Print("\n");
1430   PrintLine("=", 79);
1431   Print("Number of tapes found: %d\n", num_tapes_found);
1432   Print("Number of tapes patched: %d\n", num_tapes_patched);
1433   PrintLine("=", 79);
1434
1435   CloseAllAndExit(0);
1436 }
1437
1438
1439 // ---------- new tape button stuff -------------------------------------------
1440
1441 static struct
1442 {
1443   int graphic;
1444   struct XY *pos;
1445   int gadget_id;
1446   char *infotext;
1447 } tapebutton_info[NUM_TAPE_BUTTONS] =
1448 {
1449   {
1450     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1451     TAPE_CTRL_ID_EJECT,                 "eject tape"
1452   },
1453   {
1454     // (same position as "eject" button)
1455     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1456     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1457   },
1458   {
1459     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1460     TAPE_CTRL_ID_STOP,                  "stop tape"
1461   },
1462   {
1463     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1464     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1465   },
1466   {
1467     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1468     TAPE_CTRL_ID_RECORD,                "record tape"
1469   },
1470   {
1471     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1472     TAPE_CTRL_ID_PLAY,                  "play tape"
1473   },
1474   {
1475     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1476     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
1477   },
1478   {
1479     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
1480     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
1481   }
1482 };
1483
1484 void CreateTapeButtons(void)
1485 {
1486   int i;
1487
1488   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1489   {
1490     int graphic = tapebutton_info[i].graphic;
1491     struct GraphicInfo *gfx = &graphic_info[graphic];
1492     struct XY *pos = tapebutton_info[i].pos;
1493     struct GadgetInfo *gi;
1494     int gd_x = gfx->src_x;
1495     int gd_y = gfx->src_y;
1496     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1497     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1498     int id = i;
1499
1500     gi = CreateGadget(GDI_CUSTOM_ID, id,
1501                       GDI_IMAGE_ID, graphic,
1502                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
1503                       GDI_X, VX + pos->x,
1504                       GDI_Y, VY + pos->y,
1505                       GDI_WIDTH, gfx->width,
1506                       GDI_HEIGHT, gfx->height,
1507                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
1508                       GDI_STATE, GD_BUTTON_UNPRESSED,
1509                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
1510                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
1511                       GDI_DIRECT_DRAW, FALSE,
1512                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
1513                       GDI_CALLBACK_ACTION, HandleTapeButtons,
1514                       GDI_END);
1515
1516     if (gi == NULL)
1517       Error(ERR_EXIT, "cannot create gadget");
1518
1519     tape_gadget[id] = gi;
1520   }
1521 }
1522
1523 void FreeTapeButtons(void)
1524 {
1525   int i;
1526
1527   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1528     FreeGadget(tape_gadget[i]);
1529 }
1530
1531 void MapTapeEjectButton(void)
1532 {
1533   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1534   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1535 }
1536
1537 void MapTapeWarpButton(void)
1538 {
1539   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1540   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1541 }
1542
1543 void MapTapeButtons(void)
1544 {
1545   int i;
1546
1547   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1548     if (i != TAPE_CTRL_ID_EXTRA)
1549       MapGadget(tape_gadget[i]);
1550
1551   if (tape.recording || tape.playing)
1552     MapTapeWarpButton();
1553
1554   if (tape.show_game_buttons)
1555     MapGameButtonsOnTape();
1556 }
1557
1558 void UnmapTapeButtons(void)
1559 {
1560   int i;
1561
1562   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1563     UnmapGadget(tape_gadget[i]);
1564
1565   if (tape.show_game_buttons)
1566     UnmapGameButtonsOnTape();
1567 }
1568
1569 void RedrawTapeButtons(void)
1570 {
1571   int i;
1572
1573   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1574     RedrawGadget(tape_gadget[i]);
1575
1576   if (tape.show_game_buttons)
1577     RedrawGameButtonsOnTape();
1578 }
1579
1580 void RedrawOrRemapTapeButtons(void)
1581 {
1582   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
1583   {
1584     // tape buttons already mapped
1585     RedrawTapeButtons();
1586   }
1587   else
1588   {
1589     UnmapTapeButtons();
1590     MapTapeButtons();
1591   }
1592 }
1593
1594 static void HandleTapeButtonsExt(int id)
1595 {
1596   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
1597     return;
1598
1599   switch (id)
1600   {
1601     case TAPE_CTRL_ID_EJECT:
1602       TapeStop();
1603
1604       if (TAPE_IS_EMPTY(tape))
1605       {
1606         LoadTape(level_nr);
1607
1608         if (TAPE_IS_EMPTY(tape))
1609           Request("No tape for this level!", REQ_CONFIRM);
1610       }
1611       else
1612       {
1613         if (tape.changed)
1614           SaveTapeChecked(level_nr);
1615
1616         TapeErase();
1617       }
1618
1619       DrawCompleteVideoDisplay();
1620       break;
1621
1622     case TAPE_CTRL_ID_EXTRA:
1623       if (tape.playing)
1624       {
1625         tape.pause_before_end = !tape.pause_before_end;
1626
1627         DrawVideoDisplayCurrentState();
1628       }
1629       else if (tape.recording)
1630       {
1631         TapeSingleStep();
1632       }
1633
1634       break;
1635
1636     case TAPE_CTRL_ID_STOP:
1637       TapeStop();
1638
1639       break;
1640
1641     case TAPE_CTRL_ID_PAUSE:
1642       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1643
1644       break;
1645
1646     case TAPE_CTRL_ID_RECORD:
1647       if (TAPE_IS_STOPPED(tape))
1648       {
1649         TapeStartGameRecording();
1650       }
1651       else if (tape.pausing)
1652       {
1653         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
1654           TapeAppendRecording();
1655         else
1656           TapeTogglePause(TAPE_TOGGLE_MANUAL);
1657       }
1658
1659       break;
1660
1661     case TAPE_CTRL_ID_PLAY:
1662       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
1663       {
1664         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
1665
1666         TapeTogglePause(TAPE_TOGGLE_MANUAL);
1667       }
1668
1669       if (TAPE_IS_EMPTY(tape))
1670         break;
1671
1672       if (TAPE_IS_STOPPED(tape))
1673       {
1674         TapeStartGamePlaying();
1675       }
1676       else if (tape.playing)
1677       {
1678         if (tape.pausing)                       // PAUSE -> PLAY
1679         {
1680           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
1681         }
1682         else if (!tape.fast_forward)            // PLAY -> FFWD
1683         {
1684           tape.fast_forward = TRUE;
1685         }
1686         else if (!tape.warp_forward)            // FFWD -> WARP
1687         {
1688           tape.warp_forward = TRUE;
1689         }
1690         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
1691         {
1692           tape.deactivate_display = TRUE;
1693
1694           TapeDeactivateDisplayOn();
1695         }
1696         else                                    // WARP BLIND -> PLAY
1697         {
1698           tape.fast_forward = FALSE;
1699           tape.warp_forward = FALSE;
1700           tape.deactivate_display = FALSE;
1701
1702           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1703         }
1704
1705         DrawVideoDisplayCurrentState();
1706       }
1707
1708       break;
1709
1710     case TAPE_CTRL_ID_INSERT_SOLUTION:
1711       InsertSolutionTape();
1712
1713       break;
1714
1715     case TAPE_CTRL_ID_PLAY_SOLUTION:
1716       PlaySolutionTape();
1717
1718       break;
1719
1720     default:
1721       break;
1722   }
1723 }
1724
1725 static void HandleTapeButtons(struct GadgetInfo *gi)
1726 {
1727   HandleTapeButtonsExt(gi->custom_id);
1728 }
1729
1730 void HandleTapeButtonKeys(Key key)
1731 {
1732   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
1733   boolean extra_button_is_active = !eject_button_is_active;
1734
1735   if (key == setup.shortcut.tape_eject && eject_button_is_active)
1736     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
1737   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
1738     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
1739   else if (key == setup.shortcut.tape_stop)
1740     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
1741   else if (key == setup.shortcut.tape_pause)
1742     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
1743   else if (key == setup.shortcut.tape_record)
1744     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
1745   else if (key == setup.shortcut.tape_play)
1746     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
1747 }