some work on PSP CLUT
[picodrive.git] / platform / psp / menu.c
1 // (c) Copyright 2006,2007 notaz, All rights reserved.
2 // Free for non-commercial use.
3
4 // For commercial use, separate licencing terms must be obtained.
5
6 // don't like to use loads of #ifdefs, so duplicating GP2X code
7 // horribly instead
8
9 //#include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <wchar.h>
13 #include <unistd.h>
14 #include <sys/syslimits.h> // PATH_MAX
15
16 #include <pspdisplay.h>
17 #include <pspgu.h>
18 #include <pspiofilemgr.h>
19
20 #include "psp.h"
21 #include "emu.h"
22 #include "menu.h"
23 #include "../common/menu.h"
24 #include "../common/emu.h"
25 #include "../common/readpng.h"
26 #include "../common/lprintf.h"
27 #include "version.h"
28
29 #include <Pico/PicoInt.h>
30 #include <Pico/Patch.h>
31 #include <zlib/zlib.h>
32
33
34 #define pspKeyUnkn "???"
35 static const char * const pspKeyNames[] = {
36         "SELECT",   pspKeyUnkn, pspKeyUnkn, "START",    "UP",       "RIGHT",    "DOWN",     "LEFT",
37         "L",        "R",        pspKeyUnkn, pspKeyUnkn, "TRIANGLE", "CIRCLE",   "X",        "SQUARE",
38         "HOME",     "HOLD",     "WLAN_UP",  "REMOTE",   "VOLUP",    "VOLDOWN",  "SCREEN",   "NOTE",
39         pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn
40 };
41
42 static unsigned char bg_buffer[480*272*2] __attribute__((aligned(16))); // TODO: move to vram?
43 #define menu_screen psp_screen
44
45 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker);
46 static void menu_prepare_bg(int use_game_bg);
47
48
49 static unsigned int inp_prev = 0;
50
51 static unsigned long wait_for_input(unsigned int interesting)
52 {
53         unsigned int ret;
54         static int repeats = 0, wait = 50;
55         int release = 0, i;
56
57         if (repeats == 2 || repeats == 4) wait /= 2;
58         if (repeats == 6) wait = 15;
59
60         for (i = 0; i < 6 && inp_prev == psp_pad_read(1); i++) {
61                 if (i == 0) repeats++;
62                 psp_msleep(wait);
63         }
64
65         while ( !((ret = psp_pad_read(1)) & interesting) ) {
66                 psp_msleep(50);
67                 release = 1;
68         }
69
70         if (release || ret != inp_prev) {
71                 repeats = 0;
72                 wait = 50;
73         }
74         inp_prev = ret;
75
76         // we don't need diagonals in menus
77         if ((ret&BTN_UP)   && (ret&BTN_LEFT))  ret &= ~BTN_LEFT;
78         if ((ret&BTN_UP)   && (ret&BTN_RIGHT)) ret &= ~BTN_RIGHT;
79         if ((ret&BTN_DOWN) && (ret&BTN_LEFT))  ret &= ~BTN_LEFT;
80         if ((ret&BTN_DOWN) && (ret&BTN_RIGHT)) ret &= ~BTN_RIGHT;
81
82         return ret;
83 }
84
85 static void menu_draw_begin(void)
86 {
87         // short *src = (short *)bg_buffer, *dst = (short *)menu_screen;
88         // int i;
89
90         // for (i = 272; i >= 0; i--, dst += 512, src += 480)
91         //      memcpy32((int *)dst, (int *)src, 480*2/4);
92
93         sceGuSync(0,0); // sync with prev
94         sceGuStart(GU_DIRECT, guCmdList);
95         sceGuCopyImage(GU_PSM_5650, 0, 0, 480, 272, 480, bg_buffer, 0, 0, 512, menu_screen);
96         sceGuFinish();
97         sceGuSync(0,0);
98 }
99
100
101 static void menu_draw_end(void)
102 {
103         psp_video_flip(1);
104 }
105
106
107 // --------- loading ROM screen ----------
108
109 static void load_progress_cb(int percent)
110 {
111         int ln, len = percent * 480 / 100;
112         unsigned short *dst;
113
114         sceDisplayWaitVblankStart();
115
116         dst = (unsigned short *)menu_screen + 512*20;
117
118         if (len > 480) len = 480;
119         for (ln = 10; ln > 0; ln--, dst += 512)
120                 memset(dst, 0xff, len*2);
121 }
122
123 void menu_romload_prepare(const char *rom_name)
124 {
125         const char *p = rom_name + strlen(rom_name);
126         while (p > rom_name && *p != '/') p--;
127
128         psp_video_switch_to_single();
129         menu_draw_begin();
130
131         smalltext_out16(1, 1, "Loading", 0xffff);
132         smalltext_out16_lim(1, 10, p, 0xffff, 80);
133         PicoCartLoadProgressCB = load_progress_cb;
134 }
135
136 void menu_romload_end(void)
137 {
138         PicoCartLoadProgressCB = NULL;
139         smalltext_out16(1, 30, "Starting emulation...", 0xffff);
140 }
141
142 // -------------- ROM selector --------------
143
144 // SceIoDirent
145 #define DT_DIR FIO_SO_IFDIR
146 #define DT_REG FIO_SO_IFREG
147
148 struct my_dirent
149 {
150         unsigned char d_type;
151         char d_name[255];
152 };
153
154 // bbbb bggg gggr rrrr
155 static unsigned short file2color(const char *fname)
156 {
157         const char *ext = fname + strlen(fname) - 3;
158         static const char *rom_exts[]   = { "zip", "bin", "smd", "gen", "iso" };
159         static const char *other_exts[] = { "gmv", "pat" };
160         int i;
161
162         if (ext < fname) ext = fname;
163         for (i = 0; i < sizeof(rom_exts)/sizeof(rom_exts[0]); i++)
164                 if (strcasecmp(ext, rom_exts[i]) == 0) return 0xfdf7;
165         for (i = 0; i < sizeof(other_exts)/sizeof(other_exts[0]); i++)
166                 if (strcasecmp(ext, other_exts[i]) == 0) return 0xaff5;
167         return 0xffff;
168 }
169
170 static void draw_dirlist(char *curdir, struct my_dirent **namelist, int n, int sel)
171 {
172         int start, i, pos;
173
174         start = 13 - sel;
175         n--; // exclude current dir (".")
176
177         menu_draw_begin();
178
179         if (rom_data == NULL) {
180 //              menu_darken_bg(menu_screen, menu_screen, 321*240, 0);
181         }
182
183         menu_darken_bg((char *)menu_screen + 512*129*2, (char *)menu_screen + 512*129*2, 512*10, 0);
184
185         if (start - 2 >= 0)
186                 smalltext_out16_lim(14, (start - 2)*10, curdir, 0xffff, 53-2);
187         for (i = 0; i < n; i++) {
188                 pos = start + i;
189                 if (pos < 0)  continue;
190                 if (pos > 26) break;
191                 if (namelist[i+1]->d_type & DT_DIR) {
192                         smalltext_out16_lim(14,   pos*10, "/", 0xd7ff, 1);
193                         smalltext_out16_lim(14+6, pos*10, namelist[i+1]->d_name, 0xd7ff, 53-3);
194                 } else {
195                         unsigned short color = file2color(namelist[i+1]->d_name);
196                         smalltext_out16_lim(14,   pos*10, namelist[i+1]->d_name, color, 53-2);
197                 }
198         }
199         text_out16(5, 130, ">");
200         menu_draw_end();
201 }
202
203 static int scandir_cmp(const void *p1, const void *p2)
204 {
205         struct my_dirent **d1 = (struct my_dirent **)p1, **d2 = (struct my_dirent **)p2;
206         if ((*d1)->d_type == (*d2)->d_type) return strcasecmp((*d1)->d_name, (*d2)->d_name);
207         if ((*d1)->d_type & DT_DIR) return -1; // put before
208         if ((*d2)->d_type & DT_DIR) return  1;
209         return strcasecmp((*d1)->d_name, (*d2)->d_name);
210 }
211
212 static char *filter_exts[] = {
213         ".mp3", ".srm", ".brm", "s.gz", ".mds", "bcfg", ".txt", ".htm", "html",
214         ".jpg", ".cue", ".pbp"
215 };
216
217 static int scandir_filter(const struct my_dirent *ent)
218 {
219         const char *p;
220         int i;
221
222         if (ent == NULL || ent->d_name == NULL) return 0;
223         if (strlen(ent->d_name) < 5) return 1;
224
225         p = ent->d_name + strlen(ent->d_name) - 4;
226
227         for (i = 0; i < sizeof(filter_exts)/sizeof(filter_exts[0]); i++)
228         {
229                 if (strcasecmp(p, filter_exts[i]) == 0) return 0;
230         }
231
232         return 1;
233 }
234
235 static int my_scandir(const char *dir, struct my_dirent ***namelist_out,
236                 int(*filter)(const struct my_dirent *),
237                 int(*compar)(const void *, const void *))
238 {
239         int ret = -1, dir_uid = -1, name_alloc = 4, name_count = 0;
240         struct my_dirent **namelist = NULL, *ent;
241         SceIoDirent sce_ent;
242
243         namelist = malloc(sizeof(*namelist) * name_alloc);
244         if (namelist == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
245
246         // try to read first..
247         dir_uid = sceIoDopen(dir);
248         if (dir_uid >= 0)
249         {
250                 /* it is very important to clear SceIoDirent to be passed to sceIoDread(), */
251                 /* or else it may crash, probably misinterpreting something in it. */
252                 memset(&sce_ent, 0, sizeof(sce_ent));
253                 ret = sceIoDread(dir_uid, &sce_ent);
254                 if (ret < 0)
255                 {
256                         lprintf("sceIoDread(\"%s\") failed with %i\n", dir, ret);
257                         goto fail;
258                 }
259         }
260         else
261                 lprintf("sceIoDopen(\"%s\") failed with %i\n", dir, dir_uid);
262
263         while (ret > 0)
264         {
265                 ent = malloc(sizeof(*ent));
266                 if (ent == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
267                 ent->d_type = sce_ent.d_stat.st_attr;
268                 strncpy(ent->d_name, sce_ent.d_name, sizeof(ent->d_name));
269                 ent->d_name[sizeof(ent->d_name)-1] = 0;
270                 if (filter == NULL || filter(ent))
271                      namelist[name_count++] = ent;
272                 else free(ent);
273
274                 if (name_count >= name_alloc)
275                 {
276                         void *tmp;
277                         name_alloc *= 2;
278                         tmp = realloc(namelist, sizeof(*namelist) * name_alloc);
279                         if (tmp == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
280                         namelist = tmp;
281                 }
282
283                 memset(&sce_ent, 0, sizeof(sce_ent));
284                 ret = sceIoDread(dir_uid, &sce_ent);
285         }
286
287         // sort
288         if (compar != NULL && name_count > 3) qsort(&namelist[2], name_count - 2, sizeof(namelist[0]), compar);
289
290         // all done.
291         ret = name_count;
292         *namelist_out = namelist;
293         goto end;
294
295 fail:
296         if (namelist != NULL)
297         {
298                 while (name_count--)
299                         free(namelist[name_count]);
300                 free(namelist);
301         }
302 end:
303         if (dir_uid >= 0) sceIoDclose(dir_uid);
304         return ret;
305 }
306
307
308 static char *romsel_loop(char *curr_path)
309 {
310         struct my_dirent **namelist;
311         int n, iret, sel = 0;
312         unsigned long inp = 0;
313         char *ret = NULL, *fname = NULL;
314         SceIoStat cpstat;
315
316         // is this a dir or a full path?
317         memset(&cpstat, 0, sizeof(cpstat));
318         iret = sceIoGetstat(curr_path, &cpstat);
319         if (iret >= 0 && (cpstat.st_attr & FIO_SO_IFREG)) { // file
320                 char *p;
321                 for (p = curr_path + strlen(curr_path) - 1; p > curr_path && *p != '/'; p--);
322                 *p = 0;
323                 fname = p+1;
324         }
325         else if (iret >= 0 && (cpstat.st_attr & FIO_SO_IFDIR)); // dir
326         else strcpy(curr_path, "ms0:/"); // something else
327
328         n = my_scandir(curr_path, &namelist, scandir_filter, scandir_cmp);
329         if (n < 0) {
330                 // try root..
331                 n = my_scandir("ms0:/", &namelist, scandir_filter, scandir_cmp);
332                 if (n < 0) {
333                         // oops, we failed
334                         lprintf("scandir failed, dir: "); lprintf(curr_path); lprintf("\n");
335                         return NULL;
336                 }
337         }
338
339         // try to find sel
340         if (fname != NULL) {
341                 int i;
342                 for (i = 1; i < n; i++) {
343                         if (strcmp(namelist[i]->d_name, fname) == 0) {
344                                 sel = i - 1;
345                                 break;
346                         }
347                 }
348         }
349
350         for (;;)
351         {
352                 draw_dirlist(curr_path, namelist, n, sel);
353                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_L|BTN_R|BTN_X|BTN_CIRCLE);
354                 if(inp & BTN_UP  )  { sel--;   if (sel < 0)   sel = n-2; }
355                 if(inp & BTN_DOWN)  { sel++;   if (sel > n-2) sel = 0; }
356                 if(inp & BTN_LEFT)  { sel-=10; if (sel < 0)   sel = 0; }
357                 if(inp & BTN_L)     { sel-=24; if (sel < 0)   sel = 0; }
358                 if(inp & BTN_RIGHT) { sel+=10; if (sel > n-2) sel = n-2; }
359                 if(inp & BTN_R)     { sel+=24; if (sel > n-2) sel = n-2; }
360                 if(inp & BTN_X)     { // enter dir/select
361                         if (namelist[sel+1]->d_type & DT_REG) {
362                                 strcpy(romFileName, curr_path);
363                                 strcat(romFileName, "/");
364                                 strcat(romFileName, namelist[sel+1]->d_name);
365                                 ret = romFileName;
366                                 break;
367                         } else if (namelist[sel+1]->d_type & DT_DIR) {
368                                 int newlen = strlen(curr_path) + strlen(namelist[sel+1]->d_name) + 2;
369                                 char *p, *newdir = malloc(newlen);
370                                 if (strcmp(namelist[sel+1]->d_name, "..") == 0) {
371                                         char *start = curr_path;
372                                         p = start + strlen(start) - 1;
373                                         while (*p == '/' && p > start) p--;
374                                         while (*p != '/' && *p != ':' && p > start) p--;
375                                         if (p <= start || *p == ':' || p[-1] == ':') strcpy(newdir, "ms0:/");
376                                         else { strncpy(newdir, start, p-start); newdir[p-start] = 0; }
377                                 } else {
378                                         strcpy(newdir, curr_path);
379                                         p = newdir + strlen(newdir) - 1;
380                                         while (*p == '/' && p >= newdir) *p-- = 0;
381                                         strcat(newdir, "/");
382                                         strcat(newdir, namelist[sel+1]->d_name);
383                                 }
384                                 ret = romsel_loop(newdir);
385                                 free(newdir);
386                                 break;
387                         }
388                 }
389                 if(inp & BTN_CIRCLE) break; // cancel
390         }
391
392         if (n > 0) {
393                 while(n--) free(namelist[n]);
394                 free(namelist);
395         }
396
397         return ret;
398 }
399
400 // ------------ debug menu ------------
401
402 char *debugString(void);
403
404 static void draw_debug(void)
405 {
406         char *p, *str = debugString();
407         int len, line;
408
409         menu_draw_begin();
410
411         p = str;
412         for (line = 0; line < 24; line++)
413         {
414                 while (*p && *p != '\n') p++;
415                 len = p - str;
416                 if (len > 55) len = 55;
417                 smalltext_out16_lim(1, line*10, str, 0xffff, len);
418                 if (*p == 0) break;
419                 p++; str = p;
420         }
421         menu_draw_end();
422 }
423
424 static void debug_menu_loop(void)
425 {
426         draw_debug();
427         wait_for_input(BTN_X|BTN_CIRCLE);
428 }
429
430 // ------------ patch/gg menu ------------
431
432 static void draw_patchlist(int sel)
433 {
434         int start, i, pos, active;
435
436         start = 13 - sel;
437
438         menu_draw_begin();
439
440         for (i = 0; i < PicoPatchCount; i++) {
441                 pos = start + i;
442                 if (pos < 0)  continue;
443                 if (pos > 26) break;
444                 active = PicoPatches[i].active;
445                 smalltext_out16_lim(14,     pos*10, active ? "ON " : "OFF", active ? 0xfff6 : 0xffff, 3);
446                 smalltext_out16_lim(14+6*4, pos*10, PicoPatches[i].name, active ? 0xfff6 : 0xffff, 53-6);
447         }
448         pos = start + i;
449         if (pos < 27) smalltext_out16_lim(14, pos*10, "done", 0xffff, 4);
450
451         text_out16(5, 130, ">");
452         menu_draw_end();
453 }
454
455
456 static void patches_menu_loop(void)
457 {
458         int menu_sel = 0;
459         unsigned long inp = 0;
460
461         for(;;)
462         {
463                 draw_patchlist(menu_sel);
464                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_L|BTN_R|BTN_X|BTN_CIRCLE);
465                 if(inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
466                 if(inp & BTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
467                 if(inp &(BTN_LEFT|BTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
468                 if(inp &(BTN_RIGHT|BTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
469                 if(inp & BTN_X) { // action
470                         if (menu_sel < PicoPatchCount)
471                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
472                         else    return;
473                 }
474                 if(inp & BTN_CIRCLE) return;
475         }
476
477 }
478
479 // ------------ savestate loader ------------
480
481 static int state_slot_flags = 0;
482
483 static void state_check_slots(void)
484 {
485         int slot;
486
487         state_slot_flags = 0;
488
489         for (slot = 0; slot < 10; slot++)
490         {
491                 if (emu_checkSaveFile(slot))
492                 {
493                         state_slot_flags |= 1 << slot;
494                 }
495         }
496 }
497
498 static void draw_savestate_bg(int slot)
499 {
500         struct PicoVideo tmp_pv;
501         unsigned short tmp_cram[0x40];
502         unsigned short tmp_vsram[0x40];
503         void *tmp_vram, *file;
504         char *fname;
505
506         fname = emu_GetSaveFName(1, 0, slot);
507         if (!fname) return;
508
509         tmp_vram = malloc(sizeof(Pico.vram));
510         if (tmp_vram == NULL) return;
511
512         memcpy(tmp_vram, Pico.vram, sizeof(Pico.vram));
513         memcpy(tmp_cram, Pico.cram, sizeof(Pico.cram));
514         memcpy(tmp_vsram, Pico.vsram, sizeof(Pico.vsram));
515         memcpy(&tmp_pv, &Pico.video, sizeof(Pico.video));
516
517         if (strcmp(fname + strlen(fname) - 3, ".gz") == 0) {
518                 file = gzopen(fname, "rb");
519                 emu_setSaveStateCbs(1);
520         } else {
521                 file = fopen(fname, "rb");
522                 emu_setSaveStateCbs(0);
523         }
524
525         if (file) {
526                 if (PicoMCD & 1) {
527                         PicoCdLoadStateGfx(file);
528                 } else {
529                         areaSeek(file, 0x10020, SEEK_SET);  // skip header and RAM in state file
530                         areaRead(Pico.vram, 1, sizeof(Pico.vram), file);
531                         areaSeek(file, 0x2000, SEEK_CUR);
532                         areaRead(Pico.cram, 1, sizeof(Pico.cram), file);
533                         areaRead(Pico.vsram, 1, sizeof(Pico.vsram), file);
534                         areaSeek(file, 0x221a0, SEEK_SET);
535                         areaRead(&Pico.video, 1, sizeof(Pico.video), file);
536                 }
537                 areaClose(file);
538         }
539
540         emu_forcedFrame();
541         menu_prepare_bg(1);
542
543         memcpy(Pico.vram, tmp_vram, sizeof(Pico.vram));
544         memcpy(Pico.cram, tmp_cram, sizeof(Pico.cram));
545         memcpy(Pico.vsram, tmp_vsram, sizeof(Pico.vsram));
546         memcpy(&Pico.video, &tmp_pv,  sizeof(Pico.video));
547         free(tmp_vram);
548 }
549
550 static void draw_savestate_menu(int menu_sel, int is_loading)
551 {
552         int tl_x = 80+25, tl_y = 16+60, y, i;
553
554         if (state_slot_flags & (1 << menu_sel))
555                 draw_savestate_bg(menu_sel);
556         menu_draw_begin();
557
558         text_out16(tl_x, 16+30, is_loading ? "Load state" : "Save state");
559
560         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 108);
561
562         /* draw all 10 slots */
563         y = tl_y;
564         for (i = 0; i < 10; i++, y+=10)
565         {
566                 text_out16(tl_x, y, "SLOT %i (%s)", i, (state_slot_flags & (1 << i)) ? "USED" : "free");
567         }
568         text_out16(tl_x, y, "back");
569
570         menu_draw_end();
571 }
572
573 static int savestate_menu_loop(int is_loading)
574 {
575         static int menu_sel = 10;
576         int menu_sel_max = 10;
577         unsigned long inp = 0;
578
579         state_check_slots();
580
581         for(;;)
582         {
583                 draw_savestate_menu(menu_sel, is_loading);
584                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE);
585                 if(inp & BTN_UP  ) {
586                         do {
587                                 menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max;
588                         } while (!(state_slot_flags & (1 << menu_sel)) && menu_sel != menu_sel_max && is_loading);
589                 }
590                 if(inp & BTN_DOWN) {
591                         do {
592                                 menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0;
593                         } while (!(state_slot_flags & (1 << menu_sel)) && menu_sel != menu_sel_max && is_loading);
594                 }
595                 if(inp & BTN_X) { // save/load
596                         if (menu_sel < 10) {
597                                 state_slot = menu_sel;
598                                 PicoStateProgressCB = emu_stateCb; /* also suitable for menu */
599                                 if (emu_SaveLoadGame(is_loading, 0)) {
600                                         strcpy(menuErrorMsg, is_loading ? "Load failed" : "Save failed");
601                                         return 1;
602                                 }
603                                 return 0;
604                         } else  return 1;
605                 }
606                 if(inp & BTN_CIRCLE) return 1;
607         }
608 }
609
610 // -------------- key config --------------
611
612 static char *action_binds(int player_idx, int action_mask)
613 {
614         static char strkeys[32*5];
615         int i;
616
617         strkeys[0] = 0;
618         for (i = 0; i < 32; i++) // i is key index
619         {
620                 if (currentConfig.KeyBinds[i] & action_mask)
621                 {
622                         if (player_idx >= 0 && ((currentConfig.KeyBinds[i] >> 16) & 3) != player_idx) continue;
623                         if (strkeys[0]) { strcat(strkeys, " + "); strcat(strkeys, pspKeyNames[i]); break; }
624                         else strcpy(strkeys, pspKeyNames[i]);
625                 }
626         }
627
628         return strkeys;
629 }
630
631 static void unbind_action(int action)
632 {
633         int i;
634
635         for (i = 0; i < 32; i++)
636                 currentConfig.KeyBinds[i] &= ~action;
637 }
638
639 static int count_bound_keys(int action, int pl_idx)
640 {
641         int i, keys = 0;
642
643         for (i = 0; i < 32; i++)
644         {
645                 if (pl_idx >= 0 && (currentConfig.KeyBinds[i]&0x30000) != (pl_idx<<16)) continue;
646                 if (currentConfig.KeyBinds[i] & action) keys++;
647         }
648
649         return keys;
650 }
651
652 typedef struct { char *name; int mask; } bind_action_t;
653
654 static void draw_key_config(const bind_action_t *opts, int opt_cnt, int player_idx, int sel)
655 {
656         int x, y, tl_y = 16+40, i;
657
658         menu_draw_begin();
659         if (player_idx >= 0) {
660                 text_out16(80+80, 16+20, "Player %i controls", player_idx + 1);
661                 x = 80+80;
662         } else {
663                 text_out16(80+80, 16+20, "Emulator controls");
664                 x = 80+40;
665         }
666
667         menu_draw_selection(x - 16, tl_y + sel*10, (player_idx >= 0) ? 66 : 130);
668
669         y = tl_y;
670         for (i = 0; i < opt_cnt; i++, y+=10)
671                 text_out16(x, y, "%s : %s", opts[i].name, action_binds(player_idx, opts[i].mask));
672
673         text_out16(x, y, "Done");
674
675         if (sel < opt_cnt) {
676                 text_out16(80+30, 180, "Press a button to bind/unbind");
677                 text_out16(80+30, 190, "Use SELECT to clear");
678                 text_out16(80+30, 200, "To bind UP/DOWN, hold SELECT");
679                 text_out16(80+30, 210, "Select \"Done\" to exit");
680         } else {
681                 text_out16(80+30, 190, "Use Options -> Save cfg");
682                 text_out16(80+30, 200, "to save controls");
683                 text_out16(80+30, 210, "Press X or O to exit");
684         }
685         menu_draw_end();
686 }
687
688 static void key_config_loop(const bind_action_t *opts, int opt_cnt, int player_idx)
689 {
690         int sel = 0, menu_sel_max = opt_cnt, prev_select = 0, i;
691         unsigned long inp = 0;
692
693         for (;;)
694         {
695                 draw_key_config(opts, opt_cnt, player_idx, sel);
696                 inp = wait_for_input(CONFIGURABLE_KEYS|BTN_SELECT);
697                 if (!(inp & BTN_SELECT)) {
698                         prev_select = 0;
699                         if(inp & BTN_UP  ) { sel--; if (sel < 0) sel = menu_sel_max; continue; }
700                         if(inp & BTN_DOWN) { sel++; if (sel > menu_sel_max) sel = 0; continue; }
701                 }
702                 if (sel >= opt_cnt) {
703                         if (inp & (BTN_X|BTN_CIRCLE)) break;
704                         else continue;
705                 }
706                 // if we are here, we want to bind/unbind something
707                 if ((inp & BTN_SELECT) && !prev_select)
708                         unbind_action(opts[sel].mask);
709                 prev_select = inp & BTN_SELECT;
710                 inp &= CONFIGURABLE_KEYS;
711                 inp &= ~BTN_SELECT;
712                 for (i = 0; i < 32; i++)
713                         if (inp & (1 << i)) {
714                                 if (count_bound_keys(opts[sel].mask, player_idx) >= 2)
715                                      currentConfig.KeyBinds[i] &= ~opts[sel].mask; // allow to unbind only
716                                 else currentConfig.KeyBinds[i] ^=  opts[sel].mask;
717                                 if (player_idx >= 0 && (currentConfig.KeyBinds[i] & opts[sel].mask)) {
718                                         currentConfig.KeyBinds[i] &= ~(3 << 16);
719                                         currentConfig.KeyBinds[i] |= player_idx << 16;
720                                 }
721                         }
722         }
723 }
724
725 static void draw_kc_sel(int menu_sel)
726 {
727         int tl_x = 80+25+40, tl_y = 16+60, y;
728
729         y = tl_y;
730         menu_draw_begin();
731         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 138);
732
733         text_out16(tl_x, y,       "Player 1");
734         text_out16(tl_x, (y+=10), "Player 2");
735         text_out16(tl_x, (y+=10), "Emulator controls");
736         text_out16(tl_x, (y+=10), "Done");
737
738         menu_draw_end();
739 }
740
741
742 // PicoPad[] format: MXYZ SACB RLDU
743 static bind_action_t ctrl_actions[] =
744 {
745         { "UP     ", 0x001 },
746         { "DOWN   ", 0x002 },
747         { "LEFT   ", 0x004 },
748         { "RIGHT  ", 0x008 },
749         { "A      ", 0x040 },
750         { "B      ", 0x010 },
751         { "C      ", 0x020 },
752         { "START  ", 0x080 },
753         { "MODE   ", 0x800 },
754         { "X      ", 0x400 },
755         { "Y      ", 0x200 },
756         { "Z      ", 0x100 },
757 };
758
759 // player2_flag, ?, ?, ?, ?, ?, ?, menu
760 // "NEXT SAVE SLOT", "PREV SAVE SLOT", "SWITCH RENDERER", "SAVE STATE",
761 // "LOAD STATE", "VOLUME UP", "VOLUME DOWN", "DONE"
762 static bind_action_t emuctrl_actions[] =
763 {
764         { "Load State     ", 1<<28 },
765         { "Save State     ", 1<<27 },
766         { "Prev Save Slot ", 1<<25 },
767         { "Next Save Slot ", 1<<24 },
768         { "Switch Renderer", 1<<26 },
769         { "Volume Down    ", 1<<30 },
770         { "Volume Up      ", 1<<29 },
771 };
772
773 static void kc_sel_loop(void)
774 {
775         int menu_sel = 3, menu_sel_max = 3;
776         unsigned long inp = 0;
777         int is_6button = currentConfig.PicoOpt & 0x020;
778
779         while (1)
780         {
781                 draw_kc_sel(menu_sel);
782                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE);
783                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
784                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
785                 if (inp & BTN_X) {
786                         switch (menu_sel) {
787                                 case 0: key_config_loop(ctrl_actions, is_6button ? 12 : 8, 0); return;
788                                 case 1: key_config_loop(ctrl_actions, is_6button ? 12 : 8, 1); return;
789                                 case 2: key_config_loop(emuctrl_actions,
790                                                 sizeof(emuctrl_actions)/sizeof(emuctrl_actions[0]), -1); return;
791                                 case 3: if (rom_data == NULL) emu_WriteConfig(0); return;
792                                 default: return;
793                         }
794                 }
795                 if (inp & BTN_CIRCLE) return;
796         }
797 }
798
799
800 // --------- sega/mega cd options ----------
801
802 menu_entry cdopt_entries[] =
803 {
804         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_USA, NULL, 0, 0, 0, 1 },
805         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_EUR, NULL, 0, 0, 0, 1 },
806         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_JAP, NULL, 0, 0, 0, 1 },
807         { "CD LEDs",                   MB_ONOFF, MA_CDOPT_LEDS,         &currentConfig.EmuOpt,  0x0400, 0, 0, 1 },
808         { "CDDA audio (using mp3s)",   MB_ONOFF, MA_CDOPT_CDDA,         &currentConfig.PicoOpt, 0x0800, 0, 0, 1 },
809         { "PCM audio",                 MB_ONOFF, MA_CDOPT_PCM,          &currentConfig.PicoOpt, 0x0400, 0, 0, 1 },
810         { NULL,                        MB_NONE,  MA_CDOPT_READAHEAD,    NULL, 0, 0, 0, 1 },
811         { "SaveRAM cart",              MB_ONOFF, MA_CDOPT_SAVERAM,      &currentConfig.PicoOpt, 0x8000, 0, 0, 1 },
812         { "Scale/Rot. fx (slow)",      MB_ONOFF, MA_CDOPT_SCALEROT_CHIP,&currentConfig.PicoOpt, 0x1000, 0, 0, 1 },
813         { "Better sync (slow)",        MB_ONOFF, MA_CDOPT_BETTER_SYNC,  &currentConfig.PicoOpt, 0x2000, 0, 0, 1 },
814         { "done",                      MB_NONE,  MA_CDOPT_DONE,         NULL, 0, 0, 0, 1 },
815 };
816
817 #define CDOPT_ENTRY_COUNT (sizeof(cdopt_entries) / sizeof(cdopt_entries[0]))
818
819
820 struct bios_names_t
821 {
822         char us[32], eu[32], jp[32];
823 };
824
825 static void menu_cdopt_cust_draw(const menu_entry *entry, int x, int y, void *param)
826 {
827         struct bios_names_t *bios_names = param;
828         char ra_buff[16];
829
830         switch (entry->id)
831         {
832                 case MA_CDOPT_TESTBIOS_USA: text_out16(x, y, "USA BIOS:     %s", bios_names->us); break;
833                 case MA_CDOPT_TESTBIOS_EUR: text_out16(x, y, "EUR BIOS:     %s", bios_names->eu); break;
834                 case MA_CDOPT_TESTBIOS_JAP: text_out16(x, y, "JAP BIOS:     %s", bios_names->jp); break;
835                 case MA_CDOPT_READAHEAD:
836                         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
837                         else strcpy(ra_buff, "     OFF");
838                         text_out16(x, y, "ReadAhead buffer      %s", ra_buff);
839                         break;
840                 default:break;
841         }
842 }
843
844 static void draw_cd_menu_options(int menu_sel, struct bios_names_t *bios_names)
845 {
846         int tl_x = 80+25, tl_y = 16+60;
847         menu_id selected_id;
848         char ra_buff[16];
849
850         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
851         else strcpy(ra_buff, "     OFF");
852
853         menu_draw_begin();
854
855         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 246);
856
857         me_draw(cdopt_entries, CDOPT_ENTRY_COUNT, tl_x, tl_y, menu_cdopt_cust_draw, bios_names);
858
859         selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
860         if ((selected_id == MA_CDOPT_TESTBIOS_USA && strcmp(bios_names->us, "NOT FOUND")) ||
861                 (selected_id == MA_CDOPT_TESTBIOS_EUR && strcmp(bios_names->eu, "NOT FOUND")) ||
862                 (selected_id == MA_CDOPT_TESTBIOS_JAP && strcmp(bios_names->jp, "NOT FOUND")))
863                         text_out16(tl_x, 210, "Press start to test selected BIOS");
864
865         menu_draw_end();
866 }
867
868 static void cd_menu_loop_options(void)
869 {
870         static int menu_sel = 0;
871         int menu_sel_max = 10;
872         unsigned long inp = 0;
873         struct bios_names_t bios_names;
874         menu_id selected_id;
875         char *bios, *p;
876
877         if (emu_findBios(4, &bios)) { // US
878                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--); p++;
879                 strncpy(bios_names.us, p, sizeof(bios_names.us)); bios_names.us[sizeof(bios_names.us)-1] = 0;
880         } else  strcpy(bios_names.us, "NOT FOUND");
881
882         if (emu_findBios(8, &bios)) { // EU
883                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--); p++;
884                 strncpy(bios_names.eu, p, sizeof(bios_names.eu)); bios_names.eu[sizeof(bios_names.eu)-1] = 0;
885         } else  strcpy(bios_names.eu, "NOT FOUND");
886
887         if (emu_findBios(1, &bios)) { // JP
888                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--); p++;
889                 strncpy(bios_names.jp, p, sizeof(bios_names.jp)); bios_names.jp[sizeof(bios_names.jp)-1] = 0;
890         } else  strcpy(bios_names.jp, "NOT FOUND");
891
892         for(;;)
893         {
894                 draw_cd_menu_options(menu_sel, &bios_names);
895                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE);
896                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
897                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
898                 selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
899                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
900                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
901                             selected_id == MA_CDOPT_READAHEAD) {
902                                 if (inp & BTN_LEFT) {
903                                         PicoCDBuffers >>= 1;
904                                         if (PicoCDBuffers < 64) PicoCDBuffers = 0;
905                                 } else {
906                                         if (PicoCDBuffers < 64) PicoCDBuffers = 64;
907                                         else PicoCDBuffers <<= 1;
908                                         if (PicoCDBuffers > 8*1024) PicoCDBuffers = 8*1024; // 16M
909                                 }
910                         }
911                 }
912                 if (inp & BTN_X) { // toggleable options
913                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, 1) &&
914                             selected_id == MA_CDOPT_DONE) {
915                                 return;
916                         }
917                         switch (selected_id) { // BIOS testers
918                                 case MA_CDOPT_TESTBIOS_USA:
919                                         if (emu_findBios(4, &bios)) { // test US
920                                                 strcpy(romFileName, bios);
921                                                 engineState = PGS_ReloadRom;
922                                                 return;
923                                         }
924                                         break;
925                                 case MA_CDOPT_TESTBIOS_EUR:
926                                         if (emu_findBios(8, &bios)) { // test EU
927                                                 strcpy(romFileName, bios);
928                                                 engineState = PGS_ReloadRom;
929                                                 return;
930                                         }
931                                         break;
932                                 case MA_CDOPT_TESTBIOS_JAP:
933                                         if (emu_findBios(1, &bios)) { // test JP
934                                                 strcpy(romFileName, bios);
935                                                 engineState = PGS_ReloadRom;
936                                                 return;
937                                         }
938                                         break;
939                                 default:
940                                         break;
941                         }
942                 }
943                 if (inp & BTN_CIRCLE) return;
944         }
945 }
946
947
948 // --------- advanced options ----------
949
950 menu_entry opt2_entries[] =
951 {
952         { "Emulate Z80",               MB_ONOFF, MA_OPT2_ENABLE_Z80,    &currentConfig.PicoOpt,0x0004, 0, 0, 1 },
953         { "Emulate YM2612 (FM)",       MB_ONOFF, MA_OPT2_ENABLE_YM2612, &currentConfig.PicoOpt,0x0001, 0, 0, 1 },
954         { "Emulate SN76496 (PSG)",     MB_ONOFF, MA_OPT2_ENABLE_SN76496,&currentConfig.PicoOpt,0x0002, 0, 0, 1 },
955 //      { "Double buffering",          MB_ONOFF, MA_OPT2_DBLBUFF,       &currentConfig.EmuOpt, 0x8000, 0, 0, 1 },
956 //      { "Wait for V-sync (slow)",    MB_ONOFF, MA_OPT2_VSYNC,         &currentConfig.EmuOpt, 0x2000, 0, 0, 1 },
957         { "gzip savestates",           MB_ONOFF, MA_OPT2_GZIP_STATES,   &currentConfig.EmuOpt, 0x0008, 0, 0, 1 },
958         { "Don't save last used ROM",  MB_ONOFF, MA_OPT2_NO_LAST_ROM,   &currentConfig.EmuOpt, 0x0020, 0, 0, 1 },
959         { "done",                      MB_NONE,  MA_OPT2_DONE,          NULL, 0, 0, 0, 1 },
960 };
961
962 #define OPT2_ENTRY_COUNT (sizeof(opt2_entries) / sizeof(opt2_entries[0]))
963
964
965 static void draw_amenu_options(int menu_sel)
966 {
967         int tl_x = 80+25, tl_y = 16+50;
968
969         menu_draw_begin();
970
971         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 252);
972
973         me_draw(opt2_entries, OPT2_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
974
975         menu_draw_end();
976 }
977
978 static void amenu_loop_options(void)
979 {
980         static int menu_sel = 0;
981         int menu_sel_max;
982         unsigned long inp = 0;
983         menu_id selected_id;
984
985         menu_sel_max = me_count_enabled(opt2_entries, OPT2_ENTRY_COUNT) - 1;
986
987         for(;;)
988         {
989                 draw_amenu_options(menu_sel);
990                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE);
991                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
992                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
993                 selected_id = me_index2id(opt2_entries, OPT2_ENTRY_COUNT, menu_sel);
994                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
995                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
996                             selected_id == MA_OPT2_GAMMA) {
997                                 while ((inp = psp_pad_read(1)) & (BTN_LEFT|BTN_RIGHT)) {
998                                         currentConfig.gamma += (inp & BTN_LEFT) ? -1 : 1;
999                                         if (currentConfig.gamma <   1) currentConfig.gamma =   1;
1000                                         if (currentConfig.gamma > 300) currentConfig.gamma = 300;
1001                                         draw_amenu_options(menu_sel);
1002                                         psp_msleep(18);
1003                                 }
1004                         }
1005                 }
1006                 if (inp & BTN_X) { // toggleable options
1007                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, 1) &&
1008                             selected_id == MA_OPT2_DONE) {
1009                                 return;
1010                         }
1011                 }
1012                 if (inp & BTN_CIRCLE) return;
1013         }
1014 }
1015
1016 // -------------- options --------------
1017
1018
1019 menu_entry opt_entries[] =
1020 {
1021         { NULL,                        MB_NONE,  MA_OPT_RENDERER,      NULL, 0, 0, 0, 1 },
1022         { "Scale low res mode",        MB_ONOFF, MA_OPT_SCALING,       &currentConfig.scaling, 0x0001, 0, 3, 1 },
1023         { "Accurate timing (slower)",  MB_ONOFF, MA_OPT_ACC_TIMING,    &currentConfig.PicoOpt, 0x0040, 0, 0, 1 },
1024         { "Accurate sprites (slower)", MB_ONOFF, MA_OPT_ACC_SPRITES,   &currentConfig.PicoOpt, 0x0080, 0, 0, 1 },
1025         { "Show FPS",                  MB_ONOFF, MA_OPT_SHOW_FPS,      &currentConfig.EmuOpt,  0x0002, 0, 0, 1 },
1026         { NULL,                        MB_RANGE, MA_OPT_FRAMESKIP,     &currentConfig.Frameskip, 0, -1, 16, 1 },
1027         { "Enable sound",              MB_ONOFF, MA_OPT_ENABLE_SOUND,  &currentConfig.EmuOpt,  0x0004, 0, 0, 1 },
1028         { NULL,                        MB_NONE,  MA_OPT_SOUND_QUALITY, NULL, 0, 0, 0, 1 },
1029         { "6 button pad",              MB_ONOFF, MA_OPT_6BUTTON_PAD,   &currentConfig.PicoOpt, 0x0020, 0, 0, 1 },
1030         { NULL,                        MB_NONE,  MA_OPT_REGION,        NULL, 0, 0, 0, 1 },
1031         { "Use SRAM/BRAM savestates",  MB_ONOFF, MA_OPT_SRAM_STATES,   &currentConfig.EmuOpt,  0x0001, 0, 0, 1 },
1032         { NULL,                        MB_NONE,  MA_OPT_CONFIRM_STATES,NULL, 0, 0, 0, 1 },
1033         { "Save slot",                 MB_RANGE, MA_OPT_SAVE_SLOT,     &state_slot, 0, 0, 9, 1 },
1034         { NULL,                        MB_NONE,  MA_OPT_CPU_CLOCKS,    NULL, 0, 0, 0, 1 },
1035         { "[Sega/Mega CD options]",    MB_NONE,  MA_OPT_SCD_OPTS,      NULL, 0, 0, 0, 1 },
1036         { "[advanced options]",        MB_NONE,  MA_OPT_ADV_OPTS,      NULL, 0, 0, 0, 1 },
1037         { NULL,                        MB_NONE,  MA_OPT_SAVECFG,       NULL, 0, 0, 0, 1 },
1038         { "Save cfg for current game only",MB_NONE,MA_OPT_SAVECFG_GAME,NULL, 0, 0, 0, 1 },
1039         { NULL,                        MB_NONE,  MA_OPT_LOADCFG,       NULL, 0, 0, 0, 1 },
1040 };
1041
1042 #define OPT_ENTRY_COUNT (sizeof(opt_entries) / sizeof(opt_entries[0]))
1043
1044
1045 static const char *region_name(unsigned int code)
1046 {
1047         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
1048         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
1049         int u, i = 0;
1050         if (code) {
1051                 code <<= 1;
1052                 while((code >>= 1)) i++;
1053                 if (i > 4) return "unknown";
1054                 return names[i];
1055         } else {
1056                 static char name[24];
1057                 strcpy(name, "Auto:");
1058                 for (u = 0; u < 3; u++) {
1059                         i = 0; code = ((PicoAutoRgnOrder >> u*4) & 0xf) << 1;
1060                         while((code >>= 1)) i++;
1061                         strcat(name, names_short[i]);
1062                 }
1063                 return name;
1064         }
1065 }
1066
1067
1068 static void menu_opt_cust_draw(const menu_entry *entry, int x, int y, void *param)
1069 {
1070         char *str, str24[24];
1071
1072         switch (entry->id)
1073         {
1074                 case MA_OPT_RENDERER:
1075                         if (currentConfig.PicoOpt&0x10)
1076                                 str = " 8bit fast";
1077                         else if (currentConfig.EmuOpt&0x80)
1078                                 str = "16bit accurate";
1079                         else
1080                                 str = " 8bit accurate";
1081                         text_out16(x, y, "Renderer:            %s", str);
1082                         break;
1083                 case MA_OPT_FRAMESKIP:
1084                         if (currentConfig.Frameskip < 0)
1085                              strcpy(str24, "Auto");
1086                         else sprintf(str24, "%i", currentConfig.Frameskip);
1087                         text_out16(x, y, "Frameskip                  %s", str24);
1088                         break;
1089                 case MA_OPT_SOUND_QUALITY:
1090                         str = (currentConfig.PicoOpt&0x08)?"stereo":"mono";
1091                         text_out16(x, y, "Sound Quality:     %5iHz %s", currentConfig.PsndRate, str);
1092                         break;
1093                 case MA_OPT_REGION:
1094                         text_out16(x, y, "Region:              %s", region_name(currentConfig.PicoRegion));
1095                         break;
1096                 case MA_OPT_CONFIRM_STATES:
1097                         switch ((currentConfig.EmuOpt >> 9) & 5) {
1098                                 default: str = "OFF";    break;
1099                                 case 1:  str = "writes"; break;
1100                                 case 4:  str = "loads";  break;
1101                                 case 5:  str = "both";   break;
1102                         }
1103                         text_out16(x, y, "Confirm savestate          %s", str);
1104                         break;
1105                 case MA_OPT_CPU_CLOCKS:
1106                         text_out16(x, y, "CPU/bus clock       %3i/%3iMHz", currentConfig.CPUclock, currentConfig.CPUclock/2);
1107                         break;
1108                 case MA_OPT_SAVECFG:
1109                         str24[0] = 0;
1110                         if (config_slot != 0) sprintf(str24, " (profile: %i)", config_slot);
1111                         text_out16(x, y, "Save cfg as default%s", str24);
1112                         break;
1113                 case MA_OPT_LOADCFG:
1114                         text_out16(x, y, "Load cfg from profile %i", config_slot);
1115                         break;
1116                 default:
1117                         lprintf("%s: unimplemented (%i)\n", __FUNCTION__, entry->id);
1118                         break;
1119         }
1120 }
1121
1122
1123
1124 static void draw_menu_options(int menu_sel)
1125 {
1126         int tl_x = 80+25, tl_y = 16+24;
1127
1128         menu_draw_begin();
1129
1130         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 284);
1131
1132         me_draw(opt_entries, OPT_ENTRY_COUNT, tl_x, tl_y, menu_opt_cust_draw, NULL);
1133
1134         menu_draw_end();
1135 }
1136
1137 static int sndrate_prevnext(int rate, int dir)
1138 {
1139         int i, rates[] = { 11025, 22050, 44100 };
1140
1141         for (i = 0; i < 5; i++)
1142                 if (rates[i] == rate) break;
1143
1144         i += dir ? 1 : -1;
1145         if (i > 2) return dir ? 44100 : 22050;
1146         if (i < 0) return dir ? 22050 : 11025;
1147         return rates[i];
1148 }
1149
1150 static void region_prevnext(int right)
1151 {
1152         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
1153         static int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
1154         int i;
1155         if (right) {
1156                 if (!currentConfig.PicoRegion) {
1157                         for (i = 0; i < 6; i++)
1158                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1159                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
1160                         else currentConfig.PicoRegion=1;
1161                 }
1162                 else currentConfig.PicoRegion<<=1;
1163                 if (currentConfig.PicoRegion > 8) currentConfig.PicoRegion = 8;
1164         } else {
1165                 if (!currentConfig.PicoRegion) {
1166                         for (i = 0; i < 6; i++)
1167                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1168                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
1169                 }
1170                 else currentConfig.PicoRegion>>=1;
1171         }
1172 }
1173
1174 static void menu_options_save(void)
1175 {
1176         PicoOpt = currentConfig.PicoOpt;
1177         PsndRate = currentConfig.PsndRate;
1178         PicoRegionOverride = currentConfig.PicoRegion;
1179         if (!(PicoOpt & 0x20)) {
1180                 // unbind XYZ MODE, just in case
1181                 unbind_action(0xf00);
1182         }
1183 }
1184
1185 static int menu_loop_options(void)
1186 {
1187         static int menu_sel = 0;
1188         int menu_sel_max, ret;
1189         unsigned long inp = 0;
1190         menu_id selected_id;
1191
1192         currentConfig.PicoOpt = PicoOpt;
1193         currentConfig.PsndRate = PsndRate;
1194         currentConfig.PicoRegion = PicoRegionOverride;
1195
1196         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_SAVECFG_GAME, rom_data != NULL);
1197         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1198         menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1199         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1200
1201         while (1)
1202         {
1203                 draw_menu_options(menu_sel);
1204                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE);
1205                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1206                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1207                 selected_id = me_index2id(opt_entries, OPT_ENTRY_COUNT, menu_sel);
1208                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1209                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0)) {
1210                                 switch (selected_id) {
1211                                         case MA_OPT_RENDERER:
1212                                                 if (inp & BTN_LEFT) {
1213                                                         if ((currentConfig.PicoOpt&0x10) || !(currentConfig.EmuOpt &0x80)) {
1214                                                                 currentConfig.PicoOpt&= ~0x10;
1215                                                                 currentConfig.EmuOpt |=  0x80;
1216                                                         }
1217                                                 } else {
1218                                                         if (!(currentConfig.PicoOpt&0x10) || (currentConfig.EmuOpt &0x80)) {
1219                                                                 currentConfig.PicoOpt|=  0x10;
1220                                                                 currentConfig.EmuOpt &= ~0x80;
1221                                                         }
1222                                                 }
1223                                                 break;
1224                                         case MA_OPT_SOUND_QUALITY:
1225                                                 if ((inp & BTN_RIGHT) && currentConfig.PsndRate == 44100 &&
1226                                                                 !(currentConfig.PicoOpt&0x08))
1227                                                 {
1228                                                         currentConfig.PsndRate =  11025;
1229                                                         currentConfig.PicoOpt |=  8;
1230                                                 } else if ((inp & BTN_LEFT) && currentConfig.PsndRate == 11025 &&
1231                                                                 (currentConfig.PicoOpt&0x08) && !(PicoMCD&1))
1232                                                 {
1233                                                         currentConfig.PsndRate =  44100;
1234                                                         currentConfig.PicoOpt &= ~8;
1235                                                 } else
1236                                                         currentConfig.PsndRate = sndrate_prevnext(currentConfig.PsndRate, inp & BTN_RIGHT);
1237                                                 break;
1238                                         case MA_OPT_REGION:
1239                                                 region_prevnext(inp & BTN_RIGHT);
1240                                                 break;
1241                                         case MA_OPT_CONFIRM_STATES: {
1242                                                          int n = ((currentConfig.EmuOpt>>9)&1) | ((currentConfig.EmuOpt>>10)&2);
1243                                                          n += (inp & BTN_LEFT) ? -1 : 1;
1244                                                          if (n < 0) n = 0; else if (n > 3) n = 3;
1245                                                          n |= n << 1; n &= ~2;
1246                                                          currentConfig.EmuOpt &= ~0xa00;
1247                                                          currentConfig.EmuOpt |= n << 9;
1248                                                          break;
1249                                                  }
1250                                         case MA_OPT_SAVE_SLOT:
1251                                                  if (inp & BTN_RIGHT) {
1252                                                          state_slot++; if (state_slot > 9) state_slot = 0;
1253                                                  } else {state_slot--; if (state_slot < 0) state_slot = 9;
1254                                                  }
1255                                                  break;
1256                                         case MA_OPT_CPU_CLOCKS:
1257                                                  while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1258                                                          currentConfig.CPUclock += (inp & BTN_LEFT) ? -1 : 1;
1259                                                          if (currentConfig.CPUclock <  19) currentConfig.CPUclock = 19;
1260                                                          if (currentConfig.CPUclock > 333) currentConfig.CPUclock = 333;
1261                                                          draw_menu_options(menu_sel); // will wait vsync
1262                                                  }
1263                                                  break;
1264                                         case MA_OPT_SAVECFG:
1265                                         case MA_OPT_SAVECFG_GAME:
1266                                         case MA_OPT_LOADCFG:
1267                                                  config_slot += (inp&BTN_RIGHT) ? 1 : -1;
1268                                                  if (config_slot > 9) config_slot = 0;
1269                                                  if (config_slot < 0) config_slot = 9;
1270                                                  me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1271                                                  menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1272                                                  if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1273                                                  break;
1274                                         default:
1275                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1276                                                 break;
1277                                 }
1278                         }
1279                 }
1280                 if (inp & BTN_X) {
1281                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, 1))
1282                         {
1283                                 switch (selected_id)
1284                                 {
1285                                         case MA_OPT_SCD_OPTS:
1286                                                 cd_menu_loop_options();
1287                                                 if (engineState == PGS_ReloadRom)
1288                                                         return 0; // test BIOS
1289                                                 break;
1290                                         case MA_OPT_ADV_OPTS:
1291                                                 amenu_loop_options();
1292                                                 break;
1293                                         case MA_OPT_SAVECFG: // done (update and write)
1294                                                 menu_options_save();
1295                                                 if (emu_WriteConfig(0)) strcpy(menuErrorMsg, "config saved");
1296                                                 else strcpy(menuErrorMsg, "failed to write config");
1297                                                 return 1;
1298                                         case MA_OPT_SAVECFG_GAME: // done (update and write for current game)
1299                                                 menu_options_save();
1300                                                 if (emu_WriteConfig(1)) strcpy(menuErrorMsg, "config saved");
1301                                                 else strcpy(menuErrorMsg, "failed to write config");
1302                                                 return 1;
1303                                         case MA_OPT_LOADCFG:
1304                                                 ret = emu_ReadConfig(1, 1);
1305                                                 if (!ret) ret = emu_ReadConfig(0, 1);
1306                                                 if (ret)  strcpy(menuErrorMsg, "config loaded");
1307                                                 else      strcpy(menuErrorMsg, "failed to load config");
1308                                                 return 1;
1309                                         default:
1310                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1311                                                 break;
1312                                 }
1313                         }
1314                 }
1315                 if(inp & BTN_CIRCLE) {
1316                         menu_options_save();
1317                         return 0;  // done (update, no write)
1318                 }
1319         }
1320 }
1321
1322 // -------------- credits --------------
1323
1324 static void draw_menu_credits(void)
1325 {
1326         int tl_x = 80+15, tl_y = 16+64, y;
1327         menu_draw_begin();
1328
1329         text_out16(tl_x, 16+20, "PicoDrive v" VERSION " (c) notaz, 2006,2007");
1330
1331         y = tl_y;
1332         text_out16(tl_x, y, "Credits:");
1333         text_out16(tl_x, (y+=10), "Dave: base code of PicoDrive");
1334         text_out16(tl_x, (y+=10), "MAME devs: YM2612 and SN76496 cores");
1335         text_out16(tl_x, (y+=10), "Charles MacDonald: Genesis hw docs");
1336         text_out16(tl_x, (y+=10), "Stephane Dallongeville:");
1337         text_out16(tl_x, (y+=10), "      opensource Gens");
1338         text_out16(tl_x, (y+=10), "Haze: Genesis hw info");
1339         text_out16(tl_x, (y+=10), "ketchupgun: skin design");
1340
1341         menu_draw_end();
1342 }
1343
1344
1345 // -------------- root menu --------------
1346
1347 menu_entry main_entries[] =
1348 {
1349         { "Resume game",        MB_NONE, MA_MAIN_RESUME_GAME, NULL, 0, 0, 0, 0 },
1350         { "Save State",         MB_NONE, MA_MAIN_SAVE_STATE,  NULL, 0, 0, 0, 0 },
1351         { "Load State",         MB_NONE, MA_MAIN_LOAD_STATE,  NULL, 0, 0, 0, 0 },
1352         { "Reset game",         MB_NONE, MA_MAIN_RESET_GAME,  NULL, 0, 0, 0, 0 },
1353         { "Load new ROM/ISO",   MB_NONE, MA_MAIN_LOAD_ROM,    NULL, 0, 0, 0, 1 },
1354         { "Change options",     MB_NONE, MA_MAIN_OPTIONS,     NULL, 0, 0, 0, 1 },
1355         { "Configure controls", MB_NONE, MA_MAIN_CONTROLS,    NULL, 0, 0, 0, 1 },
1356         { "Credits",            MB_NONE, MA_MAIN_CREDITS,     NULL, 0, 0, 0, 1 },
1357         { "Patches / GameGenie",MB_NONE, MA_MAIN_PATCHES,     NULL, 0, 0, 0, 0 },
1358         { "Exit",               MB_NONE, MA_MAIN_EXIT,        NULL, 0, 0, 0, 1 }
1359 };
1360
1361 #define MAIN_ENTRY_COUNT (sizeof(main_entries) / sizeof(main_entries[0]))
1362
1363 static void draw_menu_root(int menu_sel)
1364 {
1365         const int tl_x = 80+70, tl_y = 16+70;
1366
1367         menu_draw_begin();
1368
1369         text_out16(tl_x, 16+20, "PicoDrive v" VERSION);
1370
1371         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 146);
1372
1373         me_draw(main_entries, MAIN_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1374
1375         // error
1376         if (menuErrorMsg[0]) {
1377                 // memset((char *)menu_screen + 321*224*2, 0, 321*16*2);
1378                 text_out16(5, 258, menuErrorMsg);
1379         }
1380         menu_draw_end();
1381 }
1382
1383
1384 static void menu_loop_root(void)
1385 {
1386         static int menu_sel = 0;
1387         int ret, menu_sel_max;
1388         unsigned long inp = 0;
1389
1390         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESUME_GAME, rom_data != NULL);
1391         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_SAVE_STATE,  rom_data != NULL);
1392         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_LOAD_STATE,  rom_data != NULL);
1393         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESET_GAME,  rom_data != NULL);
1394         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_PATCHES,     PicoPatches != NULL);
1395
1396         menu_sel_max = me_count_enabled(main_entries, MAIN_ENTRY_COUNT) - 1;
1397         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1398
1399         /* make sure action buttons are not pressed on entering menu */
1400         draw_menu_root(menu_sel);
1401
1402         while (psp_pad_read(1) & (BTN_X|BTN_CIRCLE|BTN_SELECT)) psp_msleep(50);
1403
1404         for (;;)
1405         {
1406                 draw_menu_root(menu_sel);
1407                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE|BTN_SELECT|BTN_L|BTN_R);
1408                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1409                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1410                 if((inp & (BTN_L|BTN_R)) == (BTN_L|BTN_R)) debug_menu_loop();
1411                 if( inp & (BTN_SELECT|BTN_CIRCLE)) {
1412                         if (rom_data) {
1413                                 while (psp_pad_read(1) & (BTN_SELECT|BTN_CIRCLE)) psp_msleep(50); // wait until released
1414                                 engineState = PGS_Running;
1415                                 break;
1416                         }
1417                 }
1418                 if(inp & BTN_X)  {
1419                         switch (me_index2id(main_entries, MAIN_ENTRY_COUNT, menu_sel))
1420                         {
1421                                 case MA_MAIN_RESUME_GAME:
1422                                         if (rom_data) {
1423                                                 while (psp_pad_read(1) & BTN_X) psp_msleep(50);
1424                                                 engineState = PGS_Running;
1425                                                 return;
1426                                         }
1427                                         break;
1428                                 case MA_MAIN_SAVE_STATE:
1429                                         if (rom_data) {
1430                                                 if(savestate_menu_loop(0))
1431                                                         continue;
1432                                                 engineState = PGS_Running;
1433                                                 return;
1434                                         }
1435                                         break;
1436                                 case MA_MAIN_LOAD_STATE:
1437                                         if (rom_data) {
1438                                                 if(savestate_menu_loop(1))
1439                                                         continue;
1440                                                 engineState = PGS_Running;
1441                                                 return;
1442                                         }
1443                                         break;
1444                                 case MA_MAIN_RESET_GAME:
1445                                         if (rom_data) {
1446                                                 emu_ResetGame();
1447                                                 engineState = PGS_Running;
1448                                                 return;
1449                                         }
1450                                         break;
1451                                 case MA_MAIN_LOAD_ROM:
1452                                 {
1453                                         char curr_path[PATH_MAX], *selfname;
1454                                         FILE *tstf;
1455                                         if ( (tstf = fopen(currentConfig.lastRomFile, "rb")) )
1456                                         {
1457                                                 fclose(tstf);
1458                                                 strcpy(curr_path, currentConfig.lastRomFile);
1459                                         }
1460                                         else
1461                                                 getcwd(curr_path, PATH_MAX);
1462                                         selfname = romsel_loop(curr_path);
1463                                         if (selfname) {
1464                                                 lprintf("selected file: %s\n", selfname);
1465                                                 engineState = PGS_ReloadRom;
1466                                                 return;
1467                                         }
1468                                         break;
1469                                 }
1470                                 case MA_MAIN_OPTIONS:
1471                                         ret = menu_loop_options();
1472                                         if (ret == 1) continue; // status update
1473                                         if (engineState == PGS_ReloadRom)
1474                                                 return; // BIOS test
1475                                         break;
1476                                 case MA_MAIN_CONTROLS:
1477                                         kc_sel_loop();
1478                                         break;
1479                                 case MA_MAIN_CREDITS:
1480                                         draw_menu_credits();
1481                                         psp_msleep(500);
1482                                         inp = wait_for_input(BTN_X|BTN_CIRCLE);
1483                                         break;
1484                                 case MA_MAIN_EXIT:
1485                                         engineState = PGS_Quit;
1486                                         return;
1487                                 case MA_MAIN_PATCHES:
1488                                         if (rom_data && PicoPatches) {
1489                                                 patches_menu_loop();
1490                                                 PicoPatchApply();
1491                                                 strcpy(menuErrorMsg, "Patches applied");
1492                                                 continue;
1493                                         }
1494                                         break;
1495                                 default:
1496                                         lprintf("%s: something unknown selected\n", __FUNCTION__);
1497                                         break;
1498                         }
1499                 }
1500                 menuErrorMsg[0] = 0; // clear error msg
1501         }
1502 }
1503
1504 // warning: alignment
1505 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker)
1506 {
1507         unsigned int *dest = dst;
1508         const unsigned int *srce = src;
1509         pixels /= 2;
1510         if (darker)
1511         {
1512                 while (pixels--)
1513                 {
1514                         unsigned int p = *srce++;
1515                         *dest++ = ((p&0xf79ef79e)>>1) - ((p&0xc618c618)>>3);
1516                 }
1517         }
1518         else
1519         {
1520                 while (pixels--)
1521                 {
1522                         unsigned int p = *srce++;
1523                         *dest++ = (p&0xf79ef79e)>>1;
1524                 }
1525         }
1526 }
1527
1528 static void menu_prepare_bg(int use_game_bg)
1529 {
1530         memset(bg_buffer, 0, sizeof(bg_buffer));
1531
1532         if (use_game_bg)
1533         {
1534                 // darken the active framebuffer
1535                 /*
1536                 memset(bg_buffer, 0, 321*8*2);
1537                 menu_darken_bg(bg_buffer + 321*8*2, (char *)giz_screen + 321*8*2, 321*224, 1);
1538                 memset(bg_buffer + 321*232*2, 0, 321*8*2);
1539                 */
1540         }
1541         else
1542         {
1543                 // should really only happen once, on startup..
1544                 readpng(bg_buffer, "skin/background.png", READPNG_BG);
1545         }
1546 }
1547
1548 static void menu_gfx_prepare(void)
1549 {
1550         menu_prepare_bg(rom_data != NULL);
1551
1552         menu_draw_begin();
1553         menu_draw_end();
1554 }
1555
1556
1557 void menu_loop(void)
1558 {
1559         menu_gfx_prepare();
1560
1561         menu_loop_root();
1562
1563         menuErrorMsg[0] = 0;
1564 }
1565
1566
1567 // --------- CD tray close menu ----------
1568
1569 static void draw_menu_tray(int menu_sel)
1570 {
1571         int tl_x = 70, tl_y = 90, y;
1572
1573         menu_draw_begin();
1574
1575         text_out16(tl_x, 20, "The unit is about to");
1576         text_out16(tl_x, 30, "close the CD tray.");
1577
1578         y = tl_y;
1579         text_out16(tl_x, y,       "Load new CD image");
1580         text_out16(tl_x, (y+=10), "Insert nothing");
1581
1582         // draw cursor
1583         text_out16(tl_x - 16, tl_y + menu_sel*10, ">");
1584         // error
1585         if (menuErrorMsg[0]) text_out16(5, 226, menuErrorMsg);
1586         menu_draw_end();
1587 }
1588
1589
1590 int menu_loop_tray(void)
1591 {
1592         int menu_sel = 0, menu_sel_max = 1;
1593         unsigned long inp = 0;
1594         char curr_path[PATH_MAX], *selfname;
1595         FILE *tstf;
1596
1597         menu_gfx_prepare();
1598
1599         if ( (tstf = fopen(currentConfig.lastRomFile, "rb")) )
1600         {
1601                 fclose(tstf);
1602                 strcpy(curr_path, currentConfig.lastRomFile);
1603         }
1604         else
1605         {
1606                 getcwd(curr_path, PATH_MAX);
1607         }
1608
1609         /* make sure action buttons are not pressed on entering menu */
1610         draw_menu_tray(menu_sel);
1611         while (psp_pad_read(1) & BTN_X) psp_msleep(50);
1612
1613         for (;;)
1614         {
1615                 draw_menu_tray(menu_sel);
1616                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X);
1617                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1618                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1619                 if(inp & BTN_X   )  {
1620                         switch (menu_sel) {
1621                                 case 0: // select image
1622                                         selfname = romsel_loop(curr_path);
1623                                         if (selfname) {
1624                                                 int ret = -1, cd_type;
1625                                                 cd_type = emu_cdCheck(NULL);
1626                                                 if (cd_type > 0)
1627                                                         ret = Insert_CD(romFileName, cd_type == 2);
1628                                                 if (ret != 0) {
1629                                                         sprintf(menuErrorMsg, "Load failed, invalid CD image?");
1630                                                         lprintf("%s\n", menuErrorMsg);
1631                                                         continue;
1632                                                 }
1633                                                 engineState = PGS_RestartRun;
1634                                                 return 1;
1635                                         }
1636                                         break;
1637                                 case 1: // insert nothing
1638                                         engineState = PGS_RestartRun;
1639                                         return 0;
1640                         }
1641                 }
1642                 menuErrorMsg[0] = 0; // clear error msg
1643         }
1644 }
1645
1646