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 DWORD noticeMsgTime = 0;
35 static short *snd_cbuff = NULL;
36 static int snd_cbuf_samples = 0, snd_all_samples = 0;
39 static void blit(const char *fps, const char *notice);
40 static void clearArea(int full);
42 void emu_noticeMsgUpdated(void)
44 noticeMsgTime = GetTickCount();
47 void emu_getMainDir(char *dst, int len)
49 if (len > 0) *dst = 0;
52 static void emu_msg_cb(const char *msg)
54 if (giz_screen != NULL) Framework2D_UnlockBuffer();
55 giz_screen = Framework2D_LockBuffer(1);
57 memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
58 emu_textOut16(4, 232, msg);
59 noticeMsgTime = GetTickCount() - 2000;
61 /* assumption: emu_msg_cb gets called only when something slow is about to happen */
64 Framework2D_UnlockBuffer();
65 giz_screen = Framework2D_LockBuffer((currentConfig.EmuOpt&0x8000) ? 0 : 1);
68 void emu_stateCb(const char *str)
70 if (giz_screen != NULL) Framework2D_UnlockBuffer();
71 giz_screen = Framework2D_LockBuffer(1);
76 Framework2D_UnlockBuffer();
79 Sleep(0); /* yield the CPU, the system may need it */
82 static void emu_msg_tray_open(void)
84 strcpy(noticeMsg, "CD tray opened");
85 noticeMsgTime = GetTickCount();
91 // make dirs for saves, cfgs, etc.
98 PicoMessage = emu_msg_cb;
99 PicoMCDopenTray = emu_msg_tray_open;
100 PicoMCDcloseTray = menu_loop_tray;
103 void emu_Deinit(void)
106 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
107 emu_SaveLoadGame(0, 1);
111 if (!(currentConfig.EmuOpt & 0x20))
112 config_writelrom(PicoConfigFile);
117 void emu_setDefaultConfig(void)
119 memset(¤tConfig, 0, sizeof(currentConfig));
120 currentConfig.lastRomFile[0] = 0;
121 currentConfig.EmuOpt = 0x1f | 0x680; // | confirm_save, cd_leds, 16bit rend
122 currentConfig.PicoOpt = 0x07 | 0xc00; // | cd_pcm, cd_cdda
123 currentConfig.PsndRate = 22050;
124 currentConfig.PicoRegion = 0; // auto
125 currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP
126 currentConfig.Frameskip = -1; // auto
127 currentConfig.volume = 50;
128 currentConfig.KeyBinds[ 2] = 1<<0; // SACB RLDU
129 currentConfig.KeyBinds[ 3] = 1<<1;
130 currentConfig.KeyBinds[ 0] = 1<<2;
131 currentConfig.KeyBinds[ 1] = 1<<3;
132 currentConfig.KeyBinds[ 5] = 1<<4;
133 currentConfig.KeyBinds[ 6] = 1<<5;
134 currentConfig.KeyBinds[ 7] = 1<<6;
135 currentConfig.KeyBinds[ 4] = 1<<7;
136 currentConfig.KeyBinds[13] = 1<<26; // switch rend
137 currentConfig.KeyBinds[ 8] = 1<<27; // save state
138 currentConfig.KeyBinds[ 9] = 1<<28; // load state
139 currentConfig.KeyBinds[12] = 1<<29; // vol up
140 currentConfig.KeyBinds[11] = 1<<30; // vol down
141 currentConfig.PicoCDBuffers = 0;
142 currentConfig.scaling = 0;
143 defaultConfig.turbo_rate = 15;
147 static int EmuScanBegin16(unsigned int num)
149 if (!(Pico.video.reg[1]&8)) num += 8;
150 DrawLineDest = (unsigned short *) giz_screen + 321 * num;
152 if ((currentConfig.EmuOpt&0x4000) && (num&1) == 0) // (Pico.m.frame_count&1))
153 return 1; // skip next line
158 static int EmuScanBegin8(unsigned int num)
160 // draw like the fast renderer
161 if (!(Pico.video.reg[1]&8)) num += 8;
162 HighCol = gfx_buffer + 328 * num;
167 static void osd_text(int x, int y, const char *text)
169 int len = strlen(text) * 8 / 2;
171 for (h = 0; h < 8; h++) {
172 p = (int *) ((unsigned short *) giz_screen+x+321*(y+h));
173 p = (int *) ((int)p & ~3); // align
176 emu_textOut16(x, y, text);
180 void log1(void *p1, void *p2)
182 lprintf("%p %p %p\n", p1, p2, DrawLineDest);
186 static void cd_leds(void)
188 static int old_reg = 0;
189 unsigned int col_g, col_r, *p;
191 if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change
192 old_reg = Pico_mcd->s68k_regs[0];
194 p = (unsigned int *)((short *)giz_screen + 321*2+4+2);
195 col_g = (old_reg & 2) ? 0x06000600 : 0;
196 col_r = (old_reg & 1) ? 0xc000c000 : 0;
197 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 321/2 - 12/2 + 1;
198 *p++ = col_g; p+=3; *p++ = col_r; p += 321/2 - 10/2;
199 *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
203 static short localPal[0x100];
205 static void blit(const char *fps, const char *notice)
207 int emu_opt = currentConfig.EmuOpt;
211 int lines_flags = 224;
212 // 8bit fast renderer
213 if (Pico.m.dirtyPal) {
215 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
217 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
218 if (currentConfig.EmuOpt&0x4000)
219 lines_flags|=0x40000; // (Pico.m.frame_count&1)?0x20000:0x40000;
220 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
222 else if (!(emu_opt&0x80))
225 // 8bit accurate renderer
226 if (Pico.m.dirtyPal) {
228 vidConvCpyRGB565(localPal, Pico.cram, 0x40);
229 if (Pico.video.reg[0xC]&8) { // shadow/hilight mode
230 //vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
231 //vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40); // TODO?
232 blockcpy(localPal+0xc0, localPal+0x40, 0x40*2);
233 localPal[0xc0] = 0x0600;
234 localPal[0xd0] = 0xc000;
235 localPal[0xe0] = 0x0000; // reserved pixels for OSD
236 localPal[0xf0] = 0xffff;
239 else if (rendstatus & 0x20) { // mid-frame palette changes
240 vidConvCpyRGB565(localPal+0x40, HighPal, 0x40);
241 vidConvCpyRGB565(localPal+0x80, HighPal+0x40, 0x40);
244 lines_flags = (Pico.video.reg[1]&8) ? 240 : 224;
245 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
246 if (currentConfig.EmuOpt&0x4000)
247 lines_flags|=0x40000; // (Pico.m.frame_count&1)?0x20000:0x40000;
248 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
251 if (notice || (emu_opt & 2)) {
253 if (notice) osd_text(4, h, notice);
254 if (emu_opt & 2) osd_text(OSD_FPS_X, h, fps);
257 if ((emu_opt & 0x400) && (PicoAHW & PAHW_MCD))
261 // clears whole screen or just the notice area (in all buffers)
262 static void clearArea(int full)
264 if (giz_screen == NULL)
265 giz_screen = Framework2D_LockBuffer(1);
266 if (full) memset32(giz_screen, 0, 320*240*2/4);
267 else memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
269 if (currentConfig.EmuOpt&0x8000) {
270 Framework2D_UnlockBuffer();
271 giz_screen = Framework2D_LockBuffer(0);
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);
277 static void vidResetMode(void)
279 giz_screen = Framework2D_LockBuffer(1);
282 } else if (currentConfig.EmuOpt&0x80) {
283 PicoDrawSetColorFormat(1);
284 PicoScanBegin = EmuScanBegin16;
286 PicoDrawSetColorFormat(-1);
287 PicoScanBegin = EmuScanBegin8;
289 if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80)) {
290 // setup pal for 8-bit modes
291 localPal[0xc0] = 0x0600;
292 localPal[0xd0] = 0xc000;
293 localPal[0xe0] = 0x0000; // reserved pixels for OSD
294 localPal[0xf0] = 0xffff;
298 memset32(giz_screen, 0, 321*240*2/4);
299 if (currentConfig.EmuOpt&0x8000) {
300 Framework2D_UnlockBuffer();
301 giz_screen = Framework2D_LockBuffer(0);
302 memset32(giz_screen, 0, 321*240*2/4);
304 Framework2D_UnlockBuffer();
310 static void stdbg(const char *fmt, ...)
315 sprintf(noticeMsg, "%x ", cnt++);
317 vsnprintf(noticeMsg+strlen(noticeMsg), sizeof(noticeMsg)-strlen(noticeMsg), fmt, vl);
320 noticeMsgTime = GetTickCount();
324 static void updateSound(int len)
326 if (PicoOpt&8) len<<=1;
328 snd_all_samples += len;
330 if (PsndOut - snd_cbuff >= snd_cbuf_samples)
332 //if (PsndOut - snd_cbuff != snd_cbuf_samples)
333 // stdbg("snd diff is %i, not %i", PsndOut - snd_cbuff, snd_cbuf_samples);
339 static void SkipFrame(void)
346 /* forced frame to front buffer */
347 void emu_forcedFrame(int opts)
349 int po_old = PicoOpt;
350 int eo_old = currentConfig.EmuOpt;
353 PicoOpt |= opts|POPT_ACC_SPRITES;
354 currentConfig.EmuOpt |= 0x80;
356 if (giz_screen == NULL)
357 giz_screen = Framework2D_LockBuffer(1);
359 PicoDrawSetColorFormat(1);
360 PicoScanBegin = EmuScanBegin16;
364 Framework2D_UnlockBuffer();
368 currentConfig.EmuOpt = eo_old;
372 static void RunEvents(unsigned int which)
374 if (which & 0x1800) // save or load (but not both)
379 FrameworkAudio_SetPause(1);
380 if (giz_screen == NULL)
381 giz_screen = Framework2D_LockBuffer(1);
382 if ( emu_checkSaveFile(state_slot) &&
383 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
384 (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
387 blit("", (which & 0x1000) ? "LOAD STATE? (PLAY=yes, STOP=no)" : "OVERWRITE SAVE? (PLAY=yes, STOP=no)");
388 while( !((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) )
390 if (keys & BTN_STOP) do_it = 0;
391 while( ((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) ) // wait for release
398 osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");
399 PicoStateProgressCB = emu_stateCb;
400 emu_SaveLoadGame((which & 0x1000) >> 12, 0);
401 PicoStateProgressCB = NULL;
406 FrameworkAudio_SetPause(0);
409 if (which & 0x0400) // switch renderer
411 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |= 0x80; }
412 else { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
417 strcpy(noticeMsg, " 8bit fast renderer");
418 } else if (currentConfig.EmuOpt&0x80) {
419 strcpy(noticeMsg, "16bit accurate renderer");
421 strcpy(noticeMsg, " 8bit accurate renderer");
424 noticeMsgTime = GetTickCount();
430 if(state_slot < 0) state_slot = 9;
433 if(state_slot > 9) state_slot = 0;
435 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
436 noticeMsgTime = GetTickCount();
440 static void updateKeys(void)
442 unsigned int keys, allActions[2] = { 0, 0 }, events;
443 static unsigned int prevEvents = 0;
446 keys = Framework_PollGetButtons();
448 engineState = PGS_Menu;
450 keys &= CONFIGURABLE_KEYS;
452 for (i = 0; i < 32; i++)
456 int pl, acts = currentConfig.KeyBinds[i];
458 pl = (acts >> 16) & 1;
459 if (kb_combo_keys & (1 << i))
461 int u = i+1, acts_c = acts & kb_combo_acts;
462 // let's try to find the other one
465 if ( (keys & (1 << u)) && (currentConfig.KeyBinds[u] & acts_c) ) {
466 allActions[pl] |= acts_c & currentConfig.KeyBinds[u];
467 keys &= ~((1 << i) | (1 << u));
471 // add non-combo actions if combo ones were not found
472 if (!acts_c || u == 32)
473 allActions[pl] |= acts & ~kb_combo_acts;
475 allActions[pl] |= acts;
480 PicoPad[0] = allActions[0] & 0xfff;
481 PicoPad[1] = allActions[1] & 0xfff;
483 if (allActions[0] & 0x7000) emu_DoTurbo(&PicoPad[0], allActions[0]);
484 if (allActions[1] & 0x7000) emu_DoTurbo(&PicoPad[1], allActions[1]);
486 events = (allActions[0] | allActions[1]) >> 16;
488 // volume is treated in special way and triggered every frame
489 if ((events & 0x6000) && PsndOut != NULL)
491 int vol = currentConfig.volume;
492 if (events & 0x2000) {
493 if (vol < 100) vol++;
497 FrameworkAudio_SetVolume(vol, vol);
498 sprintf(noticeMsg, "VOL: %02i ", vol);
499 noticeMsgTime = GetTickCount();
500 currentConfig.volume = vol;
503 events &= ~prevEvents;
504 if (events) RunEvents(events);
505 if (movie_data) emu_updateMovie();
507 prevEvents = (allActions[0] | allActions[1]) >> 16;
511 static void simpleWait(DWORD until)
516 tval = GetTickCount();
517 diff = (int)until - (int)tval;
521 while ((tval = GetTickCount()) < until && until - tval < 512) // some simple overflow detection
522 spend_cycles(1024*2);
527 static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
528 char fpsbuff[24]; // fps count c string
529 DWORD tval, tval_prev = 0, tval_thissec = 0; // timing
530 int frames_done = 0, frames_shown = 0, oldmodes = 0, sec_ms = 1000;
531 int target_fps, target_frametime, lim_time, tval_diff, i;
534 lprintf("entered emu_Loop()\n");
538 // make sure we are in correct mode
540 if (currentConfig.scaling) PicoOpt|=0x4000;
541 else PicoOpt&=~0x4000;
543 oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
544 emu_findKeyBindCombos();
546 // pal/ntsc might have changed, reset related stuff
547 target_fps = Pico.m.pal ? 50 : 60;
548 target_frametime = Pico.m.pal ? (1000<<8)/50 : (1000<<8)/60+1;
552 if (PicoAHW & PAHW_MCD) PicoCDBufferInit();
554 // prepare sound stuff
556 if (currentConfig.EmuOpt & 4)
558 int ret, snd_excess_add, stereo;
559 if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
560 PsndRerate(Pico.m.frame_count ? 1 : 0);
562 stereo=(PicoOpt&8)>>3;
563 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;
564 snd_cbuf_samples = (PsndRate<<stereo) * 16 / target_fps;
565 lprintf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",
566 PsndRate, PsndLen, snd_excess_add, stereo, Pico.m.pal);
567 ret = FrameworkAudio_Init(PsndRate, snd_cbuf_samples, stereo);
569 lprintf("FrameworkAudio_Init() failed: %i\n", ret);
570 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
571 noticeMsgTime = GetTickCount();
572 currentConfig.EmuOpt &= ~4;
574 FrameworkAudio_SetVolume(currentConfig.volume, currentConfig.volume);
575 PicoWriteSound = updateSound;
576 snd_cbuff = FrameworkAudio_56448Buffer();
577 PsndOut = snd_cbuff + snd_cbuf_samples / 2; // start writing at the middle
579 PsndRate_old = PsndRate;
580 PicoOpt_old = PicoOpt;
581 pal_old = Pico.m.pal;
586 while (engineState == PGS_Running)
590 tval = GetTickCount();
591 if (reset_timing || tval < tval_prev) {
592 //stdbg("timing reset");
595 frames_shown = frames_done = 0;
598 // show notice message?
600 static int noticeMsgSum;
601 if (tval - noticeMsgTime > 2000) { // > 2.0 sec
606 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
607 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
612 // check for mode changes
613 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
614 if (modes != oldmodes) {
620 if (tval - tval_thissec >= sec_ms)
623 static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
626 bench_fps_s = bench_fps;
627 bf[bfp++ & 3] = bench_fps;
630 bench_fps += frames_shown;
631 sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
633 if(currentConfig.EmuOpt & 2)
634 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);
636 //tval_thissec += 1000;
637 tval_thissec += sec_ms;
641 /* some code which tries to sync things to audio clock, the dirty way */
642 static int audio_skew_prev = 0;
643 int audio_skew, adj, co = 9, shift = 7;
644 audio_skew = snd_all_samples*2 - FrameworkAudio_BufferPos();
645 if (PsndRate == 22050) co = 10;
646 if (PsndRate > 22050) co = 11;
647 if (PicoOpt&8) shift++;
648 if (audio_skew < 0) {
649 adj = -((-audio_skew) >> shift);
650 if (audio_skew > -(6<<co)) adj>>=1;
651 if (audio_skew > -(4<<co)) adj>>=1;
652 if (audio_skew > -(2<<co)) adj>>=1;
653 if (audio_skew > audio_skew_prev) adj>>=2; // going up already
655 adj = audio_skew >> shift;
656 if (audio_skew < (6<<co)) adj>>=1;
657 if (audio_skew < (4<<co)) adj>>=1;
658 if (audio_skew < (2<<co)) adj>>=1;
659 if (audio_skew < audio_skew_prev) adj>>=2;
661 audio_skew_prev = audio_skew;
662 target_frametime += adj;
663 sec_ms = (target_frametime * target_fps) >> 8;
664 //stdbg("%i %i %i", audio_skew, adj, sec_ms);
665 frames_done = frames_shown = 0;
667 else if (currentConfig.Frameskip < 0) {
668 frames_done -= target_fps; if (frames_done < 0) frames_done = 0;
669 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
670 if (frames_shown > frames_done) frames_shown = frames_done;
672 frames_done = frames_shown = 0;
676 sprintf(fpsbuff, "%i", Pico.m.frame_count);
680 lim_time = (frames_done+1) * target_frametime;
681 if (currentConfig.Frameskip >= 0) // frameskip enabled
683 for (i = 0; i < currentConfig.Frameskip; i++) {
685 SkipFrame(); frames_done++;
686 if (PsndOut) { // do framelimitting if sound is enabled
688 tval = GetTickCount();
689 tval_diff = (int)(tval - tval_thissec) << 8;
690 if (tval_diff < lim_time) // we are too fast
691 simpleWait(tval + ((lim_time - tval_diff)>>8));
693 lim_time += target_frametime;
696 else // auto frameskip
699 tval = GetTickCount();
700 tval_diff = (int)(tval - tval_thissec) << 8;
701 if (tval_diff > lim_time)
703 // no time left for this frame - skip
704 if (tval_diff - lim_time >= (300<<8)) {
705 /* something caused a slowdown for us (disk access? cache flush?)
706 * try to recover by resetting timing... */
711 SkipFrame(); frames_done++;
718 if (currentConfig.EmuOpt&0x80)
719 /* be sure correct framebuffer is locked */
720 giz_screen = Framework2D_LockBuffer((currentConfig.EmuOpt&0x8000) ? 0 : 1);
724 if (giz_screen == NULL)
725 giz_screen = Framework2D_LockBuffer((currentConfig.EmuOpt&0x8000) ? 0 : 1);
727 blit(fpsbuff, notice);
729 if (giz_screen != NULL) {
730 Framework2D_UnlockBuffer();
734 if (currentConfig.EmuOpt&0x2000)
735 Framework2D_WaitVSync();
737 if (currentConfig.EmuOpt&0x8000)
741 tval = GetTickCount();
742 tval_diff = (int)(tval - tval_thissec) << 8;
744 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300<<8)) // slowdown detection
746 else if (PsndOut != NULL || currentConfig.Frameskip < 0)
748 // sleep if we are still too fast
749 if (tval_diff < lim_time)
752 simpleWait(tval + ((lim_time - tval_diff) >> 8));
756 frames_done++; frames_shown++;
760 if (PicoAHW & PAHW_MCD) PicoCDBufferFree();
762 if (PsndOut != NULL) {
763 PsndOut = snd_cbuff = NULL;
764 FrameworkAudio_Close();
768 if ((currentConfig.EmuOpt & 1) && SRam.changed) {
769 emu_stateCb("Writing SRAM/BRAM..");
770 emu_SaveLoadGame(0, 1);
776 void emu_ResetGame(void)