graphics3d

cg fundamentals

vectors, matrices, cameras, rasterizing, ray tracing, light, shadows and color, drawn small.

report a mistake
.md

a scene is points and directions. matrices move them in front of a camera, the projection and the divide by w flatten them onto the screen, and then each pixel works out what it sees and how much light reaches it.

a vertex's trip
P · V · M · p then ÷ w, then the viewport
dot product
|a| |b| cos θ lighting runs on it
order
T · R · S scale first, move last
depth
2 × near half the depth buffer is used up before it
pbr
D · V · F ggx, smith and schlick, per gltf
srgb 0.5
21% of the light. mix in linear
reach for it
  • reading shader and three.js code
  • placing a camera, picking near and far
  • choosing a lighting model
  • fixing acne, dark mixes and washed-out color
on this page
  1. vectors + matrices
  2. transforms
  3. camera + projection
  4. rasterization vs ray tracing
  5. lighting models (lambert, phong, pbr)
  6. shadows
  7. color spaces + gamma
  8. pitfalls
  9. sources

the ideas under every 3d renderer, from a fragment shader to a game engine: vectors and matrices that move points, a camera that flattens them onto the screen, two ways to fill in the pixels, and how light, shadows and color get worked out. each section has the math as code you can run and a small figure to drag.

vectors + matrices

a vector is a direction with a length: three numbers, x, y and z. a point is written the same way, as an offset from the origin. the difference only shows when something moves them, in the next section.

the dot product multiplies matching parts and adds them up. it also equals the two lengths times the cosine of the angle between them, so for two vectors of length 1 it is the cosine itself: 1 when they point the same way, 0 at 90°, −1 when they’re opposite. lighting runs on it.

a⋅b=axbx+ayby+azbz=∣a∣ ∣b∣cos⁡θ\mathbf a \cdot \mathbf b = a_x b_x + a_y b_y + a_z b_z = |\mathbf a|\,|\mathbf b| \cos\theta

the cross product is perpendicular to both, and as long as the area of the parallelogram they span. order matters: b × a points the other way. a triangle with corners p, q and r has the normal (q − p) × (r − p), so the order of its corners decides which side it faces.

type Vec3 = [number, number, number];

const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: Vec3, b: Vec3): Vec3 => [
  a[1] * b[2] - a[2] * b[1],
  a[2] * b[0] - a[0] * b[2],
  a[0] * b[1] - a[1] * b[0],
];
const length = (a: Vec3) => Math.hypot(a[0], a[1], a[2]);
const normalize = (a: Vec3): Vec3 => {
  const n = length(a); // 0 for the zero vector, which has no direction: check before dividing
  return [a[0] / n, a[1] / n, a[2] / n];
};
// the angle in radians. Math.acos(dot / lengths) can be handed 1.0000000000000002 and return NaN
const angle = (a: Vec3, b: Vec3) => Math.atan2(length(cross(a, b)), dot(a, b));

dot([3, 1, 0], [1, 2, 0]); // 5
angle([3, 1, 0], [1, 2, 0]); // 0.785..., which is 45°
cross([1, 0, 0], [0, 1, 0]); // [0, 0, 1]: x × y is z

glsl has them built in. reflect wants a normal of length 1:1

float d = dot(a, b);
vec3 n = normalize(cross(q - p, r - p)); // the normal of the triangle p, q, r
vec3 m = reflect(-l, n);                 // where light from l bounces to, phong's r below
ba

drag a tip, or tab to it and use the arrow keys

a · b
3·1 + 1·2 = 5
θ, the angle
45.0°
|a| |b| cos θ
3.16 · 2.24 · 0.71 = 5.00
a × b
(0, 0, 5)

the dot product is positive: they point less than 90° apart. the cross product points out of the screen, since b is counter-clockwise from a. the gray bar is b's shadow on a: a · b / |a| long.

two arrows from the origin on a grid, a in cyan at (3, 1) and b in amber at (1, 2). drag either tip, or tab to it and use the arrow keys, and the readout follows: the dot product, 5 at the start, worked out both ways, the angle, 45 degrees, and the cross product, (0, 0, 5), which points out of the screen while b is counter-clockwise from a. a gray bar marks b's shadow on a, a · b / |a| long.

the dot product's sign is the quick test: positive under 90°, zero at 90°, negative past it.

a matrix is a grid of numbers that maps vectors to vectors. its columns are where the x, y and z axes land, so you can read a matrix by its columns. multiplying two gives one matrix that does both.

glsl stores matrices column by column: a mat4 built from 16 numbers takes them a column at a time, and m[1] is the second column, not the second row.2 uniformMatrix4fv with transpose false expects the same order.3 three.js keeps its elements column by column too, but its set() takes the numbers row by row, the way you’d write them on paper.4

transforms

translate, rotate and scale are each a 4 × 4 matrix. the fourth coordinate, w, is what lets one matrix move things: a point has w = 1, so it picks up the translation in the last column, and a direction has w = 0, so it turns and stretches but never moves.

matrices apply right to left. T · R · S scales first, then rotates, then translates. three.js builds every object’s matrix from its position, rotation and scale in that order.4 swap two and you get somewhere else: rotate after translating and the object swings around the origin instead of turning in place.

// 4 × 4 matrices as 16 numbers, column by column, the order webgl and glsl use
const translation = (x, y, z) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
const scaling = (x, y, z) => [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1];
const rotationZ = (rad) => {
  const c = Math.cos(rad);
  const s = Math.sin(rad);
  return [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
};
// a · b: one matrix that does b first, then a
const multiply = (a, b) => {
  const out = new Array(16).fill(0);
  for (let c = 0; c < 4; c++)
    for (let r = 0; r < 4; r++)
      for (let k = 0; k < 4; k++) out[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
  return out;
};
// m · (x, y, z, w)
const apply = (m, [x, y, z, w]) =>
  [0, 1, 2, 3].map((r) => m[r] * x + m[4 + r] * y + m[8 + r] * z + m[12 + r] * w);

const model = multiply(multiply(translation(3, 0, 0), rotationZ(Math.PI / 2)), scaling(2, 1, 1));
apply(model, [1, 0, 0, 1]); // ≈ [3, 2, 0, 1]: stretched to 2, turned to (0, 2), moved to (3, 2)
apply(model, [1, 0, 0, 0]); // ≈ [0, 2, 0, 0]: a direction turns and stretches but stays put
T · R · p: turn, then moveR · T · p: move, then turn

cyan then moved 3 right: its tip is at (3, 1). amber then turned 90° about the origin, not about itself, so it swung around to (0, 4).

an arrow at the origin with its tip at (1, 0), turned and moved 3 to the right in both orders. cyan is T · R: it turns in place, then moves, so at 90 degrees its tip ends at (3, 1). amber is R · T: it moves first, then the turn swings it around the origin, so its tip ends at (0, 4). buttons step through the start, one step and both steps, and a slider sets the turn from 0 to 180 degrees.

the same two matrices, multiplied in the other order. R · T is T · R with its move turned too.

in a vertex shader the whole chain is one line, read from the right: the model matrix places the vertex in the world, the view matrix moves the world in front of the camera, the projection flattens it. three.js splits it into a model-view matrix and a projection matrix, and does the same multiply.5

#version 300 es
uniform mat4 model, view, projection;
uniform mat3 normalMatrix; // transpose(inverse(mat3(model))), worked out once per object
in vec3 position;
in vec3 normal;
out vec3 worldNormal;

void main() {
  worldNormal = normalize(normalMatrix * normal);
  gl_Position = projection * view * model * vec4(position, 1.0);
}

camera + projection

after the model matrix, two more matrices take a vertex to the screen. the view matrix moves the world so the eye sits at the origin, looking down −z, with up along +y.7 the projection matrix squeezes what the camera can see into a box. then the gpu divides x, y and z by w, which gives normalized device coordinates, −1 to 1 on each axis, and maps those to pixels.8

P=(faspect0000f0000far+nearnear−far2 far nearnear−far00−10)f=1tan⁡(fov/2)P = \begin{pmatrix} \frac{f}{\text{aspect}} & 0 & 0 & 0 \\ 0 & f & 0 & 0 \\ 0 & 0 & \frac{\text{far} + \text{near}}{\text{near} - \text{far}} & \frac{2\,\text{far}\,\text{near}}{\text{near} - \text{far}} \\ 0 & 0 & -1 & 0 \end{pmatrix} \qquad f = \frac{1}{\tan(\text{fov} / 2)}

that’s gluPerspective’s matrix. fov is the field of view up and down, aspect is width over height, and near and far are distances in front of the camera.9 its last row copies the distance, −z, into w, and dividing by w is the perspective: the same offset lands half as far from the middle at twice the distance. anything outside −w to w on any axis gets clipped.8

// gluPerspective's matrix, column by column. fov is vertical, in degrees
function perspective(fov, aspect, near, far) {
  const f = 1 / Math.tan((fov * Math.PI) / 360);
  const nf = near - far;
  return [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / nf, -1, 0, 0, (2 * far * near) / nf, 0];
}

// a point already in the camera's frame to a pixel of a width by height picture
function toPixel(p, [x, y, z], width, height) {
  const clip = [p[0] * x, p[5] * y, p[10] * z + p[14], -z]; // p · (x, y, z, 1)
  const ndc = clip.slice(0, 3).map((c) => c / clip[3]); // the divide by w
  return [((ndc[0] + 1) / 2) * width, ((1 - ndc[1]) / 2) * height, ndc[2]]; // y flips: row 0 is the top
}

toPixel(perspective(50, 1.5, 1, 12), [1.5, -0.5, -6.5], 300, 200); // ≈ [199.5, 116.5, 0.85]

from above. the camera looks right

nearfar

the picture it makes

dashed: eye level, where the ground meets the horizon

postw, distancendc xheight
cyan4.0−0.4327%
amber6.50.3316%

50° tall is 69.9° wide at this aspect, and f = 1 / tan(25.0°) = 2.14. the cyan post: ndc x = (f / aspect) · x / w = 1.43 · (−1.2) / 4.0 = −0.43.

a camera at eye height and two posts on the ground, seen from above on one side and as the picture the camera makes on the other. the cyan post starts 4 in front and the amber one 6.5, and a table gives each one's w, its ndc x after the divide, and its height in the picture: the nearer post is taller and wider by the same 1 / w. a slider sets the field of view from 20 to 120 degrees, starting at 50, three.js's default, which is 69.9 degrees across at this 3:2 aspect. drag a post, or tab to it and use the arrow keys.

w is the post's distance in front of the camera. its ndc x is (f / aspect) · x / w, so a wider fov pulls everything toward the middle.

depth isn’t spread evenly. ndc z goes as 1 / distance, so the depth buffer spends most of its values close to the camera. with near 0.1 and far 100, half of them are used up by 0.2 in front, and everything past 10 shares the last 0.9%. near is what matters: move it out to 1 and the halfway point moves to 1.98, while pulling far in to 50 barely changes it. the halfway point always sits within 2 × near. gluPerspective’s notes put it as about log₂(far / near) bits of depth precision lost, and say near must never be 0.9

three.js’s PerspectiveCamera takes the same four numbers and defaults to a fov of 50, an aspect of 1, near 0.1 and far 2000.6

const camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
camera.position.set(0, 1, 5);
camera.lookAt(0, 0, 0);

// after a resize, or any change to fov, aspect, near or far
camera.aspect = width / height;
camera.updateProjectionMatrix();

rasterization vs ray tracing

two ways to find what each pixel shows. rasterization starts from the triangles: for each one, find the pixels it covers. ray tracing starts from the pixels: for each one, send a ray into the scene and find the first thing it hits. gpus are built to rasterize. ray tracing costs more per pixel, but follows light where rasterizing can’t, to reflections, refractions and shadows.

for a triangle, an edge function says which side of an edge a point is on: zero on the line, positive on one side, negative on the other. it is linear, so one pixel to the right adds a constant, which is how hardware steps it.10

Eab(p)=(px−ax)(by−ay)−(py−ay)(bx−ax)E_{ab}(p) = (p_x - a_x)(b_y - a_y) - (p_y - a_y)(b_x - a_x)

a pixel is drawn when its center is inside all three edges. a center exactly on an edge needs a tie-breaker. opengl only asks that exactly one of two triangles sharing the edge draws it,11 and direct3d’s top-left rule spells one out: a center on a top or a left edge is in, so a shared edge is drawn once.12

// zero on the line a → b. at the third corner it is twice the triangle's signed area
const edge = (a, b, p) => (p.x - a.x) * (b.y - a.y) - (p.y - a.y) * (b.x - a.x);

function rasterize([a, b, c], plot) {
  if (edge(a, b, c) < 0) [b, c] = [c, b]; // wind it so the inside is positive
  const area = edge(a, b, c);
  const xs = [a.x, b.x, c.x];
  const ys = [a.y, b.y, c.y];
  // the pixels whose centers can be inside: the bounding box
  for (let y = Math.ceil(Math.min(...ys) - 0.5); y <= Math.floor(Math.max(...ys) - 0.5); y++)
    for (let x = Math.ceil(Math.min(...xs) - 0.5); x <= Math.floor(Math.max(...xs) - 0.5); x++) {
      const p = { x: x + 0.5, y: y + 0.5 }; // the pixel's center
      const w = [edge(b, c, p), edge(c, a, p), edge(a, b, p)];
      // a center exactly on an edge (a 0) is left out here. the top-left rule decides those
      if (w.every((e) => e > 0)) plot(x, y, w.map((e) => e / area)); // the corners' weights
    }
}

the three edge values over twice the area are the pixel’s barycentric weights. they blend whatever the corners carry: colors, normals, texture coordinates. after a perspective projection the gpu divides each corner’s value by its w before blending, so textures don’t slide, and blends depth without that divide.11 a depth buffer then keeps the nearest surface at each pixel.

ray tracing needs one test per kind of shape. for a sphere it is a quadratic:

// the nearest t past tMin where origin + t · dir is on the sphere, or null. dir has length 1
function hitSphere(origin, dir, center, radius, tMin = 1e-4) {
  const oc = origin.map((v, i) => v - center[i]);
  const b = oc[0] * dir[0] + oc[1] * dir[1] + oc[2] * dir[2];
  const c = oc[0] * oc[0] + oc[1] * oc[1] + oc[2] * oc[2] - radius * radius;
  const disc = b * b - c; // t² + 2bt + c = 0
  if (disc < 0) return null;
  const root = Math.sqrt(disc);
  if (-b - root > tMin) return -b - root; // the near side
  if (-b + root > tMin) return -b + root; // the far side, for a ray that starts inside
  return null;
}

hitSphere([0, 0, 0], [0, 0, -1], [0, 0, -5], 1); // 4

whitted’s 1980 paper made it recursive. at each hit, more rays go out toward the lights, for shadows, and along the reflected and refracted directions, so each pixel gets a tree of rays.13

pixel (7, 5): edges 30, 44, 25, all positive: inside. over twice the area, 99, they are the weights 0.30, 0.44, 0.25.

inside so far: 39. pixels tested: 54 of 120, the box around the triangle

one 16 by 12 grid of pixels, filled two ways and stepped a pixel at a time. rasterize loops over the 120 pixels in the triangle's bounding box and tests each center against the three edges: 54 are inside, and the readout gives the edge values and the barycentric weights. trace sends one ray through each of the 192 pixels at a sphere: 68 hit, shaded by lambert's n · l. it opens part way through either loop, at pixel (7, 5), and a stepper steps, plays or scrubs it.

the same grid either way. rasterizing only visits the box around the triangle. tracing visits every pixel, and tests each ray against every object it might hit.

lighting models (lambert, phong, pbr)

a lighting model answers one question per pixel. given the normal n, the direction to the light l and the direction to the viewer v, all of length 1, how much light leaves toward the viewer?

lambert. a matte surface sends light out equally in every direction, and the light it gets goes with the cosine of the angle between n and l.14 so it is albedo⋅max⁡(n⋅l,0)\text{albedo} \cdot \max(n \cdot l, 0), and the viewer doesn’t matter.

phong. phong’s 1975 model adds a highlight: the cosine of the angle between the light’s mirror direction r and the viewer, raised to a power. the bigger the power, the smaller and sharper the highlight. he used powers from 1 to 10 and called the numbers empirical. the same paper also interpolates the normal across each polygon, which is what makes highlights look smooth on a faceted mesh.15

blinn-phong. blinn’s 1977 version measures the highlight with h, the direction halfway between l and v: the way a mirror would have to face to send the light into the eye. it takes the cosine between n and h to a power, typically 50 or 60, and with the light and the eye far away, h only changes when the light moves.14 for the same highlight it needs about 4 times phong’s power, since the angle from n to h is about half the angle from r to v.

phong: max⁡(r⋅v,0)sblinn-phong: max⁡(n⋅h,0)s,h=l+v∣l+v∣\text{phong: } \max(r \cdot v, 0)^{s} \qquad \text{blinn-phong: } \max(n \cdot h, 0)^{s}, \quad h = \frac{l + v}{|l + v|}

pbr. physically based models treat a surface as countless tiny mirrors, microfacets. cook and torrance’s model multiplies three things: d, how many facets face h; g, how many are neither shadowed nor hidden by their neighbors; and f, fresnel, how much a facet reflects at that angle.16 the gltf 2.0 spec writes down a version many renderers share: ggx for d, a smith visibility term v that folds g together with the rest of the denominator, and schlick’s approximation for f.17

f=(1−F) albedoπ+F D VD=α2π ((n⋅h)2(α2−1)+1)2F=f0+(1−f0)(1−v⋅h)5f = (1 - F)\,\frac{\text{albedo}}{\pi} + F\,D\,V \qquad D = \frac{\alpha^2}{\pi\,\big((n \cdot h)^2 (\alpha^2 - 1) + 1\big)^2} \qquad F = f_0 + (1 - f_0)(1 - v \cdot h)^5

α is the roughness squared, which makes the roughness slider feel even.17 ggx is the trowbridge-reitz distribution. blinn’s 1977 paper already offered it, and walter and others found it again in 2007 and called it ggx. its tails are longer than those of the beckmann distribution cook and torrance used, and that matches many real surfaces.141817 schlick’s fresnel is one line where the full equations take many: f0 is what the surface reflects head on, rising toward 1 at grazing angles.19 for non-metals gltf fixes f0 at 0.04, an index of refraction of 1.5. for metals, f0 is the base color and there is no diffuse part.17 unreal engine 4 moved to the same pieces in 2013, ggx, a smith-style g and schlick’s fresnel, and found ggx cost little more than blinn-phong.20

// n, l, v have length 1. each returns light toward the viewer, in linear light, for a light of strength 1
float lambert(vec3 n, vec3 l) {
  return max(dot(n, l), 0.0);
}

float blinnPhong(vec3 n, vec3 l, vec3 v, float shininess) {
  vec3 h = normalize(l + v);
  return dot(n, l) > 0.0 ? pow(max(dot(n, h), 0.0), shininess) : 0.0;
}

// the gltf 2.0 dielectric: ggx, height-correlated smith, schlick with f0 = 0.04
vec3 pbr(vec3 n, vec3 l, vec3 v, vec3 albedo, float roughness) {
  float nl = max(dot(n, l), 0.0);
  float nv = max(dot(n, v), 1e-4);
  vec3 h = normalize(l + v);
  float nh = max(dot(n, h), 0.0);
  float vh = max(dot(v, h), 0.0);
  float a = max(roughness * roughness, 1e-3); // α = 0 is a perfect mirror, which this form can't evaluate
  float a2 = a * a;
  float d = nh * nh * (a2 - 1.0) + 1.0;
  float D = a2 / (3.14159265 * d * d);
  float V = 0.5 / (nl * sqrt(nv * nv * (1.0 - a2) + a2) + nv * sqrt(nl * nl * (1.0 - a2) + a2));
  float F = 0.04 + 0.96 * pow(1.0 - vh, 5.0);
  return ((1.0 - F) * albedo / 3.14159265 + F * D * V) * nl;
}

the ring is the light: drag on the sphere, or focus it and use the arrow keys

lambert + 0.5 · max(n · h, 0)^shininess

shininess 32: the angle from n to h is about half the angle from r to v, so the same exponent spreads wider than phong's.

a gray sphere shaded pixel by pixel on a canvas, lit from up and to the left. buttons switch between lambert, phong, blinn-phong and pbr with ggx. a slider sets the shininess, in powers of 2 from 1 to 256, for phong and blinn-phong, or the roughness, 0.05 to 1, for pbr. drag on the sphere, or focus it and use the arrow keys, to move the light. the readout gives the formula, and for phong how far off the mirror direction the highlight dims to half: 11.9 degrees at a shininess of 32.

the same light and an albedo of 0.5 in every model. pbr's light is given a strength of π, so its diffuse part lines up with lambert.

shadows

a point is in shadow when something sits between it and the light. a ray tracer asks directly: send a ray toward the light and see if it hits anything. a rasterizer uses a shadow map, williams’s 1978 trick. render the scene once from the light, keeping only depth: how far the light gets before it hits something. then move each point the camera sees into the light’s view and compare. if it is farther from the light than the stored depth, something nearer is in the way. it costs about twice as much as rendering the scene without shadows.21

uniform sampler2D shadowMap; // depth from the light's view, 0 to 1
uniform mat4 lightViewProjection;
uniform float bias;

// 1.0 if the light reaches a point in the world, 0.0 if something nearer is in the way
float lit(vec3 worldPos) {
  vec4 p = lightViewProjection * vec4(worldPos, 1.0);
  vec3 q = p.xyz / p.w * 0.5 + 0.5;           // ndc to 0..1: a texture coordinate and a depth
  float stored = texture(shadowMap, q.xy).r; // the nearest thing the light hit there
  return q.z - bias > stored ? 0.0 : 1.0;
}

two things go wrong. the map keeps one depth per texel, and a surface tilted to the light changes depth across a texel, so part of every texel ends up behind its own stored value and shadows itself: speckles and moiré on lit surfaces, called shadow acne.22 williams already subtracted a bias to stop it.21 too much bias lets light through where it shouldn’t: shadows come loose from the things that cast them, called peter panning.22 in the figure, the low ledge’s shadow goes first, since the gap between it and the ground is small.

the bias acne needs is at most the change in depth across half a texel, so a sharper map needs less. in the figure’s scene that is 0.36 at 8 texels, 0.18 at 16 and 0.09 at 32. engines also scale the bias with the surface’s slope to the light, and soften the edges by filtering several texels, percentage closer filtering.22

light
▮ reads lit▮ reads shadowed● wrong▬ where the shadow really is
acne
18
lit ground shadowed by its own texel. it clears at a bias of 0.14
leaks
0
shadow read as lit, from too much bias. the ledge's shadow leaks from 0.54
edges
2
within a texel of a shadow's edge, where the texel saw the other side

a side view of a shadow map. a light from the upper left, a tall box and a low ledge on the ground. the light's view is a row of texels, each with a cyan ray to the first thing it hits. each point along the ground is a bar, amber where the map says lit and gray where it says shadowed, with a red dot under a wrong one. a bar under the ground marks where the shadows really are. buttons pick 8, 16, 32 or 64 texels and a slider sets the bias from 0 to 0.6. it opens at 16 texels and no bias, with 18 points of acne. the acne clears at a bias of 0.14, and past 0.54 the ledge's shadow starts to leak.

acne wants more bias and leaks want less. more texels shrink what acne needs, so the room between the two grows.

three.js does all of this behind a few switches: renderer.shadowMap.enabled, castShadow on the light and the objects, receiveShadow on the ground. all are off by default, and light.shadow starts with a bias and a normalBias of 0 and a 512 × 512 map.23

renderer.shadowMap.enabled = true;
light.castShadow = true;
light.shadow.mapSize.set(1024, 1024);
light.shadow.bias = -0.0005; // three.js adds it to the depth, so negative is toward the light. tune it by eye
box.castShadow = true;
ground.receiveShadow = true;

color spaces + gamma

an 8-bit color channel doesn’t store light. srgb stores it on a curve that spends more of the 256 codes on the darks: the darkest 10% of the light gets 35% of the range. so a stored 0.5 is about 21% of white’s light, and half of white’s light is stored as 0.735: 188 of 255, #bcbcbc.24

light={c12.92c≤0.04045(c+0.0551.055)2.4c>0.04045\text{light} = \begin{cases} \dfrac{c}{12.92} & c \le 0.04045 \\[6pt] \left(\dfrac{c + 0.055}{1.055}\right)^{2.4} & c > 0.04045 \end{cases}

light adds: two lamps on a wall give the sum of their light. so lighting, blending and blurring belong in linear light. decode a color when you read it, do the math, and encode once at the end. mixing the stored values instead comes out too dark in the middle. halfway from red to green is #808000 mixed as stored values, 20% of white’s light, against #bcbc00 mixed as light, 47%.25

// the srgb transfer function from css color 4, one channel at a time. c is 0 to 1
vec3 toLinear(vec3 c) {
  return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, step(c, vec3(0.04045)));
}
vec3 toSrgb(vec3 c) {
  return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, step(c, vec3(0.0031308)));
}

css mixes hex, named and rgb() colors as stored srgb values by default, for compatibility, though the spec itself says that gives overly dark or grayish mixes, and names srgb-linear as the space for mixing lights. a gradient can ask for it, in chrome 111, firefox 127 and safari 16.2 and later:26

.stored {
  background: linear-gradient(to right, red, lime); /* mixed as stored values */
}
.light {
  background: linear-gradient(to right in srgb-linear, red, lime); /* mixed as light */
}

mixed as stored values: what css does with hex colors

#808080 gives 22% of white's light

mixed as light, then stored

#bcbcbc gives 50% of white's light

stored value, 0 to 1light, 0 to 1011

one channel on its way from 0 to 1, 50% along. the cyan strip stores 128 of 255, which is 22% of the light. the amber strip has 50% of the light, stored as 188 of 255. dashed: a straight line, if stored values were light.

two strips between the same two colors, black to white, red to green or blue to yellow. the cyan one mixes the stored srgb values, the way css mixes hex colors, the amber one mixes the light and then stores it. a slider moves a marker along both and reads each one's hex color and its share of white's light: halfway from black to white, #808080, 128 of 255, gives 22%, and #bcbcbc, 188 of 255, gives 50%. below, the srgb curve from stored value to light, with both strips' points on it at the slider, and a dashed straight line for comparison.

the cyan strip is what css draws for a gradient between two hex colors. the amber one is what the light would do. #808080 is 128 of 255, a hair over 0.5, so it gives 22%, not 21%.

webgl 2 can do both steps in hardware. a texture stored as SRGB8_ALPHA8 is decoded to linear when it is sampled, and a framebuffer with srgb encoding re-encodes after blending.27 three.js works in linear srgb, and encodes to renderer.outputColorSpace, srgb by default, at the end of its shaders. a texture’s colorSpace starts as NoColorSpace. set it to SRGBColorSpace for color images, and leave it for data like normal and roughness maps.28

pitfalls

sources

  1. the opengl es shading language 3.00 spec (opens in a new tab), section 8.5 for dot, cross, length, normalize and reflect, which computes i − 2 (n · i) n and needs n normalized, and section 8.6 for transpose and inverse. ↩ ↩2

  2. the opengl es shading language 3.00 spec (opens in a new tab), section 4.1.6: the first number in a matrix type is its columns, and constructors fill it in column-major order. section 5.6: one subscript picks a column, so m[1] is the second column. ↩

  3. the opengl es 3.0.6 spec (opens in a new tab), section 2.12.6.1: with transpose false, UniformMatrix4fv takes the matrix in column-major order. the webgl 2.0 spec (opens in a new tab) describes an api that conforms closely to opengl es 3.0. ↩

  4. three.js r186: Matrix4.js (opens in a new tab), where set() takes its arguments in row-major order, elements is column-major, and compose() builds the matrix from position, rotation and scale; Object3D.js (opens in a new tab), whose updateMatrix() calls compose(); Matrix3.js (opens in a new tab), where getNormalMatrix() is the inverse transpose of the upper 3 × 3; and Euler.js (opens in a new tab), whose angles are in radians. ↩ ↩2 ↩3 ↩4 ↩5

  5. three.js r186, the project_vertex (opens in a new tab) shader chunk: modelViewMatrix times the position, then projectionMatrix times that, into gl_Position. ↩

  6. three.js r186: PerspectiveCamera.js (opens in a new tab), whose constructor defaults to a fov of 50, an aspect of 1, near 0.1 and far 2000, with fov the vertical angle in degrees, and whose updateProjectionMatrix() must be called after any change; and makePerspective() in Matrix4.js (opens in a new tab), with one depth mapping for webgl and one for webgpu that runs from 0 to 1. ↩ ↩2 ↩3 ↩4

  7. the gluLookAt (opens in a new tab) reference page: the view matrix maps the eye to the origin and the point looked at onto the negative z axis, with up mapped to positive y. ↩

  8. the opengl es 3.0.6 spec (opens in a new tab), section 2.13 for the divide by w into normalized device coordinates, 2.13.1 for the viewport, whose x and y give its lower left corner, and 2.18 for the clip volume, −w to w on each axis. ↩ ↩2 ↩3

  9. the gluPerspective (opens in a new tab) reference page: fovy is the vertical angle in degrees, the aspect should match the viewport’s, f is the cotangent of fovy / 2, the matrix itself, and the note that about log₂(zFar / zNear) bits of depth precision are lost, so zNear must never be 0. ↩ ↩2 ↩3

  10. juan pineda, a parallel algorithm for polygon rasterization (opens in a new tab), siggraph 1988. checked against its abstract on the acm siggraph history archive (opens in a new tab): each edge of a polygon as a linear edge function, above zero on one side and below zero on the other, interpolated by the same kind of hardware that interpolates color and z, and computed for neighboring pixels in parallel. ↩

  11. the opengl es 3.0.6 spec (opens in a new tab), section 3.6.1: fragment centers inside the triangle are produced, a center on an edge shared by two triangles is produced by exactly one of them, attributes are blended with barycentric weights divided by each corner’s w (equation 3.7), and depth is blended without that divide (equation 3.8). ↩ ↩2

  12. microsoft’s rasterization rules (opens in a new tab) for direct3d: the top-left rule, and what counts as a top, bottom, left and right edge. ↩

  13. turner whitted, an improved illumination model for shaded display (opens in a new tab), communications of the acm, june 1980. checked against its abstract on the acm siggraph history archive (opens in a new tab): a tree of rays per pixel, from the viewer to the first surface and from there to other surfaces and to the lights, for reflection, shadows and refraction. ↩

  14. james blinn, models of light reflection for computer synthesized pictures (opens in a new tab), siggraph 1977: lambert’s law, the halfway direction h and the cosine between n and h taken to a power, typically 50 or 60, h computed once per light when the light and the eye are far away, and trowbridge and reitz’s facet distribution. ↩ ↩2 ↩3

  15. bui tuong phong, illumination for computer generated pictures (opens in a new tab), communications of the acm, june 1975: the normal interpolated along each edge (equation 2), and the shading function with its specular term, a power n of the cosine between the reflected light and the line of sight, with n from 1 to 10, set by eye (equation 3, page 315). ↩

  16. robert cook and kenneth torrance, a reflectance model for computer graphics (opens in a new tab), siggraph 1981, with a longer version in acm transactions on graphics in 1982. checked against its abstract on the acm siggraph history archive (opens in a new tab), which lists beckmann and spizzichino among its references, and against the pbr book’s further reading (opens in a new tab) on reflection models, which calls it a variant of torrance and sparrow’s microfacet model. ↩

  17. the gltf 2.0 spec (opens in a new tab), appendix b: the trowbridge-reitz / ggx distribution, the height-correlated smith term folded into a visibility function, schlick’s fresnel, α = roughness², a dielectric with an index of refraction of 1.5, so f0 = 0.04, mixed with a lambertian diffuse by fresnel, metals with f0 taken from the base color, α = 0 kept out of the formula, and the note that walter et al. found ggx fits measured data better than beckmann. ↩ ↩2 ↩3 ↩4

  18. bruce walter, stephen marschner, hongsong li and kenneth torrance, microfacet models for refraction through rough surfaces (opens in a new tab), eurographics symposium on rendering 2007. checked against the pbr book’s microfacet section (opens in a new tab): walter and others derived the trowbridge-reitz distribution on their own and called it ggx, and its long tails, longer than beckmann’s, match many real surfaces. ↩

  19. christophe schlick, an inexpensive brdf model for physically-based rendering (opens in a new tab), computer graphics forum, 1994, equation 15: fresnel as f + (1 − f)(1 − u)^5, with u the cosine of the angle, checked against the author’s copy, eur2.ps.gz (opens in a new tab). ↩

  20. brian karis, real shading in unreal engine 4 (opens in a new tab), siggraph 2013 course notes: lambert for diffuse, ggx for the distribution, worth its small extra cost over blinn-phong, schlick’s g and fresnel, and α = roughness², taken from disney’s model. ↩

  21. lance williams, casting curved shadows on curved surfaces (opens in a new tab), siggraph 1978: a z-buffer view from the light, then each point the observer sees moved into it and tested, a bias subtracted so surfaces don’t shadow themselves, and a cost of roughly twice rendering the scene. ↩ ↩2

  22. microsoft’s common techniques to improve shadow depth maps (opens in a new tab): shadow acne, peter panning from too large a depth offset, slope-scaled depth bias, tight near and far planes for the light, and percentage closer filtering for softer edges. ↩ ↩2 ↩3 ↩4

  23. three.js r186: WebGLShadowMap.js (opens in a new tab), where enabled starts false, Object3D.js (opens in a new tab), where castShadow and receiveShadow start false, LightShadow.js (opens in a new tab), with bias and normalBias at 0 and mapSize at 512 by 512, and the shadowmap_pars_fragment (opens in a new tab) chunk, which adds the bias to the point’s depth before the compare, so a negative bias moves it toward the light. ↩

  24. css color 4 (opens in a new tab), section 10.2: the srgb transfer function, linear up to 0.04045 and a 2.4 power above it. the shares of light are computed from it. ↩

  25. the shares of white’s light use the y row of the srgb to xyz matrix in css color 4 (opens in a new tab)’s sample code, section 19: about 0.2126 of red, 0.7152 of green and 0.0722 of blue, in linear light. ↩

  26. css color 4 (opens in a new tab), section 13.2: srgb-linear for mixing lights, srgb’s overly dark or grayish mixes, and legacy colors interpolated as gamma-encoded srgb for web compatibility. css images 4 (opens in a new tab), section 3.1, for the color space in linear-gradient(), and mdn’s linear-gradient() (opens in a new tab) compatibility table for the browser versions. ↩

  27. the opengl es 3.0.6 spec (opens in a new tab), section 3.8.16, srgb textures converted to linear as part of filtering, and section 4.1.8, colors converted back to srgb after blending into an srgb framebuffer. ↩

  28. three.js r186: ColorManagement.js (opens in a new tab), with linear srgb as the working color space; WebGLRenderer.js (opens in a new tab), with outputColorSpace set to srgb; Texture.js (opens in a new tab), with colorSpace starting as NoColorSpace; the colorspace_pars_fragment (opens in a new tab) chunk, the transfer function in glsl; and the colorspace_fragment (opens in a new tab) chunk, the last step of a material’s fragment shader, as in meshphysical (opens in a new tab), which converts the color for the output. ↩