Uniform (GLSL)

From OpenGL.org
Jump to: navigation, search

A uniform is a global GLSL variable declared with the "uniform" storage qualifier. These act as parameters that the user of a shader program can pass to that program. They are stored in a program object.

Uniforms are so named because they do not change from one execution of a shader program to the next within a particular rendering call. This makes them unlike shader stage inputs and outputs, which are often different for each invocation of a program stage.

GLSL definition and behavior

Uniform variables must be defined in GLSL at global scope.

Uniforms can be of any type, or any aggregation of types. The following is all legal GLSL code:

struct TheStruct
{
  vec3 first;
  vec4 second;
  mat4x3 third;
};
 
uniform vec3 oneUniform;
uniform TheStruct aUniformOfArrayType;
uniform mat4 matrixArrayUniform[25];
uniform TheStruct uniformArrayOfStructs[10];

Uniforms are implicitly constant, within the shader. Attempting to change them with shader code will result in a compiler error. Similarly, you cannot pass a uniform as an out or inout parameter to a function.

Uniforms are intended to be set by the user. However, you can initialize them to a default value using standard GLSL initalizer syntax:

uniform vec3 initialUniform = vec3(1.0, 0.0, 0.0);

This will cause the uniform to have this vector as its value until the user changes it.

Driver bug note: Some drivers do not implement uniform initializers correctly.

Explicit uniform location

Explicit Uniform Location
Core in version 4.4
Core since version 4.3
Core ARB extension ARB_explicit_uniform_location
V · E

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.

Active uniforms

GLSL compilers and linkers try to be as efficient as possible. Therefore, they do their best to eliminate code that does not affect the stage outputs. Because of this, a uniform defined in a shader file does not have to be made available in the linked program. It is only available if that uniform is used by code that affects the stage output, and that the uniform itself can change the output of the stage.

Therefore, a uniform that is exposed by a fully linked program is called an "active" uniform; any other uniform specified by the original shaders is inactive. Inactive uniforms cannot be used to do anything in a program.

Implementation limits

The number of active uniforms available is bound by a set of limits. Each shader stage has a limit on the number of available uniforms. The per-stage limits are the constants GL_MAX_VERTEX_UNIFORM_COMPONENTS​, GL_MAX_GEOMETRY_UNIFORM_COMPONENTS​, and GL_MAX_FRAGMENT_UNIFORM_COMPONENTS​ (also GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS​ and GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS​ if GL 4.0/ARB_tessellation_shader). You can query these limits with glGetIntegerv, but they are all quite generous—at least 1024 in OpenGL 3.0+.

The limit refers to the quantity of space for individual floats, integers, or booleans. A vec3​ is expected to take up 3 components. Matrix types will take up no more than 4 * the smallest count of rows/columns. Thus, a mat2x3​ will not take up any more than 8 components and may take up less. Arrays of these will take up the array size * that number of components. Double-precision values (from GL 4.0/ARB_gpu_shader_fp64) will take up 2x the space of single-precision equivalents.

Implementation note: OpenGL implementations are allowed to reject shaders for implementation-dependent reasons. So you can have fewer active uniform components by your reckoning and still fail to link due to uniform limits. This is usually on hardware that is innately vector hardware. Pre-GeForce 8xxx hardware, and all ATi hardware does this. In this case, you should assume that each separate uniform takes up 4 components, much like it would in D3D. That means a "uniform float" is 4 components, a mat2x4 is 16 components (each row is 4 components), but a mat4x2 is 8 components.

ATI/AMD note: The ATI max component values are wrong. To get the actual number of components, you must divide the result from GL_MAX_*_UNIFORM_COMPONENTS​ by 4.

Do recall that these limits are for active uniforms only. Uniforms that are deemed inactive are not relevant to this limit.

The maximum number of uniform locations that can be explicitly assigned in a program is defined by GL_MAX_UNIFORM_LOCATIONS​. This limits the numbers you can use when giving uniforms explicit locations.

Uniform management

Like regular OpenGL Objects, program objects encapsulate certain state. In this case, this state is a set of uniforms that will be used when rendering with that program. All of the stages within a program object use the same set of uniforms. Thus, if you have a uniform named "projectionMatrix" defined as a mat4 in both the vertex and the fragment stages, then there will be only one uniform of that name exposed by the program object. Changing this uniform will affect both the vertex and fragment stages.

Therefore, it is a program linker error to have a uniform in a vertex and fragment shader that uses the same name, but has a different type in each shader.

Each active uniform has a location. The location is a numeric handle to that uniform; it functions as a shorthand that is faster to search for than the uniform's name. Uniform locations are unique to a specific program. If you do not explicitly assign a uniform to a location (via the OpenGL 4.3/ARB_explicit_uniform_location feature mentioned above), then OpenGL will assign them arbitrarily. In this case, even if you define the exact same set of uniforms in two different programs, OpenGL does not guarantee that the same uniforms in the two programs will have the same location. So if you do not explicitly define the locations for uniforms, you must keep track of them individually for each program.

If you have a uniform name, you can get the uniform location via this function:

 GLint glGetUniformLocation(GLuint program​, const char *name​);

The program​ is the program object name that you want to find a uniform for. This must be a program that has successfully linked. And name​ is the name of the uniform you wish to search for. The return value is -1 if name​ isn't an active uniform in the program, name​ is the name of a uniform block (see below), or program​ isn't a successfully linked program. Otherwise, the return value is the uniform's location.

The name​ of the uniform does not have to be a simple name. If you want to use a struct of uniforms, each individual field in the struct has a separate location. For example, take this GLSL uniform definition:

struct MyStruct
{
  vec2 firstField;
  vec4 secondField;
  mat2 thirdField;
};
 
uniform MyStruct mainUniform;

The name "mainUniform" does not have a location; calling glGetUniformLocation on it will return -1. However, each of mainUniform's fields do have a location. So you can call glGetUniformLocation(program, "mainUniform.secondField");​ just fine.

When explicitly defining the location of a struct uniform, the first member of the struct (recursively, until it finds a non-struct type) gets that uniform location. OpenGL then gives every following member sequentially larger uniform locations.

Arrays are handled simply. Take this GLSL uniform definition:

uniform vec3 positions[20];

Each individual element in the uniform array has a location. The names of them are "positions[2]", "positions[3]", etc. However, the uniform location for "positions" and "positions[0]" are the same; they point to the first element of the array.

If you use the array uniform upload functions on an array location, then the referenced location and those following it will be updated.

In a similar way as to structs, explicitly-located array uniforms are given sequential location values. "position[0]" will be the explicit location, while "position[3]" will be 3 larger than this value.

Arrays of structures are special. Take this as an example:

uniform MyStruct manyStructs[3];

Struct uniforms, as mentioned above, do not have a location. Therefore, each entry in the array does not have a location; manyStructs[0]​ will return -1. Each struct field of each array element has its own uniform location. So you will need to set manyStructs[0].firstField​ and anyStructs[1].firstField​ separately.

If, and only if, an array of structs is given an explicit location (core GL 4.3 or ARB_explicit_uniform_location), then the rules work more or less as expected. For example:

layout(location = 5) uniform MyStruct manyStructs[3];

manyStructs[0].firstField​ will have the location 5. manyStructs[0].thirdField​ will have the location 7. manyStructs[2].secondField​ will have the location (2*3 [array] + 1 [struct offset] + 5 [base location]), or 12. And so forth. Note again that this is only true for explicit uniform locations.

Structs that contain arrays work similarly.

Changing uniform values

The purpose of getting the uniform location is to change the uniform's value. This is done with a large set of functions of the form glUniform*, where * defines the type of value to upload. These can upload matrices, vectors, individual values, and arrays of each of these.

However, in order to change a uniform value, you must first bind the program to the context with glUseProgram. The glUniform* functions do not take a program object name; they use the currently bound program. If you are using GL 4.1+, or ARB_separate_shader_objects, you may use the glProgramUniform* functions to set uniforms directly on a program.

Uniform blocks and buffers

It is often useful to store a set of uniforms in storage that is separate from the program object. This can allow for fast switching between sets of uniforms, as well as having multiple programs share uniform data. This is done by using GLSL uniform blocks and creating Buffer Objects for storing that data. Collectively, this concept is called Uniform Buffer Objects.

Samplers cannot be part of uniform blocks.

Accessing uniform information

Information about uniforms, whether global or within interface blocks, can be queried via the introspection API.