asm cpu works, added sync()s
[fceu.git] / fce.c
1 /* FCE Ultra - NES/Famicom Emulator
2  *
3  * Copyright notice for this file:
4  *  Copyright (C) 1998 BERO
5  *  Copyright (C) 2002 Ben Parnell
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include        <string.h>
23 #include        <stdio.h>
24 #include        <stdlib.h>
25
26 #include        "types.h"
27 #include        "x6502.h"
28 #include        "fce.h"
29 #include        "sound.h"
30 #include        "svga.h"
31 #include        "netplay.h"
32 #include        "general.h"
33 #include        "endian.h"
34 #include        "version.h"
35 #include        "memory.h"
36
37 #include        "cart.h"
38 #include        "nsf.h"
39 #include        "fds.h"
40 #include        "ines.h"
41 #include        "unif.h"
42 #include        "cheat.h"
43
44 #include        "state.h"
45 #include        "video.h"
46 #include        "input.h"
47 #include        "file.h"
48 #include        "crc32.h"
49 #include        "ppu.h"
50
51 #define Pal     (PALRAM)
52
53
54 #ifdef DEBUG_ASM_6502
55 extern int cpu_repeat;
56 extern int cpu_lastval;
57 #endif
58
59 static void (*RefreshLine)(uint8 *P, uint32 vofs) = NULL;
60 static void PRefreshLine(void);
61
62 static void ResetPPU(void);
63 static void PowerPPU(void);
64
65 uint64 timestampbase=0;
66
67 int MMC5Hack;
68 uint32 MMC5HackVROMMask;
69 uint8 *MMC5HackExNTARAMPtr;
70 uint8 *MMC5HackVROMPTR;
71 uint8 MMC5HackCHRMode=0;
72 uint8 MMC5HackSPMode;
73 uint8 MMC5HackSPScroll;
74 uint8 MMC5HackSPPage;
75
76 uint8 *MMC5SPRVPage[8];
77 uint8 *MMC5BGVPage[8];
78
79
80 uint8 VRAMBuffer,PPUGenLatch;
81
82 uint8 *vnapage[4];
83 uint8 PPUNTARAM;
84 uint8 PPUCHRRAM;
85
86 /* Color deemphasis emulation.  Joy... */
87 static uint8 deemp=0;
88 static int deempcnt[8];
89
90 int tosprite=256;
91
92 FCEUGI FCEUGameInfo;
93 void (*GameInterface)(int h);
94
95 void FP_FASTAPASS(1) (*PPU_hook)(uint32 A);
96
97 void (*GameStateRestore)(int version);
98 void (*GameHBIRQHook)(void);
99
100 readfunc ARead[0x10000];
101 writefunc BWrite[0x10000];
102 static readfunc *AReadG;
103 static writefunc *BWriteG;
104 static int RWWrap=0;
105
106 #ifdef ASM_6502
107 static void asmcpu_update(int32 cycles)
108 {
109  // timestamp..
110  timestamp += ((cycles >> 4) * 43) >> 7; // aproximating /= 48
111
112  // some code from x6502.c
113  fhcnt-=cycles;
114  if(fhcnt<=0)
115  {
116   FrameSoundUpdate();
117   fhcnt+=fhinc;
118  }
119
120  if(PCMIRQCount>0)
121  {
122   PCMIRQCount-=cycles;
123   if(PCMIRQCount<=0)
124   {
125    vdis=1;
126    if((PSG[0x10]&0x80) && !(PSG[0x10]&0x40))
127    {
128     extern uint8 SIRQStat;
129     SIRQStat|=0x80;
130     X6502_IRQBegin(FCEU_IQDPCM);
131    }
132   }
133  }
134 }
135
136 void asmcpu_unpack(void)
137 {
138         nes_registers[0] = X.A << 24;
139         nes_registers[1] = X.X;
140         nes_registers[2] = X.Y;
141         pc_base = 0;
142         nes_registers[3] = X.PC;
143         X6502_rebase_a();
144         nes_registers[4] = X.S << 24;
145         nes_registers[4]|= X.IRQlow << 8;
146         nes_registers[7] = (uint32)X.count;
147
148         // NVUB DIZC
149         nes_registers[4]|= X.P & 0x5d;
150         nes_registers[5] = X.P << 24; // N
151         if (!(X.P&0x02)) nes_registers[5] |= 1; // Z
152 }
153
154 void asmcpu_pack(void)
155 {
156         X.A = nes_registers[0] >> 24;
157         X.X = nes_registers[1];
158         X.Y = nes_registers[2];
159         X.PC= nes_registers[3] - pc_base;
160         X.S = nes_registers[4] >> 24;
161         X.IRQlow = nes_registers[4] >> 8;
162         X.count = (int32) nes_registers[7];
163
164         // NVUB DIZC
165         X.P = nes_registers[4] & 0x5d;
166         if (  nes_registers[5]&0x80000000)  X.P |= 0x80; // N
167         if (!(nes_registers[5]&0x000000ff)) X.P |= 0x02; // Z
168 }
169 #endif
170
171 DECLFW(BNull)
172 {
173
174 }
175
176 DECLFR(ANull)
177 {
178  return(X.DB);
179 }
180
181 int AllocGenieRW(void)
182 {
183  if(!(AReadG=FCEU_malloc(0x8000*sizeof(readfunc))))
184   return 0;
185  if(!(BWriteG=FCEU_malloc(0x8000*sizeof(writefunc))))
186   return 0;
187  RWWrap=1;
188  return 1;
189 }
190
191 void FlushGenieRW(void)
192 {
193  int32 x;
194
195  if(RWWrap)
196  {
197   for(x=0;x<0x8000;x++)
198   {
199    ARead[x+0x8000]=AReadG[x];
200    BWrite[x+0x8000]=BWriteG[x];
201   }
202   free(AReadG);
203   free(BWriteG);
204   AReadG=0;
205   BWriteG=0;
206   RWWrap=0;
207  }
208 }
209
210 readfunc FASTAPASS(1) GetReadHandler(int32 a)
211 {
212   if(a>=0x8000 && RWWrap)
213    return AReadG[a-0x8000];
214   else
215    return ARead[a];
216 }
217
218 void FASTAPASS(3) SetReadHandler(int32 start, int32 end, readfunc func)
219 {
220   int32 x;
221
222   if(!func)
223    func=ANull;
224
225   if(RWWrap)
226    for(x=end;x>=start;x--)
227    {
228     if(x>=0x8000)
229      AReadG[x-0x8000]=func;
230     else
231      ARead[x]=func;
232    }
233   else
234
235    for(x=end;x>=start;x--)
236     ARead[x]=func;
237 }
238
239 writefunc FASTAPASS(1) GetWriteHandler(int32 a)
240 {
241   if(RWWrap && a>=0x8000)
242    return BWriteG[a-0x8000];
243   else
244    return BWrite[a];
245 }
246
247 void FASTAPASS(3) SetWriteHandler(int32 start, int32 end, writefunc func)
248 {
249   int32 x;
250
251   if(!func)
252    func=BNull;
253
254   if(RWWrap)
255    for(x=end;x>=start;x--)
256    {
257     if(x>=0x8000)
258      BWriteG[x-0x8000]=func;
259     else
260      BWrite[x]=func;
261    }
262   else
263    for(x=end;x>=start;x--)
264     BWrite[x]=func;
265 }
266
267 uint8 vtoggle=0;
268 uint8 XOffset=0;
269
270 uint32 TempAddr,RefreshAddr;
271
272
273 /* scanline is equal to the current visible scanline we're on. */
274
275 int scanline;
276
277 uint8 GameMemBlock[131072] __attribute__ ((aligned (4)));
278 uint8 NTARAM[0x800] __attribute__ ((aligned (4)));
279 uint8 PALRAM[0x20] __attribute__ ((aligned (4)));
280 #if !defined(ASM_6502) || defined(DEBUG_ASM_6502)
281 uint8 RAM[0x800] __attribute__ ((aligned (4)));
282 #endif
283
284 uint8 PPU[4];
285 uint8 PPUSPL;
286
287 uint8 PAL=0;
288
289
290 #define MMC5BGVRAMADR(V)      &MMC5BGVPage[(V)>>10][(V)]
291 #define VRAMADR(V)      &VPage[(V)>>10][(V)]
292
293 static DECLFW(BRAML)
294 {
295         RAM[A]=V;
296 }
297
298 static DECLFW(BRAMH)
299 {
300         RAM[A&0x7FF]=V;
301 }
302
303 static DECLFR(ARAML)
304 {
305         return RAM[A];
306 }
307
308 static DECLFR(ARAMH)
309 {
310         return RAM[A&0x7FF];
311 }
312
313
314 static DECLFR(A2002)
315 {
316                         uint8 ret;
317 #ifdef DEBUG_ASM_6502
318         if (cpu_repeat) return cpu_lastval;
319 #endif
320                         ret = PPU_status;
321                         vtoggle=0;
322                         PPU_status&=0x7F;
323 #ifdef DEBUG_ASM_6502
324         cpu_lastval=ret|(PPUGenLatch&0x1F);
325 #endif
326                         return ret|(PPUGenLatch&0x1F);
327 }
328
329 static DECLFR(A200x)
330 {
331                         return PPUGenLatch;
332 }
333
334 static DECLFR(A2007)
335 {
336                         uint8 ret;
337                         uint32 tmp=RefreshAddr&0x3FFF;
338 #ifdef DEBUG_ASM_6502
339         if (cpu_repeat) return cpu_lastval;
340 #endif
341
342                         PPUGenLatch=ret=VRAMBuffer;
343                         if(PPU_hook) PPU_hook(tmp);
344                         if(tmp<0x2000)
345                         {
346                          VRAMBuffer=VPage[tmp>>10][tmp];
347                         }
348                         else
349                         {
350                          VRAMBuffer=vnapage[(tmp>>10)&0x3][tmp&0x3FF];
351                         }
352
353                         if (INC32) RefreshAddr+=32;
354                         else RefreshAddr++;
355                         if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
356 #ifdef DEBUG_ASM_6502
357         cpu_lastval=ret;
358 #endif
359                         return ret;
360 }
361
362 static DECLFW(B2000)
363 {
364                 PPUGenLatch=V;
365                 PPU[0]=V;
366                 TempAddr&=0xF3FF;
367                 TempAddr|=(V&3)<<10;
368 }
369
370 static DECLFW(B2001)
371 {
372                   PPUGenLatch=V;
373                   PPU[1]=V;
374                   if(V&0xE0)
375                    deemp=V>>5;
376                   //printf("$%04x:$%02x, %d\n",X.PC,V,scanline);
377 }
378
379 static DECLFW(B2002)
380 {
381                  PPUGenLatch=V;
382 }
383
384 static DECLFW(B2003)
385 {
386                 PPUGenLatch=V;
387                 PPU[3]=V;
388                 PPUSPL=V&0x7;
389 }
390
391 static DECLFW(B2004)
392 {
393                 PPUGenLatch=V;
394                 //SPRAM[PPU[3]++]=V;
395                 if(PPUSPL&8)
396                 {
397                  if(PPU[3]>=8)
398                   SPRAM[PPU[3]]=V;
399                 }
400                 else
401                 {
402                  //printf("$%02x:$%02x\n",PPUSPL,V);
403                  SPRAM[PPUSPL]=V;
404                  PPUSPL++;
405                 }
406                 PPU[3]++;
407
408 }
409
410 static DECLFW(B2005)
411 {
412                 uint32 tmp=TempAddr;
413
414                 PPUGenLatch=V;
415                 if (!vtoggle)
416                 {
417                  tmp&=0xFFE0;
418                  tmp|=V>>3;
419                  XOffset=V&7;
420                 }
421                 else
422                 {
423                  tmp&=0x8C1F;
424                  tmp|=((V&~0x7)<<2);
425                  tmp|=(V&7)<<12;
426                 }
427
428                 TempAddr=tmp;
429                 vtoggle^=1;
430 }
431
432 static DECLFW(B2006)
433 {
434                        PPUGenLatch=V;
435                        if(!vtoggle)
436                        {
437                         TempAddr&=0x00FF;
438                         TempAddr|=(V&0x3f)<<8;
439                        }
440                        else
441                        {
442                         TempAddr&=0xFF00;
443                         TempAddr|=V;
444                         RefreshAddr=TempAddr;
445
446                         if(PPU_hook)
447                          PPU_hook(RefreshAddr);
448                        }
449                       vtoggle^=1;
450 }
451
452 static DECLFW(B2007)
453 {
454                         uint32 tmp=RefreshAddr&0x3FFF;
455
456                         PPUGenLatch=V;
457                         if(tmp>=0x3F00)
458                         {
459                         // hmmm....
460                         if(!(tmp&0xf))
461                          PALRAM[0x00]=PALRAM[0x04]=PALRAM[0x08]=PALRAM[0x0C]=
462                          PALRAM[0x10]=PALRAM[0x14]=PALRAM[0x18]=PALRAM[0x1c]=V&0x3f;
463                         else if(tmp&3) PALRAM[(tmp&0x1f)]=V&0x3f;
464                         }
465                         else if(tmp<0x2000)
466                         {
467                           if(PPUCHRRAM&(1<<(tmp>>10)))
468                             VPage[tmp>>10][tmp]=V;
469                         }
470                         else
471                         {
472                          if(PPUNTARAM&(1<<((tmp&0xF00)>>10)))
473                           vnapage[((tmp&0xF00)>>10)][tmp&0x3FF]=V;
474                         }
475                         if (INC32) RefreshAddr+=32;
476                         else RefreshAddr++;
477                         if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
478 }
479
480 static DECLFW(B4014)
481 {
482         uint32 t=V<<8;
483         int x;
484 #ifdef DEBUG_ASM_6502
485   if (cpu_repeat) { X6502_AddCycles_a(512); return; }
486         for(x=0;x<256;x++)
487          B2004(0x2004,X.DB=ARead[t+x](t+x));
488         X6502_AddCycles_c(512);
489 #else
490         for(x=0;x<256;x++)
491          B2004(0x2004,X.DB=ARead[t+x](t+x));
492         X6502_AddCycles(512);
493 #endif
494 }
495
496 void BGRender(uint8 *target)
497 {
498         uint32 tem, vofs;
499         vofs=((PPU[0]&0x10)<<8) | ((RefreshAddr>>12)&7);
500
501         Pal[0]|=64;
502         Pal[4]|=64;
503         Pal[8]|=64;
504         Pal[0xC]|=64;
505         RefreshLine(target-XOffset, vofs);
506         Pal[0]&=63;
507         Pal[4]&=63;
508         Pal[8]&=63;
509         Pal[0xC]&=63;
510
511         if(!(PPU[1]&2))
512         {
513          tem=Pal[0]|0x40;
514          tem|=tem<<8;
515          tem|=tem<<16;
516          *(uint32 *)target=*(uint32 *)(target+4)=tem;
517         }
518 }
519
520 #ifdef FRAMESKIP
521 int FSkip_setting=-1; // auto
522 int FSkip=0;
523 void FCEUI_FrameSkip(int x)
524 {
525  FSkip=x;
526 }
527 #endif
528
529 /*      This is called at the beginning of each visible scanline */
530 static void Loop6502(void)
531 {
532         uint32 tem;
533         int x;
534         uint8 *target=XBuf+scanline*320+32;
535
536         if(ScreenON || SpriteON)
537         {
538          /* PRefreshLine() will not get called on skipped frames.  This
539             could cause a problem, but the solution would be rather complex,
540             due to the current sprite 0 hit code.
541          */
542          #ifdef FRAMESKIP
543          if(!FSkip)
544          {
545          #endif
546           if(ScreenON)
547           {
548            if(scanline>=FSettings.FirstSLine && scanline<=FSettings.LastSLine)
549             BGRender(target);
550            else
551            {
552             if(PPU_hook)
553              PRefreshLine();
554            }
555           }
556           else
557           {
558            tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
559            tem|=0x40404040;
560            FCEU_dwmemset(target,tem,264);
561           }
562          #ifdef FRAMESKIP
563          }
564          #endif
565          if (SpriteON && scanline)
566           RefreshSprite(target);
567          #ifdef FRAMESKIP
568          if(!FSkip)
569          {
570          #endif
571           if(PPU[1]&0x01)
572           {
573            for(x=63;x>=0;x--)
574             ((uint32 *)target)[x]=((uint32*)target)[x]&0xF0F0F0F0;
575           }
576            if((PPU[1]>>5)==0x7)
577             for(x=63;x>=0;x--)
578              ((uint32 *)target)[x]=(((uint32*)target)[x]&0x3f3f3f3f)|0x40404040;
579            else if(PPU[1]&0xE0)
580             for(x=63;x>=0;x--)
581              ((uint32 *)target)[x]=((uint32*)target)[x]|0xC0C0C0C0;
582            else
583             for(x=63;x>=0;x--)
584              ((uint32 *)target)[x]=((uint32*)target)[x]&0x3f3f3f3f;
585           FCEU_dwmemset(target-  8,0x3f3f3f3f,8);
586           FCEU_dwmemset(target+256,0x3f3f3f3f,8);
587          #ifdef FRAMESKIP
588          }
589          #endif
590         }
591         else
592         {
593          tem=Pal[0]|(Pal[0]<<8)|(Pal[0]<<16)|(Pal[0]<<24);
594          FCEU_dwmemset(target,tem,256);
595         }
596         if(InputScanlineHook)
597          InputScanlineHook(target, scanline);
598 }
599
600 #define PAL(c)  ((c)+cc)
601
602
603 static void PRefreshLine(void)
604 {
605         uint32 vofs;
606         uint8 X1;
607
608         vofs = 0;
609         if (BGAdrHI) vofs = 0x1000;
610
611         vofs+=(RefreshAddr>>12)&7;
612
613         for(X1=33;X1;X1--)
614         {
615                 register uint8 no;
616                 register uint8 zz2;
617                 zz2=(uint8)((RefreshAddr>>10)&3);
618                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
619                 no  = vnapage[zz2][(RefreshAddr&0x3ff)];
620                 PPU_hook((no<<4)+vofs);
621                 if((RefreshAddr&0x1f)==0x1f)
622                  RefreshAddr^=0x41F;
623                 else
624                  RefreshAddr++;
625         }
626 }
627
628 /* This high-level graphics MMC5 emulation code was written
629    for MMC5 carts in "CL" mode.  It's probably not totally
630    correct for carts in "SL" mode.
631    */
632 static void RefreshLine_MMC5Hack1(uint8 *P, uint32 vofs)
633 {
634           int8 tochange, X1;
635
636           tochange=MMC5HackSPMode&0x1F;
637
638           for(X1=33;X1;X1--,P+=8)
639           {
640                 uint8 *C;
641                 uint8 cc,zz,zz2;
642                 uint32 vadr;
643
644                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
645                    (tochange>0 && !(MMC5HackSPMode&0x40)))
646                 {
647                  uint8 xs,ys;
648
649                  xs=33-X1;
650                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
651                  if(ys>=0x1E) ys-=0x1E;
652                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
653
654                  C = MMC5HackVROMPTR+vadr;
655                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
656
657                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
658                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
659                 }
660                 else
661                 {
662                  zz=RefreshAddr&0x1F;
663                  zz2=(RefreshAddr>>10)&3;
664                  vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
665                  C = MMC5BGVRAMADR(vadr);
666                  cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
667                  cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
668                 }
669                 #include "fceline.h"
670
671                 if((RefreshAddr&0x1f)==0x1f)
672                  RefreshAddr^=0x41F;
673                 else
674                  RefreshAddr++;
675                 tochange--;
676           }
677 }
678
679 static void RefreshLine_MMC5Hack2(uint8 *P, uint32 vofs)
680 {
681           int8 tochange, X1;
682
683           tochange=MMC5HackSPMode&0x1F;
684
685           for(X1=33;X1;X1--,P+=8)
686           {
687                 uint8 *C;
688                 uint8 cc;
689                 uint8 zz2;
690                 uint32 vadr;
691
692                 if((tochange<=0 && MMC5HackSPMode&0x40) ||
693                    (tochange>0 && !(MMC5HackSPMode&0x40)))
694                 {
695                  uint8 xs,ys;
696
697                  xs=33-X1;
698                  ys=((scanline>>3)+MMC5HackSPScroll)&0x1F;
699                  if(ys>=0x1E) ys-=0x1E;
700                  vadr=(MMC5HackExNTARAMPtr[xs|(ys<<5)]<<4)+(vofs&7);
701
702                  C = MMC5HackVROMPTR+vadr;
703                  C += ((MMC5HackSPPage & 0x3f & MMC5HackVROMMask) << 12);
704
705                  cc=MMC5HackExNTARAMPtr[0x3c0+(xs>>2)+((ys&0x1C)<<1)];
706                  cc=((cc >> ((xs&2) + ((ys&0x2)<<1))) &3) <<2;
707                 }
708                 else
709                 {
710                  C=MMC5HackVROMPTR;
711                  zz2=(RefreshAddr>>10)&3;
712                  vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
713                  C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
714                          MMC5HackVROMMask) << 12) + (vadr & 0xfff);
715                  vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
716                  cc = vadr;
717                 }
718                 #include "fceline.h"
719                 if((RefreshAddr&0x1f)==0x1f)
720                  RefreshAddr^=0x41F;
721                 else
722                  RefreshAddr++;
723                 tochange--;
724           }
725 }
726
727 static void RefreshLine_MMC5Hack3(uint8 *P, uint32 vofs)
728 {
729           int8 X1;
730
731           for(X1=33;X1;X1--,P+=8)
732           {
733                 uint8 *C;
734                 uint8 cc;
735                 uint8 zz2;
736                 uint32 vadr;
737
738                 C=MMC5HackVROMPTR;
739                 zz2=(RefreshAddr>>10)&3;
740                 vadr = (vnapage[zz2][RefreshAddr & 0x3ff] << 4) + vofs;
741                 C += (((MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff]) & 0x3f &
742                         MMC5HackVROMMask) << 12) + (vadr & 0xfff);
743                 vadr = (MMC5HackExNTARAMPtr[RefreshAddr & 0x3ff] & 0xC0)>> 4;
744                 cc = vadr;
745
746                 #include "fceline.h"
747                 if((RefreshAddr&0x1f)==0x1f)
748                  RefreshAddr^=0x41F;
749                 else
750                  RefreshAddr++;
751           }
752 }
753
754 static void RefreshLine_MMC5Hack4(uint8 *P, uint32 vofs)
755 {
756           int8 X1;
757
758           for(X1=33;X1;X1--,P+=8)
759           {
760                 uint8 *C;
761                 uint8 cc,zz,zz2;
762                 uint32 vadr;
763
764                 zz=RefreshAddr&0x1F;
765                 zz2=(RefreshAddr>>10)&3;
766                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
767                 C = MMC5BGVRAMADR(vadr);
768                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
769                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
770
771                 #include "fceline.h"
772
773                 if((RefreshAddr&0x1f)==0x1f)
774                  RefreshAddr^=0x41F;
775                 else
776                  RefreshAddr++;
777           }
778 }
779
780 static void RefreshLine_PPU_hook(uint8 *P, uint32 vofs)
781 {
782          int8 X1;
783
784          for(X1=33;X1;X1--,P+=8)
785          {
786                 uint8 *C;
787                 uint8 cc,zz,zz2;
788                 uint32 vadr;
789
790                 zz=RefreshAddr&0x1F;
791                 zz2=(RefreshAddr>>10)&3;
792                 PPU_hook(0x2000|(RefreshAddr&0xFFF));
793                 cc=vnapage[zz2][0x3c0+(zz>>2)+((RefreshAddr&0x380)>>4)];
794                 cc=((cc >> ((zz&2) + ((RefreshAddr&0x40)>>4))) &3) <<2;
795                 vadr=(vnapage[zz2][RefreshAddr&0x3ff]<<4)+vofs;
796                 C = VRAMADR(vadr);
797
798                 #include "fceline.h"
799
800                 PPU_hook(vadr);
801
802                 if((RefreshAddr&0x1f)==0x1f)
803                  RefreshAddr^=0x41F;
804                 else
805                  RefreshAddr++;
806          }
807 }
808
809 static void RefreshLine_normal(uint8 *P, uint32 vofs) // vofs is 0x107 max
810 {
811          int8 X1;
812          uint32 rfraddr = RefreshAddr;
813          uint8 *page = vnapage[(rfraddr>>10)&3];
814          uint32 cc2=0;
815
816          if ((rfraddr&0xc)!=0)
817           cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
818
819          for (X1=33;X1;X1--,P+=8)
820          {
821                 uint8 cc,*C;
822                 uint32 vadr;
823
824                 vadr=(page[rfraddr&0x3ff]<<4)+vofs;
825                 C = VRAMADR(vadr);
826                 if ((rfraddr&0xc)==0)
827                  cc2=*(uint32 *) (page + ((rfraddr&0x380)>>4) + ((rfraddr&0x10)>>2) + 0x3c0);
828                 cc=((cc2 >> ((rfraddr&2) + ((rfraddr&0x40)>>4) + ((rfraddr&0xc)<<1))) & 3) << 2;
829
830                 #include "fceline.h"
831
832                 if((rfraddr&0x1f)==0x1f) {
833                  rfraddr^=0x41F;
834                  page = vnapage[(rfraddr>>10)&3];
835                 } else
836                  rfraddr++;
837          }
838          RefreshAddr = rfraddr;
839 }
840
841 static void SetRefreshLine(void)
842 {
843         if(MMC5Hack && geniestage!=1)
844         {
845          if(MMC5HackCHRMode==0 && (MMC5HackSPMode&0x80))
846          {
847                  if (RefreshLine != RefreshLine_MMC5Hack1) printf("set refr RefreshLine_MMC5Hack1\n");
848                  RefreshLine = RefreshLine_MMC5Hack1;
849          }
850          else if(MMC5HackCHRMode==1 && (MMC5HackSPMode&0x80))
851          {
852                 if (RefreshLine != RefreshLine_MMC5Hack2) printf("set refr RefreshLine_MMC5Hack2\n");
853                  RefreshLine = RefreshLine_MMC5Hack2;
854          }
855          else if(MMC5HackCHRMode==1)
856          {
857                 if (RefreshLine != RefreshLine_MMC5Hack3) printf("set refr RefreshLine_MMC5Hack3\n");
858                  RefreshLine = RefreshLine_MMC5Hack3;
859          }
860          else
861          {
862                 if (RefreshLine != RefreshLine_MMC5Hack4) printf("set refr RefreshLine_MMC5Hack4\n");
863                  RefreshLine = RefreshLine_MMC5Hack4;
864          }
865         }       // End if(MMC5Hack)
866         else if(PPU_hook)
867         {
868                 if (RefreshLine != RefreshLine_PPU_hook) printf("set refr RefreshLine_PPU_hook\n");
869                 RefreshLine = RefreshLine_PPU_hook;
870         }
871         else
872         {
873                 if (RefreshLine != RefreshLine_normal) printf("set refr RefreshLine_normal\n");
874                 RefreshLine = RefreshLine_normal;
875         }
876 }
877
878 //static INLINE
879 void Fixit2(void)
880 {
881    if(ScreenON || SpriteON)
882    {
883     uint32 rad=RefreshAddr;
884     rad&=0xFBE0;
885     rad|=TempAddr&0x041f;
886     RefreshAddr=rad;
887     //PPU_hook(RefreshAddr,-1);
888    }
889 }
890
891 //static INLINE
892 void Fixit1(void)
893 {
894    if(ScreenON || SpriteON)
895    {
896     uint32 rad=RefreshAddr;
897
898     if((rad&0x7000)==0x7000)
899     {
900      rad^=0x7000;
901      if((rad&0x3E0)==0x3A0)
902      {
903       rad^=0x3A0;
904       rad^=0x800;
905      }
906      else
907      {
908       if((rad&0x3E0)==0x3e0)
909        rad^=0x3e0;
910       else rad+=0x20;
911      }
912     }
913     else
914      rad+=0x1000;
915     RefreshAddr=rad;
916     //PPU_hook(RefreshAddr,-1);
917    }
918 }
919
920 //#define NEW_TRY
921
922 /*      This is called at the beginning of all h-blanks on visible lines. */
923 #ifndef NEW_TRY
924 static void DoHBlank(void)
925 {
926  if(ScreenON || SpriteON)
927   FetchSpriteData();
928  if(GameHBIRQHook && (ScreenON || SpriteON))
929  {
930   X6502_Run(12);
931   GameHBIRQHook();
932   X6502_Run(25-12);
933   Fixit2();
934   X6502_Run(85-25);
935  }
936  else
937  {
938   X6502_Run(25);        // Tried 65, caused problems with Slalom(maybe others)
939   Fixit2();
940   X6502_Run(85-25);
941  }
942  //PPU_hook(0,-1);
943  //fprintf(stderr,"%3d: $%04x\n",scanline,RefreshAddr);
944 }
945 #endif
946
947
948 // ============================//
949 // end of new code
950 // ===========================//
951
952 void ResetMapping(void)
953 {
954         int x;
955
956         SetReadHandler(0x0000,0xFFFF,ANull);
957         SetWriteHandler(0x0000,0xFFFF,BNull);
958
959         SetReadHandler(0,0x7FF,ARAML);
960         SetWriteHandler(0,0x7FF,BRAML);
961
962         SetReadHandler(0x800,0x1FFF,ARAMH);  /* Part of a little */
963         SetWriteHandler(0x800,0x1FFF,BRAMH); /* hack for a small speed boost. */
964
965         for(x=0x2000;x<0x4000;x+=8)
966         {
967          ARead[x]=A200x;
968          BWrite[x]=B2000;
969          ARead[x+1]=A200x;
970          BWrite[x+1]=B2001;
971          ARead[x+2]=A2002;
972          BWrite[x+2]=B2002;
973          ARead[x+3]=A200x;
974          BWrite[x+3]=B2003;
975          ARead[x+4]=A200x;
976          BWrite[x+4]=B2004;
977          ARead[x+5]=A200x;
978          BWrite[x+5]=B2005;
979          ARead[x+6]=A200x;
980          BWrite[x+6]=B2006;
981          ARead[x+7]=A2007;
982          BWrite[x+7]=B2007;
983         }
984
985         BWrite[0x4014]=B4014;
986         SetNESSoundMap();
987         InitializeInput();
988 }
989
990 int GameLoaded=0;
991 void CloseGame(void)
992 {
993  if(GameLoaded)
994  {
995   if(FCEUGameInfo.type!=GIT_NSF)
996    FlushGameCheats();
997   #ifdef NETWORK
998   if(FSettings.NetworkPlay) KillNetplay();
999   #endif
1000   GameInterface(GI_CLOSE);
1001   CloseGenie();
1002   GameLoaded=0;
1003  }
1004 }
1005
1006 void ResetGameLoaded(void)
1007 {
1008         if(GameLoaded) CloseGame();
1009         GameStateRestore=0;
1010         PPU_hook=0;
1011         GameHBIRQHook=0;
1012         GameExpSound.Fill=0;
1013         GameExpSound.RChange=0;
1014         if(GameExpSound.Kill)
1015          GameExpSound.Kill();
1016         GameExpSound.Kill=0;
1017         MapIRQHook=0;
1018         MMC5Hack=0;
1019         PAL&=1;
1020         pale=0;
1021
1022         FCEUGameInfo.name=0;
1023         FCEUGameInfo.type=GIT_CART;
1024         FCEUGameInfo.vidsys=GIV_USER;
1025         FCEUGameInfo.input[0]=FCEUGameInfo.input[1]=-1;
1026         FCEUGameInfo.inputfc=-1;
1027 }
1028
1029 FCEUGI *FCEUI_LoadGame(char *name)
1030 {
1031         int fp;
1032
1033         Exit=1;
1034         ResetGameLoaded();
1035
1036         fp=FCEU_fopen(name,"rb");
1037         if(!fp)
1038         {
1039          FCEU_PrintError("Error opening \"%s\"!",name);
1040          return 0;
1041         }
1042
1043         GetFileBase(name);
1044         if(iNESLoad(name,fp))
1045          goto endlseq;
1046         if(NSFLoad(fp))
1047          goto endlseq;
1048         if(FDSLoad(name,fp))
1049          goto endlseq;
1050         if(UNIFLoad(name,fp))
1051          goto endlseq;
1052
1053         FCEU_PrintError("An error occurred while loading the file.");
1054         FCEU_fclose(fp);
1055         return 0;
1056
1057         endlseq:
1058         FCEU_fclose(fp);
1059         GameLoaded=1;
1060
1061         FCEU_ResetVidSys();
1062         if(FCEUGameInfo.type!=GIT_NSF)
1063          if(FSettings.GameGenie)
1064           OpenGenie();
1065
1066         PowerNES();
1067         #ifdef NETWORK
1068         if(FSettings.NetworkPlay) InitNetplay();
1069         #endif
1070         SaveStateRefresh();
1071         if(FCEUGameInfo.type!=GIT_NSF)
1072         {
1073          LoadGamePalette();
1074          LoadGameCheats();
1075         }
1076
1077         FCEU_ResetPalette();
1078         Exit=0;
1079         return(&FCEUGameInfo);
1080 }
1081
1082
1083 void FCEU_ResetVidSys(void)
1084 {
1085  int w;
1086
1087  if(FCEUGameInfo.vidsys==GIV_NTSC)
1088   w=0;
1089  else if(FCEUGameInfo.vidsys==GIV_PAL)
1090   w=1;
1091  else
1092   w=FSettings.PAL;
1093
1094  if(w)
1095  {
1096   PAL=1;
1097   FSettings.FirstSLine=FSettings.UsrFirstSLine[1];
1098   FSettings.LastSLine=FSettings.UsrLastSLine[1];
1099  }
1100  else
1101  {
1102   PAL=0;
1103   FSettings.FirstSLine=FSettings.UsrFirstSLine[0];
1104   FSettings.LastSLine=FSettings.UsrLastSLine[0];
1105  }
1106  printf("PAL = %i\n", PAL);
1107  SetSoundVariables();
1108 }
1109
1110 int FCEUI_Initialize(void)
1111 {
1112         if(!InitVirtualVideo())
1113          return 0;
1114         memset(&FSettings,0,sizeof(FSettings));
1115         FSettings.UsrFirstSLine[0]=8;
1116         FSettings.UsrFirstSLine[1]=0;
1117         FSettings.UsrLastSLine[0]=FSettings.UsrLastSLine[1]=239;
1118         FSettings.SoundVolume=65535;    // 100%
1119         return 1;
1120 }
1121
1122 #define harko 0xe //0x9
1123 static INLINE void Thingo(void)
1124 {
1125    Loop6502();
1126 #ifndef NEW_TRY
1127
1128    if(tosprite>=256)
1129    {
1130     X6502_Run(256-harko);
1131     Fixit1();
1132     X6502_Run(harko);
1133    }
1134    else
1135    {
1136     if(tosprite<=240)
1137     {
1138      X6502_Run(tosprite);
1139      PPU[2]|=0x40;
1140      X6502_Run(256-tosprite-harko);
1141      Fixit1();
1142      X6502_Run(harko);
1143     }
1144     else
1145     {
1146      X6502_Run(256-harko);
1147      Fixit1();
1148      X6502_Run(tosprite-(256-harko));
1149      PPU[2]|=0x40;
1150      X6502_Run(256-tosprite);
1151     }
1152     tosprite=256;
1153    }
1154    DoHBlank();
1155 #else
1156    X6502_Run_scanline();
1157 #endif
1158 }
1159 #undef harko
1160
1161 void EmLoop(void)
1162 {
1163  for(;;)
1164  {
1165   uint32 scanlines_per_frame = PAL ? 312 : 262;
1166         //extern int asdc;
1167         //printf("asdc: %i\n", asdc);
1168         //asdc=0;
1169   ApplyPeriodicCheats();
1170   X6502_Run(256+85);
1171
1172   PPU[2]|=0x80;
1173   PPU[3]=PPUSPL=0;             /* Not sure if this is correct.  According
1174                                   to Matt Conte and my own tests, it is.  Timing is probably
1175                                   off, though.  NOTE:  Not having this here
1176                                   breaks a Super Donkey Kong game. */
1177
1178   X6502_Run(12);                /* I need to figure out the true nature and length
1179                                    of this delay.
1180                                 */
1181   if(FCEUGameInfo.type==GIT_NSF)
1182    TriggerNMINSF();
1183   else if(VBlankON)
1184    TriggerNMI();
1185
1186   X6502_Run(256+85-12);
1187   for(scanline=242+1;scanline<scanlines_per_frame;scanline++)
1188     X6502_Run(256+85);
1189
1190   PPU_status&=0x1f;
1191
1192   X6502_Run(256);
1193   {
1194    static int kook=0;
1195    if(ScreenON || SpriteON)
1196     if(GameHBIRQHook)
1197      GameHBIRQHook();
1198
1199    X6502_Run(85-kook);
1200    kook=(kook+1)&1;
1201   }
1202
1203   if(ScreenON || SpriteON)
1204   {
1205    RefreshAddr=TempAddr;
1206    if(PPU_hook) PPU_hook(RefreshAddr&0x3fff);
1207   }
1208   if(FCEUGameInfo.type==GIT_NSF)
1209   {
1210    X6502_Run((256+85)*240);
1211   }
1212   else
1213   {
1214    int x,max,maxref;
1215
1216    deemp=PPU[1]>>5;
1217    SetRefreshLine();
1218    for(scanline=0;scanline<240;scanline++)
1219    {
1220     deempcnt[deemp]++;
1221     Thingo();
1222    }
1223    for(x=1,max=0,maxref=0;x<7;x++)
1224    {
1225     if(deempcnt[x]>max)
1226     {
1227      max=deempcnt[x];
1228      maxref=x;
1229     }
1230     deempcnt[x]=0;
1231    }
1232    //FCEU_DispMessage("%2x:%2x:%2x:%2x:%2x:%2x:%2x:%2x %d",deempcnt[0],deempcnt[1],deempcnt[2],deempcnt[3],deempcnt[4],deempcnt[5],deempcnt[6],deempcnt[7],maxref);
1233    //memset(deempcnt,0,sizeof(deempcnt));
1234    SetNESDeemph(maxref,0);
1235   }
1236
1237   {
1238    int ssize;
1239
1240    ssize=FlushEmulateSound();
1241
1242    #ifdef FRAMESKIP
1243    if(FSkip)
1244    {
1245     FCEU_PutImageDummy();
1246     FSkip--;
1247     FCEUD_Update(0,WaveFinalMono,ssize);
1248    }
1249    else
1250    #endif
1251    {
1252     FCEU_PutImage();
1253     FCEUD_Update(XBuf+8,WaveFinalMono,ssize);
1254    }
1255    UpdateInput();
1256   }
1257
1258   if(Exit)
1259   {
1260    CloseGame();
1261    break;
1262   }
1263
1264  }
1265 }
1266
1267 #ifdef FPS
1268 #include <sys/time.h>
1269 uint64 frcount;
1270 #endif
1271 void FCEUI_Emulate(void)
1272 {
1273         #ifdef FPS
1274         uint64 starttime,end;
1275         struct timeval tv;
1276         frcount=0;
1277         gettimeofday(&tv,0);
1278         starttime=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1279         #endif
1280         EmLoop();
1281
1282         #ifdef FPS
1283         // Probably won't work well on Windows port; for
1284         // debugging/speed testing.
1285         {
1286          uint64 w;
1287          int i,frac;
1288          gettimeofday(&tv,0);
1289          end=((uint64)tv.tv_sec*1000000)+tv.tv_usec;
1290          w=frcount*10000000000LL/(end-starttime);
1291          i=w/10000;
1292          frac=w-i*10000;
1293          printf("Average FPS: %d.%04d\n",i,frac);
1294         }
1295         #endif
1296
1297 }
1298
1299 void FCEUI_CloseGame(void)
1300 {
1301         Exit=1;
1302 }
1303
1304 static void ResetPPU(void)
1305 {
1306         VRAMBuffer=PPU[0]=PPU[1]=PPU[2]=PPU[3]=0;
1307         PPUSPL=0;
1308         PPUGenLatch=0;
1309         RefreshAddr=TempAddr=0;
1310         vtoggle = 0;
1311 }
1312
1313 static void PowerPPU(void)
1314 {
1315         memset(NTARAM,0x00,0x800);
1316         memset(PALRAM,0x00,0x20);
1317         memset(SPRAM,0x00,0x100);
1318         ResetPPU();
1319 }
1320
1321 void ResetNES(void)
1322 {
1323         if(!GameLoaded || (FCEUGameInfo.type==GIT_NSF)) return;
1324         GameInterface(GI_RESETM2);
1325         ResetSound();
1326         ResetPPU();
1327         X6502_Reset();
1328 }
1329
1330 void PowerNES(void)
1331 {
1332         if(!GameLoaded) return;
1333
1334         FCEU_CheatResetRAM();
1335         FCEU_CheatAddRAM(2,0,RAM);
1336
1337         GeniePower();
1338
1339 printf("X.DB offs: %02x\n", (int)&X.DB - (int)&X);
1340
1341         memset(RAM,0x00,0x800);
1342         ResetMapping();
1343         GameInterface(GI_POWER);
1344         PowerSound();
1345         PowerPPU();
1346         timestampbase=0;
1347         X6502_Power();
1348 }
1349