Uniform (GLSL)

From OpenGL Wiki
Revision as of 18:43, 25 April 2019 by Alfonse (talk | contribs) (Some wording cleanup.)
Jump to navigation Jump to search

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

Uniforms are so named because they do not change from one shader invocation 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 shader 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 are 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 (though they are not Constant Expressions). 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 from OpenGL, rather than within the shader. 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.

Platform Issue (Unknown): Some drivers do not implement uniform initializers correctly.

Explicit uniform location

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

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.

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 OpenGL 4.0 or ARB_tessellation_shader, and GL_MAX_COMPUTE_UNIFORM_COMPONENTS if OpenGL 4.3 or ARB_compute_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.

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 or 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 Program Introspection. The naming convention for variables allows you to get the uniform location of an array (of basic types) as a whole, as well as elements within the array or the elements of structures.

For arrays of Basic Types, the location of each element in the array will be the location of the array + the array index. However, for structs (or arrays of structs), if the locations were not explicitly specified then the location of any particular element will have no relation to any other element. So you cannot count on the next element being one location index higher than the previous. This is true even for arrays of structs.

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 OpenGL 4.1 or ARB_separate_shader_objects, you may use the glProgramUniform* functions to set uniforms directly on a program, without having to bind the program first.

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 declaring a group of uniforms to be in an Interface Block, then using storage in a Buffer Object to store those uniforms. Collectively, this concept is called Uniform Buffer Objects.

Opaque types like 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.