First beta version 1.0
[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 <endian.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include "../libsdl/sdl.h"
27 #include "../libsdl/opengl.h"
28 #include "../libcpu/m68k.h"
29 #include "../libcpu/execute.h"
30 #include "../libvideo/video.h"
31 #include "../libsound/sound.h"
32 #include "../libjoystick/joystick.h"
33 #include "../libkeyboard/keyboard.h"
34 #include "../libdisk/disk.h"
35 #include "mercenary.h"
36
37 static int config_amiga_speed = 1;
38 static const char *config_gamesave_dir = ".mercenary";
39 static int config_video_filter = 0;
40 static int config_audio_filter = 1;
41
42 #define CPU_SPEED       7093790.0;
43
44 #define SOUND_SAMPLERATE 48000
45 /* - game IRQ rate
46  * - must be used for sound rendering chunk
47  */
48 #define IRQ_RATE        50
49 /* numbe of buffer chunks to dejitter:
50  * - SDL render interval
51  * - sound rendering interval
52  * - sound card interval
53  * 4 should be minimum, if video rate is >=50 Hz
54  */
55 #define SOUND_CHUNKS    4
56
57 /* test sound to check if buffer does not overflow / underrun */
58 //#define DEBUG_SOUND_BUFFERING
59
60 #define IOSIZE          0x1000 /* bytes in io space */
61 #define MEMORY_SIZE     0x80000
62 static uint8_t *memory = NULL;
63 static uint8_t *image = NULL;
64 #define SCREEN_WIDTH    (320*3)
65 #define SCREEN_HEIGHT   (200*3)
66 #define IMAGE_WIDTH     320
67 #define IMAGE_HEIGHT    200
68 #define BENSON_AT_LINE  136
69 #define IMAGE_DIWSTART  0x2c
70 static uint16_t *chipreg = NULL;
71 static float *sound_buffer = NULL; /* sound buffer memory */
72 static int sound_buffer_size; /* buffer sample size */
73 static int sound_buffer_writep; /* write pointer at buffer */
74 static int sound_buffer_readp; /* read pointer at buffer */
75
76 static const char *home_dir;
77
78 static int quit = 0;
79
80 static void main_loop(void)
81 {
82         int had_first_irq = 0;
83         static uint32_t current_time, last_time = 0, diff;
84         int i, rc;
85         int space, length;
86         int cycle_count;
87         double render_delay = 0.0;
88         uint32_t palette_address;
89         uint16_t palette[16];
90
91         last_time = SDL_GetTicks();
92
93         /* render result on window */
94         while (!quit) {
95                 /* STEP 1: let the CPU render/process the game */
96                 /* don't render if we still delay */
97                 if (!render_delay) {
98                         /* execute until the rendered image is ready */
99                         cycle_count = execute_cpu(0, mercenary_stop_at);
100                         /* copy palette */
101                         palette_address = mercenary_palette();
102                         for (i = 0; i < 16; i++)
103                                 palette[i] = m68k_read_memory_16(palette_address + i*2);
104                         /* for amiga speed: set delay by the number of cycles */
105                         if (config_amiga_speed)
106                                 render_delay = (double)cycle_count / CPU_SPEED;
107                 }
108
109                 /* STEP 2: render image in memory via OpenGL */
110                 if (had_first_irq) {
111                         /* render game view without benson
112                          * because benson is not updated before VBL IRQ, we don't want old image from double buffer
113                          */
114                         emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, 0, BENSON_AT_LINE);
115                 }
116                 rc = event_sdl();
117                 if (rc)
118                         break;
119                 render_opengl(image, config_video_filter);
120                 swap_sdl();
121
122                 /* STEP 3: execute interrupt at rate of 50Hz, render sound */
123                 current_time = SDL_GetTicks();
124                 diff = current_time - last_time;
125                 /* in case of timer glitch, execute IRQ only by maximum number of SOUND_CHUNKS */
126                 if (diff > 1000 * SOUND_CHUNKS / IRQ_RATE) {
127                         diff = 1000 * SOUND_CHUNKS / IRQ_RATE;
128                         last_time = current_time - 1000 * SOUND_CHUNKS / IRQ_RATE;
129                 }
130                 while (diff > 1000 / IRQ_RATE) {
131                         execute_cpu(3, NULL);
132                         execute_cpu(4, NULL);
133                         had_first_irq = 1;
134                         /* render benson without game view
135                          * because we only got benson refreshed during VBL IRQ
136                          */
137                         emul_video(image, memory, palette, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DIWSTART, chipreg, BENSON_AT_LINE, IMAGE_HEIGHT);
138                         /* render sound to sound buffer
139                          * buffer pointer read and write is atomic, so no locking required!
140                          */
141                         space = (sound_buffer_readp - sound_buffer_writep - 1 + sound_buffer_size) % sound_buffer_size;
142                         if (space < SOUND_SAMPLERATE / IRQ_RATE) {
143 #ifdef DEBUG_SOUND_BUFFERING
144                                 fprintf(stderr, "sound buffer overflow\n");
145 #endif
146                                 length = space;
147                         } else
148                                 length = SOUND_SAMPLERATE / IRQ_RATE;
149 #ifdef DEBUG_SOUND_BUFFERING
150                         printf("can write %d, write %d\n", space, length);
151                         static int cnt = 0;
152                         int s;
153                         for (s = 0; s < length; s++) {
154                                 sound_buffer[(sound_buffer_writep + s) % sound_buffer_size]
155                                         = sin(2 * M_PI * 999 * cnt / SOUND_SAMPLERATE)
156                                         * sin(2 * M_PI * 21 * cnt / SOUND_SAMPLERATE)
157                                         * sin(2 * M_PI * 0.5 * cnt / SOUND_SAMPLERATE);
158                                  cnt++;
159                         }
160 #else
161                         render_sound(memory, sound_buffer, sound_buffer_size, sound_buffer_writep, length, config_audio_filter);
162 #endif
163                         sound_buffer_writep = (sound_buffer_writep + length) % sound_buffer_size;
164                         diff -= 1000 / IRQ_RATE;
165                         last_time += 1000 / IRQ_RATE;
166
167                         /* count down render delay */
168                         if (render_delay) {
169                                 render_delay -= 1.0 / (double)IRQ_RATE;
170                                 if (render_delay < 0.0)
171                                         render_delay = 0.0;
172                         }
173                 }
174         }
175 }
176
177 int main(int __attribute__((unused)) argc, char *argv[])
178 {
179         int rc;
180         int sdl_sound_chunk;
181
182         home_dir = getenv("HOME");
183         if (!home_dir)
184                 home_dir = "";
185
186         /* allocate image */
187         image = calloc(IMAGE_WIDTH * IMAGE_HEIGHT, 3);
188         if (!image) {
189                 fprintf(stderr, "Failed to allocate image buffer\n");
190                 goto done;
191         }
192
193         if ((SOUND_SAMPLERATE % IRQ_RATE)) {
194                 fprintf(stderr, "Sample rate must be a multiple of IRQ rate, please fix!\n");
195                 goto done;
196         }
197         if ((1000 % IRQ_RATE)) {
198                 fprintf(stderr, "1000 (Ticks per second) rate must be a multiple of IRQ rate, please fix!\n");
199                 goto done;
200         }
201
202         /* calculate SDL chunk size for audio
203          * it must be a power of two, but not more than the chunk size for each IRQ!
204          */
205         for (sdl_sound_chunk = 2; sdl_sound_chunk <= (SOUND_SAMPLERATE / IRQ_RATE); sdl_sound_chunk <<= 1)
206                 ;
207         sdl_sound_chunk >>= 1;
208 //      printf("samples per IRQ = %d, samples per SDL audio = %d\n", SOUND_SAMPLERATE / IRQ_RATE, sdl_sound_chunk); exit(0);
209
210         /* allocate sound buffers */
211         sound_buffer_size = SOUND_SAMPLERATE / IRQ_RATE * SOUND_CHUNKS;
212         sound_buffer = calloc(sound_buffer_size, sizeof(*sound_buffer));
213         if (!sound_buffer) {
214                 fprintf(stderr, "Failed to allocate image buffer\n");
215                 goto done;
216         }
217
218         /* allocate memory */
219         memory = calloc(MEMORY_SIZE, 1);
220         if (!memory) {
221                 fprintf(stderr, "Failed to allocate cpu's memory\n");
222                 goto done;
223         }
224         chipreg = calloc(IOSIZE, 1);
225         if (!chipreg) {
226                 fprintf(stderr, "Failed to allocate chip register\n");
227                 goto done;
228         }
229
230         /* init cpu code */
231         execute_init(MEMORY_SIZE, memory, chipreg);
232
233         /* load binary */
234         mercenary_load();
235
236         /* patch some stuff */
237         mercenary_patch();
238
239         /* init SDL and OpenGL */
240         rc = init_sdl(argv[0], SCREEN_WIDTH, SCREEN_HEIGHT, SOUND_SAMPLERATE, sdl_sound_chunk);
241         if (rc < 0)
242                 goto done;
243         rc = init_opengl(IMAGE_WIDTH, IMAGE_HEIGHT);
244         if (rc < 0)
245                 goto done;
246         resize_opengl(SCREEN_WIDTH, SCREEN_HEIGHT);
247
248         /* init audio filter */
249         sound_init_filter(SOUND_SAMPLERATE);
250
251         /* start cpu */
252         reset_cpu();
253
254         printf("Welcome to Mercenary Reloaded!\n\n");
255         printf("Hold CTRL and use cursor keys to select inventory or pickup/drop item.\n");
256         printf("Press CTRL + f to toggle full screen.\n");
257         printf("Press CTRL + s to toggle rendering speed.\n");
258         printf("Press CTRL + v to toggle video filter.\n");
259         printf("Press CTRL + a to toggle audio filter.\n");
260         printf("Press CTRL + c to exit game.\n");
261         printf("\n");
262
263         /* run game */
264         main_loop();
265
266 done:
267         exit_opengl();
268         exit_sdl();
269
270         if (chipreg)
271                 free(chipreg);
272         if (memory)
273                 free(memory);
274         if (sound_buffer)
275                 free(sound_buffer);
276         if (image)
277                 free(image);
278
279         return 0;
280 }
281
282 void audio_sdl(float *data, int length)
283 {
284         int fill, s;
285
286         /* read sound from sound buffer
287          * buffer pointer read and write is atomic, so no locking required!
288          */
289         fill = (sound_buffer_writep - sound_buffer_readp + sound_buffer_size) % sound_buffer_size;
290         if (fill < length) {
291 #ifdef DEBUG_SOUND_BUFFERING
292                 fprintf(stderr, "sound buffer underrun\n");
293 #endif
294                 /* correct read pointer as if the buffer would have 'length' of samples stored inside */
295                 sound_buffer_readp = (sound_buffer_readp + fill - length + sound_buffer_size) % sound_buffer_size;
296         }
297         for (s = 0; s < length; s++)
298                 *data++ = sound_buffer[(sound_buffer_readp + s) % sound_buffer_size];
299 #ifdef DEBUG_SOUND_BUFFERING
300         printf("fill %d = %.4f\n", length, sound_buffer[sound_buffer_readp]);
301 #endif
302         sound_buffer_readp =(sound_buffer_readp + length) % sound_buffer_size;
303 }
304
305 static int shift = 0, ctrl = 0;
306
307 void keyboard_sdl(int down, SDL_Keycode sym)
308 {
309         switch (sym) {
310         case SDLK_LCTRL:
311         case SDLK_RCTRL:
312                 ctrl = down;
313                 break;
314         case SDLK_v:
315                 if (down) {
316                         config_video_filter ^= 1;
317                         printf("audio filter: %d\n", config_audio_filter);
318                 }
319                 break;
320         case SDLK_a:
321                 if (down) {
322                         config_audio_filter ^= 1;
323                         printf("video filter: %d\n", config_video_filter);
324                 }
325                 break;
326         case SDLK_s:
327                 if (down) {
328                         printf("amiga speed: %d\n", config_amiga_speed);
329                         config_amiga_speed ^= 1;
330                 }
331                 break;
332         case SDLK_c:
333                 if (down)
334                         quit = 1;
335                 break;
336         }
337
338         switch (sym) {
339         case SDLK_LSHIFT:
340                 set_key("LSH", down);
341                 shift = down;
342                 break;
343         case SDLK_RSHIFT:
344                 set_key("RSH", down);
345                 shift = down;
346                 break;
347         case SDLK_LEFT:
348                 if (shift && down) {
349                         set_key("LF", down);
350                         set_joystick(-1, -1, -1, -1, -1);
351                         break;
352                 }
353                 set_key("LF", 0);
354                 set_joystick(down, -1, -1, -1, -1);
355                 break;
356         case SDLK_RIGHT:
357                 if (shift && down) {
358                         set_key("RT", down);
359                         set_joystick(-1, -1, -1, -1, -1);
360                         break;
361                 }
362                 set_key("RT", 0);
363                 set_joystick(-1, down, -1, -1, -1);
364                 break;
365         case SDLK_UP:
366                 if (shift && down) {
367                         set_key("UP", down);
368                         set_joystick(-1, -1, -1, -1, -1);
369                         break;
370                 }
371                 set_key("UP", 0);
372                 set_joystick(-1, -1, down, -1, -1);
373                 break;
374         case SDLK_DOWN:
375                 if (shift && down) {
376                         set_key("DN", down);
377                         set_joystick(-1, -1, -1, -1, -1);
378                         break;
379                 }
380                 set_key("DN", 0);
381                 set_joystick(-1, -1, -1, down, -1);
382                 break;
383         case SDLK_END:
384                 set_joystick(-1, -1, -1, -1, down);
385                 break;
386
387         case SDLK_a: set_key("A", down); break;
388         case SDLK_b: set_key("B", down); break;
389         case SDLK_c: set_key("C", down); break;
390         case SDLK_d: set_key("D", down); break;
391         case SDLK_e: set_key("E", down); break;
392         case SDLK_f: set_key("F", down); break;
393         case SDLK_g: set_key("G", down); break;
394         case SDLK_h: set_key("H", down); break;
395         case SDLK_i: set_key("I", down); break;
396         case SDLK_j: set_key("J", down); break;
397         case SDLK_k: set_key("K", down); break;
398         case SDLK_l: set_key("L", down); break;
399         case SDLK_m: set_key("M", down); break;
400         case SDLK_n: set_key("N", down); break;
401         case SDLK_o: set_key("O", down); break;
402         case SDLK_p: set_key("P", down); break;
403         case SDLK_q: set_key("Q", down); break;
404         case SDLK_r: set_key("R", down); break;
405         case SDLK_s: set_key("S", down); break;
406         case SDLK_t: set_key("T", down); break;
407         case SDLK_u: set_key("U", down); break;
408         case SDLK_v: set_key("V", down); break;
409         case SDLK_w: set_key("W", down); break;
410         case SDLK_x: set_key("X", down); break;
411         case SDLK_y: set_key("Y", down); break;
412         case SDLK_z: set_key("Z", down); break;
413
414         case SDLK_0: set_key("0", down); break;
415         case SDLK_1: set_key("1", down); break;
416         case SDLK_2: set_key("2", down); break;
417         case SDLK_3: set_key("3", down); break;
418         case SDLK_4: set_key("4", down); break;
419         case SDLK_5: set_key("5", down); break;
420         case SDLK_6: set_key("6", down); break;
421         case SDLK_7: set_key("7", down); break;
422         case SDLK_8: set_key("8", down); break;
423         case SDLK_9: set_key("9", down); break;
424
425         case SDLK_KP_0: set_key("NP0", down); break;
426         case SDLK_KP_1: set_key("NP1", down); break;
427         case SDLK_KP_2: set_key("NP2", down); break;
428         case SDLK_KP_3: set_key("NP3", down); break;
429         case SDLK_KP_4: set_key("NP4", down); break;
430         case SDLK_KP_5: set_key("NP5", down); break;
431         case SDLK_KP_6: set_key("NP6", down); break;
432         case SDLK_KP_7: set_key("NP7", down); break;
433         case SDLK_KP_8: set_key("NP8", down); break;
434         case SDLK_KP_9: set_key("NP9", down); break;
435         case SDLK_KP_DIVIDE: set_key("NPDIV", down); break;
436         case SDLK_KP_MULTIPLY: set_key("NPMUL", down); break;
437         case SDLK_KP_MINUS: set_key("NPSUB", down); break;
438         case SDLK_KP_PLUS: set_key("NPADD", down); break;
439         case SDLK_KP_PERIOD: set_key("NPDEL", down); break;
440         // NPLPAREN and NPRPAREN are not emulated
441
442         case SDLK_F1: set_key("F1", down); break;
443         case SDLK_F2: set_key("F2", down); break;
444         case SDLK_F3: set_key("F3", down); break;
445         case SDLK_F4: set_key("F4", down); break;
446         case SDLK_F5: set_key("F5", down); break;
447         case SDLK_F6: set_key("F6", down); break;
448         case SDLK_F7: set_key("F7", down); break;
449         case SDLK_F8: set_key("F8", down); break;
450         case SDLK_F9: set_key("F9", down); break;
451         case SDLK_F10: set_key("F10", down); break;
452
453         case SDLK_SPACE: set_key("SPC", down); break;
454         case SDLK_BACKSPACE: set_key("BS", down); break;
455         case SDLK_TAB: set_key("TAB", down); break;
456         case SDLK_KP_ENTER: set_key("ENT", down); break;
457         case SDLK_RETURN: set_key("RET", down); break;
458         case SDLK_ESCAPE: set_key("ESC", down); break;
459         case SDLK_DELETE: set_key("DEL", down); break;
460         case SDLK_INSERT: set_key("HELP", down); break;
461
462         }
463 }
464
465 uint16_t emulate_io_read(uint32_t address)
466 {
467         uint16_t value = 0xffff;
468
469         /* joystick and fire button */
470         if (address == 0xbfe000 || address == 0xdff00c)
471                 value &= emulate_joystick_read(address);
472         /* keyboard */
473         if (address == 0xbfec00 || address == 0xbfed00 || address == 0xbfee00)
474                 value &= emulate_keyboard_read(address);
475         /* diskette */
476         if (address == 0xbfd100 || address == 0xbfe000 || address == 0xdff01a || address == 0xdff01e)
477                 value &= emulate_disk_read(address);
478
479         return value;
480 }
481
482 void emulate_io_write(uint32_t address, uint16_t value)
483 {
484         /* dmacon and sound registers */
485         if (address == 0xdff096 || (address >= 0xdff0a0 && address <= 0xdff0df))
486                 emulate_sound_write(address, value, SOUND_SAMPLERATE);
487         if (address == 0xbfd100 || (address >= 0xdff020 && address <= 0xdff024))
488                 emulate_disk_write(address, value);
489 }
490
491 /* two tracks with 0x1820 words of length */
492 static uint8_t game_save[2][0x1820 << 1];
493 static int last_track = 0;
494
495 /* game reads track with saved game */
496 void disk_read(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
497 {
498         if (length > sizeof(game_save[0])) {
499                 fprintf(stderr, "loading game state failed, because length exceeds game save data size, please fix!\n");
500                 return;
501         }
502
503         /* if even track is selected, load game */
504         if (!(track & 1)) {
505                 char filename[256];
506                 int gamesave_num = (track - 2) >> 1;
507                 int got;
508                 FILE *fp;
509
510                 memset(game_save, 0, sizeof(game_save)); /* clear so make the game fail, if we fail */
511                 sprintf(filename, "%s/%s/%d.gamesave", home_dir, config_gamesave_dir, gamesave_num);
512                 fp = fopen(filename, "r");
513                 if (!fp) {
514 fail:
515                         fprintf(stderr, "failed to load game from '%s'\n", filename);
516                         goto copy;
517                 }
518                 got = fread(game_save, sizeof(game_save[0]), 2, fp);
519                 fclose(fp);
520                 if (got != 2)
521                         goto fail;
522         }
523
524 copy:
525         /* copy track */
526         memcpy(memory + data, game_save[track & 1], length /* sizeof(game_save[0])*/);
527 }
528
529 /* game writes track with saved game */
530 void disk_write(int track, int __attribute__((unused)) side, uint32_t data, uint16_t length)
531 {
532         /* skip sync info that is provided by game and only relevant for a real disk track */
533         data += 0x200;
534         length -= 0x200;
535
536         if (length != sizeof(game_save[0])) {
537                 fprintf(stderr, "saving game state failed, because length of data does not match, please fix!\n");
538                 return;
539         }
540
541         /* don't save if last track is the same, because disk is written on both sides with the same data */
542         if (track == last_track) {
543                 if (memcmp(memory + data, game_save[track & 1], length)) {
544                         fprintf(stderr, "saving game data on other side of the disk is different, please fix!\n");
545                 }
546                 return;
547         }
548         last_track = track;
549
550         /* save game data */
551         memcpy(game_save[track & 1], memory + data, length);
552
553         /* if done with saving */
554         if ((track & 1)) {
555                 char filename[256];
556                 int gamesave_num = (track - 2) >> 1;
557                 int wrote;
558                 FILE *fp;
559
560                 sprintf(filename, "%s/%s", home_dir, config_gamesave_dir);
561                 mkdir(filename, 0777);
562                 sprintf(filename + strlen(filename), "/%d.gamesave", gamesave_num);
563                 fp = fopen(filename, "w");
564                 if (!fp) {
565 fail:
566                         fprintf(stderr, "failed to save game to '%s'\n", filename);
567                         return;
568                 }
569                 printf("Game state saved to '%s'\n", filename);
570                 wrote = fwrite(game_save, sizeof(game_save[0]), 2, fp);
571                 fclose(fp);
572                 if (wrote != 2)
573                         goto fail;
574         }
575 }