Add command line option for various game rendering improvements
[mercenary-reloaded.git] / src / mercenary / main.c
1 /* main routine
2  *
3  * (C) 2018 by Andreas Eversberg <jolly@eversberg.eu>
4  * All Rights Reserved
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <math.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include "../../include/keycodes.h"
28 #include "../libsdl/sdl.h"
29 #ifdef HAVE_OVR
30 #include "../libovr/ovr.h"
31 #include "../libovr/keyboard.h"
32 #endif
33 #include "../libsdl/opengl.h"
34 #include "../libsdl/print.h"
35 #include "../libcpu/m68k.h"
36 #include "../libcpu/execute.h"
37 #include "../libframerate/framerate.h"
38 #include "../libvideo/video.h"
39 #include "../libsound/sound.h"
40 #include "../libjoystick/joystick.h"
41 #include "../libkeyboard/keyboard.h"
42 #include "../libdisk/disk.h"
43 #include "../libtext/text.h"
44 #include "mercenary.h"
45 #include "render.h"
46
47 #define FOV_MIN         10.0
48 #define FOV_NOVAGEN     64.0
49 #define FOV_JOLLY       80.0
50 #define FOV_MAX         170.0
51
52 #define STICK_WALK_THRESHOLD 0.3 /* move the stick until the player moves */
53 #define STICK_ROTATE_THRESHOLD 0.3 /* move the stick until the player rotates */
54 #define STICK_THRUST_THRESHOLD 0.3 /* move the stick until the craft moves */
55
56 static int config_ctrl_c = 0;
57 static int config_amiga_speed = 0; /* fast speed */
58 static double config_fps = 16.0;
59 #if !defined(_WIN32)
60 static const char *config_gamesave_dir = ".mercenary";
61 #endif
62 static int config_video_filter = 1;
63 static int config_audio_filter = 1;
64 static int config_render = 1; /* opengl render */
65 static int config_skip_intro = 0;
66 static int config_multisampling = 8;
67 static double config_fov = FOV_NOVAGEN;
68 static double config_monitor_distance = 31.5; /* inch */
69 #ifdef HAVE_OVR
70 static double config_keyboard_distance = 28.5; /* inch */
71 static double config_keyboard_height = 10.0; /* inch */
72 #endif
73 static double config_benson_size = 1.0;
74 static int config_debug_transparent = 0;
75 static int config_debug_opengl = 0;
76 /* render improvements */
77 static int config_improve_extend_roads = 1;     /* set to 1 to extend roads */
78 static int config_improve_smooth_planets = 1;   /* set to 1 to rotate planets smoothly */
79 static int config_improve_stars_rotation = 1;   /* set to 1 to improve star rendering */
80 static int config_improve_fix_sky_rotation = 0; /* set to 1 to fix sky rotation */
81
82 #define CPU_SPEED       7093790.0;
83
84 #define SOUND_SAMPLERATE 48000
85 /* - game IRQ rate
86  * - must be used for sound rendering chunk
87  */
88 #define IRQ_RATE        50
89 /* numbe of buffer chunks to dejitter:
90  * - SDL render interval
91  * - sound rendering interval
92  * - sound card interval
93  * 4 should be minimum, if video rate is >=50 Hz
94  */
95 #define SOUND_CHUNKS    4
96
97 /* test sound to check if buffer does not overflow / underrun */
98 //#define DEBUG_SOUND_BUFFERING
99
100 #define IOSIZE          0x1000 /* bytes in io space */
101 #define MEMORY_SIZE     0x80000
102 static uint8_t *memory = NULL;
103 static uint8_t *stop_event = NULL;
104 static uint8_t *image = NULL;
105 static uint8_t *help_osd[2] = { NULL, NULL };
106 static uint8_t *info_osd = NULL;
107 static int help_view = 1;
108 static int help_views = 1;
109 static int32_t osd_timer = 0;
110 #ifdef HAVE_OVR
111 #define SCREEN_WIDTH    1344
112 #define SCREEN_HEIGHT   800
113 #else
114 #define SCREEN_WIDTH    (320*3)
115 #define SCREEN_HEIGHT   (200*3)
116 #endif
117 #define IMAGE_WIDTH     320
118 #define IMAGE_HEIGHT    200
119 #define BENSON_AT_LINE  136
120 #define IMAGE_DIWSTART  0x2c
121 #define HELP_ALPHA      0xd0
122 #define OSD_WIDTH       320
123 #define OSD_HEIGHT      16
124 static uint16_t *chipreg = NULL;
125 static stereo_t *sound_buffer = NULL; /* sound buffer memory */
126 static int sound_buffer_size; /* buffer sample size */
127 static int sound_buffer_writep; /* write pointer at buffer */
128 static int sound_buffer_readp; /* read pointer at buffer */
129 static int double_pixel_size = 1; /* render in double size, so each pixle is 2*2 pixles wide */
130 static double benson_size; /* render size of benson */
131 static int render_legacy = 0; /* render original amiga screen, if set */
132 static int render_improved = 0; /* render improved image, if set */
133 static int debug_opengl = 0; /* render both, amiga screen and  improved image, if set */
134 static int intro_skipped = 0; /* indicated if we already have landed */
135 static int window_width, window_height;
136
137 static const char *home_dir;
138
139 static int quit = 0;
140
141 int parse_args(int argc, char *argv[])
142 {
143         int i = 1;
144
145         while (argc > i) {
146                 if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
147                         /*          |                                                                             | */
148                         print_info("Usage: %s\n", argv[0]);
149                         print_info(" -s --render-speed original | fast\n");
150                         print_info("        Set speed of rendering to original Amiga or fast speed.\n");
151                         print_info("    --fps <fps>\n");
152                         print_info("        Set frames per second for fast rate (default = %.1f).\n", config_fps);
153                         print_info(" -v --video-filter on | off\n");
154                         print_info("        Set video filter.\n");
155                         print_info(" -a --audio-filter on | off\n");
156                         print_info("        Set audio filter.\n");
157                         print_info(" -r --render original | opengl\n");
158                         print_info("        Set speed of rendering to original Amiga or OpenGL.\n");
159                         print_info(" -b --benson normal | half\n");
160                         print_info("        Size of 'Benson' (control panel).\n");
161                         print_info(" -m --multisampling <samples>\n");
162                         print_info("        Use multisampling (default = %d) to render the scene.\n", config_multisampling);
163                         print_info(" -f --fov <%.0f..%.0f..%.0f>\n", FOV_MIN, FOV_NOVAGEN, FOV_MAX);
164                         print_info("        Set field-of-view. Default is %.0f.\n", FOV_NOVAGEN);
165                         print_info(" -i --skip-intro\n");
166                         print_info("        Skip intro sequence approaching to Eris space port.\n");
167                         print_info("Improvement options:\n");
168                         print_info("    --extend-roads 1 | 0\n");
169                         print_info("        Roads in the distance end in a single point. This was ok for low\n");
170                         print_info("        resolution, but for OpenGL we want equal width all the way.\n");
171                         print_info("        This requires OpenGL rendering. (default = %d)\n", config_improve_extend_roads);
172                         print_info("    --smooth-planets 1 | 0\n");
173                         print_info("        Planet's rotation uses integer value, so they judder in the original\n");
174                         print_info("        game rendering. This option requires OpenGL rendering. (default = %d)\n", config_improve_smooth_planets);
175                         print_info("    --stars-rotation 1 | 0\n");
176                         print_info("        Stars are rendered originally by using a fast routine. Use this option\n");
177                         print_info("        to make them render on a sphere. They also rotate with the sky then.\n");
178                         print_info("        This requires OpenGL rendering and is default with VR. (default = %d)\n", config_improve_stars_rotation);
179                         print_info("    --fix-sky-rotation 1 | 0\n");
180                         print_info("        Sky rotates in the wrong direction, if flying over planet. This is\n");
181                         print_info("        fixed by rotating all sky object by 180 degrees. The original (wrong)\n");
182                         print_info("        rotation is default, because it preserves the game's spirit!\n");
183                         print_info("        This option requires OpenGL rendering. (default = %d)\n", config_improve_fix_sky_rotation);
184                         print_info("Debug options:\n");
185                         print_info(" -o --debug-opengl\n");
186                         print_info("        Use split screen to display both Amiga and OpenGL rendering.\n");
187                         print_info("    --debug-transparent\n");
188                         print_info("        Draw all things half transparent.\n");
189                         print_info("    --ctrl-c\n");
190                         print_info("        Use CTRL+C to exit game (used for development)\n");
191                         return -1;
192                 } else
193                 if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--render-speed")) {
194                         i++;
195                         if (argc == i) {
196 missing_parameter:
197                                 print_info("Missing parameter, use '--help'!\n");
198                                 return -1;
199                         }
200                         if (!strcmp(argv[i], "original"))
201                                 config_amiga_speed = 1;
202                         else
203                         if (!strcmp(argv[i], "fast"))
204                                 config_amiga_speed = 0;
205                         else {
206 illegal_parameter:
207                                 print_info("Illegal parameter, use '--help'!\n");
208                                 return -1;
209                         }
210                 } else
211                 if (!strcmp(argv[i], "--fps")) {
212                         i++;
213                         if (argc == i)
214                                 goto missing_parameter;
215                         config_fps = atof(argv[i]);
216                         if (config_fov <= 0.0)
217                                 goto illegal_parameter;
218                 } else
219                 if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--video-filter")) {
220                         i++;
221                         if (argc == i)
222                                 goto missing_parameter;
223                         if (!strcmp(argv[i], "on"))
224                                 config_video_filter = 1;
225                         else
226                         if (!strcmp(argv[i], "off"))
227                                 config_video_filter = 0;
228                         else
229                                 goto illegal_parameter;
230                 } else
231                 if (!strcmp(argv[i], "-a") || !strcmp(argv[i], "--audio-filter")) {
232                         i++;
233                         if (argc == i)
234                                 goto missing_parameter;
235                         if (!strcmp(argv[i], "on"))
236                                 config_audio_filter = 1;
237                         else
238                         if (!strcmp(argv[i], "off"))
239                                 config_audio_filter = 0;
240                         else
241                                 goto illegal_parameter;
242                 } else
243                 if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--render")) {
244                         i++;
245                         if (argc == i)
246                                 goto missing_parameter;
247                         if (!strcmp(argv[i], "original"))
248                                 config_render = 0;
249                         else
250                         if (!strcmp(argv[i], "opengl"))
251                                 config_render = 1;
252                         else
253                                 goto illegal_parameter;
254                 } else
255                 if (!strcmp(argv[i], "-b") || !strcmp(argv[i], "--benson")) {
256                         i++;
257                         if (argc == i)
258                                 goto missing_parameter;
259                         if (!strcmp(argv[i], "normal"))
260                                 config_benson_size = 1.0;
261                         else
262                         if (!strcmp(argv[i], "half")) {
263                                 config_benson_size = 0.5;
264                                 if (config_fov == FOV_NOVAGEN)
265                                         config_fov = FOV_JOLLY;
266                         } else
267                                 goto illegal_parameter;
268                 } else
269                 if (!strcmp(argv[i], "-m") || !strcmp(argv[i], "--multisampling")) {
270                         i++;
271                         if (argc == i)
272                                 goto missing_parameter;
273                         config_multisampling = atoi(argv[i]);
274                 } else
275                 if (!strcmp(argv[i], "-f") || !strcmp(argv[i], "--fov")) {
276                         i++;
277                         if (argc == i)
278                                 goto missing_parameter;
279                         config_fov = atof(argv[i]);
280                         if (config_fov < 1.0 || config_fov > 179.0)
281                                 goto illegal_parameter;
282                 } else
283                 if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--skip-intro")) {
284                         config_skip_intro = 1;
285                 } else
286                 if (!strcmp(argv[i], "--extend-roads")) {
287                         i++;
288                         if (argc == i)
289                                 goto missing_parameter;
290                         config_improve_extend_roads = atoi(argv[i]);
291                 } else
292                 if (!strcmp(argv[i], "--smooth-planets")) {
293                         i++;
294                         if (argc == i)
295                                 goto missing_parameter;
296                         config_improve_smooth_planets = atoi(argv[i]);
297                 } else
298                 if (!strcmp(argv[i], "--stars-rotation")) {
299                         i++;
300                         if (argc == i)
301                                 goto missing_parameter;
302                         config_improve_stars_rotation = atoi(argv[i]);
303                 } else
304                 if (!strcmp(argv[i], "--fix-sky-rotation")) {
305                         i++;
306                         if (argc == i)
307                                 goto missing_parameter;
308                         config_improve_fix_sky_rotation = atoi(argv[i]);
309                 } else
310                 if (!strcmp(argv[i], "-o") || !strcmp(argv[i], "--debug-opengl")) {
311                         config_debug_opengl = 1;
312                 } else
313                 if (!strcmp(argv[i], "--debug-transparent")) {
314                         config_debug_transparent = 1;
315                 } else
316                 if (!strcmp(argv[i], "--ctrl-c")) {
317                         config_ctrl_c = 1;
318                 } else {
319                         print_info("Illegal option '%s', use '--help'!\n", argv[i]);
320                         return -1;
321                 }
322                 i++;
323         }
324
325         return 0;
326 }
327
328 static void osd_info(const char *param, const char *value)
329 {
330         char line[41] = "                                        ";
331
332         if (param[0]) {
333                 strncpy(line + 21 - strlen(param), param, strlen(param));
334                 line[22] = ':';
335         }
336         if (strlen(value) > 15) {
337                 print_error("string too long\n");
338                 return;
339         }
340         strncpy(line + 25, value, strlen(value));
341         text_render(info_osd, OSD_WIDTH, OSD_HEIGHT, line, 0x00, 4, 0, 0, 1);
342         osd_timer = ticks_sdl() + 2500;
343 }
344
345 static void resize_window(int width, int height)
346 {
347         window_width = width;
348         window_height = height;
349 }
350
351 #ifdef HAVE_OVR
352 static int __attribute__((unused)) button_a_last = 0, button_b_last = 0, button_x_last = 0, button_y_last = 0, button_menu_last = 0, button_trigger_last = 0, button_left_thumb_last = 0, button_right_thumb_last = 0;
353 static double __attribute__((unused)) stick_left_x_last = 0.0, stick_left_y_last = 0.0, stick_right_x_last = 0.0, stick_right_y_last = 0.0;
354 static int thrust_last = KEYCODE_SPACE;
355 static int keyboard_on = 0;
356 static enum keycode vr_key_pressed = 0, vr_key = 0;
357
358 static void handle_vr_poses(void)
359 {
360         int button_a = 0, button_b = 0, button_x = 0, button_y = 0, button_menu = 0, button_trigger = 0, button_left_thumb = 0, button_right_thumb = 0;
361         double hand_right_x = 0.0, hand_right_y = 0.0, hand_right_z = 0.0;
362         double hand_right_yaw = 0.0, hand_right_pitch = 0.0, hand_right_roll = 0.0;
363         double head_yaw = 0.0, head_pitch = 0.0, head_roll = 0.0;
364         double stick_left_x = 0.0, stick_left_y = 0.0, stick_right_x = 0.0, stick_right_y = 0.0;
365         int thrust = KEYCODE_SPACE;
366
367         get_poses_ovr(&button_a, &button_b, &button_x, &button_y, &button_menu, &button_trigger, &button_left_thumb, &button_right_thumb, &hand_right_x, &hand_right_y, &hand_right_z, &hand_right_yaw, &hand_right_pitch, &hand_right_roll, &stick_left_x, &stick_left_y, &stick_right_x, &stick_right_y, &head_yaw, &head_pitch, &head_roll);
368         if (button_menu && !button_menu_last) {
369                 /* menu toggle */
370                 if (help_view == help_views)
371                         help_view = 0;
372                 else
373                         help_view++;
374         }
375         if (help_view) {
376                 if (button_trigger && !button_trigger_last) {
377                         /* rigger pressed */
378                         normalize_observer_ovr();
379                         osd_info("", "change height");
380                 }
381         } else {
382                 /* handle input */
383                 if (button_a && !button_a_last) {
384                         /* keyboard A toggle */
385                         if (keyboard_on == 1)
386                                 keyboard_on = 0;
387                         else
388                                 keyboard_on = 1;
389                 }
390                 if (button_b && !button_b_last) {
391                         /* keyboard B toggle */
392                         if (keyboard_on == 2)
393                                 keyboard_on = 0;
394                         else
395                                 keyboard_on = 2;
396                 }
397                 if (button_x && !button_x_last) {
398                         /* 'board' pressed */
399                         set_amiga_key(KEYCODE_b, 1);
400                         set_amiga_key(KEYCODE_b, 0);
401                 }
402                 if (button_y && !button_y_last) {
403                         /* 'leave' pressed */
404                         set_amiga_key(KEYCODE_l, 1);
405                         set_amiga_key(KEYCODE_l, 0);
406                 }
407                 if (button_left_thumb && !button_left_thumb_last) {
408                         /* 'escape' pressed */
409                         set_amiga_key(KEYCODE_ESCAPE, 1);
410                         set_amiga_key(KEYCODE_ESCAPE, 0);
411                 }
412                 if (!button_left_thumb && button_left_thumb_last) {
413                         /* 'escape' released */
414                         set_amiga_key(KEYCODE_SPACE, 1);
415                         set_amiga_key(KEYCODE_SPACE, 0);
416                 }
417                 if (button_trigger && !button_trigger_last) {
418                         /* trigger pressed */
419                         if (!keyboard_on) {
420                                 set_joystick(-1, -1, -1, -1, 1);
421                         } else if (vr_key) {
422                                 vr_key_pressed = vr_key;
423                                 set_amiga_key(vr_key_pressed, 1);
424                         }
425                 }
426                 if (!button_trigger && button_trigger_last) {
427                         /* trigger released */
428                         set_joystick(-1, -1, -1, -1, 0);
429                         if (vr_key_pressed) {
430                                 set_amiga_key(vr_key_pressed, 0);
431                                 vr_key_pressed = 0;
432                         }
433                 }
434                 /* joystick */
435                 if (stick_right_x > STICK_ROTATE_THRESHOLD)
436                         set_joystick(0, 1, -1, -1, -1);
437                 else
438                 if (stick_right_x < -STICK_ROTATE_THRESHOLD)
439                         set_joystick(1, 0, -1, -1, -1);
440                 else
441                 if (stick_right_x_last > STICK_ROTATE_THRESHOLD || stick_right_x_last < -STICK_ROTATE_THRESHOLD)
442                         set_joystick(0, 0, -1, -1, -1);
443                 if (stick_right_y > STICK_WALK_THRESHOLD)
444                         set_joystick(-1, -1, 1, 0, -1);
445                 else
446                 if (stick_right_y < -STICK_WALK_THRESHOLD)
447                         set_joystick(-1, -1, 0, 1, -1);
448                 else
449                 if (stick_right_y_last > STICK_WALK_THRESHOLD || stick_right_y_last < -STICK_WALK_THRESHOLD)
450                         set_joystick(-1, -1, 0, 0, -1);
451                 /* thrust */
452                 if (stick_left_y > STICK_THRUST_THRESHOLD)
453                         thrust = (stick_left_y - STICK_THRUST_THRESHOLD) / (1.0 - STICK_THRUST_THRESHOLD) * 10.5;
454                 else
455                 if (stick_left_y < -STICK_THRUST_THRESHOLD)
456                         thrust = (stick_left_y - -STICK_THRUST_THRESHOLD) / (1.0 - -STICK_THRUST_THRESHOLD) * 10.5;
457                 else
458                         thrust = 0;
459                 if (thrust >= 10)
460                         thrust = KEYCODE_0;
461                 else
462                 if (thrust > 0)
463                         thrust = KEYCODE_1 + thrust - 1;
464                 else
465                 if (thrust < 0)
466                         thrust = KEYCODE_F1 - thrust - 1;
467                 else
468                 if (thrust <= -10)
469                         thrust = KEYCODE_F10;
470                 else
471                         thrust = KEYCODE_SPACE;
472                 if (thrust_last != thrust) {
473                         set_amiga_key(thrust, 1);
474                         set_amiga_key(thrust, 0);
475                 }
476         }
477         button_a_last = button_a;
478         button_b_last = button_b;
479         button_x_last = button_x;
480         button_y_last = button_y;
481         button_menu_last = button_menu;
482         button_trigger_last = button_trigger;
483         button_left_thumb_last = button_left_thumb;
484         button_right_thumb_last = button_right_thumb;
485         stick_left_x_last = stick_left_x;
486         stick_left_y_last = stick_left_y;
487         stick_right_x_last = stick_right_x;
488         stick_right_y_last = stick_right_y;
489         thrust_last = thrust;
490
491         /* we must handle keyboard after toggeling keyboard_on,
492          * so that keyboard_on will not change until keyboard is rendered */
493         vr_key = 0;
494         if (keyboard_on)
495                 handle_vr_keyboard(keyboard_on - 1, hand_right_x, hand_right_y, hand_right_z, hand_right_yaw, hand_right_pitch, &vr_key);
496
497         if (stick_right_y > STICK_WALK_THRESHOLD || stick_right_y < -STICK_WALK_THRESHOLD) {
498                 double roll, pitch, yaw;
499                 double dist, east, north;
500                 int32_t move_east[4], move_north[4];
501
502                 mercenary_get_orientation(&roll, &pitch, &yaw);
503                 /* we use a maximum move of 40 for all 4 steps (this is 10 for each step - equal to 'running') */
504                 if (stick_right_y > 0.0)
505                         dist = (stick_right_y - STICK_WALK_THRESHOLD) / (1.0 - STICK_WALK_THRESHOLD) * 40.0;
506                 else
507                         dist = (stick_right_y + STICK_WALK_THRESHOLD) / (1.0 - STICK_WALK_THRESHOLD) * 40.0;
508                 east = sin(hand_right_yaw + yaw + M_PI) * dist;
509                 north = -cos(hand_right_yaw + yaw + M_PI) * dist;
510                 /* calculatate the integer positions of 4 steps */
511                 move_east[0] = (int32_t)((east * 0.25) + 0.5);
512                 move_north[0] = (int32_t)((north * 0.25) + 0.5);
513                 move_east[1] = (int32_t)((east * 0.5) + 0.5);
514                 move_north[1] = (int32_t)((north * 0.5) + 0.5);
515                 move_east[2] = (int32_t)((east * 0.75) + 0.5);
516                 move_north[2] = (int32_t)((north * 0.75) + 0.5);
517                 move_east[3] = (int32_t)(east + 0.5);
518                 move_north[3] = (int32_t)(north + 0.5);
519                 /* calculate the delta between each of the 4 step */
520                 move_east[3] -= move_east[2];
521                 move_north[3] -= move_north[2];
522                 move_east[2] -= move_east[1];
523                 move_north[2] -= move_north[1];
524                 move_east[1] -= move_east[0];
525                 move_north[1] -= move_north[0];
526                 /* the game takes 4 steps to move the player */
527                 mercenary_vr_move(1, move_east, move_north,
528                         256,
529                         (int)(256.0 * fabs(stick_right_y) - STICK_WALK_THRESHOLD / (1.0 - STICK_WALK_THRESHOLD) + 0.5));
530         } else {
531                 /* don't change what the game actually does when moving joystick in y-direction */
532                 mercenary_vr_move(0, NULL, NULL, 256, 256);
533         }
534 }
535 #endif
536
537 static void skip_intro(void)
538 {
539         int event;
540         double render_delay = 0.0;
541         double cycle_count;
542
543         if (intro_skipped)
544                 return;
545
546         print_info("*** Skipping intro, fast forwarding... ***\n\n");
547         do {
548                 /* render, if not delayed */
549                 if (render_delay <= 0.0) {
550                         cycle_count = 0;
551                         do {
552                                 cycle_count += execute_cpu(0, &event);
553                         } while (event != STOP_AT_WAIT_VBL && event != STOP_AT_CLEAR_SCREEN1);
554                         render_delay += (double)cycle_count / CPU_SPEED;
555                 }
556                 /* VBL */
557                 execute_cpu(3, NULL);
558                 /* count down render delay */
559                 if (render_delay) {
560                         render_delay -= 1.0 / (double)IRQ_RATE;
561                         if (render_delay < 0.0)
562                                 render_delay = 0.0;
563                 }
564         } while (event != STOP_AT_CLEAR_SCREEN1);
565
566         intro_skipped = 1;
567 }
568
569 static void special_event(int event)
570 {
571 #ifdef HAVE_OVR
572         /* handle VR events */
573         if (event == STOP_AT_PATCH_VR) {
574                 mercenary_patch_vr();
575                 return;
576         }
577 #endif
578         /* handle events to improve rendering */
579         if (render_improved)
580                 render_capture_event(event);
581 }
582
583 static void main_loop(void)
584 {
585         double frame_step, frame_time = 0.0, frame_render = 1;
586         int had_first_irq = 0;
587         static uint32_t current_time, last_time = 0, diff;
588         int i, rc;
589         int space, length;
590         int cycle_count, event = STOP_AT_END;
591         double render_delay = 0.0;
592         uint32_t palette_address;
593         uint16_t palette[16];
594 #ifdef HAVE_OVR
595         int eye;
596 #endif
597
598         last_time = ticks_sdl();
599
600         /* render result on window */
601         while (!quit) {
602 #ifdef HAVE_OVR
603                 /* get vr poses */
604                 handle_vr_poses();
605 #endif
606                 /* if we are in interstellar fligt, we use 50 Hz */
607                 /* if we are approaching to Eris Space Port, we use 10 Hz */
608                 /* else we use whatever frame rate the user wants */
609                 if (render_capture_is_interstellar())
610                         frame_step = vbl_duration * 50.0;
611                 else if (!intro_skipped)
612                         frame_step = vbl_duration * 10.0;
613                 else
614                         frame_step = vbl_duration * config_fps;
615                 if (frame_step > 1.0)
616                         frame_step = 1.0;
617                 /* handle SDL events */
618                 rc = event_sdl();
619                 if (rc)
620                         break;
621
622                 /* initialize rendering */
623                 debug_opengl = config_debug_opengl;
624                 benson_size = config_benson_size;
625                 render_legacy = (!config_render) || debug_opengl;
626                 render_improved = config_render || debug_opengl;
627                 if (!render_improved) {
628                         /* be sure to clean all capture history, so we don't get glichtes when turning on improved rendering again */
629                         render_capture_reset();
630                 }
631                 /* STEP 1: let the CPU render/process the game, also improve rendering via OpenGL, if enabled */
632                 /* amgia speed: don't render if we still delay */
633                 /* non amiga speed: render if we need a new frame */
634                 /* NOTE: at input event we must render after every VBL, so we do this in every loop */
635                 /* in case of help view: stop cpu after first IRQ, regardless of other options */
636                 /* NOTE: We need initial IRQ, so we have out copper list initialized */
637                 if (((frame_render && !config_amiga_speed)
638                   || (config_amiga_speed && render_delay <= 0.0)
639                   || event == STOP_AT_WAIT_INPUT)
640                 && !(had_first_irq && help_view)) {
641                         frame_render = 0;
642                         /* start capturing for improved graphics */
643                         if (render_improved)
644                                 render_capture_start(config_fov, config_improve_extend_roads, config_improve_smooth_planets, config_improve_stars_rotation, config_improve_fix_sky_rotation, config_debug_transparent);
645
646                         /* execute until the rendered image is ready (wait for VBL) */
647                         cycle_count = 0;
648                         do {
649                                 cycle_count += execute_cpu(0, &event);
650                                 /* handle special events */
651                                 special_event(event);
652                                 if (event == STOP_AT_CLEAR_SCREEN1)
653                                         intro_skipped = 1;
654                         } while (event != STOP_AT_WAIT_VBL && event != STOP_AT_WAIT_INPUT);
655                         /* stop capturing for improved graphics */
656                         if (render_improved)
657                                 render_capture_stop();
658                         /* copy palette */
659                         palette_address = mercenary_palette_view();
660                         for (i = 0; i < 16; i++)
661                                 palette[i] = m68k_read_memory_16(palette_address + i*2);
662                         /* for amiga speed: set delay by the number of cycles */
663                         if (config_amiga_speed)
664                                 render_delay += (double)cycle_count / CPU_SPEED;
665                 }
666
667                 /* STEP 2: transfer legacy image (or just benson) in memory to OpenGL texture */
668 #ifdef HAVE_OVR
669                 begin_render_ovr();
670
671                 for (eye = 0; eye < 2; eye++) {
672                         double camera_x, camera_y, camera_z;
673                         /* begin of rendering eye, viewport and frustum is set here */
674                         begin_render_ovr_eye(eye, &camera_x, &camera_y, &camera_z);
675 #else
676                 {
677 #endif
678                         /* clear screen */
679 #ifdef HAVE_OVR
680                         opengl_clear(1);
681 #else
682                         opengl_clear(0);
683 #endif
684                         /* render benson + osd ontop of improved opengl rendering, if enabled */
685                         if (render_improved) {
686 #ifndef HAVE_OVR
687                                 /* viewport and frustum is set here */
688                                 opengl_viewport(window_width, window_height, (debug_opengl) ? 2 : 0, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, benson_size);
689 #endif
690                                 /* render improved graphics, interpolate, if required,
691                                  * if no item list is available, for legacy rendering
692                                  */
693 #ifdef HAVE_OVR
694                                 rc = render_all_items((config_amiga_speed) ? 1.0 : frame_time, 1);
695 #else
696                                 rc = render_all_items((config_amiga_speed) ? 1.0 : frame_time, 0);
697 #endif
698                                 if (rc)
699                                         goto goto_legacy;
700 #ifdef HAVE_OVR
701                                 opengl_blit_image(image, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, 1, config_fov, config_monitor_distance, benson_size, 1);
702 #else
703                                 opengl_blit_image(image, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, 1, config_fov, config_monitor_distance, benson_size, 0);
704 #endif
705                                 if (help_view)
706                                         opengl_blit_osd(0, help_osd[help_view - 1], config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, config_monitor_distance, benson_size, 1.0, 1.0, 0.0, 0.0);
707                                 if (osd_timer) {
708                                         opengl_blit_osd(1, info_osd, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, config_monitor_distance, benson_size, 0.5, 0.04, 0.5, -0.95);
709                                         if (osd_timer - (int32_t)ticks_sdl() < 0)
710                                                 osd_timer = 0;
711                                 }
712                         }
713                         /* setup viewport for legacy image and render image, if enabled */
714                         /* also render legacy, if render_improved failed due to not (yet) available items */
715                         if (render_legacy) {
716                                 goto_legacy:
717                                 /* render game view without benson
718                                  * because benson is not updated before VBL IRQ, we don't want old image from double buffer
719                                  */
720                                 if (had_first_irq)
721                                         emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, 0, BENSON_AT_LINE, double_pixel_size);
722 #ifndef HAVE_OVR
723                                 /* viewport and frustum is set here */
724                                 opengl_viewport(window_width, window_height, (debug_opengl) ? 1 : 0, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, 1.0);
725 #endif
726                                 opengl_blit_image(image, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, 0, config_fov, config_monitor_distance, 1.0, 0);
727                                 if (help_view)
728                                         opengl_blit_osd(0, help_osd[help_view - 1], config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, config_monitor_distance, 1.0, 1.0, 1.0, 0.0, 0.0);
729                                 if (osd_timer) {
730                                         opengl_blit_osd(1, info_osd, config_video_filter, (double_pixel_size) ? BENSON_AT_LINE * 2 : BENSON_AT_LINE, config_fov, config_monitor_distance, 1.0, 0.5, 0.04, 0.5, -0.95);
731                                         if (osd_timer - (int32_t)ticks_sdl() < 0)
732                                                 osd_timer = 0;
733                                 }
734                         }
735 #ifdef HAVE_OVR
736                         /* render keyboard */
737                         if (keyboard_on)
738                                 render_vr_keyboard(keyboard_on - 1, camera_x, camera_y);
739
740                         /* end of rendering eye */
741                         end_render_ovr_eye(eye);
742                 }
743                 /* at this point we are ready with our image, so we display */
744                 end_render_ovr();
745                 render_mirror_ovr(window_width, window_height);
746 #else
747                 }
748 #endif
749                 swap_sdl();
750
751                 /* advance frame time, if we are not in help view  */
752                 if (!(had_first_irq && help_view)) {
753                         frame_time += frame_step;
754                         if (frame_time >= 1.0) {
755                                 frame_time -= 1.0;
756                                 frame_render = 1;
757                         }
758                 }
759
760                 /* measure frame rate */
761                 framerate_measure();
762
763                 /* STEP 3: execute interrupt at rate of 50Hz, render sound */
764                 /* only do this, if we are not in help view */
765                 /* NOTE: We need initial IRQ, so we have out copper list initialized */
766                 if (!(had_first_irq && help_view)) {
767                         current_time = ticks_sdl();
768                         diff = current_time - last_time;
769                         /* in case of timer glitch, execute IRQ only by maximum number of SOUND_CHUNKS */
770                         if (diff > 1000 * SOUND_CHUNKS / IRQ_RATE) {
771                                 diff = 1000 * SOUND_CHUNKS / IRQ_RATE;
772                                 last_time = current_time - 1000 * SOUND_CHUNKS / IRQ_RATE;
773                         }
774                         while (diff > 1000 / IRQ_RATE) {
775                                 /* trigger and execute IRQ 3 = VBL */
776                                 execute_cpu(3, NULL);
777                                 had_first_irq = 1;
778                                 /* transfer benson without game view
779                                  * because we only got benson refreshed during VBL IRQ
780                                  */
781                                 emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, BENSON_AT_LINE, IMAGE_HEIGHT, double_pixel_size);
782                                 /* render sound to sound buffer
783                                  * buffer pointer read and write is atomic, so no locking required!
784                                  */
785                                 space = (sound_buffer_readp - sound_buffer_writep - 1 + sound_buffer_size) % sound_buffer_size;
786                                 if (space < SOUND_SAMPLERATE / IRQ_RATE) {
787 #ifdef DEBUG_SOUND_BUFFERING
788                                         fprintf(stderr, "sound buffer overflow\n");
789 #endif
790                                         length = space;
791                                 } else
792                                         length = SOUND_SAMPLERATE / IRQ_RATE;
793 #ifdef DEBUG_SOUND_BUFFERING
794                                 printf("can write %d, write %d\n", space, length);
795                                 static int cnt = 0;
796                                 int s;
797                                 for (s = 0; s < length; s++) {
798                                         sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].left =
799                                         sound_buffer[(sound_buffer_writep + s) % sound_buffer_size].right
800                                                 = sin(2 * M_PI * 999 * cnt / SOUND_SAMPLERATE)
801                                                 * sin(2 * M_PI * 21 * cnt / SOUND_SAMPLERATE)
802                                                 * sin(2 * M_PI * 0.5 * cnt / SOUND_SAMPLERATE);
803                                          cnt++;
804                                 }
805 #else
806                                 render_sound(memory, sound_buffer, sound_buffer_size, sound_buffer_writep, length, config_audio_filter);
807 #endif
808                                 sound_buffer_writep = (sound_buffer_writep + length) % sound_buffer_size;
809                                 diff -= 1000 / IRQ_RATE;
810                                 last_time += 1000 / IRQ_RATE;
811
812                                 /* count down render delay */
813                                 if (render_delay) {
814                                         render_delay -= 1.0 / (double)IRQ_RATE;
815                                         if (render_delay < 0.0)
816                                                 render_delay = 0.0;
817                                 }
818                         }
819                 }
820         }
821 }
822
823 static uint16_t io_read(uint32_t address)
824 {
825         uint16_t value = 0xffff;
826
827         /* joystick and fire button */
828         if (address == 0xbfe000 || address == 0xdff00c)
829                 value &= emulate_joystick_read(address);
830         /* keyboard */
831         if (address == 0xbfec00 || address == 0xbfed00 || address == 0xbfee00)
832                 value &= emulate_keyboard_read(address);
833         /* diskette */
834         if (address == 0xbfd100 || address == 0xbfe000 || address == 0xdff01a || address == 0xdff01e)
835                 value &= emulate_disk_read(address);
836
837         return value;
838 }
839
840 static void io_write(uint32_t address, uint16_t value)
841 {
842         /* dmacon and sound registers */
843         if (address == 0xdff096 || address == 0xdff09a || (address >= 0xdff0a0 && address <= 0xdff0df))
844                 emulate_sound_write(address, value, SOUND_SAMPLERATE);
845         if (address == 0xbfd100 || (address >= 0xdff020 && address <= 0xdff024))
846                 emulate_disk_write(address, value);
847 }
848
849 /* two tracks with 0x1820 words of length */
850 static uint8_t game_save[2][0x1820 << 1];
851 static int last_track = 0;
852
853 /* game reads track with saved game */
854 static void disk_read(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
855 {
856         if (length > sizeof(game_save[0])) {
857                 print_error("loading game state failed, because length exceeds game save data size, please fix!\n");
858                 return;
859         }
860
861         /* if even track is selected, load game */
862         if (!(track & 1)) {
863                 char filename[256];
864                 int gamesave_num = (track - 2) >> 1;
865                 int got;
866                 FILE *fp;
867
868                 memset(game_save, 0, sizeof(game_save)); /* clear so make the game fail, if we fail */
869 #if defined(_WIN32)
870                 filename[0] = '\0';
871 #else
872                 sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
873                 mkdir(filename, 0777);
874 #endif
875                 sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
876                 fp = fopen(filename, "r");
877                 if (!fp) {
878 fail:
879                         print_info("failed to load game from '%s'\n", filename);
880                         goto copy;
881                 }
882                 got = fread(game_save, sizeof(game_save[0]), 2, fp);
883                 fclose(fp);
884                 if (got != 2)
885                         goto fail;
886         }
887
888 copy:
889         /* copy track */
890         memcpy(memory + data, game_save[track & 1], length /* sizeof(game_save[0])*/);
891 }
892
893 /* game writes track with saved game */
894 static void disk_write(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
895 {
896         /* skip sync info that is provided by game and only relevant for a real disk track */
897         data += 0x200;
898         length -= 0x200;
899
900         if (length != sizeof(game_save[0])) {
901                 print_error("saving game state failed, because length of data does not match, please fix!\n");
902                 return;
903         }
904
905         /* don't save if last track is the same, because disk is written on both sides with the same data */
906         if (track == last_track) {
907                 if (memcmp(memory + data, game_save[track & 1], length)) {
908                         print_error("saving game data on other side of the disk is different, please fix!\n");
909                 }
910                 return;
911         }
912         last_track = track;
913
914         /* save game data */
915         memcpy(game_save[track & 1], memory + data, length);
916
917         /* if done with saving */
918         if ((track & 1)) {
919                 char filename[256];
920                 int gamesave_num = (track - 2) >> 1;
921                 int wrote;
922                 FILE *fp;
923
924 #if defined(_WIN32)
925                 filename[0] = '\0';
926 #else
927                 sprintf(filename, "%s/%s/", home_dir, config_gamesave_dir);
928                 mkdir(filename, 0777);
929 #endif
930                 sprintf(filename + strlen(filename), "%d%s", gamesave_num, mercenary_gamesavesuffix);
931                 fp = fopen(filename, "w");
932                 if (!fp) {
933 fail:
934                         print_error("failed to save game to '%s'\n", filename);
935                         return;
936                 }
937                 print_info("Game state saved to '%s'\n", filename);
938                 wrote = fwrite(game_save, sizeof(game_save[0]), 2, fp);
939                 fclose(fp);
940                 if (wrote != 2)
941                         goto fail;
942         }
943 }
944
945 static int shift = 0, ctrl = 0;
946
947 static void keyboard_sdl(int down, enum keycode keycode)
948 {
949         switch (keycode) {
950         case KEYCODE_LCTRL:
951         case KEYCODE_RCTRL:
952                 ctrl = down;
953                 break;
954         default: break;
955         }
956
957         if (ctrl && down) {
958                 switch (keycode) {
959                 case KEYCODE_h:
960                         if (help_view == help_views)
961                                 help_view = 0;
962                         else
963                                 help_view++;
964                         break;
965                 case KEYCODE_v:
966                         config_video_filter ^= 1;
967                         osd_info("video filter", (config_video_filter) ? "on" : "off");
968                         break;
969                 case KEYCODE_a:
970                         config_audio_filter ^= 1;
971                         osd_info("audio filter", (config_audio_filter) ? "on" : "off");
972                         break;
973                 case KEYCODE_s:
974                         config_amiga_speed ^= 1;
975                         osd_info("render speed", (config_amiga_speed) ? "original" : "fast");
976                         break;
977                 case KEYCODE_r:
978                         config_render ^= 1;
979                         osd_info("render mode", (config_render) ? "OpenGL" : "original");
980                         break;
981                 case KEYCODE_b:
982                         if (!config_render && !config_debug_opengl) {
983                                 osd_info("", "not applicable");
984                                 break;
985                         }
986                         if (config_benson_size == 0.5) {
987                                 config_benson_size = 1.0;
988                                 config_fov = FOV_NOVAGEN;
989                         } else {
990                                 config_benson_size = 0.5;
991                                 config_fov = FOV_JOLLY;
992                         }
993                         osd_info("Benson size", (config_benson_size == 0.5) ? "half" : "normal");
994                         break;
995                 case KEYCODE_i:
996                         if (!intro_skipped)
997                                 skip_intro();
998                         else
999                                 osd_info("", "not applicable");
1000                         break;
1001                 case KEYCODE_c:
1002                         if (config_ctrl_c)
1003                                 quit = 1;
1004                         break;
1005                 case KEYCODE_o:
1006 #ifdef HAVE_OVR
1007                         normalize_observer_ovr();
1008                         osd_info("", "change height");
1009 #else
1010                         osd_info("", "not applicable");
1011 #endif
1012                         break;
1013                 case KEYCODE_KP_PLUS:
1014                         if (config_fov / 1.2 >= FOV_MIN)
1015                                 config_fov /= 1.2;
1016                         disp_fov:
1017                         {
1018                                 char text[16];
1019                                 sprintf(text, "%.2f", config_fov);
1020                                 osd_info("FOV", text);
1021                         }
1022                         break;
1023                 case KEYCODE_KP_MINUS:
1024                         if (config_fov * 1.2 <= FOV_MAX)
1025                                 config_fov *= 1.2;
1026                         goto disp_fov;
1027                 default: break;
1028                 }
1029                 /* do not pass keys to game while holding CTRL */
1030                 return;
1031         }
1032
1033         if (keycode == KEYCODE_PAUSE && down) {
1034                 if (help_view == help_views)
1035                         help_view = 0;
1036                 else
1037                         help_view++;
1038         }
1039
1040         /* in help view we must not forward keypresses */
1041         if (help_view)
1042                 return;
1043
1044         switch (keycode) {
1045         case KEYCODE_LSHIFT:
1046                 set_amiga_key(keycode, down);
1047                 shift = down;
1048                 break;
1049         case KEYCODE_RSHIFT:
1050                 set_amiga_key(keycode, down);
1051                 shift = down;
1052                 break;
1053         case KEYCODE_LEFT:
1054                 if (shift && down) {
1055                         set_amiga_key(keycode, down);
1056                         set_joystick(-1, -1, -1, -1, -1);
1057                         break;
1058                 }
1059                 set_amiga_key(keycode, 0);
1060                 set_joystick(down, -1, -1, -1, -1);
1061                 break;
1062         case KEYCODE_RIGHT:
1063                 if (shift && down) {
1064                         set_amiga_key(keycode, down);
1065                         set_joystick(-1, -1, -1, -1, -1);
1066                         break;
1067                 }
1068                 set_amiga_key(keycode, 0);
1069                 set_joystick(-1, down, -1, -1, -1);
1070                 break;
1071         case KEYCODE_UP:
1072                 if (shift && down) {
1073                         set_amiga_key(keycode, down);
1074                         set_joystick(-1, -1, -1, -1, -1);
1075                         break;
1076                 }
1077                 set_amiga_key(keycode, 0);
1078                 set_joystick(-1, -1, down, -1, -1);
1079                 break;
1080         case KEYCODE_DOWN:
1081                 if (shift && down) {
1082                         set_amiga_key(keycode, down);
1083                         set_joystick(-1, -1, -1, -1, -1);
1084                         break;
1085                 }
1086                 set_amiga_key(keycode, 0);
1087                 set_joystick(-1, -1, -1, down, -1);
1088                 break;
1089         case KEYCODE_END:
1090                 set_joystick(-1, -1, -1, -1, down);
1091                 break;
1092         case KEYCODE_INSERT:
1093                 set_amiga_key(KEYCODE_HELP, down);
1094                 break;
1095         default:
1096                 set_amiga_key(keycode, down);
1097         }
1098 }
1099
1100 void audio_sdl(float *data, int length)
1101 {
1102         int fill, s;
1103
1104         /* read sound from sound buffer
1105          * buffer pointer read and write is atomic, so no locking required!
1106          */
1107         fill = (sound_buffer_writep - sound_buffer_readp + sound_buffer_size) % sound_buffer_size;
1108         if (fill < length) {
1109 #ifdef DEBUG_SOUND_BUFFERING
1110                 fprintf(stderr, "sound buffer underrun\n");
1111 #endif
1112                 /* correct read pointer as if the buffer would have 'length' of samples stored inside */
1113                 sound_buffer_readp = (sound_buffer_readp + fill - length + sound_buffer_size) % sound_buffer_size;
1114         }
1115         for (s = 0; s < length; s++) {
1116                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].left;
1117                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size].right;
1118         }
1119 #ifdef DEBUG_SOUND_BUFFERING
1120         printf("fill %d = %.4f\n", length, sound_buffer[sound_buffer_readp][0]);
1121 #endif
1122         sound_buffer_readp =(sound_buffer_readp + length) % sound_buffer_size;
1123 }
1124
1125 void sound_irq(void)
1126 {
1127         /* trigger and execute IRQ 4 = sound */
1128         execute_cpu(4, NULL);
1129 }
1130
1131 int main(int argc, char *argv[])
1132 {
1133         int rc;
1134         int sdl_sound_chunk;
1135
1136         home_dir = getenv("HOME");
1137         if (!home_dir)
1138                 home_dir = "";
1139
1140         rc = parse_args(argc, argv);
1141         if (rc)
1142                 return 0;
1143
1144         /* allocate image */
1145         image = calloc(IMAGE_WIDTH * IMAGE_HEIGHT * ((double_pixel_size) ? 4 : 1), 3);
1146         if (!image) {
1147                 print_error("Failed to allocate image buffer\n");
1148                 goto done;
1149         }
1150
1151         if ((SOUND_SAMPLERATE % IRQ_RATE)) {
1152                 print_error("Sample rate must be a multiple of IRQ rate, please fix!\n");
1153                 goto done;
1154         }
1155         if ((1000 % IRQ_RATE)) {
1156                 print_error("1000 (Ticks per second) rate must be a multiple of IRQ rate, please fix!\n");
1157                 goto done;
1158         }
1159
1160         /* calculate SDL chunk size for audio
1161          * it must be a power of two, but not more than the chunk size for each IRQ!
1162          */
1163         for (sdl_sound_chunk = 2; sdl_sound_chunk <= (SOUND_SAMPLERATE / IRQ_RATE); sdl_sound_chunk <<= 1)
1164                 ;
1165         sdl_sound_chunk >>= 1;
1166 //      printf("samples per IRQ = %d, samples per SDL audio = %d\n", SOUND_SAMPLERATE / IRQ_RATE, sdl_sound_chunk); exit(0);
1167
1168         /* allocate sound buffers */
1169         sound_buffer_size = SOUND_SAMPLERATE / IRQ_RATE * SOUND_CHUNKS;
1170         sound_buffer = calloc(sound_buffer_size, sizeof(*sound_buffer));
1171         if (!sound_buffer) {
1172                 print_error("Failed to allocate image buffer\n");
1173                 goto done;
1174         }
1175
1176         /* allocate memory */
1177         memory = calloc(MEMORY_SIZE, 1);
1178         if (!memory) {
1179                 print_error("Failed to allocate cpu's memory\n");
1180                 goto done;
1181         }
1182         stop_event = calloc(MEMORY_SIZE, 1);
1183         if (!stop_event) {
1184                 print_error("Failed to allocate cpu's stop_event memory\n");
1185                 goto done;
1186         }
1187         chipreg = calloc(IOSIZE, 1);
1188         if (!chipreg) {
1189                 print_error("Failed to allocate chip register\n");
1190                 goto done;
1191         }
1192
1193         /* init cpu code */
1194         execute_init(MEMORY_SIZE, memory, stop_event, chipreg, io_read, io_write, mercenary_stop_at);
1195
1196         /* init disk emulation */
1197         disk_init(disk_read, disk_write);
1198
1199         /* load binary */
1200         mercenary_load();
1201
1202         /* patch some stuff */
1203         mercenary_patch();
1204
1205         /* init SDL and OpenGL */
1206 #ifdef HAVE_OVR
1207         int vbl_sync = 0;
1208         int rift = 1;
1209         int multisampling = 0;
1210         window_width = SCREEN_WIDTH;
1211         window_height = SCREEN_HEIGHT;
1212 #else
1213         int vbl_sync = 1;
1214         int rift = 0;
1215         int multisampling = config_multisampling;
1216         window_width = (config_debug_opengl) ? SCREEN_WIDTH / 3 * 2 : SCREEN_WIDTH;
1217         window_height = (config_debug_opengl) ? SCREEN_HEIGHT / 3 * 4 : SCREEN_HEIGHT;
1218 #endif
1219         rc = init_sdl(argv[0], window_width, window_height, SOUND_SAMPLERATE, sdl_sound_chunk, keyboard_sdl, audio_sdl, resize_window, multisampling, vbl_sync, rift);
1220         if (rc < 0)
1221                 goto done;
1222 #ifdef HAVE_OVR
1223         rc = init_ovr(config_multisampling);
1224         if (rc < 0)
1225                 goto done;
1226         rc = init_vr_keyboard(config_keyboard_height, config_keyboard_distance);
1227         if (rc < 0)
1228                 goto done;
1229 #endif
1230         rc = init_opengl_image((double_pixel_size) ? IMAGE_WIDTH * 2 : IMAGE_WIDTH, (double_pixel_size) ? IMAGE_HEIGHT * 2 : IMAGE_HEIGHT);
1231         if (rc < 0)
1232                 goto done;
1233
1234         /* init osd */
1235         rc = init_opengl_osd(0, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2);
1236         if (rc < 0)
1237                 goto done;
1238         rc = init_opengl_osd(1, OSD_WIDTH, OSD_HEIGHT);
1239         if (rc < 0)
1240                 goto done;
1241         help_osd[0] = text_alloc(IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, HELP_ALPHA);
1242         if (!help_osd[0])
1243                 goto done;
1244         text_render(help_osd[0], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, mercenary_name, HELP_ALPHA, 3, (double)(80 - strlen(mercenary_name)) / 2.0, 1, 1);
1245         text_render(help_osd[0], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2,
1246                 "Emulation:\n"
1247                 "        Press `PAUSE' to toggle this help screen on or off.\n"
1248                 "        Press `CTRL' + `F' to toggle between full screen / window mode.\n"
1249                 "        Press `CTRL' + `R' to toggle between original / OpenGL rendering.\n"
1250                 "        Press `CTRL' + `S' to toggle between original / fast rendering.\n"
1251                 "        Press `CTRL' + `B' to toggle between large / small Benson.\n"
1252                 "        Press `CTRL' + `V' to toggle video filter on / off.\n"
1253                 "        Press `CTRL' + `A' to toggle audio filter on / off.\n"
1254                 "        Press `CTRL' + `+' or `-' to change field-of-view (OpenGL).\n"
1255                 "        Press `CTRL' + `I' to skip intro (approaching to Eris).\n"
1256 #ifdef HAVE_OVR
1257                 "        Press `CTRL' + `O' (or right trigger) to reset observer position.\n"
1258 #endif
1259                 "\n"
1260                 "Answer to a Question:\n"
1261                 "        Press `O' (not Zero) for OK and other key for NO.\n"
1262                 "\n"
1263                 "Walking / Driving / Flying:\n"
1264                 "        Use cursor keys as joystick, to move player / craft.\n"
1265                 "        Press `R' for running, 'W' for walking speed.\n"
1266                 "        Press `B' to board, `L' to leave.\n"
1267                 "        Press `1'...`0' to drive / fly (slow...fast), `+' or `-' to adjust.\n"
1268                 "        Press `F1'...`F0' to drive / fly backwards (slow...fast).\n"
1269                 "        Press `SPACE' to stop craft.\n"
1270                 "        Press `ESCAPE' to activate escape sequence on crafts.\n"
1271                 "        Press `T' for turbo on certain craft.\n"
1272                 "        Press `END' as joystick's fire button.\n"
1273                 "\n"
1274                 "Elevator:\n"
1275                 "        Press `1'...`9' to select floor, 'G' for ground, `B' for basement.\n"
1276                 "\n"
1277                 "Inside a transporter:\n"
1278                 "        Press `1'...`0' to select destination.\n"
1279                 "\n"
1280                 "Items:\n"
1281                 "        Press `SHFIT' + cursor left / right keys to choose item.\n"
1282                 "        Press `SHFIT' + cursor up / down keys to pickup / drop item.\n"
1283                 "        Press `NUMPAD Enter' to select certain items.\n"
1284                 "        Press `NUMPAD +' / `NUMPAD -' to select entries.\n"
1285                 "        Press `NUMPAD *' to read entry\n"
1286                 "Saving / Loading / Pause:\n"
1287                 "        Press `INSERT' to loading and saving options.\n"
1288                 "        Press `ENTER' to pause game, other key to continue.\n"
1289                 ,HELP_ALPHA, 1, 2, 5, 0);
1290 #ifdef HAVE_OVR
1291         help_osd[1] = text_alloc(IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, HELP_ALPHA);
1292         if (!help_osd[1])
1293                 goto done;
1294         text_render(help_osd[1], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, mercenary_name, HELP_ALPHA, 3, (double)(80 - strlen(mercenary_name)) / 2.0, 1, 1);
1295         text_render(help_osd[1], IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2,
1296                 "Emulation using Controller:\n"
1297                 "        Press `Enter' button to toggle this help screen on or off.\n"
1298                 "        Press `A' button to emulate keyboard to control game.\n"
1299                 "        Press `B' button to emulate keyboard to enter alphanumeric keys.\n"
1300                 "        Press `A' or `B' button again to dismiss keyboard.\n"
1301                 "        Point right controller to a key on keyboard. The key will highlight.\n"
1302                 "        Press `Trigger' on right controller enter the highlighted key.\n"
1303                 "\n"
1304                 "Walking / Driving / Flying using Controller:\n"
1305                 "        Use thumb stick on right controller, to move player / craft.\n"
1306                 "        Press `X' button to board, `Y' button to leave.\n"
1307                 "        Move thumb stick on left controller to drive/fly forward or backward.\n"
1308                 "        Press and hold thumb stick on left controller for escape sequence.\n"
1309                 "        Release thumb stick on left controller stop craft.\n"
1310                 "        Press `Trigger' on right controller to fire.\n"
1311                 "\n"
1312                 "For all other game function, use the emulated keyboards!\n"
1313                 ,HELP_ALPHA, 1, 2, 5, 0);
1314         help_views = 2;
1315 #endif
1316         info_osd = text_alloc(OSD_WIDTH, OSD_HEIGHT, 0x00);
1317         if (!info_osd)
1318                 goto done;
1319
1320         /* init audio */
1321         sound_init(SOUND_SAMPLERATE, sound_irq);
1322
1323         /* start cpu */
1324         reset_cpu();
1325
1326         if (config_skip_intro)
1327                 skip_intro();
1328
1329         /* run game */
1330         main_loop();
1331
1332 done:
1333         exit_opengl();
1334 #ifdef HAVE_OVR
1335         exit_ovr();
1336 #endif
1337         exit_sdl();
1338
1339         if (chipreg)
1340                 free(chipreg);
1341         if (stop_event)
1342                 free(stop_event);
1343         if (memory)
1344                 free(memory);
1345         if (sound_buffer)
1346                 free(sound_buffer);
1347         if (image)
1348                 free(image);
1349         if (help_osd[0])
1350                 free(help_osd[0]);
1351         if (help_osd[1])
1352                 free(help_osd[1]);
1353         if (info_osd)
1354                 free(info_osd);
1355
1356         return 0;
1357 }
1358