Search code examples
openglgraphicsglslshadervao

Can a different VAO use the previous used vertex attribute index number


Can two VAOs (va01, vao2) have the same vertex attribute index number?

GLuint vao1, vao2;

glGenVertexArrays(1, &vao1); 
glGenVertexArrays(1, &vao2); 

{
glBindVertexArray(vao1);
...
glBindBuffer(GL_ARRAY_BUFFER, vbo1);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
...
glBindVertexArray(0);
}

{
glBindVertexArray(vao2);
...
glBindBuffer(GL_ARRAY_BUFFER, vbo2);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
...
glBindVertexArray(0);
}

Suppose vbo1 and vbo2are defined before these code and they got glBufferDataalready. Can vao1 and vao2 both have the same vertex attribute index number 0?


Solution

  • Yes, several VAOs can set up the same vertex attributes, pointing to different VBOs each.

    Suppose vbo1 and vbo2are defined before these code and they got glBufferDataalready. Can vao1 and vao2 both have the same vertex attribute index number 0?

    You are confusing some things here. VAOs never care about the BufferData. VAOs store the attribute pointers, the attribute enables, and the GL_ELEMENT_ARRAY_BUFFER_BINDING. They do not store any vertex data, they only reference to it. And they do reference a VBO by name - that means that you can just do:

    glBindBuffer(GL_ARRAY_BUFFER, vbo1);
    glVertexAttribPointer(i, ...); // here, a reference to vbo1 gets part of the attrib pointer for attrib i 
    ...
    glBindBuffer(GL_ARRAY_BUFFER, vbo1);
    glBufferData(...); // VAO will now point into this buffer storage 
    

    (this also means that you can set up the pointer before you created the buffer storage for the VBO, you just need to have created the VBO object). Maybe you find my illustration in this answer helpful.