OpenGL Vertex Buffer doesn't draw anything in golang

前端 未结 4 1759
忘了有多久
忘了有多久 2021-01-03 05:52

I tried to use this tutorial with Golang: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/ The go-version opens the window and makes the bac

4条回答
  •  情歌与酒
    2021-01-03 06:38

    I recently came into a similar issue with the Golang OpenGL bindings, and this question was one of the only references to it I could find. However, none of the existing answers solved my problem, as the bindings appear to be slightly different now in 2015 than they looked in 2012.

    The solution to my issue which hasn't already been covered by the existing answers involved the gl.BufferData() function called when creating a VBO.

    A problem-producing example of the code in question would look like this:

    [...]
    vertices := []float32{0, 1, 0, -1, -1, 0, 1, -1, 0}
    [...]
    gl.BufferData(
        gl.ARRAY_BUFFER,
        len(vertices)*4,
        unsafe.Pointer(&vertices),
        gl.STATIC_DRAW)
    [...]
    

    One solution already provided recommended to change this code to something like this:

    [...]
    vertices := []float32{0, 1, 0, -1, -1, 0, 1, -1, 0}
    [...]
    gl.BufferData(
        gl.ARRAY_BUFFER,
        len(vertices)*4,
        vertices,
        gl.STATIC_DRAW)
    [...]
    

    However the bindings I used had a different function signature to those used here, and errored with:

    cannot use vertices (type []float32) as type unsafe.Pointer in argument to gl.BufferData
    

    The solution I ended up finding, and wanted to put here so nobody else should have to go through the headache it took trying to figure out the issue, looks like this:

    [...]
    vertices := []float32{0, 1, 0, -1, -1, 0, 1, -1, 0}
    [...]
    gl.BufferData(
        gl.ARRAY_BUFFER,
        len(vertices)*4, //len(vertices)*int(reflect.TypeOf(vertices).Elem().Size()),
        gl.Ptr(vertices),
        gl.STATIC_DRAW)
    [...]
    

    I also included a commented out option to replace len(vertices)*4 with, which produces the exact same result, but finds the '4' based on the type of slice (float32 in this case)

    Footnotes

    The bindings I used:
    github.com/go-gl/gl/all-core/gl
    github.com/go-gl/glfw/v3.1/glfw

    My OpenGL context was created with these hints: primaryMonitor := glfw.GetPrimaryMonitor() vidMode := primaryMonitor.GetVideoMode()

    glfw.WindowHint(glfw.ContextVersionMajor, 3)
    glfw.WindowHint(glfw.ContextVersionMinor, 3)
    glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
    glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
    
    glfw.WindowHint(glfw.RedBits, vidMode.RedBits)
    glfw.WindowHint(glfw.GreenBits, vidMode.GreenBits)
    glfw.WindowHint(glfw.BlueBits, vidMode.BlueBits)
    glfw.WindowHint(glfw.RefreshRate, vidMode.RefreshRate)
    glfw.WindowHint(glfw.Visible, glfw.False)
    

提交回复
热议问题