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"
13 #include "../common/config.h"
17 #include "asm_utils.h"
19 #include <Pico/PicoInt.h>
27 // main 300K gfx-related buffer. Used by menu and renderers.
28 unsigned char gfx_buffer[321*240*2*2];
29 char romFileName[MAX_PATH];
32 unsigned char *PicoDraw2FB = gfx_buffer; // temporary buffer for alt renderer ( (8+320)*(8+240+8) )
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) fb_unlock();
56 giz_screen = fb_lock(1);
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 giz_screen = fb_lock((currentConfig.EmuOpt&0x8000) ? 0 : 1);
69 void emu_stateCb(const char *str)
71 if (giz_screen != NULL) fb_unlock();
72 giz_screen = fb_lock(1);
80 Sleep(0); /* yield the CPU, the system may need it */
83 static void emu_msg_tray_open(void)
85 strcpy(noticeMsg, "CD tray opened");
86 noticeMsgTime = GetTickCount();
92 // make dirs for saves, cfgs, etc.
99 PicoMessage = emu_msg_cb;
100 PicoMCDopenTray = emu_msg_tray_open;
101 PicoMCDcloseTray = menu_loop_tray;
104 void emu_Deinit(void)
107 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
108 emu_SaveLoadGame(0, 1);
112 if (!(currentConfig.EmuOpt & 0x20))
113 config_writelrom(PicoConfigFile);
118 void emu_prepareDefaultConfig(void)
120 memset(&defaultConfig, 0, sizeof(defaultConfig));
121 defaultConfig.EmuOpt = 0x1d | 0x680; // | confirm_save, cd_leds, 16bit rend
122 defaultConfig.s_PicoOpt = 0x0f | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_SVP_DRC|POPT_ACC_SPRITES;
123 defaultConfig.s_PsndRate = 22050;
124 defaultConfig.s_PicoRegion = 0; // auto
125 defaultConfig.s_PicoAutoRgnOrder = 0x184; // US, EU, JP
126 defaultConfig.s_PicoCDBuffers = 0;
127 defaultConfig.Frameskip = -1; // auto
128 defaultConfig.volume = 50;
129 defaultConfig.KeyBinds[ 2] = 1<<0; // SACB RLDU
130 defaultConfig.KeyBinds[ 3] = 1<<1;
131 defaultConfig.KeyBinds[ 0] = 1<<2;
132 defaultConfig.KeyBinds[ 1] = 1<<3;
133 defaultConfig.KeyBinds[ 5] = 1<<4;
134 defaultConfig.KeyBinds[ 6] = 1<<5;
135 defaultConfig.KeyBinds[ 7] = 1<<6;
136 defaultConfig.KeyBinds[ 4] = 1<<7;
137 defaultConfig.KeyBinds[13] = 1<<26; // switch rend
138 defaultConfig.KeyBinds[ 8] = 1<<27; // save state
139 defaultConfig.KeyBinds[ 9] = 1<<28; // load state
140 defaultConfig.KeyBinds[12] = 1<<29; // vol up
141 defaultConfig.KeyBinds[11] = 1<<30; // vol down
142 defaultConfig.scaling = 0;
143 defaultConfig.turbo_rate = 15;
146 void emu_setDefaultConfig(void)
148 memcpy(¤tConfig, &defaultConfig, sizeof(currentConfig));
149 PicoOpt = currentConfig.s_PicoOpt;
150 PsndRate = currentConfig.s_PsndRate;
151 PicoRegionOverride = currentConfig.s_PicoRegion;
152 PicoAutoRgnOrder = currentConfig.s_PicoAutoRgnOrder;
153 PicoCDBuffers = currentConfig.s_PicoCDBuffers;
157 static int EmuScanBegin16(unsigned int num)
159 if (!(Pico.video.reg[1]&8)) num += 8;
160 DrawLineDest = (unsigned short *) giz_screen + 321 * num;
162 if ((currentConfig.EmuOpt&0x4000) && (num&1) == 0) // (Pico.m.frame_count&1))
163 return 1; // skip next line
168 static int EmuScanBegin8(unsigned int num)
170 // draw like the fast renderer
171 if (!(Pico.video.reg[1]&8)) num += 8;
172 HighCol = gfx_buffer + 328 * num;
177 static void osd_text(int x, int y, const char *text)
179 int len = strlen(text) * 8 / 2;
181 for (h = 0; h < 8; h++) {
182 p = (int *) ((unsigned short *) giz_screen+x+321*(y+h));
183 p = (int *) ((int)p & ~3); // align
186 emu_textOut16(x, y, text);
190 void log1(void *p1, void *p2)
192 lprintf("%p %p %p\n", p1, p2, DrawLineDest);
196 static void cd_leds(void)
198 static int old_reg = 0;
199 unsigned int col_g, col_r, *p;
201 if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change
202 old_reg = Pico_mcd->s68k_regs[0];
204 p = (unsigned int *)((short *)giz_screen + 321*2+4+2);
205 col_g = (old_reg & 2) ? 0x06000600 : 0;
206 col_r = (old_reg & 1) ? 0xc000c000 : 0;
207 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 321/2 - 12/2 + 1;
208 *p++ = col_g; p+=3; *p++ = col_r; p += 321/2 - 10/2;
209 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
213 static short localPal[0x100];
215 static void blit(const char *fps, const char *notice)
217 int emu_opt = currentConfig.EmuOpt;
221 int lines_flags = 224;
222 // 8bit fast renderer
223 if (Pico.m.dirtyPal) {
225 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
228 if (PicoRead16Hook == PicoSVPRead16)
229 memset32((int *)(PicoDraw2FB+328*8+328*223), 0xe0e0e0e0, 328);
230 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
231 if (currentConfig.EmuOpt&0x4000)
232 lines_flags|=0x40000; // (Pico.m.frame_count&1)?0x20000:0x40000;
233 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
235 else if (!(emu_opt&0x80))
238 // 8bit accurate renderer
239 if (Pico.m.dirtyPal) {
241 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
242 if (Pico.video.reg[0xC]&8) { // shadow/hilight mode
243 //vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
244 //vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40); // TODO?
245 memcpy32((void *)(localPal+0xc0), (void *)(localPal+0x40), 0x40*2/4);
246 localPal[0xc0] = 0x0600;
247 localPal[0xd0] = 0xc000;
248 localPal[0xe0] = 0x0000; // reserved pixels for OSD
249 localPal[0xf0] = 0xffff;
252 else if (rendstatus & 0x20) { // mid-frame palette changes
253 vidConvCpyRGB565(localPal+0x40, HighPal, 0x40);
254 vidConvCpyRGB565(localPal+0x80, HighPal+0x40, 0x40);
257 lines_flags = (Pico.video.reg[1]&8) ? 240 : 224;
258 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
259 if (currentConfig.EmuOpt&0x4000)
260 lines_flags|=0x40000; // (Pico.m.frame_count&1)?0x20000:0x40000;
261 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
264 if (notice || (emu_opt & 2)) {
266 if (notice) osd_text(4, h, notice);
267 if (emu_opt & 2) osd_text(OSD_FPS_X, h, fps);
270 if ((emu_opt & 0x400) && (PicoAHW & PAHW_MCD))
274 // clears whole screen or just the notice area (in all buffers)
275 static void clearArea(int full)
277 if (giz_screen == NULL)
278 giz_screen = fb_lock(1);
279 if (full) memset32(giz_screen, 0, 320*240*2/4);
280 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
282 if (currentConfig.EmuOpt&0x8000) {
284 giz_screen = fb_lock(0);
285 if (full) memset32(giz_screen, 0, 320*240*2/4);
286 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
290 static void vidResetMode(void)
292 giz_screen = fb_lock(1);
295 } else if (currentConfig.EmuOpt&0x80) {
296 PicoDrawSetColorFormat(1);
297 PicoScanBegin = EmuScanBegin16;
299 PicoDrawSetColorFormat(-1);
300 PicoScanBegin = EmuScanBegin8;
302 if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80)) {
303 // setup pal for 8-bit modes
304 localPal[0xc0] = 0x0600;
305 localPal[0xd0] = 0xc000;
306 localPal[0xe0] = 0x0000; // reserved pixels for OSD
307 localPal[0xf0] = 0xffff;
311 memset32(giz_screen, 0, 321*240*2/4);
312 if (currentConfig.EmuOpt&0x8000) {
314 giz_screen = fb_lock(0);
315 memset32(giz_screen, 0, 321*240*2/4);
323 static void stdbg(const char *fmt, ...)
328 sprintf(noticeMsg, "%x ", cnt++);
330 vsnprintf(noticeMsg+strlen(noticeMsg), sizeof(noticeMsg)-strlen(noticeMsg), fmt, vl);
333 noticeMsgTime = GetTickCount();
337 static void updateSound(int len)
339 if (PicoOpt&8) len<<=1;
341 snd_all_samples += len;
343 if (PsndOut - snd_cbuff >= snd_cbuf_samples)
345 //if (PsndOut - snd_cbuff != snd_cbuf_samples)
346 // stdbg("snd diff is %i, not %i", PsndOut - snd_cbuff, snd_cbuf_samples);
352 static void SkipFrame(void)
359 /* forced frame to front buffer */
360 void emu_forcedFrame(int opts)
362 int po_old = PicoOpt;
363 int eo_old = currentConfig.EmuOpt;
366 PicoOpt |= opts|POPT_ACC_SPRITES;
367 currentConfig.EmuOpt |= 0x80;
369 if (giz_screen == NULL)
370 giz_screen = fb_lock(1);
372 PicoDrawSetColorFormat(1);
373 PicoScanBegin = EmuScanBegin16;
381 currentConfig.EmuOpt = eo_old;
385 static void RunEvents(unsigned int which)
387 if (which & 0x1800) // save or load (but not both)
392 FrameworkAudio_SetPause(1);
393 if (giz_screen == NULL)
394 giz_screen = fb_lock(1);
395 if ( emu_checkSaveFile(state_slot) &&
396 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
397 (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
400 blit("", (which & 0x1000) ? "LOAD STATE? (PLAY=yes, STOP=no)" : "OVERWRITE SAVE? (PLAY=yes, STOP=no)");
401 while( !((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) )
403 if (keys & BTN_STOP) do_it = 0;
404 while( ((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) ) // wait for release
411 osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");
412 PicoStateProgressCB = emu_stateCb;
413 emu_SaveLoadGame((which & 0x1000) >> 12, 0);
414 PicoStateProgressCB = NULL;
419 FrameworkAudio_SetPause(0);
422 if (which & 0x0400) // switch renderer
424 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }
425 else { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
430 strcpy(noticeMsg, " 8bit fast renderer");
431 } else if (currentConfig.EmuOpt&0x80) {
432 strcpy(noticeMsg, "16bit accurate renderer");
434 strcpy(noticeMsg, " 8bit accurate renderer");
437 noticeMsgTime = GetTickCount();
443 if(state_slot < 0) state_slot = 9;
446 if(state_slot > 9) state_slot = 0;
448 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
449 noticeMsgTime = GetTickCount();
453 static void updateKeys(void)
455 unsigned int keys, allActions[2] = { 0, 0 }, events;
456 static unsigned int prevEvents = 0;
459 keys = Framework_PollGetButtons();
461 engineState = PGS_Menu;
463 keys &= CONFIGURABLE_KEYS;
465 for (i = 0; i < 32; i++)
469 int pl, acts = currentConfig.KeyBinds[i];
471 pl = (acts >> 16) & 1;
472 if (kb_combo_keys & (1 << i))
474 int u = i+1, acts_c = acts & kb_combo_acts;
475 // let's try to find the other one
478 if ( (keys & (1 << u)) && (currentConfig.KeyBinds[u] & acts_c) ) {
479 allActions[pl] |= acts_c & currentConfig.KeyBinds[u];
480 keys &= ~((1 << i) | (1 << u));
484 // add non-combo actions if combo ones were not found
485 if (!acts_c || u == 32)
486 allActions[pl] |= acts & ~kb_combo_acts;
488 allActions[pl] |= acts;
493 PicoPad[0] = allActions[0] & 0xfff;
494 PicoPad[1] = allActions[1] & 0xfff;
496 if (allActions[0] & 0x7000) emu_DoTurbo(&PicoPad[0], allActions[0]);
497 if (allActions[1] & 0x7000) emu_DoTurbo(&PicoPad[1], allActions[1]);
499 events = (allActions[0] | allActions[1]) >> 16;
501 // volume is treated in special way and triggered every frame
502 if ((events & 0x6000) && PsndOut != NULL)
504 int vol = currentConfig.volume;
505 if (events & 0x2000) {
506 if (vol < 100) vol++;
510 FrameworkAudio_SetVolume(vol, vol);
511 sprintf(noticeMsg, "VOL: %02i ", vol);
512 noticeMsgTime = GetTickCount();
513 currentConfig.volume = vol;
516 events &= ~prevEvents;
517 if (events) RunEvents(events);
518 if (movie_data) emu_updateMovie();
520 prevEvents = (allActions[0] | allActions[1]) >> 16;
523 void emu_platformDebugCat(char *str)
528 static void simpleWait(DWORD until)
533 tval = GetTickCount();
534 diff = (int)until - (int)tval;
538 while ((tval = GetTickCount()) < until && until - tval < 512) // some simple overflow detection
539 spend_cycles(1024*2);
544 static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
545 char fpsbuff[24]; // fps count c string
546 DWORD tval, tval_prev = 0, tval_thissec = 0; // timing
547 int frames_done = 0, frames_shown = 0, oldmodes = 0, sec_ms = 1000;
548 int target_fps, target_frametime, lim_time, tval_diff, i;
551 lprintf("entered emu_Loop()\n");
555 // make sure we are in correct mode
557 if (currentConfig.scaling) PicoOpt|=0x4000;
558 else PicoOpt&=~0x4000;
560 oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
561 emu_findKeyBindCombos();
563 // pal/ntsc might have changed, reset related stuff
564 target_fps = Pico.m.pal ? 50 : 60;
565 target_frametime = Pico.m.pal ? (1000<<8)/50 : (1000<<8)/60+1;
569 if (PicoAHW & PAHW_MCD) PicoCDBufferInit();
571 // prepare sound stuff
573 if (currentConfig.EmuOpt & 4)
575 int ret, snd_excess_add, stereo;
576 if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
577 PsndRerate(Pico.m.frame_count ? 1 : 0);
579 stereo=(PicoOpt&8)>>3;
580 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;
581 snd_cbuf_samples = (PsndRate<<stereo) * 16 / target_fps;
582 lprintf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",
583 PsndRate, PsndLen, snd_excess_add, stereo, Pico.m.pal);
584 ret = FrameworkAudio_Init(PsndRate, snd_cbuf_samples, stereo);
586 lprintf("FrameworkAudio_Init() failed: %i\n", ret);
587 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
588 noticeMsgTime = GetTickCount();
589 currentConfig.EmuOpt &= ~4;
591 FrameworkAudio_SetVolume(currentConfig.volume, currentConfig.volume);
592 PicoWriteSound = updateSound;
593 snd_cbuff = FrameworkAudio_56448Buffer();
594 PsndOut = snd_cbuff + snd_cbuf_samples / 2; // start writing at the middle
596 PsndRate_old = PsndRate;
597 PicoOpt_old = PicoOpt;
598 pal_old = Pico.m.pal;
603 while (engineState == PGS_Running)
607 tval = GetTickCount();
608 if (reset_timing || tval < tval_prev) {
609 //stdbg("timing reset");
612 frames_shown = frames_done = 0;
615 // show notice message?
617 static int noticeMsgSum;
618 if (tval - noticeMsgTime > 2000) { // > 2.0 sec
623 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
624 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
629 // check for mode changes
630 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
631 if (modes != oldmodes) {
637 if (tval - tval_thissec >= sec_ms)
640 static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
643 bench_fps_s = bench_fps;
644 bf[bfp++ & 3] = bench_fps;
647 bench_fps += frames_shown;
648 sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
650 if(currentConfig.EmuOpt & 2)
651 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);
653 //tval_thissec += 1000;
654 tval_thissec += sec_ms;
658 /* some code which tries to sync things to audio clock, the dirty way */
659 static int audio_skew_prev = 0;
660 int audio_skew, adj, co = 9, shift = 7;
661 audio_skew = snd_all_samples*2 - FrameworkAudio_BufferPos();
662 if (PsndRate == 22050) co = 10;
663 if (PsndRate > 22050) co = 11;
664 if (PicoOpt&8) shift++;
665 if (audio_skew < 0) {
666 adj = -((-audio_skew) >> shift);
667 if (audio_skew > -(6<<co)) adj>>=1;
668 if (audio_skew > -(4<<co)) adj>>=1;
669 if (audio_skew > -(2<<co)) adj>>=1;
670 if (audio_skew > audio_skew_prev) adj>>=2; // going up already
672 adj = audio_skew >> shift;
673 if (audio_skew < (6<<co)) adj>>=1;
674 if (audio_skew < (4<<co)) adj>>=1;
675 if (audio_skew < (2<<co)) adj>>=1;
676 if (audio_skew < audio_skew_prev) adj>>=2;
678 audio_skew_prev = audio_skew;
679 target_frametime += adj;
680 sec_ms = (target_frametime * target_fps) >> 8;
681 //stdbg("%i %i %i", audio_skew, adj, sec_ms);
682 frames_done = frames_shown = 0;
684 else if (currentConfig.Frameskip < 0) {
685 frames_done -= target_fps; if (frames_done < 0) frames_done = 0;
686 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
687 if (frames_shown > frames_done) frames_shown = frames_done;
689 frames_done = frames_shown = 0;
693 sprintf(fpsbuff, "%i", Pico.m.frame_count);
697 lim_time = (frames_done+1) * target_frametime;
698 if (currentConfig.Frameskip >= 0) // frameskip enabled
700 for (i = 0; i < currentConfig.Frameskip; i++) {
702 SkipFrame(); frames_done++;
703 if (PsndOut) { // do framelimitting if sound is enabled
705 tval = GetTickCount();
706 tval_diff = (int)(tval - tval_thissec) << 8;
707 if (tval_diff < lim_time) // we are too fast
708 simpleWait(tval + ((lim_time - tval_diff)>>8));
710 lim_time += target_frametime;
713 else // auto frameskip
716 tval = GetTickCount();
717 tval_diff = (int)(tval - tval_thissec) << 8;
718 if (tval_diff > lim_time)
720 // no time left for this frame - skip
721 if (tval_diff - lim_time >= (300<<8)) {
722 /* something caused a slowdown for us (disk access? cache flush?)
723 * try to recover by resetting timing... */
728 SkipFrame(); frames_done++;
735 if (currentConfig.EmuOpt&0x80)
736 /* be sure correct framebuffer is locked */
737 giz_screen = fb_lock((currentConfig.EmuOpt&0x8000) ? 0 : 1);
741 if (giz_screen == NULL)
742 giz_screen = fb_lock((currentConfig.EmuOpt&0x8000) ? 0 : 1);
744 blit(fpsbuff, notice);
746 if (giz_screen != NULL) {
751 if (currentConfig.EmuOpt&0x2000)
752 Framework2D_WaitVSync();
754 if (currentConfig.EmuOpt&0x8000)
758 tval = GetTickCount();
759 tval_diff = (int)(tval - tval_thissec) << 8;
761 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300<<8)) // slowdown detection
763 else if (PsndOut != NULL || currentConfig.Frameskip < 0)
765 // sleep if we are still too fast
766 if (tval_diff < lim_time)
769 simpleWait(tval + ((lim_time - tval_diff) >> 8));
773 frames_done++; frames_shown++;
777 if (PicoAHW & PAHW_MCD) PicoCDBufferFree();
779 if (PsndOut != NULL) {
780 PsndOut = snd_cbuff = NULL;
781 FrameworkAudio_Close();
785 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
786 emu_stateCb("Writing SRAM/BRAM..");
787 emu_SaveLoadGame(0, 1);
793 void emu_ResetGame(void)