Reputation: 1547
I created a Vertex Buffer Object class to manage lots of vertices in my application. The user calls the constructor to create a glBuffer and calls glBufferData to allocate a specified amount of space.
There is a class function called resize that allows the user to change the capacity of the VBO by calling again the glBufferData. My question is, how do I deallocate the previous allocation? Or Is it done automatically?
glDeleteBuffer, according to the opengl docs, only deletes the buffer itself with no mention of the actual memory allocated with glBufferData. Can I keep calling glBufferData on the same bound buffer with no memory leak?
Upvotes: 3
Views: 4995
Reputation: 3911
glDeleteBuffer
delete the buffer handle and the associated resource, if any, should be collected/released soon by the system.
If the buffer is currently binded the driver will unbind it (bind to zero), although it is ugly to delete a binded buffer.
Upvotes: 0
Reputation: 54602
You can't create a memory leak by repeatedly calling glBufferData()
for the same buffer object. The new allocation replaces the old one.
There's one subtle aspect that most of the time you don't need to worry about, but may still be useful to understand: There is a possibility of having multiple active allocations for the same buffer object temporarily. This happens due to the asynchronous nature of OpenGL. For illustration, picture a call sequence like this:
glBufferData(dataA)
glDraw()
glBufferData(dataB)
glDraw()
When you make the API call for item 3 in this sequence, the GPU may not yet have finished with the draw call from call 2. It may in fact still be queued up somewhere in the driver, and not handed over to the GPU yet. Since call 2 depends on dataA
, that data can not be deleted until the GPU finished executing the draw call 2. In this case, the allocations for dataA
and dataB
temporarily exist at the same time.
When exactly dataA
is actually deleted depends on the implementation. It just can't be earlier than the time where the GPU finishes with draw call 2. After that it could be immediately, based on some garbage collection timer, when memory runs low, or many other options.
glDeleteBuffer()
will also delete the buffer memory. Very similarly to the point above, it may not happen immediately. Again, it can only be deleted after the GPU finished executing all pending operations that use the buffer memory.
If you don't plan to use the buffer object anymore, calling glDeleteBuffer()
is the best option.
Upvotes: 6
Reputation: 1547
After 10 minutes I read the docs for the glBufferData page.
glBufferData creates a new data store for the buffer object currently bound to target. Any pre-existing data store is deleted.
,which solves my question. I indeed can keep calling it to increase or decrease the size of my VBO.
Upvotes: 0