aboutsummaryrefslogtreecommitdiff
path: root/nes/nes.go
blob: 5d96e8f5f8136ab8765690fbf4eb8e85e5e34a0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package nes

import (
	"crecher.net/gones/v2/cart"
	"crecher.net/gones/v2/cpu"
	"crecher.net/gones/v2/ppu"
)

type Console struct {
	CPU  *cpu.CPU
	PPU  *ppu.PPU
	Cart *cart.Cartridge
	RAM  [0x800]uint8

	controllers [2]controller
	dmaPending  bool
	// APU once it exists
	cycles uint64
}

func New(c *cart.Cartridge) *Console {
	n := &Console{Cart: c}
	n.PPU = ppu.New(c.Mapper, c.Mirroring)
	n.CPU = cpu.NewCPU(n)
	n.CPU.Reset()
	return n
}

func (n *Console) Step() int {
	cycles := n.CPU.Step()
	if n.dmaPending {
		n.dmaPending = false
		stall := n.dmaStallCycles()
		n.CPU.Stall(stall)
		cycles += stall
	}
	n.cycles += uint64(cycles)
	for i := 0; i < cycles*3; i++ {
		n.PPU.Tick()
		if n.PPU.PollNMI() {
			n.CPU.NMI()
		}
	}
	return cycles
}

// runs until the PPU finishes a frame, the framebuffer then holds a full picture
func (n *Console) StepFrame() {
	frame := n.PPU.Frame
	for n.PPU.Frame == frame {
		n.Step()
	}
}