WebGPU From Zero · Episode 09
Depth & the Third Dimension
Depth & the Third Dimension is Episode 09 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Every demo in Season 1 was flat. A gradient, some particles, a 2D field — all of it lived on the screen plane because we never left it. We fed the GPU clip-space coordinates directly and called it a day. But a triangle isn't a thing. To make a thing — something with a front and a back, something you can rotate and that hides its own far side — you need two pieces of machinery: a camera that projects 3D points onto the screen, and a depth buffer that remembers, for every pixel, how far away the closest fragment was. Without the second one, your cube is a glass shell: back faces paint over front faces and the whole thing turns to mush.
This episode builds both, from nothing. We write the 4×4 matrix math by hand (a dozen
lines — WebGPU has no math library, and we like it that way), assemble a
model · view · projection chain, ship it to the vertex shader as a
uniform, and add a depth24plus texture so fragments fight for each pixel and
the nearest one wins. The payoff is a spinning, lit cube that occludes itself correctly —
and then a whole drifting cloud of them. Watch Stage 1 garble itself first; the fix in
Stage 2 is the most dramatic single toggle in the series.
What you're looking at
One cube (or, at the last stage, a few dozen) built from 24 vertices and 36 indices, living in real 3D world space. A perspective camera sits some distance back — drag the distance slider to dolly it in and out — and looks at the origin. The spin slider controls how fast the cube tumbles. The badge bottom-left tells you whether you're on the real WebGPU path or the Canvas2D fallback, and the description bottom-right narrates the current stage. The six stages are the same machine revealed one part at a time:
Stages 1 and 2 are deliberately the same scene with one difference — the depth test — so you feel what the depth buffer does. Everything from Stage 3 on assumes depth is on. Let's walk the machine.
Stage 1 — A cube through MVP, with no depth test
We have a cube in world space and a camera. To get from a 3D vertex to a 2D pixel, we
multiply by three matrices in order: model (place the cube in the world),
view (move the world so the camera sits at the origin looking down −Z),
and projection (apply perspective foreshortening and squash everything
into clip space). Concatenate them — P · V · M — and one matrix-times-vector
in the vertex shader does the whole journey.
That part works immediately: you'll see a cube-shaped silhouette. But look closely as it turns and it's wrong. Triangles are drawn in the order they appear in the index buffer, and the GPU has no idea that the back-left face is behind the front-right one. Whichever triangle is rasterized last wins the pixel, regardless of depth. The result is a garbled, see-through shell where edges that should be hidden punch through to the front. This is the bug the next stage exists to kill.
Stage 2 — The depth buffer (the dramatic fix)
The fix is a second texture the size of the canvas, holding one depth value per pixel.
We allocate a depth24plus texture, tell the pipeline about it with a
depthStencil state (depthCompare: 'less',
depthWriteEnabled: true), and attach it to the render pass. Now, before the
GPU writes a fragment, it compares the fragment's depth to whatever is already stored at
that pixel. Closer? Draw it and update the stored depth. Farther? Discard it. The
back faces lose every fight they should lose, and the cube snaps into a solid object.
Flip between Stage 1 and Stage 2 a few times. Same geometry, same camera, same shader — one extra texture and three lines of pipeline config turn a chaotic mesh into a thing with a near side and a far side. This is the single most important idea in real-time 3D, and it costs almost nothing.
Stage 3 — The perspective camera
So far the camera has been static. Now we make it real. The projection
matrix comes from mat4.persp(fov, aspect, near, far) — note that WebGPU's clip
space puts z in [0, 1], not OpenGL's [−1, 1], so our
persp() is built for that range (get this wrong and everything clips at the
wrong plane). The view matrix comes from mat4.lookAt(eye, target,
up), which builds a basis from the camera's position and a point to stare at. Drag
the distance slider: the cube grows and shrinks with honest perspective foreshortening,
near edges splaying wider than far ones.
Stage 4 — The model transform (spin it)
The model matrix is where the cube earns its own place in the world independent of the
camera. We build it as rotY(t) · rotX(t · 0.6) — a rotation about the vertical
axis composed with a slower tilt about the horizontal — so the cube tumbles on two axes at
once. Because matrix multiply is not commutative, order matters: apply
rotX first (right-most, closest to the vertex), then rotY. Crank
the spin slider and watch every face take its turn facing you, each one correctly occluding
the faces behind it thanks to Stage 2.
Stage 5 — Simple shading (normal · light)
A solid white cube is hard to read — without shading, adjacent faces blur into one
silhouette. So we give each vertex a normal (the direction its face points)
and, in the fragment shader, compute max(dot(N, L), 0) against a fixed light
direction. Faces square-on to the lamp glow; faces at a glancing angle fall into shadow.
Because normals must rotate with the cube, we pass a second matrix — the rotation part of
the model — and transform the normal by it before the dot product. Now the cube reads as a
genuine solid: you can see its corners and edges by the way light rakes across them.
Stage 6 — Many cubes + an orbiting camera
Depth, camera, model, and shading all compose for free across many objects. We scatter a few dozen cubes through space, each with its own position, size, and spin phase, and set the camera auto-orbiting in a slow circle so the scene is alive the instant the page loads — no input required. Every cube is depth-tested against every other, so near cubes cleanly hide far ones. This is a recognizable little 3D scene, built from nothing but inline matrices and one depth texture.
The code
Four pieces carry this episode: building the MVP and shipping it as a uniform; creating the depth texture and wiring it into the pipeline and pass; generating the cube geometry with a vertex layout; and the WGSL that applies the matrix and shades by normal. Here is the real code, lightly trimmed.
1 · Build P · V · M and write the uniform
The mat4 helpers are column-major, matching WGSL's mat4x4<f32>
memory layout, so a Float32Array(16) in this order maps 1:1 onto the uniform.
We send two matrices: the full MVP for positions, and the model's rotation for normals.
// column-major mat4 helpers — WebGPU clip z is [0,1], persp targets it
const mat4 = {
ident:()=>[1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1],
mul(a,b){const o=new Array(16);for(let c=0;c<4;c++)for(let r=0;r<4;r++)
o[c*4+r]=a[r]*b[c*4]+a[4+r]*b[c*4+1]+a[8+r]*b[c*4+2]+a[12+r]*b[c*4+3];return o;},
persp(fovy,asp,n,f){const t=1/Math.tan(fovy/2);return [t/asp,0,0,0, 0,t,0,0, 0,0,(f)/(n-f),-1, 0,0,(f*n)/(n-f),0];},
rotY(a){const c=Math.cos(a),s=Math.sin(a);return [c,0,-s,0, 0,1,0,0, s,0,c,0, 0,0,0,1];},
rotX(a){const c=Math.cos(a),s=Math.sin(a);return [1,0,0,0, 0,c,s,0, 0,-s,c,0, 0,0,0,1];},
lookAt(eye,tgt,up){const z=norm(sub(eye,tgt)),x=norm(cross(up,z)),y=cross(z,x);
return [x[0],y[0],z[0],0, x[1],y[1],z[1],0, x[2],y[2],z[2],0, -dot(x,eye),-dot(y,eye),-dot(z,eye),1];},
};
// per frame: concatenate, then upload 2 matrices into one 128-byte uniform
const proj = mat4.persp(1.0, canvas.width/canvas.height, 0.1, 100);
const view = mat4.lookAt([0, 0, dist], [0,0,0], [0,1,0]);
const model = mat4.mul(mat4.rotY(t), mat4.rotX(t*0.6)); // rotX applied first
const mvp = mat4.mul(proj, mat4.mul(view, model)); // P · V · M
uni.set(mvp, 0); // mat4x4 at byte 0
uni.set(model, 16); // model (rotation) at byte 64 — for normals
device.queue.writeBuffer(ubo, 0, uni);
2 · The depth texture + pipeline state + attachment
Three touch-points: a texture with RENDER_ATTACHMENT usage, a
depthStencil block on the pipeline, and a depthStencilAttachment on
the pass. Stage 1 simply omits all three; Stage 2 turns them on — that's the whole
difference. The texture must be recreated on resize or it won't match the canvas.
// (re)create whenever the canvas size changes
function makeDepth() {
if (depthTex) depthTex.destroy();
depthTex = device.createTexture({
size: [canvas.width, canvas.height],
format: 'depth24plus',
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
}
// on the pipeline — present only for the depth-on stages
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: { module, entryPoint: 'vs', buffers: [vbLayout] },
fragment: { module, entryPoint: 'fs', targets: [{ format }] },
primitive:{ topology: 'triangle-list', cullMode: 'back' },
depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
});
// on the render pass
const pass = enc.beginRenderPass({
colorAttachments: [{ view: context.getCurrentTexture().createView(),
clearValue: { r:0.04, g:0.05, b:0.07, a:1 }, loadOp:'clear', storeOp:'store' }],
depthStencilAttachment: {
view: depthTex.createView(),
depthClearValue: 1.0, // far plane = 1 in WebGPU's [0,1]
depthLoadOp: 'clear', depthStoreOp: 'store',
},
});
3 · Cube geometry + vertex layout
24 vertices (not 8) because each face needs its own flat normal — a corner shared by three faces can't carry three different normals. Each vertex is 6 floats: position then normal. 36 indices stitch the 6 faces into 12 triangles, wound counter-clockwise so back-face culling keeps the inside hidden.
// one face = 4 verts (pos.xyz, normal.xyz) + 2 triangles
function cube() {
const f = [ // [normal, and the 4 corner offsets in that face's plane]
[[0,0,1], [[-1,-1],[1,-1],[1,1],[-1,1]]], // +Z front
[[0,0,-1], [[1,-1],[-1,-1],[-1,1],[1,1]]], // −Z back
[[1,0,0], [[1,-1],[1,-1],[1,1],[1,1]]], // +X right
/* …−X, +Y, −Y … */
];
const verts = [], idx = [];
f.forEach((face, fi) => {
const [nrm, corners] = face;
corners.forEach(c => verts.push(/* pos from corner+normal */ 0, ...nrm));
const b = fi * 4;
idx.push(b, b+1, b+2, b, b+2, b+3); // CCW winding
});
return { verts: new Float32Array(verts), idx: new Uint16Array(idx) };
}
// the layout the pipeline reads: 6 floats per vertex = 24-byte stride
const vbLayout = {
arrayStride: 6 * 4,
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x3' }, // position
{ shaderLocation: 1, offset: 3*4, format: 'float32x3' }, // normal
],
};
4 · The WGSL — vertex applies MVP, fragment does N · L
The vertex shader multiplies the position by the MVP and rotates the normal by the model matrix. The fragment shader does one diffuse dot product against a fixed light, with a touch of ambient so back faces aren't pure black.
struct Uniforms {
mvp: mat4x4<f32>,
model: mat4x4<f32>, // rotation only — rigid cube, so this is fine for normals
};
@group(0) @binding(0) var<uniform> u: Uniforms;
struct VSOut {
@builtin(position) pos: vec4f,
@location(0) normal: vec3f,
};
@vertex fn vs(@location(0) pos: vec3f, @location(1) nrm: vec3f) -> VSOut {
var o: VSOut;
o.pos = u.mvp * vec4f(pos, 1.0); // 3D → clip space
o.normal = (u.model * vec4f(nrm, 0.0)).xyz; // w=0: rotate, don't translate
return o;
}
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
let N = normalize(in.normal);
let L = normalize(vec3f(0.4, 0.8, 0.5)); // fixed light direction
let diff = max(dot(N, L), 0.0);
let shade = 0.18 + 0.82 * diff; // ambient + diffuse
return vec4f(vec3f(0.55, 0.78, 0.98) * shade, 1.0);
}
Common pitfalls
- No depth test = wrong overlap (the headline bug). Without a depth
attachment, triangles paint in index order and far faces bleed over near ones. If your
mesh looks see-through or scrambled, you forgot the depth texture, the
depthStencilpipeline state, or thedepthStencilAttachment— you need all three. This is exactly Stage 1 vs Stage 2. - WebGPU clip space z is [0, 1], not [−1, 1]. If you paste an OpenGL
perspective matrix, near/far map to the wrong range and geometry clips early or z-fights.
Use a
persp()built for[0, 1](this one is) and clear depth to1.0(the far plane), compare with'less'. - mat4 is column-major. Our arrays are laid out column-by-column to
match
mat4x4<f32>. If your cube is sheared or transposed, you're feeding row-major data into a column-major uniform — don't transpose by hand, keep the layout consistent end to end. - Cull mode & winding must agree. With
cullMode: 'back'the GPU drops triangles whose vertices wind clockwise on screen. Get the winding backwards and your cube turns inside-out (you see only the far faces). Match your index order to your cull mode, or setcullMode: 'none'while debugging. - Recreate the depth texture on resize. A depth texture is a fixed size. If the canvas grows and the depth texture doesn't, the render pass fails validation ("attachment sizes must match"). Rebuild it in your resize handler alongside reconfiguring the canvas.
- Don't translate normals. Transform normals with
w = 0.0so the translation column is ignored — and for a rigid spin, use only the rotation part of the model matrix (a non-uniform scale would need the inverse-transpose instead).
Exercises
- Orbit camera on drag. Capture
pointerdown/move, turn the mouse delta into yaw and pitch angles, and placeeyeon a sphere around the target with[r·cos(pitch)·sin(yaw), r·sin(pitch), r·cos(pitch)·cos(yaw)]. Feed that intolookAt. You now fly around the cube — and the depth buffer keeps the occlusion correct from every angle. - Add a ground plane. Generate two triangles at
y = −1with an up-facing normal and draw them in the same pass. Watch the cubes' near edges correctly occlude the floor behind them — proof the depth test works across different meshes, not just within one. - Instance the cubes. Stage 6 redraws the cube N times with a loop and
a uniform rewrite per cube. Replace it with a single instanced
draw(36, N): put per-cube transforms in a storage buffer and index it by@builtin(instance_index)in the vertex shader. One draw call, hundreds of cubes — the same trick Season 1's particles used.
What's next
Episode 10 — PBR Lighting in WGSL. Our N · L is the crudest
possible lamp: no specular highlight, no notion of how rough or metallic a surface is, no
energy conservation. Next we build a physically based shading model — the
Cook–Torrance microfacet BRDF — directly in WGSL, so the cube stops looking like flat plastic
and starts looking like a real material catching real light. Same depth-tested 3D scene, a
far better fragment shader.