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