-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
320 lines (277 loc) · 7.67 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
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
package main
import (
"flag"
"fmt"
"os"
"runtime/debug"
"sync"
"time"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/zeozeozeo/gopsx/emulator"
)
var (
width, height = 1024, 512
gpu *emulator.GPU
currentFrame = ebiten.NewImage(1024, 512)
wg sync.WaitGroup
prevFrameTime = time.Now()
showFps *bool
showCycles *bool
cpu *emulator.CPU
didPanic bool
panicString string
doRecover *bool
frameDt float64
disc *emulator.Disc
)
// Gamepad button can be binded to multiple keys
var keyboardGamepadBindings = map[emulator.Button][]ebiten.Key{
emulator.BUTTON_START: {ebiten.KeyBackspace},
emulator.BUTTON_SELECT: {ebiten.KeyShiftRight},
emulator.BUTTON_DUP: {ebiten.KeyUp},
emulator.BUTTON_DRIGHT: {ebiten.KeyRight},
emulator.BUTTON_DDOWN: {ebiten.KeyDown},
emulator.BUTTON_DLEFT: {ebiten.KeyLeft},
emulator.BUTTON_L2: {ebiten.KeyKPDivide},
emulator.BUTTON_R2: {ebiten.KeyKPMultiply},
emulator.BUTTON_L1: {ebiten.KeyKP7},
emulator.BUTTON_R1: {ebiten.KeyKP9},
emulator.BUTTON_TRIANGLE: {ebiten.KeyKP8},
emulator.BUTTON_CIRCLE: {ebiten.KeyKP6},
emulator.BUTTON_CROSS: {ebiten.KeyKP2},
emulator.BUTTON_SQUARE: {ebiten.KeyKP4},
}
type ebitenGame struct {
renderer *emulator.EbitenRenderer
gamepadIDs map[ebiten.GamepadID]struct{}
axes map[ebiten.GamepadID][]float64
}
func (g *ebitenGame) Update() error {
if cpu == nil {
return nil
}
pad := cpu.Inter.PadMemCard.Pad1
g.handleConnectedGamepads()
g.handleGamepadInput(pad)
handleKeyboard(pad)
return nil
}
func handleKeyboard(pad *emulator.Gamepad) {
for _, button := range emulator.GamepadButtons {
keys := keyboardGamepadBindings[button]
for _, key := range keys {
if ebiten.IsKeyPressed(key) {
pad.SetButtonState(button, emulator.BUTTON_STATE_PRESSED)
} else if inpututil.IsKeyJustReleased(key) {
pad.SetButtonState(button, emulator.BUTTON_STATE_RELEASED)
}
break
}
}
if ebiten.IsKeyPressed(ebiten.KeyEscape) {
os.Exit(0)
}
}
func (g *ebitenGame) handleConnectedGamepads() {
if g.gamepadIDs == nil {
g.gamepadIDs = map[ebiten.GamepadID]struct{}{}
}
gamepadsConnected := inpututil.AppendJustConnectedGamepadIDs(nil)
for _, id := range gamepadsConnected {
fmt.Printf("main: gamepad connected: id: %d, SDL ID: %s\n", id, ebiten.GamepadSDLID(id))
g.gamepadIDs[id] = struct{}{}
}
for id := range g.gamepadIDs {
if inpututil.IsGamepadJustDisconnected(id) {
fmt.Printf("main: gamepad disconnected: id: %d\n", id)
delete(g.gamepadIDs, id)
}
}
}
func (g *ebitenGame) handleGamepadInput(pad *emulator.Gamepad) {
g.axes = map[ebiten.GamepadID][]float64{}
for id := range g.gamepadIDs {
maxAxis := ebiten.GamepadAxisCount(id)
for a := 0; a < maxAxis; a++ {
v := ebiten.GamepadAxisValue(id, a)
g.axes[id] = append(g.axes[id], v)
}
maxButton := ebiten.GamepadButton(ebiten.GamepadButtonCount(id))
for b := ebiten.GamepadButton(id); b < maxButton; b++ {
// log button events
if inpututil.IsGamepadButtonJustPressed(id, b) {
fmt.Printf("main: button pressed: id: %d, button: %d\n", id, b)
pad.SetButtonState(buttonFromId(int(b)), emulator.BUTTON_STATE_PRESSED)
}
if inpututil.IsGamepadButtonJustReleased(id, b) {
fmt.Printf("main: button released: id: %d, button: %d\n", id, b)
pad.SetButtonState(buttonFromId(int(b)), emulator.BUTTON_STATE_RELEASED)
}
}
}
}
func buttonFromId(id int) emulator.Button {
switch id {
case 0: // A -> Cross
return emulator.BUTTON_CROSS
case 1: // B -> Circle
return emulator.BUTTON_CIRCLE
case 3: // X -> Square
return emulator.BUTTON_SQUARE
case 4: // Y -> Triangle
return emulator.BUTTON_TRIANGLE
case 15: // DPadUp
return emulator.BUTTON_DUP
case 17: // DPadDown
return emulator.BUTTON_DDOWN
case 18: // DPadLeft
return emulator.BUTTON_DLEFT
case 16: // DPadRight
return emulator.BUTTON_DRIGHT
case 11: // Start
return emulator.BUTTON_START
case 12: // Back -> Select
return emulator.BUTTON_SELECT
case 6: // LeftShoulder
return emulator.BUTTON_L1
case 7: // RightShoulder
return emulator.BUTTON_R1
case 8:
return emulator.BUTTON_R2
case 9:
return emulator.BUTTON_L2
}
return 0
}
func (g *ebitenGame) Draw(screen *ebiten.Image) {
op := &ebiten.DrawImageOptions{}
op.Filter = ebiten.FilterLinear
// scale rendered frame to fit window
fx := currentFrame.Bounds().Dx()
fy := currentFrame.Bounds().Dy()
scaleX := float64(width) / float64(fx)
scaleY := float64(height) / float64(fy)
op.GeoM.Scale(scaleX, scaleY)
wg.Wait()
screen.DrawImage(currentFrame, op)
if *showFps {
ebitenutil.DebugPrintAt(screen, fmt.Sprintf("%f fps", 1/frameDt), 8, 8)
}
if *showCycles {
ebitenutil.DebugPrintAt(
screen,
fmt.Sprintf("%d cycles\npc: 0x%x", cpu.Th.Cycles, cpu.PC),
8, 24,
)
}
// draw error message if there was a panic
if didPanic {
ebitenutil.DebugPrintAt(screen, panicString, 8, 48+24)
}
}
func (g *ebitenGame) Layout(insideWidth, insideHeight int) (int, int) {
return width, height
}
func (g *ebitenGame) drawFrame() {
wg.Add(1)
defer wg.Done()
// calculate delta time
frameDt = time.Since(prevFrameTime).Seconds()
// create renderer if it's nil
if g.renderer == nil {
g.renderer = gpu.NewEbitenRenderer()
}
// clear previous frame and draw the new one
// FIXME: for some reason, the image is flickering after the GPU timings were implemented
currentFrame.Clear()
g.renderer.Draw(currentFrame)
prevFrameTime = time.Now()
}
func startEbitenWindow(g *ebitenGame) {
ebiten.SetWindowSize(width, height)
ebiten.SetWindowTitle("gopsx")
ebiten.SetTPS(ebiten.SyncWithFPS)
if err := ebiten.RunGame(g); err != nil {
panic(err)
}
}
func main() {
// parse arguments
biosPath := flag.String("bios", "SCPH1001.BIN", "path to the BIOS file")
showFps = flag.Bool("fps", true, "show FPS value")
showCycles = flag.Bool("cycles", true, "show amount of CPU cycles")
doRecover = flag.Bool("recover", true, "recover from emulator panics")
discPath := flag.String("disc", "", "disc .BIN path")
nogui := flag.Bool(
"nogui", false,
"whether to run without the GUI (useful for debugging)",
)
flag.Parse()
if *discPath != "" {
// try to load disc
file, err := os.Open(*discPath)
if err != nil {
panic(err)
}
defer file.Close()
disc, err = emulator.NewDisc(file)
if err != nil {
panic(err)
}
fmt.Printf("main: disc region: %s\n", disc.RegionString())
}
g := &ebitenGame{}
if !*nogui {
go startEmulator(g, *biosPath, *nogui)
startEbitenWindow(g)
} else {
// run on main thread
startEmulator(g, *biosPath, *nogui)
}
}
func startEmulator(g *ebitenGame, biosPath string, nogui bool) {
// start emulator
bios := loadBios(biosPath)
ram := emulator.NewRAM()
hardware := emulator.HARDWARE_NTSC
if disc != nil {
hardware = emulator.GetHardwareFromRegion(disc.Region)
}
gpu = emulator.NewGPU(hardware)
if !nogui {
gpu.SetFrameEnd(g.drawFrame)
}
inter := emulator.NewInterconnect(bios, ram, gpu, disc)
cpu = emulator.NewCPU(inter)
defer func() {
if *doRecover {
if r := recover(); r != nil {
fmt.Printf("\nrecovered from panic: %s\n\n%s\n", r, debug.Stack())
didPanic = true
panicString = fmt.Sprintf("recovered from panic:\n%s", r)
}
}
}()
for {
cpu.RunNextInstruction()
}
}
func loadBios(path string) *emulator.BIOS {
fmt.Printf("main: loading bios \"%s\"\n", path)
start := time.Now()
// read bios
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
// load bios
bios, err := emulator.LoadBIOS(file)
if err != nil {
panic(err)
}
fmt.Printf("main: loaded bios in %s\n", time.Since(start))
return bios
}