bump version, since this is not the same as last released binary
[picodrive.git] / platform / common / menu_pico.c
1 /*
2  * PicoDrive
3  * (C) notaz, 2010,2011
4  *
5  * This work is licensed under the terms of MAME license.
6  * See COPYING file in the top-level directory.
7  */
8 #include <stdio.h>
9 #include <string.h>
10
11 #include "emu.h"
12 #include "menu_pico.h"
13 #include "input_pico.h"
14 #include "version.h"
15
16 #include <pico/pico.h>
17 #include <pico/patch.h>
18
19 #ifdef PANDORA
20 #define MENU_X2 1
21 #else
22 #define MENU_X2 0
23 #endif
24
25 // FIXME
26 #define REVISION "0"
27
28 static const char *rom_exts[] = {
29         "zip",
30         "bin", "smd", "gen",
31         "iso", "cso", "cue",
32         "32x",
33         "sms",
34         NULL
35 };
36
37 // rrrr rggg gggb bbbb
38 static unsigned short fname2color(const char *fname)
39 {
40         const char *ext = fname + strlen(fname) - 3;
41         static const char *other_exts[] = { "gmv", "pat" };
42         int i;
43
44         if (ext < fname) ext = fname;
45         for (i = 0; rom_exts[i] != NULL; i++)
46                 if (strcasecmp(ext, rom_exts[i]) == 0) return 0xbdff; // FIXME: mk defines
47         for (i = 0; i < array_size(other_exts); i++)
48                 if (strcasecmp(ext, other_exts[i]) == 0) return 0xaff5;
49         return 0xffff;
50 }
51
52 #include "../libpicofe/menu.c"
53
54 static const char *men_dummy[] = { NULL };
55
56 /* platform specific options and handlers */
57 #if   defined(__GP2X__)
58 #include "../gp2x/menu.c"
59 #elif defined(PANDORA)
60 #include "../pandora/menu.c"
61 #else
62 #define MENU_OPTIONS_GFX
63 #define MENU_OPTIONS_ADV
64 #define menu_main_plat_draw NULL
65 #endif
66
67 static void make_bg(int no_scale)
68 {
69         unsigned short *src = (void *)g_menubg_src_ptr;
70         int w = g_screen_width, h = g_screen_height;
71         short *dst;
72         int x, y;
73
74         if (!no_scale && g_menuscreen_w / w >= 2 && g_menuscreen_h / h >= 2)
75         {
76                 unsigned int t, *d = g_menubg_ptr;
77                 d += (g_menuscreen_h / 2 - h * 2 / 2)
78                         * g_menuscreen_w / 2;
79                 d += (g_menuscreen_w / 2 - w * 2 / 2) / 2;
80                 for (y = 0; y < h; y++, src += w, d += g_menuscreen_w*2/2) {
81                         for (x = 0; x < w; x++) {
82                                 t = src[x];
83                                 t = ((t & 0xf79e)>>1) - ((t & 0xc618)>>3);
84                                 t |= t << 16;
85                                 d[x] = d[x + g_menuscreen_w / 2] = t;
86                         }
87                 }
88                 return;
89         }
90
91         if (w > g_menuscreen_w)
92                 w = g_menuscreen_w;
93         if (h > g_menuscreen_h)
94                 h = g_menuscreen_h;
95         dst = (short *)g_menubg_ptr +
96                 (g_menuscreen_h / 2 - h / 2) * g_menuscreen_w +
97                 (g_menuscreen_w / 2 - w / 2);
98
99         // darken the active framebuffer
100         for (; h > 0; dst += g_menuscreen_w, src += g_screen_width, h--)
101                 menu_darken_bg(dst, src, w, 1);
102 }
103
104 static void menu_enter(int is_rom_loaded)
105 {
106         if (is_rom_loaded)
107         {
108                 make_bg(0);
109         }
110         else
111         {
112                 char buff[256];
113
114                 // should really only happen once, on startup..
115                 emu_make_path(buff, "skin/background.png", sizeof(buff));
116                 if (readpng(g_menubg_ptr, buff, READPNG_BG, g_menuscreen_w, g_menuscreen_h) < 0)
117                         memset(g_menubg_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
118         }
119
120         plat_video_menu_enter(is_rom_loaded);
121 }
122
123 static void draw_savestate_bg(int slot)
124 {
125         const char *fname;
126         void *tmp_state;
127
128         fname = emu_get_save_fname(1, 0, slot);
129         if (!fname)
130                 return;
131
132         tmp_state = PicoTmpStateSave();
133
134         PicoStateLoadGfx(fname);
135
136         /* do a frame and fetch menu bg */
137         pemu_forced_frame(0, 0);
138
139         make_bg(0);
140
141         PicoTmpStateRestore(tmp_state);
142 }
143
144 // --------- loading ROM screen ----------
145
146 static int cdload_called = 0;
147
148 static void load_progress_cb(int percent)
149 {
150         int ln, len = percent * g_menuscreen_w / 100;
151         unsigned short *dst;
152
153         if (len > g_menuscreen_w)
154                 len = g_menuscreen_w;
155
156         menu_draw_begin(0, 1);
157         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_w * me_sfont_h * 2;
158         for (ln = me_sfont_h - 2; ln > 0; ln--, dst += g_menuscreen_w)
159                 memset(dst, 0xff, len * 2);
160         menu_draw_end();
161 }
162
163 static void cdload_progress_cb(const char *fname, int percent)
164 {
165         int ln, len = percent * g_menuscreen_w / 100;
166         unsigned short *dst;
167
168         menu_draw_begin(0, 1);
169         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_w * me_sfont_h * 2;
170         memset(dst, 0xff, g_menuscreen_w * (me_sfont_h - 2) * 2);
171
172         smalltext_out16(1, 3 * me_sfont_h, "Processing CD image / MP3s", 0xffff);
173         smalltext_out16(1, 4 * me_sfont_h, fname, 0xffff);
174         dst += g_menuscreen_w * me_sfont_h * 3;
175
176         if (len > g_menuscreen_w)
177                 len = g_menuscreen_w;
178
179         for (ln = (me_sfont_h - 2); ln > 0; ln--, dst += g_menuscreen_w)
180                 memset(dst, 0xff, len * 2);
181         menu_draw_end();
182
183         cdload_called = 1;
184 }
185
186 void menu_romload_prepare(const char *rom_name)
187 {
188         const char *p = rom_name + strlen(rom_name);
189         int i;
190
191         while (p > rom_name && *p != '/')
192                 p--;
193
194         /* fill all buffers, callbacks won't update in full */
195         for (i = 0; i < 3; i++) {
196                 menu_draw_begin(1, 1);
197                 smalltext_out16(1, 1, "Loading", 0xffff);
198                 smalltext_out16(1, me_sfont_h, p, 0xffff);
199                 menu_draw_end();
200         }
201
202         PicoCartLoadProgressCB = load_progress_cb;
203         PicoCDLoadProgressCB = cdload_progress_cb;
204         cdload_called = 0;
205 }
206
207 void menu_romload_end(void)
208 {
209         PicoCartLoadProgressCB = NULL;
210         PicoCDLoadProgressCB = NULL;
211
212         menu_draw_begin(0, 1);
213         smalltext_out16(1, (cdload_called ? 6 : 3) * me_sfont_h,
214                 "Starting emulation...", 0xffff);
215         menu_draw_end();
216 }
217
218 // ------------ patch/gg menu ------------
219
220 static void draw_patchlist(int sel)
221 {
222         int max_cnt, start, i, pos, active;
223
224         max_cnt = g_menuscreen_h / me_sfont_h;
225         start = max_cnt / 2 - sel;
226
227         menu_draw_begin(1, 0);
228
229         for (i = 0; i < PicoPatchCount; i++) {
230                 pos = start + i;
231                 if (pos < 0) continue;
232                 if (pos >= max_cnt) break;
233                 active = PicoPatches[i].active;
234                 smalltext_out16(14,                pos * me_sfont_h, active ? "ON " : "OFF", active ? 0xfff6 : 0xffff);
235                 smalltext_out16(14 + me_sfont_w*4, pos * me_sfont_h, PicoPatches[i].name,    active ? 0xfff6 : 0xffff);
236         }
237         pos = start + i;
238         if (pos < max_cnt)
239                 smalltext_out16(14, pos * me_sfont_h, "done", 0xffff);
240
241         text_out16(5, max_cnt / 2 * me_sfont_h, ">");
242         menu_draw_end();
243 }
244
245 static void menu_loop_patches(void)
246 {
247         static int menu_sel = 0;
248         int inp;
249
250         for (;;)
251         {
252                 draw_patchlist(menu_sel);
253                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_L|PBTN_R
254                                 |PBTN_MOK|PBTN_MBACK, NULL, 33);
255                 if (inp & PBTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
256                 if (inp & PBTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
257                 if (inp &(PBTN_LEFT|PBTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
258                 if (inp &(PBTN_RIGHT|PBTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
259                 if (inp & PBTN_MOK) { // action
260                         if (menu_sel < PicoPatchCount)
261                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
262                         else    break;
263                 }
264                 if (inp & PBTN_MBACK)
265                         break;
266         }
267 }
268
269 // -------------- key config --------------
270
271 // PicoPad[] format: MXYZ SACB RLDU
272 me_bind_action me_ctrl_actions[] =
273 {
274         { "UP     ", 0x0001 },
275         { "DOWN   ", 0x0002 },
276         { "LEFT   ", 0x0004 },
277         { "RIGHT  ", 0x0008 },
278         { "A      ", 0x0040 },
279         { "B      ", 0x0010 },
280         { "C      ", 0x0020 },
281         { "A turbo", 0x4000 },
282         { "B turbo", 0x1000 },
283         { "C turbo", 0x2000 },
284         { "START  ", 0x0080 },
285         { "MODE   ", 0x0800 },
286         { "X      ", 0x0400 },
287         { "Y      ", 0x0200 },
288         { "Z      ", 0x0100 },
289         { NULL,      0 },
290 };
291
292 me_bind_action emuctrl_actions[] =
293 {
294         { "Load State       ", PEV_STATE_LOAD },
295         { "Save State       ", PEV_STATE_SAVE },
296         { "Prev Save Slot   ", PEV_SSLOT_PREV },
297         { "Next Save Slot   ", PEV_SSLOT_NEXT },
298         { "Switch Renderer  ", PEV_SWITCH_RND },
299         { "Volume Down      ", PEV_VOL_DOWN },
300         { "Volume Up        ", PEV_VOL_UP },
301         { "Fast forward     ", PEV_FF },
302         { "Enter Menu       ", PEV_MENU },
303         { "Pico Next page   ", PEV_PICO_PNEXT },
304         { "Pico Prev page   ", PEV_PICO_PPREV },
305         { "Pico Switch input", PEV_PICO_SWINP },
306         { NULL,                0 }
307 };
308
309 static int key_config_loop_wrap(int id, int keys)
310 {
311         switch (id) {
312                 case MA_CTRL_PLAYER1:
313                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
314                         break;
315                 case MA_CTRL_PLAYER2:
316                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
317                         break;
318                 case MA_CTRL_EMU:
319                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
320                         break;
321                 default:
322                         break;
323         }
324         return 0;
325 }
326
327 static const char *mgn_dev_name(int id, int *offs)
328 {
329         const char *name = NULL;
330         static int it = 0;
331
332         if (id == MA_CTRL_DEV_FIRST)
333                 it = 0;
334
335         for (; it < IN_MAX_DEVS; it++) {
336                 name = in_get_dev_name(it, 1, 1);
337                 if (name != NULL)
338                         break;
339         }
340
341         it++;
342         return name;
343 }
344
345 static int mh_saveloadcfg(int id, int keys);
346 static const char *mgn_saveloadcfg(int id, int *offs);
347
348 static menu_entry e_menu_keyconfig[] =
349 {
350         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
351         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
352         mee_handler_id("Emulator controls", MA_CTRL_EMU,        key_config_loop_wrap),
353         mee_onoff     ("6 button pad",      MA_OPT_6BUTTON_PAD, PicoOpt, POPT_6BTN_PAD),
354         mee_range     ("Turbo rate",        MA_CTRL_TURBO_RATE, currentConfig.turbo_rate, 1, 30),
355         mee_range     ("Analog deadzone",   MA_CTRL_DEADZONE,   currentConfig.analog_deadzone, 1, 99),
356         mee_cust_nosave("Save global config",       MA_OPT_SAVECFG, mh_saveloadcfg, mgn_saveloadcfg),
357         mee_cust_nosave("Save cfg for loaded game", MA_OPT_SAVECFG_GAME, mh_saveloadcfg, mgn_saveloadcfg),
358         mee_label     (""),
359         mee_label     ("Input devices:"),
360         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
361         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
362         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
363         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
364         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
365         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
366         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
367         mee_end,
368 };
369
370 static int menu_loop_keyconfig(int id, int keys)
371 {
372         static int sel = 0;
373
374         me_enable(e_menu_keyconfig, MA_OPT_SAVECFG_GAME, PicoGameLoaded);
375         me_loop(e_menu_keyconfig, &sel);
376         return 0;
377 }
378
379 // ------------ SCD options menu ------------
380
381 static const char *mgn_cdopt_ra(int id, int *offs)
382 {
383         *offs = -5;
384         if (PicoCDBuffers <= 0)
385                 return "     OFF";
386         sprintf(static_buff, "%5iK", PicoCDBuffers * 2);
387         return static_buff;
388 }
389
390 static int mh_cdopt_ra(int id, int keys)
391 {
392         if (keys & PBTN_LEFT) {
393                 PicoCDBuffers >>= 1;
394                 if (PicoCDBuffers < 2)
395                         PicoCDBuffers = 0;
396         } else {
397                 if (PicoCDBuffers <= 0)
398                         PicoCDBuffers = 1;
399                 PicoCDBuffers <<= 1;
400                 if (PicoCDBuffers > 8*1024)
401                         PicoCDBuffers = 8*1024; // 16M
402         }
403         return 0;
404 }
405
406 static const char h_cdleds[] = "Show power/CD LEDs of emulated console";
407 static const char h_cdda[]   = "Play audio tracks from mp3s/wavs/bins";
408 static const char h_cdpcm[]  = "Emulate PCM audio chip for effects/voices/music";
409 static const char h_srcart[] = "Emulate the save RAM cartridge accessory\n"
410                                 "most games don't need this";
411 static const char h_scfx[]   = "Emulate scale/rotate ASIC chip for graphics effects\n"
412                                 "disable to improve performance";
413 static const char h_bsync[]  = "More accurate mode for CPUs (needed for some games)\n"
414                                 "disable to improve performance";
415
416 static menu_entry e_menu_cd_options[] =
417 {
418         mee_onoff_h("CD LEDs",              MA_CDOPT_LEDS,          currentConfig.EmuOpt, EOPT_EN_CD_LEDS, h_cdleds),
419         mee_onoff_h("CDDA audio",           MA_CDOPT_CDDA,          PicoOpt, POPT_EN_MCD_CDDA, h_cdda),
420         mee_onoff_h("PCM audio",            MA_CDOPT_PCM,           PicoOpt, POPT_EN_MCD_PCM, h_cdpcm),
421         mee_cust   ("ReadAhead buffer",     MA_CDOPT_READAHEAD,     mh_cdopt_ra, mgn_cdopt_ra),
422         mee_onoff_h("SaveRAM cart",         MA_CDOPT_SAVERAM,       PicoOpt, POPT_EN_MCD_RAMCART, h_srcart),
423         mee_onoff_h("Scale/Rot. fx (slow)", MA_CDOPT_SCALEROT_CHIP, PicoOpt, POPT_EN_MCD_GFX, h_scfx),
424         mee_onoff_h("Better sync (slow)",   MA_CDOPT_BETTER_SYNC,   PicoOpt, POPT_EN_MCD_PSYNC, h_bsync),
425         mee_end,
426 };
427
428 static int menu_loop_cd_options(int id, int keys)
429 {
430         static int sel = 0;
431         me_loop(e_menu_cd_options, &sel);
432         return 0;
433 }
434
435 // ------------ 32X options menu ------------
436
437 #ifndef NO_32X
438
439 // convert from multiplier of VClk
440 static int mh_opt_sh2cycles(int id, int keys)
441 {
442         int *mul = (id == MA_32XOPT_MSH2_CYCLES) ? &p32x_msh2_multiplier : &p32x_ssh2_multiplier;
443
444         if (keys & (PBTN_LEFT|PBTN_RIGHT))
445                 *mul += (keys & PBTN_LEFT) ? -10 : 10;
446         if (keys & (PBTN_L|PBTN_R))
447                 *mul += (keys & PBTN_L) ? -100 : 100;
448
449         if (*mul < 1)
450                 *mul = 1;
451         else if (*mul > (10 << SH2_MULTI_SHIFT))
452                 *mul = 10 << SH2_MULTI_SHIFT;
453
454         return 0;
455 }
456
457 static const char *mgn_opt_sh2cycles(int id, int *offs)
458 {
459         int mul = (id == MA_32XOPT_MSH2_CYCLES) ? p32x_msh2_multiplier : p32x_ssh2_multiplier;
460         
461         sprintf(static_buff, "%d", 7670 * mul >> SH2_MULTI_SHIFT);
462         return static_buff;
463 }
464
465 static const char h_32x_enable[] = "Enable emulation of the 32X addon";
466 static const char h_pwm[]        = "Disabling may improve performance, but break sound";
467 static const char h_sh2cycles[]  = "Cycles/millisecond (similar to DOSBox)\n"
468                                    "lower values speed up emulation but break games\n"
469                                    "at least 11000 recommended for compatibility";
470
471 static menu_entry e_menu_32x_options[] =
472 {
473         mee_onoff_h   ("32X enabled",       MA_32XOPT_ENABLE_32X,  PicoOpt, POPT_EN_32X, h_32x_enable),
474         mee_enum      ("32X renderer",      MA_32XOPT_RENDERER,    currentConfig.renderer32x, renderer_names32x),
475         mee_onoff_h   ("PWM sound",         MA_32XOPT_PWM,         PicoOpt, POPT_EN_PWM, h_pwm),
476         mee_cust_h    ("Master SH2 cycles", MA_32XOPT_MSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
477         mee_cust_h    ("Slave SH2 cycles",  MA_32XOPT_SSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
478         mee_end,
479 };
480
481 static int menu_loop_32x_options(int id, int keys)
482 {
483         static int sel = 0;
484
485         me_enable(e_menu_32x_options, MA_32XOPT_RENDERER, renderer_names32x[0] != NULL);
486         me_loop(e_menu_32x_options, &sel);
487
488         return 0;
489 }
490
491 #endif
492
493 // ------------ adv options menu ------------
494
495 static menu_entry e_menu_adv_options[] =
496 {
497         mee_onoff     ("SRAM/BRAM saves",          MA_OPT_SRAM_STATES,    currentConfig.EmuOpt, EOPT_EN_SRAM),
498         mee_onoff     ("Disable sprite limit",     MA_OPT2_NO_SPRITE_LIM, PicoOpt, POPT_DIS_SPRITE_LIM),
499         mee_onoff     ("Emulate Z80",              MA_OPT2_ENABLE_Z80,    PicoOpt, POPT_EN_Z80),
500         mee_onoff     ("Emulate YM2612 (FM)",      MA_OPT2_ENABLE_YM2612, PicoOpt, POPT_EN_FM),
501         mee_onoff     ("Emulate SN76496 (PSG)",    MA_OPT2_ENABLE_SN76496,PicoOpt, POPT_EN_PSG),
502         mee_onoff     ("gzip savestates",          MA_OPT2_GZIP_STATES,   currentConfig.EmuOpt, EOPT_GZIP_SAVES),
503         mee_onoff     ("Don't save last used ROM", MA_OPT2_NO_LAST_ROM,   currentConfig.EmuOpt, EOPT_NO_AUTOSVCFG),
504         mee_onoff     ("Disable idle loop patching",MA_OPT2_NO_IDLE_LOOPS,PicoOpt, POPT_DIS_IDLE_DET),
505         mee_onoff     ("Disable frame limiter",    MA_OPT2_NO_FRAME_LIMIT,currentConfig.EmuOpt, EOPT_NO_FRMLIMIT),
506         MENU_OPTIONS_ADV
507         mee_end,
508 };
509
510 static int menu_loop_adv_options(int id, int keys)
511 {
512         static int sel = 0;
513         me_loop(e_menu_adv_options, &sel);
514         return 0;
515 }
516
517 // ------------ gfx options menu ------------
518
519 static const char h_gamma[] = "Gamma/brightness adjustment (default 100)";
520
521 static menu_entry e_menu_gfx_options[] =
522 {
523         mee_enum   ("Video output mode", MA_OPT_VOUT_MODE, plat_target.vout_method, men_dummy),
524         mee_enum   ("Renderer",          MA_OPT_RENDERER, currentConfig.renderer, renderer_names),
525         mee_enum   ("Filter",            MA_OPT3_FILTERING, currentConfig.filter, men_dummy),
526         mee_range_h("Gamma adjustment",  MA_OPT3_GAMMA, currentConfig.gamma, 1, 200, h_gamma),
527         MENU_OPTIONS_GFX
528         mee_end,
529 };
530
531 static int menu_loop_gfx_options(int id, int keys)
532 {
533         static int sel = 0;
534
535         me_enable(e_menu_gfx_options, MA_OPT_RENDERER, renderer_names[0] != NULL);
536         me_loop(e_menu_gfx_options, &sel);
537
538         return 0;
539 }
540
541 // ------------ options menu ------------
542
543 static menu_entry e_menu_options[];
544
545 static int sndrate_prevnext(int rate, int dir)
546 {
547         static const int rates[] = { 8000, 11025, 16000, 22050, 44100 };
548         int i;
549
550         for (i = 0; i < 5; i++)
551                 if (rates[i] == rate) break;
552
553         i += dir ? 1 : -1;
554         if (i > 4) {
555                 if (!(PicoOpt & POPT_EN_STEREO)) {
556                         PicoOpt |= POPT_EN_STEREO;
557                         return rates[0];
558                 }
559                 return rates[4];
560         }
561         if (i < 0) {
562                 if (PicoOpt & POPT_EN_STEREO) {
563                         PicoOpt &= ~POPT_EN_STEREO;
564                         return rates[4];
565                 }
566                 return rates[0];
567         }
568         return rates[i];
569 }
570
571 static void region_prevnext(int right)
572 {
573         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
574         static const int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
575         int i;
576
577         if (right) {
578                 if (!PicoRegionOverride) {
579                         for (i = 0; i < 6; i++)
580                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
581                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
582                         else PicoRegionOverride=1;
583                 }
584                 else
585                         PicoRegionOverride <<= 1;
586                 if (PicoRegionOverride > 8)
587                         PicoRegionOverride = 8;
588         } else {
589                 if (!PicoRegionOverride) {
590                         for (i = 0; i < 6; i++)
591                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
592                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
593                 }
594                 else
595                         PicoRegionOverride >>= 1;
596         }
597 }
598
599 static int mh_opt_misc(int id, int keys)
600 {
601         switch (id) {
602         case MA_OPT_SOUND_QUALITY:
603                 PsndRate = sndrate_prevnext(PsndRate, keys & PBTN_RIGHT);
604                 break;
605         case MA_OPT_REGION:
606                 region_prevnext(keys & PBTN_RIGHT);
607                 break;
608         default:
609                 break;
610         }
611         return 0;
612 }
613
614 static int mh_saveloadcfg(int id, int keys)
615 {
616         int ret;
617
618         if (keys & (PBTN_LEFT|PBTN_RIGHT)) { // multi choice
619                 config_slot += (keys & PBTN_LEFT) ? -1 : 1;
620                 if (config_slot < 0) config_slot = 9;
621                 else if (config_slot > 9) config_slot = 0;
622                 me_enable(e_menu_options, MA_OPT_LOADCFG, config_slot != config_slot_current);
623                 return 0;
624         }
625
626         switch (id) {
627         case MA_OPT_SAVECFG:
628         case MA_OPT_SAVECFG_GAME:
629                 if (emu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0))
630                         menu_update_msg("config saved");
631                 else
632                         menu_update_msg("failed to write config");
633                 break;
634         case MA_OPT_LOADCFG:
635                 ret = emu_read_config(rom_fname_loaded, 1);
636                 if (!ret) ret = emu_read_config(NULL, 1);
637                 if (ret)  menu_update_msg("config loaded");
638                 else      menu_update_msg("failed to load config");
639                 break;
640         default:
641                 return 0;
642         }
643
644         return 1;
645 }
646
647 static int mh_restore_defaults(int id, int keys)
648 {
649         emu_set_defconfig();
650         menu_update_msg("defaults restored");
651         return 1;
652 }
653
654 static const char *mgn_opt_fskip(int id, int *offs)
655 {
656         if (currentConfig.Frameskip < 0)
657                 return "Auto";
658         sprintf(static_buff, "%d", currentConfig.Frameskip);
659         return static_buff;
660 }
661
662 static const char *mgn_opt_sound(int id, int *offs)
663 {
664         const char *str2;
665         *offs = -8;
666         str2 = (PicoOpt & POPT_EN_STEREO) ? "stereo" : "mono";
667         sprintf(static_buff, "%5iHz %s", PsndRate, str2);
668         return static_buff;
669 }
670
671 static const char *mgn_opt_region(int id, int *offs)
672 {
673         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
674         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
675         int code = PicoRegionOverride;
676         int u, i = 0;
677
678         *offs = -6;
679         if (code) {
680                 code <<= 1;
681                 while ((code >>= 1)) i++;
682                 if (i > 4)
683                         return "unknown";
684                 return names[i];
685         } else {
686                 strcpy(static_buff, "Auto:");
687                 for (u = 0; u < 3; u++) {
688                         code = (PicoAutoRgnOrder >> u*4) & 0xf;
689                         for (i = 0; code; code >>= 1, i++)
690                                 ;
691                         strcat(static_buff, names_short[i]);
692                 }
693                 return static_buff;
694         }
695 }
696
697 static const char *mgn_saveloadcfg(int id, int *offs)
698 {
699         static_buff[0] = 0;
700         if (config_slot != 0)
701                 sprintf(static_buff, "[%i]", config_slot);
702         return static_buff;
703 }
704
705 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
706 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
707                                         "loading state or both";
708
709 static menu_entry e_menu_options[] =
710 {
711         mee_range     ("Save slot",                MA_OPT_SAVE_SLOT,     state_slot, 0, 9),
712         mee_range_cust("Frameskip",                MA_OPT_FRAMESKIP,     currentConfig.Frameskip, -1, 16, mgn_opt_fskip),
713         mee_cust      ("Region",                   MA_OPT_REGION,        mh_opt_misc, mgn_opt_region),
714         mee_onoff     ("Show FPS",                 MA_OPT_SHOW_FPS,      currentConfig.EmuOpt, EOPT_SHOW_FPS),
715         mee_onoff     ("Enable sound",             MA_OPT_ENABLE_SOUND,  currentConfig.EmuOpt, EOPT_EN_SOUND),
716         mee_cust      ("Sound Quality",            MA_OPT_SOUND_QUALITY, mh_opt_misc, mgn_opt_sound),
717         mee_enum_h    ("Confirm savestate",        MA_OPT_CONFIRM_STATES,currentConfig.confirm_save, men_confirm_save, h_confirm_save),
718         mee_range     ("",                         MA_OPT_CPU_CLOCKS,    currentConfig.CPUclock, 20, 1200),
719         mee_handler   ("[Display options]",        menu_loop_gfx_options),
720         mee_handler   ("[Sega/Mega CD options]",   menu_loop_cd_options),
721 #ifndef NO_32X
722         mee_handler   ("[32X options]",            menu_loop_32x_options),
723 #endif
724         mee_handler   ("[Advanced options]",       menu_loop_adv_options),
725         mee_cust_nosave("Save global config",      MA_OPT_SAVECFG, mh_saveloadcfg, mgn_saveloadcfg),
726         mee_cust_nosave("Save cfg for loaded game",MA_OPT_SAVECFG_GAME, mh_saveloadcfg, mgn_saveloadcfg),
727         mee_cust_nosave("Load cfg from profile",   MA_OPT_LOADCFG, mh_saveloadcfg, mgn_saveloadcfg),
728         mee_handler   ("Restore defaults",         mh_restore_defaults),
729         mee_end,
730 };
731
732 static int menu_loop_options(int id, int keys)
733 {
734         static int sel = 0;
735         int i;
736
737         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
738         e_menu_options[i].enabled = e_menu_options[i].name[0] ? 1 : 0;
739         me_enable(e_menu_options, MA_OPT_SAVECFG_GAME, PicoGameLoaded);
740         me_enable(e_menu_options, MA_OPT_LOADCFG, config_slot != config_slot_current);
741
742         me_loop(e_menu_options, &sel);
743
744         return 0;
745 }
746
747 // ------------ debug menu ------------
748
749 #include <pico/debug.h>
750
751 extern void SekStepM68k(void);
752
753 static void mplayer_loop(void)
754 {
755         pemu_sound_start();
756
757         while (1)
758         {
759                 PDebugZ80Frame();
760                 if (in_menu_wait_any(NULL, 0) & PBTN_MA3)
761                         break;
762                 emu_sound_wait();
763         }
764
765         emu_sound_stop();
766 }
767
768 static void draw_text_debug(const char *str, int skip, int from)
769 {
770         const char *p;
771         int line;
772
773         p = str;
774         while (skip-- > 0)
775         {
776                 while (*p && *p != '\n')
777                         p++;
778                 if (*p == 0 || p[1] == 0)
779                         return;
780                 p++;
781         }
782
783         str = p;
784         for (line = from; line < g_menuscreen_h / me_sfont_h; line++)
785         {
786                 smalltext_out16(1, line * me_sfont_h, str, 0xffff);
787                 while (*p && *p != '\n')
788                         p++;
789                 if (*p == 0)
790                         break;
791                 p++; str = p;
792         }
793 }
794
795 #ifdef __GNUC__
796 #define COMPILER "gcc " __VERSION__
797 #else
798 #define COMPILER
799 #endif
800
801 static void draw_frame_debug(void)
802 {
803         char layer_str[48] = "layers:                   ";
804         if (PicoDrawMask & PDRAW_LAYERB_ON)      memcpy(layer_str +  8, "B", 1);
805         if (PicoDrawMask & PDRAW_LAYERA_ON)      memcpy(layer_str + 10, "A", 1);
806         if (PicoDrawMask & PDRAW_SPRITES_LOW_ON) memcpy(layer_str + 12, "spr_lo", 6);
807         if (PicoDrawMask & PDRAW_SPRITES_HI_ON)  memcpy(layer_str + 19, "spr_hi", 6);
808         if (PicoDrawMask & PDRAW_32X_ON)         memcpy(layer_str + 26, "32x", 4);
809
810         pemu_forced_frame(1, 0);
811         make_bg(1);
812
813         smalltext_out16(4, 1, "build: r" REVISION "  "__DATE__ " " __TIME__ " " COMPILER, 0xffff);
814         smalltext_out16(4, g_menuscreen_h - me_sfont_h, layer_str, 0xffff);
815 }
816
817 static void debug_menu_loop(void)
818 {
819         int inp, mode = 0;
820         int spr_offs = 0, dumped = 0;
821         char *tmp;
822
823         while (1)
824         {
825                 menu_draw_begin(1, 0);
826                 switch (mode)
827                 {
828                         case 0: tmp = PDebugMain();
829                                 plat_debug_cat(tmp);
830                                 draw_text_debug(tmp, 0, 0);
831                                 if (dumped) {
832                                         smalltext_out16(g_menuscreen_w - 6 * me_sfont_h,
833                                                 g_menuscreen_h - me_mfont_h, "dumped", 0xffff);
834                                         dumped = 0;
835                                 }
836                                 break;
837                         case 1: draw_frame_debug();
838                                 break;
839                         case 2: pemu_forced_frame(1, 0);
840                                 make_bg(1);
841                                 PDebugShowSpriteStats((unsigned short *)g_menuscreen_ptr + (g_menuscreen_h/2 - 240/2)*g_menuscreen_w +
842                                         g_menuscreen_w/2 - 320/2, g_menuscreen_w);
843                                 break;
844                         case 3: memset(g_menuscreen_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
845                                 PDebugShowPalette(g_menuscreen_ptr, g_menuscreen_w);
846                                 PDebugShowSprite((unsigned short *)g_menuscreen_ptr + g_menuscreen_w*120 + g_menuscreen_w/2 + 16,
847                                         g_menuscreen_w, spr_offs);
848                                 draw_text_debug(PDebugSpriteList(), spr_offs, 6);
849                                 break;
850                         case 4: tmp = PDebug32x();
851                                 draw_text_debug(tmp, 0, 0);
852                                 break;
853                 }
854                 menu_draw_end();
855
856                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
857                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, NULL, 70);
858                 if (inp & PBTN_MBACK) return;
859                 if (inp & PBTN_L) { mode--; if (mode < 0) mode = 4; }
860                 if (inp & PBTN_R) { mode++; if (mode > 4) mode = 0; }
861                 switch (mode)
862                 {
863                         case 0:
864                                 if (inp & PBTN_MOK)
865                                         PDebugCPUStep();
866                                 if (inp & PBTN_MA3) {
867                                         while (inp & PBTN_MA3)
868                                                 inp = in_menu_wait_any(NULL, -1);
869                                         mplayer_loop();
870                                 }
871                                 if ((inp & (PBTN_MA2|PBTN_LEFT)) == (PBTN_MA2|PBTN_LEFT)) {
872                                         mkdir("dumps", 0777);
873                                         PDebugDumpMem();
874                                         while (inp & PBTN_MA2) inp = in_menu_wait_any(NULL, -1);
875                                         dumped = 1;
876                                 }
877                                 break;
878                         case 1:
879                                 if (inp & PBTN_LEFT)  PicoDrawMask ^= PDRAW_LAYERB_ON;
880                                 if (inp & PBTN_RIGHT) PicoDrawMask ^= PDRAW_LAYERA_ON;
881                                 if (inp & PBTN_DOWN)  PicoDrawMask ^= PDRAW_SPRITES_LOW_ON;
882                                 if (inp & PBTN_UP)    PicoDrawMask ^= PDRAW_SPRITES_HI_ON;
883                                 if (inp & PBTN_MA2)   PicoDrawMask ^= PDRAW_32X_ON;
884                                 if (inp & PBTN_MOK) {
885                                         PsndOut = NULL; // just in case
886                                         PicoSkipFrame = 1;
887                                         PicoFrame();
888                                         PicoSkipFrame = 0;
889                                         while (inp & PBTN_MOK) inp = in_menu_wait_any(NULL, -1);
890                                 }
891                                 break;
892                         case 3:
893                                 if (inp & PBTN_DOWN)  spr_offs++;
894                                 if (inp & PBTN_UP)    spr_offs--;
895                                 if (spr_offs < 0) spr_offs = 0;
896                                 break;
897                 }
898         }
899 }
900
901 // ------------ main menu ------------
902
903 static const char credits[] =
904         "PicoDrive v" VERSION " (c) notaz, 2006-2011\n\n\n"
905         "Credits:\n"
906         "fDave: Cyclone 68000 core,\n"
907         "      base code of PicoDrive\n"
908         "Reesy & FluBBa: DrZ80 core\n"
909         "MAME devs: YM2612 and SN76496 cores\n"
910         "Inder, ketchupgun: graphics\n"
911 #ifdef __GP2X__
912         "rlyeh and others: minimal SDK\n"
913         "Squidge: mmuhack\n"
914         "Dzz: ARM940 sample\n"
915 #endif
916         "\n"
917         "special thanks (for docs, ideas):\n"
918         " Charles MacDonald, Haze,\n"
919         " Stephane Dallongeville,\n"
920         " Lordus, Exophase, Rokas,\n"
921         " Nemesis, Tasco Deluxe";
922
923 static int main_menu_handler(int id, int keys)
924 {
925         const char *ret_name;
926
927         switch (id)
928         {
929         case MA_MAIN_RESUME_GAME:
930                 if (PicoGameLoaded)
931                         return 1;
932                 break;
933         case MA_MAIN_SAVE_STATE:
934                 if (PicoGameLoaded)
935                         return menu_loop_savestate(0);
936                 break;
937         case MA_MAIN_LOAD_STATE:
938                 if (PicoGameLoaded)
939                         return menu_loop_savestate(1);
940                 break;
941         case MA_MAIN_RESET_GAME:
942                 if (PicoGameLoaded) {
943                         emu_reset_game();
944                         return 1;
945                 }
946                 break;
947         case MA_MAIN_LOAD_ROM:
948                 rom_fname_reload = NULL;
949                 ret_name = menu_loop_romsel(rom_fname_loaded,
950                         sizeof(rom_fname_loaded), rom_exts, NULL);
951                 if (ret_name != NULL) {
952                         lprintf("selected file: %s\n", ret_name);
953                         rom_fname_reload = ret_name;
954                         engineState = PGS_ReloadRom;
955                         return 1;
956                 }
957                 break;
958         case MA_MAIN_CREDITS:
959                 draw_menu_message(credits, NULL);
960                 in_menu_wait(PBTN_MOK|PBTN_MBACK, NULL, 70);
961                 break;
962         case MA_MAIN_EXIT:
963                 engineState = PGS_Quit;
964                 return 1;
965         case MA_MAIN_PATCHES:
966                 if (PicoGameLoaded && PicoPatches) {
967                         menu_loop_patches();
968                         PicoPatchApply();
969                         menu_update_msg("Patches applied");
970                 }
971                 break;
972         default:
973                 lprintf("%s: something unknown selected\n", __FUNCTION__);
974                 break;
975         }
976
977         return 0;
978 }
979
980 static menu_entry e_menu_main[] =
981 {
982         mee_label     ("PicoDrive " VERSION),
983         mee_label     (""),
984         mee_label     (""),
985         mee_label     (""),
986         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
987         mee_handler_id("Save State",         MA_MAIN_SAVE_STATE,  main_menu_handler),
988         mee_handler_id("Load State",         MA_MAIN_LOAD_STATE,  main_menu_handler),
989         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
990         mee_handler_id("Load new ROM/ISO",   MA_MAIN_LOAD_ROM,    main_menu_handler),
991         mee_handler   ("Change options",                          menu_loop_options),
992         mee_handler   ("Configure controls",                      menu_loop_keyconfig),
993         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
994         mee_handler_id("Patches / GameGenie",MA_MAIN_PATCHES,     main_menu_handler),
995         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
996         mee_end,
997 };
998
999 void menu_loop(void)
1000 {
1001         static int sel = 0;
1002
1003         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, PicoGameLoaded);
1004         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  PicoGameLoaded);
1005         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  PicoGameLoaded);
1006         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  PicoGameLoaded);
1007         me_enable(e_menu_main, MA_MAIN_PATCHES, PicoPatches != NULL);
1008
1009         menu_enter(PicoGameLoaded);
1010         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1011         me_loop_d(e_menu_main, &sel, NULL, menu_main_plat_draw);
1012
1013         if (PicoGameLoaded) {
1014                 if (engineState == PGS_Menu)
1015                         engineState = PGS_Running;
1016                 /* wait until menu, ok, back is released */
1017                 while (in_menu_wait_any(NULL, 50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1018                         ;
1019         }
1020
1021         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1022         plat_video_menu_leave();
1023 }
1024
1025 // --------- CD tray close menu ----------
1026
1027 static int mh_tray_load_cd(int id, int keys)
1028 {
1029         const char *ret_name;
1030
1031         rom_fname_reload = NULL;
1032         ret_name = menu_loop_romsel(rom_fname_loaded,
1033                         sizeof(rom_fname_loaded), rom_exts, NULL);
1034         if (ret_name == NULL)
1035                 return 0;
1036
1037         rom_fname_reload = ret_name;
1038         engineState = PGS_RestartRun;
1039         return emu_swap_cd(ret_name);
1040 }
1041
1042 static int mh_tray_nothing(int id, int keys)
1043 {
1044         return 1;
1045 }
1046
1047 static menu_entry e_menu_tray[] =
1048 {
1049         mee_label  ("The CD tray has opened."),
1050         mee_label  (""),
1051         mee_label  (""),
1052         mee_handler("Load CD image",  mh_tray_load_cd),
1053         mee_handler("Insert nothing", mh_tray_nothing),
1054         mee_end,
1055 };
1056
1057 int menu_loop_tray(void)
1058 {
1059         int ret = 1, sel = 0;
1060
1061         menu_enter(PicoGameLoaded);
1062
1063         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1064         me_loop(e_menu_tray, &sel);
1065
1066         if (engineState != PGS_RestartRun) {
1067                 engineState = PGS_RestartRun;
1068                 ret = 0; /* no CD inserted */
1069         }
1070
1071         while (in_menu_wait_any(NULL, 50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK));
1072         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1073         plat_video_menu_leave();
1074
1075         return ret;
1076 }
1077
1078 void menu_update_msg(const char *msg)
1079 {
1080         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1081         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1082
1083         menu_error_time = plat_get_ticks_ms();
1084         lprintf("msg: %s\n", menu_error_msg);
1085 }
1086
1087 // ------------ util ------------
1088
1089 /* hidden options for config engine only */
1090 static menu_entry e_menu_hidden[] =
1091 {
1092         mee_onoff("Accurate sprites", MA_OPT_ACC_SPRITES, PicoOpt, 0x080),
1093         mee_end,
1094 };
1095
1096 static menu_entry *e_menu_table[] =
1097 {
1098         e_menu_options,
1099         e_menu_gfx_options,
1100         e_menu_adv_options,
1101         e_menu_cd_options,
1102 #ifndef NO_32X
1103         e_menu_32x_options,
1104 #endif
1105         e_menu_keyconfig,
1106         e_menu_hidden,
1107 };
1108
1109 static menu_entry *me_list_table = NULL;
1110 static menu_entry *me_list_i = NULL;
1111
1112 menu_entry *me_list_get_first(void)
1113 {
1114         me_list_table = me_list_i = e_menu_table[0];
1115         return me_list_i;
1116 }
1117
1118 menu_entry *me_list_get_next(void)
1119 {
1120         int i;
1121
1122         me_list_i++;
1123         if (me_list_i->name != NULL)
1124                 return me_list_i;
1125
1126         for (i = 0; i < array_size(e_menu_table); i++)
1127                 if (me_list_table == e_menu_table[i])
1128                         break;
1129
1130         if (i + 1 < array_size(e_menu_table))
1131                 me_list_table = me_list_i = e_menu_table[i + 1];
1132         else
1133                 me_list_table = me_list_i = NULL;
1134
1135         return me_list_i;
1136 }
1137
1138 void menu_init(void)
1139 {
1140         int i;
1141
1142         menu_init_base();
1143
1144         i = me_id2offset(e_menu_gfx_options, MA_OPT_VOUT_MODE);
1145         e_menu_gfx_options[i].data = plat_target.vout_methods;
1146         me_enable(e_menu_gfx_options, MA_OPT_VOUT_MODE,
1147                 plat_target.vout_methods != NULL);
1148
1149         i = me_id2offset(e_menu_gfx_options, MA_OPT3_FILTERING);
1150         e_menu_gfx_options[i].data = plat_target.hwfilters;
1151         me_enable(e_menu_gfx_options, MA_OPT3_FILTERING,
1152                 plat_target.hwfilters != NULL);
1153
1154         me_enable(e_menu_gfx_options, MA_OPT3_GAMMA,
1155                 plat_target.gamma_set != NULL);
1156 }