What is the proper way to modify OpenGL vertex buffer?

The size of any OpenGL buffer object is set when you call glBufferData. That is, OpenGL will allocate the amount of memory you specify in the second argument of glBufferData (which isn't listed in the OP). In fact, if you call, for example glBufferData( GL_ARRAY_BUFFER, bufferSize, NULL, GL_DYNAMIC_DRAW ); OpenGL will create a buffer of bufferSize bytes of uninitialized data.

You can load any amount of data (up to the size of the buffer) using glBufferSubData, glMapBuffer, or any of the other routines for passing data. The only way to resize the buffer is to call glBufferData with a new size for the same buffer id (the value returned from glGenBuffers).

That said, you can always use a subset of the data in the buffer (which would be akin to deleting vertices), and if you render using glDrawElements, you can randomly access elements in the buffer. Adding vertices to a buffer would require allocating a larger buffer, and then you'd need to reload all of the data in the buffer.


http://www.opengl.org/wiki/GLAPI/glBufferData

glBufferData creates a new data store for the buffer object currently bound to target​. Any pre-existing data store is deleted.

This explains a call to glBufferData will "reallocate" the data, the buffer will have a new size. All the old data will be lost. If you want to write to only a part of the buffer, use glBufferSubData instead.

http://www.opengl.org/wiki/GLAPI/glBufferSubData

Edit: glBufferSubData is only if you want to replace data; to resize the buffer instead, you have to call glBufferData.

Also, you don't have to destroy the buffer first and generate a new one. Remember the GLuint is only a 'pointer' of sorts for OpenGL. It is not the actual storage, thus it is perfectly fine to reuse the same 'pointer' (if you did not delete it yet of course).

Tags:

Opengl