glGetUniformLocation
Looks up the location (slot number) of a uniform variable by its GLSL name.
Part of the family glGet*
Signature
GLint glGetUniformLocation(GLuint program, const GLchar *name);
How it works
Uniforms are values that stay the same for a whole draw call — matrices, colors, time. To set one you need its location, an integer assigned by the linker. This function asks for it by name.
Locations do not change until the program is re-linked, so look them up once and cache them instead of calling this every frame.
Parameters
A linked program.
Exact uniform name. Struct members and array elements use GLSL syntax: "light.color", "lights[2].position".
Return value
The location, or -1 if no ACTIVE uniform has that name.
Tips & pitfalls
-1 does not always mean a typo: the compiler removes uniforms that do not affect the output. An unused uniform returns -1 too.
With GLSL 4.30+ you can fix locations in the shader with layout(location = N) and skip the lookup.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GL_INVALID_OPERATION
- program has not been linked successfully.
Example
1// once, after linking
2GLint uModel = glGetUniformLocation(program, "model");
3
4// every frame
5glUseProgram(program);
6glUniformMatrix4fv(uModel, 1, GL_FALSE, glm::value_ptr(model));