main: backport gl02 goodies

This commit is contained in:
Edgaru089 2022-02-05 19:43:28 +08:00
parent 92b0ace7a2
commit d376a0fd39
4 changed files with 92 additions and 7 deletions

7
cmd/main.cfg.json Normal file
View File

@ -0,0 +1,7 @@
{
"WindowWidth": 1600,
"WindowHeight": 900,
"FramerateLimit": 60
}

View File

@ -13,34 +13,48 @@ import (
"github.com/go-gl/glfw/v3.3/glfw"
)
const (
//windowWidth = 852
//windowHeight = 480
windowWidth = 1600
windowHeight = 900
var (
frameTick *time.Ticker
)
func init() {
runtime.LockOSThread()
}
func main() {
err := gio.LoadConfig()
if err != nil {
panic(err)
}
if err := glfw.Init(); err != nil {
panic(err)
}
defer glfw.Terminate()
// framerate limit ticker
if gio.MainConfig.FramerateLimit > 0 {
frameTick = time.NewTicker(time.Second / time.Duration(gio.MainConfig.FramerateLimit))
}
glfw.WindowHint(glfw.Resizable, 1)
glfw.WindowHint(glfw.ContextVersionMajor, 3)
glfw.WindowHint(glfw.ContextVersionMinor, 3)
glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
glfw.WindowHint(glfw.OpenGLForwardCompatible, 1)
win, err := glfw.CreateWindow(windowWidth, windowHeight, "Gl01", nil, nil)
win, err := glfw.CreateWindow(gio.MainConfig.WindowWidth, gio.MainConfig.WindowHeight, "Gl01", nil, nil)
if err != nil {
panic(err)
}
win.MakeContextCurrent()
glfw.SwapInterval(1)
// vsync
if gio.MainConfig.FramerateLimit == 0 {
glfw.SwapInterval(1)
} else {
glfw.SwapInterval(0)
}
err = gl.Init()
if err != nil {
@ -83,5 +97,9 @@ func main() {
} else {
fpsCounter++
}
if gio.MainConfig.FramerateLimit > 0 {
<-frameTick.C
}
}
}

20
internal/io/config.go Normal file
View File

@ -0,0 +1,20 @@
package io
import "edgaru089.ml/go/gl01/internal/util"
var (
MainConfig struct {
WindowWidth, WindowHeight int
FramerateLimit int // 0: vsync, -1: unlimited
}
)
func LoadConfig() (err error) {
err = util.LoadJSON("main.cfg.json", &MainConfig)
if err != nil {
return
}
return
}

40
internal/util/json.go Normal file
View File

@ -0,0 +1,40 @@
package util
import (
"encoding/json"
"os"
)
func LoadJSON(filename string, object interface{}) (err error) {
file, err := os.Open(filename)
if err != nil {
return
}
dec := json.NewDecoder(file)
err = dec.Decode(object)
if err != nil {
return
}
file.Close()
return
}
func SaveJSON(filename string, object interface{}) (err error) {
file, err := os.Create(filename)
if err != nil {
return
}
enc := json.NewEncoder(file)
err = enc.Encode(object)
if err != nil {
return
}
file.Close()
return
}