// renders the display on each update func render() { gl.Clear(gl.COLOR_BUFFER_BIT) gl.Enable(gl.BLEND) gl.Enable(gl.POINT_SMOOTH) gl.Enable(gl.LINE_SMOOTH) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.LoadIdentity() // draw pipes for _, pipeBox := range pipe { gl.PushMatrix() pos := pipeBox.Body.Position() gl.Translatef(float32(pos.X), float32(pos.Y), 0.0) drawSquare(.19, .8, .19, 1) // limegreen gl.PopMatrix() } // draw flappy for _, flappyBird := range flappyBirds { gl.PushMatrix() pos := flappyBird.Body.Position() gl.Translatef(float32(pos.X), float32(pos.Y), 0.0) drawSquare(1, .84, 0, 1) // gold gl.PopMatrix() } gl.Color4f(1, 0, 1, 1) scoreStr := "[ Score: " + strconv.Itoa(score) + " ]" // draw score drawScore(scoreStr) }
//Call this function once to enable debug print message (to stdout). Will not crash if your machine does not support GL_ARB_debug_output func EnableGLDebugLogging() { if lux.Extensions["GL_ARB_debug_output"] { log.Print("debugging enabled") gl.Enable(gl.DEBUG_OUTPUT_SYNCHRONOUS_ARB) gl.DebugMessageCallbackARB(gl.DebugProc(glDebugCallback), gl.Ptr(nil)) } }
func (t *Text) Draw() { if t.IsDebug { t.BoundingBox.Draw() } gl.UseProgram(t.font.program) gl.ActiveTexture(gl.TEXTURE0) gl.BindTexture(gl.TEXTURE_2D, t.font.textureID) // uniforms gl.Uniform1i(t.font.fragmentTextureUniform, 0) gl.Uniform4fv(t.font.colorUniform, 1, &t.color[0]) gl.Uniform2fv(t.font.finalPositionUniform, 1, &t.finalPosition[0]) gl.UniformMatrix4fv(t.font.orthographicMatrixUniform, 1, false, &t.font.OrthographicMatrix[0]) gl.UniformMatrix4fv(t.font.scaleMatrixUniform, 1, false, &t.scaleMatrix[0]) // draw drawCount := int32(t.RuneCount * 6) if drawCount > int32(t.eboIndexCount) { drawCount = int32(t.eboIndexCount) } if drawCount < 0 { drawCount = 0 } gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.BindVertexArray(t.vao) gl.DrawElements(gl.TRIANGLES, drawCount, gl.UNSIGNED_INT, nil) gl.BindVertexArray(0) gl.Disable(gl.BLEND) }
// InitGraphics creates an OpenGL window and initializes the required graphics libraries. // It will either succeed or panic. func (app *ExampleApp) InitGraphics(title string, w int, h int) { err := glfw.Init() if err != nil { panic("Can't init glfw! " + err.Error()) } // request a OpenGL 3.3 core context glfw.WindowHint(glfw.Samples, 0) glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) // do the actual window creation app.MainWindow, err = glfw.CreateWindow(w, h, title, nil, nil) if err != nil { panic("Failed to create the main window! " + err.Error()) } app.MainWindow.MakeContextCurrent() glfw.SwapInterval(0) // make sure that all of the GL functions are initialized err = gl.Init() if err != nil { panic("Failed to initialize GL! " + err.Error()) } // set the app window dimensions app.Width = w app.Height = h gl.FrontFace(gl.CCW) gl.CullFace(gl.BACK) gl.Enable(gl.CULL_FACE) }
func SetPerspective(width, height int) { Projection := mathgl.Perspective(mathgl.DegToRad(45.0), float32(width/height), 0.1, 100.0) viewM = mathgl.LookAt(0.0, 0.0, 20.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) projectionM = Projection gl.Disable(gl.CULL_FACE) gl.Enable(gl.DEPTH_TEST) }
// createRenderer creates a new graphics Renderer engine and does // any initializiation necessary. // // NOTE: in the future, this can create either a forward or deferred // renderer with more advanced options. func createRenderer(mainWindow *glfw.Window) (*GameRenderer, error) { gr := new(GameRenderer) gr.Shaders = make(map[string]*fizzle.RenderShader) // create the renderer itself windowW, windowH := mainWindow.GetFramebufferSize() forwardRenderer := fizzle.NewForwardRenderer(mainWindow) forwardRenderer.Init(int32(windowW), int32(windowH)) gr.Renderer = forwardRenderer gr.MainWindow = mainWindow // load the landscape diffuse shader shader, err := fizzle.LoadShaderProgramFromFiles(landscapeShaderPath, nil) if err != nil { return nil, fmt.Errorf("Failed to compile and link the diffuse shader program!\n%v", err) } gr.Shaders["landscape"] = shader // load the diffuse shader shader, err = fizzle.LoadShaderProgramFromFiles(diffuseShaderPath, nil) if err != nil { return nil, fmt.Errorf("Failed to compile and link the diffuse shader program!\n%v", err) } gr.Shaders["diffuse"] = shader // put a test light in the renderer light := fizzle.NewLight() //light.Position = mgl.Vec3{8.0, 8.0, 8.0} light.DiffuseColor = mgl.Vec4{1.0, 1.0, 1.0, 1.0} light.Direction = mgl.Vec3{0.1, -1.0, -0.1} light.DiffuseIntensity = 0.6 light.AmbientIntensity = 0.4 //light.Attenuation = 1.0 forwardRenderer.ActiveLights[0] = light // setup the camera to look at the cube gr.camera = fizzle.NewOrbitCamera(mgl.Vec3{0.0, 0.0, 0.0}, mgl.DegToRad(35.0), 16.0, mgl.DegToRad(90.0)) // set some OpenGL flags gl.Enable(gl.CULL_FACE) gl.Enable(gl.DEPTH_TEST) return gr, nil }
func (r *EffectsRenderer) Bind() error { gl.BindFramebuffer(gl.FRAMEBUFFER, r.framebuffer) gl.Enable(gl.STENCIL_TEST) gl.Viewport(0, 0, int32(r.width), int32(r.height)) gl.ClearStencil(0) gl.ClearColor(0.0, 0.0, 0.0, 0.0) gl.StencilMask(0xFF) // Write to buffer gl.Clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT) gl.StencilMask(0x00) // Don't write to buffer return nil }
func main() { app = NewApp() app.InitGraphics("Cube Drop", 800, 600) app.SetKeyCallback(keyCallback) app.OnRender = renderCallback app.OnUpdate = updateCallback defer app.Terminate() // compile the shaders var err error diffuseShader, err = LoadShaderProgram(DiffuseTextureVertShader, DiffuseTextureFragShader) if err != nil { panic("Failed to compile the diffuse shader! " + err.Error()) } // setup the slice of cubes to render cubes = make([]*Entity, 0, 128) // load the grass texture for the ground grassTex, err := LoadImageToTexture(grassTexturePath) if err != nil { panic("Failed to load the grass texture! " + err.Error()) } // load the crate texture for the cubes crateTexture, err = LoadImageToTexture(crateTexturePath) if err != nil { panic("Failed to load the crate texture! " + err.Error()) } // create the ground plane groundPlane = cubez.NewCollisionPlane(m.Vector3{0.0, 1.0, 0.0}, 0.0) // make a ground plane to draw ground = CreatePlaneXZ(-500.0, 500.0, 500.0, -500.0, 64.0) ground.Shader = diffuseShader ground.Color = mgl.Vec4{1.0, 1.0, 1.0, 1.0} ground.Tex0 = grassTex // setup the camera app.CameraPos = mgl.Vec3{0.0, 3.0, 10.0} app.CameraRotation = mgl.QuatLookAtV( mgl.Vec3{0.0, 5.0, 10.0}, mgl.Vec3{0.0, 0.0, 0.0}, mgl.Vec3{0.0, 1.0, 0.0}) gl.Enable(gl.DEPTH_TEST) app.RenderLoop() }
func CreateBuffers() { var err error program, err = MakeProgram(VertexShader(), FragmentShader()) // defer program.Delete() if err != nil { fmt.Println("Error loading shaders: " + err.Error()) panic("error loading shaders") } gl.BindFragDataLocation(program, 0, gl.Str("color\x00")) MVPid = gl.GetUniformLocation(program, gl.Str("MVP\x00")) lightpositionID = gl.GetUniformLocation(program, gl.Str("light.position\x00")) lightintensitiesID = gl.GetUniformLocation(program, gl.Str("light.intensities\x00")) lightattenuationID = gl.GetUniformLocation(program, gl.Str("light.attenuation\x00")) lightambientCoeficientID = gl.GetUniformLocation(program, gl.Str("light.ambientCoeficient\x00")) cameraPositionID = gl.GetUniformLocation(program, gl.Str("cameraPosition\x00")) // View := mathgl.LookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) // viewM = View gl.DepthFunc(gl.LEQUAL) gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) // var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) // var vbo uint32 gl.GenBuffers(1, &vbo) // gl.GenBuffers(1, &elementvbo) // fmt.Println(program) gl.UseProgram(program) for idx, img := range aggregateImages { bindAggregateImage(img, idx) } }
func (ps *ParticleSystem) Render(delta float64, VP glm.Mat4, camera glm.Vec3) { ps.time += delta //do update ps.gTime.Uniform1f(float32(ps.time) * 1000) ps.gDeltaTimeMillis.Uniform1f(float32(delta) * 1000) //bind the rand texture //m_randomTexture.Bind(RANDOM_TEXTURE_UNIT); gl.Enable(gl.RASTERIZER_DISCARD) ps.buffers[ps.currentVB].Bind(gl.ARRAY_BUFFER) ps.transformfeedbacks[ps.currentTFB].Bind() gl.EnableVertexAttribArray(0) gl.EnableVertexAttribArray(1) gl.EnableVertexAttribArray(2) gl.EnableVertexAttribArray(3) gl.VertexAttribPointer(0, 1, gl.FLOAT, false, int32(unsafe.Sizeof(Particle{})), unsafe.Pointer(uintptr(0))) gl.VertexAttribPointer(1, 3, gl.FLOAT, false, int32(unsafe.Sizeof(Particle{})), unsafe.Pointer(uintptr(4))) gl.VertexAttribPointer(2, 3, gl.FLOAT, false, int32(unsafe.Sizeof(Particle{})), unsafe.Pointer(uintptr(16))) gl.VertexAttribPointer(3, 1, gl.FLOAT, false, int32(unsafe.Sizeof(Particle{})), unsafe.Pointer(uintptr(28))) gl.BeginTransformFeedback(gl.POINTS) if ps.isFirst { gl.DrawArrays(gl.POINTS, 0, 1) ps.isFirst = false } else { gl.DrawTransformFeedback(gl.POINTS, uint32(ps.transformfeedbacks[ps.currentVB])) } gl.EndTransformFeedback() gl.DisableVertexAttribArray(0) gl.DisableVertexAttribArray(1) gl.DisableVertexAttribArray(2) gl.DisableVertexAttribArray(3) //do render ps.currentVB = ps.currentTFB ps.currentTFB = (ps.currentTFB + 1) & 0x1 }
// RenderString must be called on the render thread. x and y are the initial position of the pen, // in screen coordinates, and height is the height of a full line of text, in screen coordinates. func (d *Dictionary) RenderString(str string, x, y, height float64) { if str == "" { return } // No synchronization necessary because everything is run serially on the render thread anyway. if d.strs == nil { d.strs = make(map[string]strData) } data, ok := d.strs[str] if !ok { data = d.bindString(str) d.strs[str] = data } render.EnableShader("glop.font") defer render.EnableShader("") gl.ActiveTexture(gl.TEXTURE0) gl.BindTexture(gl.TEXTURE_2D, d.atlas.texture) location, _ := render.GetUniformLocation("glop.font", "tex") gl.Uniform1i(location, 0) gl.BindSampler(0, d.atlas.sampler) location, _ = render.GetUniformLocation("glop.font", "height") gl.Uniform1f(location, float32(height)) var viewport [4]int32 gl.GetIntegerv(gl.VIEWPORT, &viewport[0]) location, _ = render.GetUniformLocation("glop.font", "screen") gl.Uniform2f(location, float32(viewport[2]), float32(viewport[3])) location, _ = render.GetUniformLocation("glop.font", "pen") gl.Uniform2f(location, float32(x)+float32(viewport[0]), float32(y)+float32(viewport[1])) location, _ = render.GetUniformLocation("glop.font", "textColor") gl.Uniform3f(location, d.color[0], d.color[1], d.color[2]) gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.BindVertexArray(data.varrays[0]) gl.DrawArrays(gl.TRIANGLES, 0, data.count) }
func (c *Context) CreateWindow(w, h int, name string) (err error) { c.w = w c.h = h c.name = name c.createWindow() c.SetCursor(c.cursor) gl.Init() if e := gl.GetError(); e != 0 { if e != gl.INVALID_ENUM { err = fmt.Errorf("OpenGL glInit error: %X\n", e) return } } c.OpenGLVersion = glfw.GetVersionString() c.ShaderVersion = gl.GoStr(gl.GetString(gl.SHADING_LANGUAGE_VERSION)) gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.ClearColor(0.0, 0.0, 0.0, 1.0) gl.Disable(gl.CULL_FACE) glfw.SwapInterval(1) return }
func (c *Context) CreateWindow(w, h int, name string) (err error) { c.w = w c.h = h c.name = name var monitor *glfw.Monitor if c.fullscreen == true { monitor = glfw.GetPrimaryMonitor() } if c.window, err = glfw.CreateWindow(c.w, c.h, c.name, monitor, nil); err != nil { return } if c.cursor == false { c.window.SetInputMode(glfw.CursorMode, glfw.CursorHidden) } c.window.MakeContextCurrent() gl.Init() if e := gl.GetError(); e != 0 { if e == gl.INVALID_ENUM { fmt.Printf("GL_INVALID_ENUM when calling glInit\n") } else { err = fmt.Errorf("OpenGL glInit error: %X\n", e) return } } c.OpenGLVersion = glfw.GetVersionString() c.ShaderVersion = gl.GoStr(gl.GetString(gl.SHADING_LANGUAGE_VERSION)) gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.ClearColor(0.0, 0.0, 0.0, 1.0) gl.Disable(gl.CULL_FACE) glfw.SwapInterval(1) if c.VAO, err = CreateVAO(); err != nil { return } gl.BindVertexArray(c.VAO) c.Events = NewEventHandler(c.window) return }
func CreateContext(width, height int) Context { vertexShader := ` #version 330 uniform mat4 projection; uniform mat4 camera; uniform mat4 model; in vec3 vert; void main() { gl_Position = projection * camera * model * vec4(vert, 1); } ` + "\x00" fragmentShader := ` #version 330 uniform vec4 color; out vec4 outputColor; void main() { outputColor = color; } ` + "\x00" vertices := []float32{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, } if err := glfw.Init(); err != nil { log.Fatalln("failed to initialize glfw:", err) } // defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) window, err := glfw.CreateWindow(width, height, "OpenGL", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() if err := gl.Init(); err != nil { panic(err) } program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) projection := mgl32.Ortho2D(0, 800, 0, 600) projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00")) gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0]) camera := mgl32.LookAtV(mgl32.Vec3{0, 0, 0.5}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0}) cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00")) gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0]) model := mgl32.Ident4() modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00")) gl.UniformMatrix4fv(modelUniform, 1, false, &model[0]) var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) return Context{Window: window, program: program} }
func main() { vertices, normals := obj.Parse(os.Args[1]) // initialize GLFW if err := glfw.Init(); err != nil { panic(err) } defer glfw.Terminate() // set opengl core profile 3.3 glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) window, err := glfw.CreateWindow(640, 480, "GOpenGL", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // initialise OpenGL library if err := gl.Init(); err != nil { panic(err) } // link program from shaders program, err := newProgram("vertex.glsl", "fragment.glsl") if err != nil { panic(err) } gl.UseProgram(program) // vertex attribute object holds links between attributes and vbo var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) // vertex buffer with per-vertex data var vbo [2]uint32 gl.GenBuffers(2, &vbo[0]) // position data gl.BindBuffer(gl.ARRAY_BUFFER, vbo[0]) gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) // set up position attribute with layout of vertices posAttrib := uint32(gl.GetAttribLocation(program, gl.Str("position\x00"))) gl.VertexAttribPointer(posAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) gl.EnableVertexAttribArray(posAttrib) // normal data gl.BindBuffer(gl.ARRAY_BUFFER, vbo[1]) gl.BufferData(gl.ARRAY_BUFFER, len(normals)*4, gl.Ptr(normals), gl.STATIC_DRAW) normAttrib := uint32(gl.GetAttribLocation(program, gl.Str("normal\x00"))) gl.VertexAttribPointer(normAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) gl.EnableVertexAttribArray(normAttrib) uniModel := gl.GetUniformLocation(program, gl.Str("model\x00")) uniView := gl.GetUniformLocation(program, gl.Str("view\x00")) uniProj := gl.GetUniformLocation(program, gl.Str("proj\x00")) matView := mgl32.LookAt(2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) gl.UniformMatrix4fv(uniView, 1, false, &matView[0]) matProj := mgl32.Perspective(mgl32.DegToRad(45.0), 640.0/480.0, 1.0, 10.0) gl.UniformMatrix4fv(uniProj, 1, false, &matProj[0]) uniLightDir := gl.GetUniformLocation(program, gl.Str("lightDir\x00")) uniLightCol := gl.GetUniformLocation(program, gl.Str("lightCol\x00")) gl.Uniform3f(uniLightDir, -0.5, 0.0, -1.0) gl.Uniform3f(uniLightCol, 0.0, 0.5, 0.5) startTime := glfw.GetTime() gl.Enable(gl.DEPTH_TEST) gl.ClearColor(1.0, 1.0, 1.0, 1.0) for !window.ShouldClose() { // clear buffer gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) matRot := mgl32.HomogRotate3DZ(float32(glfw.GetTime() - startTime)) gl.UniformMatrix4fv(uniModel, 1, false, &matRot[0]) gl.DrawArrays(gl.TRIANGLES, 0, int32(len(vertices))) window.SwapBuffers() glfw.PollEvents() } }
func main() { // init glfw if err := glfw.Init(); err != nil { panic(err) } defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 4) glfw.WindowHint(glfw.ContextVersionMinor, 1) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) // make an application window window, err := glfw.CreateWindow(windowWidth, windowHeight, "Hello", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // init gl if err := gl.Init(); err != nil { panic(err) } fmt.Println("OpenGL version", gl.GoStr(gl.GetString(gl.VERSION))) // create vertex & fragment shader program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) gl.BindFragDataLocation(program, 0, gl.Str("fc\x00")) points := []float32{ -0.5, -0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, } vertices := []uint32{ 0, 2, 1, 3, } // configure the vertex data var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) defer gl.BindVertexArray(0) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(points)*4, gl.Ptr(points), gl.STATIC_DRAW) var ibo uint32 gl.GenBuffers(1, &ibo) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo) gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("pv\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 2, gl.FLOAT, false, 2*4, gl.PtrOffset(0)) // global settings gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) gl.ClearColor(1.0, 1.0, 1.0, 1.0) for !window.ShouldClose() { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gl.UseProgram(program) gl.BindVertexArray(vao) gl.DrawElements(gl.LINE_LOOP, 4, gl.UNSIGNED_INT, gl.PtrOffset(0)) window.SwapBuffers() glfw.PollEvents() } }
func Init() error { if err := gl.Init(); err != nil { return err } log.Printf("OpenGL version: %s", gl.GoStr(gl.GetString(gl.VERSION))) vs, err := asset.String("shader.vert") if err != nil { return err } fs, err := asset.String("shader.frag") if err != nil { return err } program, err := createProgram(vs, fs) if err != nil { return err } gl.UseProgram(program) var shaderErr error uniform := func(name string) int32 { var loc int32 loc, shaderErr = getUniformLocation(program, name) return loc } projectionViewMatrixUniform = uniform("u_projectionViewMatrix") modelMatrixUniform = uniform("u_modelMatrix") normalMatrixUniform = uniform("u_normalMatrix") ambientLightColorUniform = uniform("u_ambientLightColor") directionalLightColorUniform = uniform("u_directionalLightColor") directionalVectorUniform = uniform("u_directionalVector") textureUniform = uniform("u_texture") grayscaleUniform = uniform("u_grayscale") brightnessUniform = uniform("u_brightness") alphaUniform = uniform("u_alpha") mixColorUniform = uniform("u_mixColor") mixAmountUniform = uniform("u_mixAmount") if shaderErr != nil { return shaderErr } vm := newViewMatrix(cameraPosition, targetPosition, up) nm := vm.inverse().transpose() gl.UniformMatrix4fv(normalMatrixUniform, 1, false, &nm[0]) gl.Uniform3fv(ambientLightColorUniform, 1, &ambientLightColor[0]) gl.Uniform3fv(directionalLightColorUniform, 1, &directionalLightColor[0]) gl.Uniform3fv(directionalVectorUniform, 1, &directionalVector[0]) SizeCallback = func(width, height int) { if winWidth == width && winHeight == height { return } log.Printf("window size changed (%dx%d -> %dx%d)", int(winWidth), int(winHeight), width, height) gl.Viewport(0, 0, int32(width), int32(height)) // Calculate new perspective projection view matrix. winWidth, winHeight = width, height fw, fh := float32(width), float32(height) aspect := fw / fh fovRadians := float32(math.Pi) / 3 perspectiveProjectionViewMatrix = vm.mult(newPerspectiveMatrix(fovRadians, aspect, 1, 2000)) // Calculate new ortho projection view matrix. orthoProjectionViewMatrix = newOrthoMatrix(fw, fh, fw /* use width as depth */) } if err := initMeshes(); err != nil { return err } if err := initTextures(); err != nil { return err } gl.Enable(gl.CULL_FACE) gl.CullFace(gl.BACK) gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) gl.ClearColor(0, 0, 0, 0) return nil }
func main() { // init glfw if err := glfw.Init(); err != nil { panic(err) } defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 4) glfw.WindowHint(glfw.ContextVersionMinor, 1) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) // make an application window window, err := glfw.CreateWindow(windowWidth, windowHeight, "Transform", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // init gl if err := gl.Init(); err != nil { panic(err) } fmt.Println("OpenGL version", gl.GoStr(gl.GetString(gl.VERSION))) // create vertex & fragment shader program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) projection := mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/windowHeight, 0.1, 10.0) projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00")) gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0]) camera := mgl32.LookAtV( mgl32.Vec3{3, 3, 3}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0}, ) cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00")) gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0]) model := mgl32.Ident4() modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00")) gl.UniformMatrix4fv(modelUniform, 1, false, &model[0]) gl.BindFragDataLocation(program, 0, gl.Str("vert\x00")) points := []float32{ -0.9, -0.9, -0.9, 0.9, -0.9, -0.9, 0.9, -0.9, 0.9, -0.9, -0.9, 0.9, -0.9, 0.9, -0.9, 0.9, 0.9, -0.9, 0.9, 0.9, 0.9, -0.9, 0.9, 0.9, } vertices := []uint32{ 0, 1, 1, 2, 2, 3, 3, 0, 0, 4, 1, 5, 2, 6, 3, 7, 4, 5, 5, 6, 6, 7, 7, 4, } // configure the vertex data var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) defer gl.BindVertexArray(0) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(points)*4, gl.Ptr(points), gl.STATIC_DRAW) var ibo uint32 gl.GenBuffers(1, &ibo) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo) gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) // global settings gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) gl.ClearColor(0.0, 0.0, 0.0, 1.0) angleX := 0.0 angleY := 0.0 angleZ := 0.0 previousTime := glfw.GetTime() for !window.ShouldClose() { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) time := glfw.GetTime() elapsed := time - previousTime previousTime = time angleX += math.Sin((elapsed / period) * math.Pi * 2.0) angleY += math.Sin((elapsed / period) / 6.0 * math.Pi * 2.0) angleZ += math.Sin((elapsed / period) / 3.0 * math.Pi * 2.0) model = mgl32.HomogRotate3DY(float32(angleY)).Mul4(mgl32.HomogRotate3DX(float32(angleX))).Mul4(mgl32.HomogRotate3DZ(float32(angleZ))) gl.UseProgram(program) gl.UniformMatrix4fv(modelUniform, 1, false, &model[0]) gl.BindVertexArray(vao) gl.DrawElements(gl.LINES, int32(len(vertices)), gl.UNSIGNED_INT, gl.PtrOffset(0)) window.SwapBuffers() glfw.PollEvents() } }
//PostRender renable depth test func (ppfb *PostProcessFramebuffer) PostRender() { gl.Enable(gl.DEPTH_TEST) }
func main() { app = NewApp() app.InitGraphics("Ballistic", 800, 600) app.SetKeyCallback(keyCallback) app.OnRender = renderCallback app.OnUpdate = updateCallback defer app.Terminate() // compile the shaders var err error colorShader, err = LoadShaderProgram(DiffuseColorVertShader, DiffuseColorFragShader) if err != nil { panic("Failed to compile the shader! " + err.Error()) } // create the ground plane groundPlane = cubez.NewCollisionPlane(m.Vector3{0.0, 1.0, 0.0}, 0.0) // make a ground plane to draw ground = CreatePlaneXZ(-500.0, 500.0, 500.0, -500.0, 1.0) ground.Shader = colorShader ground.Color = mgl.Vec4{0.6, 0.6, 0.6, 1.0} // create a test cube to render cubeNode := CreateCube(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0) cubeNode.Shader = colorShader cubeNode.Color = mgl.Vec4{1.0, 0.0, 0.0, 1.0} // create the collision box for the the cube var cubeMass m.Real = 8.0 var cubeInertia m.Matrix3 cubeCollider := cubez.NewCollisionCube(nil, m.Vector3{1.0, 1.0, 1.0}) cubeCollider.Body.Position = m.Vector3{0.0, 5.0, 0.0} cubeCollider.Body.SetMass(cubeMass) cubeInertia.SetBlockInertiaTensor(&cubeCollider.HalfSize, cubeMass) cubeCollider.Body.SetInertiaTensor(&cubeInertia) cubeCollider.Body.CalculateDerivedData() cubeCollider.CalculateDerivedData() // make the entity out of the renerable and collider cube = NewEntity(cubeNode, cubeCollider) // make a slice of entities for bullets bullets = make([]*Entity, 0, 16) // make the backboard to bound the bullets off of backboardNode := CreateCube(-0.5, -2.0, -0.25, 0.5, 2.0, 0.25) backboardNode.Shader = colorShader backboardNode.Color = mgl.Vec4{0.25, 0.2, 0.2, 1.0} backboardCollider := cubez.NewCollisionCube(nil, m.Vector3{0.5, 2.0, 0.25}) backboardCollider.Body.Position = m.Vector3{0.0, 2.0, -10.0} backboardCollider.Body.SetInfiniteMass() backboardCollider.Body.CalculateDerivedData() backboardCollider.CalculateDerivedData() SetGlVector3(&backboardNode.Location, &backboardCollider.Body.Position) // make the backboard entity backboard = NewEntity(backboardNode, backboardCollider) // setup the camera app.CameraPos = mgl.Vec3{-3.0, 3.0, 15.0} app.CameraRotation = mgl.QuatLookAtV( mgl.Vec3{-3.0, 3.0, 15.0}, mgl.Vec3{0.0, 1.0, 0.0}, mgl.Vec3{0.0, 1.0, 0.0}) gl.Enable(gl.DEPTH_TEST) app.RenderLoop() }
func InitGL() error { defer tlog.FuncLog(tlog.Func("InitGL")) err := gl.Init() if err != nil { return err } gl.GetError() // cleanup gl error state version := gl.GoStr(gl.GetString(gl.VERSION)) tlog.Println("OpenGL version", version) gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL) Check() gl.ReadBuffer(gl.BACK) Check() gl.DrawBuffer(gl.BACK) Check() gl.FrontFace(gl.CW) Check() gl.CullFace(gl.BACK) Check() gl.Disable(gl.CULL_FACE) Check() gl.ClearColor(1, 1, 0.5, 0) Check() gl.ClearDepth(1.0) Check() gl.ClearStencil(0) Check() gl.Disable(gl.STENCIL_TEST) Check() gl.StencilMask(0xFFFFFFFF) Check() gl.StencilFunc(gl.EQUAL, 0x00000000, 0x00000001) Check() gl.StencilOp(gl.KEEP, gl.KEEP, gl.KEEP) Check() gl.Disable(gl.DITHER) Check() gl.Enable(gl.DEPTH_TEST) Check() gl.DepthFunc(gl.LEQUAL) Check() gl.DepthMask(true) Check() gl.DepthRange(0., 1.) Check() gl.Enable(gl.DEPTH_CLAMP) Check() gl.Enable(gl.BLEND) Check() gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) ForceCheck() return nil }