Saturday, December 29, 2007

Default Uniform Values

In GLSL 1.10 all uniforms are assigned a default value of 0 when a program is successfully linked.  In GLSL 1.20 all uniforms, except for samplers, can have an initializer, like so:

uniform vec3 color = vec3(0.7, 0.7, 0.2);

All uniforms without initializers are assigned a default value of 0.

References:
GLSL 1.20 specification, p. 24

Thursday, December 27, 2007

Active Shader Uniforms and Vertex Attributes

A uniform is only active if the GLSL compiler and/or linker determine that it is used in the shader, or cannot conclusively determine that it is not used in the shader.  As an example, in the following shader pair foo, rex, and gl_LightModel.ambient are the only active uniforms.

[vertex]
uniform vec4 foo, bar, baz, rex;
varying vec4 var;
void main()
{
   var = rex;
   gl_Position = foo;
}

[fragment]
uniform vec4 color, size, rex, throwaway;
varying vec4 var;
void main()
{
   gl_FragColor = (rex + var) * gl_LightModel.ambient;
}

In this more complex example posMod and baz are the only active uniforms.

[vertex]
uniform vec4 v_color, posMod, foo, bar;
varying vec4 colMod;
void main()
{
  colMod = v_color * gl_Vertex;
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex + posMod;
}

[fragment]
uniform vec4 f_color, rex, baz;
varying vec4 colMod;
void main()
{
   vec4 finalColor = f_color * colMod;
   finalColor += rex;
   gl_FragColor = baz;
}

Even though v_color, f_color, and rex are all used in the code as written they do not have any affect on the final vertex position or fragment color.  As such, a good GLSL compiler/linker will determine that they are unused.

Vertex attributes have similar rules.  In order to be considered active they must in some way affect the final vertex position or fragment color.

This differentiation between active and inactive can be important, especially if you are dealing with procedurally generated shaders.  Only active uniforms and attributes count towards implementation defined limits.  That is, if your implementation has a limit of 16 vertex attributes you can still declare more than 16 as long as 16 or fewer actually affect the final vertex position or fragment color.

References:
OpenGL 2.1 Specification (12/01/2006) pp. 76-79