glDrawArrays with buffer not working in JOGL

2019-08-17 05:09发布

I was wondering whether someone can help me find out why my JOGL code does not show a triangle. There are no exceptions for some reason. Am I missing something?

    IntBuffer vacantNameBuffer = IntBuffer.allocate(3);
    gl.glGenBuffers(1, vacantNameBuffer);
        int vertexBufferName = vacantNameBuffer.get();
    float[] triangleArray = {
            -1.0f, -1.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            0.0f, 1.0f, 0.0f
    };

    FloatBuffer triangleVertexBuffer = FloatBuffer.wrap(triangleArray);
    gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, vacantNameBuffer.get());
    gl.glBufferData(
            GL2.GL_ARRAY_BUFFER, 
            triangleVertexBuffer.capacity() * Buffers.SIZEOF_FLOAT, 
            triangleVertexBuffer, 
            GL2.GL_STATIC_DRAW);
    gl.glEnableVertexAttribArray(vacantNameBuffer.get());
    gl.glVertexAttribPointer(0, 3, GL2.GL_FLOAT, false, 0, 0);
    gl.glDrawArrays(GL2.GL_TRIANGLES, 0, 3);
    gl.glDisableVertexAttribArray(vacantNameBuffer.get());
    gl.glFlush();

标签: opengl jogl
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-17 05:47

As already mentioned in @ratchet_freak's answer, the arguments to glEnableVertexAttribArray() and glDisableVertexAttribArray() need to be changed to pass the location of the attribute:

gl.glEnableVertexAttribArray(0);
...
gl.glDisableVertexAttribArray(0);

Beyond that, you have some problems in how you use your buffer objects. You have these types of calls multiple times:

vacantNameBuffer.get()

get() is the relative get method, which gets the value at the current buffer position, and then advances the position. So without resetting the buffer position, it will only give you the first value in the buffer the first time you make this call.

You already have a statement that gets the first value, and stores it in a variable:

int vertexBufferName = vacantNameBuffer.get();

All you need to do is use this value in the rest of the code, instead of calling get() again. So change this call:

gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, vacantNameBuffer.get());

to this:

gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, vertexBufferName);

Another option would be to use get(0), which gives you the value at an absolute position.

查看更多
孤傲高冷的网名
3楼-- · 2019-08-17 05:52

glEnableVertexAttribArray expects the attribute location (the number you set as first parameter of glVertexAttribPointer) so you should change it to:

gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 3, GL2.GL_FLOAT, false, 0, 0);
gl.glDrawArrays(GL2.GL_TRIANGLES, 0, 3);
gl.glDisableVertexAttribArray(0);
查看更多
登录 后发表回答