Introduction

So far this series has been about getting the right shapes onto the right pixels. But a flat-coloured sphere looks like a flat circle: lighting is what makes a 3D object look 3D. Real light bounces around in incredibly complicated ways, so games use simplified models that look convincing and are cheap to calculate. This post covers the classic model, which is built from three parts, and where to run it:

  • Diffuse light, which makes surfaces facing the light brighter, using Lambert’s cosine law
  • Specular light, the shiny highlight, using the Blinn-Phong model
  • Ambient light, a cheap stand-in for light bouncing around the room
  • The difference between lighting per vertex and per pixel

It brings together nearly everything from the series: normals from part 3, spaces from part 5, and both kinds of shader.

What You Need: Normals and Directions

Lighting at a point on a surface depends on a few directions. Each is a vector (three numbers, like a position) that points somewhere and has a length of exactly 1, called a unit vector. Keeping the length at 1 means only the direction matters:

  • N, the normal: which way the surface faces at this point. It’s stored with each vertex and interpolated across the triangle.
  • L: the direction from the point towards the light. For a far-away light like the sun, it’s the same everywhere.
  • V: the direction from the point towards the camera.

The key tool for comparing two directions is the dot product, written A · B: multiply the matching numbers of the two vectors and add the results, AxBx + AyBy + AzBz. For two unit vectors, it measures how closely they line up: 1 when they point the same way, 0 at right angles, and negative when they point apart, down to −1 when opposite. (It’s the cosine of the angle between them.) It’s just three multiplications and two additions, so lighting code is full of them. (The Dot Product explores it with demos.)

Diffuse: Lambert’s Cosine Law

Think of sunlight as a stream of parallel rays. A beam hitting a surface head-on lands on a small patch, concentrating its energy. Tilt the surface and the same beam spreads over a bigger area, so each bit receives less light: exactly how closely the normal and light direction line up, N · L. This is Lambert’s cosine law, and it gives a matte look, like chalk or unpolished wood. The light scatters equally in all directions, so it looks the same from any viewpoint.

Drag the sun around and tilt the surface below.

The same beam of light spreading over a tilted surface

In a shader, diffuse lighting is a single line:

float diffuse = max(dot(N, L), 0.0);   // 0 when facing away from the light
vec3 colour = diffuse * surfaceColour * lightColour;

Here N is the surface’s normal and L the direction from the surface towards the light, both one unit long; surfaceColour and lightColour are the surface’s and light’s colours. max(a, b) gives whichever is bigger, so surfaces facing away from the light don’t go negative, which would remove light.

Specular: Shiny Highlights

Shiny materials like plastic, metal and wet surfaces also reflect light like a mirror, making a bright highlight where it heads straight towards your eye. Unlike diffuse light, the highlight moves with the camera.

The Blinn-Phong model (Jim Blinn’s 1977 refinement of Bui Tuong Phong’s 1975 model) estimates it with the half vector, H: the direction exactly halfway between L and V. If the surface’s normal lines up with H, the surface is angled to reflect the light straight at the camera, and the highlight is brightest:

vec3 H = normalize(L + V);
float specular = pow(max(dot(N, H), 0.0), shininess);

V is the direction from the surface towards the camera (the viewer). normalize scales a vector to length 1, and pow(x, n) raises x to the power n (multiplies it by itself n times). As N · H is at most 1, a big power makes it fall away fast as the surface turns from the perfect angle. That power, the shininess, sets the highlight’s size: large for a tight sparkle like polished plastic, small for a broad sheen.

Ambient: Faking Bounced Light

In a real room, surfaces facing away from the light aren’t pitch black, because light bounces off everything. Calculating that is expensive, so the classic model adds a small constant amount everywhere, ambient light. It’s crude (real bounced light varies), and modern games use much better techniques, but it stops shadowed sides from being completely black.

Putting It Together

The final colour is the sum of the three terms. Turn them on and off below, change the shininess, and watch the highlight as the light moves (press Pause to hold it still). Drag the object to look at it from different sides and watch the highlight follow you.

Ambient, diffuse and specular lighting on a 3D object

Per Vertex or Per Pixel?

The lighting maths can run in either shader. Early 3D hardware ran it once per vertex and blended the resulting colours across each triangle. This Gouraud shading is cheap, as there are far fewer vertices than pixels, but it can’t show a highlight smaller than a triangle: if one falls mid-triangle, no corner is bright, and it disappears.

Set Work out lighting to Per vertex and lower the Detail: the highlight turns blotchy and star-shaped, crawls across the triangles, and can vanish. Running the maths in the fragment shader, blending the normal instead of the colour, gives a smooth result at any detail. This is often called Phong shading (not the Phong lighting model), and almost every game does it today.

Under the hood

Two details are easy to get wrong. First, an interpolated normal is no longer exactly length 1 (blending two unit vectors gives a shorter one), so the fragment shader must normalize it again, or the lighting dims towards the middle of each triangle. Second, normals can’t always be transformed by the same matrix as positions: if an object is stretched unevenly, its normals would tilt the wrong way. They use the normal matrix, made by inverting (part 6) and transposing (part 8) the top-left 3×3 corner of the model matrix, passed in as a uniform. And lighting maths should use linear light values, converted to the screen’s sRGB encoding at the end: the demo’s shader ends with pow(c, 1.0 / 2.2), where c is the finished colour in linear light and the power 1 Ă· 2.2 approximates sRGB. The sRGB and gamma post explains why.

Beyond Blinn-Phong

This model has been used in countless games, but it isn’t based on real physics: the highlight can reflect more light than arrived, and the settings don’t match real materials. Modern games use physically based rendering (PBR), which describes materials by properties like roughness and metalness and conserves energy. It’s built from the same ingredients: N, L, V, H and dot products.

Questions You Might Have

What about more than one light?

Work out the diffuse and specular light from each light separately and add them together (ambient is usually added once). Light simply adds up, which is also why the sums are done in linear light (sRGB and Gamma).

Summary

  • Lighting uses directions: the normal N, the direction to the light L and to the camera V.
  • Diffuse light follows Lambert’s cosine law: brightness = max(N · L, 0).
  • Specular highlights in Blinn-Phong use the half vector: pow(max(N · H, 0), shininess).
  • Ambient adds a constant to fake bounced light.
  • Lighting per pixel looks far better than per vertex, because it doesn’t miss highlights inside triangles.

That’s the end of Graphics Fundamentals! You now know the whole journey from triangles to lit pixels. From here, the Textures & Sampling series looks at how images are wrapped onto these surfaces.

Further Reading