-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathui.go
More file actions
405 lines (334 loc) · 11.5 KB
/
ui.go
File metadata and controls
405 lines (334 loc) · 11.5 KB
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
package ui
import (
"fmt"
"os"
"os/signal"
"runtime/pprof"
"github.com/lazy-stripes/goholint/assets"
"github.com/lazy-stripes/goholint/gameboy"
"github.com/lazy-stripes/goholint/logger"
"github.com/lazy-stripes/goholint/options"
"github.com/lazy-stripes/goholint/ui/widgets"
"github.com/lazy-stripes/goholint/ui/widgets/align"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
"github.com/veandco/go-sdl2/ttf"
)
const (
// Margin is the space in pixels between screen border and UI text.
Margin = 2
)
// Package-wide logger.
var log = logger.New("ui", "UI-related messages")
type dialog struct {
widgets.Widget
title string
}
// UI structure to manage user commands and overlay.
// TODO: move Gameboy inside UI, implement UI.Tick(), see if it works.
type UI struct {
Emulator *gameboy.GameBoy
KeyboardControls map[options.KeyStroke]Action
GameControllerControls map[sdl.GameControllerButton]Action
SigINTChan chan os.Signal
// Send true to this channel to quit the program.
QuitChan chan bool
paused bool
// Current palette.
paletteIndex int
screen *widgets.Screen
dialogs *widgets.Stack
root *widgets.Group
zoomFactor int // From -zoom to compute offsets in various textures
renderer *sdl.Renderer
screenRect *sdl.Rect // Screen dimensions (accounting for zoom factor)
font *ttf.Font
fgColor sdl.Color // Text color
bgColor sdl.Color // Text outline color
recording bool // True if currently recording to GIF.
ticks uint
}
// Return a UI instance given a renderer to create the overlay texture.
func New() *UI {
window, err := sdl.CreateWindow("Goholint",
sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
options.ScreenWidth*int32(options.Run.ZoomFactor),
options.ScreenHeight*int32(options.Run.ZoomFactor),
sdl.WINDOW_SHOWN)
if err != nil {
panic(err)
}
icon, err := img.LoadRW(assets.WindowIconRW(), false)
if err != nil {
panic(err)
}
window.SetIcon(icon)
renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
if err != nil {
panic(err)
}
if options.Run.VSync {
if err = sdl.GLSetSwapInterval(-1); err != nil {
log.Infof("Can't set adaptive vsync: %s", sdl.GetError())
// Try 'just' syncing to vblank then.
if err = sdl.GLSetSwapInterval(1); err != nil {
log.Warningf("Can't sync to vblank: %s", sdl.GetError())
}
}
}
if info, err := renderer.GetInfo(); err == nil {
log.Info("SDL_RENDERER info:")
w, h, _ := renderer.GetOutputSize()
log.Infof("RESOLUTION: %d×%d", w, h)
log.Infof("SOFTWARE: %t", info.Flags&sdl.RENDERER_SOFTWARE != 0)
log.Infof("ACCELERATED: %t", info.Flags&sdl.RENDERER_ACCELERATED != 0)
log.Infof("PRESENTVSYNC: %t", info.Flags&sdl.RENDERER_PRESENTVSYNC != 0)
}
// TODO: ui.Font(size) -> *ttf.Font (cached by size).
font, err := ttf.OpenFontRW(assets.UIFontRW(), 1, int(8*options.Run.ZoomFactor))
if err != nil {
panic(err)
}
titleFont, err := ttf.OpenFontRW(assets.UIFontRW(), 1, int(12*options.Run.ZoomFactor))
if err != nil {
panic(err)
}
// Keep computed screen size for drawing.
screenRect := &sdl.Rect{
X: 0,
Y: 0,
W: options.ScreenWidth * int32(options.Run.ZoomFactor),
H: options.ScreenHeight * int32(options.Run.ZoomFactor),
}
// TODO: try and move all of this to the widgets package to clean up the ui one.
// Colors from options.Run.
fg := sdl.Color(options.Run.UIForeground)
bg := sdl.Color(options.Run.UIBackground)
// By default, use BG color at zero transparency for clearing widgets. It
// makes the outline of labels blend better.
background := bg
background.A = 0
// Store default widget properties in the widget package namespace. This
// will be copied to every new widget.
// FIXME: should that be set directly from options package?
widgets.DefaultProperties = widgets.Properties{
Font: font,
TitleFont: titleFont,
BgColor: bg,
FgColor: fg,
HorizontalAlign: align.Center,
VerticalAlign: align.Middle,
Border: 1,
//BorderColor: sdl.Color{0xff, 0x00, 0x00, 0xff},
//Background: sdl.Color{0xff, 0xff, 0xff, 0x00},
Background: background,
Zoom: int(options.Run.ZoomFactor),
}
// XXX: maybe pass props as parameters too?
widgets.Init(renderer)
// Screen widget the emulator will write into via the PixelWriter interface.
gbScreen := widgets.NewScreen(screenRect)
emulator := gameboy.New(gbScreen)
gbScreen.PPU = emulator.PPU // Only used for debugging.
ui := &UI{
QuitChan: make(chan bool),
SigINTChan: make(chan os.Signal, 1),
Emulator: emulator,
renderer: renderer,
screenRect: screenRect,
font: font,
zoomFactor: int(options.Run.ZoomFactor),
fgColor: fg,
bgColor: bg,
dialogs: widgets.NewStack(screenRect, nil),
root: widgets.NewGroup(screenRect, nil), // WIP, still not sure how I'll organize this. I still like bg/fg.
screen: gbScreen,
}
// The UI should primarily show the emulator's screen, with some menu or
// special widget on top whenever emulation is paused.
// TODO: Make gb display its own dialog?
ui.root.Add(gbScreen)
ui.root.Add(ui.dialogs)
ui.dialogs.SetVisible(false)
// Create menu stack with extra widgets. Those will only be shown when the
// emulator is paused.
ui.buildMenu()
ui.SetControls(options.Run.Keymap, options.Run.Joymap)
go ui.handleSIGINT()
return ui
}
// handleSIGINT prints and dumps debug data on CTRL+C. This should be run as a
// goroutine at startup after creating UI.
func (u *UI) handleSIGINT() {
// Wait for signal, quit cleanly with potential extra debug info if needed.
signal.Notify(u.SigINTChan, os.Interrupt)
<-u.SigINTChan
fmt.Println("\nTerminated...")
// TODO: quit-time cleanup in gb, ui, etc.
//gb.Display.Close()
// TODO: only dump RAM/VRAM/Other if requested in parameters.
fmt.Print(u.Emulator.CPU)
fmt.Print(u.Emulator.PPU)
u.Emulator.CPU.DumpMemory()
// Force stopping CPU profiling.
pprof.StopCPUProfile()
// FIXME: quit cleanly
os.Exit(-1)
}
// TODO: FillAudioBuffer
func (u *UI) Tick() (res gameboy.TickResult) {
u.ticks++
if u.ticks%1000 == 0 {
sdl.Do(u.ProcessEvents)
}
// FIXME: pause on vblank. Should be using gb.Tick() return here anyway.
if !u.paused {
defer u.Emulator.Recover()
return u.Emulator.Tick()
}
return gameboy.TickResult{Play: true} // Always return silence. TODO: play samples of our UI SFXes...es here!
}
func (u *UI) buildMenu() {
mainMenu := widgets.NewMenu(u.screenRect)
// Main menu should always be the Stack's bottom widget. It's shown first.
u.dialogs.Add(mainMenu)
mainMenu.AddChoice("Resume", u.Hide)
mainMenu.AddChoice("Open", u.OpenROM)
// TODO: other features.
mainMenu.AddChoice("Quit", func() { u.QuitChan <- true }) // FIXME u.Quit action
mainMenu.Select(0) // highlight first entry
}
func (u *UI) Show() {
u.paused = true
u.screen.Pause()
u.dialogs.SetVisible(true)
u.Repaint()
}
func (u *UI) Hide() {
u.paused = false
u.screen.Unpause()
u.dialogs.SetVisible(false)
u.Repaint()
}
// SetControls validates and sets the given control map for the emulator's UI.
func (u *UI) SetControls(keymap options.Keymap, joymap options.Joymap) (err error) {
// Intermediate mapping between labels and actual actions.
// TODO: re-add all the stuff previously done on the gb side (screenshots, gif, etc)
actions := map[string]Action{
// High-level actions.
"home": u.Home,
"quit": u.Quit,
// TODO: Maybe I could have subcontrols for widgets?
// Might need a bespoke root widget type.
"nextpalette": u.EmulatorAction(u.NextPalette),
"previouspalette": u.EmulatorAction(u.PreviousPalette),
"recordgif": u.EmulatorAction(u.StartStopRecord),
"screenshot": u.EmulatorAction(u.Screenshot),
"togglevoice1": u.EmulatorAction(u.ToggleVoice1),
"togglevoice2": u.EmulatorAction(u.ToggleVoice2),
"togglevoice3": u.EmulatorAction(u.ToggleVoice3),
"togglevoice4": u.EmulatorAction(u.ToggleVoice4),
// Button presses that could either be handled by GB or UI.
"up": u.ButtonAction(widgets.ButtonUp, u.Emulator.JoypadUp),
"down": u.ButtonAction(widgets.ButtonDown, u.Emulator.JoypadDown),
"left": u.ButtonAction(widgets.ButtonLeft, u.Emulator.JoypadLeft),
"right": u.ButtonAction(widgets.ButtonRight, u.Emulator.JoypadRight),
"a": u.ButtonAction(widgets.ButtonA, u.Emulator.JoypadA),
"b": u.ButtonAction(widgets.ButtonB, u.Emulator.JoypadB),
"select": u.ButtonAction(widgets.ButtonSelect, u.Emulator.JoypadSelect),
"start": u.ButtonAction(widgets.ButtonStart, u.Emulator.JoypadStart),
}
u.KeyboardControls = make(map[options.KeyStroke]Action)
for label, keyStroke := range keymap {
u.KeyboardControls[keyStroke] = actions[label]
}
u.GameControllerControls = make(map[sdl.GameControllerButton]Action)
for label, button := range joymap {
u.GameControllerControls[button] = actions[label]
}
return nil
}
// EmulatorAction returns a control action function that will handle some
// high-level events but only if the emulator is currently running (so that we
// don't change palettes or stuff while the emulator is paused).
func (u *UI) EmulatorAction(action Action) Action {
return func(state uint8) {
// Don't handle event if emulator is paused.
if !u.paused {
action(state)
}
}
}
// ButtonAction returns a control action function that will propagate event
// keys for button presses to the proper object (emulator if it's running, UI if
// it's paused).
func (u *UI) ButtonAction(e widgets.Event, gbAction gameboy.Action) Action {
// Convert keystroke into simpler one-shot widget event. We only care about
// given event type to tell if a key was pressed.
return func(state uint8) {
if !u.paused {
gbAction(state == sdl.PRESSED)
} else if u.root != nil && state == sdl.PRESSED {
u.root.ProcessEvent(e)
u.Repaint()
}
}
}
func (u *UI) ProcessEvents() {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
eventType := event.GetType()
switch eventType {
// Button presses and UI keys
case sdl.KEYDOWN, sdl.KEYUP:
keyEvent := event.(*sdl.KeyboardEvent)
keyStroke := options.KeyStroke{
Code: keyEvent.Keysym.Sym,
Mod: sdl.Keymod(keyEvent.Keysym.Mod & options.ModMask),
}
if action := u.KeyboardControls[keyStroke]; action != nil {
action(keyEvent.State)
} else {
if eventType == sdl.KEYDOWN {
log.Infof("unknown key code: 0x%x", keyStroke.Code)
log.Infof(" modifier: 0x%x", sdl.GetModState())
}
}
case sdl.CONTROLLERBUTTONDOWN, sdl.CONTROLLERBUTTONUP:
ctrlEvent := event.(*sdl.ControllerButtonEvent)
btn := sdl.GameControllerButton(ctrlEvent.Button)
if action := u.GameControllerControls[btn]; action != nil {
action(ctrlEvent.State)
} else {
log.Infof("unknown controller button: 0x%x (%s)", btn,
sdl.GameControllerGetStringForButton(btn))
}
// Internal events generated by widgets.
case sdl.RENDER_TARGETS_RESET:
u.Repaint()
// Window redraw events
case sdl.WINDOWEVENT:
u.Repaint()
// Window-closing event
case sdl.QUIT:
u.QuitChan <- true
}
}
}
func (u *UI) Repaint() {
// At this point, we can pretty much just render the root widget.
texture := u.root.Texture()
u.renderer.SetRenderTarget(nil)
u.renderer.Copy(texture, nil, nil)
// Debug stuff
var gridSize int32 = 8
if log.Enabled() && logger.Level >= logger.Debug {
u.renderer.SetDrawColor(0xff, 0x00, 0x00, 0xff)
for x := int32(0); x < u.screenRect.W; x += gridSize * int32(options.Run.ZoomFactor) {
u.renderer.DrawLine(x, 0, x, u.screenRect.H)
}
for y := int32(0); y < u.screenRect.H; y += gridSize * int32(options.Run.ZoomFactor) {
u.renderer.DrawLine(0, y, u.screenRect.W, y)
}
}
u.renderer.Present()
}