Vertex arraysGL 3.3

glVertexAttribDivisor

Makes an attribute advance per instance instead of per vertex (for instancing).

Signature

void glVertexAttribDivisor(GLuint index, GLuint divisor);

How it works

Normally the GPU reads the next value of every attribute for every vertex. With a divisor of 1, the attribute only advances once per instance — so all vertices of instance 0 see the first value, all of instance 1 see the second, and so on.

That is how you give each of 10 000 instanced asteroids its own model matrix or color while sharing a single mesh.

Parameters

indexGLuint

Attribute location.

divisorGLuint

0 = per vertex (default). N = advance once every N instances.

Tips & pitfalls

  • A mat4 attribute occupies 4 consecutive locations; set the divisor on all four.

Errors

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

GL_INVALID_VALUE
index ≥ GL_MAX_VERTEX_ATTRIBS.

Example

example.cpp
1// mat4 instance matrix at locations 3..6
2for (int i = 0; i < 4; ++i) {
3    glEnableVertexAttribArray(3 + i);
4    glVertexAttribPointer(3 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4),
5                          (void*)(i * sizeof(glm::vec4)));
6    glVertexAttribDivisor(3 + i, 1);
7}
8glDrawElementsInstanced(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0, amount);
Official Khronos documentation