bugfixes, but silpheed is broken
[libpicofe.git] / gp2x / emu.c
1 // (c) Copyright 2006 notaz, All rights reserved.\r
2 // Free for non-commercial use.\r
3 \r
4 // For commercial use, separate licencing terms must be obtained.\r
5 \r
6 #include <stdio.h>\r
7 #include <stdlib.h>\r
8 #include <sys/time.h>\r
9 #include <sys/stat.h>\r
10 #include <sys/types.h>\r
11 #include <linux/limits.h>\r
12 #include <ctype.h>\r
13 #include <unistd.h>\r
14 \r
15 #include <stdarg.h>\r
16 \r
17 #include "emu.h"\r
18 #include "gp2x.h"\r
19 #include "usbjoy.h"\r
20 #include "menu.h"\r
21 #include "asmutils.h"\r
22 #include "cpuctrl.h"\r
23 \r
24 #include <Pico/PicoInt.h>\r
25 #include <Pico/Patch.h>\r
26 #include <zlib/zlib.h>\r
27 \r
28 \r
29 #ifdef BENCHMARK\r
30 #define OSD_FPS_X 220\r
31 #else\r
32 #define OSD_FPS_X 260\r
33 #endif\r
34 \r
35 // PicoPad[] format: SACB RLDU\r
36 char *actionNames[] = {\r
37         "UP", "DOWN", "LEFT", "RIGHT", "B", "C", "A", "START",\r
38         0, 0, 0, 0, 0, 0, 0, 0, // Z, Y, X, MODE (enabled only when needed), ?, ?, ?, ?\r
39         0, 0, 0, 0, 0, 0, 0, "ENTER MENU", // player2_flag, ?, ?, ?, ?, ?, ?, menu\r
40         "NEXT SAVE SLOT", "PREV SAVE SLOT", "SWITCH RENDERER", "SAVE STATE",\r
41         "LOAD STATE", "VOLUME UP", "VOLUME DOWN", "DONE"\r
42 };\r
43 \r
44 int engineState;\r
45 int select_exits = 0;\r
46 char *PicoConfigFile = "picoconfig.bin";\r
47 currentConfig_t currentConfig;\r
48 \r
49 char romFileName[PATH_MAX];\r
50 unsigned char *rom_data = NULL;\r
51 \r
52 extern int crashed_940;\r
53 \r
54 static short sndBuffer[2*44100/50];\r
55 static char noticeMsg[64];                                      // notice msg to draw\r
56 static struct timeval noticeMsgTime = { 0, 0 }; // when started showing\r
57 static int reset_timing, osd_fps_x;\r
58 static int combo_keys = 0, combo_acts = 0;      // keys and actions which need button combos\r
59 static int gp2x_old_gamma = 100;\r
60 static unsigned char *movie_data = NULL;\r
61 static int movie_size = 0;\r
62 unsigned char *framebuff = 0;  // temporary buffer for alt renderer\r
63 int state_slot = 0;\r
64 \r
65 /*\r
66 // tmp\r
67 static FILE *logf = NULL;\r
68 \r
69 void pprintf(char *texto, ...)\r
70 {\r
71         va_list args;\r
72 \r
73         va_start(args,texto);\r
74         vfprintf(logf,texto,args);\r
75         va_end(args);\r
76         fflush(logf);\r
77         sync();\r
78 }\r
79 */\r
80 // utilities\r
81 static void strlwr(char* string)\r
82 {\r
83         while ( (*string++ = (char)tolower(*string)) );\r
84 }\r
85 \r
86 static int try_rfn_cut(void)\r
87 {\r
88         FILE *tmp;\r
89         char *p;\r
90 \r
91         p = romFileName + strlen(romFileName) - 1;\r
92         for (; p > romFileName; p--)\r
93                 if (*p == '.') break;\r
94         *p = 0;\r
95 \r
96         if((tmp = fopen(romFileName, "rb"))) {\r
97                 fclose(tmp);\r
98                 return 1;\r
99         }\r
100         return 0;\r
101 }\r
102 \r
103 static void get_ext(char *file, char *ext)\r
104 {\r
105         char *p;\r
106 \r
107         p = file + strlen(file) - 4;\r
108         if (p < file) p = file;\r
109         strncpy(ext, p, 4);\r
110         ext[4] = 0;\r
111         strlwr(ext);\r
112 }\r
113 \r
114 char *biosfiles_us[] = { "us_scd2_9306", "SegaCDBIOS9303", "us_scd1_9210" };\r
115 char *biosfiles_eu[] = { "eu_mcd2_9306", "eu_mcd2_9303",   "eu_mcd1_9210" };\r
116 char *biosfiles_jp[] = { "jp_mcd1_9112", "jp_mcd1_9111" };\r
117 \r
118 extern char **g_argv;\r
119 \r
120 int find_bios(int region, char **bios_file)\r
121 {\r
122         static char bios_path[1024];\r
123         int i, j, count;\r
124         char **files;\r
125         FILE *f = NULL;\r
126 \r
127         if (region == 4) { // US\r
128                 files = biosfiles_us;\r
129                 count = sizeof(biosfiles_us) / sizeof(char *);\r
130         } else if (region == 8) { // EU\r
131                 files = biosfiles_eu;\r
132                 count = sizeof(biosfiles_eu) / sizeof(char *);\r
133         } else if (region == 1 || region == 2) {\r
134                 files = biosfiles_jp;\r
135                 count = sizeof(biosfiles_jp) / sizeof(char *);\r
136         } else {\r
137                 return 0;\r
138         }\r
139 \r
140         for (i = 0; i < count; i++)\r
141         {\r
142                 strncpy(bios_path, g_argv[0], 1023);\r
143                 bios_path[1024-32] = 0;\r
144                 for (j = strlen(bios_path); j > 0; j--)\r
145                         if (bios_path[j] == '/') { bios_path[j+1] = 0; break; }\r
146                 strcat(bios_path, files[i]);\r
147                 strcat(bios_path, ".bin");\r
148                 f = fopen(bios_path, "rb");\r
149                 if (f) break;\r
150 \r
151                 bios_path[strlen(bios_path) - 4] = 0;\r
152                 strcat(bios_path, ".zip");\r
153                 f = fopen(bios_path, "rb");\r
154                 if (f) break;\r
155         }\r
156 \r
157         if (f) {\r
158                 printf("using bios: %s\n", bios_path);\r
159                 fclose(f);\r
160                 if (bios_file) *bios_file = bios_path;\r
161                 return 1;\r
162         } else {\r
163                 sprintf(menuErrorMsg, "no %s BIOS files found, read docs",\r
164                         region != 4 ? (region == 8 ? "EU" : "JAP") : "USA");\r
165                 printf("%s\n", menuErrorMsg);\r
166                 return 0;\r
167         }\r
168 }\r
169 \r
170 /* checks if romFileName points to valid MegaCD image\r
171  * if so, checks for suitable BIOS */\r
172 static int cd_check(char **bios_file)\r
173 {\r
174         unsigned char buf[32];\r
175         pm_file *cd_f;\r
176         int type = 0, region = 4; // 1: Japan, 4: US, 8: Europe\r
177 \r
178         cd_f = pm_open(romFileName);\r
179         if (!cd_f) return 0; // let the upper level handle this\r
180 \r
181         if (pm_read(buf, 32, cd_f) != 32) {\r
182                 pm_close(cd_f);\r
183                 return 0;\r
184         }\r
185 \r
186         if (!strncasecmp("SEGADISCSYSTEM", (char *)buf+0x00, 14)) type = 1;       // Sega CD (ISO)\r
187         if (!strncasecmp("SEGADISCSYSTEM", (char *)buf+0x10, 14)) type = 2;       // Sega CD (BIN)\r
188         if (type == 0) {\r
189                 pm_close(cd_f);\r
190                 return 0;\r
191         }\r
192 \r
193         /* it seems we have a CD image here. Try to detect region and load a suitable BIOS now.. */\r
194         pm_seek(cd_f, (type == 1) ? 0x100+0x10B : 0x110+0x10B, SEEK_SET);\r
195         pm_read(buf, 1, cd_f);\r
196         pm_close(cd_f);\r
197 \r
198         if (buf[0] == 0x64) region = 8; // EU\r
199         if (buf[0] == 0xa1) region = 1; // JAP\r
200 \r
201         printf("detected %s Sega/Mega CD image with %s region\n",\r
202                 type == 2 ? "BIN" : "ISO", region != 4 ? (region == 8 ? "EU" : "JAP") : "USA");\r
203 \r
204         if (PicoRegionOverride) {\r
205                 region = PicoRegionOverride;\r
206                 printf("overrided region to %s\n", region != 4 ? (region == 8 ? "EU" : "JAP") : "USA");\r
207         }\r
208 \r
209         if(find_bios(region, bios_file))\r
210                  return type;   // CD and BIOS detected\r
211 \r
212         return -1;              // CD detected but load failed\r
213 }\r
214 \r
215 int emu_ReloadRom(void)\r
216 {\r
217         unsigned int rom_size = 0;\r
218         char *used_rom_name = romFileName;\r
219         char ext[5];\r
220         pm_file *rom;\r
221         int ret, cd_state;\r
222 \r
223         printf("emu_ReloadRom(%s)\n", romFileName);\r
224 \r
225         get_ext(romFileName, ext);\r
226 \r
227         // detect wrong extensions\r
228         if(!strcmp(ext, ".srm") || !strcmp(ext, "s.gz") || !strcmp(ext, ".mds")) { // s.gz ~ .mds.gz\r
229                 sprintf(menuErrorMsg, "Not a ROM selected.");\r
230                 return 0;\r
231         }\r
232 \r
233         PicoPatchUnload();\r
234 \r
235         // check for movie file\r
236         if(movie_data) {\r
237                 free(movie_data);\r
238                 movie_data = 0;\r
239         }\r
240         if(!strcmp(ext, ".gmv")) {\r
241                 // check for both gmv and rom\r
242                 int dummy;\r
243                 FILE *movie_file = fopen(romFileName, "rb");\r
244                 if(!movie_file) {\r
245                         sprintf(menuErrorMsg, "Failed to open movie.");\r
246                         return 0;\r
247                 }\r
248                 fseek(movie_file, 0, SEEK_END);\r
249                 movie_size = ftell(movie_file);\r
250                 fseek(movie_file, 0, SEEK_SET);\r
251                 if(movie_size < 64+3) {\r
252                         sprintf(menuErrorMsg, "Invalid GMV file.");\r
253                         fclose(movie_file);\r
254                         return 0;\r
255                 }\r
256                 movie_data = malloc(movie_size);\r
257                 if(movie_data == NULL) {\r
258                         sprintf(menuErrorMsg, "low memory.");\r
259                         fclose(movie_file);\r
260                         return 0;\r
261                 }\r
262                 fread(movie_data, 1, movie_size, movie_file);\r
263                 fclose(movie_file);\r
264                 if (strncmp((char *)movie_data, "Gens Movie TEST", 15) != 0) {\r
265                         sprintf(menuErrorMsg, "Invalid GMV file.");\r
266                         return 0;\r
267                 }\r
268                 dummy = try_rfn_cut() || try_rfn_cut();\r
269                 if (!dummy) {\r
270                         sprintf(menuErrorMsg, "Could't find a ROM for movie.");\r
271                         return 0;\r
272                 }\r
273                 get_ext(romFileName, ext);\r
274         }\r
275         else if (!strcmp(ext, ".pat")) {\r
276                 int dummy;\r
277                 PicoPatchLoad(romFileName);\r
278                 dummy = try_rfn_cut() || try_rfn_cut();\r
279                 if (!dummy) {\r
280                         sprintf(menuErrorMsg, "Could't find a ROM to patch.");\r
281                         return 0;\r
282                 }\r
283                 get_ext(romFileName, ext);\r
284         }\r
285 \r
286         // check for MegaCD image\r
287         cd_state = cd_check(&used_rom_name);\r
288         if (cd_state > 0) {\r
289                 PicoMCD |= 1;\r
290                 get_ext(used_rom_name, ext);\r
291         } else if (cd_state == -1) {\r
292                 // bios_help() ?\r
293                 return 0;\r
294         } else {\r
295                 if (PicoMCD & 1) PicoExitMCD();\r
296                 PicoMCD &= ~1;\r
297         }\r
298 \r
299         rom = pm_open(used_rom_name);\r
300         if(!rom) {\r
301                 sprintf(menuErrorMsg, "Failed to open rom.");\r
302                 return 0;\r
303         }\r
304 \r
305         if(rom_data) {\r
306                 free(rom_data);\r
307                 rom_data = 0;\r
308                 rom_size = 0;\r
309         }\r
310 \r
311         if( (ret = PicoCartLoad(rom, &rom_data, &rom_size)) ) {\r
312                 sprintf(menuErrorMsg, "PicoCartLoad() failed.");\r
313                 printf("%s\n", menuErrorMsg);\r
314                 pm_close(rom);\r
315                 return 0;\r
316         }\r
317         pm_close(rom);\r
318 \r
319         // detect wrong files (Pico crashes on very small files), also see if ROM EP is good\r
320         if(rom_size <= 0x200 || strncmp((char *)rom_data, "Pico", 4) == 0 ||\r
321           ((*(unsigned short *)(rom_data+4)<<16)|(*(unsigned short *)(rom_data+6))) >= (int)rom_size) {\r
322                 if (rom_data) free(rom_data);\r
323                 rom_data = 0;\r
324                 sprintf(menuErrorMsg, "Not a ROM selected.");\r
325                 return 0;\r
326         }\r
327 \r
328         // load config for this ROM (do this before insert to get correct region)\r
329         ret = emu_ReadConfig(1);\r
330         if (!ret)\r
331                 emu_ReadConfig(0);\r
332 \r
333         printf("PicoCartInsert(%p, %d);\n", rom_data, rom_size);\r
334         if(PicoCartInsert(rom_data, rom_size)) {\r
335                 sprintf(menuErrorMsg, "Failed to load ROM.");\r
336                 return 0;\r
337         }\r
338 \r
339         Pico.m.frame_count = 0;\r
340 \r
341         // insert CD if it was detected\r
342         if (cd_state > 0) {\r
343                 ret = Insert_CD(romFileName, cd_state == 2);\r
344                 if (ret != 0) {\r
345                         sprintf(menuErrorMsg, "Insert_CD() failed, invalid CD image?");\r
346                         printf("%s\n", menuErrorMsg);\r
347                         return 0;\r
348                 }\r
349         }\r
350 \r
351         // emu_ReadConfig() might have messed currentConfig.lastRomFile\r
352         strncpy(currentConfig.lastRomFile, romFileName, sizeof(currentConfig.lastRomFile)-1);\r
353         currentConfig.lastRomFile[sizeof(currentConfig.lastRomFile)-1] = 0;\r
354 \r
355         if (PicoPatches) {\r
356                 PicoPatchPrepare();\r
357                 PicoPatchApply();\r
358         }\r
359 \r
360         // additional movie stuff\r
361         if(movie_data) {\r
362                 if(movie_data[0x14] == '6')\r
363                      PicoOpt |=  0x20; // 6 button pad\r
364                 else PicoOpt &= ~0x20;\r
365                 PicoOpt |= 0x40; // accurate timing\r
366                 if(movie_data[0xF] >= 'A') {\r
367                         if(movie_data[0x16] & 0x80) {\r
368                                 PicoRegionOverride = 8;\r
369                         } else {\r
370                                 PicoRegionOverride = 4;\r
371                         }\r
372                         PicoReset(0);\r
373                         // TODO: bits 6 & 5\r
374                 }\r
375                 movie_data[0x18+30] = 0;\r
376                 sprintf(noticeMsg, "MOVIE: %s", (char *) &movie_data[0x18]);\r
377         }\r
378         else\r
379         {\r
380                 if(Pico.m.pal) {\r
381                         strcpy(noticeMsg, "PAL SYSTEM / 50 FPS");\r
382                 } else {\r
383                         strcpy(noticeMsg, "NTSC SYSTEM / 60 FPS");\r
384                 }\r
385         }\r
386         gettimeofday(&noticeMsgTime, 0);\r
387 \r
388         // load SRAM for this ROM\r
389         if(currentConfig.EmuOpt & 1)\r
390                 emu_SaveLoadGame(1, 1);\r
391 \r
392         return 1;\r
393 }\r
394 \r
395 \r
396 static void emu_msg_cb(const char *msg);\r
397 \r
398 void emu_Init(void)\r
399 {\r
400         // make temp buffer for alt renderer\r
401         framebuff = malloc((8+320)*(8+240+8));\r
402         if (!framebuff)\r
403         {\r
404                 printf("framebuff == 0\n");\r
405         }\r
406 \r
407         // make dirs for saves, cfgs, etc.\r
408         mkdir("mds", 0777);\r
409         mkdir("srm", 0777);\r
410         mkdir("brm", 0777);\r
411         mkdir("cfg", 0777);\r
412 \r
413         PicoInit();\r
414         PicoMessage = emu_msg_cb;\r
415 \r
416 //      logf = fopen("log.txt", "w");\r
417 }\r
418 \r
419 \r
420 static void romfname_ext(char *dst, const char *prefix, const char *ext)\r
421 {\r
422         char *p;\r
423         int prefix_len = 0;\r
424 \r
425         // make save filename\r
426         for (p = romFileName+strlen(romFileName)-1; p >= romFileName && *p != '/'; p--); p++;\r
427         *dst = 0;\r
428         if (prefix) {\r
429                 strcpy(dst, prefix);\r
430                 prefix_len = strlen(prefix);\r
431         }\r
432         strncpy(dst + prefix_len, p, 511-prefix_len);\r
433         dst[511-8] = 0;\r
434         if (dst[strlen(dst)-4] == '.') dst[strlen(dst)-4] = 0;\r
435         if (ext) strcat(dst, ext);\r
436 }\r
437 \r
438 \r
439 static void find_combos(void)\r
440 {\r
441         int act, u;\r
442 \r
443         // find out which keys and actions are combos\r
444         combo_keys = combo_acts = 0;\r
445         for (act = 0; act < 32; act++)\r
446         {\r
447                 int keyc = 0;\r
448                 if (act == 16) continue; // player2 flag\r
449                 for (u = 0; u < 32; u++)\r
450                 {\r
451                         if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;\r
452                 }\r
453                 if (keyc > 1)\r
454                 {\r
455                         // loop again and mark those keys and actions as combo\r
456                         for (u = 0; u < 32; u++)\r
457                         {\r
458                                 if (currentConfig.KeyBinds[u] & (1 << act)) {\r
459                                         combo_keys |= 1 << u;\r
460                                         combo_acts |= 1 << act;\r
461                                 }\r
462                         }\r
463                 }\r
464         }\r
465         // printf("combo keys/acts: %08x %08x\n", combo_keys, combo_acts);\r
466 }\r
467 \r
468 \r
469 int emu_ReadConfig(int game)\r
470 {\r
471         FILE *f;\r
472         char cfg[512];\r
473         int bread = 0;\r
474 \r
475         if (!game)\r
476         {\r
477                 // set default config\r
478                 memset(&currentConfig, 0, sizeof(currentConfig));\r
479                 currentConfig.lastRomFile[0] = 0;\r
480                 currentConfig.EmuOpt  = 0x1f | 0x400; // | cd_leds\r
481                 currentConfig.PicoOpt = 0x0f | 0xe00; // | use_940 | cd_pcm | cd_cdda\r
482                 currentConfig.PsndRate = 22050; // 44100;\r
483                 currentConfig.PicoRegion = 0; // auto\r
484                 currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP\r
485                 currentConfig.Frameskip = -1; // auto\r
486                 currentConfig.CPUclock = 200;\r
487                 currentConfig.volume = 50;\r
488                 currentConfig.KeyBinds[ 0] = 1<<0; // SACB RLDU\r
489                 currentConfig.KeyBinds[ 4] = 1<<1;\r
490                 currentConfig.KeyBinds[ 2] = 1<<2;\r
491                 currentConfig.KeyBinds[ 6] = 1<<3;\r
492                 currentConfig.KeyBinds[14] = 1<<4;\r
493                 currentConfig.KeyBinds[13] = 1<<5;\r
494                 currentConfig.KeyBinds[12] = 1<<6;\r
495                 currentConfig.KeyBinds[ 8] = 1<<7;\r
496                 currentConfig.KeyBinds[15] = 1<<26; // switch rend\r
497                 currentConfig.KeyBinds[10] = 1<<27; // save state\r
498                 currentConfig.KeyBinds[11] = 1<<28; // load state\r
499                 currentConfig.KeyBinds[23] = 1<<29; // vol up\r
500                 currentConfig.KeyBinds[22] = 1<<30; // vol down\r
501                 currentConfig.gamma = 100;\r
502                 currentConfig.PicoCDBuffers = 64;\r
503                 strncpy(cfg, PicoConfigFile, 511);\r
504                 cfg[511] = 0;\r
505         } else {\r
506                 romfname_ext(cfg, "cfg/", ".pbcfg");\r
507                 f = fopen(cfg, "rb");\r
508                 if (!f) romfname_ext(cfg, NULL, ".pbcfg");\r
509                 else fclose(f);\r
510         }\r
511 \r
512         printf("emu_ReadConfig: %s ", cfg);\r
513         f = fopen(cfg, "rb");\r
514         if (f) {\r
515                 bread = fread(&currentConfig, 1, sizeof(currentConfig), f);\r
516                 fclose(f);\r
517         }\r
518         printf((bread == sizeof(currentConfig)) ? "(ok)\n" : "(failed)\n");\r
519 \r
520         PicoOpt = currentConfig.PicoOpt;\r
521         PsndRate = currentConfig.PsndRate;\r
522         PicoRegionOverride = currentConfig.PicoRegion;\r
523         PicoAutoRgnOrder = currentConfig.PicoAutoRgnOrder;\r
524         PicoCDBuffers = currentConfig.PicoCDBuffers;\r
525         if (PicoOpt & 0x20) {\r
526                 actionNames[ 8] = "Z"; actionNames[ 9] = "Y";\r
527                 actionNames[10] = "X"; actionNames[11] = "MODE";\r
528         }\r
529         // some sanity checks\r
530         if (currentConfig.CPUclock < 1 || currentConfig.CPUclock > 4096) currentConfig.CPUclock = 200;\r
531         if (currentConfig.gamma < 10 || currentConfig.gamma > 300) currentConfig.gamma = 100;\r
532         // if volume keys are unbound, bind them to volume control\r
533         if (!currentConfig.KeyBinds[23] && !currentConfig.KeyBinds[22]) {\r
534                 currentConfig.KeyBinds[23] = 1<<29; // vol up\r
535                 currentConfig.KeyBinds[22] = 1<<30; // vol down\r
536         }\r
537 \r
538         return (bread == sizeof(currentConfig));\r
539 }\r
540 \r
541 \r
542 int emu_WriteConfig(int game)\r
543 {\r
544         FILE *f;\r
545         char cfg[512];\r
546         int bwrite = 0;\r
547 \r
548         if (!game)\r
549         {\r
550                 strncpy(cfg, PicoConfigFile, 511);\r
551                 cfg[511] = 0;\r
552         } else {\r
553                 romfname_ext(cfg, "cfg/", ".pbcfg");\r
554         }\r
555 \r
556         printf("emu_WriteConfig: %s ", cfg);\r
557         f = fopen(cfg, "wb");\r
558         if (f) {\r
559                 currentConfig.PicoOpt = PicoOpt;\r
560                 currentConfig.PsndRate = PsndRate;\r
561                 currentConfig.PicoRegion = PicoRegionOverride;\r
562                 currentConfig.PicoAutoRgnOrder = PicoAutoRgnOrder;\r
563                 currentConfig.PicoCDBuffers = PicoCDBuffers;\r
564                 bwrite = fwrite(&currentConfig, 1, sizeof(currentConfig), f);\r
565                 fflush(f);\r
566                 fclose(f);\r
567                 sync();\r
568         }\r
569         printf((bwrite == sizeof(currentConfig)) ? "(ok)\n" : "(failed)\n");\r
570 \r
571         return (bwrite == sizeof(currentConfig));\r
572 }\r
573 \r
574 \r
575 void emu_Deinit(void)\r
576 {\r
577         // save SRAM\r
578         if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
579                 emu_SaveLoadGame(0, 1);\r
580                 SRam.changed = 0;\r
581         }\r
582 \r
583         if (!(currentConfig.EmuOpt & 0x20))\r
584                 emu_WriteConfig(0);\r
585         free(framebuff);\r
586 \r
587         PicoExit();\r
588 //      fclose(logf);\r
589 \r
590         // restore gamma\r
591         if (gp2x_old_gamma != 100)\r
592                 set_gamma(100);\r
593 }\r
594 \r
595 \r
596 void osd_text(int x, int y, const char *text)\r
597 {\r
598         int len = strlen(text)*8;\r
599 \r
600         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
601                 int *p, i, h;\r
602                 x &= ~3; // align x\r
603                 len = (len+3) >> 2;\r
604                 for (h = 0; h < 8; h++) {\r
605                         p = (int *) ((unsigned char *) gp2x_screen+x+320*(y+h));\r
606                         for (i = len; i; i--, p++) *p = 0xe0e0e0e0;\r
607                 }\r
608                 gp2x_text_out8_2(x, y, text, 0xf0);\r
609         } else {\r
610                 int *p, i, h;\r
611                 x &= ~1; // align x\r
612                 len = (len+1) >> 1;\r
613                 for (h = 0; h < 8; h++) {\r
614                         p = (int *) ((unsigned short *) gp2x_screen+x+320*(y+h));\r
615                         for (i = len; i; i--, p++) *p = (*p>>2)&0x39e7;\r
616                 }\r
617                 gp2x_text_out15(x, y, text);\r
618         }\r
619 }\r
620 \r
621 static void cd_leds(void)\r
622 {\r
623         // mmu problems?\r
624 //      static\r
625         int old_reg;\r
626 //      if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change\r
627         old_reg = Pico_mcd->s68k_regs[0];\r
628 \r
629         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
630                 // 8-bit modes\r
631                 unsigned int col_g = (old_reg & 2) ? 0xc0c0c0c0 : 0xe0e0e0e0;\r
632                 unsigned int col_r = (old_reg & 1) ? 0xd0d0d0d0 : 0xe0e0e0e0;\r
633                 *(unsigned int *)((char *)gp2x_screen + 320*2+ 4) =\r
634                 *(unsigned int *)((char *)gp2x_screen + 320*3+ 4) =\r
635                 *(unsigned int *)((char *)gp2x_screen + 320*4+ 4) = col_g;\r
636                 *(unsigned int *)((char *)gp2x_screen + 320*2+12) =\r
637                 *(unsigned int *)((char *)gp2x_screen + 320*3+12) =\r
638                 *(unsigned int *)((char *)gp2x_screen + 320*4+12) = col_r;\r
639         } else {\r
640                 // 16-bit modes\r
641                 unsigned int *p = (unsigned int *)((short *)gp2x_screen + 320*2+4);\r
642                 unsigned int col_g = (old_reg & 2) ? 0x06000600 : 0;\r
643                 unsigned int col_r = (old_reg & 1) ? 0xc000c000 : 0;\r
644                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
645                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
646                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
647         }\r
648 }\r
649 \r
650 static int EmuScan16(unsigned int num, void *sdata)\r
651 {\r
652         if (!(Pico.video.reg[1]&8)) num += 8;\r
653         DrawLineDest = (unsigned short *) gp2x_screen + 320*(num+1);\r
654 \r
655         return 0;\r
656 }\r
657 \r
658 static int EmuScan8(unsigned int num, void *sdata)\r
659 {\r
660         if (!(Pico.video.reg[1]&8)) num += 8;\r
661         DrawLineDest = (unsigned char *)  gp2x_screen + 320*(num+1);\r
662 \r
663         return 0;\r
664 }\r
665 \r
666 int localPal[0x100];\r
667 static void (*vidCpyM2)(void *dest, void *src) = NULL;\r
668 \r
669 static void blit(const char *fps, const char *notice)\r
670 {\r
671         int emu_opt = currentConfig.EmuOpt;\r
672 \r
673         if (PicoOpt&0x10) {\r
674                 // 8bit fast renderer\r
675                 if (Pico.m.dirtyPal) {\r
676                         Pico.m.dirtyPal = 0;\r
677                         vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
678                         // feed new palette to our device\r
679                         gp2x_video_setpalette(localPal, 0x40);\r
680                 }\r
681                 vidCpyM2((unsigned char *)gp2x_screen+320*8, framebuff+328*8);\r
682         } else if (!(emu_opt&0x80)) {\r
683                 // 8bit accurate renderer\r
684                 if (Pico.m.dirtyPal) {\r
685                         Pico.m.dirtyPal = 0;\r
686                         if(Pico.video.reg[0xC]&8) { // shadow/hilight mode\r
687                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
688                                 vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);\r
689                                 vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40);\r
690                                 blockcpy(localPal+0xc0, localPal+0x40, 0x40*4);\r
691                                 localPal[0xc0] = 0x0000c000;\r
692                                 localPal[0xd0] = 0x00c00000;\r
693                                 localPal[0xe0] = 0x00000000; // reserved pixels for OSD\r
694                                 localPal[0xf0] = 0x00ffffff;\r
695                                 gp2x_video_setpalette(localPal, 0x100);\r
696                         } else if (rendstatus & 0x20) { // mid-frame palette changes\r
697                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
698                                 vidConvCpyRGB32(localPal+0x40, HighPal, 0x40);\r
699                                 vidConvCpyRGB32(localPal+0x80, HighPal+0x40, 0x40);\r
700                                 gp2x_video_setpalette(localPal, 0xc0);\r
701                         } else {\r
702                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
703                                 gp2x_video_setpalette(localPal, 0x40);\r
704                         }\r
705                 }\r
706         }\r
707 \r
708         if (notice) osd_text(4, 232, notice);\r
709         if (emu_opt & 2)\r
710                 osd_text(osd_fps_x, 232, fps);\r
711         if ((emu_opt & 0x400) && (PicoMCD & 1))\r
712                 cd_leds();\r
713 \r
714         //gp2x_video_wait_vsync();\r
715         gp2x_video_flip();\r
716 \r
717         if (!(PicoOpt&0x10)) {\r
718                 if (!(Pico.video.reg[1]&8)) {\r
719                         if (currentConfig.EmuOpt&0x80) {\r
720                                 DrawLineDest = (unsigned short *) gp2x_screen + 320*8;\r
721                         } else {\r
722                                 DrawLineDest = (unsigned char  *) gp2x_screen + 320*8;\r
723                         }\r
724                 } else {\r
725                         DrawLineDest = gp2x_screen;\r
726                 }\r
727         }\r
728 }\r
729 \r
730 \r
731 // clears whole screen or just the notice area (in all buffers)\r
732 static void clearArea(int full)\r
733 {\r
734         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
735                 // 8-bit renderers\r
736                 if (full) gp2x_memset_all_buffers(0, 0xe0, 320*240);\r
737                 else      gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
738         } else {\r
739                 // 16bit accurate renderer\r
740                 if (full) gp2x_memset_all_buffers(0, 0, 320*240*2);\r
741                 else      gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
742         }\r
743 }\r
744 \r
745 \r
746 static void vidResetMode(void)\r
747 {\r
748         if (PicoOpt&0x10) {\r
749                 gp2x_video_changemode(8);\r
750         } else if (currentConfig.EmuOpt&0x80) {\r
751                 gp2x_video_changemode(15);\r
752                 PicoDrawSetColorFormat(1);\r
753                 PicoScan = EmuScan16;\r
754                 PicoScan(0, 0);\r
755         } else {\r
756                 gp2x_video_changemode(8);\r
757                 PicoDrawSetColorFormat(2);\r
758                 PicoScan = EmuScan8;\r
759                 PicoScan(0, 0);\r
760         }\r
761         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
762                 // setup pal for 8-bit modes\r
763                 localPal[0xc0] = 0x0000c000; // MCD LEDs\r
764                 localPal[0xd0] = 0x00c00000;\r
765                 localPal[0xe0] = 0x00000000; // reserved pixels for OSD\r
766                 localPal[0xf0] = 0x00ffffff;\r
767                 gp2x_video_setpalette(localPal, 0x100);\r
768                 gp2x_memset_all_buffers(0, 0xe0, 320*240);\r
769                 gp2x_video_flip();\r
770         }\r
771         Pico.m.dirtyPal = 1;\r
772         // reset scaling\r
773         gp2x_video_RGB_setscaling((PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 240);\r
774 }\r
775 \r
776 \r
777 static void emu_msg_cb(const char *msg)\r
778 {\r
779         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
780                 // 8-bit renderers\r
781                 gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
782                 osd_text(4, 232, msg);\r
783                 gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232, 320*232, 320*8);\r
784         } else {\r
785                 // 16bit accurate renderer\r
786                 gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
787                 osd_text(4, 232, msg);\r
788                 gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232*2, 320*232*2, 320*8*2);\r
789         }\r
790         gettimeofday(&noticeMsgTime, 0);\r
791         noticeMsgTime.tv_sec -= 2;\r
792 }\r
793 \r
794 static void emu_state_cb(const char *str)\r
795 {\r
796         clearArea(0);\r
797         blit("", str);\r
798 }\r
799 \r
800 static void RunEvents(unsigned int which)\r
801 {\r
802         if(which & 0x1800) { // save or load (but not both)\r
803                 int do_it = 1;\r
804                 if (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200) && emu_check_save_file(state_slot)) {\r
805                         unsigned long keys;\r
806                         blit("", "OVERWRITE SAVE? (Y=yes, X=no)");\r
807                         while( !((keys = gp2x_joystick_read(1)) & (GP2X_X|GP2X_Y)) )\r
808                                 usleep(50*1024);\r
809                         if (keys & GP2X_X) do_it = 0;\r
810                         clearArea(0);\r
811                 }\r
812                 if (do_it) {\r
813                         osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");\r
814                         PicoStateProgressCB = emu_state_cb;\r
815                         gp2x_memcpy_all_buffers(gp2x_screen, 0, 320*240*2);\r
816                         emu_SaveLoadGame((which & 0x1000) >> 12, 0);\r
817                         PicoStateProgressCB = NULL;\r
818                 }\r
819 \r
820                 reset_timing = 1;\r
821         }\r
822         if(which & 0x0400) { // switch renderer\r
823                 if      (  PicoOpt&0x10)             { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }\r
824                 else if (!(currentConfig.EmuOpt&0x80)) PicoOpt|= 0x10;\r
825                 else   currentConfig.EmuOpt &= ~0x80;\r
826 \r
827                 vidResetMode();\r
828 \r
829                 if (PicoOpt&0x10) {\r
830                         strcpy(noticeMsg, " 8bit fast renderer");\r
831                 } else if (currentConfig.EmuOpt&0x80) {\r
832                         strcpy(noticeMsg, "16bit accurate renderer");\r
833                 } else {\r
834                         strcpy(noticeMsg, " 8bit accurate renderer");\r
835                 }\r
836 \r
837                 gettimeofday(&noticeMsgTime, 0);\r
838         }\r
839         if(which & 0x0300) {\r
840                 if(which&0x0200) {\r
841                         state_slot -= 1;\r
842                         if(state_slot < 0) state_slot = 9;\r
843                 } else {\r
844                         state_slot += 1;\r
845                         if(state_slot > 9) state_slot = 0;\r
846                 }\r
847                 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_check_save_file(state_slot) ? "USED" : "FREE");\r
848                 gettimeofday(&noticeMsgTime, 0);\r
849         }\r
850         if(which & 0x0080) {\r
851                 engineState = PGS_Menu;\r
852         }\r
853 }\r
854 \r
855 \r
856 static void updateMovie(void)\r
857 {\r
858         int offs = Pico.m.frame_count*3 + 0x40;\r
859         if (offs+3 > movie_size) {\r
860                 free(movie_data);\r
861                 movie_data = 0;\r
862                 strcpy(noticeMsg, "END OF MOVIE.");\r
863                 printf("END OF MOVIE.\n");\r
864                 gettimeofday(&noticeMsgTime, 0);\r
865         } else {\r
866                 // MXYZ SACB RLDU\r
867                 PicoPad[0] = ~movie_data[offs]   & 0x8f; // ! SCBA RLDU\r
868                 if(!(movie_data[offs]   & 0x10)) PicoPad[0] |= 0x40; // A\r
869                 if(!(movie_data[offs]   & 0x20)) PicoPad[0] |= 0x10; // B\r
870                 if(!(movie_data[offs]   & 0x40)) PicoPad[0] |= 0x20; // A\r
871                 PicoPad[1] = ~movie_data[offs+1] & 0x8f; // ! SCBA RLDU\r
872                 if(!(movie_data[offs+1] & 0x10)) PicoPad[1] |= 0x40; // A\r
873                 if(!(movie_data[offs+1] & 0x20)) PicoPad[1] |= 0x10; // B\r
874                 if(!(movie_data[offs+1] & 0x40)) PicoPad[1] |= 0x20; // A\r
875                 PicoPad[0] |= (~movie_data[offs+2] & 0x0A) << 8; // ! MZYX\r
876                 if(!(movie_data[offs+2] & 0x01)) PicoPad[0] |= 0x0400; // X\r
877                 if(!(movie_data[offs+2] & 0x04)) PicoPad[0] |= 0x0100; // Z\r
878                 PicoPad[1] |= (~movie_data[offs+2] & 0xA0) << 4; // ! MZYX\r
879                 if(!(movie_data[offs+2] & 0x10)) PicoPad[1] |= 0x0400; // X\r
880                 if(!(movie_data[offs+2] & 0x40)) PicoPad[1] |= 0x0100; // Z\r
881         }\r
882 }\r
883 \r
884 \r
885 static void updateKeys(void)\r
886 {\r
887         unsigned long keys, allActions[2] = { 0, 0 }, events;\r
888         static unsigned long prevEvents = 0;\r
889         int joy, i;\r
890 \r
891         keys = gp2x_joystick_read(0);\r
892         if (keys & GP2X_SELECT) {\r
893                 engineState = select_exits ? PGS_Quit : PGS_Menu;\r
894                 // wait until select is released, so menu would not resume game\r
895                 while (gp2x_joystick_read(1) & GP2X_SELECT) usleep(50*1000);\r
896         }\r
897 \r
898         keys &= CONFIGURABLE_KEYS;\r
899 \r
900         for (i = 0; i < 32; i++)\r
901         {\r
902                 if (keys & (1 << i)) {\r
903                         int pl, acts = currentConfig.KeyBinds[i];\r
904                         if (!acts) continue;\r
905                         pl = (acts >> 16) & 1;\r
906                         if (combo_keys & (1 << i)) {\r
907                                 int u = i+1, acts_c = acts & combo_acts;\r
908                                 // let's try to find the other one\r
909                                 if (acts_c)\r
910                                         for (; u < 32; u++)\r
911                                                 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {\r
912                                                         allActions[pl] |= acts_c;\r
913                                                         keys &= ~((1 << i) | (1 << u));\r
914                                                         break;\r
915                                                 }\r
916                                 // add non-combo actions if combo ones were not found\r
917                                 if (!acts_c || u == 32)\r
918                                         allActions[pl] |= acts & ~combo_acts;\r
919                         } else {\r
920                                 allActions[pl] |= acts;\r
921                         }\r
922                 }\r
923         }\r
924 \r
925         // add joy inputs\r
926         if (num_of_joys > 0)\r
927         {\r
928                 gp2x_usbjoy_update();\r
929                 for (joy = 0; joy < num_of_joys; joy++) {\r
930                         int keys = gp2x_usbjoy_check2(joy);\r
931                         for (i = 0; i < 32; i++) {\r
932                                 if (keys & (1 << i)) {\r
933                                         int acts = currentConfig.JoyBinds[joy][i];\r
934                                         int pl = (acts >> 16) & 1;\r
935                                         allActions[pl] |= acts;\r
936                                 }\r
937                         }\r
938                 }\r
939         }\r
940 \r
941         PicoPad[0] = (unsigned short) allActions[0];\r
942         PicoPad[1] = (unsigned short) allActions[1];\r
943 \r
944         events = (allActions[0] | allActions[1]) >> 16;\r
945 \r
946         // volume is treated in special way and triggered every frame\r
947         if(events & 0x6000) {\r
948                 int vol = currentConfig.volume;\r
949                 if (events & 0x2000) {\r
950                         if (vol < 90) vol++;\r
951                 } else {\r
952                         if (vol >  0) vol--;\r
953                 }\r
954                 gp2x_sound_volume(vol, vol);\r
955                 sprintf(noticeMsg, "VOL: %02i", vol);\r
956                 gettimeofday(&noticeMsgTime, 0);\r
957                 currentConfig.volume = vol;\r
958         }\r
959 \r
960         events &= ~prevEvents;\r
961         if (events) RunEvents(events);\r
962         if (movie_data) updateMovie();\r
963 \r
964         prevEvents = (allActions[0] | allActions[1]) >> 16;\r
965 }\r
966 \r
967 \r
968 static void updateSound(int len)\r
969 {\r
970         if (PicoOpt&8) len<<=1;\r
971 \r
972         gp2x_sound_write(PsndOut, len<<1);\r
973 }\r
974 \r
975 \r
976 static void SkipFrame(void)\r
977 {\r
978         PicoSkipFrame=1;\r
979         PicoFrame();\r
980         PicoSkipFrame=0;\r
981 }\r
982 \r
983 \r
984 void emu_forced_frame(void)\r
985 {\r
986         int po_old = PicoOpt;\r
987 \r
988         PicoOpt |= 0x10;\r
989         PicoFrameFull();\r
990 \r
991         if (!(Pico.video.reg[12]&1)) {\r
992                 vidCpyM2 = vidCpyM2_32col;\r
993                 clearArea(1);\r
994         } else  vidCpyM2 = vidCpyM2_40col;\r
995 \r
996         vidCpyM2((unsigned char *)gp2x_screen+320*8, framebuff+328*8);\r
997         vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
998         gp2x_video_setpalette(localPal, 0x40);\r
999 \r
1000         PicoOpt = po_old;\r
1001 }\r
1002 \r
1003 static void simpleWait(int thissec, int lim_time)\r
1004 {\r
1005         struct timeval tval;\r
1006 \r
1007         spend_cycles(1024);\r
1008         gettimeofday(&tval, 0);\r
1009         if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
1010 \r
1011         while(tval.tv_usec < lim_time)\r
1012         {\r
1013                 spend_cycles(1024);\r
1014                 gettimeofday(&tval, 0);\r
1015                 if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
1016         }\r
1017 }\r
1018 \r
1019 \r
1020 void emu_Loop(void)\r
1021 {\r
1022         static int gp2x_old_clock = 200;\r
1023         static int PsndRate_old = 0, PicoOpt_old = 0, PsndLen_real = 0, pal_old = 0;\r
1024         char fpsbuff[24]; // fps count c string\r
1025         struct timeval tval; // timing\r
1026         int thissec = 0, frames_done = 0, frames_shown = 0, oldmodes = 0;\r
1027         int target_fps, target_frametime, lim_time, i;\r
1028         char *notice = 0;\r
1029 \r
1030         printf("entered emu_Loop()\n");\r
1031 \r
1032         if (gp2x_old_clock != currentConfig.CPUclock) {\r
1033                 printf("changing clock to %i...", currentConfig.CPUclock); fflush(stdout);\r
1034                 set_FCLK(currentConfig.CPUclock);\r
1035                 gp2x_old_clock = currentConfig.CPUclock;\r
1036                 printf(" done\n");\r
1037         }\r
1038 \r
1039         if (gp2x_old_gamma != currentConfig.gamma) {\r
1040                 set_gamma(currentConfig.gamma);\r
1041                 gp2x_old_gamma = currentConfig.gamma;\r
1042                 printf("updated gamma to %i\n", currentConfig.gamma);\r
1043         }\r
1044 \r
1045         fpsbuff[0] = 0;\r
1046 \r
1047         // make sure we are in correct mode\r
1048         vidResetMode();\r
1049         Pico.m.dirtyPal = 1;\r
1050         oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;\r
1051         find_combos();\r
1052 \r
1053         // pal/ntsc might have changed, reset related stuff\r
1054         target_fps = Pico.m.pal ? 50 : 60;\r
1055         target_frametime = 1000000/target_fps;\r
1056         reset_timing = 1;\r
1057 \r
1058         // prepare sound stuff\r
1059         if(currentConfig.EmuOpt & 4) {\r
1060                 int snd_excess_add;\r
1061                 if(PsndRate != PsndRate_old || (PicoOpt&0x20b) != (PicoOpt_old&0x20b) || Pico.m.pal != pal_old || crashed_940) {\r
1062                         /* if 940 is turned off, we need it to be put back to sleep */\r
1063                         if (!(PicoOpt&0x200) && ((PicoOpt^PicoOpt_old)&0x200)) {\r
1064                                 Reset940(1, 2);\r
1065                                 Pause940(1);\r
1066                         }\r
1067                         sound_rerate(1);\r
1068                 }\r
1069                 //excess_samples = PsndRate - PsndLen*target_fps;\r
1070                 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;\r
1071                 printf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n", PsndRate, PsndLen, snd_excess_add, (PicoOpt&8)>>3, Pico.m.pal);\r
1072                 gp2x_start_sound(PsndRate, 16, (PicoOpt&8)>>3);\r
1073                 gp2x_sound_volume(currentConfig.volume, currentConfig.volume);\r
1074                 PicoWriteSound = updateSound;\r
1075                 memset(sndBuffer, 0, sizeof(sndBuffer));\r
1076                 PsndOut = sndBuffer;\r
1077                 PsndRate_old = PsndRate;\r
1078                 PsndLen_real = PsndLen;\r
1079                 PicoOpt_old  = PicoOpt;\r
1080                 pal_old = Pico.m.pal;\r
1081         } else {\r
1082                 PsndOut = 0;\r
1083         }\r
1084 \r
1085         // prepare CD buffer\r
1086         if (PicoMCD & 1) PicoCDBufferInit();\r
1087 \r
1088         // loop?\r
1089         while (engineState == PGS_Running)\r
1090         {\r
1091                 int modes;\r
1092 \r
1093                 gettimeofday(&tval, 0);\r
1094                 if(reset_timing) {\r
1095                         reset_timing = 0;\r
1096                         thissec = tval.tv_sec;\r
1097                         frames_shown = frames_done = tval.tv_usec/target_frametime;\r
1098                 }\r
1099 \r
1100                 // show notice message?\r
1101                 if(noticeMsgTime.tv_sec) {\r
1102                         static int noticeMsgSum;\r
1103                         if((tval.tv_sec*1000000+tval.tv_usec) - (noticeMsgTime.tv_sec*1000000+noticeMsgTime.tv_usec) > 2000000) { // > 2.0 sec\r
1104                                 noticeMsgTime.tv_sec = noticeMsgTime.tv_usec = 0;\r
1105                                 clearArea(0);\r
1106                                 notice = 0;\r
1107                         } else {\r
1108                                 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];\r
1109                                 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }\r
1110                                 notice = noticeMsg;\r
1111                         }\r
1112                 }\r
1113 \r
1114                 // check for mode changes\r
1115                 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);\r
1116                 if (modes != oldmodes) {\r
1117                         int scalex = 320;\r
1118                         osd_fps_x = OSD_FPS_X;\r
1119                         if (modes & 4) {\r
1120                                 vidCpyM2 = vidCpyM2_40col;\r
1121                         } else {\r
1122                                 if (PicoOpt & 0x100) {\r
1123                                         vidCpyM2 = vidCpyM2_32col_nobord;\r
1124                                         scalex = 256;\r
1125                                         osd_fps_x = OSD_FPS_X - 64;\r
1126                                 } else {\r
1127                                         vidCpyM2 = vidCpyM2_32col;\r
1128                                 }\r
1129                         }\r
1130                         gp2x_video_RGB_setscaling(scalex, 240);\r
1131                         oldmodes = modes;\r
1132                         clearArea(1);\r
1133                 }\r
1134 \r
1135                 // second changed?\r
1136                 if(thissec != tval.tv_sec) {\r
1137 #ifdef BENCHMARK\r
1138                         static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];\r
1139                         if(++bench == 10) {\r
1140                                 bench = 0;\r
1141                                 bench_fps_s = bench_fps;\r
1142                                 bf[bfp++ & 3] = bench_fps;\r
1143                                 bench_fps = 0;\r
1144                         }\r
1145                         bench_fps += frames_shown;\r
1146                         sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);\r
1147 #else\r
1148                         if(currentConfig.EmuOpt & 2)\r
1149                                 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);\r
1150 #endif\r
1151                         thissec = tval.tv_sec;\r
1152 \r
1153                         if(PsndOut == 0 && currentConfig.Frameskip >= 0) {\r
1154                                 frames_done = frames_shown = 0;\r
1155                         } else {\r
1156                                 // it is quite common for this implementation to leave 1 fame unfinished\r
1157                                 // when second changes, but we don't want buffer to starve.\r
1158                                 if(PsndOut && frames_done < target_fps && frames_done > target_fps-5) {\r
1159                                         updateKeys();\r
1160                                         SkipFrame(); frames_done++;\r
1161                                 }\r
1162 \r
1163                                 frames_done  -= target_fps; if (frames_done  < 0) frames_done  = 0;\r
1164                                 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;\r
1165                                 if (frames_shown > frames_done) frames_shown = frames_done;\r
1166                         }\r
1167                 }\r
1168 \r
1169                 lim_time = (frames_done+1) * target_frametime;\r
1170                 if(currentConfig.Frameskip >= 0) { // frameskip enabled\r
1171                         for(i = 0; i < currentConfig.Frameskip; i++) {\r
1172                                 updateKeys();\r
1173                                 SkipFrame(); frames_done++;\r
1174                                 if (PsndOut) { // do framelimitting if sound is enabled\r
1175                                         gettimeofday(&tval, 0);\r
1176                                         if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
1177                                         if(tval.tv_usec < lim_time) { // we are too fast\r
1178                                                 simpleWait(thissec, lim_time);\r
1179                                         }\r
1180                                 }\r
1181                                 lim_time += target_frametime;\r
1182                         }\r
1183                 } else if(tval.tv_usec > lim_time) { // auto frameskip\r
1184                         // no time left for this frame - skip\r
1185                         if (tval.tv_usec - lim_time >= 0x300000) {\r
1186                                 /* something caused a slowdown for us (disk access? cache flush?)\r
1187                                  * try to recover by resetting timing... */\r
1188                                 reset_timing = 1;\r
1189                                 continue;\r
1190                         }\r
1191                         updateKeys();\r
1192                         SkipFrame(/*tval.tv_usec < lim_time+target_frametime*/); frames_done++;\r
1193                         continue;\r
1194                 }\r
1195 \r
1196                 updateKeys();\r
1197                 PicoFrame();\r
1198 \r
1199 #if 0\r
1200 if (Pico.m.frame_count == 31563) {\r
1201         FILE *f;\r
1202         f = fopen("ram_p.bin", "wb");\r
1203         if (!f) { printf("!f\n"); exit(1); }\r
1204         fwrite(Pico.ram, 1, 0x10000, f);\r
1205         fclose(f);\r
1206         exit(0);\r
1207 }\r
1208 #endif\r
1209 #if 0\r
1210                 // debug\r
1211                 {\r
1212                         #define BYTE unsigned char\r
1213                         #define WORD unsigned short\r
1214                         struct\r
1215                         {\r
1216                                 BYTE IDLength;        /* 00h  Size of Image ID field */\r
1217                                 BYTE ColorMapType;    /* 01h  Color map type */\r
1218                                 BYTE ImageType;       /* 02h  Image type code */\r
1219                                 WORD CMapStart;       /* 03h  Color map origin */\r
1220                                 WORD CMapLength;      /* 05h  Color map length */\r
1221                                 BYTE CMapDepth;       /* 07h  Depth of color map entries */\r
1222                                 WORD XOffset;         /* 08h  X origin of image */\r
1223                                 WORD YOffset;         /* 0Ah  Y origin of image */\r
1224                                 WORD Width;           /* 0Ch  Width of image */\r
1225                                 WORD Height;          /* 0Eh  Height of image */\r
1226                                 BYTE PixelDepth;      /* 10h  Image pixel size */\r
1227                                 BYTE ImageDescriptor; /* 11h  Image descriptor byte */\r
1228                         } __attribute__((packed)) TGAHEAD;\r
1229                         static unsigned short oldscr[320*240];\r
1230                         FILE *f; char name[128]; int i;\r
1231 \r
1232                         memset(&TGAHEAD, 0, sizeof(TGAHEAD));\r
1233                         TGAHEAD.ImageType = 2;\r
1234                         TGAHEAD.Width = 320;\r
1235                         TGAHEAD.Height = 240;\r
1236                         TGAHEAD.PixelDepth = 16;\r
1237                         TGAHEAD.ImageDescriptor = 2<<4; // image starts at top-left\r
1238 \r
1239                         #define CONV(X) (((X>>1)&0x7fe0)|(X&0x1f)) // 555?\r
1240 \r
1241                         for (i = 0; i < 320*240; i++)\r
1242                                 if(oldscr[i] != CONV(((unsigned short *)gp2x_screen)[i])) break;\r
1243                         if (i < 320*240)\r
1244                         {\r
1245                                 for (i = 0; i < 320*240; i++)\r
1246                                         oldscr[i] = CONV(((unsigned short *)gp2x_screen)[i]);\r
1247                                 sprintf(name, "%05i.tga", Pico.m.frame_count);\r
1248                                 f = fopen(name, "wb");\r
1249                                 if (!f) { printf("!f\n"); exit(1); }\r
1250                                 fwrite(&TGAHEAD, 1, sizeof(TGAHEAD), f);\r
1251                                 fwrite(oldscr, 1, 320*240*2, f);\r
1252                                 fclose(f);\r
1253                         }\r
1254                 }\r
1255 #endif\r
1256 \r
1257                 // check time\r
1258                 gettimeofday(&tval, 0);\r
1259                 if (thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
1260 \r
1261                 if (currentConfig.Frameskip < 0 && tval.tv_usec - lim_time >= 0x300000) // slowdown detection\r
1262                         reset_timing = 1;\r
1263                 else if (PsndOut != NULL || currentConfig.Frameskip < 0)\r
1264                 {\r
1265                         // sleep if we are still too fast\r
1266                         // usleep sleeps for ~20ms minimum, so it is not a solution here\r
1267                         if(tval.tv_usec < lim_time)\r
1268                         {\r
1269                                 // we are too fast\r
1270                                 simpleWait(thissec, lim_time);\r
1271                         }\r
1272                 }\r
1273 \r
1274                 blit(fpsbuff, notice);\r
1275 \r
1276                 frames_done++; frames_shown++;\r
1277         }\r
1278 \r
1279 \r
1280         if (PicoMCD & 1) PicoCDBufferFree();\r
1281 \r
1282         // save SRAM\r
1283         if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
1284                 osd_text(4, 232, "Writing SRAM/BRAM..");\r
1285                 emu_SaveLoadGame(0, 1);\r
1286                 SRam.changed = 0;\r
1287         }\r
1288 \r
1289         // if in 16bit mode, generate 8it image for menu background\r
1290         if (!(PicoOpt&0x10) && (currentConfig.EmuOpt&0x80))\r
1291                 emu_forced_frame();\r
1292 \r
1293         // for menu bg\r
1294         gp2x_memcpy_buffers((1<<2), gp2x_screen, 0, 320*240*2);\r
1295 }\r
1296 \r
1297 \r
1298 void emu_ResetGame(void)\r
1299 {\r
1300         PicoReset(0);\r
1301         reset_timing = 1;\r
1302 }\r
1303 \r
1304 \r
1305 size_t gzRead2(void *p, size_t _size, size_t _n, void *file)\r
1306 {\r
1307         return gzread(file, p, _n);\r
1308 }\r
1309 \r
1310 \r
1311 size_t gzWrite2(void *p, size_t _size, size_t _n, void *file)\r
1312 {\r
1313         return gzwrite(file, p, _n);\r
1314 }\r
1315 \r
1316 static int try_ropen_file(const char *fname)\r
1317 {\r
1318         FILE *f;\r
1319 \r
1320         f = fopen(fname, "rb");\r
1321         if (f) {\r
1322                 fclose(f);\r
1323                 return 1;\r
1324         }\r
1325         return 0;\r
1326 }\r
1327 \r
1328 char *emu_GetSaveFName(int load, int is_sram, int slot)\r
1329 {\r
1330         static char saveFname[512];\r
1331         char ext[16];\r
1332 \r
1333         if (is_sram)\r
1334         {\r
1335                 romfname_ext(saveFname, (PicoMCD&1) ? "brm/" : "srm/", (PicoMCD&1) ? ".brm" : ".srm");\r
1336                 if (load) {\r
1337                         if (try_ropen_file(saveFname)) return saveFname;\r
1338                         // try in current dir..\r
1339                         romfname_ext(saveFname, NULL, (PicoMCD&1) ? ".brm" : ".srm");\r
1340                         if (try_ropen_file(saveFname)) return saveFname;\r
1341                         return NULL; // give up\r
1342                 }\r
1343         }\r
1344         else\r
1345         {\r
1346                 ext[0] = 0;\r
1347                 if(slot > 0 && slot < 10) sprintf(ext, ".%i", slot);\r
1348                 strcat(ext, (currentConfig.EmuOpt & 8) ? ".mds.gz" : ".mds");\r
1349 \r
1350                 romfname_ext(saveFname, "mds/", ext);\r
1351                 if (load) {\r
1352                         if (try_ropen_file(saveFname)) return saveFname;\r
1353                         romfname_ext(saveFname, NULL, ext);\r
1354                         if (try_ropen_file(saveFname)) return saveFname;\r
1355                         if (currentConfig.EmuOpt & 8) {\r
1356                                 ext[0] = 0;\r
1357                                 if(slot > 0 && slot < 10) sprintf(ext, ".%i", slot);\r
1358                                 strcat(ext, ".mds");\r
1359 \r
1360                                 romfname_ext(saveFname, "mds/", ext);\r
1361                                 if (try_ropen_file(saveFname)) return saveFname;\r
1362                                 romfname_ext(saveFname, NULL, ext);\r
1363                                 if (try_ropen_file(saveFname)) return saveFname;\r
1364                         }\r
1365                         return NULL;\r
1366                 }\r
1367         }\r
1368 \r
1369         return saveFname;\r
1370 }\r
1371 \r
1372 int emu_check_save_file(int slot)\r
1373 {\r
1374         return emu_GetSaveFName(1, 0, slot) ? 1 : 0;\r
1375 }\r
1376 \r
1377 void emu_set_save_cbs(int gz)\r
1378 {\r
1379         if (gz) {\r
1380                 areaRead  = gzRead2;\r
1381                 areaWrite = gzWrite2;\r
1382                 areaEof   = (areaeof *) gzeof;\r
1383                 areaSeek  = (areaseek *) gzseek;\r
1384                 areaClose = (areaclose *) gzclose;\r
1385         } else {\r
1386                 areaRead  = (arearw *) fread;\r
1387                 areaWrite = (arearw *) fwrite;\r
1388                 areaEof   = (areaeof *) feof;\r
1389                 areaSeek  = (areaseek *) fseek;\r
1390                 areaClose = (areaclose *) fclose;\r
1391         }\r
1392 }\r
1393 \r
1394 int emu_SaveLoadGame(int load, int sram)\r
1395 {\r
1396         int ret = 0;\r
1397         char *saveFname;\r
1398 \r
1399         // make save filename\r
1400         saveFname = emu_GetSaveFName(load, sram, state_slot);\r
1401         if (saveFname == NULL) {\r
1402                 if (!sram) {\r
1403                         strcpy(noticeMsg, load ? "LOAD FAILED (missing file)" : "SAVE FAILED  ");\r
1404                         gettimeofday(&noticeMsgTime, 0);\r
1405                 }\r
1406                 return -1;\r
1407         }\r
1408 \r
1409         printf("saveLoad (%i, %i): %s\n", load, sram, saveFname);\r
1410 \r
1411         if(sram) {\r
1412                 FILE *sramFile;\r
1413                 int sram_size;\r
1414                 unsigned char *sram_data;\r
1415                 if (PicoMCD&1) {\r
1416                         sram_size = 0x2000;\r
1417                         sram_data = Pico_mcd->bram;\r
1418                 } else {\r
1419                         sram_size = SRam.end-SRam.start+1;\r
1420                         if(SRam.reg_back & 4) sram_size=0x2000;\r
1421                         sram_data = SRam.data;\r
1422                 }\r
1423                 if(!sram_data) return 0; // SRam forcefully disabled for this game\r
1424 \r
1425                 if(load) {\r
1426                         sramFile = fopen(saveFname, "rb");\r
1427                         if(!sramFile) return -1;\r
1428                         fread(sram_data, 1, sram_size, sramFile);\r
1429                         fclose(sramFile);\r
1430                 } else {\r
1431                         // sram save needs some special processing\r
1432                         // see if we have anything to save\r
1433                         for(; sram_size > 0; sram_size--)\r
1434                                 if(sram_data[sram_size-1]) break;\r
1435 \r
1436                         if(sram_size) {\r
1437                                 sramFile = fopen(saveFname, "wb");\r
1438                                 ret = fwrite(sram_data, 1, sram_size, sramFile);\r
1439                                 ret = (ret != sram_size) ? -1 : 0;\r
1440                                 fclose(sramFile);\r
1441                                 sync();\r
1442                         }\r
1443                 }\r
1444                 return ret;\r
1445         }\r
1446         else\r
1447         {\r
1448                 void *PmovFile = NULL;\r
1449                 if (strcmp(saveFname + strlen(saveFname) - 3, ".gz") == 0) {\r
1450                         if( (PmovFile = gzopen(saveFname, load ? "rb" : "wb")) ) {\r
1451                                 emu_set_save_cbs(1);\r
1452                                 if(!load) gzsetparams(PmovFile, 9, Z_DEFAULT_STRATEGY);\r
1453                         }\r
1454                 }\r
1455                 else\r
1456                 {\r
1457                         if( (PmovFile = fopen(saveFname, load ? "rb" : "wb")) ) {\r
1458                                 emu_set_save_cbs(0);\r
1459                         }\r
1460                 }\r
1461                 if(PmovFile) {\r
1462                         ret = PmovState(load ? 6 : 5, PmovFile);\r
1463                         areaClose(PmovFile);\r
1464                         PmovFile = 0;\r
1465                         if (!load) sync();\r
1466                         else Pico.m.dirtyPal=1;\r
1467                 }\r
1468                 else    ret = -1;\r
1469                 if (!ret)\r
1470                         strcpy(noticeMsg, load ? "GAME LOADED  " : "GAME SAVED   ");\r
1471                 else\r
1472                 {\r
1473                         strcpy(noticeMsg, load ? "LOAD FAILED  " : "SAVE FAILED  ");\r
1474                         ret = -1;\r
1475                 }\r
1476 \r
1477                 gettimeofday(&noticeMsgTime, 0);\r
1478                 return ret;\r
1479         }\r
1480 }\r