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