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