Part IA Michaelmas Term
GLSL Basics
What is GLSL?
GLSL (OpenGL Shading Language) is a C-like language for writing shaders:
- Runs on the GPU
- Supports vector and matrix operations natively
- Hardware-optimised for graphics computations
Data Types
Scalar Types
| Type | Description |
|---|---|
float | Single-precision float |
double | Double-precision float |
int | Signed integer |
uint | Unsigned integer |
bool | Boolean |
Vector Types
| Type | Description |
|---|---|
vec2, vec3, vec4 | Float vectors |
ivec2, ivec3, ivec4 | Integer vectors |
dvec2, dvec3, dvec4 | Double vectors |
Matrix Types
| Type | Description |
|---|---|
mat2 | 2×2 float matrix |
mat3 | 3×3 float matrix |
mat4 | 4×4 float matrix |
Swizzling
Access and rearrange vector components using .xyzw, .rgba, or .stpq:
vec4 colour = vec4(1.0, 0.5, 0.0, 1.0);
vec3 rgb = colour.rgb; // (1.0, 0.5, 0.0)
vec3 gbr = colour.gbr; // (0.5, 1.0, 0.0)
vec2 rg = colour.xy; // (1.0, 0.5)
Swizzling can also set values:
vec4 result = vec4(0.0);
result.rgb = vec3(1.0, 0.5, 0.25);
Storage Qualifiers
| Qualifier | Purpose |
|---|---|
in | Input to shader (vertex attributes or interpolated) |
out | Output from shader |
uniform | Global parameter, constant per draw call |
const | Compile-time constant |
buffer | GPU memory buffer (read/write) |
Vertex Attributes vs Uniforms
Vertex Attributes
- Different for each vertex
- Stored in VBOs
- Interpolated across triangles
- Examples: position, normal, texture coordinates
Uniforms
- Same value for all vertices/fragments in a draw call
- Set once per object or frame
- Examples: transformation matrices, light parameters, material properties
uniform mat4 mvp_matrix;
uniform vec3 light_position;
uniform vec3 material_colour;
Built-in Functions
Mathematical
float x = abs(v); // Absolute value
float y = sqrt(v); // Square root
float z = pow(v, n); // Power
float w = sin(theta); // Trigonometric functions
Vector Operations
float len = length(v); // Vector magnitude
float d = distance(a, b); // Distance between points
float dp = dot(a, b); // Dot product
vec3 cp = cross(a, b); // Cross product
vec3 n = normalize(v); // Unit vector
Interpolation
vec3 result = mix(a, b, t); // Linear interpolation: a*(1-t) + b*t
vec3 s = smoothstep(a, b, x); // Hermite interpolation
Shader Version
Specify GLSL version at the top of each shader:
#version 330 // OpenGL 3.3
#version 450 // OpenGL 4.5
Summary
- GLSL provides vector and matrix types with hardware support
- Swizzling enables flexible component access
uniformfor global data,in/outfor per-vertex/per-fragment data- Built-in functions for common graphics operations
Past Paper Questions
2025 Paper 3 Question 4(b)(iii): Explain the main difference between uniform variables and vertex attributes. [2 marks]
2024 Paper 3 Question 4: Write GLSL declarations for a vertex shader that receives position and normal attributes, and applies an MVP matrix uniform.
2023 Paper 3 Question 4: What is swizzling in GLSL? Give an example.