-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
242 lines (202 loc) · 4.96 KB
/
main.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
package main
// typedef unsigned char Uint8;
// void AudioCallback(void *userdata, Uint8 *stream, int len);
import "C"
import (
"flag"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"reflect"
"runtime"
"time"
"unsafe"
"github.com/pmcatominey/gochip8/chip8"
"github.com/veandco/go-sdl2/sdl"
)
const (
toneHz = 440
sampleHz = 4800
dPhase = 2 * math.Pi * toneHz / sampleHz
)
// Config
var (
// If this flag is present, the rom shold be loaded then output to stdout line by line with
// an explanation of each opcode
disassemble = flag.Bool("disassemble", false, "disassemble to stdout")
// Scale factor for upscaling the display from Chip 8 resolution of 64*32
scaleFactor = flag.Int("scaling", 10, "scale factor to multiply Chip 8 resolution (64*32) by")
// Controls execution speed, useful since some roms play at mad speeds compared to others
cyclesPerLoop = flag.Int("cycles", 10, "steps to emulate per loop")
// Default key bindings
defaultKeyBindings = map[sdl.Keycode]chip8.Key{
sdl.K_1: chip8.Key1, sdl.K_2: chip8.Key2, sdl.K_3: chip8.Key3, sdl.K_4: chip8.KeyC, // 1 2 3 4
sdl.K_q: chip8.Key4, sdl.K_w: chip8.Key5, sdl.K_e: chip8.Key6, sdl.K_r: chip8.KeyD, // Q W E R
sdl.K_a: chip8.Key7, sdl.K_s: chip8.Key8, sdl.K_d: chip8.Key9, sdl.K_f: chip8.KeyE, // A S D F
sdl.K_z: chip8.KeyA, sdl.K_x: chip8.Key0, sdl.K_c: chip8.KeyB, sdl.K_v: chip8.KeyF, // Z X C V
}
keyBindings = defaultKeyBindings
)
// State
var (
c8 *chip8.Chip8
window *sdl.Window
renderer *sdl.Renderer
// Reuse pixel for drawing
pixel = &sdl.Rect{
W: int32(*scaleFactor),
H: int32(*scaleFactor),
}
exitChan = make(chan bool, 1) // true sent this channel to exit main loop
)
func main() {
flag.Parse()
romFile := flag.Arg(0)
if len(romFile) == 0 {
fmt.Println("no rom file specified")
os.Exit(1)
}
program := readProgram(romFile)
if *disassemble {
fmt.Println("Disassembling ROM to stdout")
disassembleROM(program)
} else {
fmt.Println("Running ROM")
runROM(program)
}
}
func readProgram(filename string) []byte {
if program, err := ioutil.ReadFile(filename); err != nil {
fmt.Println("error reading from rom file:", err.Error())
os.Exit(1)
return nil
} else {
return program
}
}
func setupSDL() {
var (
w = *scaleFactor * chip8.DisplayWidth
h = *scaleFactor * chip8.DisplayHeight
romName = filepath.Base(flag.Arg(0))
err error
)
sdl.Init(sdl.INIT_VIDEO | sdl.INIT_AUDIO)
window, err = sdl.CreateWindow("gochip8 - "+romName, sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, w, h, 0)
if err != nil {
panic(err)
}
renderer, err = sdl.CreateRenderer(window, -1, 0)
if err != nil {
panic(err)
}
// audio spec
spec := &sdl.AudioSpec{
Freq: sampleHz,
Format: sdl.AUDIO_U8,
Channels: 2,
Samples: sampleHz,
Callback: sdl.AudioCallback(C.AudioCallback),
}
sdl.OpenAudio(spec, nil)
}
func cleanUpSDL() {
renderer.Destroy()
window.Destroy()
sdl.Quit()
}
func runROM(rom []byte) {
c8 = chip8.New(rom)
// Lock goroutine to main thread
runtime.LockOSThread()
// Setup and ensure cleanup of SDL
setupSDL()
defer cleanUpSDL()
// Run main loop at 60Hz
c := time.Tick(time.Second / 60)
for _ = range c {
select {
case <-exitChan:
return
default:
}
c8.UpdateTimers()
processInput()
for i := 0; i < *cyclesPerLoop; i++ {
c8.Step()
}
// Sound
if c8.ShouldBuzz() {
sdl.PauseAudio(false)
} else {
sdl.PauseAudio(true)
}
// Draw if needed
if c8.DrawFlag {
c8.DrawFlag = false
draw()
}
}
}
func disassembleROM(rom []byte) {
for i := 0; i < len(rom); i += 2 {
op := chip8.GetOpcode(rom[i], rom[i+1])
inst := chip8.DecodeOpcode(op)
fmt.Printf("%#x ; %s\n", op, inst.Description)
}
}
// processInput polls and handles SDL events
func processInput() {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch e := event.(type) {
case *sdl.QuitEvent:
exitChan <- true
case *sdl.KeyDownEvent:
if e.Keysym.Sym == sdl.K_ESCAPE {
exitChan <- true
} else {
k, ok := keyBindings[e.Keysym.Sym]
if ok {
c8.PressKey(k)
}
}
case *sdl.KeyUpEvent:
k, ok := keyBindings[e.Keysym.Sym]
if ok {
c8.DePressKey(k)
}
}
}
}
//export AudioCallback
func AudioCallback(userdata unsafe.Pointer, stream *C.Uint8, length C.int) {
n := int(length)
hdr := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(stream)), Len: n, Cap: n}
buf := *(*[]C.Uint8)(unsafe.Pointer(&hdr))
var phase float64
for i := 0; i < n; i += 2 {
phase += dPhase
sample := C.Uint8((math.Sin(phase) + 0.999999) * 128)
buf[i] = sample
buf[i+1] = sample
}
}
func draw() {
display := c8.Display()
renderer.SetDrawColor(0, 0, 0, 1)
renderer.Clear()
renderer.SetDrawColor(255, 255, 255, 1)
for y := 0; y < chip8.DisplayHeight; y++ {
for x := 0; x < chip8.DisplayWidth; x++ {
// Only draw if set to 1
if display[x][y] == 1 {
pixel.X = int32(*scaleFactor * x)
pixel.Y = int32(*scaleFactor * y)
renderer.FillRect(pixel)
}
}
}
renderer.Present()
}