Skip to content
Back to Modules
Part IA Michaelmas Term

Introduction to Graphics

Graphics Mathematics C++ GLSL Part IA Michaelmas Term
  • Foundations

    Visual computing pipeline, digital images, memory layout, sampling, and pixel formats

    • Visual Computing Pipeline

      Overview

      The course is structured around the Visual Computing Pipeline, which describes how visual information flows between the physical world, computers, and human observers:

      The Visual Computing Pipeline showing Scene, Digital Image, Display Light, and Human Perception

      Pipeline Stages

      1. Scene Description

      The mathematical model of the 3D scene:

      • Geometry (objects, shapes, surfaces)
      • Materials (surface properties, textures)
      • Lighting (light sources, intensities)
      • Camera (viewpoint, projection)

      2. Computer Graphics (Rendering)

      The process of generating a digital image from the 3D scene description:

      • Input: Scene description
      • Output: 2D array of pixel values
      • Methods: Ray tracing, rasterisation

      3. Image Display

      Converting the digital image in memory into physical light output:

      • Monitor (CRT, LCD, OLED)
      • Projector
      • Print

      4. Visual Perception

      How the human eye and brain capture and process the displayed light to perceive the scene:

      • Photoreceptor response
      • Neural processing
      • Cognitive interpretation

      5. Image Analysis and Computer Vision

      The inverse of rendering: extracting a 3D scene description or understanding from digital images:

      • Object recognition
      • Depth estimation
      • Scene understanding

      Forward vs Inverse Problems

      Forward (Graphics): Scene → Image

      • Well-defined mathematical process
      • Rendering algorithms solve this

      Inverse (Vision): Image → Scene

      • Ill-posed problem
      • Multiple scenes can produce the same image

      Summary

      • The visual computing pipeline describes the flow from scene to perception
      • Computer graphics solves the forward problem (scene to image)
      • Computer vision solves the inverse problem (image to understanding)
      • Understanding the whole pipeline helps design better rendering algorithms
    • Digital Images and Pixels

      What is a Digital Image?

      A digital image can be understood from two perspectives:

      • Computing perspective: A 2D array of pixels stored in memory
      • Mathematical perspective: A 2D function I(x,y)I(x, y) giving intensity at any coordinate

      The Pixel

      A pixel (Picture Element) is:

      • In computing: A triple of values for red, green, and blue channels, typically stored as bytes (0-255)
      • In mathematics: A point sample with no dimension or area

      Important: A pixel is not a box, disk, or tiny light. It is a sample point.

      Comparison showing pixels as points vs the common misconception of pixels as squares

      Why This Matters

      A pixel as a point sample means:

      • No inherent size or shape
      • Represents the value at an exact location
      • Can be resampled to any output resolution

      Image as a 2D Function

      Mathematically, an image can be viewed as: I:R2R3I: \mathbb{R}^2 \rightarrow \mathbb{R}^3

      mapping spatial coordinates (x,y)(x, y) to a colour vector (r,g,b)(r, g, b).

      For greyscale: I:R2RI: \mathbb{R}^2 \rightarrow \mathbb{R}

      mapping to a single intensity value.

      Resolution

      Spatial resolution: The number of pixels in each dimension (width × height).

      Example: A 1920 × 1080 image has 2,073,600 pixels.

      Summary

      • A digital image is a 2D array of pixel samples
      • Pixels are point samples with no area, not little squares
      • Images can be viewed mathematically as 2D functions
      • Resolution determines the sampling density

      Past Paper Questions

      2024 Paper 3 Question 4: Explain why a pixel should be considered a point sample rather than a small square. What implications does this have for image processing operations?

    • Image Memory Layout

      Storing Images in Memory

      A 2D image array must be stored in linear (1D) memory. The mapping from 2D coordinates to 1D memory index uses strides.

      Row-Major vs Column-Major Order

      Row-Major Order (Most Common)

      Elements in the same row are stored contiguously: i(x,y)=x+yncolsi(x, y) = x + y \cdot n_{\text{cols}}

      Column-Major Order

      Elements in the same column are stored contiguously: i(x,y)=xnrows+yi(x, y) = x \cdot n_{\text{rows}} + y

      Interleaved Colour Storage

      For colour images with 3 channels (RGB), interleaved row-major: i(x,y,c)=x3+y3ncols+ci(x, y, c) = x \cdot 3 + y \cdot 3 \cdot n_{\text{cols}} + c

      where c{0,1,2}c \in \{0, 1, 2\} for the R, G, B channels.

      Memory layout showing row-major interleaved RGB storage

      General Stride Formula

      The most general formula for any memory layout: i(x,y,c)=istart+xsx+ysy+csci(x, y, c) = i_{\text{start}} + x \cdot s_x + y \cdot s_y + c \cdot s_c

      where:

      • istarti_{\text{start}} is the starting offset
      • sxs_x, sys_y, scs_c are the strides for each dimension

      Common Stride Configurations

      Layoutsxs_xsys_yscs_c
      Row-major, grayscale1nn-
      Column-major, grayscalemm1-
      Row-major, interleaved RGB33n3n1
      Row-major, planar RGB1nnnmnm

      Padded Images

      Sometimes images are padded with extra pixels for operations that need neighbourhood access (e.g., convolution).

      The stride sys_y is larger than the image width to account for padding.

      Regions of Interest (ROI)

      A region of interest is a rectangular subset of an image. An ROI borrows the parent’s data array without copying:

      • istarti_{\text{start}} = offset to ROI origin
      • Strides are inherited from parent

      Padded image showing allocated memory, actual image, and ROI

      Summary

      • Row-major order stores rows contiguously; column-major stores columns contiguously
      • Strides define the step size for each dimension
      • Interleaved RGB alternates channels; planar separates them
      • ROIs share parent memory without copying

      Past Paper Questions

      2023 Paper 3 Question 4: Design an ExImage class that supports ROIs. What constructor parameters are needed?

    • Sampling and Quantisation

      Continuous to Discrete

      The physical world is continuous, but computers work with discrete values. Two processes convert between them:

      Original continuous signal, sampled signal, and quantised signal

      Sampling

      Sampling maps a continuous function to a discrete one:

      • Spatial coordinates: continuous → discrete pixel positions
      • A continuous image I(x,y)I(x, y) becomes samples I[i,j]I[i, j]

      Sampling an Image

      Isampled[i,j]=I(xi,yj)I_{\text{sampled}}[i,j] = I(x_i, y_j)

      where (xi,yj)(x_i, y_j) are the discrete sample positions on a rectangular grid.

      Sampling Rate

      The sampling rate (or spatial frequency) determines how densely the continuous signal is sampled:

      • Higher rate: more samples, better representation of detail
      • Lower rate: fewer samples, risk of aliasing

      Quantisation

      Quantisation maps continuous values to discrete ones:

      • Intensity values: continuous → discrete levels
      • Each colour channel typically quantised to 8 bits (256 levels)

      Quantisation Levels

      For bb bits per channel, there are 2b2^b discrete levels:

      • 8 bits: 256 levels (0-255)
      • 10 bits: 1024 levels
      • 12 bits: 4096 levels

      Relationship Between Sampling and Quantisation

      ProcessDomainEffect
      SamplingSpatialDetermines spatial resolution
      QuantisationIntensityDetermines tonal resolution

      Both contribute to image quality and file size.

      Summary

      • Sampling discretises spatial coordinates
      • Quantisation discretises intensity values
      • Higher sampling rate captures more detail
      • More quantisation levels capture smoother gradients

      Past Paper Questions

      2023 Paper 3 Question 3: What is meant by “sampling an image”? How does it differ from quantisation?

    • Pixel Formats and Bit Depth

      Pixel Formats

      Common pixel formats determine how colour information is stored:

      FormatBits per PixelNumber of Colours
      Greyscale8 bits (1 byte)256
      Highcolour16 bits (2 bytes)65,536
      Truecolour24 bits (3 bytes)16.7 million
      Deepcolour≥32 bits (4+ bytes)Billions+

      Why Bit Depth Matters

      Storage Requirements

      Each colour channel typically uses 8 bits (values 0-255). A 5-megapixel uncompressed truecolour image requires: 5×106×3=15 MB5 \times 10^6 \times 3 = 15 \text{ MB}

      Why 8 Bits Suffice

      Gamma encoding makes the 8-bit scale perceptually uniform. Without gamma:

      • Perceptible banding in smooth gradients
      • At least 12 bits per channel needed

      Colour Banding

      When there are insufficient bits to represent smooth colour gradients, banding artefacts appear.

      Causes

      • Limited bit depth
      • Dark regions where gamma encoding compresses values
      • Smooth gradients across large areas

      Visual Illusions That Exacerbate Banding

      Mach band illusion: The visual system exaggerates perceived intensity differences at edges, making band steps more visible.

      Chevreul illusion: Similar edge enhancement effect.

      Solutions

      • Dithering: Add controlled noise to break up visible bands
      • Higher bit depth: 10-bit or 12-bit encoding
      • Avoid smooth gradients in design where possible

      Colour banding example showing smooth gradient vs banded gradient with Mach bands

      Deep Colour

      For HDR content and professional workflows:

      • 10-bit: 1024 levels per channel (used in HDR video)
      • 12-bit: 4096 levels per channel
      • 16-bit float: Per-channel floating-point precision

      Summary

      • Truecolour (24-bit) is standard for most applications
      • 8 bits per channel suffices because gamma encoding makes it perceptually uniform
      • Insufficient bit depth causes visible banding
      • Dithering can reduce visible banding artefacts
  • Ray Tracing

    Pinhole camera, ray tracing algorithm, intersections, shadow rays, and anti-aliasing

    • Pinhole Camera Model

      The Pinhole Camera

      Ray tracing is based on the pinhole camera model, where:

      • Light passes through a single point (the pinhole/aperture)
      • An image is formed on the image plane behind the pinhole
      • Each point on the image corresponds to a unique ray from the scene

      Pinhole camera model showing eye point, screen plane, and rays through pixels

      In Ray Tracing

      In the computational model:

      • The camera origin (eye point) corresponds to the pinhole aperture
      • The screen plane (image plane) is where the image is formed
      • Rays are traced from the eye through each pixel into the scene

      Pinhole Camera Properties

      • No depth of field: All distances are equally sharp (infinite depth of field)
      • Perfect focus: No lens effects
      • Point aperture: All rays diverge from a single point

      Finite Aperture Camera

      A real camera with a finite aperture (lens):

      • Distributes rays over a lens disc
      • Produces blur for out-of-focus objects (depth of field)
      • Objects at the focus distance appear sharp

      Summary

      • The pinhole camera is the fundamental model for ray tracing
      • The camera origin corresponds to the pinhole aperture
      • All rays originate from a single point through the image plane
      • Finite aperture cameras model depth of field effects

      Past Paper Questions

      2025 Paper 3 Question 3(a): Explain what a pinhole camera model is and what the camera origin in ray tracing corresponds to in the pinhole model. [2 marks]

    • Ray Tracing Algorithm

      Basic Algorithm

      The ray tracing algorithm traces rays from the eye through each pixel:

      select an eye point and a screen plane
      FOR every pixel in the screen plane
          determine the ray from the eye through the pixel's centre
          FOR each object in the scene
              IF the object is intersected by the ray
                  IF the intersection is the closest (so far) to the eye
                      record intersection point and object
                  END IF
              END IF
          END FOR
          calculate colour for the closest intersection point (if any)
      END FOR

      Time Complexity

      Standard RGB Rendering

      Assuming:

      • npn_p pixels in the image
      • non_o objects in the scene
      • nln_l light sources (Phong shading, no recursion)

      Time complexity: O(npnonl)O(n_p \cdot n_o \cdot n_l)

      Breakdown:

      • O(npno)O(n_p \cdot n_o) for finding ray-object intersections
      • O(nl)O(n_l) per intersection to compute shading (3 channels RGB)

      Spectral Rendering (2025 Paper 3 Question 3(f))

      To compute physically realistic colour, we simulate the full visible spectrum instead of just RGB:

      • Divide the visible spectrum (380-730 nm) into nλn_\lambda discrete wavelength bins
      • For each pixel, trace rays as usual but evaluate illumination at every wavelength

      Time complexity: O(npnonlnλ)O(n_p \cdot n_o \cdot n_l \cdot n_\lambda)

      The factor of nλn_\lambda replaces the constant 3 (RGB channels).

      The Outer Loop

      The pixel loop is the outermost loop:

      • Each pixel produces one ray (or multiple for anti-aliasing)
      • The intersection test loops over all objects
      • The shading calculation loops over all lights

      Optimisation Techniques

      • Spatial data structures: BVH, octrees reduce intersection tests from O(no)O(n_o) to O(logno)O(\log n_o)
      • Early termination: Whitted-style recursion bounds
      • Parallel processing: Pixels are independent, ideal for GPU

      Summary

      • Ray tracing traces one ray per pixel (or more for anti-aliasing)
      • Time complexity is O(npnonl)O(n_p \cdot n_o \cdot n_l) for basic Phong shading
      • Spectral rendering adds a factor of nλn_\lambda for wavelength sampling
      • Spatial data structures can dramatically improve performance

      Past Paper Questions

      2025 Paper 3 Question 3(b): Assuming a Phong shading model and no recursion, what is the time complexity of a ray tracing algorithm and why? [5 marks]

      2025 Paper 3 Question 3(f): How would you compute an approximate full spectrum of colours instead of RGB values for each pixel? What is the time complexity? [4 marks]

    • Ray Equation

      Ray Representation

      A ray is represented parametrically as: P(s)=O+sD,s0\mathbf{P}(s) = \mathbf{O} + s\mathbf{D}, \quad s \geq 0

      where:

      • O\mathbf{O} is the ray origin (starting point)
      • D\mathbf{D} is the direction vector (typically normalised)
      • ss is the parameter measuring distance along the ray

      Properties

      • For s=0s = 0: P(0)=O\mathbf{P}(0) = \mathbf{O} (origin)
      • For s>0s > 0: Points along the ray in direction D\mathbf{D}
      • Negative ss values are invalid (behind the origin)

      Constructing Rays from Camera

      For a pixel at screen coordinates (x,y)(x, y):

      1. Compute the world-space position of the pixel on the image plane
      2. Direction: D=PpixelOcameraPpixelOcamera\mathbf{D} = \frac{\mathbf{P}_{\text{pixel}} - \mathbf{O}_{\text{camera}}}{|\mathbf{P}_{\text{pixel}} - \mathbf{O}_{\text{camera}}|}

      Why Parametric?

      The parametric form is ideal for intersection testing:

      • Substitute P(s)\mathbf{P}(s) into the surface equation
      • Solve for ss (the distance to intersection)
      • IF s0s \geq 0, the intersection is in front of the ray origin

      Summary

      • A ray is defined by origin O\mathbf{O} and direction D\mathbf{D}
      • The parameter ss gives distance along the ray
      • Parametric form enables algebraic intersection calculations
    • Ray-Object Intersections

      Intersection Testing

      Finding where a ray hits geometric objects is fundamental to ray tracing.

      Ray-Sphere Intersection

      Given:

      • Ray: P(s)=O+sD\mathbf{P}(s) = \mathbf{O} + s\mathbf{D}
      • Sphere: (PC)(PC)=r2(\mathbf{P} - \mathbf{C}) \cdot (\mathbf{P} - \mathbf{C}) = r^2

      Substituting the ray equation: (O+sDC)(O+sDC)=r2(\mathbf{O} + s\mathbf{D} - \mathbf{C}) \cdot (\mathbf{O} + s\mathbf{D} - \mathbf{C}) = r^2

      This is a quadratic in ss: as2+bs+c=0as^2 + bs + c = 0

      where:

      • a=DDa = \mathbf{D} \cdot \mathbf{D}
      • b=2D(OC)b = 2\mathbf{D} \cdot (\mathbf{O} - \mathbf{C})
      • c=(OC)(OC)r2c = (\mathbf{O} - \mathbf{C}) \cdot (\mathbf{O} - \mathbf{C}) - r^2

      Discriminant

      The discriminant d=b24acd = b^2 - 4ac determines intersection type:

      • d<0d < 0: No intersection (miss)
      • d=0d = 0: Tangent (one intersection)
      • d>0d > 0: Two intersections (enter and exit)

      Solutions

      s1=b+d2a,s2=bd2as_1 = \frac{-b + \sqrt{d}}{2a}, \quad s_2 = \frac{-b - \sqrt{d}}{2a}

      The closest valid intersection is the smallest positive ss.

      Ray-sphere intersection showing both hit points

      Ray-Plane Intersection

      Given:

      • Ray: P(s)=O+sD\mathbf{P}(s) = \mathbf{O} + s\mathbf{D}
      • Plane: PN+d=0\mathbf{P} \cdot \mathbf{N} + d = 0

      where N\mathbf{N} is the plane normal and dd is the distance offset.

      Substituting: s=dNONDs = \frac{-d - \mathbf{N} \cdot \mathbf{O}}{\mathbf{N} \cdot \mathbf{D}}

      Valid if:

      • s0s \geq 0 (intersection in front of origin)
      • ND0\mathbf{N} \cdot \mathbf{D} \neq 0 (ray not parallel to plane)

      Ray-Polygon Intersection

      For a polygon:

      1. Intersect the ray with the plane containing the polygon
      2. Check if the intersection point lies inside the polygon (2D geometry test)

      For a disc: Check if distance from centre is less than radius.

      Ray-Cone Intersection (2022 Paper 3 Question 3)

      For a cone with apex at origin, base radius rr, height hh, axis along yy:

      Implicit equation: x2+z2(rh)2y2=0x^2 + z^2 - \left(\frac{r}{h}\right)^2 y^2 = 0

      Intersection Method

      1. Base: Intersect ray with plane y=hy = h; accept if x2+z2r2x^2 + z^2 \leq r^2
      2. Side: Substitute ray into implicit equation, solve quadratic in ss

      Normal Calculation

      For a point (x,y,z)(x, y, z) on the cone side, the normal is proportional to: N(2x,2(rh)2y,2z)\mathbf{N} \propto \left(2x, -2\left(\frac{r}{h}\right)^2 y, 2z\right)

      The normal is the gradient of the implicit function f(x,y,z)=0f(x, y, z) = 0.

      Transformed Objects

      For an object transformed by matrix M\mathbf{M}:

      1. Transform the ray by M1\mathbf{M}^{-1}
      2. Intersect with the canonical (untransformed) object
      3. Transform the intersection point back by M\mathbf{M}
      4. Transform the normal by (M1)(\mathbf{M}^{-1})^\top

      Summary

      • Ray-sphere intersection reduces to a quadratic equation
      • Ray-plane intersection is a simple division
      • Polygon intersections require inside/outside tests
      • Cone normals are computed from the implicit gradient
      • Transformed objects require transforming the ray by the inverse matrix

      Past Paper Questions

      2022 Paper 3 Question 3: Derive the ray-cone intersection. Find the normal at an intersection point.

    • Shadow Rays

      What are Shadow Rays?

      After finding an intersection, shadow rays determine whether the point is illuminated by each light source.

      Pshadow=Phit+ϵLto_light\mathbf{P}_{\text{shadow}} = \mathbf{P}_{\text{hit}} + \epsilon \mathbf{L}_{\text{to\_light}}

      where ϵ\epsilon is a small offset to avoid self-intersection with the surface.

      Shadow Ray Algorithm

      FOR each light source
          cast shadow ray from hit point towards light
          IF shadow ray intersects any object before reaching light
              point is in shadow for this light
          ELSE
              point is illuminated by this light
      END FOR

      Hard Shadows

      A point is either:

      • Fully illuminated: Shadow ray reaches light unblocked
      • Fully in shadow: Shadow ray blocked by an object

      This produces sharp shadow boundaries.

      Shadow ray from intersection point to light source, blocked by another object

      Soft Shadows

      Area light sources create penumbrae (partial shadows):

      • Multiple shadow rays distributed over the light surface
      • Average the visibility results
      • Partially blocked points receive partial illumination

      Soft shadow from area light source vs hard shadow from point light

      Colour in Shadow

      If a point is in shadow for a light source:

      • The diffuse and specular components for that light are zero
      • Only ambient illumination contributes

      For multiple lights, shadows are computed per-light:

      • A point may be illuminated by some lights but shadowed from others

      Self-Intersection Problem

      A shadow ray starting exactly on the surface may hit the same surface due to floating-point precision:

      • Solution: Offset the ray origin by a small ϵ\epsilon along the surface normal

      Summary

      • Shadow rays determine if intersection points are illuminated
      • Hard shadows use one ray per light (sharp edges)
      • Soft shadows use multiple rays over area lights (penumbra)
      • Points in shadow only receive ambient illumination

      Past Paper Questions

      2025 Paper 3 Question 3(c): Explain shadow rays. What is the colour of a pixel if it is in shadow? [3 marks]

    • Reflection and Refraction

      Recursive Ray Tracing

      At an intersection point, we can spawn additional rays:

      • Reflection rays for mirrors
      • Refraction rays for transparent materials

      Ray spawning for reflection and refraction through a transparent sphere

      Reflection

      For mirror-like surfaces, a reflected ray is spawned:

      R=D2(DN)N\mathbf{R} = \mathbf{D} - 2(\mathbf{D} \cdot \mathbf{N})\mathbf{N}

      where D\mathbf{D} is the incoming ray direction and N\mathbf{N} is the surface normal.

      Reflection Direction Derivation

      The reflection is the incident direction mirrored about the normal:

      • Component parallel to N\mathbf{N}: reversed
      • Component perpendicular to N\mathbf{N}: unchanged

      Refraction (Transparency)

      Transparent objects bend light according to Snell’s law:

      n1sinθ1=n2sinθ2n_1 \sin\theta_1 = n_2 \sin\theta_2

      where n1n_1 and n2n_2 are refractive indices.

      Refracted Direction

      T=n1n2D+(n1n2cosθ1cosθ2)N\mathbf{T} = \frac{n_1}{n_2}\mathbf{D} + \left(\frac{n_1}{n_2}\cos\theta_1 - \cos\theta_2\right)\mathbf{N}

      Total Internal Reflection

      When light travels from a denser to less dense medium:

      • If incident angle exceeds critical angle: No refraction, only reflection
      • Critical angle: θc=arcsin(n2/n1)\theta_c = \arcsin(n_2/n_1)

      Fresnel Effect

      At glancing angles, more light is reflected; at normal incidence, more is refracted:

      • Approximate with Schlick’s approximation
      • Important for realistic glass and water

      Combining Effects

      The final colour combines:

      • Local shading (Phong)
      • Reflected colour (weighted by reflectivity)
      • Refracted colour (weighted by transparency)

      I=Ilocal+krIreflected+ktIrefractedI = I_{\text{local}} + k_r I_{\text{reflected}} + k_t I_{\text{refracted}}

      Summary

      • Reflection rays use the mirror direction formula
      • Refraction follows Snell’s law
      • Total internal reflection occurs above the critical angle
      • Combined colour blends local, reflected, and refracted contributions
    • Anti-Aliasing in Ray Tracing

      The Aliasing Problem

      Shooting a single ray through each pixel’s centre causes aliasing artefacts:

      • Jagged edges (stair-step patterns)
      • Small or thin objects missed entirely
      • Moire patterns in fine detail

      Super-Sampling Methods

      Regular Grid Sampling

      Divide each pixel into an N×NN \times N grid and shoot rays through each sub-pixel centre.

      • Problem: Can still produce noticeable patterns
      • Average all results

      Random Sampling

      Shoot NN rays at random positions within each pixel.

      • Replaces structured aliasing with noise
      • The eye tolerates noise better than patterns

      Jittered (Stratified) Sampling

      Divide pixel into NN sub-regions (strata) and shoot one random ray per region.

      • Combines benefits of regular and random
      • Good approximation to Poisson disc
      • Each region is guaranteed one sample

      Poisson Disc Sampling

      Random samples with a minimum distance constraint.

      • Best quality
      • Hardest to implement correctly
      • Requires Poisson distribution generation

      Comparison of sampling patterns - regular, random, jittered, Poisson disc

      Adaptive Super-Sampling

      Shoot a few rays per pixel. If the variance of results is high, shoot more rays.

      Benefits:

      • Concentrates effort where needed (edges, detail)
      • Saves computation in smooth regions

      Distributed Ray Tracing

      Extend super-sampling to multiple dimensions simultaneously:

      DimensionEffect
      Pixel areaAnti-aliasing
      Light source areaSoft shadows with penumbra
      TimeMotion blur
      Lens apertureDepth of field

      Each effect requires averaging multiple samples per pixel.

      Summary

      • Single ray per pixel causes aliasing
      • Super-sampling replaces aliasing with less objectionable noise
      • Jittered sampling is a good balance of quality and simplicity
      • Distributed ray tracing adds realistic effects beyond anti-aliasing
  • Shading

    Phong reflection model, diffuse and specular reflection, cacheability, microfacets

    • Phong Reflection Model

      The Phong Model

      The complete Phong shading model combines three reflection components:

      I=Iaka+lightsIlkdmax(0,NL)+lightsIlksmax(0,RV)nI = I_a k_a + \sum_{\text{lights}} I_l k_d \max(0, \mathbf{N} \cdot \mathbf{L}) + \sum_{\text{lights}} I_l k_s \max(0, \mathbf{R} \cdot \mathbf{V})^n

      Components

      ComponentTermProperties
      AmbientIakaI_a k_aConstant; approximates indirect illumination
      DiffuseIlkd(NL)I_l k_d (\mathbf{N} \cdot \mathbf{L})View-independent; Lambertian reflection
      SpecularIlks(RV)nI_l k_s (\mathbf{R} \cdot \mathbf{V})^nView-dependent; creates highlights

      Symbols

      SymbolMeaning
      ka,kd,ksk_a, k_d, k_sReflection coefficients
      Ia,IlI_a, I_lAmbient and light intensities
      N\mathbf{N}Surface normal (unit vector)
      L\mathbf{L}Direction to light (unit vector)
      R\mathbf{R}Perfect reflection direction
      V\mathbf{V}Direction to viewer (unit vector)
      nnPhong exponent (shininess)

      Reflection Direction

      R=2(LN)NL\mathbf{R} = 2(\mathbf{L} \cdot \mathbf{N})\mathbf{N} - \mathbf{L}

      Or equivalently: R=2cosθNL\mathbf{R} = 2\cos\theta \mathbf{N} - \mathbf{L}

      Phong shading geometry showing N, L, R, V, and α

      Per-Channel Computation

      The shading equation is computed for each RGB channel separately:

      • Different kdk_d values for each channel give surface colour
      • Specular highlights often use light colour (white for plastics)

      Clamping

      • max(0,)\max(0, \cdot) prevents negative contributions (light behind surface)
      • Without clamping, surfaces can become incorrectly dark

      Summary

      • Phong shading = ambient + diffuse + specular
      • Ambient approximates global illumination
      • Diffuse is view-independent (Lambertian)
      • Specular is view-dependent (highlights)
      • The max(0,)\max(0, \cdot) prevents negative values from light behind surfaces
    • Diffuse (Lambertian) Reflection

      Diffuse Surfaces

      Diffuse surfaces scatter light equally in all directions. Matte surfaces like paper, chalk, and unpolished wood.

      Lambert’s Cosine Law

      The reflected intensity depends only on the angle between the surface normal and light direction:

      Idiffuse=Ilkdcosθ=Ilkd(NL)I_{\text{diffuse}} = I_l k_d \cos\theta = I_l k_d (\mathbf{N} \cdot \mathbf{L})

      where:

      • IlI_l is the light source intensity
      • kdk_d is the diffuse reflection coefficient (surface colour)
      • N\mathbf{N} is the surface normal (unit vector)
      • L\mathbf{L} is the direction to the light (unit vector)
      • θ\theta is the angle between N\mathbf{N} and L\mathbf{L}

      Diffuse shading geometry with N, L, and θ

      Physical Interpretation

      NL=cosθ\mathbf{N} \cdot \mathbf{L} = \cos\theta represents:

      • Projected area: A surface receives less light energy when tilted
      • At glancing angles (θ90°\theta \approx 90°), the same energy spreads over a larger area
      • At perpendicular angles (θ=0°\theta = 0°), maximum energy per unit area

      View Independence

      Diffuse reflection is view-independent:

      • The surface appears equally bright from any viewing angle
      • Light scatters uniformly in all directions
      • Only depends on N\mathbf{N} and L\mathbf{L}, not on V\mathbf{V}

      When Diffuse is Zero

      Diffuse is zero when:

      • NL0\mathbf{N} \cdot \mathbf{L} \leq 0: Light is behind or tangent to the surface
      • kd=0k_d = 0: Surface has zero diffuse reflectance (pure mirror)

      One-Sided vs Two-Sided Surfaces

      One-sided surfaces: Only illuminate the side in direction of N\mathbf{N}. If cosθ<0\cos\theta < 0, render black.

      Two-sided surfaces: If cosθ<0\cos\theta < 0, use cosθ|\cos\theta| (or flip N\mathbf{N}) to illuminate the back.

      Summary

      • Diffuse reflection follows Lambert’s cosine law
      • Intensity proportional to cosθ\cos\theta = NL\mathbf{N} \cdot \mathbf{L}
      • View-independent: same brightness from any angle
      • Zero when light is behind the surface

      Past Paper Questions

      2025 Paper 3 Question 3(d): In the Phong shading model, explain when the diffuse component becomes zero. [Part of 4 marks]

    • Specular Reflection

      Specular Highlights

      Specular reflection models shiny surfaces that reflect light in a preferred direction, creating bright highlights.

      Phong Specular Term

      Ispecular=Ilkscosnα=Ilks(RV)nI_{\text{specular}} = I_l k_s \cos^n\alpha = I_l k_s (\mathbf{R} \cdot \mathbf{V})^n

      where:

      • ksk_s is the specular reflection coefficient
      • R\mathbf{R} is the perfect reflection direction of the light
      • V\mathbf{V} is the direction to the viewer
      • α\alpha is the angle between R\mathbf{R} and V\mathbf{V}
      • nn is the Phong exponent (shininess)

      Reflection Direction

      R=2(LN)NL\mathbf{R} = 2(\mathbf{L} \cdot \mathbf{N})\mathbf{N} - \mathbf{L}

      Effect of Shininess nn

      MaterialTypical nnEffect
      Matte1-5Broad, dull highlight
      Plastic10-50Moderate highlight
      Metal50-200Sharp, tight highlight
      MirrorPerfect reflection (delta function)

      Higher nn concentrates the highlight around the mirror direction.

      When Specular is Zero

      Specular reflection is zero when:

      • RV0\mathbf{R} \cdot \mathbf{V} \leq 0: Viewer is on wrong side of reflection lobe
      • NL0\mathbf{N} \cdot \mathbf{L} \leq 0: Light behind surface (no illumination at all)
      • ks=0k_s = 0: Surface has zero specular reflectance

      View Dependence

      Specular reflection is view-dependent:

      • Highlight moves as the camera moves
      • Must be recomputed every frame for animations
      • Cannot be cached if camera changes

      Phong shading geometry showing N, L, R, V, and α

      Physical Approximation

      The Phong model is an approximation:

      • Does not conserve energy
      • Not physically based (BRDF is ad-hoc)
      • But computationally efficient and produces plausible results

      Summary

      • Specular creates shiny highlights
      • Intensity depends on angle between reflection and viewer
      • Shininess nn controls highlight size
      • View-dependent: must recompute if camera moves

      Past Paper Questions

      2025 Paper 3 Question 3(e): How does the specular highlight differ from diffuse reflection in the Phong shading model? [2 marks]

      2025 Paper 3 Question 3(d): Explain when the specular component becomes zero. [Part of 4 marks]

    • Cacheability of Phong Terms

      Caching for Animation

      When rendering animations, we can cache certain Phong shading components depending on what is moving in the scene.

      Component Cacheability

      ComponentTermCacheable?Reason
      AmbientIakaI_a k_aAlwaysConstant; independent of everything
      DiffuseIlkd(NL)I_l k_d (\mathbf{N} \cdot \mathbf{L})Yes (if static)Depends on N\mathbf{N} and L\mathbf{L}, not V\mathbf{V}
      SpecularIlks(RV)nI_l k_s (\mathbf{R} \cdot \mathbf{V})^nNever if cam. movesDepends on viewer direction

      Ambient Term

      Always cacheable:

      • Constant per surface (independent of camera, lights, objects)
      • Compute once and reuse across all frames

      Diffuse Term

      Cacheable if:

      • Lights are static
      • Objects are static

      Cannot cache if:

      • Lights move (changes L\mathbf{L})
      • Objects move/rotate (changes N\mathbf{N})

      View-independent: unaffected by camera motion.

      Specular Term

      Never cacheable if camera moves:

      • Depends on V\mathbf{V} (viewer direction)
      • Must recompute every frame

      Could cache if:

      • Camera is static
      • Lights and objects are static
      • (Rare: only useful for walk-through with fixed viewpoint)

      Summary

      • Ambient: always cacheable
      • Diffuse: cacheable if lights and objects are static
      • Specular: never cacheable if camera moves (depends on V\mathbf{V})

      Past Paper Questions

      2023 Paper 3 Question 3(a)(iv): In the Phong shading model, which terms can be cached in an animation? Explain why.

    • Microfacet Interpretation

      Microfacet Model

      Surface reflection can be understood through the microfacet model: surfaces are composed of tiny mirrors (facets) with varying orientations.

      Facet Distributions

      MaterialFacet DistributionReflection Behaviour
      Diffuse (Lambertian)Random in all directionsScatter equally everywhere
      Imperfect specularMostly aligned, some spreadBroad highlight
      Perfect specular (mirror)All co-planar with surfaceOne sharp reflection

      Diffuse Surfaces

      Facets randomly oriented in all directions:

      • Light hits facets at all angles
      • Light scatters uniformly
      • No preferred reflection direction

      Result: View-independent reflection (Lambertian).

      Imperfect Specular Surfaces

      Facets mostly aligned with the macro-surface normal, but with some angular spread:

      • Most light reflects near the mirror direction
      • Some spread creates a broad highlight
      • Higher alignment = higher shininess nn

      Result: Phong-like specular with finite highlight size.

      Perfect Specular Surfaces

      All facets perfectly co-planar with the surface:

      • All light reflects in exactly one direction
      • No diffuse component
      • Mirror-like reflection

      Result: nn \to \infty, perfect mirror.

      Physical Insight

      The microfacet model explains why:

      • Metals have coloured specular (ksk_s takes metal colour)
      • Plastics have white specular (ksk_s is light colour)
      • Rough surfaces have broad, dim highlights
      • Polished surfaces have sharp, bright highlights

      Summary

      • Microfacets model surfaces as collections of tiny mirrors
      • Facet orientation distribution determines reflection properties
      • Random facets → diffuse; aligned facets → specular
      • Phong exponent nn models the spread of facet orientations
  • Transformations

    2D and 3D transformations, homogeneous coordinates, matrix composition, normal transforms

    • 2D Transformations

      Why Transformations?

      Transformations allow us to:

      • Place predefined objects at arbitrary locations, orientations, and sizes
      • Build complex scenes from simple primitives
      • Animate objects over time

      Basic object transformed to multiple instances in a scene

      Basic Transformations

      Scale (about origin, factor mm)

      x=mx,y=myx' = mx, \quad y' = my

      Rotate (about origin, angle θ\theta)

      x=xcosθysinθx' = x\cos\theta - y\sin\theta y=xsinθ+ycosθy' = x\sin\theta + y\cos\theta

      Translate (by vector (xo,yo)(x_o, y_o))

      x=x+xo,y=y+yox' = x + x_o, \quad y' = y + y_o

      Shear (parallel to x-axis, factor aa)

      x=x+ay,y=yx' = x + ay, \quad y' = y

      Matrix Representation

      2×2 matrices work for scale, rotate, and shear, but not translation.

      Scale: [xy]=[m00m][xy]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} m & 0 \\ 0 & m \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

      Rotate: [xy]=[cosθsinθsinθcosθ][xy]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

      Identity: [xy]=[1001][xy]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

      The Translation Problem

      Translation cannot be represented as 2×2 matrix multiplication: [xy]=[xy]+[xoyo]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix} x_o \\ y_o \end{bmatrix}

      This breaks uniformity—other transforms are multiplicative.

      Summary

      • Scale, rotate, and shear can be expressed as matrix multiplication
      • Translation requires an additive term (not multiplicative)
      • This motivates homogeneous coordinates
    • Homogeneous Coordinates

      The Problem

      Translation cannot be represented as a 2×2 matrix multiplication on 2D vectors. We need an additive term.

      The Solution

      Add a third coordinate ww:

      2D point (x,y)Homogeneous (x,y,1)\text{2D point } (x, y) \equiv \text{Homogeneous } (x, y, 1)

      More generally: (x,y,w)(xw,yw)(x, y, w) \equiv \left(\frac{x}{w}, \frac{y}{w}\right)

      Properties

      An infinite number of homogeneous coordinates map to each 2D point:

      • (1,2,1)(2,4,2)(3,6,3)(1, 2, 1) \equiv (2, 4, 2) \equiv (3, 6, 3)

      When w=0w = 0: Point at infinity (direction vector).

      Transformation Matrices

      Scale (factor mm)

      [xyw]=[m000m0001][xyw]\begin{bmatrix} x' \\ y' \\ w' \end{bmatrix} = \begin{bmatrix} m & 0 & 0 \\ 0 & m & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ w \end{bmatrix}

      Rotate (angle θ\theta)

      [xyw]=[cosθsinθ0sinθcosθ0001][xyw]\begin{bmatrix} x' \\ y' \\ w' \end{bmatrix} = \begin{bmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ w \end{bmatrix}

      Translate (by (xo,yo)(x_o, y_o))

      [xyw]=[10xo01yo001][xyw]\begin{bmatrix} x' \\ y' \\ w' \end{bmatrix} = \begin{bmatrix} 1 & 0 & x_o \\ 0 & 1 & y_o \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ w \end{bmatrix}

      Shear (factor aa)

      [xyw]=[1a0010001][xyw]\begin{bmatrix} x' \\ y' \\ w' \end{bmatrix} = \begin{bmatrix} 1 & a & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ w \end{bmatrix}

      Effects of each transformation on a square

      3D Homogeneous Coordinates

      A 3D point (x,y,z)(x, y, z) is represented as (x,y,z,w)(x, y, z, w): (x,y,z,w)(xw,yw,zw)(x, y, z, w) \equiv \left(\frac{x}{w}, \frac{y}{w}, \frac{z}{w}\right)

      Points vs Vectors

      TypewwAffected by Translation?
      Point1Yes
      Vector0No

      Vectors represent directions and should not be translated.

      Summary

      • Homogeneous coordinates add ww to represent translation as matrix multiplication
      • Points: w=1w = 1; Vectors: w=0w = 0
      • All affine transforms are now uniform matrix multiplications
    • 3D Transformation Matrices

      Identity

      [1000010000100001]\begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Scale (uniform, factor mm)

      [m0000m0000m00001]\begin{bmatrix} m & 0 & 0 & 0 \\ 0 & m & 0 & 0 \\ 0 & 0 & m & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      For non-uniform scaling, use different values on the diagonal.

      Translate (by (tx,ty,tz)(t_x, t_y, t_z))

      [100tx010ty001tz0001]\begin{bmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Rotation Matrices

      Rotate about x-axis

      Rx(θ)=[10000cosθsinθ00sinθcosθ00001]\mathbf{R}_x(\theta) = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & \cos\theta & -\sin\theta & 0 \\ 0 & \sin\theta & \cos\theta & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Rotate about y-axis

      Ry(θ)=[cosθ0sinθ00100sinθ0cosθ00001]\mathbf{R}_y(\theta) = \begin{bmatrix} \cos\theta & 0 & \sin\theta & 0 \\ 0 & 1 & 0 & 0 \\ -\sin\theta & 0 & \cos\theta & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Rotate about z-axis

      Rz(θ)=[cosθsinθ00sinθcosθ0000100001]\mathbf{R}_z(\theta) = \begin{bmatrix} \cos\theta & -\sin\theta & 0 & 0 \\ \sin\theta & \cos\theta & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Mnemonic

      The axis being rotated about has 1 on the diagonal and 0 in that row/column. The other entries form a 2D rotation matrix.

      Non-Commutativity

      3D rotations are non-commutative:

      • Rx(90°)Rz(90°)Rz(90°)Rx(90°)\mathbf{R}_x(90°) \cdot \mathbf{R}_z(90°) \neq \mathbf{R}_z(90°) \cdot \mathbf{R}_x(90°)

      Cube showing different orientations from different rotation orders

      Summary

      • Translation uses the fourth column
      • Rotation matrices are orthogonal (determinant = 1)
      • 3D rotations are non-commutative
    • Transformation Composition

      Concatenation

      Multiple transformations combine by multiplying their matrices:

      Mcombined=MnMn1M2M1\mathbf{M}_{\text{combined}} = \mathbf{M}_n \cdot \mathbf{M}_{n-1} \cdots \mathbf{M}_2 \cdot \mathbf{M}_1

      Transformations are applied right-to-left.

      Standard Order: SRT

      Scale → Rotate → Translate

      Written as: M=TRS\mathbf{M} = \mathbf{T} \cdot \mathbf{R} \cdot \mathbf{S}

      The rightmost matrix (S\mathbf{S}) is applied first.

      Example: Shear then Scale

      [xyw]=[m000m0001][1a0010001][xyw]=[mma00m0001][xyw]\begin{bmatrix} x'' \\ y'' \\ w'' \end{bmatrix} = \begin{bmatrix} m & 0 & 0 \\ 0 & m & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} 1 & a & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ w \end{bmatrix} = \begin{bmatrix} m & ma & 0 \\ 0 & m & 0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ w \end{bmatrix}

      Non-Commutativity

      Transformations generally do not commute.

      Example: Scale by 2 along x, then rotate 45° \neq Rotate 45°, then scale by 2 along x.

      Two objects showing different results from different transformation orders

      Transformations About Arbitrary Points

      To transform about point (xo,yo)(x_o, y_o):

      1. Translate (xo,yo)(x_o, y_o) to origin
      2. Apply transformation
      3. Translate back to (xo,yo)(x_o, y_o)

      Scale about (xo,yo)(x_o, y_o): M=T(xo,yo)S(m)T(xo,yo)\mathbf{M} = \mathbf{T}(x_o, y_o) \cdot \mathbf{S}(m) \cdot \mathbf{T}(-x_o, -y_o)

      Steps for scaling about an arbitrary point

      Efficiency

      Concatenate matrices once, then apply to all vertices:

      • One matrix multiplication per concatenated transform
      • More efficient than applying each matrix sequentially

      Summary

      • Matrices multiply right-to-left
      • Standard order: Scale, Rotate, Translate (SRT)
      • Transformations are non-commutative
      • Arbitrary pivots require translate-transform-translate
    • Normal Vector Transformation

      The Problem

      Normal vectors transform differently from positions!

      For transformation matrix M\mathbf{M} applied to positions, normals transform using: N=(M1)N\mathbf{N}' = (\mathbf{M}^{-1})^\top \mathbf{N}

      Derivation

      The normal N\mathbf{N} is perpendicular to the tangent vector T\mathbf{T}: NT=0\mathbf{N} \cdot \mathbf{T} = 0

      After transformation, T=MT\mathbf{T}' = \mathbf{M}\mathbf{T}. We need NT=0\mathbf{N}' \cdot \mathbf{T}' = 0: N(MT)=((M1)N)(MT)=NM1MT=NT=0\mathbf{N}' \cdot (\mathbf{M}\mathbf{T}) = ((\mathbf{M}^{-1})^\top \mathbf{N}) \cdot (\mathbf{M}\mathbf{T}) = \mathbf{N}^\top \mathbf{M}^{-1} \mathbf{M}\mathbf{T} = \mathbf{N} \cdot \mathbf{T} = 0

      Simplifications

      Pure Rotation

      If M\mathbf{M} is orthogonal (rotation only): M1=M\mathbf{M}^{-1} = \mathbf{M}^\top

      Therefore: N=MN\mathbf{N}' = \mathbf{M}\mathbf{N}

      Normals use the same rotation matrix as positions.

      Uniform Scale + Rotation

      The scale factor cancels (normals are renormalised anyway): N=RN\mathbf{N}' = \mathbf{R}\mathbf{N}

      Non-Uniform Scale or Shear

      Must compute and apply (M1)(\mathbf{M}^{-1})^\top: N=(M1)N\mathbf{N}' = (\mathbf{M}^{-1})^\top \mathbf{N}

      Translation

      Normals are unchanged by pure translations (direction vectors).

      Why It Matters

      Non-uniform scaling distorts normals:

      • A sphere scaled to an ellipsoid needs transformed normals
      • Using M\mathbf{M} directly would make normals point in wrong direction

      Normal transformation showing correct vs incorrect transformation after non-uniform scaling

      Summary

      • Normals transform with (M1)(\mathbf{M}^{-1})^\top, not M\mathbf{M}
      • Pure rotation: normals use same matrix as positions
      • Uniform scale: scale cancels after renormalisation
      • Non-uniform scale/shear: must compute inverse transpose
      • Translation: no effect on direction vectors

      Past Paper Questions

      2025 Paper 3 Question 4(a)(ii): How would you obtain the transformation for the normal using scaling, rotation, and translation? Simplify if possible. [2 marks]

    • Model Transform Example

      Problem (2025 Paper 3 Question 4(a)(i))

      Transform a cylinder (radius 1, height 2, centred at origin, aligned along y-axis) to have:

      • Radius 2
      • Ends at (1,2,3)(1, 2, 3) and (2,4,5)(2, 4, 5)

      Solution

      Order: Scale → Rotate → Translate

      Compute Target Properties

      • Axis vector: v=(21,42,53)=(1,2,2)\mathbf{v} = (2-1, 4-2, 5-3) = (1, 2, 2)
      • Length: v=12+22+22=3|\mathbf{v}| = \sqrt{1^2 + 2^2 + 2^2} = 3
      • Midpoint: m=(1+22,2+42,3+52)=(1.5,3,4)\mathbf{m} = \left(\frac{1+2}{2}, \frac{2+4}{2}, \frac{3+5}{2}\right) = (1.5, 3, 4)

      1. Scale

      Original: radius 1, height 2. Target: radius 2, height 3.

      • sx=2s_x = 2, sz=2s_z = 2 (double radius)
      • sy=1.5s_y = 1.5 (height 3 from 2: 3/2=1.53/2 = 1.5)

      S=[200001.50000200001]\mathbf{S} = \begin{bmatrix} 2 & 0 & 0 & 0 \\ 0 & 1.5 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      2. Rotate

      Align y-axis (0,1,0)(0,1,0) with target axis (1,2,2)(1, 2, 2).

      Step A: Zero z-component. Rotate about x-axis by θ=45°\theta = 45°.

      Step B: Zero x-component. Rotate about z-axis by ϕ=arcsin(1/3)19.47°\phi = \arcsin(1/3) \approx 19.47°.

      The rotation aligning the axis: R1=Rx(45°)Rz(arcsin(1/3))\mathbf{R}^{-1} = \mathbf{R}_x(-45°) \cdot \mathbf{R}_z(-\arcsin(1/3))

      3. Translate

      Move origin to midpoint (1.5,3,4)(1.5, 3, 4): T=[1001.5010300140001]\mathbf{T} = \begin{bmatrix} 1 & 0 & 0 & 1.5 \\ 0 & 1 & 0 & 3 \\ 0 & 0 & 1 & 4 \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Overall Model Matrix

      M=TRx(45°)Rz(arcsin(1/3))S\mathbf{M} = \mathbf{T} \cdot \mathbf{R}_x(-45°) \cdot \mathbf{R}_z(-\arcsin(1/3)) \cdot \mathbf{S}

      Cylinder transformation showing original, scaled, rotated, and translated states

      Summary

      • Compute geometric properties first (axis, length, midpoint)
      • Apply SRT order: Scale, Rotate, Translate
      • Rotate by inverse of the rotation that aligns axis to canonical

      Past Paper Questions

      2025 Paper 3 Question 4(a)(i): Transform a cylinder to have specified radius and endpoints. [6 marks]

  • Projection and Viewing

    View frustum, perspective and orthographic projection, look-at matrix, MVP pipeline, scene graphs

    • View Frustum

      Definition

      The view frustum is the region of space visible through the camera:

      • A truncated pyramid (for perspective) or box (for orthographic)
      • Contains everything that will be rendered

      Six Clipping Planes

      PlanePurpose
      NearObjects closer than this are clipped
      FarObjects beyond this are clipped
      Left, RightHorizontal bounds
      Top, BottomVertical bounds

      View frustum showing all six planes

      Frustum Culling

      Objects entirely outside the frustum are not rendered:

      • Test each object’s bounding volume against frustum planes
      • If completely outside, skip rendering
      • Important optimisation for large scenes

      Field of View

      The field of view (FOV) determines how much of the scene is visible:

      • Vertical FOV: Angle from top to bottom of frustum
      • Horizontal FOV: Derived from aspect ratio

      Higher FOV: More visible (wide-angle). Lower FOV: Zoomed in (telephoto).

      Aspect Ratio

      The ratio of viewport width to height: aspect=widthheight\text{aspect} = \frac{\text{width}}{\text{height}}

      Determines horizontal FOV from vertical FOV.

      Summary

      • The frustum defines the visible region of 3D space
      • Bounded by six clipping planes
      • Frustum culling removes non-visible objects
      • FOV and aspect ratio define the frustum shape
    • Perspective Projection

      How Perspective Works

      Objects farther away appear smaller. Parallel lines converge to a vanishing point.

      Perspective projection showing converging projectors to a single point

      Geometry

      For a camera at origin looking down z-z, with image plane at distance dd:

      x=xdz,y=ydzx' = \frac{x \cdot d}{z}, \quad y' = \frac{y \cdot d}{z}

      Perspective geometry with similar triangles

      Matrix Form

      Perspective can be expressed with a matrix:

      [xdydzdz]=[d0000d0000d00010][xyz1]\begin{bmatrix} x \cdot d \\ y \cdot d \\ z \cdot d \\ z \end{bmatrix} = \begin{bmatrix} d & 0 & 0 & 0 \\ 0 & d & 0 & 0 \\ 0 & 0 & d & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix}

      After dividing by w=zw = z: correct projected coordinates.

      Why Preserve 1/z1/z?

      The ww component stores zz, enabling:

      • Z-buffer interpolation (interpolate 1/z1/z, not zz)
      • Perspective-correct texture mapping

      Properties

      • Realistic appearance
      • Distant objects smaller
      • Parallel lines converge
      • Used in games, film, photography

      Summary

      • Perspective divides by zz: x=xd/zx' = xd/z, y=yd/zy' = yd/z
      • Preserves 1/z1/z for correct depth interpolation
      • Matches how cameras and eyes work
    • Orthographic Projection

      Parallel Projectors

      All projectors (projection lines) are parallel to each other:

      • No vanishing point
      • Parallel lines remain parallel
      • No perspective distortion

      Parallel projection showing parallel projectors

      Mathematical Form

      Simply discard the zz coordinate:

      (x,y,z)(x,y)(x, y, z) \rightarrow (x, y)

      Matrix Form

      Orthographic projection maps a box to the NDC cube [1,1]3[-1, 1]^3:

      Portho=[2rl00r+lrl02tb0t+btb002fnf+nfn0001]\mathbf{P}_{\text{ortho}} = \begin{bmatrix} \frac{2}{r-l} & 0 & 0 & -\frac{r+l}{r-l} \\ 0 & \frac{2}{t-b} & 0 & -\frac{t+b}{t-b} \\ 0 & 0 & \frac{2}{f-n} & -\frac{f+n}{f-n} \\ 0 & 0 & 0 & 1 \end{bmatrix}

      where l,r,b,t,n,fl, r, b, t, n, f are left, right, bottom, top, near, far planes.

      Properties

      • Preserves measurements (no perspective distortion)
      • Parallel lines stay parallel
      • Used in CAD, architecture, technical drawings
      • Looks “flat” and unrealistic for natural scenes

      When to Use

      • Technical drawings where accuracy matters
      • 2D games and UI
      • Isometric view games
      • Architectural plans

      Summary

      • Orthographic discards zz: parallel projection
      • No perspective: distant objects same size
      • Preserves parallel lines and measurements
      • Used for technical applications
    • View Matrix and Look-At

      Purpose

      The view matrix transforms world coordinates to camera coordinates:

      • Camera at origin
      • Looking down z-z axis
      • +y+y up, +x+x right

      Standard Camera Assumptions

      For uniform projection mathematics:

      • Camera at origin (0,0,0)(0, 0, 0)
      • Screen centre at (0,0,d)(0, 0, -d)
      • Screen parallel to xyxy-plane

      Look-At Construction

      Given:

      • Camera position c\mathbf{c}
      • Look-at point l\mathbf{l} (where camera points)
      • Up direction u\mathbf{u} (which way is “up”)

      Build Orthonormal Basis

      1. Forward: v^=clcl\hat{\mathbf{v}} = \frac{\mathbf{c} - \mathbf{l}}{|\mathbf{c} - \mathbf{l}|}

      2. Right: r^=u×v^u×v^\hat{\mathbf{r}} = \frac{\mathbf{u} \times \hat{\mathbf{v}}}{|\mathbf{u} \times \hat{\mathbf{v}}|}

      3. True up: u^=v^×r^\hat{\mathbf{u}} = \hat{\mathbf{v}} \times \hat{\mathbf{r}}

      View Matrix

      V=[r^xr^yr^zcr^u^xu^yu^zcu^v^xv^yv^zcv^0001]\mathbf{V} = \begin{bmatrix} \hat{r}_x & \hat{r}_y & \hat{r}_z & -\mathbf{c} \cdot \hat{\mathbf{r}} \\ \hat{u}_x & \hat{u}_y & \hat{u}_z & -\mathbf{c} \cdot \hat{\mathbf{u}} \\ \hat{v}_x & \hat{v}_y & \hat{v}_z & -\mathbf{c} \cdot \hat{\mathbf{v}} \\ 0 & 0 & 0 & 1 \end{bmatrix}

      Look-at construction showing camera position, look-at point, up vector, and resulting basis vectors

      Coordinate System Conventions

      SpaceHandednessz-axis
      Camera (OpenGL)Right-handedLook down z-z
      NDCLeft-handed+z+z into screen

      The projection matrix flips the handedness.

      Summary

      • View matrix places camera at origin, looking down z-z
      • Constructed from position, look-at point, and up vector
      • Build orthonormal basis using cross products
      • Translation to origin + rotation to align axes

      Past Paper Questions

      2024 Paper 3 Question 4(b): Derive the look-at view matrix for a camera at position c\mathbf{c}, looking at point l\mathbf{l}, with up vector u\mathbf{u}.

    • MVP Pipeline

      Complete Transformation Pipeline

      Object coords → World coords → View coords → Clip coords → NDC → Screen coords

      Complete pipeline showing coordinate transformations

      The MVP Matrix

      [xsyszsws]=PVM[xyzw]\begin{bmatrix} x_s \\ y_s \\ z_s \\ w_s \end{bmatrix} = \mathbf{P} \cdot \mathbf{V} \cdot \mathbf{M} \begin{bmatrix} x \\ y \\ z \\ w \end{bmatrix}

      Model Matrix (M)

      Object coordinates → World coordinates:

      • Places object in the scene
      • Applies scale, rotate, translate

      View Matrix (V)

      World coordinates → Camera coordinates:

      • Positions camera at origin
      • Orients camera to look down z-z

      Projection Matrix (P)

      Camera coordinates → Clip coordinates:

      • Projects 3D to 2D (perspective or orthographic)
      • Maps frustum to NDC cube [1,1]3[-1, 1]^3

      MVP transformation pipeline with diagrams at each stage

      After Projection

      1. Perspective division: Divide by ww
      2. Viewport transform: Map NDC to screen pixels
      3. Rasterisation: Convert to fragments

      Summary

      • M: Places object in world
      • V: Places camera at origin
      • P: Projects to 2D and maps to NDC
      • Combined: PVM\mathbf{P} \cdot \mathbf{V} \cdot \mathbf{M} applied to each vertex

      Past Paper Questions

      2024 Paper 3 Question 4: Explain the purpose of the model, view, and projection matrices. What coordinate system does each transform between?

    • Scene Graphs

      Definition

      A scene graph is a tree structure representing hierarchical relationships between objects in a scene.

      Scene graph tree with transformations accumulating down the hierarchy

      Transformation Inheritance

      Child objects inherit transformations from parent nodes:

      • Each node has its own local transformation
      • World transformation = product of all parent transformations

      Traversal Pseudocode

      traverse(node, T_parent):
          M = T_parent * node.T * node.E
          node.draw(M)
          for child in node.children:
              traverse(child, T_parent * node.T)

      where:

      • node.T: Transformation relative to parent
      • node.E: Optional additional transformation (e.g., animation)

      Example: Robot Arm

      Body → Shoulder → UpperArm → Elbow → LowerArm → Hand
      • Body: Positioned in world space
      • Shoulder: Rotates relative to body
      • Elbow: Rotates relative to upper arm
      • Hand: Rotates relative to lower arm

      Each transformation is relative to its parent.

      Benefits

      • Natural representation of articulated objects
      • Easy animation (just modify local transforms)
      • Efficient rendering (traverse tree, accumulate transforms)
      • Supports instancing (same object under different parent nodes)

      Summary

      • Scene graphs organise objects hierarchically
      • Children inherit parent transformations
      • Traversal accumulates transformations down the tree
      • Natural for articulated objects and animations

      Past Paper Questions

      2021 Paper 3 Question 4: Explain how scene graphs work. How are transformations accumulated?

  • Rasterisation

    Rasterisation algorithm, triangle meshes, barycentric coordinates, Z-buffer, shading types

    • Rasterisation Algorithm

      Why Rasterisation?

      Ray tracing produces high-quality images but is computationally expensive. Real-time applications need faster rendering.

      Rasterisation is the dominant technique for real-time rendering:

      • Model surfaces as meshes of polygons (usually triangles)
      • Project vertices to screen coordinates
      • Fill visible polygons

      Comparison - ray tracing vs rasterisation approach

      The Algorithm

      Set model, view and projection (MVP) transformations
      FOR every triangle in the scene
          transform its vertices using MVP matrices
          IF the triangle is within the view frustum
              clip the triangle to the screen border
              FOR each fragment (pixel candidate) in the triangle
                  interpolate fragment position and attributes between vertices
                  compute fragment colour
                  IF the fragment is closer to the camera than any pixel drawn so far
                      update the screen pixel with the fragment colour
                  END IF
              END FOR
          END IF
      END FOR

      Fragments

      A fragment is a candidate pixel within a triangle:

      • Has a screen position, depth, and interpolated attributes
      • May or may not become a final pixel (depending on depth test)

      Complexity

      Time complexity: O(triangles+fragments)O(\text{triangles} + \text{fragments})

      For nn triangles and pp pixels:

      • Transform: O(n)O(n) for vertices
      • Rasterise: O(ptriangles per pixel)O(p \cdot \text{triangles per pixel})

      Generally: O(n+p)O(n + p) with good clipping and culling.

      Summary

      • Rasterisation projects triangles and fills pixels
      • Faster than ray tracing for real-time
      • Fragments are pixel candidates with interpolated attributes
      • Complexity: O(triangles+fragments)O(\text{triangles} + \text{fragments})
    • Triangle Meshes

      Planar Polygons

      • A triangle (3 vertices) is always planar
      • Polygons with >3 vertices may not be planar

      Planar triangle vs non-planar quadrilateral

      Triangulation

      Most GPUs are optimised for triangles. Polygons with more vertices are split into triangles.

      Why triangles?

      • Always planar
      • Convex (easy to fill)
      • Simple interpolation
      • Hardware acceleration

      Splitting a hexagon into triangles

      Triangle Mesh Indexing

      For efficient storage:

      • Vertex array: Unique vertex positions
      • Index array: Which vertices form each triangle

      Example: A cube has 8 vertices but 12 triangles (36 indices with sharing, or 24 vertices without).

      Summary

      • Triangles are always planar; other polygons may not be
      • GPUs are optimised for triangles
      • Indexed meshes reuse vertices for efficiency
    • Barycentric Coordinates

      Definition

      Barycentric coordinates (α,β,γ)(\alpha, \beta, \gamma) express a point inside a triangle as a weighted combination of the vertices:

      P=αA+βB+γC\mathbf{P} = \alpha\mathbf{A} + \beta\mathbf{B} + \gamma\mathbf{C}

      where α+β+γ=1\alpha + \beta + \gamma = 1 and α,β,γ0\alpha, \beta, \gamma \geq 0 for points inside the triangle.

      Triangle with barycentric coordinates showing point P inside

      Computing Barycentric Coordinates

      Given triangle vertices (xA,yA)(x_A, y_A), (xB,yB)(x_B, y_B), (xC,yC)(x_C, y_C) and point (x,y)(x, y):

      Define implicit line equation: fAB(x,y)=(yAyB)x+(xBxA)y+xAyBxByAf_{AB}(x, y) = (y_A - y_B)x + (x_B - x_A)y + x_A y_B - x_B y_A

      Then: α=fBC(x,y)fBC(xA,yA)\alpha = \frac{f_{BC}(x, y)}{f_{BC}(x_A, y_A)} β=fAC(x,y)fAC(xB,yB)\beta = \frac{f_{AC}(x, y)}{f_{AC}(x_B, y_B)} γ=1αβ\gamma = 1 - \alpha - \beta

      Interpolating Attributes

      Any attribute QQ (colour, normal, texture coordinates) can be interpolated:

      Q(x,y)=αQA+βQB+γQCQ(x, y) = \alpha Q_A + \beta Q_B + \gamma Q_C

      Used for:

      • Colour interpolation (Gouraud shading)
      • Normal interpolation (Phong shading)
      • Texture coordinate interpolation

      Point-in-Triangle Test

      A point is inside the triangle if and only if: α>0 and β>0 and γ>0\alpha > 0 \text{ and } \beta > 0 \text{ and } \gamma > 0

      Summary

      • Barycentric coordinates express points as vertex weights
      • Sum to 1 inside triangle; all positive for interior points
      • Enable smooth attribute interpolation across triangle

      Past Paper Questions

      2025 Paper 3 Question 4(b)(iv): What are barycentric coordinates, and where are they needed in the OpenGL rendering pipeline? [3 marks]

    • Perspective-Correct Interpolation

      The Problem

      Linear interpolation in screen space is only correct for parallel (orthographic) projection.

      Under perspective projection, 3D properties are projected non-linearly onto 2D screen. Simply interpolating in screen space causes attributes like texture coordinates to distort.

      The Solution

      Interpolate quantities that are linear in screen space:

      • Perspective-divided attribute Q/zQ/z
      • Reciprocal depth 1/z1/z

      The Formula

      For pixel with barycentric coordinates (α,β,γ)(\alpha, \beta, \gamma) and depths zA,zB,zCz_A, z_B, z_C:

      1. Interpolate Q/zQ/z: (Qz)interp=αQAzA+βQBzB+γQCzC\left(\frac{Q}{z}\right)_{\text{interp}} = \alpha \frac{Q_A}{z_A} + \beta \frac{Q_B}{z_B} + \gamma \frac{Q_C}{z_C}

      2. Interpolate 1/z1/z: (1z)interp=α1zA+β1zB+γ1zC\left(\frac{1}{z}\right)_{\text{interp}} = \alpha \frac{1}{z_A} + \beta \frac{1}{z_B} + \gamma \frac{1}{z_C}

      3. Reconstruct: Q(x,y)=(Q/z)interp(1/z)interpQ(x, y) = \frac{(Q/z)_{\text{interp}}}{(1/z)_{\text{interp}}}

      Why This Works

      After perspective projection, 1/z1/z varies linearly in screen space. Dividing attributes by zz before interpolation, then dividing by 1/z1/z after, gives correct results.

      Summary

      • Screen-space linear interpolation is wrong for perspective
      • Interpolate Q/zQ/z and 1/z1/z in screen space
      • Divide the results to recover perspective-correct QQ

      Past Paper Questions

      2022 Paper 3 Question 4: How does perspective-correct interpolation differ from linear interpolation on the screen? Why is it needed for texture mapping?

    • Z-Buffer Algorithm

      Hidden Surface Removal

      Multiple triangles may cover the same pixel. We need to determine which surface is closest to the camera.

      Multiple triangles overlapping the same screen region

      Z-Buffer

      The Z-buffer (depth buffer) stores the depth value for each pixel.

      Algorithm

      Initialise:
          colour(x, y) = background_colour
          depth(x, y) = z_max  // far clipping plane
      
      For each triangle:
          For each fragment (x, y):
              Calculate z for current (x, y)
              if (z < depth(x, y)) and (z > z_min):
                  depth(x, y) = z
                  colour(x, y) = fragment_colour(x, y)

      Z-buffer showing depth values being tested and updated

      Z-Buffer Precision

      Typically 24 or 32 bits. Often stores 1/z1/z instead of zz for better precision distribution.

      Why 1/z1/z?

      Perspective transformation makes zz non-linear in screen space. Interpolating 1/z1/z gives correct results.

      zscreen=znearzfarzeyez_{\text{screen}} = \frac{z_{\text{near}} \cdot z_{\text{far}}}{z_{\text{eye}}}

      Z-buffer precision showing non-linear depth distribution

      Z-Fighting

      When two surfaces are nearly coplanar, limited precision causes Z-fighting: pixels from both surfaces appear randomly.

      Solutions:

      • Increase depth buffer precision
      • Move surfaces slightly apart
      • Use polygon offset

      Z-fighting artefact showing flickering between two surfaces

      Summary

      • Z-buffer stores depth for each pixel
      • Update pixel only if new fragment is closer
      • Store 1/z1/z for better precision distribution
      • Z-fighting occurs when surfaces are nearly coplanar

      Past Paper Questions

      2025 Paper 3 Question 4(b)(i): In rasterisation, what information does the Z-buffer store? Why is this information needed, and how is it computed? [3 marks]

      2024 Paper 3 Question 3: Explain the Z-buffer algorithm. What happens when two surfaces are at the same depth?

    • Shading Types

      Flat Shading

      • One colour per triangle
      • Normal is constant across the triangle
      • Compute lighting once per triangle
      • Fast but shows faceted surfaces

      Gouraud Shading (Smooth Shading)

      • Lighting computed at each vertex
      • Colours interpolated across the triangle using barycentric coordinates
      • Smooth appearance but may miss highlights inside large triangles

      Phong Shading (Per-Pixel Shading)

      • Normal vectors interpolated across the triangle
      • Lighting equation evaluated per pixel (fragment)
      • Most accurate of the three
      • Computationally more expensive

      Comparison of flat, Gouraud, and Phong shading on a sphere

      Comparison

      MethodLighting ComputedQuality
      FlatPer triangleFaceted
      GouraudPer vertexSmooth but may miss highlights
      PhongPer pixelBest quality

      Summary

      • Flat: one colour per triangle
      • Gouraud: interpolate vertex colours
      • Phong: interpolate normals, compute lighting per pixel

      Past Paper Questions

      2023 Paper 3 Question 4: Compare flat, Gouraud, and Phong shading. When might each be appropriate?

  • OpenGL Pipeline

    GPU architecture, rendering pipeline, shaders, GLSL, VAOs/VBOs, textures and mipmaps

    • GPU Architecture

      What is a GPU?

      A Graphics Processing Unit (GPU) is specialised hardware for graphics rendering:

      • Optimised for floating-point operations on large arrays (vertices, pixels)
      • Massively parallel: hundreds to thousands of SIMD processors
      • High memory bandwidth (>1000 GB/s)
      • Efficiently handles millions of triangles and pixels simultaneously

      What Does a GPU Do?

      • Low-level tasks: Clipping, rasterisation, hidden surface removal
      • High-level tasks: Procedural shading, texturing, animation, simulation
      • Modern GPUs: Ray tracing acceleration, physics, machine learning

      GPU APIs

      An Application Programming Interface (API) provides access to GPU functionality:

      APIPlatformNotes
      OpenGLCross-platformOpen standard, general 3D applications
      DirectXWindows/XboxProprietary, game-focused
      VulkanCross-platformLow-overhead, high performance
      MetalApple devicesLow-level, Swift/Objective-C
      OpenGL ESMobileStripped-down OpenGL for embedded systems
      WebGLBrowserJavaScript, based on OpenGL ES
      WebGPUBrowserAccess to Vulkan/Metal/DirectX 12

      GPGPU: General Purpose Computing

      • CUDA: Nvidia’s parallel computing architecture (C-like)
      • OpenCL: Open standard for parallel computing (AMD, Intel, Nvidia)

      Used for physics simulation, machine learning, scientific computing.

      GPU vs CPU Architecture

      CPU Design

      • Few powerful cores (4-64 typical)
      • Optimised for sequential code and complex logic
      • Large caches per core
      • Branch prediction, out-of-order execution

      GPU Design

      • Many simpler cores (thousands)
      • Optimised for parallel throughput
      • Small caches shared across many threads
      • SIMT (Single Instruction, Multiple Threads) execution

      GPU vs CPU architecture comparison

      Memory Hierarchy

      GPU Memory Types

      • Global memory: Large, high-latency, accessible by all threads
      • Shared memory: Fast, user-managed cache within a block
      • Registers: Fastest, private to each thread
      • Texture memory: Cached, optimised for 2D spatial locality
      • Constant memory: Read-only, cached, broadcast to threads

      Bandwidth Considerations

      Modern GPUs achieve memory bandwidths exceeding 1000 GB/s through:

      • Wide memory buses (256-384 bit)
      • High clock speeds (GDDR6X, HBM2)
      • Multiple memory controllers operating in parallel

      Summary

      • GPUs are massively parallel processors optimised for graphics workloads
      • Multiple APIs exist for GPU access (OpenGL, Vulkan, DirectX, Metal)
      • GPGPU enables general-purpose computation on graphics hardware
      • GPU architecture prioritises throughput over single-thread performance

      Past Paper Questions

      2024 Paper 3 Question 4: What are the key differences between a GPU and a CPU architecture?

      2023 Paper 3 Question 4: Explain what GPGPU means and give two applications.

      2022 Paper 3 Question 4: Why are GPUs more suitable than CPUs for graphics rendering?

    • OpenGL Rendering Pipeline

      OpenGL History

      • OpenGL 1.0 (1992): Fixed-function pipeline
      • OpenGL 2.0 (2004): GLSL shaders introduced
      • OpenGL 3.2 (2009): Core profile, deprecated fixed-function
      • OpenGL 4.5+ (2014+): Modern features, SPIR-V shaders

      Programming Model

      • CPU side: gl* functions to create objects, copy data, modify state
      • GPU side: Shaders written in GLSL (OpenGL Shading Language)

      The Rendering Pipeline

      Full OpenGL pipeline with stages

      Vertex Data → Vertex Shader → Tessellation → Geometry Shader →
      Primitive Assembly → Clipping → Rasterisation → Fragment Shader → Screen Buffer

      Pipeline Stages

      Programmable Stages

      StagePurpose
      Vertex ShaderTransform vertices, pass attributes
      TessellationSubdivide patches into triangles
      Geometry ShaderCreate/modify primitives
      Fragment ShaderCompute pixel colours

      Fixed-Function Stages

      StagePurpose
      Primitive AssemblyOrganise vertices into primitives
      ClippingRemove geometry outside view frustum
      RasterisationGenerate fragments from primitives

      Primitive Assembly

      Organise vertices into primitives (triangles, lines, points) based on drawing mode.

      Clipping

      Remove geometry outside the view frustum:

      • Vertices outside are clipped
      • Edges crossing the boundary are split
      • New vertices generated at clip boundaries

      Rasterisation

      Generate fragments (pixel candidates) for each primitive:

      • Determine which pixels are inside the triangle
      • Interpolate vertex attributes using barycentric coordinates
      • Output fragment positions and interpolated attributes

      Summary

      • OpenGL pipeline combines programmable and fixed-function stages
      • Vertex shader processes individual vertices
      • Fragment shader computes final pixel colours
      • Rasterisation bridges vertex and fragment stages

      Past Paper Questions

      2024 Paper 3 Question 4: Describe the stages of the OpenGL pipeline. Which are programmable?

      2023 Paper 3 Question 4: Explain what happens during rasterisation.

      2022 Paper 3 Question 4: What is the purpose of primitive assembly and clipping in the pipeline?

    • Vertex Shader

      Purpose

      The vertex shader processes each vertex individually:

      • Transform vertex position to clip space
      • Pass attributes to fragment shader
      • Calculate lighting values (if using per-vertex lighting)

      Inputs (Vertex Attributes)

      AttributeDescription
      PositionLocal coordinates (vec3)
      NormalSurface normal for lighting (vec3)
      Texture coordinatesUV mapping (vec2)
      ColoursVertex colours (vec3/vec4)

      Outputs

      • gl_Position: Clip-space position (required)
      • Varying/out variables: Interpolated values for fragment shader

      Example GLSL

      #version 330
      in vec3 position;
      in vec3 normal;
      out vec3 frag_normal;
      uniform mat4 mvp_matrix;
      
      void main() {
          frag_normal = normal;
          gl_Position = mvp_matrix * vec4(position, 1.0);
      }

      Coordinate Transformations

      Model-View-Projection Matrix

      The MVP matrix transforms vertices through coordinate spaces:

      MMVP=MprojectionMviewMmodel\mathbf{M}_{\text{MVP}} = \mathbf{M}_{\text{projection}} \cdot \mathbf{M}_{\text{view}} \cdot \mathbf{M}_{\text{model}}

      Coordinate Spaces

      SpaceDescription
      Model/ObjectOriginal coordinates
      WorldAfter model transformation
      View/CameraRelative to camera
      ClipAfter projection, before perspective divide
      NDCNormalised Device Coordinates (−1 to 1)
      ScreenFinal pixel coordinates

      Vertex Attribute Interpolation

      Attributes are interpolated across the triangle using barycentric coordinates:

      v=αv0+βv1+γv2\mathbf{v} = \alpha \mathbf{v}_0 + \beta \mathbf{v}_1 + \gamma \mathbf{v}_2

      where α+β+γ=1\alpha + \beta + \gamma = 1.

      CPU-Side Drawing Sequence

      1. glUseProgram(shaderProgram): Activate shaders
      2. glBindVertexArray(vao): Bind vertex configuration
      3. glUniformMatrix4fv(...): Upload transformation matrices
      4. glDrawElements(...): Issue draw call

      CPU-GPU communication showing data flow


      Summary

      • Vertex shader processes each vertex once
      • Transforms position to clip space via gl_Position
      • Passes interpolated attributes to fragment shader
      • MVP matrix combines model, view, and projection transforms

      Past Paper Questions

      2025 Paper 3 Question 4(b)(ii): Give 4 examples of vertex attributes. [2 marks]

      2023 Paper 3 Question 4: What is the purpose of a vertex shader? What are its inputs and outputs?

      2022 Paper 3 Question 4: Explain the role of the vertex shader in the OpenGL pipeline.

    • 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

      InputSource
      Interpolated attributesVertex shader outputs
      UniformsGlobal parameters (matrices, lights)
      TexturesImage data sampled by UV coordinates

      Outputs

      • gl_FragColor or out 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

      1. floor(tex_uv * scale): Discretise UV into grid cells
      2. mod(tiled.x + tiled.y, 2.0): Alternate between 0 and 1
      3. Ternary operator: Assign colours based on cell parity

      Vertex and fragment shader data flow

      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

      OperationDescription
      Texture lookupSample from texture using UV
      LightingCompute diffuse, specular contributions
      BlendingCombine with existing framebuffer colour
      DiscardingConditionally 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.

    • 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

      TypeDescription
      floatSingle-precision float
      doubleDouble-precision float
      intSigned integer
      uintUnsigned integer
      boolBoolean

      Vector Types

      TypeDescription
      vec2, vec3, vec4Float vectors
      ivec2, ivec3, ivec4Integer vectors
      dvec2, dvec3, dvec4Double vectors

      Matrix Types

      TypeDescription
      mat22×2 float matrix
      mat33×3 float matrix
      mat44×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

      QualifierPurpose
      inInput to shader (vertex attributes or interpolated)
      outOutput from shader
      uniformGlobal parameter, constant per draw call
      constCompile-time constant
      bufferGPU 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
      • uniform for global data, in/out for 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.

    • Geometry Objects: VAO and VBO

      Vertex Array Object (VAO)

      A VAO encapsulates all vertex attribute state:

      • Which VBOs are bound to which attributes
      • Attribute formats (data type, stride, offset)
      • Enable/disable states for each attribute

      A VAO is a configuration object—it does not store data itself, but describes how to interpret VBO data.

      Vertex Buffer Object (VBO)

      A VBO stores vertex data on GPU memory:

      Data TypeTypical Format
      Positions3 floats per vertex (x, y, z)
      Normals3 floats per vertex (nx, ny, nz)
      Texture coordinates2 floats per vertex (u, v)
      Colours3-4 floats per vertex (r, g, b, a)

      Element Buffer Object (EBO)

      Also called an Index Buffer. Stores indices for indexed drawing:

      • Defines which vertices form each triangle
      • Allows vertex reuse (memory efficient)
      • Reduces data duplication for shared vertices

      VAO containing references to VBO and EBO

      Example: Cube Data

      A cube has 8 vertices but 6 faces with 12 triangles:

      Positions (3 floats/vertex): [x, y, z, x, y, z, ...]
      Normals (3 floats/vertex): [nx, ny, nz, nx, ny, nz, ...]
      Indices (3 ints/triangle): [0, 1, 2, 3, 4, 5, ...]

      Without an EBO: 36 vertices × 3 floats = 108 floats With an EBO: 8 vertices × 3 floats = 24 floats + 36 indices

      Setting Up VAO and VBO

      Creating a VAO

      GLuint vao;
      glGenVertexArrays(1, &vao);
      glBindVertexArray(vao);

      Creating a VBO

      GLuint vbo;
      glGenBuffers(1, &vbo);
      glBindBuffer(GL_ARRAY_BUFFER, vbo);
      glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);

      Configuring Vertex Attributes

      glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
      glEnableVertexAttribArray(0);

      Parameters:

      • Index: Attribute location in shader
      • Size: Components per vertex (1-4)
      • Type: Data type (GL_FLOAT, etc.)
      • Normalised: Whether to normalise
      • Stride: Bytes between successive attributes
      • Pointer: Offset to first component

      Shader Storage Buffer Object (SSBO)

      An SSBO is a GPU memory buffer that shaders can read and write:

      • Much larger data capacity (up to 85% of GPU memory)
      • Supports dynamic arrays and complex data structures
      • Used for GPGPU, particle simulations, advanced lighting

      SSBO buffer access showing read/write paths

      SSBO vs Uniform Buffer

      PropertyUniform BufferSSBO
      Size limit~64 KBUp to GPU memory
      AccessRead-onlyRead/write
      Use caseSmall constantsLarge dynamic data

      Summary

      • VAO stores vertex attribute configuration
      • VBO stores vertex data on GPU
      • EBO enables indexed drawing for efficiency
      • SSBO provides large, writable GPU buffers for advanced techniques

      Past Paper Questions

      2024 Paper 3 Question 4: Explain the purpose of a VAO. What information does it store?

      2023 Paper 3 Question 4: What is the difference between a VBO and an EBO?

      2022 Paper 3 Question 4: Why is using an EBO more memory-efficient than drawing without one?

    • Textures and Mipmaps

      Texture Types

      TypeDimensionsUse Case
      1DLinear arrayGradients, lookup tables
      2DWidth × heightMost common, images
      3DVolume textureMedical imaging, volumetric effects
      Cube map6 facesEnvironment mapping, skyboxes

      1D, 2D, 3D textures and cube map

      Texture Mapping Pipeline

      1. Define texture: Load image (TGA, PNG) as pixel data
      2. Specify UV mapping: Each vertex has texture coordinates (u,v)(u, v)
      3. Sampling: Look up texture colour using interpolated UV

      Texture mapping from 3D model to 2D texture

      Power-of-Two Textures

      GPUs prefer dimensions that are powers of two (2n2^n, e.g., 256, 512, 1024):

      • Better caching and filtering performance
      • Required for mipmaps
      • Non-POT textures may have limited features

      Texture Tiling

      Repeating textures (brick, tile patterns) use wrapped coordinates:

      T(u,v)=T(uu,vv)T(u, v) = T(u - \lfloor u \rfloor, v - \lfloor v \rfloor)

      Example: T(1.1,0)=T(0.1,0)T(1.1, 0) = T(0.1, 0)—the texture wraps.

      Texture Filtering

      Magnification

      Pixel larger than texel (zooming in):

      FilterResult
      Nearest neighbourPick closest texel (blocky)
      BilinearWeighted average of 4 texels (smooth)

      Nearest neighbour vs bilinear interpolation

      Minification

      Pixel smaller than texel (zooming out):

      • Many texels may map to one pixel
      • Causes aliasing and flickering
      • Solution: Use mipmaps

      Mipmaps

      A mipmap is a pre-filtered pyramid of textures at decreasing resolutions:

      • Each level is half the size of the previous
      • Only 1/3 additional storage required: 1+14+116+...=431 + \frac{1}{4} + \frac{1}{16} + ... = \frac{4}{3}
      • Used when textures are minified

      Mipmap pyramid showing decreasing resolutions

      Generating Mipmaps

      glGenerateMipmap(GL_TEXTURE_2D);

      Mipmap Filtering

      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
      ModeDescription
      GL_LINEAR_MIPMAP_NEARESTUse nearest mipmap level, bilinear filtering
      GL_LINEAR_MIPMAP_LINEARTrilinear (interpolate between mipmap levels)

      Texture Parameters

      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

      Wrap Modes

      ModeBehaviour
      GL_CLAMP_TO_EDGEClamp to edge texels
      GL_REPEATTile texture
      GL_MIRRORED_REPEATTile with mirroring

      Advanced Texture Techniques

      TechniqueDescription
      Normal mappingPerturb normals for fake surface detail
      Displacement mappingModify geometry (requires tessellation)
      Environment mappingCube map stores reflections

      Summary

      • Textures store image data sampled using UV coordinates
      • Filtering determines quality: nearest (fast), bilinear (smooth), trilinear (best)
      • Mipmaps pre-filter textures to prevent aliasing when minified
      • POT dimensions preferred for GPU efficiency

      Past Paper Questions

      2024 Paper 3 Question 4: Explain texture filtering. When would you use mipmaps?

      2023 Paper 3 Question 4: What is the difference between GL_NEAREST and GL_LINEAR filtering?

      2022 Paper 3 Question 4: Calculate the additional storage required for mipmaps on a 1024×1024 texture.

  • Human Vision

    Eye anatomy, photoreceptors, cones and rods, luminance and brightness

    • Eye Anatomy

      Structure of the Human Eye

      Cross-section of the human eye showing key components

      Key Components

      ComponentFunction
      CorneaClear front surface, provides most of the eye’s focusing power
      LensFocuses light onto the retina; changes shape for accommodation
      PupilOpening that controls light entry; dilates/contracts
      IrisControls pupil size
      RetinaLight-sensitive layer at the back of the eye
      FoveaHigh-resolution region at the centre of vision
      Optic nerveTransmits signals to the visual cortex

      Inverted Vision

      The lens forms an inverted image on the retina. The brain interprets this correctly—it is the image formed on the retina, not our perception, that is inverted.

      The Lens and Accommodation

      Focusing Mechanism

      The lens changes shape to focus on objects at different distances:

      • Near objects: Lens becomes rounder (greater refractive power)
      • Far objects: Lens becomes flatter (less refractive power)

      This process is called accommodation.

      Refractive Errors

      ConditionCauseEffect
      MyopiaEyeball too long or cornea too curvedDistant objects blurred
      HyperopiaEyeball too short or cornea too flatNear objects blurred
      PresbyopiaLens loses flexibility with ageDifficulty focusing on near objects
      AstigmatismIrregular cornea shapeDistorted vision at all distances

      The Fovea

      The fovea is a small depression in the retina:

      • Contains the highest concentration of cone cells
      • Responsible for sharp central vision
      • Essential for tasks requiring detail: reading, driving, recognising faces

      Visual Field

      • Central vision: Foveal region, high acuity, colour perception
      • Peripheral vision: Outside fovea, motion detection, lower resolution

      Visual field showing acuity distribution

      Eye Movements

      Types of Eye Movements

      MovementPurpose
      SaccadesRapid movements to scan a scene
      PursuitSmooth tracking of moving objects
      VergenceConvergence/divergence for depth perception
      Vestibulo-ocularStabilise image during head movement

      Summary

      • The eye focuses light onto the retina through cornea and lens
      • The fovea provides sharp central vision with high cone density
      • The lens accommodates to focus on objects at varying distances
      • The retina transmits visual information via the optic nerve

      Past Paper Questions

      2024 Paper 3 Question 3: Describe the structure of the human eye and the function of each component.

      2022 Paper 3 Question 3: What is the role of the lens in human vision? How does it accommodate?

      2020 Paper 3 Question 3: Explain the difference between central and peripheral vision.

    • Photoreceptors

      The Retina

      The retina is a layer of photoreceptors (light-detecting cells) that convert light into neural signals.

      Retina cross-section showing photoreceptor arrangement

      Types of Photoreceptors

      TypeFunctionLocation
      ConesDaylight vision, colourConcentrated in fovea
      RodsNight vision, motionPeripheral retina

      Cone Cells: Colour Vision

      Cones are responsible for colour perception. Three types exist, each sensitive to different wavelengths:

      Cone TypePeak SensitivityColour
      L-conesLong wavelength (~560 nm)Red
      M-conesMedium wavelength (~530 nm)Green
      S-conesShort wavelength (~420 nm)Blue

      Spectral sensitivity curves for L, M, and S cones

      Cone Response Formula

      Each cone type outputs a single value—the total light absorbed:

      Lresponse=L(λ)SL(λ)dλL_{\text{response}} = \int L(\lambda) \cdot S_L(\lambda) \, d\lambda

      where L(λ)L(\lambda) is the light spectrum and SL(λ)S_L(\lambda) is the L-cone sensitivity function.

      Limitations of Cone Vision

      We cannot distinguish between:

      • Different spectra that produce the same L, M, S responses (metamers)
      • A single wavelength from a mixture that produces the same response

      Rod Cells: Night Vision

      Rods are specialised for low-light conditions:

      • More sensitive than cones (single photon detection possible)
      • Single type—no colour discrimination in dim light
      • Concentrated in peripheral retina
      • Responsible for motion detection in peripheral vision

      Distribution Across Retina

      Distribution of cones and rods across the retina

      RegionCone DensityRod Density
      Fovea centreMaximumZero
      Fovea peripheryHighLow
      Peripheral retinaLowHigh

      Achromatic vs Chromatic Mechanisms

      Achromatic (Luminance)

      Combines L and M cone signals (L+M):

      • Provides luminance perception
      • High spatial resolution
      • Motion detection

      Chromatic (Colour)

      Compares cone outputs:

      • L−M: Red-green opponent
      • S−(L+M): Blue-yellow opponent

      Achromatic and chromatic signal pathways

      Light Adaptation

      The eye adapts to different light levels:

      Adaptation StateDominant ReceptorCharacteristics
      ScotopicRodsDim light, no colour, high sensitivity
      MesopicMixedTwilight, limited colour
      PhotopicConesDaylight, full colour, lower sensitivity

      Adaptation Time

      • Dark adaptation: ~30 minutes to full sensitivity
      • Light adaptation: Seconds

      Summary

      • Cones provide colour vision; rods provide night vision
      • Three cone types (L, M, S) with different spectral sensitivities
      • Rods are more sensitive but do not detect colour
      • The fovea has maximum cone density; periphery has more rods

      Past Paper Questions

      2024 Paper 3 Question 3: Explain the role of cones and rods in human vision. How do their distributions differ across the retina?

      2023 Paper 3 Question 3: Why do we lose colour perception in dim light?

      2022 Paper 3 Question 3: What are the three types of cone cells? What is their peak sensitivity?

    • Luminance and Brightness

      Luminance Definition

      Luminance is a measure of light weighted by the human visual system’s sensitivity:

      Lv=L(λ)V(λ)dλL_v = \int L(\lambda) \cdot V(\lambda) \, d\lambda

      where:

      • L(λ)L(\lambda) is the spectral radiance
      • V(λ)V(\lambda) is the luminous efficiency function (photopic)

      Luminous Efficiency Function

      V(λ)V(\lambda) represents the eye’s sensitivity at each wavelength for daylight (photopic) vision:

      • Peaks at 555 nm (green)
      • Determined by L and M cone sensitivities
      • Normalised to 1.0 at peak

      Luminous efficiency function V(λ) curve

      Units

      UnitSymbolDescription
      Candela per square metrecd/m²Luminance (also called “nit”)
      Lumen per wattlm/WConversion factor
      Conversion constantk=683.002k = 683.002Converts radiometric to photometric

      Why 555 nm?

      The peak at 555 nm arises from the sum of L and M cone sensitivities:

      V(λ)L(λ)+M(λ)V(\lambda) \approx L(\lambda) + M(\lambda)

      This reflects the evolutionary importance of detecting green light in natural environments.

      Luminance vs Brightness

      Luminance ≠ Brightness

      ConceptNature
      LuminancePhysical measurement weighted by spectral sensitivity
      BrightnessSubjective perceptual experience

      The relationship is non-linear and context-dependent.

      The Electromagnetic Spectrum

      Visible Light Range

      The visible spectrum spans approximately 380 nm to 730 nm:

      Wavelength RangeColour
      380-450 nmViolet, blue
      450-495 nmBlue
      495-570 nmGreen
      570-590 nmYellow
      590-620 nmOrange
      620-730 nmRed

      Electromagnetic spectrum with visible light highlighted

      Why This Range?

      • Earth’s atmosphere transmits light in this range
      • Higher energy than thermal infrared (heat doesn’t interfere)
      • Below UV threshold (tissue damage avoided)

      The Helmholtz-Kohlrausch Effect

      This effect demonstrates luminance ≠ brightness:

      • Highly saturated colours (pure red, blue) appear brighter than desaturated colours (grey) of the same physical luminance
      • Physical luminance calculations alone do not predict perceived brightness
      • Colourfulness contributes to brightness perception

      Example showing two colours with same luminance but different perceived brightness

      Visual Acuity

      Foveal Vision

      • Highest cone density
      • Each cone connects to separate nerve fibre
      • Maximum acuity: ~1 arc minute

      Peripheral Vision

      • Lower resolution
      • Larger receptive fields
      • Better motion detection
      • Better low-light sensitivity (rods)

      Summary

      • Luminance measures light weighted by human spectral sensitivity
      • The luminous efficiency function peaks at 555 nm
      • Luminance is physical; brightness is perceptual
      • The Helmholtz-Kohlrausch effect shows colour saturation affects brightness perception

      Past Paper Questions

      2024 Paper 3 Question 3: What is the luminous efficiency function? How does it relate to cone sensitivity?

      2023 Paper 3 Question 3: Explain the difference between luminance and brightness. Give an example where they differ.

      2022 Paper 3 Question 4: What is the Helmholtz-Kohlrausch effect and what does it demonstrate?

  • Colour Science

    Light and reflectance, tristimulus theory, metamerism, CIE XYZ, RGB spaces, colour transformations

    • Light and Reflectance

      Light and Colour

      Most objects don’t emit light—they reflect it. The colour we perceive depends on:

      1. Illumination: The light source spectrum
      2. Reflectance: How the surface reflects each wavelength

      The Reflectance Equation

      Lreflected(λ)=I(λ)R(λ)L_{\text{reflected}}(\lambda) = I(\lambda) \cdot R(\lambda)

      where:

      • I(λ)I(\lambda) is the illumination spectrum
      • R(λ)R(\lambda) is the surface reflectance function (0 to 1)

      Illumination spectrum × reflectance = reflected light

      Reflectance Properties

      Reflectance Function

      • Defines what fraction of light is reflected at each wavelength
      • Range: R(λ)[0,1]R(\lambda) \in [0, 1]
      • Independent of illumination intensity

      Examples

      SurfaceReflectance Characteristic
      White paperHigh reflectance across all wavelengths
      Red surfaceHigh reflectance in long wavelengths, low elsewhere
      Blue surfaceHigh reflectance in short wavelengths
      Black surfaceLow reflectance across all wavelengths

      Why Colours Change Under Different Lighting

      The same object can appear different under different illumination:

      • White object under red light: Appears red (reflects only red)
      • Blue object under sodium street lights: Appears dark grey (sodium light has no blue component to reflect)

      Metameric Shift

      Two surfaces that match under one light source may not match under another. This is called metameric shift.

      Illuminant Types

      Standard Illuminants

      IlluminantDescriptionColour Temperature
      D65Average daylight6500 K
      D50Horizon daylight5000 K
      AIncandescent tungsten2856 K
      F2Cool white fluorescent4230 K

      Reflectance and Material Perception

      Diffuse Reflection

      Light scattered equally in all directions (matte surfaces):

      Ldiffuse=kdImax(0,nl)L_{\text{diffuse}} = k_d \cdot I \cdot \max(0, \mathbf{n} \cdot \mathbf{l})

      Specular Reflection

      Mirror-like reflection dependent on viewing angle:

      Lspecular=ksImax(0,rv)nL_{\text{specular}} = k_s \cdot I \cdot \max(0, \mathbf{r} \cdot \mathbf{v})^n

      Practical Implications

      Colour Consistency

      • Colour management systems must account for illuminant
      • Print proofs use standardised lighting (D50)
      • Displays assume D65 white point

      Material Appearance

      • Gloss vs matte: Specular vs diffuse reflection ratio
      • Texture: Micro-geometry affects reflectance distribution
      • Subsurface scattering: Light enters and exits at different points

      Summary

      • Perceived colour = illumination × reflectance
      • Reflectance function defines surface colour independent of light source
      • Colours can change under different illumination
      • Different materials have different reflection characteristics

      Past Paper Questions

      2024 Paper 3 Question 3: Explain why a blue object appears dark under sodium street lights.

      2023 Paper 3 Question 3: What is the reflectance function? How does it relate to perceived colour?

      2022 Paper 3 Question 3: A red surface viewed under green light appears dark. Explain why.

    • Tristimulus Colour Representation

      The Key Insight

      Any colour can be matched by combining three linearly independent primary colours.

      This is the foundation of colour science and all colour display technology.

      Colour Matching Experiments

      Historical Experiments (1930s)

      • 2° visual field (fovea only)
      • ~12 observers with normal colour vision
      • Derived the CIE XYZ colour matching functions

      Experimental Setup

      An observer views a split screen:

      • One side: A test colour (monochromatic light)
      • Other side: Adjustable mixture of three primaries

      The observer adjusts the primary intensities until both sides match.

      Colour Matching Functions

      Three functions xˉ(λ)\bar{x}(\lambda), yˉ(λ)\bar{y}(\lambda), zˉ(λ)\bar{z}(\lambda) describe how much of each primary is needed to match monochromatic light at each wavelength.

      CIE 1931 colour matching functions

      Tristimulus Values

      Given a light spectrum L(λ)L(\lambda), the tristimulus values are:

      X=L(λ)xˉ(λ)dλX = \int L(\lambda) \bar{x}(\lambda) d\lambda

      Y=L(λ)yˉ(λ)dλY = \int L(\lambda) \bar{y}(\lambda) d\lambda

      Z=L(λ)zˉ(λ)dλZ = \int L(\lambda) \bar{z}(\lambda) d\lambda

      Why Three Primaries?

      Human Trichromacy

      Human vision is trichromatic because:

      • Three types of cones (L, M, S)
      • Each cone type produces one value
      • Three numbers fully describe colour perception

      Linear Independence

      Three primaries must be linearly independent:

      • No primary can be matched by a mixture of the other two
      • Guarantees a unique solution for any colour

      Primaries are Arbitrary

      Any three linearly independent colours work:

      • Different display technologies use different primaries
      • RGB is common but not unique
      • XYZ primaries are imaginary (not physically realisable)

      Grassmann’s Laws

      Additivity

      If colour A matches B and C matches D, then A+C matches B+D.

      Scalar Multiplication

      If A matches B, then kA matches kB for any k > 0.

      Transitivity

      If A matches B and B matches C, then A matches C.

      Practical Application

      Display Technology

      Displays exploit trichromacy:

      • Three phosphors/LEDs/subpixels (R, G, B)
      • Each pixel is a colour match for the intended spectrum
      • Viewer perceives the target colour

      Limitation

      The match is metameric:

      • Display spectrum differs from real object spectrum
      • But L, M, S cone responses are identical
      • Viewer cannot distinguish

      Summary

      • Any colour can be matched by three primaries (trichromacy)
      • Colour matching functions xˉ\bar{x}, yˉ\bar{y}, zˉ\bar{z} map spectra to XYZ
      • Three primaries work because humans have three cone types
      • Grassmann’s laws govern colour addition

      Past Paper Questions

      2024 Paper 3 Question 3: Explain the principle of tristimulus colour representation. Why do three primaries suffice?

      2023 Paper 3 Question 4: What are colour matching functions? How are they measured?

      2022 Paper 3 Question 3: State Grassmann’s laws of colour matching.

    • Metamerism

      Definition

      Two light spectra that appear identical despite being physically different are called metamers.

      Mathematical Condition

      Two spectra L1(λ)L_1(\lambda) and L2(λ)L_2(\lambda) are metamers if:

      L1(λ)SL(λ)dλ=L2(λ)SL(λ)dλ\int L_1(\lambda) S_L(\lambda) d\lambda = \int L_2(\lambda) S_L(\lambda) d\lambda

      L1(λ)SM(λ)dλ=L2(λ)SM(λ)dλ\int L_1(\lambda) S_M(\lambda) d\lambda = \int L_2(\lambda) S_M(\lambda) d\lambda

      L1(λ)SS(λ)dλ=L2(λ)SS(λ)dλ\int L_1(\lambda) S_S(\lambda) d\lambda = \int L_2(\lambda) S_S(\lambda) d\lambda

      where SLS_L, SMS_M, SSS_S are the cone sensitivity functions.

      Why Metamerism Occurs

      Dimension Reduction

      • Visible light spectrum: Infinite dimensions (continuous function)
      • Human cone response: Only 3 values (L, M, S)
      • Information is lost in the transformation

      One-Way Mapping

      Many different spectra map to the same cone responses:

      Spectrumcones(L,M,S)\text{Spectrum} \xrightarrow{\text{cones}} (L, M, S)

      The reverse mapping is not unique.

      Natural spectrum vs display RGB spectrum producing same perception

      Practical Importance

      Displays

      Displays exploit metamerism:

      • A display emits a narrow RGB spectrum
      • This matches the perception of natural objects with broad spectra
      • The viewer cannot tell the difference

      Example: A sunset captured by a camera is reproduced by mixing three narrow-band LEDs. The spectrum is completely different, but the colour matches perceptually.

      Colour Reproduction

      All colour reproduction relies on metamerism:

      • Printing: CMYK inks spectrum ≠ original reflectance
      • Photography: Sensor spectrum ≠ eye sensitivity
      • Digital displays: RGB primaries ≠ natural light

      Conditions for Metamerism

      Two spectra are metamers if and only if they have identical tristimulus values:

      X1=X2,Y1=Y2,Z1=Z2X_1 = X_2, \quad Y_1 = Y_2, \quad Z_1 = Z_2

      Metameric Failure

      Metamers may not match under different conditions:

      Observer Metamerism

      Different observers have slightly different cone sensitivities:

      • Age-related changes (lens yellows)
      • Genetic variation in cone pigments
      • Colour vision deficiency

      Illuminant Metamerism

      Two surfaces that match under one light may not match under another:

      Light SourceSurface ASurface BMatch?
      D65 (daylight)Spectrum ASpectrum BYes
      A (tungsten)Spectrum ASpectrum BNo

      This is critical for:

      • Textile industry (fabrics must match under store lighting)
      • Automotive (interior materials under various light conditions)
      • Printing (proofing under standard illuminant)

      Applications

      Colour Matching

      • Paint mixing: Find a formulation that matches a target under specified lighting
      • Quality control: Spectral matching vs metameric matching

      Colour Science Research

      • Study of observer variation
      • Development of colour difference metrics
      • Design of colour spaces

      Summary

      • Metamers are different spectra that produce identical colour perception
      • Occurs because spectrum has infinite dimensions but cone response has only 3
      • Displays rely on metamerism to reproduce colours
      • Metameric matches may fail under different observers or illuminants

      Past Paper Questions

      2024 Paper 3 Question 3: Explain metamerism. Why is it important for displays?

      2023 Paper 3 Question 4: Why can two different spectra appear the same colour?

      2022 Paper 3 Question 3: What is illuminant metamerism? Give a practical example.

    • CIE XYZ Colour Space

      Design Goals

      CIE XYZ (1931) was designed with specific objectives:

      1. Abstract from specific display primaries
      2. All colour matching functions positive (no negative light)
      3. The Y value approximates luminance

      XYZ Values

      Given a light spectrum L(λ)L(\lambda), compute XYZ:

      X=L(λ)xˉ(λ)dλX = \int L(\lambda) \bar{x}(\lambda) d\lambda

      Y=L(λ)yˉ(λ)dλY = \int L(\lambda) \bar{y}(\lambda) d\lambda

      Z=L(λ)zˉ(λ)dλZ = \int L(\lambda) \bar{z}(\lambda) d\lambda

      where xˉ\bar{x}, yˉ\bar{y}, zˉ\bar{z} are the CIE colour matching functions.

      CIE 1931 colour matching functions

      Properties of XYZ

      PropertyDescription
      All positiveAll physically realisable colours have X, Y, Z ≥ 0
      Y = LuminanceThe Y value approximates perceived brightness
      Device-independentNot tied to any specific display technology
      Imaginary primariesThe X, Y, Z primaries cannot be physically realised

      Chromaticity Coordinates

      To separate colour from intensity, normalise XYZ:

      x=XX+Y+Z,y=YX+Y+Z,z=ZX+Y+Zx = \frac{X}{X + Y + Z}, \quad y = \frac{Y}{X + Y + Z}, \quad z = \frac{Z}{X + Y + Z}

      Note: x+y+z=1x + y + z = 1, so we only need (x,y)(x, y) to specify chromaticity.

      Why Chromaticity?

      • Removes luminance information
      • Describes “colour” independent of brightness
      • Useful for comparing colours at different intensities

      The Chromaticity Diagram

      CIE xy chromaticity diagram with spectral locus

      Regions

      RegionDescription
      Curved edgePure wavelengths (spectral colours)
      Straight line (bottom)Non-spectral purples (red + blue mixtures)
      InteriorMixtures of wavelengths
      Points outsideNot physically realisable

      Reading the Diagram

      • White point: Near the centre (depends on illuminant)
      • Saturation: Colours near the edge are more saturated
      • Hue: Position around the diagram

      Colour Gamuts

      A gamut is the range of colours a device can reproduce, shown as a triangle on the chromaticity diagram.

      Chromaticity diagram with sRGB, Adobe RGB, Rec. 2020 triangles

      Common Gamuts

      GamutUseSize
      sRGBStandard displays, webSmall
      Adobe RGBPhotography, printingLarger green region
      DCI-P3Digital cinemaMedium-large
      Rec. 2020HDR, ultra-HDVery large

      Why XYZ Matters

      Standard Reference

      • XYZ is the “lingua franca” of colour science
      • All other RGB spaces are defined by transforms to/from XYZ
      • Enables colour communication between different devices

      Advantages

      • No single RGB gamut covers all colours
      • XYZ captures all visible colours
      • Transformations preserve the physical meaning

      Summary

      • CIE XYZ is a device-independent colour space designed in 1931
      • Y approximates luminance; X and Z describe chromaticity
      • Chromaticity coordinates (x, y) separate colour from intensity
      • All visible colours fall within the chromaticity diagram

      Past Paper Questions

      2024 Paper 3 Question 3: What is the CIE XYZ colour space? Why were specific design goals chosen for X, Y, and Z?

      2023 Paper 3 Question 4: Explain the purpose of chromaticity coordinates.

      2022 Paper 3 Question 3: What does the curved edge of the chromaticity diagram represent?

    • RGB Colour Spaces

      RGB Triangle

      An RGB colour space is defined by:

      • Primaries: The chromaticity coordinates (x, y) of red, green, and blue
      • White point: The chromaticity of “white” (usually D65)

      All colours within the RGB triangle on the chromaticity diagram can be reproduced.

      Linear vs Display-Encoded RGB

      Linear RGB

      PropertyDescription
      ValuesProportional to light intensity
      UsePhysical calculations, rendering
      FormatFloating point (0.0 to 1.0, or HDR > 1.0)

      Display-Encoded RGB (sRGB)

      PropertyDescription
      ValuesPerceptually uniform (roughly)
      UseStorage and display
      FormatInteger (0-255)

      Conversion: Linear to Display-Encoded

      For sRGB with γ ≈ 2.2:

      Rlinear=(R/255)γR_{\text{linear}} = (R' / 255)^\gamma

      R=255Rlinear1/γR' = 255 \cdot R_{\text{linear}}^{1/\gamma}

      Prime notation (RR') indicates display-encoded values.

      sRGB Standard

      Properties

      PropertyValue
      PrimariesITU-R BT.709
      White pointD65
      Gamma≈ 2.2 (piecewise function)
      Bit depth8 bits/channel typical

      Piecewise sRGB Transfer Function

      Linear segment near zero, gamma for the rest:

      Vout={12.92VlinearVlinear0.003131.055Vlinear1/2.40.055Vlinear>0.00313V_{\text{out}} = \begin{cases} 12.92 \cdot V_{\text{linear}} & V_{\text{linear}} \leq 0.00313 \\ 1.055 \cdot V_{\text{linear}}^{1/2.4} - 0.055 & V_{\text{linear}} > 0.00313 \end{cases}

      Major RGB Colour Spaces

      ITU-R BT.709 (sRGB)

      Primaryxy
      Red0.640.33
      Green0.300.60
      Blue0.150.06

      Standard for HD video and web.

      ITU-R BT.2020

      Primaryxy
      Red0.7080.292
      Green0.1700.797
      Blue0.1310.046

      Standard for UHD/HDR. Larger gamut than BT.709.

      Adobe RGB

      Extends green primary compared to sRGB:

      • Useful for photography
      • Better gamut for natural greens
      • Requires colour-managed workflow

      CMYK Colour Space

      Subtractive Model

      Printers use cyan, magenta, yellow inks that absorb light:

      InkAbsorbsReflects
      CyanRedGreen + Blue
      MagentaGreenRed + Blue
      YellowBlueGreen + Red

      Why Black (K)?

      Pure CMY mixing gives muddy grey, not true black:

      • Inks are not perfect absorbers
      • Black ink provides true black
      • Black ink is cheaper than CMY overlay
      • Text needs crisp black edges

      Summary

      • RGB spaces are defined by three primaries and a white point
      • Linear RGB for physics; display-encoded for storage
      • sRGB (BT.709) is the standard for web and HD
      • CMYK is subtractive, used for printing

      Past Paper Questions

      2024 Paper 3 Question 3: Explain the difference between linear RGB and sRGB. When would you use each?

      2023 Paper 3 Question 4: What are the primaries of sRGB? Why do different RGB spaces have different primaries?

      2022 Paper 3 Question 3: Why does CMYK need a black (K) channel?

    • Perceptually Uniform Colour Spaces

      The Problem with RGB and XYZ

      Distance in RGB or XYZ space does not correspond to perceived colour difference.

      MacAdam Ellipses

      Experiments showed that colours within an ellipse appear indistinguishable. Ellipses are:

      • Different sizes in different regions of the chromaticity diagram
      • Not circular (distance varies with direction)
      • Much larger in green region than in blue

      MacAdam ellipses showing regions of indistinguishable colours in xy space

      This means equal distances in XYZ do not correspond to equal perceptual differences.

      CIE Lab* (Lab)

      Design

      Lab was designed to be approximately perceptually uniform:

      ChannelMeaningRange
      L*Lightness0 (black) to 100 (white)
      a*Green (−) to Red (+)Approximately −128 to +128
      b*Blue (−) to Yellow (+)Approximately −128 to +128

      Lab colour space visualisation

      Conversion from XYZ

      L=116f(Y/Yn)16L^* = 116 f(Y/Y_n) - 16

      a=500[f(X/Xn)f(Y/Yn)]a^* = 500 [f(X/X_n) - f(Y/Y_n)]

      b=200[f(Y/Yn)f(Z/Zn)]b^* = 200 [f(Y/Y_n) - f(Z/Z_n)]

      where:

      f(t)={t1/3t>δ3t3δ2+429tδ3f(t) = \begin{cases} t^{1/3} & t > \delta^3 \\ \frac{t}{3\delta^2} + \frac{4}{29} & t \leq \delta^3 \end{cases}

      and δ=6/29\delta = 6/29, XnX_n, YnY_n, ZnZ_n are the white point values.

      Properties

      • Euclidean distance ≈ perceptual colour difference
      • Lightness separated from chromaticity
      • Device-independent

      CIE Luv* (Luv)

      Design

      Another approximately perceptually uniform space:

      ChannelMeaning
      L*Lightness (same formula as Lab)
      u’Chromaticity coordinate
      v’Chromaticity coordinate

      Advantages over Lab

      • Uses u’v’ chromaticity (improved uniformity)
      • Better for additive colour mixing
      • Simpler chromaticity diagram projection

      Colour Difference Formulas

      ΔE (Delta E)

      Measures perceptual difference between two colours:

      ΔEab=(L1L2)2+(a1a2)2+(b1b2)2\Delta E_{ab}^* = \sqrt{(L_1^* - L_2^*)^2 + (a_1^* - a_2^*)^2 + (b_1^* - b_2^*)^2}

      ΔE ValuePerceptibility
      < 1.0Not perceptible
      1-2Perceptible through close observation
      2-10Perceptible at a glance
      > 10Definitely different colours

      Use Cases

      SpaceBest For
      Lab/LuvColour difference calculations, colour picker interfaces
      RGBDisplays, rendering
      XYZDevice-independent specification, conversions

      Munsell System

      Historical Context

      Albert H. Munsell (1905) created a perceptually organised system:

      CoordinateMeaning
      HueColour type (R, Y, G, B, P)
      ValueLightness (0-10)
      ChromaSaturation (0 to maximum)

      Properties

      • Perceptually uniform spacing between samples
      • Highly irregular shape (not spherical)
      • Basis for HSV/HSL models

      HSV and HLS colour cylinders

      HSV and HLS

      User-friendly spaces derived from RGB:

      SpaceCoordinates
      HSVHue (0-360°), Saturation (0-100%), Value (0-100%)
      HLSHue (0-360°), Lightness (0-100%), Saturation (0-100%)

      Not perceptually uniform, but intuitive for colour selection interfaces.


      Summary

      • RGB and XYZ distances don’t match perceived differences
      • Lab and Luv are approximately perceptually uniform
      • ΔE measures perceptual colour difference
      • Munsell system inspired modern colour picker interfaces

      Past Paper Questions

      2024 Paper 3 Question 3: Why is RGB not perceptually uniform? What problem does this cause?

      2023 Paper 3 Question 4: Explain the purpose of the Lab colour space. What do L*, a*, and b* represent?

      2022 Paper 3 Question 3: What is ΔE and how is it used?

    • Colour Space Transformations

      Linear Transformations

      Converting between linear RGB spaces is a matrix operation:

      [XYZ]=MRGBXYZ[RGB]\begin{bmatrix} X \\ Y \\ Z \end{bmatrix} = \mathbf{M}_{\text{RGB}\to\text{XYZ}} \begin{bmatrix} R \\ G \\ B \end{bmatrix}

      RGB to XYZ Matrix

      For sRGB (ITU-R 709 primaries):

      M709XYZ=[0.41240.35760.18050.21260.71520.07220.01930.11920.9505]\mathbf{M}_{\text{709}\to\text{XYZ}} = \begin{bmatrix} 0.4124 & 0.3576 & 0.1805 \\ 0.2126 & 0.7152 & 0.0722 \\ 0.0193 & 0.1192 & 0.9505 \end{bmatrix}

      RGB → XYZ → RGB conversion path

      Between RGB Spaces

      To convert from sRGB to Rec. 2020:

      [R2020G2020B2020]=MXYZ2020M709XYZ[R709G709B709]\begin{bmatrix} R_{2020} \\ G_{2020} \\ B_{2020} \end{bmatrix} = \mathbf{M}_{\text{XYZ}\to\text{2020}} \cdot \mathbf{M}_{\text{709}\to\text{XYZ}} \begin{bmatrix} R_{709} \\ G_{709} \\ B_{709} \end{bmatrix}

      Steps

      1. Linearise: Remove gamma encoding
      2. Convert to XYZ: Apply MRGBXYZ\mathbf{M}_{\text{RGB}\to\text{XYZ}}
      3. Convert to target: Apply MXYZRGB1\mathbf{M}_{\text{XYZ}\to\text{RGB}}^{-1}
      4. Re-encode: Apply target gamma

      Computing RGB to XYZ Matrix

      Given primaries (xR,yR)(x_R, y_R), (xG,yG)(x_G, y_G), (xB,yB)(x_B, y_B) and white point (xW,yW)(x_W, y_W):

      Step 1: Form Primary Matrix

      P=[xR/yRxG/yGxB/yB111(1xRyR)/yR(1xGyG)/yG(1xByB)/yB]\mathbf{P} = \begin{bmatrix} x_R/y_R & x_G/y_G & x_B/y_B \\ 1 & 1 & 1 \\ (1-x_R-y_R)/y_R & (1-x_G-y_G)/y_G & (1-x_B-y_B)/y_B \end{bmatrix}

      Step 2: Solve for Scaling Factors

      [SRSGSB]=P1[xW/yW1(1xWyW)/yW]\begin{bmatrix} S_R \\ S_G \\ S_B \end{bmatrix} = \mathbf{P}^{-1} \begin{bmatrix} x_W/y_W \\ 1 \\ (1-x_W-y_W)/y_W \end{bmatrix}

      Step 3: Construct Transform

      MRGBXYZ=[SRxR/yRSGxG/yGSBxB/yBSRSGSBSR(1xRyR)/yRSG(1xGyG)/yGSB(1xByB)/yB]\mathbf{M}_{\text{RGB}\to\text{XYZ}} = \begin{bmatrix} S_R x_R/y_R & S_G x_G/y_G & S_B x_B/y_B \\ S_R & S_G & S_B \\ S_R(1-x_R-y_R)/y_R & S_G(1-x_G-y_G)/y_G & S_B(1-x_B-y_B)/y_B \end{bmatrix}

      Mapping to a Display with Custom Primaries

      Given:

      • Target spectrum L\mathbf{L}
      • Display primary spectra PRGB\mathbf{P}_{\text{RGB}} (N×3 matrix)
      • CIE XYZ matching functions SXYZ\mathbf{S}_{\text{XYZ}} (N×3 matrix)

      Algorithm

      1. Find XYZ of target:

      CXYZ=SXYZL=[XYZ]\mathbf{C}_{\text{XYZ}} = \mathbf{S}_{\text{XYZ}}^\top \mathbf{L} = \begin{bmatrix} X \\ Y \\ Z \end{bmatrix}

      1. Construct primary matrix:

      MRGBXYZ=SXYZPRGB\mathbf{M}_{\text{RGB}\to\text{XYZ}} = \mathbf{S}_{\text{XYZ}}^\top \mathbf{P}_{\text{RGB}}

      1. Solve for RGB:

      [RGB]=MRGBXYZ1CXYZ\begin{bmatrix} R \\ G \\ B \end{bmatrix} = \mathbf{M}_{\text{RGB}\to\text{XYZ}}^{-1} \mathbf{C}_{\text{XYZ}}

      1. Apply display encoding:

      [RGB]=[R1/γG1/γB1/γ]\begin{bmatrix} R' \\ G' \\ B' \end{bmatrix} = \begin{bmatrix} R^{1/\gamma} \\ G^{1/\gamma} \\ B^{1/\gamma} \end{bmatrix}

      Luma Formula

      Luma (display-encoded luminance approximation):

      Y=0.2126R+0.7152G+0.0722BY' = 0.2126 R' + 0.7152 G' + 0.0722 B'

      Important Note

      Luma ≠ Luminance:

      • Luma uses gamma-corrected (display-encoded) values
      • Luminance uses linear values
      • Luma is an approximation for video processing

      Gamut Mapping

      When converting between spaces with different gamuts:

      SituationAction
      Colour inside both gamutsDirect mapping
      Colour outside destinationGamut mapping required

      Gamut Mapping Strategies

      StrategyDescription
      ClippingClip to nearest in-gamut colour
      CompressionReduce saturation proportionally
      PerceptualPreserve relationships, compress into gamut

      Summary

      • Linear RGB to XYZ conversion uses 3×3 matrices
      • Transform between RGB spaces via XYZ intermediate
      • Matrix derivation requires primaries and white point
      • Luma approximates luminance from gamma-encoded values

      Past Paper Questions

      2024 Paper 3 Question 4: How would you convert a colour from sRGB to Rec. 2020? What steps are involved?

      2023 Paper 3 Question 4: Derive the RGB to XYZ transformation matrix given the primaries and white point.

      2022 Paper 3 Question 3: What is the difference between luma and luminance?

  • Tone Mapping

    Gamma correction, display encoding, HDR tone mapping, sigmoidal curves

    • Display Encoding and Gamma

      The Purpose of Gamma

      Display encoding serves two purposes:

      1. Historical: CRT monitors had non-linear response: L=VγL = V^\gamma where γ2.2\gamma \approx 2.2
      2. Perceptual: Human vision is approximately logarithmic; gamma encoding distributes quantisation noise uniformly

      Gamma Correction Equations

      Forward (Encode for Display)

      Vout=Vlinear1/γV_{\text{out}} = V_{\text{linear}}^{1/\gamma}

      Inverse (Decode from Storage)

      Vlinear=VoutγV_{\text{linear}} = V_{\text{out}}^\gamma

      Typical value: γ=2.2\gamma = 2.2 for sRGB.

      Gamma curve showing the encoding/decoding relationship

      Why Not Linear?

      Quantisation Analysis

      Without gamma encoding:

      • Need ~12 bits per channel for visually uniform quantisation
      • Dark regions have visible banding

      With gamma encoding:

      • 8 bits often sufficient
      • More codes allocated to darker values (where eye is sensitive)

      Perceptual Uniformity

      Gamma encoding approximately matches human lightness perception:

      • Weber’s law: ΔL/L\Delta L / L \approx constant
      • Logarithmic response gives uniform perceptual steps

      sRGB Transfer Function

      sRGB uses a piecewise function (not pure gamma):

      Encoding (Linear → sRGB)

      Vout={12.92VlinearVlinear0.003131.055Vlinear1/2.40.055Vlinear>0.00313V_{\text{out}} = \begin{cases} 12.92 \cdot V_{\text{linear}} & V_{\text{linear}} \leq 0.00313 \\ 1.055 \cdot V_{\text{linear}}^{1/2.4} - 0.055 & V_{\text{linear}} > 0.00313 \end{cases}

      Decoding (sRGB → Linear)

      Vlinear={Vout/12.92Vout0.04045(Vout+0.0551.055)2.4Vout>0.04045V_{\text{linear}} = \begin{cases} V_{\text{out}} / 12.92 & V_{\text{out}} \leq 0.04045 \\ \left(\frac{V_{\text{out}} + 0.055}{1.055}\right)^{2.4} & V_{\text{out}} > 0.04045 \end{cases}

      Why Piecewise?

      • Linear segment near zero avoids numerical issues
      • Better approximation of CRT behaviour
      • Matches perceptual uniformity more closely

      EOTF and OETF

      EOTF (Electro-Optical Transfer Function)

      Converts digital signal to display light output:

      StandardEOTF
      sRGB/CRTL=V2.2L = V^{2.2}
      HDR (PQ)Complex piecewise function
      HDR (HLG)Hybrid log-gamma

      OETF (Opto-Electronic Transfer Function)

      Converts light to digital signal (inverse of EOTF):

      StandardOETF
      sRGBV=L1/2.2V = L^{1/2.2} (approximately)
      Camera logVarious (LogC, S-Log, V-Log)

      sRGB in OpenGL

      OpenGL can automate sRGB conversion:

      glEnable(GL_FRAMEBUFFER_SRGB);
      • When enabled, fragments are automatically gamma-encoded
      • sRGB textures are linearised on sampling
      • Ensures correct gamma handling throughout pipeline

      Practical Considerations

      Common Mistakes

      MistakeConsequence
      Applying gamma twiceImage too dark
      Not applying gammaImage too bright, banding
      Mixing linear and gammaIncorrect blending

      Colour Space Awareness

      OperationRequire
      BlendingLinear
      FilteringLinear
      LightingLinear
      StorageGamma-encoded
      DisplayGamma-encoded

      Summary

      • Gamma correction encodes linear values for efficient storage
      • sRGB uses a piecewise function for better accuracy
      • All rendering computations must use linear values
      • OpenGL’s GL_FRAMEBUFFER_SRGB automates conversion

      Past Paper Questions

      2024 Paper 3 Question 3: Why is gamma correction needed? What would happen without it?

      2023 Paper 3 Question 4: Explain the sRGB transfer function. Why is it piecewise?

      2022 Paper 3 Question 3: What operations require linear colour values?

    • HDR Tone Mapping

      The Dynamic Range Problem

      Scene vs Display

      Dynamic range comparison - real world scene vs display capability

      SourceLuminance Range
      Real world10610^{-6} to 10610^6 cd/m² (12+ orders)
      Human vision (adapted)~10,000:1
      SDR display~100:1 to 1,000:1
      HDR display~1,000:1 to 10,000:1

      The challenge: How to represent full scene brightness on a limited display?

      Scene-Referred vs Display-Referred

      TermMeaning
      Scene-referredLinear colours representing actual scene luminance (HDR)
      Display-referredColours ready for a specific display (SDR)

      Tone mapping bridges these two domains.

      What is Tone Mapping?

      Tone mapping transforms image colours from scene-referred to display-referred:

      • Reduces dynamic range to fit the display
      • Preserves important visual details
      • Often combined with display encoding (gamma correction)

      Pipeline from HDR scene → Tone mapping → Display encoding → SDR output

      Why Do We Need It?

      1. Reduce dynamic range for limited displays
      2. Customise look (colour grading, artistic intent)
      3. Simulate human vision (dark adaptation for night scenes)
      4. Adapt to viewing conditions (ambient light)
      5. Make rendered images look more realistic

      Basic Tone Mapping

      Simple Exposure Adjustment

      Rd=RsLsexposureR_d = \frac{R_s}{L_s \cdot \text{exposure}}

      Problems:

      • No contrast compression
      • Only works for moderate dynamic range
      • Clipping occurs if range too large

      Tone Curves

      A tone curve maps input luminance to output:

      Simple tone curve with highlight compression

      RegionPurpose
      Linear (slope 1)Preserves midtones
      ShoulderCompresses highlights
      ToeLifts shadows (optional)

      The ideal tone curve has slope 1 everywhere—but display limitations require compression.

      Global vs Local Tone Mapping

      Global Tone Mapping

      Same curve applied to every pixel:

      AdvantagesDisadvantages
      Simple, fastMay lose local detail
      Consistent
      Reproducible

      Local Tone Mapping

      Different curves for different image regions:

      AdvantagesDisadvantages
      Preserves local contrastCan cause halos at edges
      More detail preservationMore complex

      Comparison of global vs local tone mapping results

      HDR vs SDR Standards

      SDR (Standard Dynamic Range)

      PropertyValue
      Colour spaceITU-R BT.709 (sRGB)
      Dynamic range~6 stops
      Bit depth8-10 bits
      Transfer functionGamma ≈ 2.2

      HDR (High Dynamic Range)

      PropertyValue
      Colour spaceITU-R BT.2020 (wider gamut)
      Transfer functionPQ or HLG
      Bit depth10-12 bits
      Peak brightnessUp to 10,000 cd/m²

      PQ (Perceptual Quantiser)

      Designed for HDR:

      • Based on human contrast sensitivity
      • Peak luminance: 10,000 cd/m²
      • Approximates perceptual uniformity

      HLG (Hybrid Log-Gamma)

      Backwards compatible with SDR:

      • Relative brightness (no absolute reference)
      • SDR displays show reasonable image
      • HDR displays show full range

      Summary

      • Tone mapping compresses HDR scene values to display range
      • Scene-referred (HDR) → Tone mapping → Display-referred (SDR)
      • Global methods apply one curve; local methods vary by region
      • HDR standards (PQ, HLG) support higher brightness ranges

      Past Paper Questions

      2024 Paper 3 Question 3: Explain the difference between scene-referred and display-referred colour. When is each used?

      2023 Paper 3 Question 3: Compare global and local tone mapping approaches.

      2022 Paper 3 Question 3: What is the dynamic range problem in graphics?

    • Sigmoidal Tone Mapping

      Why Sigmoid?

      Sigmoidal curves mimic analog film response:

      • Film was engineered over decades for good tone reproduction
      • Sigmoid shape compresses both highlights and shadows smoothly
      • Preserves midtone contrast

      Sigmoidal Tone Curve

      Shape

      • Toe: Gentle rolloff in shadows
      • Linear region: Steep slope for midtones
      • Shoulder: Gentle rolloff in highlights

      This S-curve naturally compresses extreme values while preserving detail in the midtones.

      The Reinhard Formula

      The standard two-parameter sigmoidal tone curve:

      R(x,y)=R(x,y)b(aLm)b+R(x,y)bR'(x, y) = \frac{R(x, y)^b}{(a \cdot L_m)^b + R(x, y)^b}

      where:

      • R(x,y)R(x, y) is the input linear pixel value
      • LmL_m is the geometric mean (log-average luminance) of the scene
      • aa is the exposure parameter (controls brightness)
      • bb is the contrast parameter (controls S-curve steepness)

      Geometric Mean

      The geometric mean normalises for scene brightness:

      Lm=exp(1N(x,y)ln(L(x,y)))L_m = \exp\left(\frac{1}{N} \sum_{(x,y)} \ln(L(x,y))\right)

      where L(x,y)L(x,y) is the luminance at each pixel.

      Why Geometric Mean?

      • Less affected by extreme values than arithmetic mean
      • Provides stable reference across different scenes
      • Handles HDR values appropriately

      Sigmoid curves with different a and b values

      Parameters

      Exposure Parameter aa

      Controls overall brightness:

      aa ValueEffect
      Smaller aaBrighter image
      Larger aaDarker image

      Mathematical explanation: A smaller aa decreases (aLm)b(a \cdot L_m)^b in the denominator, yielding larger output values.

      Contrast Parameter bb

      Controls curve steepness:

      bb ValueEffect
      Higher bbMore contrast (steeper midtone)
      Lower bbFlatter response (less contrast)

      Higher bb compresses highlights and shadows more aggressively.

      Simplified Formula (b=1b = 1)

      When b=1b = 1:

      R=RaLm+RR' = \frac{R}{a \cdot L_m + R}

      This simpler form is often used for quick approximations.

      Advantages of Sigmoidal Curves

      AdvantageDescription
      Film-like responseFamiliar look for photographers
      Smooth rolloffNo harsh clipping at extremes
      Preserved midtonesGood detail where most visible
      Parameter controlAdjustable exposure and contrast
      Scene adaptationUses geometric mean for automatic scaling

      Practical Implementation

      Algorithm

      1. Compute luminance L(x,y)L(x,y) for each pixel
      2. Calculate geometric mean LmL_m
      3. Apply sigmoidal formula with chosen aa and bb
      4. Output is in [0, 1] range

      Parameter Selection

      Scene TypeTypical aaTypical bb
      Normal daylight0.181.0
      High contrast0.121.5
      Low contrast (fog)0.250.8

      Comparison with Other Methods

      MethodProsCons
      Linear scalingSimpleHarsh clipping
      Reinhard sigmoidSmooth, film-likeMay need parameter tuning
      Local operatorsDetail preservationHalo artefacts

      Summary

      • Sigmoidal tone mapping mimics film response with S-curves
      • Parameters aa (exposure) and bb (contrast) control the curve
      • Geometric mean provides scene-adaptive normalisation
      • Smooth rolloff in highlights and shadows preserves detail

      Past Paper Questions

      2024 Paper 3 Question 3: Explain how sigmoidal tone mapping works. What do the parameters control?

      2023 Paper 3 Question 4: What is the geometric mean and why is it used in tone mapping?

      2022 Paper 3 Question 3: Compare sigmoidal tone mapping to simple exposure adjustment.