Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
opengl tutorial 0
package main
import(
"fmt"
"gl"
"gl/glu"
"os"
"sdl"
)
const (
SCREEN_WIDTH=800
SCREEN_HEIGHT=600
SCREEN_BPP=32
)
var (
surface *sdl.Surface
t0 uint32
frames uint32
)
func Quit(status int){
sdl.Quit()
os.Exit(status)
}
func ResizeWindow(width, height int){
if height == 0 {
height = 1
}
gl.Viewport(0,0,width,height)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
aspect := float64(gl.GLfloat(width) / gl.GLfloat(height))
var fov, near, far float64
fov = 45.0
near = 0.1
far = 100.0
glu.Perspective(fov, aspect, near, far)
gl.MatrixMode(gl.MODELVIEW)
gl.LoadIdentity()
}
func HandleKeyPress(keysym sdl.Keysym){
switch keysym.Sym{
case sdl.K_ESCAPE:
Quit(0)
case sdl.K_F1:
sdl.WM_ToggleFullScreen(surface)
}
}
func InitGL(){
gl.ShadeModel(gl.SMOOTH)
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
gl.ClearDepth(1.0)
gl.Enable(gl.DEPTH_TEST)
gl.DepthFunc(gl.LEQUAL)
gl.Hint(gl.PERSPECTIVE_CORRECTION_HINT, gl.NICEST)
}
func DrawGLScene(){
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.LoadIdentity()
sdl.GL_SwapBuffers()
frames++
t := sdl.GetTicks()
if t-t0 >= 5000{
seconds := (t-t0)/1000.0
fps := frames / seconds
fmt.Println(frames, "frames in", seconds, "seconds =", fps, "FPS")
t0 = t
frames = 0
}
}
func main(){
defer Quit(0) //At the end of this function, exit.
if sdl.Init(sdl.INIT_VIDEO) < 0 {
panic("Video Init failed: " + sdl.GetError())
}
videoFlags := uint32(sdl.OPENGL)
videoFlags |= sdl.DOUBLEBUF
videoFlags |= sdl.HWPALETTE
surface = sdl.SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags)
if surface == nil {
panic("Video mode not set: " + sdl.GetError())
Quit(1)
}
sdl.GL_SetAttribute(sdl.GL_DOUBLEBUFFER, 1)
InitGL()
ResizeWindow(SCREEN_WIDTH,SCREEN_HEIGHT)
running := true
isActive := true
event := &sdl.Event{}
for running{
for event.Poll(){
switch event.Type{
case sdl.ACTIVEEVENT:
isActive = event.Active().Gain != 0
case sdl.VIDEORESIZE:
resize := event.Resize()
width, height := int(resize.W), int(resize.H)
surface = sdl.SetVideoMode(width, height, SCREEN_BPP, videoFlags)
if surface == nil{
fmt.Println("Could not form surface after Resize: " + sdl.GetError())
Quit(1)
}
ResizeWindow(width,height)
case sdl.KEYDOWN:
HandleKeyPress(event.Keyboard().Keysym)
case sdl.QUIT:
running = false
}
}
if isActive{
DrawGLScene()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.