Uniform (GLSL)/Explicit Uniform Location

From OpenGL.org
< Uniform (GLSL)
Revision as of 22:33, 15 August 2013 by Alfonse (talk | contribs) (Minimum number of uniform locations.)

Jump to: navigation, search

Uniforms defined outside of interface block 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"); with 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 in different shader stages, it is not allowed and will result in a linker error.

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, 10). 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 vec4​s to this array with glUniform4fv(2, 3, ...);.

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];

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 this range, nor may the sequential assignment of uniform locations due to array/struct aggregation go outside of this range.