Search code examples
javaopengl3dlwjgl

LWJGL Vertex Index Buffer causes half of "Mesh" to load


I'm following the 3D Game Development with LWJGL book from Antonio Bejarano. I have reached the point of being able to render a quad to the screen. After having implemented the vertex index buffer, only one triangle of the quad renders to the screen, so I think it is safe to assume the problem is with that code.

        // Vertex Index Buffer
        idxVboId = glGenBuffers();
        vertsIdxBuffer = MemoryUtil.memAllocInt(indices.length);
        vertsIdxBuffer.put(indices).flip();
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,idxVboId);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,vertsIdxBuffer,GL_STATIC_DRAW);

The code for the vertices buffer and the colour buffer works, as I have removed the references to the index buffer and the full quad appears. I have also changed the render method to account for the new type to be rendered:

    shaderProgram.bind();

        //bind to vao
        glBindVertexArray(mesh.getVaoId());
        //enable positions buffer
        glEnableVertexAttribArray(0);
        //enable colour buffer
        glEnableVertexAttribArray(1);

        //draw verts
        glDrawElements(GL_TRIANGLES, 
        mesh.getVertexCount(),GL_UNSIGNED_INT,0);

        //restore state (?)
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        glBindVertexArray(0);

        shaderProgram.unbind();

Any suggestions are appreciated as I have been staring at this for hours and can't really see where I've made the mistake.

EDIT: Quad Mesh Code

     renderer.init();

    float[] positions = new float[]{
            -0.5f,  0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            0.5f,  0.5f, 0.0f,
            0.5f,  0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            0.5f, -0.5f, 0.0f,
    };

    float[] colours = new float[]{0.5f,0f,0f,0f,0.5f,0f,0f,0f,0.5f,0f,0.5f,0.5f};

    int[] indices = new int[]{
            0, 1, 3, 3, 1, 2,
    };

    mesh = new BMesh(positions,colours,indices);

2ND Edit Before and after positions array change

Before

After


Solution

  • After looking through the quad mesh initialization code, it seems the error is due to vertices 3 and 2 on the second quad being the same vertex, i.e. both are at (0.5, 0.5, 0.0). Perhaps you mistakenly copied the 4th and 5th vertices in your array?

    i.e. perhaps you meant to have

    float[] positions = new float[]{
            -0.5f,  0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            0.5f,  0.5f, 0.0f,
            0.5f, -0.5f, 0.0f
    };
    

    EDIT: Your indices seem to be wrong. Change them to { 0, 1, 3, 0, 3, 2 }