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