Clockworkcoders Tutorials

Uniform Variables

Tutorial Screenshot


Uniform variables are used to communicate with your vertex or fragment shader from "outside". In your shader you use the uniform qualifier to declare the variable:

uniform float myVariable;
Vertex of Fragment Shader Source Code

Uniform variables are read-only and have the same value among all processed vertices. You can only change them within your C++ program.


uniform float Scale;
void main(void)  
   vec4 a = gl_Vertex;     
   a.x = a.x * Scale;     
   a.y = a.y * Scale;     
   gl_Position = gl_ModelViewProjectionMatrix * a;  
Vertex Shader Source Code


uniform vec4 uColor;
void main (void) 
   gl_FragColor = uColor; 
Fragment Shader Source Code

In this example the vertex shader scales every incoming vertex with a value spcified in a uniform variable. In the fragment shader a uniform vector value is used as the output color.

Changing the Uniform Value in C++

Access to uniform variables is available after linking the program. With glGetUniformLocation you can retrieve the location of the uniform variable within the specified program object. Once you have that location you can set the value. If the variable is not found, -1 is returned. With glUniform you can set the value of the uniform variable.

GLint loc = glGetUniformLocation(ProgramObject, "Scale");
if (loc != -1)
   glUniform1f(loc, 0.432);
C++ Source Code

The uniform location remains valid until you link the program again, so there is no need to call glGetUniformLocation every frame.

Example Project

In this example project the above example shaders are used and the vertex position and color value is changed with a timer function.

Download: (Visual Studio 8 Project)
(If you create a project/makefile for a different platform/compiler, please send it to: christen(at) and I will put it here.)


Return to Index

(c) 2007 by Martin Christen