BuffersGL 1.5

glMapBuffer

Returns a CPU pointer through which you can read or write a whole buffer.

Signature

void *glMapBuffer(GLenum target, GLenum access);

How it works

Instead of preparing data in your own array and copying it with glBufferSubData, you write straight into the buffer's storage through the returned pointer. That saves a copy when you generate the data yourself.

The buffer stays mapped until glUnmapBuffer. While it is mapped it cannot be used for drawing, and after unmapping the pointer must not be used again.

Parameters

targetGLenum

Slot whose bound buffer is mapped.

accessGLenum

What you will do through the pointer.

Common values

GL_WRITE_ONLY
Write only — the fastest; the old contents never have to be copied to you.
GL_READ_ONLY
Read only.
GL_READ_WRITE
Both.

Return value

The pointer, or NULL on failure.

Tips & pitfalls

  • Writing through a GL_READ_ONLY mapping, or reading through GL_WRITE_ONLY, is undefined behaviour.

  • If the GPU is still using the buffer, mapping waits for it. For per-frame data prefer glMapBufferRange with explicit flags.

Errors

When the call is invalid it does nothing and sets an error, which glGetError returns:

GL_INVALID_OPERATION
No buffer bound, or the buffer is already mapped.

Example

example.cpp
1glBindBuffer(GL_ARRAY_BUFFER, vbo);
2auto* dst = static_cast<Vertex*>(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY));
3generateTerrain(dst, count);
4glUnmapBuffer(GL_ARRAY_BUFFER);
Official Khronos documentation