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