Uniform (GLSL)/Explicit Uniform Location

From OpenGL Wiki
Jump to: navigation, search

Uniforms defined outside of Interface Blocks have a location. This location can be directly assigned in the shader, using this syntax:

layout(location = 2) uniform mat4 modelToWorldMatrix;

Calling glGetUniformLocation(prog, "modelToWorldMatrix") is guaranteed to return 2. It is illegal to assign the same uniform location to two uniforms in the same shader or the same program. Even if those two uniforms have the same name and type, and are defined in different shader stages, it is not legal to explicitly assign them the same uniform location; a linker error will occur.

All non-array/struct types will be assigned a single location. Arrays and structs will be assigned sequentially increasing locations, starting with the given location. Given this:

layout(location = 2) uniform mat4 some_mats[10];

some_mats will be assigned all of the uniform locations on the half-open range [2, 12). This will apply for nested types. Consider the following:

struct Thingy
  vec4 an_array[3];
  int foo;
layout(location = 2) uniform Thingy some_thingies[6];

Each Thingy takes up 4 uniform locations; the first three going to an_array and the fourth going to foo. Thus, some_thingies takes up 24 uniform locations.

Uploading arrays of uniforms with one of the glUniform*v functions will work. For example, uniform location 2 represents the array `some_thingies[0].an_array`. As such, you can upload an array of vec4s to this array with glUniform4fv(2, 3, ...);.

No two uniform declarations in a program can be explicitly assigned the same location. This means that explicit uniform location ranges cannot overlap. So this is illegal:

layout(location = 2) uniform mat4 some_mats[10];
layout(location = 6) uniform vec4 some_vecs[4];
Warning: This rule also means that two uniforms in different Shader stages that are linked together cannot share the same explicit uniform location. Even if their declarations are identical, it is a linker error to link two such shaders into the same program. So it is not possible for an explicitly-assigned uniform location to refer to a uniform in both the vertex and fragment shaders, for example.

The maximum number of available locations within a single program is GL_MAX_UNIFORM_LOCATIONS, which will be at least 1024 locations. You may not use a uniform location outside of the range [0, GL_MAX_UNIFORM_LOCATIONS), nor may the sequential assignment of uniform locations due to array/struct aggregation go outside of this range.