Calculus for Graphics and Games
A rendered frame is the answer to an integral, every lit surface needs a normal vector that comes from partial derivatives, and every smooth camera path or racing line is a spline whose derivative is a velocity. This lesson works through those three ideas: the rendering integral and its Monte Carlo estimate, normals from partial derivatives of height maps and parametric surfaces, and Catmull-Rom splines with arc-length reparametrisation for constant-speed motion.
Background: Surface Integrals, Tangent Planes and Linear Approximations, Parametric Surfaces and Their Areas and Arc Length and Curvature. For the game-side vocabulary see Math for Games and Easing curves.
The rendering integral
The light leaving a surface point toward the viewer is the emitted light plus all incoming light reflected toward the viewer:
is the hemisphere of directions above the surface, the material's reflectance (BRDF), the angle between and the normal, and the solid-angle element. The factor is the same projection that turns flux into a surface integral: light arriving at a slant spreads over more area.
itself depends on light leaving other surfaces, so the integral is recursive and has no closed form. Path tracers estimate it by Monte Carlo: draw directions with density and average . The estimate is unbiased, and its error shrinks like regardless of dimension. Importance sampling chooses a pdf shaped like the integrand to lower the variance: cosine-weighted sampling () cancels the factor exactly.
Test it on irradiance under a sky that is brighter overhead, . The exact value is .
import numpy as np
rng = np.random.default_rng(42)
exact = 2 * np.pi / 3
for N in [16, 256, 4096, 65536]:
# uniform hemisphere: cos(theta) is uniform on [0, 1], pdf = 1 / (2 pi)
c = rng.random(N)
uniform = np.mean(c * c * 2 * np.pi)
# cosine-weighted: cos(theta) = sqrt(xi), pdf = cos(theta) / pi
c = np.sqrt(rng.random(N))
cosine = np.mean(c * np.pi) # (L * cos) / pdf = cos * pi
print(f"N = {N:6d} uniform err = {abs(uniform - exact):.5f} cosine-weighted err = {abs(cosine - exact):.5f}")N = 16 uniform err = 0.54787 cosine-weighted err = 0.14007
N = 256 uniform err = 0.20839 cosine-weighted err = 0.04200
N = 4096 uniform err = 0.01358 cosine-weighted err = 0.00857
N = 65536 uniform err = 0.00774 cosine-weighted err = 0.00066
Both estimators converge to , but the importance-sampled one has a smaller variance ( against for uniform sampling, about one sixth), so it reaches the same noise level with fewer samples, fewer rays per pixel.
Normals from partial derivatives
Lighting needs the unit normal at each point. Two common cases:
| Surface | Tangents | Normal (before normalising) |
|---|---|---|
| Height field (terrain, bump maps) | , | |
| Parametric (spheres, tori, NURBS) | , |
The height-field formula is the cross product of the two tangents, the same vector as the normal of the tangent plane. Shaders compute and from a height texture with central differences, and normal maps store the result. The program compares the exact normal of a wavy terrain with the finite-difference one a shader would use.
import numpy as np
h = lambda x, y: 0.5 * np.sin(2*x) * np.cos(y)
hx = lambda x, y: np.cos(2*x) * np.cos(y) # partial derivatives by hand
hy = lambda x, y: -0.5 * np.sin(2*x) * np.sin(y)
def unit(v):
return v / np.linalg.norm(v)
x, y = 0.3, 1.1
exact = unit(np.array([-hx(x, y), -hy(x, y), 1.0]))
for texel in [0.1, 0.01, 0.001]:
dx = (h(x + texel, y) - h(x - texel, y)) / (2 * texel)
dy = (h(x, y + texel) - h(x, y - texel)) / (2 * texel)
approx = unit(np.array([-dx, -dy, 1.0]))
angle = np.degrees(np.arccos(min(1.0, float(exact @ approx))))
print(f"texel {texel:<6} normal {np.round(approx, 5)} error {angle:.6f} degrees")
print("exact normal", np.round(exact, 5))texel 0.1 normal [-0.33928 0.22917 0.91234] error 0.122420 degrees
texel 0.01 normal [-0.34124 0.22935 0.91157] error 0.001226 degrees
texel 0.001 normal [-0.34126 0.22935 0.91156] error 0.000012 degrees
exact normal [-0.34126 0.22935 0.91156]
Splines and constant-speed motion
A Catmull-Rom spline passes through a list of points ; the segment between and is the cubic
Neighbouring segments share their end tangents, so the path is : position and velocity are continuous, with no kinks. But moving at a constant rate does not give constant speed, since varies. The fix is arc-length reparametrisation: compute , then invert it to find the that lies a given distance along the curve.
import numpy as np
P = np.array([[0, 0], [1, 2], [4, 3], [6, 0]], dtype=float)
def p(t):
P0, P1, P2, P3 = P
return 0.5 * (2*P1 + (P2 - P0)*t + (2*P0 - 5*P1 + 4*P2 - P3)*t**2 + (-P0 + 3*P1 - 3*P2 + P3)*t**3)
def dp(t):
P0, P1, P2, P3 = P
return 0.5 * ((P2 - P0) + 2*(2*P0 - 5*P1 + 4*P2 - P3)*t + 3*(-P0 + 3*P1 - 3*P2 + P3)*t**2)
t = np.linspace(0, 1, 2001)
speed = np.linalg.norm([dp(ti) for ti in t], axis=1)
s = np.concatenate([[0], np.cumsum((speed[1:] + speed[:-1]) / 2 * np.diff(t))]) # trapezoid
print("endpoints:", p(0.0), p(1.0), " tangents:", dp(0.0), dp(1.0))
print(f"segment length = {s[-1]:.4f}, speed ranges {speed.min():.3f} .. {speed.max():.3f}")
for frac in [0.25, 0.5, 0.75]:
t_frac = np.interp(frac * s[-1], s, t) # invert s(t)
print(f"{frac:.0%} of the length: t = {t_frac:.4f} (naive t = {frac}) point {np.round(p(t_frac), 3)}")endpoints: [1. 2.] [4. 3.] tangents: [2. 1.5] [ 2.5 -1. ]
segment length = 3.2646, speed ranges 2.500 .. 3.656
25% of the length: t = 0.2672 (naive t = 0.25) point [1.684 2.444]
50% of the length: t = 0.4937 (naive t = 0.5) point [2.416 2.804]
75% of the length: t = 0.7259 (naive t = 0.75) point [3.195 3.042]
In software
- Path tracing and real-time GI. Blender's Cycles, film renderers and real-time ray tracing estimate the rendering integral by Monte Carlo with importance sampling, then denoise the result.
- Normal and bump mapping. Height maps become normal maps by finite differences; procedural terrain and SDF raymarchers get normals from the gradient of the height or distance function.
- Splines. Camera rails, racing lines, animation curves (Bézier in UI and CSS, Catmull-Rom in games) and font outlines; arc-length tables give constant-speed movement along them.
Exercises
Exercise 1: A terrain normal
Find the unit normal of the height field at .
Answer
.
Solution
Exercise 2: Irradiance from a uniform sky
A sky has the same radiance in every direction. Show that the irradiance on a horizontal surface is .
Answer
.
Solution
This is why a perfectly diffuse (Lambertian) BRDF is : it makes reflected radiance equal .
Exercise 3: A Catmull-Rom tangent
The points , , are consecutive on a Catmull-Rom spline. What is the velocity of the curve as it passes ?
Answer
.
Solution
The tangent at is , for both the segment arriving at and the one leaving it, which is what makes the spline .
Exercise 4: Monte Carlo on the hemisphere (code)
Estimate with 100,000 uniform hemisphere samples (seed 3) and compare it with the exact value.
Answer
Exact: ; the estimate is 1.571, off by 0.0002.
Solution
With uniform hemisphere sampling is uniform on and the pdf is , so the estimator is the mean of .
import numpy as np
rng = np.random.default_rng(3)
u = rng.random(100_000)
est = float(np.mean(2 * np.pi * u**3))
print(round(est, 4), round(np.pi / 2, 4), round(abs(est - np.pi / 2), 4))1.571 1.5708 0.0002
Test yourself
Why does cosine-weighted sampling reduce noise when estimating the rendering integral?
- It uses fewer samples
- Its pdf is proportional to the factor of the integrand, so the ratio varies less
- It makes the integral exact for every scene
- It removes the BRDF
What is the (unnormalised) normal of the height field ?
Moving the spline parameter at a constant rate gives a varying speed. What fixes that?
- Normalising the control points
- Reparametrising by arc length
- Using a higher-degree spline
- Clamping