Part IA Michaelmas Term
Fragment Shader
Purpose
The fragment shader computes the final colour for each pixel candidate:
- Called once per fragment generated by rasterisation
- Computes colour, depth, and other per-pixel values
- Handles texturing, lighting, and procedural effects
Inputs
| Input | Source |
|---|---|
| Interpolated attributes | Vertex shader outputs |
| Uniforms | Global parameters (matrices, lights) |
| Textures | Image data sampled by UV coordinates |
Outputs
gl_FragColororout vec4 colour: Final pixel colour- Optionally: modified depth value
Example GLSL: Simple Lighting
#version 330
in vec3 frag_normal;
uniform vec3 light_dir;
out vec4 frag_colour;
void main() {
float intensity = max(dot(normalize(frag_normal),
normalize(light_dir)), 0.0);
frag_colour = vec4(vec3(intensity), 1.0);
}
Procedural Shading: Checkerboard Shader
A checkerboard shader demonstrates procedural texturing—computing patterns mathematically without image textures:
#version 330
in vec2 tex_uv;
out vec4 frag_colour;
void main() {
const float scale = 10.0;
vec2 tiled = floor(tex_uv * scale);
float checker = mod(tiled.x + tiled.y, 2.0);
vec3 col = (checker < 1.0) ? vec3(1.0, 1.0, 0.0) : vec3(0.0, 0.0, 0.0);
frag_colour = vec4(col, 1.0);
}
How It Works
floor(tex_uv * scale): Discretise UV into grid cellsmod(tiled.x + tiled.y, 2.0): Alternate between 0 and 1- Ternary operator: Assign colours based on cell parity
Fragment vs Pixel
- Fragment: A sample generated by rasterisation, may be discarded
- Pixel: Final written value after all tests pass (depth, stencil)
Common Fragment Shader Operations
| Operation | Description |
|---|---|
| Texture lookup | Sample from texture using UV |
| Lighting | Compute diffuse, specular contributions |
| Blending | Combine with existing framebuffer colour |
| Discarding | Conditionally reject fragments |
Summary
- Fragment shader computes final colours for each pixel
- Receives interpolated attributes from vertex shader
- Can perform procedural shading without textures
- Outputs colour that may be written to framebuffer
Past Paper Questions
2025 Paper 3 Question 4(b)(ii): Give 4 examples of uniform variables. [2 marks]
2024 Paper 3 Question 4: Write a fragment shader that samples a texture and applies basic lighting.
2022 Paper 3 Question 4(b): Write a GLSL fragment shader that produces a yellow and black checkerboard pattern using texture coordinates.