forked from scottferg/Fergulator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
machine.go
301 lines (241 loc) · 5.44 KB
/
machine.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"runtime"
"runtime/pprof"
"strings"
)
var (
cpuClockSpeed = 1789773
running = true
audioEnabled = true
cpu Cpu
ppu Ppu
apu Apu
rom Mapper
video Video
audio Audio
pads [2]*Controller
totalCpuCycles int
gamename string
saveStateFile string
batteryRamFile string
cpuprofile = flag.String("cprof", "", "write cpu profile to file")
)
const (
SaveState = iota
LoadState
)
func setResetVector() {
high, _ := Ram.Read(0xFFFD)
low, _ := Ram.Read(0xFFFC)
ProgramCounter = (uint16(high) << 8) + uint16(low)
}
func LoadGameState() {
fmt.Println("Loading state")
state, err := ioutil.ReadFile(saveStateFile)
if err != nil {
fmt.Println(err.Error())
return
}
for i, v := range state[:0x2000] {
Ram[i] = Word(v)
}
pchigh := uint16(state[0x2000])
pclow := uint16(state[0x2001])
ProgramCounter = (pchigh << 8) | pclow
cpu.A = Word(state[0x2002])
cpu.X = Word(state[0x2003])
cpu.Y = Word(state[0x2004])
cpu.P = Word(state[0x2005])
cpu.StackPointer = Word(state[0x2006])
// Sprite RAM
for i, v := range state[0x2007:0x2107] {
ppu.SpriteRam[i] = Word(v)
}
// Pattern VRAM
for i, v := range state[0x2107:0x4107] {
ppu.Vram[i] = Word(v)
}
// Nametable VRAM
for i, v := range state[0x4107:0x4507] {
ppu.Nametables.LogicalTables[0][i] = Word(v)
}
for i, v := range state[0x4507:0x4907] {
ppu.Nametables.LogicalTables[1][i] = Word(v)
}
for i, v := range state[0x4907:0x4D07] {
ppu.Nametables.LogicalTables[2][i] = Word(v)
}
for i, v := range state[0x4D07:0x5107] {
ppu.Nametables.LogicalTables[3][i] = Word(v)
}
// Palette RAM
for i, v := range state[0x5107:0x5126] {
ppu.PaletteRam[i] = Word(v)
}
}
func SaveGameState() {
fmt.Println("Saving state")
buf := new(bytes.Buffer)
// RAM
for _, v := range Ram[:0x2000] {
buf.WriteByte(byte(v))
}
// ProgramCounter
// High then low
buf.WriteByte(byte(ProgramCounter>>8) & 0xFF)
buf.WriteByte(byte(ProgramCounter & 0xFF))
// CPU Registers
buf.WriteByte(byte(cpu.A))
buf.WriteByte(byte(cpu.X))
buf.WriteByte(byte(cpu.Y))
buf.WriteByte(byte(cpu.P))
buf.WriteByte(byte(cpu.StackPointer))
// Sprite RAM
for _, v := range ppu.SpriteRam {
buf.WriteByte(byte(v))
}
// Pattern VRAM
for _, v := range ppu.Vram[:0x2000] {
buf.WriteByte(byte(v))
}
// Nametable VRAM
for _, v := range ppu.Nametables.LogicalTables[0] {
buf.WriteByte(byte(v))
}
for _, v := range ppu.Nametables.LogicalTables[1] {
buf.WriteByte(byte(v))
}
for _, v := range ppu.Nametables.LogicalTables[2] {
buf.WriteByte(byte(v))
}
for _, v := range ppu.Nametables.LogicalTables[3] {
buf.WriteByte(byte(v))
}
// Palette RAM
for _, v := range ppu.PaletteRam {
buf.WriteByte(byte(v))
}
if err := ioutil.WriteFile(saveStateFile, buf.Bytes(), 0644); err != nil {
panic(err.Error())
}
}
func loadBatteryRam() {
fmt.Println("Loading battery RAM")
batteryRam, err := ioutil.ReadFile(batteryRamFile)
if err != nil {
fmt.Println(err.Error())
return
}
for i, v := range batteryRam[:0x2000] {
Ram[0x6000+i] = Word(v)
}
}
func saveBatteryFile() {
buf := new(bytes.Buffer)
// Battery/Work RAM
for _, v := range Ram[0x6000:0x7FFF] {
buf.WriteByte(byte(v))
}
if err := ioutil.WriteFile(batteryRamFile, buf.Bytes(), 0644); err != nil {
panic(err.Error())
}
fmt.Println("Battery RAM saved to disk")
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
if len(os.Args) < 2 {
fmt.Println("Please specify a ROM file")
return
}
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
pads[0] = new(Controller)
pads[1] = new(Controller)
pads[0].Init(0)
pads[1].Init(0)
Ram.Init()
cpu.Init()
v := ppu.Init()
al := apu.Init()
if contents, err := ioutil.ReadFile(os.Args[len(os.Args)-1]); err == nil {
if rom, err = LoadRom(contents); err != nil {
fmt.Println(err.Error())
return
}
// Set the game name for save states
path := strings.Split(os.Args[1], "/")
gamename = strings.Split(path[len(path)-1], ".")[0]
saveStateFile = fmt.Sprintf(".%s.state", gamename)
batteryRamFile = fmt.Sprintf(".%s.battery", gamename)
if rom.BatteryBacked() {
loadBatteryRam()
defer saveBatteryFile()
}
setResetVector()
} else {
fmt.Println(err.Error())
return
}
interrupt := make(chan int)
a := NewAudio(al)
defer a.Close()
go a.Run()
// Main runloop, in a separate goroutine so that
// the video rendering can happen on this one
go func(c <-chan int) {
var lastApuTick int
var cycles int
var flip int
for running {
select {
case s := <-c:
switch s {
case LoadState:
LoadGameState()
case SaveState:
SaveGameState()
}
default:
cycles = cpu.Step()
totalCpuCycles += cycles
for i := 0; i < 3*cycles; i++ {
ppu.Step()
}
for i := 0; i < cycles; i++ {
apu.Step()
}
if audioEnabled {
if totalCpuCycles-apu.LastFrameTick >= (cpuClockSpeed / 240) {
apu.FrameSequencerStep()
apu.LastFrameTick = totalCpuCycles
}
if totalCpuCycles-lastApuTick >= ((cpuClockSpeed / 44100) + flip) {
apu.PushSample()
lastApuTick = totalCpuCycles
flip = (flip + 1) & 0x1
}
}
}
}
}(interrupt)
r := video.Init(v, gamename)
go ReadInput(r, interrupt)
// This needs to happen on the main thread for OSX
runtime.LockOSThread()
video.Render()
return
}