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