Skip to content

Instantly share code, notes, and snippets.

@alsritter
Created January 1, 2022 15:03
Show Gist options
  • Save alsritter/8ca66e89727352b0fe09bc895de84e28 to your computer and use it in GitHub Desktop.
Save alsritter/8ca66e89727352b0fe09bc895de84e28 to your computer and use it in GitHub Desktop.
opengl learn 01
package main
import (
"log"
"runtime"
"github.com/go-gl/gl/v3.3-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
)
const (
WIDTH = 500
HEIGHT = 500
)
// initGlfw initializes glfw and returns a Window to use.
func initGlfw() *glfw.Window {
if err := glfw.Init(); err != nil {
panic(err)
}
// 通过这些枚举值来设置 GLFW 的参数
glfw.WindowHint(glfw.Resizable, glfw.False) // 设置窗口大小无法修改
glfw.WindowHint(glfw.ContextVersionMajor, 3) // OpenGL最大版本
glfw.WindowHint(glfw.ContextVersionMinor, 3) // OpenGl 最小版本
glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) // 明确核心模式
glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) // Mac使用时需要加上
window, err := glfw.CreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nil, nil)
log.Println("created window")
if window == nil || err != nil {
panic(err)
}
window.MakeContextCurrent() // 通知 glfw 将当前窗口上下文绑定到当前线程的上下文
return window
}
// initOpenGL initializes OpenGL and returns an intiialized program.
func initOpenGL() uint32 {
if err := gl.Init(); err != nil {
panic(err)
}
version := gl.GoStr(gl.GetString(gl.VERSION))
log.Println("OpenGL version", version)
prog := gl.CreateProgram()
gl.LinkProgram(prog)
return prog
}
func main() {
runtime.LockOSThread()
window := initGlfw()
defer glfw.Terminate()
program := initOpenGL()
// 必须告诉 OpenGL 渲染窗口的尺寸大小,即视口(Viewport),这样 OpenGL 才只能知道怎样根据窗口大小显示数据和坐标。
gl.Viewport(0, 0, WIDTH, HEIGHT) // 起点为左下角
// 窗口大小被改变的回调函数
window.SetFramebufferSizeCallback(framebuffer_size_callback)
//渲染循环
for !window.ShouldClose() {
//用户输入
processInput(window)
draw(window, program)
}
}
func draw(window *glfw.Window, program uint32) {
gl.ClearColor(0.2, 0.3, 0.3, 1.0) //状态设置
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.UseProgram(program)
glfw.PollEvents()
window.SwapBuffers()
}
func processInput(window *glfw.Window) {
if window.GetKey(glfw.KeyEscape) == glfw.Press {
log.Println("escape pressed")
window.SetShouldClose(true)
}
}
// 在调整指定窗口的帧缓冲区大小时调用。
func framebuffer_size_callback(window *glfw.Window, width int, height int) {
log.Printf("resize width:%d, height:%d", width, height)
gl.Viewport(0, 0, int32(width), int32(height))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment