split main loop for manual main loop support

This commit is contained in:
Thomas Friedel 2018-03-24 19:20:30 +01:00
parent 385a230aa6
commit f57765cdc5
2 changed files with 58 additions and 35 deletions

2
.gitignore vendored
View file

@ -3,3 +3,5 @@ plan.txt
glowgen glowgen
testapp testapp
openglinterface.go.all openglinterface.go.all
videocap

View file

@ -17,7 +17,11 @@ import (
type Window struct { type Window struct {
Window *sdl.Window Window *sdl.Window
GLContext sdl.GLContext GLContext sdl.GLContext
frameTimes [10]time.Time
frameIndex int
frameCount int
fps float32 fps float32
close bool
} }
func CreateCanvasWindow(w, h int, title string) (*Window, *canvas.Canvas, error) { func CreateCanvasWindow(w, h int, title string) (*Window, *canvas.Canvas, error) {
@ -83,13 +87,15 @@ func (wnd *Window) FPS() float32 {
return wnd.fps return wnd.fps
} }
func (wnd *Window) MainLoop(drawFunc func()) { func (wnd *Window) Close() {
var frameTimes [10]time.Time wnd.close = true
frameIndex := 0 }
frameCount := 0
// main loop func (wnd *Window) IsClosed() bool {
for running := true; running; { return wnd.close
}
func (wnd *Window) StartFrame() error {
for { for {
ei := sdl.PollEvent() ei := sdl.PollEvent()
if ei == nil { if ei == nil {
@ -98,16 +104,42 @@ func (wnd *Window) MainLoop(drawFunc func()) {
switch e := ei.(type) { switch e := ei.(type) {
case *sdl.WindowEvent: case *sdl.WindowEvent:
if e.Event == sdl.WINDOWEVENT_CLOSE { if e.Event == sdl.WINDOWEVENT_CLOSE {
running = false wnd.close = true
} }
case *sdl.KeyDownEvent: case *sdl.KeyDownEvent:
if e.Keysym.Scancode == sdl.SCANCODE_ESCAPE { if e.Keysym.Scancode == sdl.SCANCODE_ESCAPE {
running = false wnd.close = true
} }
} }
} }
err := sdl.GL_MakeCurrent(wnd.Window, wnd.GLContext) err := sdl.GL_MakeCurrent(wnd.Window, wnd.GLContext)
if err != nil {
return err
}
return nil
}
func (wnd *Window) FinishFrame() {
now := time.Now()
wnd.frameTimes[wnd.frameIndex] = now
wnd.frameIndex++
wnd.frameIndex %= len(wnd.frameTimes)
if wnd.frameCount < len(wnd.frameTimes) {
wnd.frameCount++
} else {
diff := now.Sub(wnd.frameTimes[wnd.frameIndex]).Seconds()
wnd.fps = float32(wnd.frameCount-1) / float32(diff)
}
sdl.GL_SwapWindow(wnd.Window)
}
func (wnd *Window) MainLoop(drawFunc func()) {
// main loop
for !wnd.close {
err := wnd.StartFrame()
if err != nil { if err != nil {
time.Sleep(10 * time.Millisecond) time.Sleep(10 * time.Millisecond)
continue continue
@ -115,17 +147,6 @@ func (wnd *Window) MainLoop(drawFunc func()) {
drawFunc() drawFunc()
now := time.Now() wnd.FinishFrame()
frameTimes[frameIndex] = now
frameIndex++
frameIndex %= len(frameTimes)
if frameCount < len(frameTimes) {
frameCount++
} else {
diff := now.Sub(frameTimes[frameIndex]).Seconds()
wnd.fps = float32(frameCount-1) / float32(diff)
}
sdl.GL_SwapWindow(wnd.Window)
} }
} }