The rasterizer from two lessons ago knew which pixels each triangle covers, but it left the decisive question blank: what color to paint them. If we paint the whole hull of the ship the same gray, we will see a flat outline; what makes an object look three-dimensional is that its faces receive different amounts of light depending on which way they face. Computing that light is, almost entirely, a matter of dot products between three vectors: the surface normal, the direction toward the light and the direction toward the observer. In this lesson we build the classic lighting model—ambient, diffuse and specular—the different types of light, the correct way of transforming normals and the three ways of distributing the calculation over a triangle: flat, Gouraud and Phong shading.
The code assumes that the functions from the previous lessons (normalize, dot_product, direction_to, distance, reflect, ray_sphere, triangle_normal, spherical_to_cartesian, transform_point, transform_direction, look_at_matrix, interpolate_attribute...) and the scene data are already defined: ship, lamp, camera, hull_model and ship_world.
What a local lighting model needs
A local lighting model computes the color of a point on a surface taking into account only that point, the lights and the observer, as if there were no other objects in the scene. It knows nothing of cast shadows or of light bounced between surfaces; in exchange, it is extremely fast. It needs three vectors, all three unit vectors and all three starting at the point being lit:
| Vector | Meaning | How it is obtained |
|---|---|---|
| \(\hat{\mathbf{N}}\) | Surface normal | From the mesh (face or vertex normal) or from the formula of the surface |
| \(\hat{\mathbf{L}}\) | Direction toward the light | direction_to(point, light) |
| \(\hat{\mathbf{V}}\) | Direction toward the observer | direction_to(point, eye) |
Two more are computed from them: \(\hat{\mathbf{R}}\), the direction in which the surface reflects the light like a mirror, and \(\hat{\mathbf{H}}\), the halfway vector between \(\hat{\mathbf{L}}\) and \(\hat{\mathbf{V}}\).
Let us fix the point that will accompany us throughout the lesson: the point \(P = \left(\tfrac{26}{3}, \tfrac{10}{3}, \tfrac{13}{3}\right) \approx (8.67, 3.33, 4.33)\) on the hull where the lighthouse beam hits. It is on the face formed by the tail, the top and the right wing, whose normal is \(\hat{\mathbf{N}} = (-1, 4, -2)/\sqrt{21} \approx (-0.218, 0.873, -0.436)\). That face looks upward and backward, and the usual camera does not see it; we will observe it from the surveillance camera on beacon Alpha, at \((12, 7, 4)\).
Types of light
| Type | Defined with | Direction \(\hat{\mathbf{L}}\) | Intensity | Example |
|---|---|---|---|---|
| Ambient | A color | It has none | Constant everywhere | Diffuse light from the surroundings |
| Directional | A direction and a color | The same for every point | Constant | A distant star |
| Point | A position and a color | From the point to the light: it changes at each point | Decreases with distance | A beacon, a light bulb |
| Spot | Position, axis, cone angles and color | From the point to the light | Decreases with distance and outside the cone | The lighthouse lamp, a flashlight |
Ambient light is a fudge: a small amount of light that reaches everywhere equally, so that the areas that receive no direct light are not left completely black. It stands in, very crudely, for all the light that in reality bounces from one object to another.
A directional light is a point light so far away that its rays arrive parallel. It is the cheapest: there is no need to compute \(\hat{\mathbf{L}}\) or distances.
Distance attenuation
The energy of a point light is spread over ever larger spheres. The area of a sphere grows with \(d^2\), so the light a surface receives decreases with the square of the distance: at twice the distance, a quarter. Classic engines use a somewhat more flexible formula, with three coefficients that the artist adjusts:
\[ \text{atten}(d) = \frac{1}{k_c + k_l,d + k_q,d^2} \]
With \(k_c = 1\) the intensity is prevented from blowing up as \(d\) tends to 0; \(k_q\) is the physically correct term and \(k_l\) softens the falloff. For the lighthouse lamp we will use \((1,\ 0.05,\ 0.005)\).
The cone of a spotlight
A spotlight only lights inside a cone around its axis. A point is inside if the angle between the axis and the direction from the light to the point, \(-\hat{\mathbf{L}}\), is less than the half-angle: the in_view_cone test from "Dot Product and Cross Product". As there, cosines are compared instead of angles. So that the edge is not an abrupt cutoff, two angles are used: inside the inner cone the light is full; outside the outer one, zero; and between the two it is interpolated:
\[ \text{spot} = \operatorname{clamp}\left(\frac{\cos\alpha - \cos\theta_{\text{ext}}}{\cos\theta_{\text{int}} - \cos\theta_{\text{ext}}},\ 0,\ 1\right) \qquad \cos\alpha = \hat{\mathbf{e}} \cdot (-\hat{\mathbf{L}}) \]
where \(\operatorname{clamp}\) restricts the value to the interval \([0, 1]\).
import numpy as np
np.set_printoptions(suppress=True)
def attenuation(distance, constant=1.0, linear=0.0, quadratic=0.0):
"""Attenuation factor of a point light: 1 / (kc + kl d + kq d^2)."""
return 1.0 / (constant + linear * distance + quadratic * distance * distance)
def spot_factor(axis, l, inner_angle, outer_angle):
"""1 inside the inner cone, 0 outside the outer one and a smooth transition between the two.
axis: unit direction in which the spotlight points; l: unit direction from the point to the light.
"""
cosine = dot_product(axis, -np.asarray(l, dtype=float))
c_int, c_ext = np.cos(inner_angle), np.cos(outer_angle)
return float(np.clip((cosine - c_ext) / (c_int - c_ext), 0.0, 1.0))
p = np.array([26.0, 10.0, 13.0]) / 3.0
n = np.array([-1.0, 4.0, -2.0]) / np.sqrt(21.0)
l = direction_to(p, lamp)
lighthouse_axis = direction_to(lamp, ship) # the lamp points at the center of the ship
print(np.round(l, 4), round(distance(p, lamp), 4))
print(round(attenuation(13.0, 1.0, 0.05, 0.005), 4))
print(round(np.degrees(np.arccos(dot_product(lighthouse_axis, -l))), 2),
round(spot_factor(lighthouse_axis, l, np.radians(6.0), np.radians(10.0)), 4))The point is 13 m from the lamp, and the attenuation lets 40% of the light through: \(1/(1 + 0.65 + 0.845)\). The lamp points at the center of the ship, and our point lies 7.67° off the axis: between the inner cone (6°) and the outer one (10°), in the penumbra, with a factor of 0.64.
Diffuse light: Lambert's law
A matte surface (plaster, stone, flat paint) scatters the light it receives equally in all directions. Its appearance does not depend on where the observer is: only on how much light reaches it. And that depends on its tilt.
Imagine a beam of light of cross-section \(A\) (one square meter, for example). If it strikes perpendicularly, it lights an area of exactly \(A\). If the surface is tilted by an angle \(\theta\) relative to the beam, the same light is spread over an elongated patch, of area \(A / \cos\theta\): each square meter receives less. The energy per unit of surface ends up multiplied by \(\cos\theta\).
That angle \(\theta\) is the one formed by the normal and the direction toward the light. Since both vectors are unit vectors, its cosine is their dot product. This is Lambert's law:
\[ \text{diffuse} = \max\big(0,\ \hat{\mathbf{N}} \cdot \hat{\mathbf{L}}\big) \]
| Angle between \(\hat{\mathbf{N}}\) and \(\hat{\mathbf{L}}\) | \(\hat{\mathbf{N}} \cdot \hat{\mathbf{L}}\) | Situation |
|---|---|---|
| 0° | 1 | The light strikes head-on: maximum illumination |
| 60° | 0.5 | Half |
| 90° | 0 | Grazing light |
| More than 90° | Negative → 0 | The light is behind the surface |
The \(\max(0, \cdot)\) is essential: a negative dot product means the face has its back to the light. Without it, light would be subtracted. It is the same "in front or behind" test as in Module 3.
Example. At the point \(P\), \(\hat{\mathbf{L}} = \left(-\tfrac{2}{3}, \tfrac{2}{3}, -\tfrac{1}{3}\right)\) (the beam arrived with direction \(\left(\tfrac{2}{3}, -\tfrac{2}{3}, \tfrac{1}{3}\right)\); toward the light is the opposite):
\[ \hat{\mathbf{N}} \cdot \hat{\mathbf{L}} = \frac{(-1)(-2) + 4 \cdot 2 + (-2)(-1)}{3\sqrt{21}} = \frac{12}{3\sqrt{21}} = \frac{4}{\sqrt{21}} \approx 0.873 \]
The light arrives 29.2° off the normal: the face receives 87% of what it would receive head-on.
Specular light: the Phong model
Polished surfaces (metal, plastic, gloss paint) also have highlights: reflections of the light source itself. Unlike diffuse light, the highlight depends on the observer: it is seen only from near the direction in which the surface reflects the light like a mirror.
We have known how to compute that direction since "Distances and Geometric Projections". The light travels in the direction \(-\hat{\mathbf{L}}\), and its reflection off a surface with normal \(\hat{\mathbf{N}}\) is:
\[ \hat{\mathbf{R}} = \operatorname{reflect}(-\hat{\mathbf{L}},\ \hat{\mathbf{N}}) = 2,(\hat{\mathbf{N}} \cdot \hat{\mathbf{L}}),\hat{\mathbf{N}} - \hat{\mathbf{L}} \]
The Phong model measures how well aligned the observer is with that reflection, \(\hat{\mathbf{R}} \cdot \hat{\mathbf{V}}\), and raises it to an exponent:
\[ \text{specular} = \max\big(0,\ \hat{\mathbf{R}} \cdot \hat{\mathbf{V}}\big)^{b} \]
The exponent \(b\) is the shininess of the material. Raising a number between 0 and 1 to a power makes it smaller, all the more so the larger the exponent: only values very close to 1 survive.
| Shininess \(b\) | Appearance of the reflection | Material |
|---|---|---|
| 2–10 | Broad, soft patch | Rubber, matte plastic |
| 30–100 | Well-defined point of light | Glossy plastic, paint |
| 200 or more | Small, sharp glint | Polished metal |
Example. At \(P\), with \(\hat{\mathbf{N}} \cdot \hat{\mathbf{L}} = 4/\sqrt{21}\):
\[ \hat{\mathbf{R}} = 2 \cdot \frac{4}{\sqrt{21}} \cdot \frac{(-1, 4, -2)}{\sqrt{21}} - \frac{(-2, 2, -1)}{3} = \frac{(-8, 32, -16)}{21} - \frac{(-14, 14, -7)}{21} = \frac{(6, 18, -9)}{21} = \frac{(2, 6, -3)}{7} \]
The beam, which was coming down toward the ship, bounces upward. The camera on beacon Alpha sees the point in the direction \(\hat{\mathbf{V}} = (0.671, 0.738, -0.067)\), and \(\hat{\mathbf{R}} \cdot \hat{\mathbf{V}} = 0.853\): it is 31.4° off the perfect reflection. With shininess 32, \(0.853^{32} = 0.006\): practically outside the highlight.
Blinn-Phong: the halfway vector
The Blinn-Phong variant avoids computing \(\hat{\mathbf{R}}\). It uses the halfway vector, the bisector between the direction to the light and the direction to the observer:
\[ \hat{\mathbf{H}} = \frac{\hat{\mathbf{L}} + \hat{\mathbf{V}}}{\lVert \hat{\mathbf{L}} + \hat{\mathbf{V}} \rVert} \qquad\qquad \text{specular} = \max\big(0,\ \hat{\mathbf{N}} \cdot \hat{\mathbf{H}}\big)^{b} \]
The idea: \(\hat{\mathbf{H}}\) is the normal the surface would have to have in order to reflect the light exactly toward the observer. The more the real normal resembles \(\hat{\mathbf{H}}\), the stronger the highlight. If the observer is right on the reflection, \(\hat{\mathbf{H}} = \hat{\mathbf{N}}\) and the highlight is at its maximum, just as in Phong.
| Phong | Blinn-Phong | |
|---|---|---|
| What is compared | \(\hat{\mathbf{R}}\) with \(\hat{\mathbf{V}}\) | \(\hat{\mathbf{N}}\) with \(\hat{\mathbf{H}}\) |
| Angle measured | The observer's angle from the reflection | Approximately half of the former |
| With the same exponent | Smaller highlight | Broader highlight |
| Equivalent exponent | \(b\) | About \(4b\) |
| Grazing angles | The highlight is cut off abruptly | It stretches out, as in reality |
| Cost | One reflection per light | One addition and one normalization |
The angle between \(\hat{\mathbf{N}}\) and \(\hat{\mathbf{H}}\) is approximately half the angle between \(\hat{\mathbf{R}}\) and \(\hat{\mathbf{V}}\) (exactly half when the four vectors lie in the same plane), and that is why an exponent about four times larger is needed to obtain a highlight of the same size. Blinn-Phong was for decades the default model of graphics cards.
def diffuse_light(n, l):
"""Lambert's diffuse factor: cosine of the angle between the normal and the direction to the light."""
return max(0.0, dot_product(n, l))
def specular_light_phong(n, l, v, shininess):
"""Phong specular factor: (R . V)^shininess, with R the reflection of the light off the normal."""
if dot_product(n, l) <= 0.0:
return 0.0 # the light arrives from behind
r = reflect(-np.asarray(l, dtype=float), n)
return max(0.0, dot_product(r, v)) ** shininess
def specular_light_blinn(n, l, v, shininess):
"""Blinn-Phong specular factor: (N . H)^shininess, with H the halfway vector between L and V."""
if dot_product(n, l) <= 0.0:
return 0.0
h = normalize(np.asarray(l, dtype=float) + np.asarray(v, dtype=float))
return max(0.0, dot_product(n, h)) ** shininess
alpha = np.array([12.0, 7.0, 4.0])
v = direction_to(p, alpha)
r = reflect(-l, n)
h = normalize(l + v)
print(round(diffuse_light(n, l), 4), np.round(r * 7.0, 4), np.round(v, 4), np.round(h, 4))
print(round(np.degrees(np.arccos(dot_product(r, v))), 2),
round(np.degrees(np.arccos(dot_product(n, h))), 2))
for shininess in (8, 32, 128):
print(shininess, round(specular_light_phong(n, l, v, shininess), 4),
round(specular_light_blinn(n, l, v, shininess), 4))0.8729 [ 2. 6. -3.] [ 0.6712 0.7383 -0.0671] [ 0.0031 0.9617 -0.2741] 31.42 16.59 8 0.2811 0.7118 32 0.0062 0.2567 128 0.0 0.0043
The angles are 31.42° (Phong) and 16.59° (Blinn-Phong): approximately half. And the factor-of-4 rule holds fairly well: Phong with shininess 8 gives 0.28 and Blinn-Phong with shininess 32 gives 0.26; Phong with 32 gives 0.006 and Blinn-Phong with 128 gives 0.004. From here on we will use Blinn-Phong.
Both functions return 0 if the light arrives from behind the surface: without that check a highlight could appear on a face that receives no light.
The complete model
The final color is the sum of three terms: ambient + diffuse + specular. We still have to say how colors come into it.
A color is an RGB triple with the amounts of red, green and blue, between 0 and 1. There are two kinds:
- The color of the light: how much energy it emits in each channel.
- The color of the material: what fraction of the light it receives in each channel it gives back. A red surface, \((1, 0, 0)\), reflects red and absorbs the rest.
The reflected light is the component-by-component product of the two (it is neither a dot product nor a cross product): each channel is filtered separately. A red surface under green light looks black, \((1, 0, 0) \odot (0, 1, 0) = (0, 0, 0)\).
A classic material has a diffuse color \(\mathbf{k}_d\) (its "own" color), a specular color \(\mathbf{k}_s\) (that of its highlights; white or gray in plastics, the color of the metal in metals) and a shininess \(b\). The complete model, with several lights:
\[ \mathbf{C} = \mathbf{c}{\text{amb}} \odot \mathbf{k}d ;+; \sum{\text{lights}} f \cdot \mathbf{c}{\text{light}} \odot \Big[\mathbf{k}_d,\max(0,\ \hat{\mathbf{N}} \cdot \hat{\mathbf{L}}) + \mathbf{k}_s,\max(0,\ \hat{\mathbf{N}} \cdot \hat{\mathbf{H}})^{b}\Big] \]
where \(f\) is the product of the attenuation and the spot factor (1 for a directional light). Two remarks:
- Lights add up. Lighting is linear: two lights give the sum of what each one would give.
- The result can exceed 1. A screen cannot show more than 1 in each channel, so at the end the color is clamped: each component is cut off to \([0, 1]\). A saturated area looks "burnt out", with no detail. For that very reason the color of a light can indeed be greater than 1: it represents its intensity, and the attenuation will take care of bringing it down.
def shade_point(point, normal, eye, material, lights, ambient=(0.05, 0.05, 0.08)):
"""RGB color of a point: ambient + sum of diffuse and specular (Blinn-Phong) of each light."""
point = np.asarray(point, dtype=float)
diffuse = np.asarray(material["diffuse"], dtype=float)
specular = np.asarray(material["specular"], dtype=float)
v = direction_to(point, eye)
color = np.asarray(ambient, dtype=float) * diffuse
for light in lights:
if light["type"] == "directional":
l, factor = np.asarray(light["direction"], dtype=float), 1.0
else: # point or spot
l = direction_to(point, light["position"])
factor = attenuation(distance(point, light["position"]), *light["attenuation"])
if light["type"] == "spot":
factor *= spot_factor(light["axis"], l, *light["angles"])
reflected = (diffuse * diffuse_light(normal, l)
+ specular * specular_light_blinn(normal, l, v, material["shininess"]))
color = color + factor * np.asarray(light["color"], dtype=float) * reflected
return np.clip(color, 0.0, 1.0)A material and a light are dictionaries. In a directional light, "direction" is the unit vector toward the light. The * operator between NumPy arrays is precisely the component-by-component product, and np.clip does the clamping.
Example: the lighthouse lamp lights the hull
We define the hull's material (a bluish gray with almost white highlights), the lighthouse lamp (warm light, of intensity 2) and a distant star that contributes a faint directional light.
hull_material = {"diffuse": (0.6, 0.65, 0.7), "specular": (0.9, 0.9, 0.9), "shininess": 32.0}
lighthouse_light = {"type": "spot", "position": lamp, "color": (2.0, 1.9, 1.6),
"attenuation": (1.0, 0.05, 0.005), "axis": lighthouse_axis,
"angles": (np.radians(6.0), np.radians(10.0))}
star_light = {"type": "directional", "direction": np.array([0.36, 0.8, 0.48]),
"color": (0.3, 0.3, 0.35)}
print(np.round(shade_point(p, n, alpha, hull_material, []), 4))
print(np.round(shade_point(p, n, alpha, hull_material, [lighthouse_light]), 4))
print(np.round(shade_point(p, n, alpha, hull_material, [star_light]), 4))
print(np.round(shade_point(p, n, alpha, hull_material, [lighthouse_light, star_light]), 4))
intense_light = dict(lighthouse_light, color=(8.0, 7.6, 6.4))
print(np.round(shade_point(p, n, alpha, hull_material, [intense_light]), 4))[0.03 0.0325 0.056 ] [0.4193 0.4238 0.4035] [0.1038 0.1125 0.1565] [0.4932 0.5038 0.504 ] [1. 1. 1.]
Let us reconstruct by hand the second line, the one with the lighthouse alone:
- Ambient: \((0.05, 0.05, 0.08) \odot (0.6, 0.65, 0.7) = (0.03, 0.0325, 0.056)\).
- Light factor: attenuation × spot \(= 0.4008 \cdot 0.6435 = 0.2579\).
- Diffuse: \(0.8729 \cdot (0.6, 0.65, 0.7) = (0.524, 0.567, 0.611)\).
- Specular: \(0.2567 \cdot (0.9, 0.9, 0.9) = (0.231, 0.231, 0.231)\).
- Sum, filtered by the color of the light and by the factor: \(0.2579 \cdot (2, 1.9, 1.6) \odot (0.755, 0.798, 0.842) = (0.389, 0.391, 0.347)\).
- Total: \((0.03, 0.0325, 0.056) + (0.389, 0.391, 0.347) = (0.419, 0.424, 0.404)\).
The result is a slightly warm mid-gray: the material is bluish, but the lighthouse's light has less blue. The star alone gives a faint, bluish tone; with both lights, the colors add up. And with a lamp four times as intense, all three channels exceed 1 and the point saturates to pure white.
How normals are transformed
Normals are stored in local space, with the mesh. To light in the world they have to be transformed, and here there is a trap that we announced in "Representing 3D Objects": a normal is not transformed with the model matrix, except in particular cases.
A normal is a direction, so translation does not affect it: only the 3×3 block \(M\) counts. But a normal is not just any direction: it is defined by being perpendicular to the surface, and that is the relationship that must be preserved. A non-uniform scaling does not preserve angles. Think of a ramp at 45°: if it is stretched to twice its length horizontally, it becomes shallower, and its normal must become more vertical; but if we stretch the normal to twice its length horizontally, it becomes more horizontal. Exactly the opposite.
The correct matrix
Let \(\mathbf{t}\) be a vector tangent to the surface (an edge of a triangle, for example) and \(\mathbf{n}\) the normal: \(\mathbf{n} \cdot \mathbf{t} = 0\), which in matrix form is \(\mathbf{n}^T \mathbf{t} = 0\). Tangents are differences of points and they are indeed transformed with \(M\): \(\mathbf{t}' = M,\mathbf{t}\). We look for a matrix \(G\) such that \(\mathbf{n}' = G,\mathbf{n}\) is still perpendicular to \(\mathbf{t}'\):
\[ (G,\mathbf{n})^T (M,\mathbf{t}) = \mathbf{n}^T,G^T M,\mathbf{t} = 0 \]
This holds for every tangent if \(G^T M = I\), that is:
\[ G = \left(M^{-1}\right)^T \]
Normals are transformed with the inverse transpose of the model matrix, and then normalized.
| Type of matrix \(M\) | \(\left(M^{-1}\right)^T\) | Consequence |
|---|---|---|
| Rotation | \(M\) (because \(M^{-1} = M^T\)) | \(M\) can be used directly |
| Rotation + uniform scaling \(s\) | \(M / s^2\) | \(M\) will do, normalizing afterward |
| Non-uniform scaling, shear | A different matrix | The inverse transpose must be used |
Demonstration with the hull
The hull's matrix, \(T(8, 3, 6),N,S(4, 1, 2)\), has a non-uniform scaling. In the local octahedron, the face of our point \(P\) is the one with vertices \((0, 0, -1)\), \((0, 1, 0)\) and \((1, 0, 0)\), with normal \((1, 1, -1)/\sqrt{3}\).
- Wrong (with \(M = N,S\)): \(S,(1, 1, -1) = (4, 1, -2)\), and \(N,(4, 1, -2) = (0.8, 1, -4.4)\). Normalized: \((0.175, 0.218, -0.960)\).
- Right (with \(N,S^{-1}\), since \(\left((N S)^{-1}\right)^T = N,S^{-1}\)): \(S^{-1}(1, 1, -1) = (0.25, 1, -0.5)\), and \(N,(0.25, 1, -0.5) = (-0.25, 1, -0.5)\). Normalized: \((-0.218, 0.873, -0.436)\).
Note the effect of the inverse scaling: the hull is stretched 4 times in X, and the \(x\) component of the normal is divided by 4.
def normal_matrix(model):
"""3x3 matrix that transforms normals: the inverse transpose of the model's linear block."""
return np.linalg.inv(np.asarray(model, dtype=float)[:3, :3]).T
normal_local = np.array([1.0, 1.0, -1.0]) / np.sqrt(3.0)
wrong = normalize(hull_model[:3, :3] @ normal_local)
correct = normalize(normal_matrix(hull_model) @ normal_local)
print(np.round(wrong, 4), np.round(correct, 4))
tail, top, wing = np.array([6.4, 3.0, 4.8]), np.array([8.0, 4.0, 6.0]), np.array([10.4, 3.0, 2.8])
print(np.round([wrong @ (top - tail), wrong @ (wing - tail)], 4),
np.round([correct @ (top - tail), correct @ (wing - tail)], 4) + 0.0)
print(round(np.degrees(np.arccos(wrong @ correct)), 2), round(diffuse_light(wrong, l), 4), round(diffuse_light(correct, l), 4))
print(np.allclose(normal_matrix(ship_world), ship_world[:3, :3]))The correctly transformed normal is the one we have used all lesson, and it is perpendicular to the two edges of the face in the world (zero dot products). The wrongly transformed one is perpendicular to neither, deviates 55° from the correct one and would give a diffuse illumination of 0.35 instead of 0.87: the face would look much darker than it should. The last line confirms that for a rigid matrix such as the ship's (with no scale) the normal matrix coincides with the rotation itself.
Shading models: flat, Gouraud and Phong
The lighting model says how to compute the color at a point. A triangle covers many pixels: at how many points is it evaluated, and with which normal? There are three classic answers, the shading models.
| Flat shading | Gouraud shading | Phong shading | |
|---|---|---|---|
| The lighting is computed | Once per face | Once per vertex | Once per pixel |
| Normal used | The face normal | The normal of each vertex | The vertex normals, interpolated and renormalized |
| What is interpolated | Nothing | The colors | The normals (and the position) |
| Appearance | Visible facets | Smooth; poor or lost highlights | Smooth, with correct highlights |
| Cost | Minimal | Low | The highest |
| Suitable for | Truly faceted objects | Matte surfaces | Today's standard |
We have all the pieces: the face and vertex normals from "Representing 3D Objects", and the barycentric interpolation (with perspective correction) from "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer".
Phong shading (interpolating normals) must not be confused with the Phong reflection model (the specular term with \(\hat{\mathbf{R}}\)): they are two different ideas by the same author. Phong shading can be done with Blinn-Phong reflection, which is the usual combination.
Two details of Phong shading:
- The interpolated normal has to be renormalized: a blend of unit vectors is, in general, shorter than 1 (we saw this when interpolating quaternions with lerp).
- For a sharp-edged object such as our octahedral hull, flat shading is not a poor approximation but the correct one: its faces are flat.
Comparison on the lighthouse dome
Where the difference becomes obvious is in the highlights of a curved surface tessellated with few triangles. Take a large triangle of the lighthouse dome (a hemisphere of radius 1.5 centered at \((0, 12, 0)\)), with its exact vertex normals, which on a sphere are radial. The dome is made of bluish, very shiny glass; the camera observes it from \((0, 5, 20)\), and we place the light so that the reflection falls right at the center of the triangle.
dome_center, dome_radius = np.array([0.0, 12.0, 0.0]), 1.5
triangle = np.array([dome_center + spherical_to_cartesian(dome_radius, np.radians(az), np.radians(el))
for az, el in ((-30.0, 20.0), (30.0, 20.0), (0.0, 70.0))])
normals = (triangle - dome_center) / dome_radius # radial
center = triangle.mean(axis=0)
center_normal = normalize(normals.mean(axis=0)) # interpolated and renormalized normal
glass = {"diffuse": (0.2, 0.3, 0.5), "specular": (1.0, 1.0, 1.0), "shininess": 64.0}
toward_light = reflect(-direction_to(center, camera), center_normal)
star = {"type": "directional", "direction": toward_light, "color": (1.0, 1.0, 1.0)}
flat = shade_point(center, triangle_normal(*triangle), camera, glass, [star])
colors = np.array([shade_point(triangle[i], normals[i], camera, glass, [star])
for i in range(3)])
gouraud = interpolate_attribute((1 / 3, 1 / 3, 1 / 3), colors)
phong = shade_point(center, center_normal, camera, glass, [star])
print(np.round(colors, 4))
print(np.round(flat, 4), np.round(gouraud, 4), np.round(phong, 4))[[0.0451 0.0676 0.1277] [0.0451 0.0676 0.1277] [0.1809 0.2713 0.4671]] [1. 1. 1.] [0.0903 0.1355 0.2408] [1. 1. 1.]
The light was placed by reflecting the direction toward the camera off the normal: that is the direction the light must arrive from for the highlight to be seen exactly there. The results at the center of the triangle:
- Gouraud lights the three vertices, where there is no highlight (dark blue colors), and averages them: \((0.09, 0.14, 0.24)\). The highlight has disappeared. Gouraud can only show a highlight if it falls near a vertex, and then it spreads it over the neighboring triangles; as the camera moves, highlights pop in and out.
- Phong interpolates the normal, renormalizes it and evaluates the lighting at the point itself: pure white, the highlight where it should be. Toward the vertices, the interpolated normal moves away from the halfway vector and the highlight fades gradually, as on a real sphere.
- Flat uses the face normal, which here almost coincides with the one at the center: it gives white too, but for the whole face. The entire triangle flashes like a flat mirror and gives the facet away.
Which space to light in
The vectors \(\hat{\mathbf{N}}\), \(\hat{\mathbf{L}}\) and \(\hat{\mathbf{V}}\) must be expressed in the same coordinate system. Which one is chosen does not change the result: dot products do not vary under rigid transformations, which preserve angles and lengths.
| Space | Advantage | Drawback |
|---|---|---|
| World | Intuitive; the lights are already in it | The position of the eye has to be passed in |
| View | The eye is the origin: \(\hat{\mathbf{V}} = -\mathbf{p}/\lVert \mathbf{p} \rVert\) | The lights have to be transformed with the view matrix |
What cannot be done is lighting after the projection: clip space and NDC distort angles, and dot products lose their meaning.
alpha_view = look_at_matrix(alpha, ship)
light_in_view = dict(lighthouse_light, position=transform_point(alpha_view, lamp),
axis=transform_direction(alpha_view, lighthouse_axis))
print(np.round(shade_point(transform_point(alpha_view, p), normal_matrix(alpha_view) @ n,
[0.0, 0.0, 0.0], hull_material, [light_in_view]), 4))Taking to view space the point, the normal (with the view's normal matrix, which, being rigid, is its rotation), the position of the lamp and its axis, and putting the eye at the origin, we get exactly the same color.
Beyond: shadows, gamma and PBR
The model we have built is the starting point. Three extensions worth knowing about, even though we will not develop them:
Cast shadows. A local model lights a point even if there is an object between it and the light. The check is an intersection test from Module 3: a shadow ray is cast from the point toward the light and, if it touches something before arriving, the light does not count.
origin = p + 1e-4 * n # lifted off the surface
obstacle = ray_sphere(origin, l, [2.0, 8.0, 5.0], 5.0)
print(round(obstacle, 3), obstacle < distance(p, lamp))The result is a surprise: 3.85 m from the hull, the ray runs into the rogue asteroid, with center \((2, 8, 5)\) and radius 5. In Module 3 we computed where the beam would hit the hull, but we did not check whether anything got in the way first. As long as the asteroid stays there, our point is in shadow and receives only the ambient light and the star's. It is a good reminder of what a local model does not see. The small offset of the origin along the normal avoids the self-intersection we discussed in "Intersections: Rays, Spheres, Triangles and Boxes". Graphics cards solve shadows in real time with shadow maps: they draw the scene from the light and keep its z-buffer.
Gamma correction. Screens do not respond linearly: a value of 0.5 does not emit half the light of a 1, but considerably less (approximately \(0.5^{2.2} \approx 0.22\)). Lighting calculations must be done with linear values and converted at the end, raising each channel to \(1/2.2\). Without that conversion, the midtones come out too dark.
PBR (Physically Based Rendering). Today's engines replace the artistic parameters of Blinn-Phong with others that have a physical meaning (base color, metalness, roughness) and with models that conserve energy and include the Fresnel effect, whereby every surface reflects more at grazing angles. The structure, however, is the one we have seen: the same vectors \(\hat{\mathbf{N}}\), \(\hat{\mathbf{L}}\), \(\hat{\mathbf{V}}\) and \(\hat{\mathbf{H}}\), and the same dot products.
Common Mistakes and Tips
- Using unnormalized vectors. \(\hat{\mathbf{N}} \cdot \hat{\mathbf{L}}\) is a cosine only if both are unit vectors. Pay special attention to interpolated normals and to those transformed with scale.
- Reversing the direction of \(\hat{\mathbf{L}}\) or \(\hat{\mathbf{V}}\). Both point from the point: toward the light and toward the eye. With \(\hat{\mathbf{L}}\) the wrong way around, the faces with their back to the light are the ones that get lit.
- Forgetting the \(\max(0, \cdot)\). Negative dot products would subtract light and, raised to an even exponent, would create false highlights.
- Transforming normals with the model matrix when there is non-uniform scaling. Use the inverse transpose. And never apply the translation to them.
- Multiplying colors with a dot product. The filtering of the light by the material is component by component.
- Confusing Phong shading with Phong reflection. The former says where the lighting is evaluated; the latter, which specular formula is used.
- Expecting shadows from a local model. Each point is lit as if it were alone. Cast shadows require a separate test.
- Giving the same exponent the same meaning in Phong and in Blinn-Phong. When switching from one to the other, the shininess has to be multiplied or divided by 4, approximately.
- Tip. To debug lighting, paint the vectors as colors: a normal \((x, y, z)\) becomes the color \(\big(\tfrac{x + 1}{2}, \tfrac{y + 1}{2}, \tfrac{z + 1}{2}\big)\). An error in the normals shows up instantly.
Exercises
Exercise 1. The lighthouse beam aimed at the strip reaches the point \(Q = (1, 4, 4)\), 9 m from the lamp \((0, 12, 0)\). The normal of the strip is \(\hat{\mathbf{N}} = \left(\tfrac{1}{3}, \tfrac{2}{3}, \tfrac{2}{3}\right)\). The strip is matte, with diffuse color \((0.5, 0.5, 0.5)\) and no specular component. The light is a point light, with color \((2, 1.9, 1.6)\) and attenuation \((1, 0.05, 0.005)\); the ambient is \((0.05, 0.05, 0.08)\).
a) Compute \(\hat{\mathbf{L}}\), the diffuse factor and the angle of incidence. b) Compute the attenuation and the final color. c) In Module 3 we saw that the rogue asteroid intercepts this beam. What color does the point really have, then?
Exercise 2. A solar panel has, in its local space, the normal \((1, 1, 0)/\sqrt{2}\) and an edge in the direction \((-1, 1, 0)\). It is placed in the scene with the model matrix \(S(2, 1, 1)\).
a) What does the edge become? b) Transform the normal with the model matrix and check that it is not perpendicular to the edge. c) Transform it with the inverse transpose and check that it is.
Exercise 3. With shade_point, the hull's material and the lighthouse lamp from the lesson, seen from beacon Alpha (ignore the asteroid's shadow):
a) What color does the point \(P\) have if the lamp turns until it points exactly at \(P\)? b) With the lamp like that, compare the materials of shininess 8 and 128. c) Where would the observer have to be placed, 5 m from \(P\), to see the maximum highlight? What color would they see?
Solutions
Solution 1.
a) \(\hat{\mathbf{L}} = \dfrac{(0, 12, 0) - (1, 4, 4)}{9} = \left(-\tfrac{1}{9}, \tfrac{8}{9}, -\tfrac{4}{9}\right)\). Diffuse factor: \(\hat{\mathbf{N}} \cdot \hat{\mathbf{L}} = \dfrac{-1 + 16 - 8}{27} = \dfrac{7}{27} \approx 0.259\). The angle of incidence is \(\arccos 0.259 \approx 75°\): a very grazing light.
b) Attenuation: \(\dfrac{1}{1 + 0.05 \cdot 9 + 0.005 \cdot 81} = \dfrac{1}{1.855} = 0.539\). Total factor: \(0.539 \cdot 0.259 = 0.1398\).
- Ambient: \((0.05, 0.05, 0.08) \odot (0.5, 0.5, 0.5) = (0.025, 0.025, 0.04)\).
- Diffuse: \(0.1398 \cdot (2, 1.9, 1.6) \odot (0.5, 0.5, 0.5) = (0.140, 0.133, 0.112)\).
- Total: \((0.165, 0.158, 0.152)\). A dark gray: between the distance and the grazing angle, little light arrives.
c) If the beam is intercepted, the lamp's light does not arrive: the point is in shadow and has only the ambient term, \((0.025, 0.025, 0.04)\).
Solution 2.
a) \(S(2, 1, 1),(-1, 1, 0) = (-2, 1, 0)\).
b) \(S,(1, 1, 0) = (2, 1, 0)\). Dot product with the transformed edge: \((2, 1, 0) \cdot (-2, 1, 0) = -4 + 1 = -3 \ne 0\). It is not perpendicular.
c) The inverse transpose of \(S(2, 1, 1)\) is \(S(0.5, 1, 1)\) (a diagonal matrix is its own transpose). \(S(0.5, 1, 1),(1, 1, 0) = (0.5, 1, 0)\), and \((0.5, 1, 0) \cdot (-2, 1, 0) = -1 + 1 = 0\) ✓. Normalized: \((0.447, 0.894, 0)\). On stretching the panel in X, it has become shallower and its normal, more vertical.
Solution 3.
strip = {"diffuse": (0.5, 0.5, 0.5), "specular": (0.0, 0.0, 0.0), "shininess": 1.0}
point_light = {"type": "point", "position": lamp, "color": (2.0, 1.9, 1.6), "attenuation": (1.0, 0.05, 0.005)}
q, n_strip = np.array([1.0, 4.0, 4.0]), np.array([1.0, 2.0, 2.0]) / 3.0
print(np.round(shade_point(q, n_strip, camera, strip, [point_light]), 4),
round(ray_sphere(q + 1e-4 * n_strip, direction_to(q, lamp), [2.0, 8.0, 5.0], 5.0), 3))
panel = np.diag([2.0, 1.0, 1.0])
print(panel @ [1.0, 1.0, 0.0] @ (panel @ [-1.0, 1.0, 0.0]),
np.linalg.inv(panel).T @ [1.0, 1.0, 0.0] @ (panel @ [-1.0, 1.0, 0.0]))
lighthouse_at_p = dict(lighthouse_light, axis=direction_to(lamp, p))
print(np.round(shade_point(p, n, alpha, hull_material, [lighthouse_at_p]), 4))
for shininess in (8.0, 128.0):
print(shininess, np.round(shade_point(p, n, alpha, dict(hull_material, shininess=shininess), [lighthouse_at_p]), 4))
ideal_eye = p + 5.0 * reflect(-l, n)
print(np.round(ideal_eye, 3), np.round(shade_point(p, n, ideal_eye, hull_material, [lighthouse_at_p]), 4))[0.1648 0.1578 0.1518] 7.0 -3.0 0.0 [0.635 0.6405 0.596 ] 8.0 [0.9633 0.9524 0.8586] 128.0 [0.453 0.4675 0.4503] [10.095 7.619 2.19 ] [1. 1. 1.]
The first two lines confirm Exercises 1 and 2 (the shadow ray finds the asteroid 7 m from the point \(Q\)).
a) With the lamp pointing at \(P\), the cone factor goes from 0.64 to 1 and the color rises to \((0.635, 0.641, 0.596)\).
b) With shininess 8, the reflection is so wide that it reaches the observer (\(0.958^8 = 0.71\)) and the color almost saturates; with shininess 128, the reflection is a narrow point that does not reach the beacon (\(0.958^{128} = 0.004\)) and practically only the diffuse component is left.
c) In the direction of the reflection: \(P + 5,\hat{\mathbf{R}} = (10.10, 7.62, 2.19)\). There \(\hat{\mathbf{H}} = \hat{\mathbf{N}}\), the specular factor is 1 and the color saturates to white.
Conclusion
A local lighting model computes the color of a point from three unit vectors: the normal, the direction toward the light and the direction toward the observer. Diffuse light follows Lambert's law, \(\max(0, \hat{\mathbf{N}} \cdot \hat{\mathbf{L}})\), and does not depend on the observer; specular light measures how close the observer is to the reflection—with \(\hat{\mathbf{R}} \cdot \hat{\mathbf{V}}\) in Phong or with \(\hat{\mathbf{N}} \cdot \hat{\mathbf{H}}\) in Blinn-Phong—raised to the shininess of the material; ambient light fills in what direct light does not reach. The terms are filtered by the colors of the light and of the material component by component, multiplied by the distance attenuation and by the cone factor in spotlights, added up over all the lights and clamped. Normals are transformed with the inverse transpose of the model matrix, and the calculation is distributed over the triangle per face (flat shading), per vertex (Gouraud) or per pixel (Phong). mini3d gains attenuation, spot_factor, diffuse_light, specular_light_phong, specular_light_blinn, shade_point and normal_matrix.
With this the ship has volume, but each object is still a single flat color. Real surfaces have detail: the riveted plates of the hull, the windows of the tower, the craters of the asteroid. Modeling it with triangles would be hugely expensive; the usual approach is to paint it onto the surface with an image. In the next and last lesson of the module, "Texture Coordinates and Mapping", we will see how each point of a mesh is assigned a point of an image and how that image is read without artifacts appearing.
