Search code examples
arraysopengloffset

How to use properly glVertexAttribPointer()'s offset parameter


I am having issues with OpenGL's glVertexAttribPointer().

If you had an array of vertices for generating 2 triangles and you want to read half of it and put it in a VBO1 and VAO1 and then read the other half and put it into another VBO2 and VAO2 (reading from the same floats array) we need to use the offset parameter in the glVertexAttribPointer(), am I right? The offset is given by a pointer, so do we would need to do pointer arithmetic then? I tried this but I cannot see the second triangle: glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3* sizeof(GLfloat), (GLvoid*)0 + sizeof(GLfloat)*9);

My array contains 18 floats (3*3 for the first triangle and 3*3 for the second one). Do you know how to set the offset correctly?

This is the vertices array:

GLfloat vertices[] = {
     0.6,  0.6,  0.0,
     0.6,  0.0,  0.0,
     0.0,  0.0,  0.0,
    -0.7,  0.0,  0.0,
    -0.7,  0.6,  0.0,
    -0.2,  0.6,  0.0,
};

Solution

  • No, if you store the vertices for the two triangles in two different VBOs, as you specified here:

    you want to read half of it and put it in a VBO1 and VAO1 and then read the other half and put it into another VBO2 and VAO2

    you don't need an offset. The offset passed to glVertexAttribPointer() is relative to the start of the VBO. With each VBO containing only the vertices for one triangle, the offset will be 0 for both of them.

    The setup will look like this, with the code for creating the object names omitted:

    glBindVertexArray(vao1);
    glBindBuffer(GL_ARRAY_BUFFER, vbo1);
    glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(GLfloat), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttrib(0);
    
    glBindVertexArray(vao2);
    glBindBuffer(GL_ARRAY_BUFFER, vbo2);
    glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(GLfloat), vertices + 9, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttrib(0);
    

    So for the second VBO, the offset is applied when specifying the data using glBufferData(), so that the second half of the original vertex data is stored in the second VBO. After that, each VBO contains the vertex data for one of the two triangles, and the relative offset into the VBO, which is passed as the last argument to glVertexAttribPointer(), is 0 in both cases.