Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose VBOs stored in a VAO

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?

like image 381
user3325226 Avatar asked Aug 06 '14 18:08

user3325226


1 Answers

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.

like image 60
Reto Koradi Avatar answered Nov 15 '22 08:11

Reto Koradi