glBindBuffer
Makes a buffer the current one for a given target, so later buffer calls act on it.
Part of the family glBind*
Signature
void glBindBuffer(GLenum target, GLuint buffer);
How it works
OpenGL is a state machine: most functions do not take the object they operate on as a parameter. Instead, you first "bind" the object to a slot (the target), and every later call that uses that slot affects whatever is bound there.
glBindBuffer puts a buffer into one of those slots. After glBindBuffer(GL_ARRAY_BUFFER, vbo), a call like glBufferData(GL_ARRAY_BUFFER, ...) uploads data into vbo.
Parameters
Which slot to bind to. It defines how the buffer will be used.
Common values
- GL_ARRAY_BUFFER
- Vertex attributes (positions, colors, UVs…).
- GL_ELEMENT_ARRAY_BUFFER
- Indices for glDrawElements. This binding is stored in the current VAO.
- GL_UNIFORM_BUFFER
- Uniform blocks shared between shaders.
- GL_SHADER_STORAGE_BUFFER
- Read/write storage for shaders (GL 4.3).
- GL_COPY_READ_BUFFER / GL_COPY_WRITE_BUFFER
- Scratch slots for buffer-to-buffer copies.
The buffer ID, or 0 to unbind whatever is in the slot.
Tips & pitfalls
Never unbind GL_ELEMENT_ARRAY_BUFFER while a VAO is bound — the VAO remembers it, and unbinding erases the index buffer from the VAO.
GL_ARRAY_BUFFER is NOT stored in the VAO; what is stored is the buffer captured by each
glVertexAttribPointercall.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GL_INVALID_ENUM
- target is not an accepted value.
- GL_INVALID_VALUE
- buffer was never returned by glGenBuffers.
Example
1glBindBuffer(GL_ARRAY_BUFFER, vbo);
2glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
3glBindBuffer(GL_ARRAY_BUFFER, 0); // optional: unbind