How to dispose VBOs stored in a VAO
Asked Answered
B

1

5

I am new to OpenGL, and am learning about VBOs and VAOs. I'm trying to understand how to dispose/free/detach VBOs in a VAO, when I don't have the single VBO ids anymore, only the VAO.

Must I get all VBOs individually and then call glDeleteBuffers for each VBO? Or is there a method that takes a VAO and automatically disposes of all VBOs?

And can someone show how to get the VBOs from a VAO?

Bertine answered 6/8, 2014 at 18:29 Comment(1)
Your question does not make any sense yet. Please work on it.Necktie
H
8

You need to delete all VBO explicitly, by calling glDeleteBuffers() for them.

Your best bet is really to hold on to the VBO ids that you generated, and delete them when you don't need them anymore, which is typically around the same time you delete the VAOs. Unless the data in the VBOs is completely static, you will often need their ids anyway so that you can bind them, and update their data with calls like glBufferSubData().

To get the VBO ids for a currently bound VAO, you can use glGetVertexAttribiv(). To enumerate all of them, the code would look like this:

GLint nAttr = 0;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nAttrib);
glBindVertexArray(vaoId);
for (int iAttr = 0; iAttr < nAttr; ++iAttr) {
    GLint vboId = 0;
    glGetVertexAttribiv(iAttr, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &vboId);
    if (vboId > 0) {
        ...
    }
}

You'll have to be careful when using this to delete the VBOs, because the same VBO could be bound for multiple attributes. So you have to create a list of unique ids first, by e.g. dropping them into a std::set. It gets even trickier if you use the same VBO for multiple VAOs, which is of course completely legal and quite common.

There's one more option that I'll mention for completeness sake. I wouldn't recommend doing this. This relies on the fact that a VBO stays alive as long as it's bound to an attribute in a VAO. So in theory, you can call glDeleteBuffers() on the VBOs after you finished populating them with data and binding them to VAO attributes. While their id will be invalid after you delete them, the data will remain valid until the last VAO with a reference to the buffer is deleted.

There are some aspects to this last approach that make it pretty easy to shoot yourself in the foot. If you're seriously considering using it, you should carefully read the paragraph that starts with "Caution should be taken when deleting an object attached to a container object" under section 5.1.3 of the GL 4.4 spec, or the same in appendix D.1.2 in the GL 3.3 spec.

Hallux answered 7/8, 2014 at 3:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.