Converting OpenGL draw lists to vertex arrays or VBOs

六眼飞鱼酱① 提交于 2019-12-06 08:42:19

Here's some Java code, in C the FloatBuffers would be arrays.

public VBO createVBO(List<Vec2> vertexList, List<Vec2> texelList){
    FloatBuffer vertexBuffer = FloatBuffer.allocate(vertexList.size()*3);
    FloatBuffer texelBuffer = FloatBuffer.allocate(texelList.size()*2);
    for(Vec2 point : vertexList){
        vertexBuffer.put(point.x);
        vertexBuffer.put(point.y);
        vertexBuffer.put(0);
    }
    vertexBuffer.flip();
    for(Vec2 point : texelList){
        texelBuffer.put(point.x);
        texelBuffer.put(point.y);
    }
    texelBuffer.flip();

    int[] vbo = new int[2];
    gl.glGenBuffers(1, vbo, 0);
    gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, vbo[0]);
    gl.glBufferData(GL.GL_ARRAY_BUFFER, vertexBuffer.capacity()*4, vertexBuffer, GL2.GL_STATIC_DRAW);
    gl.glGenBuffers(1, vbo, 1);
    gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, vbo[1]);
    gl.glBufferData(GL.GL_ARRAY_BUFFER, texelBuffer.capacity()*4, texelBuffer, GL2.GL_STATIC_DRAW);

    return new VBO(vbo[0], vbo[1], vertexList.size());
}

public void renderVBO(VBO vbo){
    gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY);

    gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo.vertices);
    gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0);    
    gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo.texels);
    gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, 0);

    gl.glDrawArrays(GL.GL_TRIANGLE_FAN, 0, vbo.length);

    gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!