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