-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwindow.go
More file actions
796 lines (658 loc) · 23.3 KB
/
window.go
File metadata and controls
796 lines (658 loc) · 23.3 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
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
package glitch
import (
"fmt"
"image"
"time"
"github.com/unitoftime/flow/glm"
"github.com/unitoftime/glitch/internal/gl"
"github.com/unitoftime/glitch/internal/glfw"
"github.com/unitoftime/glitch/internal/mainthread"
)
type WindowConfig struct {
Fullscreen bool // Indicates the window should be in fullscreen
Undecorated bool // Indicates the window should be undecorated
FillMonitor bool // Indicates the window should fill the primary monitor. This will override provided width and height
Maximized bool // Indicates the window should be maximized
Vsync bool // Indicates the window should use vsync
// Resizable bool
Samples int
Icons []image.Image
}
type Window struct {
window *glfw.Window
config WindowConfig
closed bool
width, height int
tmpInput, input struct {
justPressed [KeyLast + 1]bool
justReleased [KeyLast + 1]bool
repeated [KeyLast + 1]bool
scroll struct {
X, Y float64
}
}
// TODO: Could use an array? I think gamepad indexes have restrictions in glfw and browser
cachedGamepadStates map[Gamepad]*glfw.GamepadState
mousePosition Vec2
currentPrimaryGamepad Gamepad // Tracks the current primarily used gamepad
justPressedGamepad [ButtonLast + 1]bool // Tracks buttons that were just pressed this frame
mainthreadUpdateConnectedGamepads func()
connectedGamepads []Gamepad
// TODO: Technically you could just store the last primaryGamepadState
pressedGamepad [ButtonLast + 1]bool // Tracks buttons that are currently pressed this frame
gamepadAxis [AxisLast + 1]float64 // Tracks the current axis state
// The back and front buffers for tracking typed characters
typedBack, typedFront []rune
mainthreadUpdate func()
mainthreadPressed func()
pressedKeyCheck Key
pressedKeyReturn bool
scrollCallbacks []glfw.ScrollCallback
keyCallbacks []glfw.KeyCallback
mouseButtonCallbacks []glfw.MouseButtonCallback
charCallbacks []glfw.CharCallback
repeatTracker []repeatData
mouseRepeatDelay time.Duration // amount of time delay to wait after a mouse hold to consider it repeated
mouseRepeatPeriod time.Duration // amount of time in between consecutive repeats after a repeat has started
lastUpdateTime time.Time
lastWinPos glm.IVec2
lastWinSize glm.IVec2
}
type repeatData struct {
key Key
dur time.Duration
}
func NewWindow(width, height int, title string, inputConfig WindowConfig) (*Window, error) {
win := &Window{
config: inputConfig,
scrollCallbacks: make([]glfw.ScrollCallback, 0),
keyCallbacks: make([]glfw.KeyCallback, 0),
mouseButtonCallbacks: make([]glfw.MouseButtonCallback, 0),
cachedGamepadStates: make(map[Gamepad]*glfw.GamepadState),
repeatTracker: []repeatData{
{key: MouseButtonLeft},
{key: MouseButtonRight},
{key: MouseButtonMiddle},
// TODO: Make this configurable
// TODO: Add all mousebuttons
// TODO: Add all gamepad buttons
},
mouseRepeatDelay: 350 * time.Millisecond, // Note: The total delay for first repeat is delay + period
mouseRepeatPeriod: 150 * time.Millisecond,
lastUpdateTime: time.Now(),
lastWinPos: glm.IVec2{},
lastWinSize: glm.IVec2{width, height},
}
err := mainthread.CallErr(func() error {
err := glfw.Init(gl.ContextWatcher)
if err != nil {
return err
}
glfw.WindowHint(glfw.ContextVersionMajor, 3)
glfw.WindowHint(glfw.ContextVersionMinor, 3)
// glfw.WindowHint(glfw.Resizable, config.Resizable)
if win.config.Samples > 0 {
glfw.WindowHint(glfw.Samples, win.config.Samples)
}
glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) // Compatibility - For Mac only?
// Disables the ability to minimze a fullscreen window
// glfw.WindowHint(glfw.AutoIconify, glfw.False)
var fullscreenMonitor *glfw.Monitor
if win.config.Fullscreen {
fullscreenMonitor = glfw.GetPrimaryMonitor()
// Note: These settings are for a fullscreen mode with faster alt tabs (alt tabs dont require mode switch).
// glfw.WindowHint(glfw.RedBits, mode.RedBits)
// glfw.WindowHint(glfw.GreenBits, mode.GreenBits)
// glfw.WindowHint(glfw.BlueBits, mode.BlueBits)
// glfw.WindowHint(glfw.RefreshRate, mode.RefreshRate)
// Set a restore point since we are starting fullscreened
{
r := glm.R(0, 0, float64(width), float64(height)).CenterScaled(0.8)
win.lastWinPos = glm.IVec2{int(r.Min.X), int(r.Min.Y)}
win.lastWinSize = glm.IVec2{int(r.W()), int(r.H())}
}
} else if win.config.FillMonitor {
monitor := glfw.GetPrimaryMonitor()
mode := monitor.GetVideoMode()
width = mode.Width
height = mode.Height
// Maximized must be set false because we are going to Fill the monitor manually
win.config.Maximized = false
// Set a restore point since we are starting borderless windowed
{
r := glm.R(0, 0, float64(width), float64(height)).CenterScaled(0.8)
win.lastWinPos = glm.IVec2{int(r.Min.X), int(r.Min.Y)}
win.lastWinSize = glm.IVec2{int(r.W()), int(r.H())}
}
}
if win.config.Undecorated {
glfw.WindowHint(glfw.Decorated, glfw.False)
}
if win.config.Maximized {
glfw.WindowHint(glfw.Maximized, glfw.True)
}
win.window, err = glfw.CreateWindow(width, height, title, fullscreenMonitor, nil)
if err != nil {
return err
}
win.window.MakeContextCurrent()
// log.Printf("OpenGL: %s %s %s; %v samples.\n", gl.GetString(gl.VENDOR), gl.GetString(gl.RENDERER), gl.GetString(gl.VERSION), gl.GetInteger(gl.SAMPLES))
// log.Printf("GLSL: %s.\n", gl.GetString(gl.SHADING_LANGUAGE_VERSION))
if len(win.config.Icons) > 0 {
win.window.SetIcon(win.config.Icons)
}
if win.config.Samples > 0 {
// TODO - But how to work with wasm (which enables multisample in the context?)
gl.Enable(gl.MULTISAMPLE)
}
// gl.Enable(gl.DEPTH_TEST)
// gl.Enable(gl.CULL_FACE)
// gl.CullFace(gl.BACK)
// gl.FrontFace(gl.CCW) // Default
// gl.Enable(gl.BLEND) // TODO: Will this ever need to be disabled?
// // gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); // Non premult
// gl.BlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) // Premult
if win.config.Vsync {
glfw.SwapInterval(1)
} else {
glfw.SwapInterval(0)
}
win.width = width
win.height = height
gl.Viewport(0, 0, int(width), int(height))
win.window.SetFramebufferSizeCallback(func(w *glfw.Window, width, height int) {
// fmt.Println("Framebuffer size callback", width, height)
win.width = width
win.height = height
gl.Viewport(0, 0, int(win.width), int(win.height))
})
win.AddScrollCallback(func(w *glfw.Window, xoff float64, yoff float64) {
// win.window.SetScrollCallback(func(w *glfw.Window, xoff float64, yoff float64) {
win.tmpInput.scroll.X += xoff
win.tmpInput.scroll.Y += yoff
})
win.AddMouseButtonCallback(func(w *glfw.Window, button glfw.MouseButton, action glfw.Action, mods glfw.ModifierKey) {
// win.window.SetMouseButtonCallback(func(w *glfw.Window, button glfw.MouseButton, action glfw.Action, mods glfw.ModifierKey) {
switch action {
case glfw.Press:
win.tmpInput.justPressed[Key(button)] = true
case glfw.Release:
win.tmpInput.justReleased[Key(button)] = true
// Warning: Repeat events aren't returned for mouse callbacks. so we track them with repeatTracker
// case glfw.Repeat:
// win.tmpInput.justReleased[Key(button)] = true
}
})
win.AddKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
// win.window.SetKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
if key == glfw.KeyUnknown {
return
}
switch action {
case glfw.Press:
win.tmpInput.justPressed[Key(key)] = true
case glfw.Release:
win.tmpInput.justReleased[Key(key)] = true
case glfw.Repeat:
win.tmpInput.repeated[Key(key)] = true
}
})
win.AddCharCallback(func(w *glfw.Window, char rune) {
// win.window.SetCharCallback(func(w *glfw.Window, char rune) {
win.typedBack = append(win.typedBack, char)
})
win.window.SetScrollCallback(func(w *glfw.Window, xoff float64, yoff float64) {
for _, c := range win.scrollCallbacks {
c(w, xoff, yoff)
}
})
win.window.SetMouseButtonCallback(func(w *glfw.Window, button glfw.MouseButton, action glfw.Action, mods glfw.ModifierKey) {
for _, c := range win.mouseButtonCallbacks {
c(w, button, action, mods)
}
})
win.window.SetKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
for _, c := range win.keyCallbacks {
c(w, key, scancode, action, mods)
}
})
win.window.SetCharCallback(func(w *glfw.Window, char rune) {
for _, c := range win.charCallbacks {
c(w, char)
}
})
// win.window.SetIconifyCallback(func(w *glfw.Window, iconified bool) {
// if iconified {
// // Window was iconified (ie minimized)
// } else {
// // Window was restored
// gl.Viewport(0, 0, win.width, win.height)
// }
// })
// TODO - other callbacks?
// TODO - A hack for wasm - where the framebuffer doesn't trigger until the view gets resized once, we just set the size based on what the browser window says
{
w, h := win.window.GetFramebufferSize()
win.width = w
win.height = h
gl.Viewport(0, 0, w, h)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to create window: %w", err)
}
win.mainthreadUpdate = func() {
// TODO - I think this is only useful for webgl because of how my RAF works I think in Firefox it sometimes swaps buffer before finishing the opengl stuff. Weird!
// TODO - using gl.Finish is bad? https://www.khronos.org/opengl/wiki/Swap_Interval
// gl.Flush()
// gl.Finish()
win.window.SwapBuffers()
glfw.PollEvents()
win.mainthreadCacheMousePosition()
}
win.mainthreadPressed = func() {
win.pressed()
}
// Gets and caches the connected gamepads
win.mainthreadUpdateConnectedGamepads = func() {
joysticks := win.window.GetConnectedGamepads()
win.connectedGamepads = win.connectedGamepads[:0]
for i := range joysticks {
win.connectedGamepads = append(win.connectedGamepads, Gamepad(joysticks[i]))
}
}
win.Update()
// win.DumpInfo()
return win, nil
}
func (w *Window) DumpInfo() {
mainthread.Call(func() {
fmt.Println("GL Version:", gl.GetString(gl.VERSION))
fmt.Println("GLSL Version:", gl.GetString(gl.SHADING_LANGUAGE_VERSION))
})
}
// func checkOpenGLError() {
// errorEnum := gl.GetError()
// if errorEnum != 0 {
// fmt.Println("GL ERROR: ", errorEnum)
// panic("GL ERROR")
// }
// }
func (w *Window) Update() {
// Track frame times
nextLastUpdate := time.Now()
dt := nextLastUpdate.Sub(w.lastUpdateTime)
w.lastUpdateTime = nextLastUpdate
global.finish()
mainthread.Call(w.mainthreadUpdate)
w.input = w.tmpInput
w.tmpInput.scroll.X = 0
w.tmpInput.scroll.Y = 0
w.tmpInput.justPressed = [KeyLast + 1]bool{}
w.tmpInput.justReleased = [KeyLast + 1]bool{}
w.tmpInput.repeated = [KeyLast + 1]bool{}
for i := range w.repeatTracker {
key := w.repeatTracker[i].key
if w.Pressed(key) {
w.repeatTracker[i].dur += dt
if w.repeatTracker[i].dur > w.mouseRepeatDelay {
if w.repeatTracker[i].dur > w.mouseRepeatPeriod {
w.repeatTracker[i].dur -= w.mouseRepeatPeriod
w.tmpInput.repeated[key] = true
}
}
} else {
w.repeatTracker[i].dur = 0
}
}
// --- Swap the typed buffers ---
{
backBuf := w.typedBack
w.typedBack = w.typedFront[:0]
w.typedFront = backBuf
}
// Note: Disabled this logic because the wasm performance is really bad
// // --- Gamepad ---
// // Recalculate all active gamepads
// mainthread.Call(w.mainthreadUpdateConnectedGamepads)
// // 1. I need to decide the current active gamepad
// primaryGamepadState := w.getGamepadState(w.currentPrimaryGamepad)
// primaryStillActive := checkGamepadActive(primaryGamepadState)
// if !primaryStillActive {
// newActiveGamepad := w.findNewActiveGamepad()
// if newActiveGamepad != GamepadNone {
// w.currentPrimaryGamepad = newActiveGamepad
// primaryGamepadState = w.getGamepadState(w.currentPrimaryGamepad)
// }
// }
// // 2. I need to track their input for JustPressed
// // Note: Here we calculate the *newly* pressed buttons.
// // - buttons that arent pressed in the last frame, but are pressed in this new gamepad state
// if primaryGamepadState == nil {
// // If the primary gamepad is nil, then set everything to false, it maybe got disconnected
// w.pressedGamepad = [ButtonLast + 1]bool{}
// w.justPressedGamepad = [ButtonLast + 1]bool{}
// w.gamepadAxis = [AxisLast + 1]float64{}
// } else {
// for i := range primaryGamepadState.Buttons {
// if w.pressedGamepad[i] {
// // If currently pressed, then you couldn't possibly have just pressed it
// w.justPressedGamepad[i] = false
// } else {
// // Else, If the new gamepad state has this button pressed, it means this is the first frame it was pressed
// w.justPressedGamepad[i] = (primaryGamepadState.Buttons[i] == glfw.Press)
// }
// // Finally, set the current button state
// w.pressedGamepad[i] = (primaryGamepadState.Buttons[i] == glfw.Press)
// }
// // And set the current axis state
// for i := range primaryGamepadState.Axes {
// w.gamepadAxis[i] = float64(primaryGamepadState.Axes[i])
// }
// }
}
func (w *Window) Closed() bool {
shouldClose := false
mainthread.Call(func() {
shouldClose = w.window.ShouldClose()
})
if shouldClose {
w.closed = true
}
return w.closed
}
func (w *Window) SetClose(close bool) {
w.closed = close
mainthread.Call(func() {
w.window.SetShouldClose(close)
})
}
func (w *Window) Close() {
w.SetClose(true)
}
func (w *Window) Bounds() Rect {
return glm.R(0, 0, float64(w.width), float64(w.height))
}
func (w *Window) MousePosition() (float64, float64) {
// w.mainthreadCacheMousePosition() // This would decrease cursor lag a *little* bit
return w.mousePosition.X, w.mousePosition.Y
}
// You disabled this because its broken between browser and desktop
// func (w *Window) ContentScale() (float64, float64) {
// x, y := w.window.GetContentScale()
// return float64(x), float64(y)
// }
func (w *Window) mainthreadCacheMousePosition() {
var x, y float64
var sx, sy float32
x, y = w.window.GetCursorPos()
// TODO - Use callback to get contentScale. There is a function available in glfw library. In javascript though, I'm not sure if there's a way to detect content scale (other than maybe in the framebuffer size callback) But if a window is dragged to another monitor which has a different content scale, then the framebuffer size callback may not trigger, but the content scale will be updated.
sx, sy = w.window.GetContentScale()
// We scale the mouse position (which is in window pixel coords) into framebuffer pixel coords by multiplying it by the content scale.
xPos := x * float64(sx)
yPos := float64(w.height) - (y * float64(sy)) // This flips the coordinate to quadrant 1
// return xPos, yPos
w.mousePosition.X = xPos
w.mousePosition.Y = yPos
// fmt.Println("ContentScale:", sx, sy)
// fmt.Println("CursorPos:", x, y)
// fmt.Println("FinalMousePos:", w.mousePosition)
}
// // Returns true if the key was pressed in the last frame
func (w *Window) JustPressed(key Key) bool {
if key == KeyUnknown {
return false
}
return w.input.justPressed[key]
}
func (w *Window) JustReleased(key Key) bool {
if key == KeyUnknown {
return false
}
return w.input.justReleased[key]
}
func (w *Window) Repeated(key Key) bool {
if key == KeyUnknown {
return false
}
return w.input.repeated[key]
}
// Binds the window as the OpenGL render targe
func (w *Window) Bind() {
state.bindFramebuffer(gl.NoFramebuffer, w.Bounds())
}
// Reads a rectangle of the window's frame as a collection of bytes
// func (w *Window) ReadFrame(rect Rect, dst []byte) {
// mainthreadCall(func() {
// gl.BindFramebuffer(gl.FRAMEBUFFER, gl.NoFramebuffer)
// // TODO Note: https://docs.gl/es3/glReadPixels#:~:text=glReadPixels%20returns%20pixel%20data%20from,parameters%20are%20set%20with%20glPixelStorei.
// // Format and Type Enums define the expected pixel format and type to return to the byte buffer. Right now I have that hardcoded to gl.RGBA and gl.UNSIGNED_BYTE, respectively
// gl.ReadPixels(dst, int(rect.Min[0]), int(rect.Min[1]), int(rect.W()), int(rect.H()), gl.RGBA, gl.UNSIGNED_BYTE)
// })
// }
func (w *Window) Pressed(key Key) bool {
if key == KeyUnknown {
return false
}
// TODO: You could cache these every frame to avoid calling mainthread call (ie {unset, pressed, unpressed})
w.pressedKeyCheck = key
mainthread.Call(w.mainthreadPressed)
return w.pressedKeyReturn
}
func (w *Window) pressed() {
key := w.pressedKeyCheck
var action glfw.Action
if isMouseKey(key) {
action = w.window.GetMouseButton(glfw.MouseButton(key))
} else {
action = w.window.GetKey(glfw.Key(key))
}
w.pressedKeyReturn = false
if action == glfw.Press || action == glfw.Repeat {
w.pressedKeyReturn = true
}
}
// func (w *Window) Pressed(key Key) bool {
// var action glfw.Action
// mainthreadCall(func() {
// if isMouseKey(key) {
// action = w.window.GetMouseButton(glfw.MouseButton(key))
// } else {
// action = w.window.GetKey(glfw.Key(key))
// }
// })
// if action == glfw.Press || action == glfw.Repeat {
// return true
// }
// return false
// }
// Don't cache the returned buffer because it gets overwritten
func (w *Window) Typed() []rune {
// TODO - should I copy just to be safe?
return w.typedFront
}
func (w *Window) MouseScroll() (float64, float64) {
return w.input.scroll.X, w.input.scroll.Y
}
type CursorMode uint8
const (
CursorNormal CursorMode = iota // A normal cursor
CursorHidden // A normal cursor, but not rendered
CursorDisabled // Hides and locks the cursor
)
func (w *Window) SetCursor(mode CursorMode) {
mainthread.Call(func() {
if mode == CursorNormal {
w.window.SetInputMode(glfw.CursorMode, glfw.CursorNormal)
} else if mode == CursorHidden {
w.window.SetInputMode(glfw.CursorMode, glfw.CursorHidden)
} else if mode == CursorDisabled {
w.window.SetInputMode(glfw.CursorMode, glfw.CursorDisabled)
}
})
}
// Used to check if we are in browser and we are hidden. If not in a web browser this will always return false. Should be used to selectively disable code that shouldn't be run when the browser is hidden
func (w *Window) BrowserHidden() bool {
return w.window.BrowserHidden()
}
// TODO - rename. Also potentially allow for multiple swaps?
func (w *Window) SetVSync(enable bool) {
mainthread.Call(func() {
w.config.Vsync = enable
w.setSwap()
})
}
// Returns true if vsync is enabled
func (w *Window) VSync() bool {
return w.config.Vsync
}
func (w *Window) Fullscreen() bool {
return w.config.Fullscreen
}
func (w *Window) SetFullscreen() {
w.setFullscreen(true)
}
// Sets windowed mode, but sets the window to fill the entire screen
// This is basically to setting a borderless windowed fullscreen mode
// This is similar to Maximize, except is more appropriate for ensuring the screen is filled
func (w *Window) SetWindowedFullscreen() {
mainthread.Call(func() {
w.saveLastWindow()
w.window.SetWindowToFillScreen()
// Note: In windows, when going to fullscreen, it looks like vsync data gets lost during SetMonitor, So I will manually reset swapinterval here
// GLFW Issue: https://github.com/glfw/glfw/issues/1072
w.setSwap()
// Update the config value
w.config.Fullscreen = false
})
}
// Restores the window to the last windowed state. Effectively removing exclusive fullscreen or windowed fullscreen
func (w *Window) RestoreWindowed() {
if w.config.Fullscreen {
w.setFullscreen(false)
} else {
mainthread.Call(func() {
w.restoreLastWindow()
})
}
}
func (w *Window) Decorated() bool {
return !w.config.Undecorated
}
func (w *Window) SetDecorations(value bool) {
w.config.Undecorated = !value
mainthread.Call(func() {
w.window.SetDecorations(value)
})
}
// func (w *Window) Maximize() {
// w.config.Maximized = true
// mainthread.Call(func() {
// w.window.Maximize()
// })
// }
// func (w *Window) Restore() {
// w.config.Maximized = false
// mainthread.Call(func() {
// w.window.Restore()
// })
// }
func (w *Window) setFullscreen(value bool) {
mainthread.Call(func() {
if value && !w.config.Fullscreen {
// If going fullscreen, and not currently fullscreen
w.saveLastWindow()
w.window.SetFullscreen()
} else if !value && w.config.Fullscreen {
// If going windowed and not currently windowed
w.restoreLastWindow()
}
// Note: In windows, when going to fullscreen, it looks like vsync data gets lost during SetMonitor, So I will manually reset swapinterval here
// GLFW Issue: https://github.com/glfw/glfw/issues/1072
w.setSwap()
// Update the config value
w.config.Fullscreen = value
})
}
func (w *Window) setSwap() {
if w.config.Vsync {
glfw.SwapInterval(1)
} else {
glfw.SwapInterval(0)
}
}
func (w *Window) saveLastWindow() {
x, y := w.window.GetPos()
w.lastWinPos = glm.IVec2{x, y}
width, height := w.window.GetSize()
w.lastWinSize = glm.IVec2{width, height}
}
func (w *Window) restoreLastWindow() {
w.window.SetWindowed(w.lastWinPos.X, w.lastWinPos.Y, w.lastWinSize.X, w.lastWinSize.Y)
}
// Returns true if the window is embedded in an iframe, else returns false.
// Always returns false on desktop
func (w *Window) EmbeddedIframe() bool {
return w.window.EmbeddedIframe()
}
func (w *Window) Add(filler GeometryFiller, mat glMat4, mask RGBA, material Material) {
setTarget(w)
global.Add(filler, mat, mask, material)
}
func (w *Window) GetConnectedGamepads() []Gamepad {
return w.connectedGamepads
}
func (w *Window) findNewActiveGamepad() Gamepad {
gamepads := w.GetConnectedGamepads()
for _, gp := range gamepads {
state := w.getGamepadState(gp)
if checkGamepadActive(state) {
return gp
}
}
return GamepadNone
}
// Sets the icon of the window
// Note: Currently in browser, this does nothing
func (w *Window) SetIcon(images []image.Image) {
mainthread.Call(func() {
w.window.SetIcon(images)
})
}
// By default, when running in browser. If the page unloads (ctrl-w or exit) an alert box will appear "Are you sure you want to leave?"
// If you pass a true to this function the alert box will not be shown
func (w *Window) SetSkipWarningOnBrowserClose(value bool) {
w.window.SetSkipWarningOnBrowserClose(value)
}
// --- Dear Imgui required ---
func (w *Window) GetMouse() (x, y float64) {
return w.window.GetCursorPos()
}
func (w *Window) GetMouseButton(b glfw.MouseButton) glfw.Action {
return w.window.GetMouseButton(b)
}
func (w *Window) DisplaySize() [2]float32 {
// width, height := w.Window.GetSize()
return [2]float32{float32(w.width), float32(w.height)}
}
func (w *Window) FramebufferSize() [2]float32 {
return w.DisplaySize()
}
func (w *Window) AddScrollCallback(cb glfw.ScrollCallback) {
w.scrollCallbacks = append(w.scrollCallbacks, cb)
// fmt.Println("Adding new scroll callback. Currently: ", len(w.scrollCallbacks))
}
func (w *Window) AddKeyCallback(cb glfw.KeyCallback) {
w.keyCallbacks = append(w.keyCallbacks, cb)
// fmt.Println("Adding new key callback. Currently: ", len(w.keyCallbacks))
}
func (w *Window) AddCharCallback(cb glfw.CharCallback) {
w.charCallbacks = append(w.charCallbacks, cb)
// fmt.Println("Adding new char callback. Currently: ", len(w.charCallbacks))
}
func (w *Window) AddMouseButtonCallback(cb glfw.MouseButtonCallback) {
w.mouseButtonCallbacks = append(w.mouseButtonCallbacks, cb)
// fmt.Println("Adding new mouse button callback. Currently: ", len(w.mouseButtonCallbacks))
}