psp fixes, gamma
[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 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_data) 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" };
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_data == NULL) {
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 typedef struct { char *name; int mask; } bind_action_t;
703
704 static void draw_key_config(const bind_action_t *opts, int opt_cnt, int player_idx, int sel)
705 {
706         int x, y, tl_y = 16+40, i;
707
708         menu_draw_begin();
709         if (player_idx >= 0) {
710                 text_out16(80+80, 16+20, "Player %i controls", player_idx + 1);
711                 x = 80+80;
712         } else {
713                 text_out16(80+80, 16+20, "Emulator controls");
714                 x = 80+40;
715         }
716
717         menu_draw_selection(x - 16, tl_y + sel*10, (player_idx >= 0) ? 66 : 130);
718
719         y = tl_y;
720         for (i = 0; i < opt_cnt; i++, y+=10)
721                 text_out16(x, y, "%s : %s", opts[i].name, action_binds(player_idx, opts[i].mask));
722
723         text_out16(x, y, "Done");
724
725         if (sel < opt_cnt) {
726                 text_out16(80+30, 220, "Press a button to bind/unbind");
727                 text_out16(80+30, 230, "Use SELECT to clear");
728                 text_out16(80+30, 240, "To bind UP/DOWN, hold SELECT");
729                 text_out16(80+30, 250, "Select \"Done\" to exit");
730         } else {
731                 text_out16(80+30, 230, "Use Options -> Save cfg");
732                 text_out16(80+30, 240, "to save controls");
733                 text_out16(80+30, 250, "Press X or O to exit");
734         }
735         menu_draw_end();
736 }
737
738 static void key_config_loop(const bind_action_t *opts, int opt_cnt, int player_idx)
739 {
740         int sel = 0, menu_sel_max = opt_cnt, prev_select = 0, i;
741         unsigned long inp = 0;
742
743         for (;;)
744         {
745                 draw_key_config(opts, opt_cnt, player_idx, sel);
746                 inp = wait_for_input(CONFIGURABLE_KEYS|BTN_SELECT, 1);
747                 if (!(inp & BTN_SELECT)) {
748                         prev_select = 0;
749                         if(inp & BTN_UP  ) { sel--; if (sel < 0) sel = menu_sel_max; continue; }
750                         if(inp & BTN_DOWN) { sel++; if (sel > menu_sel_max) sel = 0; continue; }
751                 }
752                 if (sel >= opt_cnt) {
753                         if (inp & (BTN_X|BTN_CIRCLE)) break;
754                         else continue;
755                 }
756                 // if we are here, we want to bind/unbind something
757                 if ((inp & BTN_SELECT) && !prev_select)
758                         unbind_action(opts[sel].mask);
759                 prev_select = inp & BTN_SELECT;
760                 inp &= CONFIGURABLE_KEYS;
761                 inp &= ~BTN_SELECT;
762                 for (i = 0; i < 32; i++)
763                         if (inp & (1 << i)) {
764                                 if (count_bound_keys(opts[sel].mask, player_idx) >= 2)
765                                      currentConfig.KeyBinds[i] &= ~opts[sel].mask; // allow to unbind only
766                                 else currentConfig.KeyBinds[i] ^=  opts[sel].mask;
767                                 if (player_idx >= 0 && (currentConfig.KeyBinds[i] & opts[sel].mask)) {
768                                         currentConfig.KeyBinds[i] &= ~(3 << 16);
769                                         currentConfig.KeyBinds[i] |= player_idx << 16;
770                                 }
771                         }
772         }
773 }
774
775 static void draw_kc_sel(int menu_sel)
776 {
777         int tl_x = 80+25+40, tl_y = 16+60, y;
778
779         y = tl_y;
780         menu_draw_begin();
781         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 138);
782
783         text_out16(tl_x, y,       "Player 1");
784         text_out16(tl_x, (y+=10), "Player 2");
785         text_out16(tl_x, (y+=10), "Emulator controls");
786         text_out16(tl_x, (y+=10), "Done");
787
788         menu_draw_end();
789 }
790
791
792 // PicoPad[] format: MXYZ SACB RLDU
793 static bind_action_t ctrl_actions[] =
794 {
795         { "UP     ", 0x001 },
796         { "DOWN   ", 0x002 },
797         { "LEFT   ", 0x004 },
798         { "RIGHT  ", 0x008 },
799         { "A      ", 0x040 },
800         { "B      ", 0x010 },
801         { "C      ", 0x020 },
802         { "START  ", 0x080 },
803         { "MODE   ", 0x800 },
804         { "X      ", 0x400 },
805         { "Y      ", 0x200 },
806         { "Z      ", 0x100 },
807 };
808
809 // player2_flag, ?, ?, ?, ?, ?, ?, menu
810 // "NEXT SAVE SLOT", "PREV SAVE SLOT", "SWITCH RENDERER", "SAVE STATE",
811 // "LOAD STATE", "VOLUME UP", "VOLUME DOWN", "DONE"
812 static bind_action_t emuctrl_actions[] =
813 {
814         { "Load State     ", 1<<28 },
815         { "Save State     ", 1<<27 },
816         { "Prev Save Slot ", 1<<25 },
817         { "Next Save Slot ", 1<<24 },
818         { "Switch Renderer", 1<<26 },
819 };
820
821 static void kc_sel_loop(void)
822 {
823         int menu_sel = 3, menu_sel_max = 3;
824         unsigned long inp = 0;
825         int is_6button = currentConfig.PicoOpt & 0x020;
826
827         while (1)
828         {
829                 draw_kc_sel(menu_sel);
830                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE, 0);
831                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
832                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
833                 if (inp & BTN_CIRCLE) {
834                         switch (menu_sel) {
835                                 case 0: key_config_loop(ctrl_actions, is_6button ? 12 : 8, 0); return;
836                                 case 1: key_config_loop(ctrl_actions, is_6button ? 12 : 8, 1); return;
837                                 case 2: key_config_loop(emuctrl_actions,
838                                                 sizeof(emuctrl_actions)/sizeof(emuctrl_actions[0]), -1); return;
839                                 case 3: if (rom_data == NULL) emu_WriteConfig(0); return;
840                                 default: return;
841                         }
842                 }
843                 if (inp & BTN_X) return;
844         }
845 }
846
847
848 // --------- sega/mega cd options ----------
849
850 menu_entry cdopt_entries[] =
851 {
852         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_USA, NULL, 0, 0, 0, 1 },
853         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_EUR, NULL, 0, 0, 0, 1 },
854         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_JAP, NULL, 0, 0, 0, 1 },
855         { "CD LEDs",                   MB_ONOFF, MA_CDOPT_LEDS,         &currentConfig.EmuOpt,  0x0400, 0, 0, 1 },
856         { "CDDA audio (using mp3s)",   MB_ONOFF, MA_CDOPT_CDDA,         &currentConfig.PicoOpt, 0x0800, 0, 0, 1 },
857         { "PCM audio",                 MB_ONOFF, MA_CDOPT_PCM,          &currentConfig.PicoOpt, 0x0400, 0, 0, 1 },
858         { NULL,                        MB_NONE,  MA_CDOPT_READAHEAD,    NULL, 0, 0, 0, 1 },
859         { "SaveRAM cart",              MB_ONOFF, MA_CDOPT_SAVERAM,      &currentConfig.PicoOpt, 0x8000, 0, 0, 1 },
860         { "Scale/Rot. fx (slow)",      MB_ONOFF, MA_CDOPT_SCALEROT_CHIP,&currentConfig.PicoOpt, 0x1000, 0, 0, 1 },
861         { "Better sync (slow)",        MB_ONOFF, MA_CDOPT_BETTER_SYNC,  &currentConfig.PicoOpt, 0x2000, 0, 0, 1 },
862         { "done",                      MB_NONE,  MA_CDOPT_DONE,         NULL, 0, 0, 0, 1 },
863 };
864
865 #define CDOPT_ENTRY_COUNT (sizeof(cdopt_entries) / sizeof(cdopt_entries[0]))
866
867
868 struct bios_names_t
869 {
870         char us[32], eu[32], jp[32];
871 };
872
873 static void menu_cdopt_cust_draw(const menu_entry *entry, int x, int y, void *param)
874 {
875         struct bios_names_t *bios_names = param;
876         char ra_buff[16];
877
878         switch (entry->id)
879         {
880                 case MA_CDOPT_TESTBIOS_USA: text_out16(x, y, "USA BIOS:     %s", bios_names->us); break;
881                 case MA_CDOPT_TESTBIOS_EUR: text_out16(x, y, "EUR BIOS:     %s", bios_names->eu); break;
882                 case MA_CDOPT_TESTBIOS_JAP: text_out16(x, y, "JAP BIOS:     %s", bios_names->jp); break;
883                 case MA_CDOPT_READAHEAD:
884                         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
885                         else strcpy(ra_buff, "     OFF");
886                         text_out16(x, y, "ReadAhead buffer      %s", ra_buff);
887                         break;
888                 default:break;
889         }
890 }
891
892 static void draw_cd_menu_options(int menu_sel, struct bios_names_t *bios_names)
893 {
894         int tl_x = 80+25, tl_y = 16+60;
895         menu_id selected_id;
896         char ra_buff[16];
897
898         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
899         else strcpy(ra_buff, "     OFF");
900
901         menu_draw_begin();
902
903         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 246);
904
905         me_draw(cdopt_entries, CDOPT_ENTRY_COUNT, tl_x, tl_y, menu_cdopt_cust_draw, bios_names);
906
907         selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
908         if ((selected_id == MA_CDOPT_TESTBIOS_USA && strcmp(bios_names->us, "NOT FOUND")) ||
909                 (selected_id == MA_CDOPT_TESTBIOS_EUR && strcmp(bios_names->eu, "NOT FOUND")) ||
910                 (selected_id == MA_CDOPT_TESTBIOS_JAP && strcmp(bios_names->jp, "NOT FOUND")))
911                         text_out16(tl_x, 250, "Press start to test selected BIOS");
912
913         menu_draw_end();
914 }
915
916 static void cd_menu_loop_options(void)
917 {
918         static int menu_sel = 0;
919         int menu_sel_max = 10;
920         unsigned long inp = 0;
921         struct bios_names_t bios_names;
922         menu_id selected_id;
923         char *bios, *p;
924
925         if (emu_findBios(4, &bios)) { // US
926                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
927                 if (*p == '/') p++;
928                 strncpy(bios_names.us, p, sizeof(bios_names.us)); bios_names.us[sizeof(bios_names.us)-1] = 0;
929         } else  strcpy(bios_names.us, "NOT FOUND");
930
931         if (emu_findBios(8, &bios)) { // EU
932                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
933                 if (*p == '/') p++;
934                 strncpy(bios_names.eu, p, sizeof(bios_names.eu)); bios_names.eu[sizeof(bios_names.eu)-1] = 0;
935         } else  strcpy(bios_names.eu, "NOT FOUND");
936
937         if (emu_findBios(1, &bios)) { // JP
938                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
939                 if (*p == '/') p++;
940                 strncpy(bios_names.jp, p, sizeof(bios_names.jp)); bios_names.jp[sizeof(bios_names.jp)-1] = 0;
941         } else  strcpy(bios_names.jp, "NOT FOUND");
942
943         menuErrorMsg[0] = 0;
944
945         for (;;)
946         {
947                 draw_cd_menu_options(menu_sel, &bios_names);
948                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE|BTN_START, 0);
949                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
950                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
951                 selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
952                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
953                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
954                             selected_id == MA_CDOPT_READAHEAD) {
955                                 if (inp & BTN_LEFT) {
956                                         PicoCDBuffers >>= 1;
957                                         if (PicoCDBuffers < 64) PicoCDBuffers = 0;
958                                 } else {
959                                         if (PicoCDBuffers < 64) PicoCDBuffers = 64;
960                                         else PicoCDBuffers <<= 1;
961                                         if (PicoCDBuffers > 8*1024) PicoCDBuffers = 8*1024; // 16M
962                                 }
963                         }
964                 }
965                 if (inp & BTN_CIRCLE) // toggleable options
966                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, 1) &&
967                             selected_id == MA_CDOPT_DONE) {
968                                 return;
969                         }
970                 if (inp & BTN_START) {
971                         switch (selected_id) { // BIOS testers
972                                 case MA_CDOPT_TESTBIOS_USA:
973                                         if (emu_findBios(4, &bios)) { // test US
974                                                 strcpy(romFileName, bios);
975                                                 engineState = PGS_ReloadRom;
976                                                 return;
977                                         }
978                                         break;
979                                 case MA_CDOPT_TESTBIOS_EUR:
980                                         if (emu_findBios(8, &bios)) { // test EU
981                                                 strcpy(romFileName, bios);
982                                                 engineState = PGS_ReloadRom;
983                                                 return;
984                                         }
985                                         break;
986                                 case MA_CDOPT_TESTBIOS_JAP:
987                                         if (emu_findBios(1, &bios)) { // test JP
988                                                 strcpy(romFileName, bios);
989                                                 engineState = PGS_ReloadRom;
990                                                 return;
991                                         }
992                                         break;
993                                 default:
994                                         break;
995                         }
996                 }
997                 if (inp & BTN_X) return;
998         }
999 }
1000
1001 // --------- display options ----------
1002
1003 menu_entry opt3_entries[] =
1004 {
1005         { NULL,                        MB_NONE,  MA_OPT3_SCALE,         NULL, 0, 0, 0, 1 },
1006         { NULL,                        MB_NONE,  MA_OPT3_HSCALE32,      NULL, 0, 0, 0, 1 },
1007         { NULL,                        MB_NONE,  MA_OPT3_HSCALE40,      NULL, 0, 0, 0, 1 },
1008         { NULL,                        MB_ONOFF, MA_OPT3_FILTERING,     &currentConfig.scaling, 1,  0,  0, 1 },
1009         { NULL,                        MB_RANGE, MA_OPT3_GAMMAA,        &currentConfig.gamma,   0, -4, 16, 1 },
1010         { NULL,                        MB_NONE,  MA_OPT3_VSYNC,         NULL, 0, 0, 0, 1 },
1011         { "Set to unscaled centered",  MB_NONE,  MA_OPT3_PRES_NOSCALE,  NULL, 0, 0, 0, 1 },
1012         { "Set to 4:3 scaled",         MB_NONE,  MA_OPT3_PRES_SCALE43,  NULL, 0, 0, 0, 1 },
1013         { "Set to fullscreen",         MB_NONE,  MA_OPT3_PRES_FULLSCR,  NULL, 0, 0, 0, 1 },
1014         { "done",                      MB_NONE,  MA_OPT3_DONE,          NULL, 0, 0, 0, 1 },
1015 };
1016
1017 #define OPT3_ENTRY_COUNT (sizeof(opt3_entries) / sizeof(opt3_entries[0]))
1018
1019
1020 static void menu_opt3_cust_draw(const menu_entry *entry, int x, int y, void *param)
1021 {
1022         switch (entry->id)
1023         {
1024                 case MA_OPT3_SCALE:
1025                         text_out16(x, y, "Scale factor:                      %.2f", currentConfig.scale);
1026                         break;
1027                 case MA_OPT3_HSCALE32:
1028                         text_out16(x, y, "Hor. scale (for low res. games):   %.2f", currentConfig.hscale32);
1029                         break;
1030                 case MA_OPT3_HSCALE40:
1031                         text_out16(x, y, "Hor. scale (for hi res. games):    %.2f", currentConfig.hscale40);
1032                         break;
1033                 case MA_OPT3_FILTERING:
1034                         text_out16(x, y, "Bilinear filtering                 %s", currentConfig.scaling?"ON":"OFF");
1035                         break;
1036                 case MA_OPT3_GAMMAA:
1037                         text_out16(x, y, "Gamma adjustment                  %2i", currentConfig.gamma);
1038                         break;
1039                 case MA_OPT3_VSYNC: {
1040                         char *val = "    never";
1041                         if (currentConfig.EmuOpt & 0x2000)
1042                                 val = (currentConfig.EmuOpt & 0x10000) ? "sometimes" : "   always";
1043                         text_out16(x, y, "Wait for vsync (slow)         %s", val);
1044                         break;
1045                 }
1046                 default: break;
1047         }
1048 }
1049
1050 static void menu_opt3_preview(int is_32col)
1051 {
1052         void *oldstate = NULL;
1053
1054         if (rom_data == NULL || ((Pico.video.reg[12]&1)^1) != is_32col)
1055         {
1056                 extern char bgdatac32_start[], bgdatac40_start[];
1057                 extern int bgdatac32_size, bgdatac40_size;
1058                 void *bgdata = is_32col ? bgdatac32_start : bgdatac40_start;
1059                 unsigned long insize = is_32col ? bgdatac32_size : bgdatac40_size, outsize = 65856;
1060                 int ret;
1061                 ret = uncompress((Bytef *)bg_buffer, &outsize, bgdata, insize);
1062                 if (ret == 0)
1063                 {
1064                         if (rom_data != NULL) oldstate = get_oldstate_for_preview();
1065                         memcpy(Pico.vram,  bg_buffer, sizeof(Pico.vram));
1066                         memcpy(Pico.cram,  (char *)bg_buffer + 0x10000, 0x40*2);
1067                         memcpy(Pico.vsram, (char *)bg_buffer + 0x10080, 0x40*2);
1068                         memcpy(&Pico.video,(char *)bg_buffer + 0x10100, 0x40);
1069                 }
1070                 else
1071                         lprintf("uncompress returned %i\n", ret);
1072         }
1073
1074         memset32_uncached(psp_screen, 0, 512*272*2/4);
1075         emu_forcedFrame();
1076         menu_prepare_bg(1, 0);
1077
1078         if (oldstate) restore_oldstate(oldstate);
1079 }
1080
1081 static void draw_dispmenu_options(int menu_sel)
1082 {
1083         int tl_x = 80, tl_y = 16+50;
1084
1085         menu_draw_begin();
1086
1087         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 316);
1088
1089         me_draw(opt3_entries, OPT3_ENTRY_COUNT, tl_x, tl_y, menu_opt3_cust_draw, NULL);
1090
1091         menu_draw_end();
1092 }
1093
1094 static void dispmenu_loop_options(void)
1095 {
1096         static int menu_sel = 0;
1097         int menu_sel_max, is_32col = (Pico.video.reg[12]&1)^1;
1098         unsigned long inp = 0;
1099         menu_id selected_id;
1100
1101         menu_sel_max = me_count_enabled(opt3_entries, OPT3_ENTRY_COUNT) - 1;
1102
1103         for (;;)
1104         {
1105                 draw_dispmenu_options(menu_sel);
1106                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1107                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1108                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1109                 selected_id = me_index2id(opt3_entries, OPT3_ENTRY_COUNT, menu_sel);
1110                 if (selected_id == MA_OPT3_HSCALE40 &&  is_32col) { is_32col = 0; menu_opt3_preview(is_32col); }
1111                 if (selected_id == MA_OPT3_HSCALE32 && !is_32col) { is_32col = 1; menu_opt3_preview(is_32col); }
1112
1113                 if (inp & (BTN_LEFT|BTN_RIGHT)) // multi choise
1114                 {
1115                         float *setting = NULL;
1116                         int tmp;
1117                         me_process(opt3_entries, OPT3_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0);
1118                         switch (selected_id) {
1119                                 case MA_OPT3_SCALE:     setting = &currentConfig.scale; break;
1120                                 case MA_OPT3_HSCALE40:  setting = &currentConfig.hscale40; is_32col = 0; break;
1121                                 case MA_OPT3_HSCALE32:  setting = &currentConfig.hscale32; is_32col = 1; break;
1122                                 case MA_OPT3_FILTERING:
1123                                 case MA_OPT3_GAMMAA:    menu_opt3_preview(is_32col); break;
1124                                 case MA_OPT3_VSYNC:    tmp = ((currentConfig.EmuOpt>>13)&1) | ((currentConfig.EmuOpt>>15)&2);
1125                                         tmp = (inp & BTN_LEFT) ? (tmp>>1) : ((tmp<<1)|1);
1126                                         if (tmp > 3) tmp = 3;
1127                                         currentConfig.EmuOpt &= ~0x12000;
1128                                         currentConfig.EmuOpt |= ((tmp&2)<<15) | ((tmp&1)<<13);
1129                                         break;
1130                                 default: break;
1131                         }
1132                         if (setting != NULL) {
1133                                 while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1134                                         *setting += (inp & BTN_LEFT) ? -0.01 : 0.01;
1135                                         if (*setting <= 0) *setting = 0.01;
1136                                         menu_opt3_preview(is_32col);
1137                                         draw_dispmenu_options(menu_sel); // will wait vsync
1138                                 }
1139                         }
1140                 }
1141                 if (inp & BTN_CIRCLE) { // toggleable options
1142                         me_process(opt3_entries, OPT3_ENTRY_COUNT, selected_id, 1);
1143                         switch (selected_id) {
1144                                 case MA_OPT3_DONE:
1145                                         return;
1146                                 case MA_OPT3_PRES_NOSCALE:
1147                                         currentConfig.scale = currentConfig.hscale40 = currentConfig.hscale32 = 1.0;
1148                                         menu_opt3_preview(is_32col);
1149                                         break;
1150                                 case MA_OPT3_PRES_SCALE43:
1151                                         currentConfig.scale = 1.20;
1152                                         currentConfig.hscale40 = 1.00;
1153                                         currentConfig.hscale32 = 1.25;
1154                                         menu_opt3_preview(is_32col);
1155                                         break;
1156                                 case MA_OPT3_PRES_FULLSCR:
1157                                         currentConfig.scale = 1.20;
1158                                         currentConfig.hscale40 = 1.25;
1159                                         currentConfig.hscale32 = 1.56;
1160                                         menu_opt3_preview(is_32col);
1161                                         break;
1162                                 case MA_OPT3_FILTERING:
1163                                         menu_opt3_preview(is_32col);
1164                                         break;
1165                                 default: break;
1166                         }
1167                 }
1168                 if (inp & BTN_X) return;
1169         }
1170 }
1171
1172
1173 // --------- advanced options ----------
1174
1175 menu_entry opt2_entries[] =
1176 {
1177         { "Emulate Z80",               MB_ONOFF, MA_OPT2_ENABLE_Z80,     &currentConfig.PicoOpt,0x00004, 0, 0, 1 },
1178         { "Emulate YM2612 (FM)",       MB_ONOFF, MA_OPT2_ENABLE_YM2612,  &currentConfig.PicoOpt,0x00001, 0, 0, 1 },
1179         { "Emulate SN76496 (PSG)",     MB_ONOFF, MA_OPT2_ENABLE_SN76496, &currentConfig.PicoOpt,0x00002, 0, 0, 1 },
1180         { "gzip savestates",           MB_ONOFF, MA_OPT2_GZIP_STATES,    &currentConfig.EmuOpt, 0x00008, 0, 0, 1 },
1181         { "Don't save last used ROM",  MB_ONOFF, MA_OPT2_NO_LAST_ROM,    &currentConfig.EmuOpt, 0x00020, 0, 0, 1 },
1182         { "Status line in main menu",  MB_ONOFF, MA_OPT2_STATUS_LINE,    &currentConfig.EmuOpt, 0x20000, 0, 0, 1 },
1183         { "Disable frame limitter",    MB_ONOFF, MA_OPT2_NO_FRAME_LIMIT, &currentConfig.EmuOpt, 0x40000, 0, 0, 1 },
1184         { "done",                      MB_NONE,  MA_OPT2_DONE,           NULL, 0, 0, 0, 1 },
1185 };
1186
1187 #define OPT2_ENTRY_COUNT (sizeof(opt2_entries) / sizeof(opt2_entries[0]))
1188
1189
1190 static void draw_amenu_options(int menu_sel)
1191 {
1192         int tl_x = 80+25, tl_y = 16+50;
1193
1194         menu_draw_begin();
1195
1196         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 252);
1197
1198         me_draw(opt2_entries, OPT2_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1199
1200         menu_draw_end();
1201 }
1202
1203 static void amenu_loop_options(void)
1204 {
1205         static int menu_sel = 0;
1206         int menu_sel_max;
1207         unsigned long inp = 0;
1208         menu_id selected_id;
1209
1210         menu_sel_max = me_count_enabled(opt2_entries, OPT2_ENTRY_COUNT) - 1;
1211
1212         for(;;)
1213         {
1214                 draw_amenu_options(menu_sel);
1215                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1216                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1217                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1218                 selected_id = me_index2id(opt2_entries, OPT2_ENTRY_COUNT, menu_sel);
1219                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1220                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
1221                             selected_id == MA_OPT2_GAMMA) {
1222                                 // TODO?
1223                         }
1224                 }
1225                 if (inp & BTN_CIRCLE) { // toggleable options
1226                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, 1) &&
1227                             selected_id == MA_OPT2_DONE) {
1228                                 return;
1229                         }
1230                 }
1231                 if (inp & BTN_X) return;
1232         }
1233 }
1234
1235 // -------------- options --------------
1236
1237
1238 menu_entry opt_entries[] =
1239 {
1240         { NULL,                        MB_NONE,  MA_OPT_RENDERER,      NULL, 0, 0, 0, 1 },
1241         { "Accurate timing (slower)",  MB_ONOFF, MA_OPT_ACC_TIMING,    &currentConfig.PicoOpt, 0x0040, 0, 0, 1 },
1242         { "Accurate sprites (slower)", MB_ONOFF, MA_OPT_ACC_SPRITES,   &currentConfig.PicoOpt, 0x0080, 0, 0, 1 },
1243         { "Show FPS",                  MB_ONOFF, MA_OPT_SHOW_FPS,      &currentConfig.EmuOpt,  0x0002, 0, 0, 1 },
1244         { NULL,                        MB_RANGE, MA_OPT_FRAMESKIP,     &currentConfig.Frameskip, 0, -1, 16, 1 },
1245         { "Enable sound",              MB_ONOFF, MA_OPT_ENABLE_SOUND,  &currentConfig.EmuOpt,  0x0004, 0, 0, 1 },
1246         { NULL,                        MB_NONE,  MA_OPT_SOUND_QUALITY, NULL, 0, 0, 0, 1 },
1247         { "6 button pad",              MB_ONOFF, MA_OPT_6BUTTON_PAD,   &currentConfig.PicoOpt, 0x0020, 0, 0, 1 },
1248         { NULL,                        MB_NONE,  MA_OPT_REGION,        NULL, 0, 0, 0, 1 },
1249         { "Use SRAM/BRAM savestates",  MB_ONOFF, MA_OPT_SRAM_STATES,   &currentConfig.EmuOpt,  0x0001, 0, 0, 1 },
1250         { NULL,                        MB_NONE,  MA_OPT_CONFIRM_STATES,NULL, 0, 0, 0, 1 },
1251         { "Save slot",                 MB_RANGE, MA_OPT_SAVE_SLOT,     &state_slot, 0, 0, 9, 1 },
1252         { NULL,                        MB_NONE,  MA_OPT_CPU_CLOCKS,    NULL, 0, 0, 0, 1 },
1253         { "[Display options]",         MB_NONE,  MA_OPT_DISP_OPTS,     NULL, 0, 0, 0, 1 },
1254         { "[Sega/Mega CD options]",    MB_NONE,  MA_OPT_SCD_OPTS,      NULL, 0, 0, 0, 1 },
1255         { "[Advanced options]",        MB_NONE,  MA_OPT_ADV_OPTS,      NULL, 0, 0, 0, 1 },
1256         { NULL,                        MB_NONE,  MA_OPT_SAVECFG,       NULL, 0, 0, 0, 1 },
1257         { "Save cfg for current game only",MB_NONE,MA_OPT_SAVECFG_GAME,NULL, 0, 0, 0, 1 },
1258         { NULL,                        MB_NONE,  MA_OPT_LOADCFG,       NULL, 0, 0, 0, 1 },
1259 };
1260
1261 #define OPT_ENTRY_COUNT (sizeof(opt_entries) / sizeof(opt_entries[0]))
1262
1263
1264 static const char *region_name(unsigned int code)
1265 {
1266         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
1267         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
1268         int u, i = 0;
1269         if (code) {
1270                 code <<= 1;
1271                 while((code >>= 1)) i++;
1272                 if (i > 4) return "unknown";
1273                 return names[i];
1274         } else {
1275                 static char name[24];
1276                 strcpy(name, "Auto:");
1277                 for (u = 0; u < 3; u++) {
1278                         i = 0; code = ((PicoAutoRgnOrder >> u*4) & 0xf) << 1;
1279                         while((code >>= 1)) i++;
1280                         strcat(name, names_short[i]);
1281                 }
1282                 return name;
1283         }
1284 }
1285
1286
1287 static void menu_opt_cust_draw(const menu_entry *entry, int x, int y, void *param)
1288 {
1289         char *str, str24[24];
1290
1291         switch (entry->id)
1292         {
1293                 case MA_OPT_RENDERER:
1294                         if (currentConfig.PicoOpt&0x10)
1295                                 str = "fast";
1296                         else if (currentConfig.EmuOpt&0x80)
1297                                 str = "accurate";
1298                         else
1299                                 str = " 8bit accurate"; // n/a
1300                         text_out16(x, y, "Renderer:                  %s", str);
1301                         break;
1302                 case MA_OPT_FRAMESKIP:
1303                         if (currentConfig.Frameskip < 0)
1304                              strcpy(str24, "Auto");
1305                         else sprintf(str24, "%i", currentConfig.Frameskip);
1306                         text_out16(x, y, "Frameskip                  %s", str24);
1307                         break;
1308                 case MA_OPT_SOUND_QUALITY:
1309                         str = (currentConfig.PicoOpt&0x08)?"stereo":"mono";
1310                         text_out16(x, y, "Sound Quality:     %5iHz %s", currentConfig.PsndRate, str);
1311                         break;
1312                 case MA_OPT_REGION:
1313                         text_out16(x, y, "Region:              %s", region_name(currentConfig.PicoRegion));
1314                         break;
1315                 case MA_OPT_CONFIRM_STATES:
1316                         switch ((currentConfig.EmuOpt >> 9) & 5) {
1317                                 default: str = "OFF";    break;
1318                                 case 1:  str = "writes"; break;
1319                                 case 4:  str = "loads";  break;
1320                                 case 5:  str = "both";   break;
1321                         }
1322                         text_out16(x, y, "Confirm savestate          %s", str);
1323                         break;
1324                 case MA_OPT_CPU_CLOCKS:
1325                         text_out16(x, y, "CPU/bus clock       %3i/%3iMHz", currentConfig.CPUclock, currentConfig.CPUclock/2);
1326                         break;
1327                 case MA_OPT_SAVECFG:
1328                         str24[0] = 0;
1329                         if (config_slot != 0) sprintf(str24, " (profile: %i)", config_slot);
1330                         text_out16(x, y, "Save cfg as default%s", str24);
1331                         break;
1332                 case MA_OPT_LOADCFG:
1333                         text_out16(x, y, "Load cfg from profile %i", config_slot);
1334                         break;
1335                 default:
1336                         lprintf("%s: unimplemented (%i)\n", __FUNCTION__, entry->id);
1337                         break;
1338         }
1339 }
1340
1341
1342 static void draw_menu_options(int menu_sel)
1343 {
1344         int tl_x = 80+25, tl_y = 16+24;
1345
1346         menu_draw_begin();
1347
1348         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 284);
1349
1350         me_draw(opt_entries, OPT_ENTRY_COUNT, tl_x, tl_y, menu_opt_cust_draw, NULL);
1351
1352         menu_draw_end();
1353 }
1354
1355 static int sndrate_prevnext(int rate, int dir)
1356 {
1357         int i, rates[] = { 11025, 22050, 44100 };
1358
1359         for (i = 0; i < 5; i++)
1360                 if (rates[i] == rate) break;
1361
1362         i += dir ? 1 : -1;
1363         if (i > 2) return dir ? 44100 : 22050;
1364         if (i < 0) return dir ? 22050 : 11025;
1365         return rates[i];
1366 }
1367
1368 static void region_prevnext(int right)
1369 {
1370         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
1371         static int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
1372         int i;
1373         if (right) {
1374                 if (!currentConfig.PicoRegion) {
1375                         for (i = 0; i < 6; i++)
1376                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1377                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
1378                         else currentConfig.PicoRegion=1;
1379                 }
1380                 else currentConfig.PicoRegion<<=1;
1381                 if (currentConfig.PicoRegion > 8) currentConfig.PicoRegion = 8;
1382         } else {
1383                 if (!currentConfig.PicoRegion) {
1384                         for (i = 0; i < 6; i++)
1385                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1386                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
1387                 }
1388                 else currentConfig.PicoRegion>>=1;
1389         }
1390 }
1391
1392 static void menu_options_save(void)
1393 {
1394         PicoOpt = currentConfig.PicoOpt;
1395         PsndRate = currentConfig.PsndRate;
1396         PicoRegionOverride = currentConfig.PicoRegion;
1397         if (!(PicoOpt & 0x20)) {
1398                 // unbind XYZ MODE, just in case
1399                 unbind_action(0xf00);
1400         }
1401 }
1402
1403 static int menu_loop_options(void)
1404 {
1405         static int menu_sel = 0;
1406         int menu_sel_max, ret;
1407         unsigned long inp = 0;
1408         menu_id selected_id;
1409
1410         currentConfig.PicoOpt = PicoOpt;
1411         currentConfig.PsndRate = PsndRate;
1412         currentConfig.PicoRegion = PicoRegionOverride;
1413
1414         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_SAVECFG_GAME, rom_data != NULL);
1415         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1416         menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1417         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1418
1419         while (1)
1420         {
1421                 draw_menu_options(menu_sel);
1422                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1423                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1424                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1425                 selected_id = me_index2id(opt_entries, OPT_ENTRY_COUNT, menu_sel);
1426                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1427                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0)) {
1428                                 switch (selected_id) {
1429                                         case MA_OPT_RENDERER:
1430                                                 if ((currentConfig.PicoOpt&0x10) || !(currentConfig.EmuOpt &0x80)) {
1431                                                         currentConfig.PicoOpt&= ~0x10;
1432                                                         currentConfig.EmuOpt |=  0x80;
1433                                                 } else {
1434                                                         currentConfig.PicoOpt|=  0x10;
1435                                                         currentConfig.EmuOpt &= ~0x80;
1436                                                 }
1437                                                 break;
1438                                         case MA_OPT_SOUND_QUALITY:
1439                                                 currentConfig.PsndRate = sndrate_prevnext(currentConfig.PsndRate, inp & BTN_RIGHT);
1440                                                 break;
1441                                         case MA_OPT_REGION:
1442                                                 region_prevnext(inp & BTN_RIGHT);
1443                                                 break;
1444                                         case MA_OPT_CONFIRM_STATES: {
1445                                                          int n = ((currentConfig.EmuOpt>>9)&1) | ((currentConfig.EmuOpt>>10)&2);
1446                                                          n += (inp & BTN_LEFT) ? -1 : 1;
1447                                                          if (n < 0) n = 0; else if (n > 3) n = 3;
1448                                                          n |= n << 1; n &= ~2;
1449                                                          currentConfig.EmuOpt &= ~0xa00;
1450                                                          currentConfig.EmuOpt |= n << 9;
1451                                                          break;
1452                                                  }
1453                                         case MA_OPT_SAVE_SLOT:
1454                                                  if (inp & BTN_RIGHT) {
1455                                                          state_slot++; if (state_slot > 9) state_slot = 0;
1456                                                  } else {state_slot--; if (state_slot < 0) state_slot = 9;
1457                                                  }
1458                                                  break;
1459                                         case MA_OPT_CPU_CLOCKS:
1460                                                  while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1461                                                          currentConfig.CPUclock += (inp & BTN_LEFT) ? -1 : 1;
1462                                                          if (currentConfig.CPUclock <  19) currentConfig.CPUclock = 19;
1463                                                          if (currentConfig.CPUclock > 333) currentConfig.CPUclock = 333;
1464                                                          draw_menu_options(menu_sel); // will wait vsync
1465                                                  }
1466                                                  break;
1467                                         case MA_OPT_SAVECFG:
1468                                         case MA_OPT_SAVECFG_GAME:
1469                                         case MA_OPT_LOADCFG:
1470                                                  config_slot += (inp&BTN_RIGHT) ? 1 : -1;
1471                                                  if (config_slot > 9) config_slot = 0;
1472                                                  if (config_slot < 0) config_slot = 9;
1473                                                  me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1474                                                  menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1475                                                  if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1476                                                  break;
1477                                         default:
1478                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1479                                                 break;
1480                                 }
1481                         }
1482                 }
1483                 if (inp & BTN_CIRCLE) {
1484                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, 1))
1485                         {
1486                                 switch (selected_id)
1487                                 {
1488                                         case MA_OPT_DISP_OPTS:
1489                                                 dispmenu_loop_options();
1490                                                 break;
1491                                         case MA_OPT_SCD_OPTS:
1492                                                 cd_menu_loop_options();
1493                                                 if (engineState == PGS_ReloadRom)
1494                                                         return 0; // test BIOS
1495                                                 break;
1496                                         case MA_OPT_ADV_OPTS:
1497                                                 amenu_loop_options();
1498                                                 break;
1499                                         case MA_OPT_SAVECFG: // done (update and write)
1500                                                 menu_options_save();
1501                                                 if (emu_WriteConfig(0)) strcpy(menuErrorMsg, "config saved");
1502                                                 else strcpy(menuErrorMsg, "failed to write config");
1503                                                 return 1;
1504                                         case MA_OPT_SAVECFG_GAME: // done (update and write for current game)
1505                                                 menu_options_save();
1506                                                 if (emu_WriteConfig(1)) strcpy(menuErrorMsg, "config saved");
1507                                                 else strcpy(menuErrorMsg, "failed to write config");
1508                                                 return 1;
1509                                         case MA_OPT_LOADCFG:
1510                                                 ret = emu_ReadConfig(1, 1);
1511                                                 if (!ret) ret = emu_ReadConfig(0, 1);
1512                                                 if (ret)  strcpy(menuErrorMsg, "config loaded");
1513                                                 else      strcpy(menuErrorMsg, "failed to load config");
1514                                                 return 1;
1515                                         default:
1516                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1517                                                 break;
1518                                 }
1519                         }
1520                 }
1521                 if(inp & BTN_X) {
1522                         menu_options_save();
1523                         return 0;  // done (update, no write)
1524                 }
1525         }
1526 }
1527
1528 // -------------- credits --------------
1529
1530 static void draw_menu_credits(void)
1531 {
1532         int tl_x = 80+15, tl_y = 16+64, y;
1533         menu_draw_begin();
1534
1535         text_out16(tl_x, 16+20, "PicoDrive v" VERSION " (c) notaz, 2006,2007");
1536
1537         y = tl_y;
1538         text_out16(tl_x, y, "Credits:");
1539         text_out16(tl_x, (y+=10), "fDave: base code of PicoDrive");
1540         text_out16(tl_x, (y+=10), "Chui: Fame/C");
1541         text_out16(tl_x, (y+=10), "NJ: CZ80");
1542         text_out16(tl_x, (y+=10), "MAME devs: YM2612 and SN76496 cores");
1543         text_out16(tl_x, (y+=10), "Stephane Dallongeville:");
1544         text_out16(tl_x, (y+=10), "    Gens code, base of Fame/C, CZ80");
1545         text_out16(tl_x, (y+=10), "Charles MacDonald: Genesis hw docs");
1546         text_out16(tl_x, (y+=10), "Haze: Genesis hw info");
1547         text_out16(tl_x, (y+=10), "ps2dev.org people: PSP SDK/code");
1548         text_out16(tl_x, (y+=10), "ketchupgun: skin design");
1549
1550         menu_draw_end();
1551 }
1552
1553
1554 // -------------- root menu --------------
1555
1556 menu_entry main_entries[] =
1557 {
1558         { "Resume game",        MB_NONE, MA_MAIN_RESUME_GAME, NULL, 0, 0, 0, 0 },
1559         { "Save State",         MB_NONE, MA_MAIN_SAVE_STATE,  NULL, 0, 0, 0, 0 },
1560         { "Load State",         MB_NONE, MA_MAIN_LOAD_STATE,  NULL, 0, 0, 0, 0 },
1561         { "Reset game",         MB_NONE, MA_MAIN_RESET_GAME,  NULL, 0, 0, 0, 0 },
1562         { "Load new ROM/ISO",   MB_NONE, MA_MAIN_LOAD_ROM,    NULL, 0, 0, 0, 1 },
1563         { "Change options",     MB_NONE, MA_MAIN_OPTIONS,     NULL, 0, 0, 0, 1 },
1564         { "Configure controls", MB_NONE, MA_MAIN_CONTROLS,    NULL, 0, 0, 0, 1 },
1565         { "Credits",            MB_NONE, MA_MAIN_CREDITS,     NULL, 0, 0, 0, 1 },
1566         { "Patches / GameGenie",MB_NONE, MA_MAIN_PATCHES,     NULL, 0, 0, 0, 0 },
1567         { "Exit",               MB_NONE, MA_MAIN_EXIT,        NULL, 0, 0, 0, 1 }
1568 };
1569
1570 #define MAIN_ENTRY_COUNT (sizeof(main_entries) / sizeof(main_entries[0]))
1571
1572 static void draw_menu_root(int menu_sel)
1573 {
1574         const int tl_x = 86+70, tl_y = 16+70;
1575         char *stat = NULL;
1576
1577         menu_draw_begin();
1578
1579         if ((currentConfig.EmuOpt&0x20000) && (stat = psp_get_status_line()))
1580                 text_out16(287, 12, "%s", stat);
1581
1582         text_out16(tl_x, 48, "PicoDrive v" VERSION);
1583
1584         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 146);
1585
1586         me_draw(main_entries, MAIN_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1587
1588         // error
1589         if (menuErrorMsg[0])
1590                 text_out16(10, 252, menuErrorMsg);
1591         menu_draw_end();
1592 }
1593
1594
1595 static void menu_loop_root(void)
1596 {
1597         static int menu_sel = 0;
1598         int ret, menu_sel_max;
1599         unsigned long inp = 0;
1600
1601         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESUME_GAME, rom_data != NULL);
1602         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_SAVE_STATE,  rom_data != NULL);
1603         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_LOAD_STATE,  rom_data != NULL);
1604         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESET_GAME,  rom_data != NULL);
1605         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_PATCHES,     PicoPatches != NULL);
1606
1607         menu_sel_max = me_count_enabled(main_entries, MAIN_ENTRY_COUNT) - 1;
1608         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1609
1610         // mp3 errors?
1611         if (mp3_last_error != 0) {
1612                 if (mp3_last_error == -1)
1613                      sprintf(menuErrorMsg, "Unsupported mp3 format, use 44kHz stereo");
1614                 else sprintf(menuErrorMsg, "mp3 init failed, code %08x", mp3_last_error);
1615                 mp3_last_error = 0;
1616         }
1617
1618         /* make sure action buttons are not pressed on entering menu */
1619         draw_menu_root(menu_sel);
1620
1621         while (psp_pad_read(1) & (BTN_X|BTN_CIRCLE|BTN_SELECT)) psp_msleep(50);
1622
1623         for (;;)
1624         {
1625                 draw_menu_root(menu_sel);
1626                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE|BTN_SELECT|BTN_L|BTN_R, 0);
1627                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1628                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1629                 if((inp & (BTN_L|BTN_R)) == (BTN_L|BTN_R)) debug_menu_loop();
1630                 if( inp & (BTN_SELECT|BTN_X)) {
1631                         if (rom_data) {
1632                                 while (psp_pad_read(1) & (BTN_SELECT|BTN_X)) psp_msleep(50); // wait until released
1633                                 engineState = PGS_Running;
1634                                 break;
1635                         }
1636                 }
1637                 if(inp & BTN_CIRCLE)  {
1638                         menuErrorMsg[0] = 0; // clear error msg
1639                         switch (me_index2id(main_entries, MAIN_ENTRY_COUNT, menu_sel))
1640                         {
1641                                 case MA_MAIN_RESUME_GAME:
1642                                         if (rom_data) {
1643                                                 while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1644                                                 engineState = PGS_Running;
1645                                                 return;
1646                                         }
1647                                         break;
1648                                 case MA_MAIN_SAVE_STATE:
1649                                         if (rom_data) {
1650                                                 if(savestate_menu_loop(0))
1651                                                         continue;
1652                                                 engineState = PGS_Running;
1653                                                 return;
1654                                         }
1655                                         break;
1656                                 case MA_MAIN_LOAD_STATE:
1657                                         if (rom_data) {
1658                                                 if(savestate_menu_loop(1))
1659                                                         continue;
1660                                                 engineState = PGS_Running;
1661                                                 return;
1662                                         }
1663                                         break;
1664                                 case MA_MAIN_RESET_GAME:
1665                                         if (rom_data) {
1666                                                 emu_ResetGame();
1667                                                 engineState = PGS_Running;
1668                                                 return;
1669                                         }
1670                                         break;
1671                                 case MA_MAIN_LOAD_ROM:
1672                                 {
1673                                         char curr_path[PATH_MAX], *selfname;
1674                                         FILE *tstf;
1675                                         if ( (tstf = fopen(currentConfig.lastRomFile, "rb")) )
1676                                         {
1677                                                 fclose(tstf);
1678                                                 strcpy(curr_path, currentConfig.lastRomFile);
1679                                         }
1680                                         else
1681                                                 getcwd(curr_path, PATH_MAX);
1682                                         selfname = romsel_loop(curr_path);
1683                                         if (selfname) {
1684                                                 lprintf("selected file: %s\n", selfname);
1685                                                 engineState = PGS_ReloadRom;
1686                                                 return;
1687                                         }
1688                                         break;
1689                                 }
1690                                 case MA_MAIN_OPTIONS:
1691                                         ret = menu_loop_options();
1692                                         if (ret == 1) continue; // status update
1693                                         if (engineState == PGS_ReloadRom)
1694                                                 return; // BIOS test
1695                                         break;
1696                                 case MA_MAIN_CONTROLS:
1697                                         kc_sel_loop();
1698                                         break;
1699                                 case MA_MAIN_CREDITS:
1700                                         draw_menu_credits();
1701                                         psp_msleep(500);
1702                                         inp = 0;
1703                                         while (!(inp & (BTN_X|BTN_CIRCLE)))
1704                                                 inp = wait_for_input(BTN_X|BTN_CIRCLE, 0);
1705                                         break;
1706                                 case MA_MAIN_EXIT:
1707                                         engineState = PGS_Quit;
1708                                         return;
1709                                 case MA_MAIN_PATCHES:
1710                                         if (rom_data && PicoPatches) {
1711                                                 patches_menu_loop();
1712                                                 PicoPatchApply();
1713                                                 strcpy(menuErrorMsg, "Patches applied");
1714                                                 continue;
1715                                         }
1716                                         break;
1717                                 default:
1718                                         lprintf("%s: something unknown selected\n", __FUNCTION__);
1719                                         break;
1720                         }
1721                 }
1722         }
1723 }
1724
1725 // warning: alignment
1726 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker)
1727 {
1728         unsigned int *dest = dst;
1729         const unsigned int *srce = src;
1730         pixels /= 2;
1731         if (darker)
1732         {
1733                 while (pixels--)
1734                 {
1735                         unsigned int p = *srce++;
1736                         *dest++ = ((p&0xf79ef79e)>>1) - ((p&0xc618c618)>>3);
1737                 }
1738         }
1739         else
1740         {
1741                 while (pixels--)
1742                 {
1743                         unsigned int p = *srce++;
1744                         *dest++ = (p&0xf79ef79e)>>1;
1745                 }
1746         }
1747 }
1748
1749 static void menu_prepare_bg(int use_game_bg, int use_fg)
1750 {
1751         if (use_game_bg)
1752         {
1753                 // darken the active framebuffer
1754                 unsigned short *dst = bg_buffer;
1755                 unsigned short *src = use_fg ? psp_video_get_active_fb() : psp_screen;
1756                 int i;
1757                 for (i = 272; i > 0; i--, dst += 480, src += 512)
1758                         menu_darken_bg(dst, src, 480, 1);
1759                 //memset32_uncached((int *)(bg_buffer + 480*264), 0, 480*8*2/4);
1760         }
1761         else
1762         {
1763                 // should really only happen once, on startup..
1764                 memset32_uncached((int *)(void *)bg_buffer, 0, sizeof(bg_buffer)/4);
1765                 readpng(bg_buffer, "skin/background.png", READPNG_BG);
1766         }
1767         sceKernelDcacheWritebackAll();
1768 }
1769
1770 static void menu_gfx_prepare(void)
1771 {
1772         menu_prepare_bg(rom_data != NULL, 1);
1773
1774         menu_draw_begin();
1775         menu_draw_end();
1776 }
1777
1778
1779 void menu_loop(void)
1780 {
1781         menu_gfx_prepare();
1782
1783         menu_loop_root();
1784
1785         menuErrorMsg[0] = 0;
1786 }
1787
1788
1789 // --------- CD tray close menu ----------
1790
1791 static void draw_menu_tray(int menu_sel)
1792 {
1793         int tl_x = 70, tl_y = 90, y;
1794
1795         menu_draw_begin();
1796
1797         text_out16(tl_x, 20, "The unit is about to");
1798         text_out16(tl_x, 30, "close the CD tray.");
1799
1800         y = tl_y;
1801         text_out16(tl_x, y,       "Load new CD image");
1802         text_out16(tl_x, (y+=10), "Insert nothing");
1803
1804         // draw cursor
1805         text_out16(tl_x - 16, tl_y + menu_sel*10, ">");
1806         // error
1807         if (menuErrorMsg[0]) text_out16(5, 226, menuErrorMsg);
1808         menu_draw_end();
1809 }
1810
1811
1812 int menu_loop_tray(void)
1813 {
1814         int menu_sel = 0, menu_sel_max = 1;
1815         unsigned long inp = 0;
1816         char curr_path[PATH_MAX], *selfname;
1817         FILE *tstf;
1818
1819         menu_gfx_prepare();
1820
1821         if ( (tstf = fopen(currentConfig.lastRomFile, "rb")) )
1822         {
1823                 fclose(tstf);
1824                 strcpy(curr_path, currentConfig.lastRomFile);
1825         }
1826         else
1827         {
1828                 getcwd(curr_path, PATH_MAX);
1829         }
1830
1831         /* make sure action buttons are not pressed on entering menu */
1832         draw_menu_tray(menu_sel);
1833         while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1834
1835         for (;;)
1836         {
1837                 draw_menu_tray(menu_sel);
1838                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_CIRCLE, 0);
1839                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1840                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1841                 if(inp & BTN_CIRCLE)  {
1842                         switch (menu_sel) {
1843                                 case 0: // select image
1844                                         selfname = romsel_loop(curr_path);
1845                                         if (selfname) {
1846                                                 int ret = -1, cd_type;
1847                                                 cd_type = emu_cdCheck(NULL);
1848                                                 if (cd_type > 0)
1849                                                         ret = Insert_CD(romFileName, cd_type == 2);
1850                                                 if (ret != 0) {
1851                                                         sprintf(menuErrorMsg, "Load failed, invalid CD image?");
1852                                                         lprintf("%s\n", menuErrorMsg);
1853                                                         continue;
1854                                                 }
1855                                                 engineState = PGS_RestartRun;
1856                                                 return 1;
1857                                         }
1858                                         break;
1859                                 case 1: // insert nothing
1860                                         engineState = PGS_RestartRun;
1861                                         return 0;
1862                         }
1863                 }
1864                 menuErrorMsg[0] = 0; // clear error msg
1865         }
1866 }
1867
1868