-
Notifications
You must be signed in to change notification settings - Fork 1
/
dmgo.go
586 lines (505 loc) · 12.6 KB
/
dmgo.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package dmgo
import (
"fmt"
)
type cpuState struct {
// everything here marshalled for snapshot
PC uint16
SP uint16
A, F, B, C, D, E, H, L byte
Mem mem
Title string
HeaderChecksum byte
LCD lcd
APU apu
InHaltMode bool
InStopMode bool
OAMDMAActive bool
OAMDMAIndex uint16
OAMDMASource uint16
CGBMode bool
FastMode bool
SpeedSwitchPrepped bool
IRDataReadEnable bool
IRSendDataEnable bool
InterruptMasterEnable bool
MasterEnableRequested bool
VBlankInterruptEnabled bool
LCDStatInterruptEnabled bool
TimerInterruptEnabled bool
SerialInterruptEnabled bool
JoypadInterruptEnabled bool
DummyEnableBits [3]bool
VBlankIRQ bool
LCDStatIRQ bool
TimerIRQ bool
SerialIRQ bool
JoypadIRQ bool
SerialTransferData byte
SerialTransferStartFlag bool
SerialTransferClockIsInternal bool
SerialFastMode bool
SerialClock uint16
SerialBitsTransferred byte
TimerOn bool
TimerLag int
TimerModuloReg byte
TimerCounterReg byte
TimerFreqSelector byte
TimerDivCycles uint16 // div reg is top 8 bits of this
Joypad Joypad
Steps uint
Cycles uint
devMode bool
debugger debugger
}
func (cs *cpuState) SetDevMode(b bool) { cs.devMode = b }
func (cs *cpuState) InDevMode() bool { return cs.devMode }
func (cs *cpuState) runSerialCycle() {
if !cs.SerialTransferStartFlag {
cs.SerialBitsTransferred = 0
cs.SerialClock = 0
return
}
if !cs.SerialTransferClockIsInternal {
// no real link cable, so wait forever
// (hopefully til game times out transfer)
return
}
cs.SerialClock++
if cs.SerialClock == 512 { // 8192Hz
cs.SerialClock = 0
cs.SerialTransferData <<= 1
// emulate a disconnected cable
cs.SerialTransferData |= 0x01
cs.SerialBitsTransferred++
if cs.SerialBitsTransferred == 8 {
cs.SerialBitsTransferred = 0
cs.SerialClock = 0
cs.SerialIRQ = true
}
}
}
// NOTE: timer is more complicated than this.
// See TCAGBD
func (cs *cpuState) runTimerCycle() {
cs.TimerDivCycles++
if !cs.TimerOn {
return
}
if cs.TimerLag > 0 {
cs.TimerLag--
if cs.TimerLag == 0 && cs.TimerCounterReg == 0 {
cs.TimerCounterReg = cs.TimerModuloReg
cs.TimerIRQ = true
}
}
cycleCount := [...]uint16{
1024, 16, 64, 256,
}[cs.TimerFreqSelector]
if cs.TimerDivCycles&(cycleCount-1) == 0 {
cs.TimerCounterReg++
if cs.TimerCounterReg == 0 {
cs.TimerLag = 4
}
}
}
func (cs *cpuState) readTimerControlReg() byte {
return 0xf8 | boolBit(cs.TimerOn, 2) | cs.TimerFreqSelector
}
func (cs *cpuState) writeTimerControlReg(val byte) {
cs.TimerOn = val&0x04 != 0
cs.TimerFreqSelector = val & 0x03
}
func (cs *cpuState) readSerialControlReg() byte {
return byteFromBools(
cs.SerialTransferStartFlag,
true,
true,
true,
true,
true,
cs.SerialFastMode,
cs.SerialTransferClockIsInternal,
)
}
func (cs *cpuState) writeSerialControlReg(val byte) {
cs.SerialTransferStartFlag = val&0x80 != 0
cs.SerialTransferClockIsInternal = val&0x01 != 0
if cs.CGBMode {
cs.SerialFastMode = val&0x02 != 0
}
}
// Joypad represents the buttons on a gameboy
type Joypad struct {
Sel bool
Start bool
Up bool
Down bool
Left bool
Right bool
A bool
B bool
readMask byte
}
func (jp *Joypad) writeJoypadReg(val byte) {
jp.readMask = (val >> 4) & 0x03
}
func (jp *Joypad) readJoypadReg() byte {
val := 0xc0 | (jp.readMask << 4) | 0x0f
if jp.readMask&0x01 == 0 {
val &^= boolBit(jp.Down, 3)
val &^= boolBit(jp.Up, 2)
val &^= boolBit(jp.Left, 1)
val &^= boolBit(jp.Right, 0)
}
if jp.readMask&0x02 == 0 {
val &^= boolBit(jp.Start, 3)
val &^= boolBit(jp.Sel, 2)
val &^= boolBit(jp.B, 1)
val &^= boolBit(jp.A, 0)
}
return val
}
func (cs *cpuState) updateJoypad(newJP Joypad) {
lastVal := cs.Joypad.readJoypadReg() & 0x0f
mask := cs.Joypad.readMask
cs.Joypad = newJP
cs.Joypad.readMask = mask
newVal := cs.Joypad.readJoypadReg() & 0x0f
// this is correct behavior. it only triggers irq
// if it goes from no-buttons-pressed to any-pressed.
if lastVal == 0x0f && newVal < lastVal {
cs.JoypadIRQ = true
}
}
func (cs *cpuState) writeIRPortReg(val byte) {
cs.IRDataReadEnable = val&0xc0 == 0xc0
cs.IRSendDataEnable = val&0x01 == 0x01
}
func (cs *cpuState) readIRPortReg() byte {
out := byte(0)
if cs.IRDataReadEnable {
out |= 0xc2 // no data received
}
if cs.IRSendDataEnable {
out |= 0x01
}
return out
}
func (cs *cpuState) writeInterruptEnableReg(val byte) {
boolsFromByte(val,
&cs.DummyEnableBits[2],
&cs.DummyEnableBits[1],
&cs.DummyEnableBits[0],
&cs.JoypadInterruptEnabled,
&cs.SerialInterruptEnabled,
&cs.TimerInterruptEnabled,
&cs.LCDStatInterruptEnabled,
&cs.VBlankInterruptEnabled,
)
}
func (cs *cpuState) readInterruptEnableReg() byte {
return byteFromBools(
cs.DummyEnableBits[2],
cs.DummyEnableBits[1],
cs.DummyEnableBits[0],
cs.JoypadInterruptEnabled,
cs.SerialInterruptEnabled,
cs.TimerInterruptEnabled,
cs.LCDStatInterruptEnabled,
cs.VBlankInterruptEnabled,
)
}
func (cs *cpuState) writeInterruptFlagReg(val byte) {
boolsFromByte(val,
nil, nil, nil,
&cs.JoypadIRQ,
&cs.SerialIRQ,
&cs.TimerIRQ,
&cs.LCDStatIRQ,
&cs.VBlankIRQ,
)
}
func (cs *cpuState) readInterruptFlagReg() byte {
return byteFromBools(
true, true, true,
cs.JoypadIRQ,
cs.SerialIRQ,
cs.TimerIRQ,
cs.LCDStatIRQ,
cs.VBlankIRQ,
)
}
func newState(cart []byte, devMode bool) *cpuState {
cartInfo := ParseCartInfo(cart)
state := cpuState{
Title: cartInfo.Title,
HeaderChecksum: cartInfo.HeaderChecksum,
Mem: mem{
cart: cart,
CartRAM: make([]byte, cartInfo.GetRAMSize()),
InternalRAMBankNumber: 1,
mbc: makeMBC(cartInfo),
},
CGBMode: cartInfo.cgbOptional() || cartInfo.cgbOnly(),
devMode: devMode,
}
state.init()
return &state
}
func (cs *cpuState) init() {
if cs.CGBMode {
cs.setAF(0x1180)
cs.setBC(0x0000)
cs.setDE(0xff56)
cs.setHL(0x000d)
} else {
cs.setAF(0x01b0)
cs.setBC(0x0013)
cs.setDE(0x00d8)
cs.setHL(0x014d)
}
cs.setSP(0xfffe)
cs.setPC(0x0100)
cs.TimerDivCycles = 0xabcc
cs.LCD.init(cs)
cs.APU.init()
cs.Mem.mbc.Init(&cs.Mem)
cs.initIORegs()
cs.APU.Sounds[0].RestartRequested = false
cs.APU.Sounds[1].RestartRequested = false
cs.APU.Sounds[2].RestartRequested = false
cs.APU.Sounds[3].RestartRequested = false
cs.initVRAM()
cs.VBlankIRQ = true
}
func (cs *cpuState) initIORegs() {
cs.write(0xff10, 0x80)
cs.write(0xff11, 0xbf)
cs.write(0xff12, 0xf3)
cs.write(0xff14, 0xbf)
cs.write(0xff17, 0x3f)
cs.write(0xff19, 0xbf)
cs.write(0xff1a, 0x7f)
cs.write(0xff1b, 0xff)
cs.write(0xff1c, 0x9f)
cs.write(0xff1e, 0xbf)
cs.write(0xff20, 0xff)
cs.write(0xff23, 0xbf)
cs.write(0xff24, 0x77)
cs.write(0xff25, 0xf3)
cs.write(0xff26, 0xf1)
cs.write(0xff40, 0x91)
cs.write(0xff47, 0xfc)
cs.write(0xff48, 0xff)
cs.write(0xff49, 0xff)
}
func (cs *cpuState) initVRAM() {
nibbleLookup := []byte{
0x00, 0x03, 0x0c, 0x0f, 0x30, 0x33, 0x3c, 0x3f,
0xc0, 0xc3, 0xcc, 0xcf, 0xf0, 0xf3, 0xfc, 0xff,
}
hdrTileData := []byte{}
for i := 0x104; i < 0x104+48; i++ {
packed := cs.read(uint16(i))
b1, b2 := nibbleLookup[packed>>4], nibbleLookup[packed&0x0f]
hdrTileData = append(hdrTileData, b1, 0, b1, 0, b2, 0, b2, 0)
}
// append boot rom tile data
hdrTileData = append(hdrTileData,
0x3c, 0x00, 0x42, 0x00, 0xb9, 0x00, 0xa5, 0x00, 0xb9, 0x00, 0xa5, 0x00, 0x42, 0x00, 0x3c, 0x00,
)
bootTileMap := []byte{
0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
}
for i := range hdrTileData {
cs.write(uint16(0x8010+i), hdrTileData[i])
}
for i := range bootTileMap {
cs.write(uint16(0x9900+i), bootTileMap[i])
}
}
func (cs *cpuState) runOAMDMACycle() {
i := cs.OAMDMAIndex
addr := cs.OAMDMASource
cs.write(0xfe00+i, cs.read(addr+i))
cs.OAMDMAIndex++
if cs.OAMDMAIndex == 0xa0 {
cs.OAMDMAActive = false
}
}
func (cs *cpuState) runCycles(numCycles uint) {
// Things that speed up to match fast mode
for i := uint(0); i < numCycles; i++ {
cs.Cycles++
cs.runTimerCycle()
cs.runSerialCycle()
if cs.OAMDMAActive {
cs.runOAMDMACycle()
}
}
if cs.FastMode {
numCycles >>= 1
}
// Things that don't speed up with fast mode
for i := uint(0); i < numCycles; i++ {
cs.APU.runCycle(cs)
cs.LCD.runCycle(cs)
}
}
func (cs *cpuState) readSpeedSwitchReg() byte {
return byteFromBools(cs.FastMode,
true, true, true,
true, true, true,
cs.SpeedSwitchPrepped,
)
}
func (cs *cpuState) writeSpeedSwitchReg(val byte) {
cs.SpeedSwitchPrepped = val&0x01 == 0x01
}
func (cs *cpuState) handleSpeedSwitching() {
// TODO: accurate timing
if cs.SpeedSwitchPrepped {
cs.SpeedSwitchPrepped = false
cs.FastMode = !cs.FastMode
}
}
// Emulator exposes the public facing fns for an emulation session
type Emulator interface {
Step()
Framebuffer() []byte
FlipRequested() bool
UpdateInput(input Input)
ReadSoundBuffer([]byte) []byte
GetSoundBufferInfo() SoundBufferInfo
GetCartRAM() []byte
SetCartRAM([]byte) error
MakeSnapshot() []byte
LoadSnapshot([]byte) (Emulator, error)
InDevMode() bool
SetDevMode(b bool)
UpdateDbgKeyState([]bool)
DbgStep()
}
func (cs *cpuState) UpdateDbgKeyState(keys []bool) {
cs.debugger.updateInput(keys)
}
func (cs *cpuState) MakeSnapshot() []byte {
return cs.makeSnapshot()
}
func (cs *cpuState) LoadSnapshot(snapBytes []byte) (Emulator, error) {
return cs.loadSnapshot(snapBytes)
}
// NewEmulator creates an emulation session
func NewEmulator(cart []byte, devMode bool) Emulator {
return newState(cart, devMode)
}
// Input covers all outside info sent to the Emulator
type Input struct {
Joypad Joypad
}
// ReadSoundBuffer returns a 44100hz * 16bit * 2ch sound buffer.
// A pre-sized buffer must be provided, which is returned resized
// if the buffer was less full than the length requested.
func (cs *cpuState) ReadSoundBuffer(toFill []byte) []byte {
return cs.APU.readSoundBuffer(toFill)
}
// SoundBufferInfo gives info about the sound buffer. IsValid is used to
// handle Emulator impls that don't have sound, e.g. errEmu
type SoundBufferInfo struct {
UsedSize int
IsValid bool
}
// GetSoundBufferLen gets the current size of the filled sound buffer.
func (cs *cpuState) GetSoundBufferInfo() SoundBufferInfo {
return SoundBufferInfo{
IsValid: true,
UsedSize: int(cs.APU.buffer.size()),
}
}
// GetCartRAM returns the current state of external RAM
func (cs *cpuState) GetCartRAM() []byte {
return append([]byte{}, cs.Mem.CartRAM...)
}
// SetCartRAM attempts to set the RAM, returning error if size not correct
func (cs *cpuState) SetCartRAM(ram []byte) error {
if len(cs.Mem.CartRAM) == len(ram) {
copy(cs.Mem.CartRAM, ram)
return nil
}
// TODO: better checks if possible (e.g. real format, cart title/checksum, etc.)
return fmt.Errorf("ram size mismatch")
}
func (cs *cpuState) UpdateInput(input Input) {
cs.updateJoypad(input.Joypad)
}
// Framebuffer returns the current state of the lcd screen
func (cs *cpuState) Framebuffer() []byte {
return cs.LCD.framebuffer[:]
}
// FlipRequested indicates if a draw request is pending
// and clears it before returning
func (cs *cpuState) FlipRequested() bool {
val := cs.LCD.FlipRequested
cs.LCD.FlipRequested = false
return val
}
var lastSP = int(-1)
func (cs *cpuState) debugLineOnStackChange() {
if lastSP != int(cs.SP) {
lastSP = int(cs.SP)
fmt.Println(cs.DebugStatusLine())
}
}
// Step steps the emulator one instruction
func (cs *cpuState) Step() {
cs.step()
}
func (cs *cpuState) DbgStep() {
cs.debugger.step(cs)
}
var hitTarget = false
func (cs *cpuState) step() {
ieAndIfFlagMatch := cs.handleInterrupts()
if cs.InHaltMode {
if ieAndIfFlagMatch {
cs.runCycles(4)
cs.InHaltMode = false
} else {
cs.runCycles(4)
return
}
}
// cs.debugLineOnStackChange()
// if cs.Steps&0x2ffff == 0 {
// if cs.PC == 0x4d19 {
// hitTarget = true
// }
// if hitTarget {
// fmt.Println(cs.DebugStatusLine())
// }
// fmt.Fprintln(os.Stderr, cs.DebugStatusLine())
// TODO: correct behavior, i.e. only resume on
// button press if not about to switch speeds.
if cs.InStopMode {
cs.TimerDivCycles = 0
cs.handleSpeedSwitching()
cs.runCycles(4)
cs.InStopMode = false
}
// this is here to lag behind the request by
// one instruction.
if cs.MasterEnableRequested {
cs.MasterEnableRequested = false
cs.InterruptMasterEnable = true
}
cs.Steps++
cs.stepOpcode()
}
func fatalErr(v ...interface{}) {
fmt.Println(v...)
panic("fatalErr()")
}