4 #include <sys/stat.h> // mkdir
7 #include "kgsdk/Framework.h"
8 #include "kgsdk/Framework2D.h"
9 #include "kgsdk/FrameworkAudio.h"
10 #include "../common/emu.h"
11 #include "../common/lprintf.h"
12 #include "../common/arm_utils.h"
16 #include "asm_utils.h"
18 #include <Pico/PicoInt.h>
26 // main 300K gfx-related buffer. Used by menu and renderers.
27 unsigned char gfx_buffer[321*240*2*2];
28 char romFileName[MAX_PATH];
31 unsigned char *PicoDraw2FB = gfx_buffer; // temporary buffer for alt renderer ( (8+320)*(8+240+8) )
34 static int combo_keys = 0, combo_acts = 0; // keys and actions which need button combos
35 static DWORD noticeMsgTime = 0;
36 static short *snd_cbuff = NULL;
37 static int snd_cbuf_samples = 0, snd_all_samples = 0;
40 static void blit(const char *fps, const char *notice);
41 static void clearArea(int full);
43 void emu_noticeMsgUpdated(void)
45 noticeMsgTime = GetTickCount();
48 void emu_getMainDir(char *dst, int len)
50 if (len > 0) *dst = 0;
53 static void emu_msg_cb(const char *msg)
55 if (giz_screen == NULL)
56 giz_screen = Framework2D_LockBuffer();
58 memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
59 emu_textOut16(4, 232, msg);
60 noticeMsgTime = GetTickCount() - 2000;
62 /* assumption: emu_msg_cb gets called only when something slow is about to happen */
66 static void emu_state_cb(const char *str)
68 if (giz_screen == NULL)
69 giz_screen = Framework2D_LockBuffer();
74 Framework2D_UnlockBuffer();
78 static void emu_msg_tray_open(void)
80 strcpy(noticeMsg, "CD tray opened");
81 noticeMsgTime = GetTickCount();
87 // make dirs for saves, cfgs, etc.
94 PicoMessage = emu_msg_cb;
95 PicoMCDopenTray = emu_msg_tray_open;
96 PicoMCDcloseTray = menu_loop_tray;
102 if((currentConfig.EmuOpt & 1) && SRam.changed) {
103 emu_SaveLoadGame(0, 1);
107 if (!(currentConfig.EmuOpt & 0x20)) {
108 FILE *f = fopen(PicoConfigFile, "r+b");
109 if (!f) emu_WriteConfig(0);
111 // if we already have config, reload it, except last ROM
112 fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);
113 fread(¤tConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);
114 fseek(f, 0, SEEK_SET);
115 fwrite(¤tConfig, 1, sizeof(currentConfig), f);
124 void emu_setDefaultConfig(void)
126 memset(¤tConfig, 0, sizeof(currentConfig));
127 currentConfig.lastRomFile[0] = 0;
128 currentConfig.EmuOpt = 0x1f | 0x680; // | confirm_save, cd_leds, 16bit rend
129 currentConfig.PicoOpt = 0x07 | 0xc00; // | cd_pcm, cd_cdda
130 currentConfig.PsndRate = 22050;
131 currentConfig.PicoRegion = 0; // auto
132 currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP
133 currentConfig.Frameskip = -1; // auto
134 currentConfig.volume = 50;
135 currentConfig.KeyBinds[ 2] = 1<<0; // SACB RLDU
136 currentConfig.KeyBinds[ 3] = 1<<1;
137 currentConfig.KeyBinds[ 0] = 1<<2;
138 currentConfig.KeyBinds[ 1] = 1<<3;
139 currentConfig.KeyBinds[ 5] = 1<<4;
140 currentConfig.KeyBinds[ 6] = 1<<5;
141 currentConfig.KeyBinds[ 7] = 1<<6;
142 currentConfig.KeyBinds[ 4] = 1<<7;
143 currentConfig.KeyBinds[13] = 1<<26; // switch rend
144 currentConfig.KeyBinds[ 8] = 1<<27; // save state
145 currentConfig.KeyBinds[ 9] = 1<<28; // load state
146 currentConfig.KeyBinds[12] = 1<<29; // vol up
147 currentConfig.KeyBinds[11] = 1<<30; // vol down
148 currentConfig.PicoCDBuffers = 0;
149 currentConfig.scaling = 0;
153 static int EmuScan16(unsigned int num, void *sdata)
155 if (!(Pico.video.reg[1]&8)) num += 8;
156 DrawLineDest = (unsigned short *) giz_screen + 321*(num+1);
158 if ((currentConfig.EmuOpt&0x4000) && (num&1) == (Pico.m.frame_count&1))
159 return 1; // skip next line
164 static int EmuScan8(unsigned int num, void *sdata)
166 // draw like the fast renderer
167 if (!(Pico.video.reg[1]&8)) num += 8;
168 HighCol = gfx_buffer + 328*(num+1);
173 static void osd_text(int x, int y, const char *text)
175 int len = strlen(text) * 8 / 2;
177 for (h = 0; h < 8; h++) {
178 p = (int *) ((unsigned short *) giz_screen+x+321*(y+h));
179 p = (int *) ((int)p & ~3); // align
182 emu_textOut16(x, y, text);
186 void log1(void *p1, void *p2)
188 lprintf("%p %p %p\n", p1, p2, DrawLineDest);
192 static void cd_leds(void)
194 static int old_reg = 0;
195 unsigned int col_g, col_r, *p;
197 if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change
198 old_reg = Pico_mcd->s68k_regs[0];
200 p = (unsigned int *)((short *)giz_screen + 321*2+4+2);
201 col_g = (old_reg & 2) ? 0x06000600 : 0;
202 col_r = (old_reg & 1) ? 0xc000c000 : 0;
203 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 321/2 - 12/2 + 1;
204 *p++ = col_g; p+=3; *p++ = col_r; p += 321/2 - 10/2;
205 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
209 static short localPal[0x100];
211 static void blit(const char *fps, const char *notice)
213 int emu_opt = currentConfig.EmuOpt;
217 int lines_flags = 224;
218 // 8bit fast renderer
219 if (Pico.m.dirtyPal) {
221 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
223 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
224 if (currentConfig.EmuOpt&0x4000)
225 lines_flags|=(Pico.m.frame_count&1)?0x20000:0x40000;
226 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
228 else if (!(emu_opt&0x80))
231 // 8bit accurate renderer
232 if (Pico.m.dirtyPal) {
234 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
235 if (Pico.video.reg[0xC]&8) { // shadow/hilight mode
236 //vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
237 //vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40); // TODO?
238 blockcpy(localPal+0xc0, localPal+0x40, 0x40*2);
239 localPal[0xc0] = 0x0600;
240 localPal[0xd0] = 0xc000;
241 localPal[0xe0] = 0x0000; // reserved pixels for OSD
242 localPal[0xf0] = 0xffff;
245 else if (rendstatus & 0x20) { // mid-frame palette changes
246 vidConvCpyRGB565(localPal+0x40, HighPal, 0x40);
247 vidConvCpyRGB565(localPal+0x80, HighPal+0x40, 0x40);
250 lines_flags = (Pico.video.reg[1]&8) ? 240 : 224;
251 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
252 if (currentConfig.EmuOpt&0x4000)
253 lines_flags|=(Pico.m.frame_count&1)?0x20000:0x40000;
254 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
257 if (notice || (emu_opt & 2)) {
259 if (notice) osd_text(4, h, notice);
260 if (emu_opt & 2) osd_text(OSD_FPS_X, h, fps);
263 if ((emu_opt & 0x400) && (PicoMCD & 1))
267 // clears whole screen or just the notice area (in all buffers)
268 static void clearArea(int full)
270 if (giz_screen == NULL)
271 giz_screen = Framework2D_LockBuffer();
272 if (full) memset32(giz_screen, 0, 320*240*2/4);
273 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
276 static void vidResetMode(void)
278 giz_screen = Framework2D_LockBuffer();
281 } else if (currentConfig.EmuOpt&0x80) {
282 PicoDrawSetColorFormat(1);
283 PicoScan = EmuScan16;
285 PicoDrawSetColorFormat(-1);
288 if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80)) {
289 // setup pal for 8-bit modes
290 localPal[0xc0] = 0x0600;
291 localPal[0xd0] = 0xc000;
292 localPal[0xe0] = 0x0000; // reserved pixels for OSD
293 localPal[0xf0] = 0xffff;
297 memset32(giz_screen, 0, 321*240*2/4);
298 Framework2D_UnlockBuffer();
304 static void stdbg(const char *fmt, ...)
309 sprintf(noticeMsg, "%x ", cnt++);
311 vsnprintf(noticeMsg+strlen(noticeMsg), sizeof(noticeMsg)-strlen(noticeMsg), fmt, vl);
314 noticeMsgTime = GetTickCount();
318 static void updateSound(int len)
320 if (PicoOpt&8) len<<=1;
322 snd_all_samples += len;
324 if (PsndOut - snd_cbuff >= snd_cbuf_samples)
326 if (PsndOut - snd_cbuff != snd_cbuf_samples)
327 stdbg("snd diff is %i, not %i", PsndOut - snd_cbuff, snd_cbuf_samples);
333 static void SkipFrame(void)
340 void emu_forcedFrame(void)
342 int po_old = PicoOpt;
343 int eo_old = currentConfig.EmuOpt;
346 PicoOpt |= 0x4080; // soft_scale | acc_sprites
347 currentConfig.EmuOpt |= 0x80;
349 if (giz_screen == NULL)
350 giz_screen = Framework2D_LockBuffer();
352 PicoDrawSetColorFormat(1);
353 PicoScan = EmuScan16;
354 PicoScan((unsigned) -1, NULL);
358 Framework2D_UnlockBuffer();
362 currentConfig.EmuOpt = eo_old;
366 static void RunEvents(unsigned int which)
368 if (which & 0x1800) { // save or load (but not both)
370 if ( emu_checkSaveFile(state_slot) &&
371 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
372 (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
375 if (giz_screen == NULL)
376 giz_screen = Framework2D_LockBuffer();
377 blit("", (which & 0x1000) ? "LOAD STATE? (PLAY=yes, STOP=no)" : "OVERWRITE SAVE? (PLAY=yes, STOP=no)");
378 while( !((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) )
380 if (keys & BTN_STOP) do_it = 0;
384 osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");
385 PicoStateProgressCB = emu_state_cb;
386 emu_SaveLoadGame((which & 0x1000) >> 12, 0);
387 PicoStateProgressCB = NULL;
392 if (which & 0x0400) { // switch renderer
393 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }
394 else { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
399 strcpy(noticeMsg, " 8bit fast renderer");
400 } else if (currentConfig.EmuOpt&0x80) {
401 strcpy(noticeMsg, "16bit accurate renderer");
403 strcpy(noticeMsg, " 8bit accurate renderer");
406 noticeMsgTime = GetTickCount();
408 if (which & 0x0300) {
411 if(state_slot < 0) state_slot = 9;
414 if(state_slot > 9) state_slot = 0;
416 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
417 noticeMsgTime = GetTickCount();
421 static void updateKeys(void)
423 unsigned int keys, allActions[2] = { 0, 0 }, events;
424 static unsigned int prevEvents = 0;
427 keys = Framework_PollGetButtons();
429 engineState = PGS_Menu;
431 keys &= CONFIGURABLE_KEYS;
433 for (i = 0; i < 32; i++)
437 int pl, acts = currentConfig.KeyBinds[i];
439 pl = (acts >> 16) & 1;
440 if (combo_keys & (1 << i))
442 int u = i+1, acts_c = acts & combo_acts;
443 // let's try to find the other one
446 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {
447 allActions[pl] |= acts_c;
448 keys &= ~((1 << i) | (1 << u));
451 // add non-combo actions if combo ones were not found
452 if (!acts_c || u == 32)
453 allActions[pl] |= acts & ~combo_acts;
455 allActions[pl] |= acts;
460 PicoPad[0] = (unsigned short) allActions[0];
461 PicoPad[1] = (unsigned short) allActions[1];
463 events = (allActions[0] | allActions[1]) >> 16;
465 // volume is treated in special way and triggered every frame
466 if ((events & 0x6000) && PsndOut != NULL)
468 int vol = currentConfig.volume;
469 if (events & 0x2000) {
470 if (vol < 100) vol++;
474 FrameworkAudio_SetVolume(vol, vol);
475 sprintf(noticeMsg, "VOL: %02i", vol);
476 noticeMsgTime = GetTickCount();
477 currentConfig.volume = vol;
480 events &= ~prevEvents;
481 if (events) RunEvents(events);
482 if (movie_data) emu_updateMovie();
484 prevEvents = (allActions[0] | allActions[1]) >> 16;
487 static void find_combos(void)
491 // find out which keys and actions are combos
492 combo_keys = combo_acts = 0;
493 for (act = 0; act < 32; act++)
496 if (act == 16 || act == 17) continue; // player2 flag
497 for (u = 0; u < 32; u++)
499 if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;
503 // loop again and mark those keys and actions as combo
504 for (u = 0; u < 32; u++)
506 if (currentConfig.KeyBinds[u] & (1 << act)) {
507 combo_keys |= 1 << u;
508 combo_acts |= 1 << act;
516 static void simpleWait(DWORD until)
521 tval = GetTickCount();
522 diff = (int)until - (int)tval;
526 while ((tval = GetTickCount()) < until && until - tval < 512) // some simple overflow detection
527 spend_cycles(1024*2);
532 static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
533 char fpsbuff[24]; // fps count c string
534 DWORD tval, tval_prev = 0, tval_thissec = 0; // timing
535 int frames_done = 0, frames_shown = 0, oldmodes = 0, sec_ms = 1000;
536 int target_fps, target_frametime, lim_time, tval_diff, i;
539 lprintf("entered emu_Loop()\n");
543 // make sure we are in correct mode
545 if (currentConfig.scaling) PicoOpt|=0x4000;
546 else PicoOpt&=~0x4000;
548 oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
551 // pal/ntsc might have changed, reset related stuff
552 target_fps = Pico.m.pal ? 50 : 60;
553 target_frametime = Pico.m.pal ? (1000<<8)/50 : (1000<<8)/60+1;
557 if (PicoMCD & 1) PicoCDBufferInit();
559 // prepare sound stuff
561 if (currentConfig.EmuOpt & 4)
563 int ret, snd_excess_add, stereo=(PicoOpt&8)>>3;
564 if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
565 sound_rerate(Pico.m.frame_count ? 1 : 0);
567 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;
568 snd_cbuf_samples = (PsndRate<<stereo) * 16 / target_fps;
569 lprintf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",
570 PsndRate, PsndLen, snd_excess_add, stereo, Pico.m.pal);
571 ret = FrameworkAudio_Init(PsndRate, snd_cbuf_samples, stereo);
573 lprintf("FrameworkAudio_Init() failed: %i\n", ret);
574 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
575 noticeMsgTime = GetTickCount();
576 currentConfig.EmuOpt &= ~4;
578 FrameworkAudio_SetVolume(currentConfig.volume, currentConfig.volume);
579 PicoWriteSound = updateSound;
580 snd_cbuff = FrameworkAudio_56448Buffer();
581 PsndOut = snd_cbuff + snd_cbuf_samples / 2; // start writing at the middle
583 PsndRate_old = PsndRate;
584 PicoOpt_old = PicoOpt;
585 pal_old = Pico.m.pal;
590 while (engineState == PGS_Running)
594 tval = GetTickCount();
595 if (reset_timing || tval < tval_prev) {
596 stdbg("timing reset");
599 frames_shown = frames_done = 0;
602 // show notice message?
604 static int noticeMsgSum;
605 if (tval - noticeMsgTime > 2000) { // > 2.0 sec
610 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
611 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
616 // check for mode changes
617 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
618 if (modes != oldmodes) {
624 if (tval - tval_thissec >= sec_ms)
627 static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
630 bench_fps_s = bench_fps;
631 bf[bfp++ & 3] = bench_fps;
634 bench_fps += frames_shown;
635 sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
637 if(currentConfig.EmuOpt & 2)
638 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);
640 //tval_thissec += 1000;
641 tval_thissec += sec_ms;
645 /* some code which tries to sync things to audio clock, the dirty way */
646 static int audio_skew_prev = 0;
647 int audio_skew, adj, co = 9, shift = 7;
648 audio_skew = snd_all_samples*2 - FrameworkAudio_BufferPos();
649 if (PsndRate == 22050) co = 10;
650 if (PsndRate > 22050) co = 11;
651 if (PicoOpt&8) shift++;
652 if (audio_skew < 0) {
653 adj = -((-audio_skew) >> shift);
654 if (audio_skew > -(6<<co)) adj>>=1;
655 if (audio_skew > -(4<<co)) adj>>=1;
656 if (audio_skew > -(2<<co)) adj>>=1;
657 if (audio_skew > audio_skew_prev) adj>>=2; // going up already
659 adj = audio_skew >> shift;
660 if (audio_skew < (6<<co)) adj>>=1;
661 if (audio_skew < (4<<co)) adj>>=1;
662 if (audio_skew < (2<<co)) adj>>=1;
663 if (audio_skew < audio_skew_prev) adj>>=2;
665 audio_skew_prev = audio_skew;
666 target_frametime += adj;
667 sec_ms = (target_frametime * target_fps) >> 8;
668 stdbg("%i %i %i", audio_skew, adj, sec_ms);
669 frames_done = frames_shown = 0;
671 else if (currentConfig.Frameskip < 0) {
672 frames_done -= target_fps; if (frames_done < 0) frames_done = 0;
673 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
674 if (frames_shown > frames_done) frames_shown = frames_done;
676 frames_done = frames_shown = 0;
680 sprintf(fpsbuff, "%i", Pico.m.frame_count);
684 lim_time = (frames_done+1) * target_frametime;
685 if (currentConfig.Frameskip >= 0) // frameskip enabled
687 for (i = 0; i < currentConfig.Frameskip; i++) {
689 SkipFrame(); frames_done++;
690 if (PsndOut) { // do framelimitting if sound is enabled
692 tval = GetTickCount();
693 tval_diff = (int)(tval - tval_thissec) << 8;
694 if (tval_diff < lim_time) // we are too fast
695 simpleWait(tval + ((lim_time - tval_diff)>>8));
697 lim_time += target_frametime;
700 else // auto frameskip
703 tval = GetTickCount();
704 tval_diff = (int)(tval - tval_thissec) << 8;
705 if (tval_diff > lim_time)
707 // no time left for this frame - skip
708 if (tval_diff - lim_time >= (300<<8)) {
709 /* something caused a slowdown for us (disk access? cache flush?)
710 * try to recover by resetting timing... */
715 SkipFrame(); frames_done++;
722 if (giz_screen == NULL && (currentConfig.EmuOpt&0x80))
723 giz_screen = Framework2D_LockBuffer();
725 PicoScan((unsigned) -1, NULL);
729 if (currentConfig.EmuOpt&0x2000)
730 Framework2D_WaitVSync();
732 if (giz_screen == NULL)
733 giz_screen = Framework2D_LockBuffer();
735 blit(fpsbuff, notice);
737 if (giz_screen != NULL) {
738 Framework2D_UnlockBuffer();
743 tval = GetTickCount();
744 tval_diff = (int)(tval - tval_thissec) << 8;
746 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300<<8)) // slowdown detection
748 else if (PsndOut != NULL || currentConfig.Frameskip < 0)
750 // sleep if we are still too fast
751 if (tval_diff < lim_time)
754 simpleWait(tval + ((lim_time - tval_diff) >> 8));
758 frames_done++; frames_shown++;
762 if (PicoMCD & 1) PicoCDBufferFree();
764 if (PsndOut != NULL) {
765 PsndOut = snd_cbuff = NULL;
766 FrameworkAudio_Close();
770 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
771 emu_state_cb("Writing SRAM/BRAM..");
772 emu_SaveLoadGame(0, 1);
778 void emu_ResetGame(void)