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