4894f1137bc9fb54fec3b5e7b81c03bcfae4fc56
[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 char tape_patch_info[MAX_OUTPUT_LINESIZE];
469
470 static void PrintTapeReplayProgress(boolean replay_finished)
471 {
472   static unsigned int counter_last = -1;
473   unsigned int counter = Counter();
474   unsigned int counter_seconds  = counter / 1000;
475
476   if (!replay_finished)
477   {
478     unsigned int counter_delay = 50;
479
480     if (counter > counter_last + counter_delay)
481     {
482       PrintNoLog("\r");
483       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
484                  level_nr,  tape_patch_info,
485                  tape.length_seconds / 60, tape.length_seconds % 60,
486                  TapeTime / 60, TapeTime % 60);
487
488       counter_last = counter;
489     }
490   }
491   else
492   {
493     float tape_length_seconds = GetTapeLengthSecondsFloat();
494
495     PrintNoLog("\r");
496     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
497           level_nr, tape_patch_info,
498           tape.length_seconds / 60, tape.length_seconds % 60,
499           counter_seconds / 60, counter_seconds % 60, counter % 1000,
500           (float)counter / tape_length_seconds / 10,
501           tape.auto_play_level_fixed ? "solved and fixed" :
502           tape.auto_play_level_solved ? "solved" :
503           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
504           "NOT SOLVED");
505
506     counter_last = -1;
507   }
508 }
509
510
511 // ============================================================================
512 // tape control functions
513 // ============================================================================
514
515 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
516 {
517   struct tm *lt = localtime(&epoch_seconds);
518
519   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
520 }
521
522 void TapeSetDateFromNow(void)
523 {
524   TapeSetDateFromEpochSeconds(time(NULL));
525 }
526
527 void TapeErase(void)
528 {
529   int i;
530
531   tape.counter = 0;
532   tape.length = 0;
533   tape.length_frames = 0;
534   tape.length_seconds = 0;
535
536   if (leveldir_current)
537     setString(&tape.level_identifier, leveldir_current->identifier);
538
539   tape.level_nr = level_nr;
540   tape.pos[tape.counter].delay = 0;
541   tape.changed = TRUE;
542
543   tape.random_seed = InitRND(level.random_seed);
544
545   tape.file_version = FILE_VERSION_ACTUAL;
546   tape.game_version = GAME_VERSION_ACTUAL;
547   tape.engine_version = level.game_version;
548
549   TapeSetDateFromNow();
550
551   for (i = 0; i < MAX_PLAYERS; i++)
552     tape.player_participates[i] = FALSE;
553
554   tape.centered_player_nr_next = -1;
555   tape.set_centered_player = FALSE;
556
557   // set flags for game actions to default values (may be overwritten later)
558   tape.use_key_actions = TRUE;
559   tape.use_mouse_actions = FALSE;
560 }
561
562 static void TapeRewind(void)
563 {
564   tape.counter = 0;
565   tape.delay_played = 0;
566   tape.pause_before_end = FALSE;
567   tape.recording = FALSE;
568   tape.playing = FALSE;
569   tape.fast_forward = FALSE;
570   tape.warp_forward = FALSE;
571   tape.deactivate_display = FALSE;
572   tape.auto_play = (global.autoplay_leveldir != NULL);
573   tape.auto_play_level_solved = FALSE;
574   tape.auto_play_level_fixed = FALSE;
575   tape.auto_play_level_not_fixable = FALSE;
576   tape.quick_resume = FALSE;
577   tape.single_step = FALSE;
578
579   tape.centered_player_nr_next = -1;
580   tape.set_centered_player = FALSE;
581
582   InitRND(tape.random_seed);
583 }
584
585 static void TapeSetRandomSeed(int random_seed)
586 {
587   tape.random_seed = InitRND(random_seed);
588 }
589
590 void TapeStartRecording(int random_seed)
591 {
592   if (!TAPE_IS_STOPPED(tape))
593     TapeStop();
594
595   TapeErase();
596   TapeRewind();
597   TapeSetRandomSeed(random_seed);
598
599   tape.recording = TRUE;
600
601   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
602   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
603   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
604   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
605
606   MapTapeWarpButton();
607
608   SetDrawDeactivationMask(REDRAW_NONE);
609   audio.sound_deactivated = FALSE;
610
611   // required here to update video display if tape door is closed
612   if (GetDoorState() & DOOR_CLOSE_2)
613     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
614 }
615
616 static void TapeStartGameRecording(void)
617 {
618   StartGameActions(network.enabled, TRUE, level.random_seed);
619 }
620
621 static void TapeAppendRecording(void)
622 {
623   if (!tape.playing || !tape.pausing)
624     return;
625
626   // stop playing
627   tape.playing = FALSE;
628   tape.fast_forward = FALSE;
629   tape.warp_forward = FALSE;
630   tape.pause_before_end = FALSE;
631   tape.deactivate_display = FALSE;
632
633   // start recording
634   tape.recording = TRUE;
635   tape.changed = TRUE;
636
637   // set current delay (for last played move)
638   tape.pos[tape.counter].delay = tape.delay_played;
639
640   // set current date
641   TapeSetDateFromNow();
642
643   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
644   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
645
646   UpdateAndDisplayGameControlValues();
647 }
648
649 void TapeHaltRecording(void)
650 {
651   tape.counter++;
652
653   // initialize delay for next tape entry (to be able to continue recording)
654   if (tape.counter < MAX_TAPE_LEN)
655     tape.pos[tape.counter].delay = 0;
656
657   tape.length = tape.counter;
658   tape.length_frames = GetTapeLengthFrames();
659   tape.length_seconds = GetTapeLengthSeconds();
660 }
661
662 void TapeStopRecording(void)
663 {
664   if (tape.recording)
665     TapeHaltRecording();
666
667   tape.recording = FALSE;
668   tape.pausing = FALSE;
669
670   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
671   MapTapeEjectButton();
672 }
673
674 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
675 {
676   int i;
677
678   if (tape.pos[tape.counter].delay > 0)         // already stored action
679   {
680     boolean changed_events = FALSE;
681
682     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
683       if (tape.pos[tape.counter].action[i] != action[i])
684         changed_events = TRUE;
685
686     if (changed_events || tape.pos[tape.counter].delay >= 255)
687     {
688       if (tape.counter >= MAX_TAPE_LEN - 1)
689         return FALSE;
690
691       tape.counter++;
692       tape.pos[tape.counter].delay = 0;
693     }
694     else
695       tape.pos[tape.counter].delay++;
696   }
697
698   if (tape.pos[tape.counter].delay == 0)        // store new action
699   {
700     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
701       tape.pos[tape.counter].action[i] = action[i];
702
703     tape.pos[tape.counter].delay++;
704   }
705
706   return TRUE;
707 }
708
709 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
710 {
711   byte action[MAX_TAPE_ACTIONS];
712   int i;
713
714   if (!tape.recording)          // (record action even when tape is paused)
715     return;
716
717   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
718     action[i] = action_raw[i];
719
720   if (tape.use_key_actions && tape.set_centered_player)
721   {
722     for (i = 0; i < MAX_PLAYERS; i++)
723       if (tape.centered_player_nr_next == i ||
724           tape.centered_player_nr_next == -1)
725         action[i] |= KEY_SET_FOCUS;
726
727     tape.set_centered_player = FALSE;
728   }
729
730   if (!TapeAddAction(action))
731     TapeStopRecording();
732 }
733
734 void TapeTogglePause(boolean toggle_mode)
735 {
736   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
737   {
738     // continue playing in normal mode
739     tape.fast_forward = FALSE;
740     tape.warp_forward = FALSE;
741     tape.deactivate_display = FALSE;
742
743     tape.pause_before_end = FALSE;
744   }
745
746   tape.pausing = !tape.pausing;
747
748   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
749     tape.single_step = FALSE;
750
751   DrawVideoDisplayCurrentState();
752
753   if (tape.deactivate_display)
754   {
755     if (tape.pausing)
756       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
757     else
758       TapeDeactivateDisplayOn();
759   }
760
761   if (tape.quick_resume)
762   {
763     tape.quick_resume = FALSE;
764
765     TapeStopWarpForward();
766     TapeAppendRecording();
767
768     if (!CheckEngineSnapshotSingle())
769       SaveEngineSnapshotSingle();
770
771     // restart step/move snapshots after quick loading tape
772     SaveEngineSnapshotToListInitial();
773
774     // do not map undo/redo buttons after quick loading tape
775     return;
776   }
777
778   if (game_status == GAME_MODE_PLAYING)
779   {
780     if (setup.show_snapshot_buttons && CheckEngineSnapshotList())
781     {
782       if (tape.pausing)
783         MapUndoRedoButtons();
784       else if (!tape.single_step)
785         UnmapUndoRedoButtons();
786     }
787
788     ModifyPauseButtons();
789   }
790 }
791
792 void TapeStartPlaying(void)
793 {
794   if (TAPE_IS_EMPTY(tape))
795     return;
796
797   if (!TAPE_IS_STOPPED(tape))
798     TapeStop();
799
800   TapeRewind();
801
802   tape.playing = TRUE;
803
804   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
805   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
806   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
807   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
808
809   MapTapeWarpButton();
810
811   SetDrawDeactivationMask(REDRAW_NONE);
812   audio.sound_deactivated = FALSE;
813 }
814
815 static void TapeStartGamePlaying(void)
816 {
817   TapeStartPlaying();
818
819   InitGame();
820 }
821
822 void TapeStopPlaying(void)
823 {
824   tape.playing = FALSE;
825   tape.pausing = FALSE;
826
827   if (tape.warp_forward)
828     TapeStopWarpForward();
829
830   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
831   MapTapeEjectButton();
832 }
833
834 byte *TapePlayAction(void)
835 {
836   int update_delay = FRAMES_PER_SECOND / 2;
837   boolean update_video_display = (FrameCounter % update_delay == 0);
838   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
839   static byte action[MAX_TAPE_ACTIONS];
840   int i;
841
842   if (!tape.playing || tape.pausing)
843     return NULL;
844
845   if (tape.pause_before_end)  // stop some seconds before end of tape
846   {
847     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
848     {
849       TapeStopWarpForward();
850       TapeTogglePause(TAPE_TOGGLE_MANUAL);
851
852       return NULL;
853     }
854   }
855
856   if (tape.counter >= tape.length)      // end of tape reached
857   {
858     if (tape.warp_forward && !tape.auto_play)
859     {
860       TapeStopWarpForward();
861       TapeTogglePause(TAPE_TOGGLE_MANUAL);
862     }
863     else
864     {
865       TapeStop();
866     }
867
868     return NULL;
869   }
870
871   if (update_video_display && !tape.deactivate_display)
872   {
873     int state = 0;
874
875     if (tape.warp_forward)
876       state |= VIDEO_STATE_WARP(update_draw_label_on);
877     else if (tape.fast_forward)
878       state |= VIDEO_STATE_FFWD(update_draw_label_on);
879
880     if (tape.pause_before_end)
881       state |= VIDEO_STATE_PBEND(update_draw_label_on);
882
883     // draw labels and symbols separately to prevent labels overlapping symbols
884     DrawVideoDisplayLabel(state);
885     DrawVideoDisplaySymbol(state);
886   }
887
888   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
889     action[i] = tape.pos[tape.counter].action[i];
890
891 #if DEBUG_TAPE_WHEN_PLAYING
892   printf("%05d", FrameCounter);
893   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
894     printf("   %08x", action[i]);
895   printf("\n");
896 #endif
897
898   tape.set_centered_player = FALSE;
899   tape.centered_player_nr_next = -999;
900
901   if (tape.use_key_actions)
902   {
903     for (i = 0; i < MAX_PLAYERS; i++)
904     {
905       if (action[i] & KEY_SET_FOCUS)
906       {
907         tape.set_centered_player = TRUE;
908         tape.centered_player_nr_next =
909           (tape.centered_player_nr_next == -999 ? i : -1);
910       }
911
912       action[i] &= ~KEY_SET_FOCUS;
913     }
914   }
915
916   tape.delay_played++;
917   if (tape.delay_played >= tape.pos[tape.counter].delay)
918   {
919     tape.counter++;
920     tape.delay_played = 0;
921   }
922
923   if (tape.auto_play)
924     PrintTapeReplayProgress(FALSE);
925
926   return action;
927 }
928
929 void TapeStop(void)
930 {
931   if (tape.pausing)
932     TapeTogglePause(TAPE_TOGGLE_MANUAL);
933
934   TapeStopRecording();
935   TapeStopPlaying();
936
937   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
938
939   if (tape.date && tape.length)
940   {
941     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
942     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
943     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
944   }
945 }
946
947 unsigned int GetTapeLengthFrames(void)
948 {
949   unsigned int tape_length_frames = 0;
950   int i;
951
952   if (TAPE_IS_EMPTY(tape))
953     return(0);
954
955   for (i = 0; i < tape.length; i++)
956     tape_length_frames += tape.pos[i].delay;
957
958   return tape_length_frames;
959 }
960
961 unsigned int GetTapeLengthSeconds(void)
962 {
963   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
964 }
965
966 static float GetTapeLengthSecondsFloat(void)
967 {
968   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
969 }
970
971 static void TapeStartWarpForward(int mode)
972 {
973   tape.fast_forward = (mode & AUTOPLAY_FFWD);
974   tape.warp_forward = (mode & AUTOPLAY_WARP);
975   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
976
977   tape.pausing = FALSE;
978
979   if (tape.deactivate_display)
980     TapeDeactivateDisplayOn();
981
982   DrawVideoDisplayCurrentState();
983 }
984
985 static void TapeStopWarpForward(void)
986 {
987   tape.fast_forward = FALSE;
988   tape.warp_forward = FALSE;
989   tape.deactivate_display = FALSE;
990
991   tape.pause_before_end = FALSE;
992
993   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
994
995   DrawVideoDisplayCurrentState();
996 }
997
998 static void TapeSingleStep(void)
999 {
1000   if (network.enabled)
1001     return;
1002
1003   if (!tape.pausing)
1004     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1005
1006   tape.single_step = !tape.single_step;
1007
1008   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1009 }
1010
1011 void TapeQuickSave(void)
1012 {
1013   if (game_status == GAME_MODE_MAIN)
1014   {
1015     Request("No game that can be saved!", REQ_CONFIRM);
1016
1017     return;
1018   }
1019
1020   if (game_status != GAME_MODE_PLAYING)
1021     return;
1022
1023   if (tape.recording)
1024     TapeHaltRecording();        // prepare tape for saving on-the-fly
1025
1026   if (TAPE_IS_EMPTY(tape))
1027   {
1028     Request("No tape that can be saved!", REQ_CONFIRM);
1029
1030     return;
1031   }
1032
1033   if (SaveTapeChecked(tape.level_nr))
1034     SaveEngineSnapshotSingle();
1035 }
1036
1037 void TapeQuickLoad(void)
1038 {
1039   char *filename = getTapeFilename(level_nr);
1040
1041   if (!fileExists(filename))
1042   {
1043     Request("No tape for this level!", REQ_CONFIRM);
1044
1045     return;
1046   }
1047
1048   if (tape.recording && !Request("Stop recording and load tape?",
1049                                  REQ_ASK | REQ_STAY_CLOSED))
1050   {
1051     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1052
1053     return;
1054   }
1055
1056   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1057     return;
1058
1059   if (CheckEngineSnapshotSingle())
1060   {
1061     TapeStartGamePlaying();
1062
1063     LoadEngineSnapshotSingle();
1064
1065     DrawCompleteVideoDisplay();
1066
1067     tape.playing = TRUE;
1068     tape.pausing = TRUE;
1069
1070     TapeStopWarpForward();
1071     TapeAppendRecording();
1072
1073     // restart step/move snapshots after quick loading tape
1074     SaveEngineSnapshotToListInitial();
1075
1076     if (FrameCounter > 0)
1077       return;
1078   }
1079
1080   TapeStop();
1081   TapeErase();
1082
1083   LoadTape(level_nr);
1084
1085   if (!TAPE_IS_EMPTY(tape))
1086   {
1087     TapeStartGamePlaying();
1088     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1089
1090     tape.quick_resume = TRUE;
1091   }
1092   else  // this should not happen (basically checked above)
1093   {
1094     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1095
1096     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1097   }
1098 }
1099
1100 boolean hasSolutionTape(void)
1101 {
1102   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1103   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1104                             level.native_sp_level->demo.is_available);
1105
1106   return (tape_file_exists || level_has_tape);
1107 }
1108
1109 boolean InsertSolutionTape(void)
1110 {
1111   if (!hasSolutionTape())
1112   {
1113     Request("No solution tape for this level!", REQ_CONFIRM);
1114
1115     return FALSE;
1116   }
1117
1118   if (!TAPE_IS_STOPPED(tape))
1119     TapeStop();
1120
1121   // if tape recorder already contains a tape, remove it without asking
1122   TapeErase();
1123
1124   LoadSolutionTape(level_nr);
1125
1126   DrawCompleteVideoDisplay();
1127
1128   if (TAPE_IS_EMPTY(tape))
1129   {
1130     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1131
1132     return FALSE;
1133   }
1134
1135   return TRUE;
1136 }
1137
1138 boolean PlaySolutionTape(void)
1139 {
1140   if (!InsertSolutionTape())
1141     return FALSE;
1142
1143   TapeStartGamePlaying();
1144
1145   return TRUE;
1146 }
1147
1148
1149 // ----------------------------------------------------------------------------
1150 // tape autoplay functions
1151 // ----------------------------------------------------------------------------
1152
1153 void AutoPlayTapes(void)
1154 {
1155   static LevelDirTree *autoplay_leveldir = NULL;
1156   static boolean autoplay_initialized = FALSE;
1157   static int autoplay_level_nr = -1;
1158   static int num_levels_played = 0;
1159   static int num_levels_solved = 0;
1160   static int num_tapes_patched = 0;
1161   static int num_tape_missing = 0;
1162   static boolean level_failed[MAX_TAPES_PER_SET];
1163   static int patch_nr = 0;
1164   static char *patch_name[] =
1165   {
1166     "original tape",
1167     "em_random_bug",
1168
1169     NULL
1170   };
1171   static int patch_version_first[] =
1172   {
1173     VERSION_IDENT(0,0,0,0),
1174     VERSION_IDENT(3,3,1,0),
1175
1176     -1
1177   };
1178   static int patch_version_last[] =
1179   {
1180     VERSION_IDENT(9,9,9,9),
1181     VERSION_IDENT(4,0,1,1),
1182
1183     -1
1184   };
1185   static byte patch_property_bit[] =
1186   {
1187     TAPE_PROPERTY_NONE,
1188     TAPE_PROPERTY_EM_RANDOM_BUG,
1189
1190     -1
1191   };
1192   int i;
1193
1194   if (autoplay_initialized)
1195   {
1196     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1197     {
1198       if (tape.auto_play_level_solved)
1199       {
1200         if (patch_nr > 0)
1201         {
1202           // level solved by patched tape -- save fixed tape
1203           char *filename = getTapeFilename(level_nr);
1204           char *filename_orig = getStringCat2(filename, ".orig");
1205
1206           // create backup from old tape, if not yet existing
1207           if (!fileExists(filename_orig))
1208             rename(filename, filename_orig);
1209
1210           SaveTapeToFilename(filename);
1211
1212           tape.auto_play_level_fixed = TRUE;
1213           num_tapes_patched++;
1214         }
1215
1216         // continue with next tape
1217         patch_nr = 0;
1218       }
1219       else if (patch_name[patch_nr + 1] != NULL)
1220       {
1221         // level not solved by patched tape -- continue with next patch
1222         patch_nr++;
1223       }
1224       else
1225       {
1226         // level not solved by any patched tape -- continue with next tape
1227         tape.auto_play_level_not_fixable = TRUE;
1228         patch_nr = 0;
1229       }
1230     }
1231
1232     // just finished auto-playing tape
1233     PrintTapeReplayProgress(TRUE);
1234
1235     if (patch_nr == 0)
1236       num_levels_played++;
1237
1238     if (tape.auto_play_level_solved)
1239       num_levels_solved++;
1240
1241     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1242       level_failed[level_nr] = !tape.auto_play_level_solved;
1243   }
1244   else
1245   {
1246     DrawCompleteVideoDisplay();
1247
1248     audio.sound_enabled = FALSE;
1249     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1250
1251     autoplay_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1252                                                   global.autoplay_leveldir);
1253
1254     if (autoplay_leveldir == NULL)
1255       Error(ERR_EXIT, "no such level identifier: '%s'",
1256             global.autoplay_leveldir);
1257
1258     leveldir_current = autoplay_leveldir;
1259
1260     if (autoplay_leveldir->first_level < 0)
1261       autoplay_leveldir->first_level = 0;
1262     if (autoplay_leveldir->last_level >= MAX_TAPES_PER_SET)
1263       autoplay_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1264
1265     autoplay_level_nr = autoplay_leveldir->first_level;
1266
1267     PrintLine("=", 79);
1268     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1269       Print("Automatically fixing level tapes\n");
1270     else
1271       Print("Automatically playing level tapes\n");
1272     PrintLine("-", 79);
1273     Print("Level series identifier: '%s'\n", autoplay_leveldir->identifier);
1274     Print("Level series name:       '%s'\n", autoplay_leveldir->name);
1275     Print("Level series author:     '%s'\n", autoplay_leveldir->author);
1276     Print("Number of levels:        %d\n",   autoplay_leveldir->levels);
1277     PrintLine("=", 79);
1278     Print("\n");
1279
1280     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1281       level_failed[i] = FALSE;
1282
1283     // only private tapes may be modified
1284     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1285       options.mytapes = TRUE;
1286
1287     autoplay_initialized = TRUE;
1288   }
1289
1290   while (1)
1291   {
1292     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1293       level_nr = autoplay_level_nr++;
1294
1295     if (level_nr > autoplay_leveldir->last_level)
1296       break;
1297
1298     // set patch info (required for progress output)
1299     strcpy(tape_patch_info, "");
1300     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1301       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1302                patch_name[patch_nr]);
1303
1304     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1305       continue;
1306
1307     TapeErase();
1308
1309     LoadLevel(level_nr);
1310
1311     if (level.no_level_file || level.no_valid_file)
1312     {
1313       Print("Tape %03d: (no level found)\n", level_nr);
1314
1315       continue;
1316     }
1317
1318 #if 0
1319     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1320     Print("Tape %03d: (only testing level)\n", level_nr);
1321     continue;
1322 #endif
1323
1324     if (options.mytapes)
1325       LoadTape(level_nr);
1326     else
1327       LoadSolutionTape(level_nr);
1328
1329     if (tape.no_valid_file)
1330     {
1331       num_tape_missing++;
1332
1333       Print("Tape %03d: (no tape found)\n", level_nr);
1334
1335       continue;
1336     }
1337
1338     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1339     {
1340       if (tape.engine_version < patch_version_first[patch_nr] ||
1341           tape.engine_version > patch_version_last[patch_nr])
1342       {
1343         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1344               level_nr,  tape_patch_info,
1345               tape.length_seconds / 60, tape.length_seconds % 60,
1346               "not suitable for version",
1347               (tape.engine_version / 1000000) % 100,
1348               (tape.engine_version / 10000  ) % 100,
1349               (tape.engine_version / 100    ) % 100,
1350               (tape.engine_version          ) % 100);
1351
1352         if (patch_name[patch_nr + 1] != NULL)
1353         {
1354           // continue with next patch
1355           patch_nr++;
1356         }
1357         else
1358         {
1359           // continue with next tape
1360           patch_nr = 0;
1361         }
1362
1363         continue;
1364       }
1365
1366       tape.property_bits |= patch_property_bit[patch_nr];
1367     }
1368
1369     InitCounter();
1370
1371     TapeStartGamePlaying();
1372     TapeStartWarpForward(global.autoplay_mode);
1373
1374     return;
1375   }
1376
1377   Print("\n");
1378   PrintLine("=", 79);
1379   Print("Number of levels played: %d\n", num_levels_played);
1380   Print("Number of levels solved: %d (%d%%)\n", num_levels_solved,
1381         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1382   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1383     Print("Number of tapes fixed: %d\n", num_tapes_patched);
1384   PrintLine("-", 79);
1385   Print("Summary (for automatic parsing by scripts):\n");
1386   Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
1387         (num_levels_played == num_levels_solved ? " OK " : "WARN"),
1388         autoplay_leveldir->identifier, num_levels_solved, num_levels_played,
1389         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1390
1391   if (num_levels_played != num_levels_solved)
1392   {
1393     Print(", FAILED:");
1394     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1395       if (level_failed[i])
1396         Print(" %03d", i);
1397   }
1398
1399   Print("\n");
1400   PrintLine("=", 79);
1401
1402   CloseAllAndExit(0);
1403 }
1404
1405
1406 // ----------------------------------------------------------------------------
1407 // tape patch functions
1408 // ----------------------------------------------------------------------------
1409
1410 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1411 {
1412   Print("[%d.%d.%d.%d]: ",
1413         (tape->engine_version / 1000000) % 100,
1414         (tape->engine_version / 10000  ) % 100,
1415         (tape->engine_version / 100    ) % 100,
1416         (tape->engine_version          ) % 100);
1417
1418   if (strEqual(mode, "info"))
1419   {
1420     Print("property bits == 0x%02x\n", tape->property_bits);
1421
1422     return FALSE;
1423   }
1424
1425   byte property_bits = tape->property_bits;
1426   byte property_bitmask = 0;
1427   boolean set_property_bit = TRUE;
1428
1429   if (strSuffix(mode, ":0") ||
1430       strSuffix(mode, ":off") ||
1431       strSuffix(mode, ":clear"))
1432     set_property_bit = FALSE;
1433
1434   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1435   {
1436     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1437     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1438         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1439     {
1440       Print("This tape version cannot be patched against EM random bug!\n");
1441
1442       return FALSE;
1443     }
1444
1445     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1446   }
1447   else
1448   {
1449     Print("Unknown patch mode '%s'!\n", mode);
1450
1451     return FALSE;
1452   }
1453
1454   if (set_property_bit)
1455     property_bits |= property_bitmask;
1456   else
1457     property_bits &= ~property_bitmask;
1458
1459   if (property_bits == tape->property_bits)
1460   {
1461     Print("Tape already patched for '%s'!\n", mode);
1462
1463     return FALSE;
1464   }
1465
1466   Print("Patching for '%s' ... ", mode);
1467
1468   tape->property_bits = property_bits;
1469
1470   return TRUE;
1471 }
1472
1473 void PatchTapes(void)
1474 {
1475   static LevelDirTree *patchtapes_leveldir = NULL;
1476   static int num_tapes_found = 0;
1477   static int num_tapes_patched = 0;
1478   char *mode = global.patchtapes_mode;
1479   int i;
1480
1481   if (strEqual(mode, "help"))
1482   {
1483     PrintLine("=", 79);
1484     Print("Supported patch modes:\n");
1485     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1486     PrintLine("-", 79);
1487     Print("Supported modifiers:\n");
1488     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1489     PrintLine("=", 79);
1490
1491     CloseAllAndExit(0);
1492   }
1493
1494   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1495                                                   global.patchtapes_leveldir);
1496
1497   if (patchtapes_leveldir == NULL)
1498     Error(ERR_EXIT, "no such level identifier: '%s'",
1499           global.patchtapes_leveldir);
1500
1501   leveldir_current = patchtapes_leveldir;
1502
1503   if (patchtapes_leveldir->first_level < 0)
1504     patchtapes_leveldir->first_level = 0;
1505   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1506     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1507
1508   PrintLine("=", 79);
1509   Print("Patching level tapes for patch mode '%s'\n", mode);
1510   PrintLine("-", 79);
1511   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1512   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1513   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1514   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1515   PrintLine("=", 79);
1516   Print("\n");
1517
1518   int first_level = patchtapes_leveldir->first_level;
1519   int last_level = patchtapes_leveldir->last_level;
1520
1521   for (i = first_level; i <= last_level; i++)
1522   {
1523     if (!global.patchtapes_all && !global.patchtapes_level[i])
1524       continue;
1525
1526     Print("Tape %03d: ", i);
1527
1528     TapeErase();
1529     LoadTape(i);
1530
1531     if (tape.no_valid_file)
1532     {
1533       Print("(no tape found)\n");
1534
1535       continue;
1536     }
1537
1538     num_tapes_found++;
1539
1540     if (PatchTape(&tape, mode))
1541     {
1542       char *filename = getTapeFilename(i);
1543       char *filename_orig = getStringCat2(filename, ".orig");
1544
1545       if (!fileExists(filename_orig))
1546         rename(filename, filename_orig);
1547
1548       SaveTapeToFilename(filename);
1549
1550       Print("patched tape saved.\n");
1551
1552       num_tapes_patched++;
1553     }
1554   }
1555
1556   Print("\n");
1557   PrintLine("=", 79);
1558   Print("Number of tapes found: %d\n", num_tapes_found);
1559   Print("Number of tapes patched: %d\n", num_tapes_patched);
1560   PrintLine("=", 79);
1561
1562   CloseAllAndExit(0);
1563 }
1564
1565
1566 // ---------- new tape button stuff -------------------------------------------
1567
1568 static struct
1569 {
1570   int graphic;
1571   struct XY *pos;
1572   int gadget_id;
1573   char *infotext;
1574 } tapebutton_info[NUM_TAPE_BUTTONS] =
1575 {
1576   {
1577     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1578     TAPE_CTRL_ID_EJECT,                 "eject tape"
1579   },
1580   {
1581     // (same position as "eject" button)
1582     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1583     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1584   },
1585   {
1586     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1587     TAPE_CTRL_ID_STOP,                  "stop tape"
1588   },
1589   {
1590     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1591     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1592   },
1593   {
1594     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1595     TAPE_CTRL_ID_RECORD,                "record tape"
1596   },
1597   {
1598     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1599     TAPE_CTRL_ID_PLAY,                  "play tape"
1600   },
1601   {
1602     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1603     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
1604   },
1605   {
1606     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
1607     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
1608   }
1609 };
1610
1611 void CreateTapeButtons(void)
1612 {
1613   int i;
1614
1615   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1616   {
1617     int graphic = tapebutton_info[i].graphic;
1618     struct GraphicInfo *gfx = &graphic_info[graphic];
1619     struct XY *pos = tapebutton_info[i].pos;
1620     struct GadgetInfo *gi;
1621     int gd_x = gfx->src_x;
1622     int gd_y = gfx->src_y;
1623     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1624     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1625     int id = i;
1626
1627     gi = CreateGadget(GDI_CUSTOM_ID, id,
1628                       GDI_IMAGE_ID, graphic,
1629                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
1630                       GDI_X, VX + pos->x,
1631                       GDI_Y, VY + pos->y,
1632                       GDI_WIDTH, gfx->width,
1633                       GDI_HEIGHT, gfx->height,
1634                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
1635                       GDI_STATE, GD_BUTTON_UNPRESSED,
1636                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
1637                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
1638                       GDI_DIRECT_DRAW, FALSE,
1639                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
1640                       GDI_CALLBACK_ACTION, HandleTapeButtons,
1641                       GDI_END);
1642
1643     if (gi == NULL)
1644       Error(ERR_EXIT, "cannot create gadget");
1645
1646     tape_gadget[id] = gi;
1647   }
1648 }
1649
1650 void FreeTapeButtons(void)
1651 {
1652   int i;
1653
1654   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1655     FreeGadget(tape_gadget[i]);
1656 }
1657
1658 void MapTapeEjectButton(void)
1659 {
1660   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1661   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1662 }
1663
1664 void MapTapeWarpButton(void)
1665 {
1666   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
1667   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
1668 }
1669
1670 void MapTapeButtons(void)
1671 {
1672   int i;
1673
1674   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1675     if (i != TAPE_CTRL_ID_EXTRA)
1676       MapGadget(tape_gadget[i]);
1677
1678   if (tape.recording || tape.playing)
1679     MapTapeWarpButton();
1680
1681   if (tape.show_game_buttons)
1682     MapGameButtonsOnTape();
1683 }
1684
1685 void UnmapTapeButtons(void)
1686 {
1687   int i;
1688
1689   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1690     UnmapGadget(tape_gadget[i]);
1691
1692   if (tape.show_game_buttons)
1693     UnmapGameButtonsOnTape();
1694 }
1695
1696 void RedrawTapeButtons(void)
1697 {
1698   int i;
1699
1700   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1701     RedrawGadget(tape_gadget[i]);
1702
1703   if (tape.show_game_buttons)
1704     RedrawGameButtonsOnTape();
1705 }
1706
1707 void RedrawOrRemapTapeButtons(void)
1708 {
1709   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
1710   {
1711     // tape buttons already mapped
1712     RedrawTapeButtons();
1713   }
1714   else
1715   {
1716     UnmapTapeButtons();
1717     MapTapeButtons();
1718   }
1719 }
1720
1721 static void HandleTapeButtonsExt(int id)
1722 {
1723   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
1724     return;
1725
1726   switch (id)
1727   {
1728     case TAPE_CTRL_ID_EJECT:
1729       TapeStop();
1730
1731       if (TAPE_IS_EMPTY(tape))
1732       {
1733         LoadTape(level_nr);
1734
1735         if (TAPE_IS_EMPTY(tape))
1736           Request("No tape for this level!", REQ_CONFIRM);
1737       }
1738       else
1739       {
1740         if (tape.changed)
1741           SaveTapeChecked(level_nr);
1742
1743         TapeErase();
1744       }
1745
1746       DrawCompleteVideoDisplay();
1747       break;
1748
1749     case TAPE_CTRL_ID_EXTRA:
1750       if (tape.playing)
1751       {
1752         tape.pause_before_end = !tape.pause_before_end;
1753
1754         DrawVideoDisplayCurrentState();
1755       }
1756       else if (tape.recording)
1757       {
1758         TapeSingleStep();
1759       }
1760
1761       break;
1762
1763     case TAPE_CTRL_ID_STOP:
1764       TapeStop();
1765
1766       break;
1767
1768     case TAPE_CTRL_ID_PAUSE:
1769       TapeTogglePause(TAPE_TOGGLE_MANUAL);
1770
1771       break;
1772
1773     case TAPE_CTRL_ID_RECORD:
1774       if (TAPE_IS_STOPPED(tape))
1775       {
1776         TapeStartGameRecording();
1777       }
1778       else if (tape.pausing)
1779       {
1780         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
1781           TapeAppendRecording();
1782         else
1783           TapeTogglePause(TAPE_TOGGLE_MANUAL);
1784       }
1785
1786       break;
1787
1788     case TAPE_CTRL_ID_PLAY:
1789       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
1790       {
1791         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
1792
1793         TapeTogglePause(TAPE_TOGGLE_MANUAL);
1794       }
1795
1796       if (TAPE_IS_EMPTY(tape))
1797         break;
1798
1799       if (TAPE_IS_STOPPED(tape))
1800       {
1801         TapeStartGamePlaying();
1802       }
1803       else if (tape.playing)
1804       {
1805         if (tape.pausing)                       // PAUSE -> PLAY
1806         {
1807           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
1808         }
1809         else if (!tape.fast_forward)            // PLAY -> FFWD
1810         {
1811           tape.fast_forward = TRUE;
1812         }
1813         else if (!tape.warp_forward)            // FFWD -> WARP
1814         {
1815           tape.warp_forward = TRUE;
1816         }
1817         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
1818         {
1819           tape.deactivate_display = TRUE;
1820
1821           TapeDeactivateDisplayOn();
1822         }
1823         else                                    // WARP BLIND -> PLAY
1824         {
1825           tape.fast_forward = FALSE;
1826           tape.warp_forward = FALSE;
1827           tape.deactivate_display = FALSE;
1828
1829           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1830         }
1831
1832         DrawVideoDisplayCurrentState();
1833       }
1834
1835       break;
1836
1837     case TAPE_CTRL_ID_INSERT_SOLUTION:
1838       InsertSolutionTape();
1839
1840       break;
1841
1842     case TAPE_CTRL_ID_PLAY_SOLUTION:
1843       PlaySolutionTape();
1844
1845       break;
1846
1847     default:
1848       break;
1849   }
1850 }
1851
1852 static void HandleTapeButtons(struct GadgetInfo *gi)
1853 {
1854   HandleTapeButtonsExt(gi->custom_id);
1855 }
1856
1857 void HandleTapeButtonKeys(Key key)
1858 {
1859   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
1860   boolean extra_button_is_active = !eject_button_is_active;
1861
1862   if (key == setup.shortcut.tape_eject && eject_button_is_active)
1863     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
1864   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
1865     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
1866   else if (key == setup.shortcut.tape_stop)
1867     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
1868   else if (key == setup.shortcut.tape_pause)
1869     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
1870   else if (key == setup.shortcut.tape_record)
1871     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
1872   else if (key == setup.shortcut.tape_play)
1873     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
1874 }