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, ...);.

If two uniforms in a program are given the same explicit location, then they refer to the same uniform. This means they must also match in variable name, type, array-index, qualifiers, etc. The following would be illegal:

layout(location = 2) uniform mat4 some_mats[10];
layout(location = 6) uniform vec4 some_vecs[4];

some_mats takes up 10 uniform locations, from [2, 12). But since some_vecs starts at uniform location 6, it would have the same location as some_mats[4]. But it wouldn't have the same name, or same type, or other characteristics. Even if some_vecs was a mat4, it would not be the same, since they don't have the same name or same array index.

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.