giz port, restructuring
[libpicofe.git] / gp2x / emu.c
1 // (c) Copyright 2006-2007 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 "../common/arm_utils.h"\r
22 #include "../common/fonts.h"\r
23 #include "../common/emu.h"\r
24 #include "cpuctrl.h"\r
25 \r
26 #include <Pico/PicoInt.h>\r
27 #include <Pico/Patch.h>\r
28 #include <zlib/zlib.h>\r
29 \r
30 //#define PFRAMES\r
31 \r
32 #ifdef BENCHMARK\r
33 #define OSD_FPS_X 220\r
34 #else\r
35 #define OSD_FPS_X 260\r
36 #endif\r
37 \r
38 \r
39 int engineState;\r
40 int select_exits = 0;\r
41 \r
42 char romFileName[PATH_MAX];\r
43 \r
44 extern int crashed_940;\r
45 \r
46 static short sndBuffer[2*44100/50];\r
47 static struct timeval noticeMsgTime = { 0, 0 }; // when started showing\r
48 static int osd_fps_x;\r
49 static int combo_keys = 0, combo_acts = 0;      // keys and actions which need button combos\r
50 static int gp2x_old_gamma = 100;\r
51 char noticeMsg[64];                     // notice msg to draw\r
52 unsigned char *PicoDraw2FB = NULL;  // temporary buffer for alt renderer\r
53 int reset_timing = 0;\r
54 \r
55 static void emu_msg_cb(const char *msg);\r
56 static void emu_msg_tray_open(void);\r
57 \r
58 \r
59 void emu_noticeMsgUpdated(void)\r
60 {\r
61         gettimeofday(&noticeMsgTime, 0);\r
62 }\r
63 \r
64 void emu_getMainDir(char *dst, int len)\r
65 {\r
66         extern char **g_argv;\r
67         int j;\r
68 \r
69         strncpy(dst, g_argv[0], len);\r
70         len -= 32; // reserve\r
71         if (len < 0) len = 0;\r
72         dst[len] = 0;\r
73         for (j = strlen(dst); j > 0; j--)\r
74                 if (dst[j] == '/') { dst[j+1] = 0; break; }\r
75 }\r
76 \r
77 void emu_Init(void)\r
78 {\r
79         // make temp buffer for alt renderer\r
80         PicoDraw2FB = malloc((8+320)*(8+240+8));\r
81         if (!PicoDraw2FB)\r
82         {\r
83                 printf("PicoDraw2FB == 0\n");\r
84         }\r
85 \r
86         // make dirs for saves, cfgs, etc.\r
87         mkdir("mds", 0777);\r
88         mkdir("srm", 0777);\r
89         mkdir("brm", 0777);\r
90         mkdir("cfg", 0777);\r
91 \r
92         PicoInit();\r
93         PicoMessage = emu_msg_cb;\r
94         PicoMCDopenTray = emu_msg_tray_open;\r
95         PicoMCDcloseTray = menu_loop_tray;\r
96 }\r
97 \r
98 \r
99 static void find_combos(void)\r
100 {\r
101         int act, u;\r
102 \r
103         // find out which keys and actions are combos\r
104         combo_keys = combo_acts = 0;\r
105         for (act = 0; act < 32; act++)\r
106         {\r
107                 int keyc = 0;\r
108                 if (act == 16) continue; // player2 flag\r
109                 for (u = 0; u < 32; u++)\r
110                 {\r
111                         if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;\r
112                 }\r
113                 if (keyc > 1)\r
114                 {\r
115                         // loop again and mark those keys and actions as combo\r
116                         for (u = 0; u < 32; u++)\r
117                         {\r
118                                 if (currentConfig.KeyBinds[u] & (1 << act)) {\r
119                                         combo_keys |= 1 << u;\r
120                                         combo_acts |= 1 << act;\r
121                                 }\r
122                         }\r
123                 }\r
124         }\r
125         // printf("combo keys/acts: %08x %08x\n", combo_keys, combo_acts);\r
126 }\r
127 \r
128 \r
129 static void scaling_update(void)\r
130 {\r
131         PicoOpt &= ~0x4100;\r
132         switch (currentConfig.scaling) {\r
133                 default: break; // off\r
134                 case 1:  // hw hor\r
135                 case 2:  PicoOpt |=  0x0100; break; // hw hor+vert\r
136                 case 3:  PicoOpt |=  0x4000; break; // sw hor\r
137         }\r
138 }\r
139 \r
140 \r
141 void emu_Deinit(void)\r
142 {\r
143         // save SRAM\r
144         if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
145                 emu_SaveLoadGame(0, 1);\r
146                 SRam.changed = 0;\r
147         }\r
148 \r
149         if (!(currentConfig.EmuOpt & 0x20)) {\r
150                 FILE *f = fopen(PicoConfigFile, "r+b");\r
151                 if (!f) emu_WriteConfig(0);\r
152                 else {\r
153                         // if we already have config, reload it, except last ROM\r
154                         fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);\r
155                         fread(&currentConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);\r
156                         fseek(f, 0, SEEK_SET);\r
157                         fwrite(&currentConfig, 1, sizeof(currentConfig), f);\r
158                         fflush(f);\r
159                         fclose(f);\r
160 #ifndef NO_SYNC\r
161                         sync();\r
162 #endif\r
163                 }\r
164         }\r
165 \r
166         free(PicoDraw2FB);\r
167 \r
168         PicoExit();\r
169 \r
170         // restore gamma\r
171         if (gp2x_old_gamma != 100)\r
172                 set_gamma(100, 0);\r
173 }\r
174 \r
175 void emu_setDefaultConfig(void)\r
176 {\r
177         memset(&currentConfig, 0, sizeof(currentConfig));\r
178         currentConfig.lastRomFile[0] = 0;\r
179         currentConfig.EmuOpt  = 0x1f | 0x600; // | confirm_save, cd_leds\r
180         currentConfig.PicoOpt = 0x0f | 0xe00; // | use_940, cd_pcm, cd_cdda\r
181         currentConfig.PsndRate = 22050; // 44100;\r
182         currentConfig.PicoRegion = 0; // auto\r
183         currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP\r
184         currentConfig.Frameskip = -1; // auto\r
185         currentConfig.CPUclock = 200;\r
186         currentConfig.volume = 50;\r
187         currentConfig.KeyBinds[ 0] = 1<<0; // SACB RLDU\r
188         currentConfig.KeyBinds[ 4] = 1<<1;\r
189         currentConfig.KeyBinds[ 2] = 1<<2;\r
190         currentConfig.KeyBinds[ 6] = 1<<3;\r
191         currentConfig.KeyBinds[14] = 1<<4;\r
192         currentConfig.KeyBinds[13] = 1<<5;\r
193         currentConfig.KeyBinds[12] = 1<<6;\r
194         currentConfig.KeyBinds[ 8] = 1<<7;\r
195         currentConfig.KeyBinds[15] = 1<<26; // switch rend\r
196         currentConfig.KeyBinds[10] = 1<<27; // save state\r
197         currentConfig.KeyBinds[11] = 1<<28; // load state\r
198         currentConfig.KeyBinds[23] = 1<<29; // vol up\r
199         currentConfig.KeyBinds[22] = 1<<30; // vol down\r
200         currentConfig.gamma = 100;\r
201         currentConfig.PicoCDBuffers = 64;\r
202         currentConfig.scaling = 0;\r
203 }\r
204 \r
205 void osd_text(int x, int y, const char *text)\r
206 {\r
207         int len = strlen(text)*8;\r
208 \r
209         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
210                 int *p, i, h;\r
211                 x &= ~3; // align x\r
212                 len = (len+3) >> 2;\r
213                 for (h = 0; h < 8; h++) {\r
214                         p = (int *) ((unsigned char *) gp2x_screen+x+320*(y+h));\r
215                         for (i = len; i; i--, p++) *p = 0xe0e0e0e0;\r
216                 }\r
217                 emu_textOut8(x, y, text);\r
218         } else {\r
219                 int *p, i, h;\r
220                 x &= ~1; // align x\r
221                 len = (len+1) >> 1;\r
222                 for (h = 0; h < 8; h++) {\r
223                         p = (int *) ((unsigned short *) gp2x_screen+x+320*(y+h));\r
224                         for (i = len; i; i--, p++) *p = (*p>>2)&0x39e7;\r
225                 }\r
226                 emu_textOut16(x, y, text);\r
227         }\r
228 }\r
229 \r
230 static void cd_leds(void)\r
231 {\r
232         // mmu problems?\r
233 //      static\r
234         int old_reg;\r
235 //      if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change\r
236         old_reg = Pico_mcd->s68k_regs[0];\r
237 \r
238         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
239                 // 8-bit modes\r
240                 unsigned int col_g = (old_reg & 2) ? 0xc0c0c0c0 : 0xe0e0e0e0;\r
241                 unsigned int col_r = (old_reg & 1) ? 0xd0d0d0d0 : 0xe0e0e0e0;\r
242                 *(unsigned int *)((char *)gp2x_screen + 320*2+ 4) =\r
243                 *(unsigned int *)((char *)gp2x_screen + 320*3+ 4) =\r
244                 *(unsigned int *)((char *)gp2x_screen + 320*4+ 4) = col_g;\r
245                 *(unsigned int *)((char *)gp2x_screen + 320*2+12) =\r
246                 *(unsigned int *)((char *)gp2x_screen + 320*3+12) =\r
247                 *(unsigned int *)((char *)gp2x_screen + 320*4+12) = col_r;\r
248         } else {\r
249                 // 16-bit modes\r
250                 unsigned int *p = (unsigned int *)((short *)gp2x_screen + 320*2+4);\r
251                 unsigned int col_g = (old_reg & 2) ? 0x06000600 : 0;\r
252                 unsigned int col_r = (old_reg & 1) ? 0xc000c000 : 0;\r
253                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
254                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
255                 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 320/2 - 12/2;\r
256         }\r
257 }\r
258 \r
259 static int EmuScan16(unsigned int num, void *sdata)\r
260 {\r
261         if (!(Pico.video.reg[1]&8)) num += 8;\r
262         DrawLineDest = (unsigned short *) gp2x_screen + 320*(num+1);\r
263 \r
264         return 0;\r
265 }\r
266 \r
267 static int EmuScan8(unsigned int num, void *sdata)\r
268 {\r
269         if (!(Pico.video.reg[1]&8)) num += 8;\r
270         DrawLineDest = (unsigned char *)  gp2x_screen + 320*(num+1);\r
271 \r
272         return 0;\r
273 }\r
274 \r
275 int localPal[0x100];\r
276 static void (*vidCpyM2)(void *dest, void *src) = NULL;\r
277 \r
278 static void blit(const char *fps, const char *notice)\r
279 {\r
280         int emu_opt = currentConfig.EmuOpt;\r
281 \r
282         if (PicoOpt&0x10) {\r
283                 // 8bit fast renderer\r
284                 if (Pico.m.dirtyPal) {\r
285                         Pico.m.dirtyPal = 0;\r
286                         vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
287                         // feed new palette to our device\r
288                         gp2x_video_setpalette(localPal, 0x40);\r
289                 }\r
290                 vidCpyM2((unsigned char *)gp2x_screen+320*8, PicoDraw2FB+328*8);\r
291         } else if (!(emu_opt&0x80)) {\r
292                 // 8bit accurate renderer\r
293                 if (Pico.m.dirtyPal) {\r
294                         Pico.m.dirtyPal = 0;\r
295                         if(Pico.video.reg[0xC]&8) { // shadow/hilight mode\r
296                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
297                                 vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);\r
298                                 vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40);\r
299                                 blockcpy(localPal+0xc0, localPal+0x40, 0x40*4);\r
300                                 localPal[0xc0] = 0x0000c000;\r
301                                 localPal[0xd0] = 0x00c00000;\r
302                                 localPal[0xe0] = 0x00000000; // reserved pixels for OSD\r
303                                 localPal[0xf0] = 0x00ffffff;\r
304                                 gp2x_video_setpalette(localPal, 0x100);\r
305                         } else if (rendstatus & 0x20) { // mid-frame palette changes\r
306                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
307                                 vidConvCpyRGB32(localPal+0x40, HighPal, 0x40);\r
308                                 vidConvCpyRGB32(localPal+0x80, HighPal+0x40, 0x40);\r
309                                 gp2x_video_setpalette(localPal, 0xc0);\r
310                         } else {\r
311                                 vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
312                                 gp2x_video_setpalette(localPal, 0x40);\r
313                         }\r
314                 }\r
315         }\r
316 \r
317         if (notice || (emu_opt & 2)) {\r
318                 int h = 232;\r
319                 if (currentConfig.scaling == 2 && !(Pico.video.reg[1]&8)) h -= 8;\r
320                 if (notice) osd_text(4, h, notice);\r
321                 if (emu_opt & 2)\r
322                         osd_text(osd_fps_x, h, fps);\r
323         }\r
324         if ((emu_opt & 0x400) && (PicoMCD & 1))\r
325                 cd_leds();\r
326 \r
327         //gp2x_video_wait_vsync();\r
328         gp2x_video_flip();\r
329 \r
330         if (!(PicoOpt&0x10)) {\r
331                 if (!(Pico.video.reg[1]&8)) {\r
332                         if (currentConfig.EmuOpt&0x80) {\r
333                                 DrawLineDest = (unsigned short *) gp2x_screen + 320*8;\r
334                         } else {\r
335                                 DrawLineDest = (unsigned char  *) gp2x_screen + 320*8;\r
336                         }\r
337                 } else {\r
338                         DrawLineDest = gp2x_screen;\r
339                 }\r
340         }\r
341 }\r
342 \r
343 \r
344 // clears whole screen or just the notice area (in all buffers)\r
345 static void clearArea(int full)\r
346 {\r
347         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
348                 // 8-bit renderers\r
349                 if (full) gp2x_memset_all_buffers(0, 0xe0, 320*240);\r
350                 else      gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
351         } else {\r
352                 // 16bit accurate renderer\r
353                 if (full) gp2x_memset_all_buffers(0, 0, 320*240*2);\r
354                 else      gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
355         }\r
356 }\r
357 \r
358 \r
359 static void vidResetMode(void)\r
360 {\r
361         if (PicoOpt&0x10) {\r
362                 gp2x_video_changemode(8);\r
363         } else if (currentConfig.EmuOpt&0x80) {\r
364                 gp2x_video_changemode(16);\r
365                 PicoDrawSetColorFormat(1);\r
366                 PicoScan = EmuScan16;\r
367                 PicoScan(0, 0);\r
368         } else {\r
369                 gp2x_video_changemode(8);\r
370                 PicoDrawSetColorFormat(2);\r
371                 PicoScan = EmuScan8;\r
372                 PicoScan(0, 0);\r
373         }\r
374         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
375                 // setup pal for 8-bit modes\r
376                 localPal[0xc0] = 0x0000c000; // MCD LEDs\r
377                 localPal[0xd0] = 0x00c00000;\r
378                 localPal[0xe0] = 0x00000000; // reserved pixels for OSD\r
379                 localPal[0xf0] = 0x00ffffff;\r
380                 gp2x_video_setpalette(localPal, 0x100);\r
381                 gp2x_memset_all_buffers(0, 0xe0, 320*240);\r
382                 gp2x_video_flip();\r
383         }\r
384         Pico.m.dirtyPal = 1;\r
385         // reset scaling\r
386         if (currentConfig.scaling == 2 && !(Pico.video.reg[1]&8))\r
387              gp2x_video_RGB_setscaling(8, (PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 224);\r
388         else gp2x_video_RGB_setscaling(0, (PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 240);\r
389 }\r
390 \r
391 \r
392 static void emu_msg_cb(const char *msg)\r
393 {\r
394         if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
395                 // 8-bit renderers\r
396                 gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
397                 osd_text(4, 232, msg);\r
398                 gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232, 320*232, 320*8);\r
399         } else {\r
400                 // 16bit accurate renderer\r
401                 gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
402                 osd_text(4, 232, msg);\r
403                 gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232*2, 320*232*2, 320*8*2);\r
404         }\r
405         gettimeofday(&noticeMsgTime, 0);\r
406         noticeMsgTime.tv_sec -= 2;\r
407 \r
408         /* assumption: emu_msg_cb gets called only when something slow is about to happen */\r
409         reset_timing = 1;\r
410 }\r
411 \r
412 static void emu_state_cb(const char *str)\r
413 {\r
414         clearArea(0);\r
415         blit("", str);\r
416 }\r
417 \r
418 static void emu_msg_tray_open(void)\r
419 {\r
420         strcpy(noticeMsg, "CD tray opened");\r
421         gettimeofday(&noticeMsgTime, 0);\r
422 }\r
423 \r
424 static void RunEvents(unsigned int which)\r
425 {\r
426         if(which & 0x1800) { // save or load (but not both)\r
427                 int do_it = 1;\r
428                 if ( emu_checkSaveFile(state_slot) &&\r
429                                 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) ||   // load\r
430                                  (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) { // save\r
431                         unsigned long keys;\r
432                         blit("", (which & 0x1000) ? "LOAD STATE? (Y=yes, X=no)" : "OVERWRITE SAVE? (Y=yes, X=no)");\r
433                         while( !((keys = gp2x_joystick_read(1)) & (GP2X_X|GP2X_Y)) )\r
434                                 usleep(50*1024);\r
435                         if (keys & GP2X_X) do_it = 0;\r
436                         clearArea(0);\r
437                 }\r
438                 if (do_it) {\r
439                         osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");\r
440                         PicoStateProgressCB = emu_state_cb;\r
441                         gp2x_memcpy_all_buffers(gp2x_screen, 0, 320*240*2);\r
442                         emu_SaveLoadGame((which & 0x1000) >> 12, 0);\r
443                         PicoStateProgressCB = NULL;\r
444                 }\r
445 \r
446                 reset_timing = 1;\r
447         }\r
448         if(which & 0x0400) { // switch renderer\r
449                 if      (  PicoOpt&0x10)             { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }\r
450                 else if (!(currentConfig.EmuOpt&0x80)) PicoOpt|= 0x10;\r
451                 else   currentConfig.EmuOpt &= ~0x80;\r
452 \r
453                 vidResetMode();\r
454 \r
455                 if (PicoOpt&0x10) {\r
456                         strcpy(noticeMsg, " 8bit fast renderer");\r
457                 } else if (currentConfig.EmuOpt&0x80) {\r
458                         strcpy(noticeMsg, "16bit accurate renderer");\r
459                 } else {\r
460                         strcpy(noticeMsg, " 8bit accurate renderer");\r
461                 }\r
462 \r
463                 gettimeofday(&noticeMsgTime, 0);\r
464         }\r
465         if(which & 0x0300) {\r
466                 if(which&0x0200) {\r
467                         state_slot -= 1;\r
468                         if(state_slot < 0) state_slot = 9;\r
469                 } else {\r
470                         state_slot += 1;\r
471                         if(state_slot > 9) state_slot = 0;\r
472                 }\r
473                 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");\r
474                 gettimeofday(&noticeMsgTime, 0);\r
475         }\r
476         if(which & 0x0080) {\r
477                 engineState = PGS_Menu;\r
478         }\r
479 }\r
480 \r
481 \r
482 static void updateKeys(void)\r
483 {\r
484         unsigned long keys, allActions[2] = { 0, 0 }, events;\r
485         static unsigned long prevEvents = 0;\r
486         int joy, i;\r
487 \r
488         keys = gp2x_joystick_read(0);\r
489         if (keys & GP2X_SELECT) {\r
490                 engineState = select_exits ? PGS_Quit : PGS_Menu;\r
491                 // wait until select is released, so menu would not resume game\r
492                 while (gp2x_joystick_read(1) & GP2X_SELECT) usleep(50*1000);\r
493         }\r
494 \r
495         keys &= CONFIGURABLE_KEYS;\r
496 \r
497         for (i = 0; i < 32; i++)\r
498         {\r
499                 if (keys & (1 << i)) {\r
500                         int pl, acts = currentConfig.KeyBinds[i];\r
501                         if (!acts) continue;\r
502                         pl = (acts >> 16) & 1;\r
503                         if (combo_keys & (1 << i)) {\r
504                                 int u = i+1, acts_c = acts & combo_acts;\r
505                                 // let's try to find the other one\r
506                                 if (acts_c)\r
507                                         for (; u < 32; u++)\r
508                                                 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {\r
509                                                         allActions[pl] |= acts_c;\r
510                                                         keys &= ~((1 << i) | (1 << u));\r
511                                                         break;\r
512                                                 }\r
513                                 // add non-combo actions if combo ones were not found\r
514                                 if (!acts_c || u == 32)\r
515                                         allActions[pl] |= acts & ~combo_acts;\r
516                         } else {\r
517                                 allActions[pl] |= acts;\r
518                         }\r
519                 }\r
520         }\r
521 \r
522         // add joy inputs\r
523         if (num_of_joys > 0)\r
524         {\r
525                 gp2x_usbjoy_update();\r
526                 for (joy = 0; joy < num_of_joys; joy++) {\r
527                         int keys = gp2x_usbjoy_check2(joy);\r
528                         for (i = 0; i < 32; i++) {\r
529                                 if (keys & (1 << i)) {\r
530                                         int acts = currentConfig.JoyBinds[joy][i];\r
531                                         int pl = (acts >> 16) & 1;\r
532                                         allActions[pl] |= acts;\r
533                                 }\r
534                         }\r
535                 }\r
536         }\r
537 \r
538         PicoPad[0] = (unsigned short) allActions[0];\r
539         PicoPad[1] = (unsigned short) allActions[1];\r
540 \r
541         events = (allActions[0] | allActions[1]) >> 16;\r
542 \r
543         // volume is treated in special way and triggered every frame\r
544         if(events & 0x6000) {\r
545                 int vol = currentConfig.volume;\r
546                 if (events & 0x2000) {\r
547                         if (vol < 99) vol++;\r
548                 } else {\r
549                         if (vol >  0) vol--;\r
550                 }\r
551                 gp2x_sound_volume(vol, vol);\r
552                 sprintf(noticeMsg, "VOL: %02i", vol);\r
553                 gettimeofday(&noticeMsgTime, 0);\r
554                 currentConfig.volume = vol;\r
555         }\r
556 \r
557         events &= ~prevEvents;\r
558         if (events) RunEvents(events);\r
559         if (movie_data) emu_updateMovie();\r
560 \r
561         prevEvents = (allActions[0] | allActions[1]) >> 16;\r
562 }\r
563 \r
564 \r
565 static void updateSound(int len)\r
566 {\r
567         if (PicoOpt&8) len<<=1;\r
568 \r
569         /* avoid writing audio when lagging behind to prevent audio lag */\r
570         if (PicoSkipFrame != 2)\r
571                 gp2x_sound_write(PsndOut, len<<1);\r
572 }\r
573 \r
574 \r
575 static void SkipFrame(int do_audio)\r
576 {\r
577         PicoSkipFrame=do_audio ? 1 : 2;\r
578         PicoFrame();\r
579         PicoSkipFrame=0;\r
580 }\r
581 \r
582 \r
583 void emu_forcedFrame(void)\r
584 {\r
585         int po_old = PicoOpt;\r
586         int eo_old = currentConfig.EmuOpt;\r
587 \r
588         PicoOpt &= ~0x0010;\r
589         PicoOpt |=  0x4080; // soft_scale | acc_sprites\r
590         currentConfig.EmuOpt |= 0x80;\r
591 \r
592         //vidResetMode();\r
593         PicoDrawSetColorFormat(1);\r
594         PicoScan = EmuScan16;\r
595         PicoScan(0, 0);\r
596         Pico.m.dirtyPal = 1;\r
597         PicoFrameDrawOnly();\r
598 \r
599 /*\r
600         if (!(Pico.video.reg[12]&1)) {\r
601                 vidCpyM2 = vidCpyM2_32col;\r
602                 clearArea(1);\r
603         } else  vidCpyM2 = vidCpyM2_40col;\r
604 \r
605         vidCpyM2((unsigned char *)gp2x_screen+320*8, PicoDraw2FB+328*8);\r
606         vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
607         gp2x_video_setpalette(localPal, 0x40);\r
608 */\r
609         PicoOpt = po_old;\r
610         currentConfig.EmuOpt = eo_old;\r
611 }\r
612 \r
613 static void simpleWait(int thissec, int lim_time)\r
614 {\r
615         struct timeval tval;\r
616 \r
617         spend_cycles(1024);\r
618         gettimeofday(&tval, 0);\r
619         if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
620 \r
621         while(tval.tv_usec < lim_time)\r
622         {\r
623                 spend_cycles(1024);\r
624                 gettimeofday(&tval, 0);\r
625                 if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
626         }\r
627 }\r
628 \r
629 \r
630 void emu_Loop(void)\r
631 {\r
632         static int gp2x_old_clock = 200;\r
633         static int PsndRate_old = 0, PicoOpt_old = 0, EmuOpt_old = 0, PsndLen_real = 0, pal_old = 0;\r
634         char fpsbuff[24]; // fps count c string\r
635         struct timeval tval; // timing\r
636         int thissec = 0, frames_done = 0, frames_shown = 0, oldmodes = 0;\r
637         int target_fps, target_frametime, lim_time, vsync_offset, i;\r
638         char *notice = 0;\r
639 \r
640         printf("entered emu_Loop()\n");\r
641 \r
642         if (gp2x_old_clock != currentConfig.CPUclock) {\r
643                 printf("changing clock to %i...", currentConfig.CPUclock); fflush(stdout);\r
644                 set_FCLK(currentConfig.CPUclock);\r
645                 gp2x_old_clock = currentConfig.CPUclock;\r
646                 printf(" done\n");\r
647         }\r
648 \r
649         if (gp2x_old_gamma != currentConfig.gamma || (EmuOpt_old&0x1000) != (currentConfig.EmuOpt&0x1000)) {\r
650                 set_gamma(currentConfig.gamma, !!(currentConfig.EmuOpt&0x1000));\r
651                 gp2x_old_gamma = currentConfig.gamma;\r
652                 printf("updated gamma to %i, A_SN's curve: %i\n", currentConfig.gamma, !!(currentConfig.EmuOpt&0x1000));\r
653         }\r
654 \r
655         if ((EmuOpt_old&0x2000) != (currentConfig.EmuOpt&0x2000)) {\r
656                 if (currentConfig.EmuOpt&0x2000)\r
657                      set_LCD_custom_rate(Pico.m.pal ? LCDR_100 : LCDR_120);\r
658                 else unset_LCD_custom_rate();\r
659         }\r
660 \r
661         EmuOpt_old = currentConfig.EmuOpt;\r
662         fpsbuff[0] = 0;\r
663 \r
664         // make sure we are in correct mode\r
665         vidResetMode();\r
666         scaling_update();\r
667         Pico.m.dirtyPal = 1;\r
668         oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;\r
669         find_combos();\r
670 \r
671         // pal/ntsc might have changed, reset related stuff\r
672         target_fps = Pico.m.pal ? 50 : 60;\r
673         target_frametime = 1000000/target_fps;\r
674         reset_timing = 1;\r
675 \r
676         // prepare sound stuff\r
677         if(currentConfig.EmuOpt & 4) {\r
678                 int snd_excess_add;\r
679                 if (PsndRate != PsndRate_old || (PicoOpt&0x20b) != (PicoOpt_old&0x20b) || Pico.m.pal != pal_old ||\r
680                                 ((PicoOpt&0x200) && crashed_940)) {\r
681                         /* if 940 is turned off, we need it to be put back to sleep */\r
682                         if (!(PicoOpt&0x200) && ((PicoOpt^PicoOpt_old)&0x200)) {\r
683                                 Reset940(1, 2);\r
684                                 Pause940(1);\r
685                         }\r
686                         sound_rerate(Pico.m.frame_count ? 1 : 0);\r
687                 }\r
688                 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;\r
689                 printf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",\r
690                         PsndRate, PsndLen, snd_excess_add, (PicoOpt&8)>>3, Pico.m.pal);\r
691                 gp2x_start_sound(PsndRate, 16, (PicoOpt&8)>>3);\r
692                 gp2x_sound_volume(currentConfig.volume, currentConfig.volume);\r
693                 PicoWriteSound = updateSound;\r
694                 memset(sndBuffer, 0, sizeof(sndBuffer));\r
695                 PsndOut = sndBuffer;\r
696                 PsndRate_old = PsndRate;\r
697                 PsndLen_real = PsndLen;\r
698                 PicoOpt_old  = PicoOpt;\r
699                 pal_old = Pico.m.pal;\r
700         } else {\r
701                 PsndOut = 0;\r
702         }\r
703 \r
704         // prepare CD buffer\r
705         if (PicoMCD & 1) PicoCDBufferInit();\r
706 \r
707         // calc vsync offset to sync timing code with vsync\r
708         if (currentConfig.EmuOpt&0x2000) {\r
709                 gettimeofday(&tval, 0);\r
710                 gp2x_video_wait_vsync();\r
711                 gettimeofday(&tval, 0);\r
712                 vsync_offset = tval.tv_usec;\r
713                 while (vsync_offset >= target_frametime)\r
714                         vsync_offset -= target_frametime;\r
715                 if (!vsync_offset) vsync_offset++;\r
716                 printf("vsync_offset: %i\n", vsync_offset);\r
717         } else\r
718                 vsync_offset = 0;\r
719 \r
720         // loop?\r
721         while (engineState == PGS_Running)\r
722         {\r
723                 int modes;\r
724 \r
725                 gettimeofday(&tval, 0);\r
726                 if(reset_timing) {\r
727                         reset_timing = 0;\r
728                         thissec = tval.tv_sec;\r
729                         frames_shown = frames_done = tval.tv_usec/target_frametime;\r
730                 }\r
731 \r
732                 // show notice message?\r
733                 if(noticeMsgTime.tv_sec) {\r
734                         static int noticeMsgSum;\r
735                         if((tval.tv_sec*1000000+tval.tv_usec) - (noticeMsgTime.tv_sec*1000000+noticeMsgTime.tv_usec) > 2000000) { // > 2.0 sec\r
736                                 noticeMsgTime.tv_sec = noticeMsgTime.tv_usec = 0;\r
737                                 clearArea(0);\r
738                                 notice = 0;\r
739                         } else {\r
740                                 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];\r
741                                 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }\r
742                                 notice = noticeMsg;\r
743                         }\r
744                 }\r
745 \r
746                 // check for mode changes\r
747                 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);\r
748                 if (modes != oldmodes) {\r
749                         int scalex = 320;\r
750                         osd_fps_x = OSD_FPS_X;\r
751                         if (modes & 4) {\r
752                                 vidCpyM2 = vidCpyM2_40col;\r
753                         } else {\r
754                                 if (PicoOpt & 0x100) {\r
755                                         vidCpyM2 = vidCpyM2_32col_nobord;\r
756                                         scalex = 256;\r
757                                         osd_fps_x = OSD_FPS_X - 64;\r
758                                 } else {\r
759                                         vidCpyM2 = vidCpyM2_32col;\r
760                                 }\r
761                         }\r
762                         if (currentConfig.scaling == 2 && !(modes&8)) // want vertical scaling and game is not in 240 line mode\r
763                              gp2x_video_RGB_setscaling(8, scalex, 224);\r
764                         else gp2x_video_RGB_setscaling(0, scalex, 240);\r
765                         oldmodes = modes;\r
766                         clearArea(1);\r
767                 }\r
768 \r
769                 // second changed?\r
770                 if(thissec != tval.tv_sec) {\r
771 #ifdef BENCHMARK\r
772                         static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];\r
773                         if(++bench == 10) {\r
774                                 bench = 0;\r
775                                 bench_fps_s = bench_fps;\r
776                                 bf[bfp++ & 3] = bench_fps;\r
777                                 bench_fps = 0;\r
778                         }\r
779                         bench_fps += frames_shown;\r
780                         sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);\r
781 #else\r
782                         if(currentConfig.EmuOpt & 2)\r
783                                 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);\r
784 #endif\r
785                         thissec = tval.tv_sec;\r
786 \r
787                         if(PsndOut == 0 && currentConfig.Frameskip >= 0) {\r
788                                 frames_done = frames_shown = 0;\r
789                         } else {\r
790                                 // it is quite common for this implementation to leave 1 fame unfinished\r
791                                 // when second changes, but we don't want buffer to starve.\r
792                                 if(PsndOut && frames_done < target_fps && frames_done > target_fps-5) {\r
793                                         updateKeys();\r
794                                         SkipFrame(1); frames_done++;\r
795                                 }\r
796 \r
797                                 frames_done  -= target_fps; if (frames_done  < 0) frames_done  = 0;\r
798                                 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;\r
799                                 if (frames_shown > frames_done) frames_shown = frames_done;\r
800                         }\r
801                 }\r
802 #ifdef PFRAMES\r
803                 sprintf(fpsbuff, "%i", Pico.m.frame_count);\r
804 #endif\r
805 \r
806                 lim_time = (frames_done+1) * target_frametime + vsync_offset;\r
807                 if(currentConfig.Frameskip >= 0) { // frameskip enabled\r
808                         for(i = 0; i < currentConfig.Frameskip; i++) {\r
809                                 updateKeys();\r
810                                 SkipFrame(1); frames_done++;\r
811                                 if (PsndOut) { // do framelimitting if sound is enabled\r
812                                         gettimeofday(&tval, 0);\r
813                                         if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
814                                         if(tval.tv_usec < lim_time) { // we are too fast\r
815                                                 simpleWait(thissec, lim_time);\r
816                                         }\r
817                                 }\r
818                                 lim_time += target_frametime;\r
819                         }\r
820                 } else if(tval.tv_usec > lim_time) { // auto frameskip\r
821                         // no time left for this frame - skip\r
822                         if (tval.tv_usec - lim_time >= 300000) {\r
823                                 /* something caused a slowdown for us (disk access? cache flush?)\r
824                                  * try to recover by resetting timing... */\r
825                                 reset_timing = 1;\r
826                                 continue;\r
827                         }\r
828                         updateKeys();\r
829                         SkipFrame(tval.tv_usec < lim_time+target_frametime*2); frames_done++;\r
830                         continue;\r
831                 }\r
832 \r
833                 updateKeys();\r
834                 PicoFrame();\r
835 \r
836 #if 0\r
837 if (Pico.m.frame_count == 31563) {\r
838         FILE *f;\r
839         f = fopen("ram_p.bin", "wb");\r
840         if (!f) { printf("!f\n"); exit(1); }\r
841         fwrite(Pico.ram, 1, 0x10000, f);\r
842         fclose(f);\r
843         exit(0);\r
844 }\r
845 #endif\r
846 #if 0\r
847                 // debug\r
848                 {\r
849                         #define BYTE unsigned char\r
850                         #define WORD unsigned short\r
851                         struct\r
852                         {\r
853                                 BYTE IDLength;        /* 00h  Size of Image ID field */\r
854                                 BYTE ColorMapType;    /* 01h  Color map type */\r
855                                 BYTE ImageType;       /* 02h  Image type code */\r
856                                 WORD CMapStart;       /* 03h  Color map origin */\r
857                                 WORD CMapLength;      /* 05h  Color map length */\r
858                                 BYTE CMapDepth;       /* 07h  Depth of color map entries */\r
859                                 WORD XOffset;         /* 08h  X origin of image */\r
860                                 WORD YOffset;         /* 0Ah  Y origin of image */\r
861                                 WORD Width;           /* 0Ch  Width of image */\r
862                                 WORD Height;          /* 0Eh  Height of image */\r
863                                 BYTE PixelDepth;      /* 10h  Image pixel size */\r
864                                 BYTE ImageDescriptor; /* 11h  Image descriptor byte */\r
865                         } __attribute__((packed)) TGAHEAD;\r
866                         static unsigned short oldscr[320*240];\r
867                         FILE *f; char name[128]; int i;\r
868 \r
869                         memset(&TGAHEAD, 0, sizeof(TGAHEAD));\r
870                         TGAHEAD.ImageType = 2;\r
871                         TGAHEAD.Width = 320;\r
872                         TGAHEAD.Height = 240;\r
873                         TGAHEAD.PixelDepth = 16;\r
874                         TGAHEAD.ImageDescriptor = 2<<4; // image starts at top-left\r
875 \r
876                         #define CONV(X) (((X>>1)&0x7fe0)|(X&0x1f)) // 555?\r
877 \r
878                         for (i = 0; i < 320*240; i++)\r
879                                 if(oldscr[i] != CONV(((unsigned short *)gp2x_screen)[i])) break;\r
880                         if (i < 320*240)\r
881                         {\r
882                                 for (i = 0; i < 320*240; i++)\r
883                                         oldscr[i] = CONV(((unsigned short *)gp2x_screen)[i]);\r
884                                 sprintf(name, "%05i.tga", Pico.m.frame_count);\r
885                                 f = fopen(name, "wb");\r
886                                 if (!f) { printf("!f\n"); exit(1); }\r
887                                 fwrite(&TGAHEAD, 1, sizeof(TGAHEAD), f);\r
888                                 fwrite(oldscr, 1, 320*240*2, f);\r
889                                 fclose(f);\r
890                         }\r
891                 }\r
892 #endif\r
893 \r
894                 // check time\r
895                 gettimeofday(&tval, 0);\r
896                 if (thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
897 \r
898                 if (currentConfig.Frameskip < 0 && tval.tv_usec - lim_time >= 300000) // slowdown detection\r
899                         reset_timing = 1;\r
900                 else if (PsndOut != NULL || currentConfig.Frameskip < 0)\r
901                 {\r
902                         // sleep or vsync if we are still too fast\r
903                         // usleep sleeps for ~20ms minimum, so it is not a solution here\r
904                         if(tval.tv_usec < lim_time)\r
905                         {\r
906                                 // we are too fast\r
907                                 if (vsync_offset) {\r
908                                         if (lim_time - tval.tv_usec > target_frametime/2)\r
909                                                 simpleWait(thissec, lim_time - target_frametime/4);\r
910                                         gp2x_video_wait_vsync();\r
911                                 } else {\r
912                                         simpleWait(thissec, lim_time);\r
913                                 }\r
914                         }\r
915                 }\r
916 \r
917                 blit(fpsbuff, notice);\r
918 \r
919                 frames_done++; frames_shown++;\r
920         }\r
921 \r
922 \r
923         if (PicoMCD & 1) PicoCDBufferFree();\r
924 \r
925         // save SRAM\r
926         if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
927                 emu_state_cb("Writing SRAM/BRAM..");\r
928                 emu_SaveLoadGame(0, 1);\r
929                 SRam.changed = 0;\r
930         }\r
931 \r
932         // if in 8bit mode, generate 16bit image for menu background\r
933         if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80))\r
934                 emu_forcedFrame();\r
935 }\r
936 \r
937 \r
938 void emu_ResetGame(void)\r
939 {\r
940         PicoReset(0);\r
941         reset_timing = 1;\r
942 }\r
943 \r
944 \r