WebGPU From Zero · Episode 16

A Tiny Renderer

A Tiny Renderer is Episode 16 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 16 · WebGPU From Zero · Season 2 Finale

Eight episodes ago we couldn't even draw a triangle in 3D. Now look at the scene below: a handful of meshes resting on a ground plane, each made of a different physical material — gold, painted plastic, brushed steel — lit by a sun that casts soft real-time shadows, the whole thing graded with bloom and tonemapped to film. It orbits on its own. It holds sixty frames a second. And it is built from nothing but the pieces you already wrote this season, finally bolted together into one small machine: a real renderer.

This is the finale, so we're not learning a new technique — we're assembling the ones we have into something you could actually ship a scene with. The promise: by the end of this page you'll have a tiny but honest engine — a scene graph of meshes, materials and lights as plain data; per-object bind groups; and a single render() that runs the passes in exactly the right order (shadow → main into an offscreen HDR target → post to the screen). Small enough to read in one sitting, structured enough to grow. That's the difference between a demo and a renderer, and it's the whole season in one file.

0 fps
the scene auto-orbits · step through the stages →
init…
The full tiny renderer: lit, shadowed, bloom-graded, auto-orbiting.

What you're looking at

A small diorama: a wide floor with four objects on it — a cube, a sphere, a torus, and a torus-knot — each a different PBR material, lit by one directional "sun" plus a couple of cool fill lights, with a camera that slowly orbits so the scene is alive the instant the page paints. The stage selector builds the renderer up one capability at a time, ending on the full thing. quality scales the shadow-map resolution and render scale (the knob a real engine exposes as "Low / Medium / High"), and post toggles the bloom + tonemap pass so you can A/B the grade. The badge bottom-left shows the backend (WebGPU or a fallback) and the shadow-map size.

The point of this episode is the architecture, so here's the shape of the whole machine up front. Three passes, in order, every frame:

render(scene) — three passes into one command encoder, in this order: ① SHADOW PASS ② MAIN PASS ③ POST PASS ┌──────────────────┐ ┌────────────────────────┐ ┌────────────────────┐ │ scene → depth │ │ scene → color + depth │ │ HDR → bloom + │ │ from the LIGHT │───▶│ lit + sample shadow map │──▶│ tonemap → SCREEN │ │ (depth32f, 1–2k²) │ │ into OFFSCREEN rgba16f │ │ (swapchain srgb) │ └──────────────────┘ └────────────────────────┘ └────────────────────┘ writes shadowTex reads shadowTex, reads hdrTex, writes hdrTex writes the canvas

Everything below is one of those three boxes, or the data that flows between them.

Stage 1 — A scene and a camera

Start with the absolute floor of "a renderer": some geometry, a camera, and a depth test so near things cover far things. We generate four meshes in JavaScript (no asset files — the procedural generators from Episodes 09–11), drop them on a ground plane, and spin an orbit camera around them with the inline mat4 math we've used all season. No lighting yet — every object is flat-shaded by its base color — but the depth buffer already makes it read as 3D: the torus passes behind the sphere, the cube sits in front of the floor. This is the skeleton. Everything else hangs off it.

Stage 2 — PBR materials

Now each object becomes a material. We bring back the Cook-Torrance / GGX microfacet BRDF from Episode 10 — metallic, roughness, base color, Fresnel — and give every mesh its own values: the sphere is polished gold, the cube is matte red plastic, the torus is brushed steel, the knot is copper. Same shader, four sets of numbers, four believable materials. This is the first hint of the data model that makes a renderer reusable: a material is just a little bundle of numbers attached to a mesh, not a bespoke shader per object.

Stage 3 — A shadow-casting light

The objects are lit but still float — nothing casts anything. We add the shadow pass from Episode 11: render the scene once from the sun's point of view into an offscreen depth texture (the shadow map), then in the main pass ask each fragment "is something closer to the light than I am?" using a sampler_comparison with PCF for soft edges. The contact shadows snap the scene to the ground — and crucially, this is our first pass that another pass depends on. The shadow texture written in pass ① is sampled in pass ②. Pass ordering has started to matter.

Stage 4 — Post-processing (bloom + tonemap)

Real renderers don't draw straight to the screen — they render the scene into an offscreen HDR target (here an rgba16float texture, which can hold values brighter than 1.0), then run a post pass that reads that texture and writes the final image. We bring back Episode 13's stack: extract the bright parts, blur them into a glow (bloom), add it back, then tonemap the HDR result down to displayable sRGB. The gold and copper highlights bloom; the whole image gets a filmic roll-off instead of clipping to white. Toggle post off to see the raw HDR buffer (clamped) and feel what the grade buys you.

Stage 5 — The engine: scene, materials, lights as data

This is the stage that's really the episode. Everything above was features; this is structure. We stop writing one-off draw code and define a small data model: a scene is { meshes, lights, camera }; a mesh is { geometry, material, transform }; a material is the PBR numbers; a light is a direction/position + color. Then one function, render(scene), walks that data and runs the three passes. Add an object? Push a mesh. Change a look? Edit a material. Move the sun? Mutate a light. No pipeline surgery. Visually this stage looks like Stage 4 — that's the point: the picture didn't change, but the code behind it became a renderer you can drive with data instead of edit by hand.

Stage 6 — The full tiny renderer

Everything on, tuned, and composed: four materials, a sun with soft shadows plus two cool fill lights, HDR + bloom + tonemap, an auto-orbiting camera, all driven by the data model from Stage 5. This is the payoff promised at the top — a lit, shadowed, bloom-graded 3D scene that is also a clean, reusable renderer. It is, structurally, a miniature of what a real engine does every frame. You built the whole thing from navigator.gpu up, with zero dependencies.

The code (a): the mini-engine data model

The heart of "a renderer, not a demo" is that the scene is data, not code. Geometry, materials, lights, and transforms are plain objects; the renderer consumes them. Here's the entire model — small enough to hold in your head, which is exactly the bar for a tiny renderer:

// A material is just numbers. Reused by any mesh that points at it.
function material({ color, metallic, roughness, emissive = 0 }) {
  return { color, metallic, roughness, emissive };
}

// A mesh = geometry (GPU buffers) + a material + a world transform (mat4).
function mesh(geometry, mat, transform) {
  return { geometry, material: mat, transform };
}

// The scene = the three things every renderer needs: things, lights, an eye.
const scene = {
  meshes: [
    mesh(geo.plane,  matFloor, mat4.translate(0, -1, 0)),
    mesh(geo.sphere, matGold,  mat4.translate(-1.7, -0.4, 0)),
    mesh(geo.cube,   matRed,   mat4.translate( 0.0, -0.4, -0.4)),
    mesh(geo.torus,  matSteel, mat4.translate( 1.7, -0.45, 0)),
    mesh(geo.knot,   matCopper,mat4.translate( 0.0, -0.3,  1.6)),
  ],
  lights: [
    { kind: 'sun', dir: [0.5, 0.95, 0.3], color: [1.0, 0.96, 0.9], intensity: 3.2, castsShadow: true },
    { kind: 'point', pos: [-3, 2, 2], color: [0.4, 0.6, 1.0], intensity: 10 },
    { kind: 'point', pos: [ 3, 1.5, -1], color: [1.0, 0.5, 0.6], intensity: 8 },
  ],
  camera: { fovy: 50, near: 0.1, far: 60, eye: [0, 3, 6.4], target: [0, -0.3, 0] },
};

That's it. Note what's not here: no pipeline objects, no bind groups, no passes. Those are the renderer's job, kept on the other side of a clean line. Authoring a scene never touches WebGPU.

The code (b): render() — the passes, in order

One function turns that data into a frame. The single most important thing about a renderer is pass order, and it falls right out of the data dependencies: the main pass samples the shadow map, so shadows go first; post reads the HDR target, so the main pass goes into an offscreen texture before post; post writes the swapchain last. Get this order wrong and you sample a texture that hasn't been written yet (garbage, or a validation error). Here is the whole orchestration:

function render(scene) {
  const enc = device.createCommandEncoder();
  const lightVP = fitSunToScene(scene);   // ortho frustum bounding the scene

  // ① SHADOW PASS — depth only, from the sun's MVP, into shadowTex.
  if (stage >= 2) {
    const sp = enc.beginRenderPass({
      colorAttachments: [],                       // no color — depth is the product
      depthStencilAttachment: shadowAttach,       // the depth32float shadow map
    });
    sp.setPipeline(shadowPipeline);
    for (const m of scene.meshes) drawMesh(sp, m, 'shadow', lightVP);
    sp.end();
  }

  // ② MAIN PASS — lit + shadowed, into the OFFSCREEN HDR target (rgba16float).
  const target = post ? hdrView : context.getCurrentTexture().createView();
  const mp = enc.beginRenderPass({
    colorAttachments: [{ view: target, clearValue: SKY, loadOp: 'clear', storeOp: 'store' }],
    depthStencilAttachment: sceneDepthAttach,
  });
  mp.setPipeline(mainPipeline);
  for (const m of scene.meshes) drawMesh(mp, m, 'main', lightVP, scene);
  mp.end();

  // ③ POST PASS — read the HDR texture, bloom + tonemap, write the SCREEN.
  if (post) {
    const pp = enc.beginRenderPass({
      colorAttachments: [{ view: context.getCurrentTexture().createView(),
                           loadOp: 'clear', storeOp: 'store', clearValue: BLACK }],
    });
    pp.setPipeline(postPipeline);
    pp.setBindGroup(0, postBind);     // samples hdrTex
    pp.draw(3);                        // one fullscreen triangle
    pp.end();
  }

  device.queue.submit([enc.finish()]);
}

Read it top to bottom and you've read the engine. Three passes, one encoder, one submit. Each pass's output is the next pass's input, which is why the order is the order. (We bloom in the post fragment shader with a small multi-tap blur to keep it one pass; a production engine would ping-pong a few downsampled blur passes — the structure is identical, just more of them.)

The code (c): a mesh + material becomes a draw call

Between "data" and "passes" sits the glue: turning one mesh into a draw. Each object needs its own uniforms (its model matrix, normal matrix, and material), so each object needs its own slice of a uniform buffer and its own bind group. We pack all objects' uniforms into one big buffer and give each a 256-byte-aligned offset — WebGPU requires uniform buffer bindings to start on a 256-byte boundary (minUniformBufferOffsetAlignment), so we round each object's stride up to 256:

// One UBO holds every object's per-draw uniforms, 256-aligned per object.
const ALIGN = 256;                                  // minUniformBufferOffsetAlignment
const STRIDE = ALIGN * Math.ceil(PER_OBJ_BYTES / ALIGN); // our struct is < 256 → STRIDE = 256
const objUBO = device.createBuffer({
  size: STRIDE * scene.meshes.length,
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});

// A bind group per object, each pointing at its 256B window via a dynamic-ish offset.
// (We use an explicit offset in the BindGroup; you can also use one bind group with
//  hasDynamicOffset:true and pass the offset to setBindGroup — same idea.)
scene.meshes.forEach((m, i) => {
  m._mainBind = device.createBindGroup({
    layout: mainPipeline.getBindGroupLayout(0),
    entries: [
      { binding: 0, resource: { buffer: objUBO, offset: i * STRIDE, size: PER_OBJ_BYTES } },
      { binding: 1, resource: frameBind },     // shared: camera, lights, shadow VP
      { binding: 2, resource: shadowView },    // the shadow map
      { binding: 3, resource: shadowSampler },
    ],
  });
});

// drawMesh: write this object's uniforms into its window, bind, draw.
function drawMesh(pass, m, which, lightVP, scene) {
  const i = m._index;
  writeObjectUniforms(objUBO, i * STRIDE, m, lightVP);   // model, normalMat, material…
  pass.setBindGroup(0, which === 'shadow' ? m._shadowBind : m._mainBind);
  pass.setVertexBuffer(0, m.geometry.vb);
  pass.setIndexBuffer(m.geometry.ib, 'uint16');
  pass.drawIndexed(m.geometry.count);
}

This per-object bind-group pattern is the thing that scales a "one cube" demo into a "scene of N objects" renderer. It's also where the 256-alignment rule bites people exactly once — forget it and pipeline creation throws "offset … is not a multiple of 256."

The code (d): the pass targets, and why they're shaped that way

Three passes need three sets of render targets, and each one's format and usage is chosen for its job. This table is the whole "render graph," such as it is:

PassColor targetDepth targetWhy
① Shadownonedepth24plus shadow map
(RENDER_ATTACHMENT | TEXTURE_BINDING)
We only want depth, and we must sample it later, so it's both a render target and a texture. We use depth24plus (not depth32float) because it's universally filterable through a comparison sampler — see the pitfalls.
② Mainrgba16float HDR
(RENDER_ATTACHMENT | TEXTURE_BINDING)
depth24plus scene depthHDR float so highlights can exceed 1.0 for bloom; sampled by post, so TEXTURE_BINDING too.
③ Postswapchain (sRGB-ish)noneThe final image. A fullscreen triangle reads the HDR texture and tonemaps to the display.

The offscreen targets are sized to the canvas (times a render-scale from the quality preset), which means they have to be recreated on resize — the single most common render-to-texture bug. We do it the same defensive way as every Season 2 episode: a ensureTargets(w, h) that destroys and rebuilds the textures whenever the size changes, and rebuilds the bind groups that reference them.

// Recreate every size-dependent target + its bind groups on resize.
function ensureTargets(w, h) {
  if (hdrTex && hdrTex.width === w && hdrTex.height === h) return;
  hdrTex?.destroy(); sceneDepth?.destroy();
  hdrTex = device.createTexture({
    size: [w, h], format: 'rgba16float',
    usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
  });
  sceneDepth = device.createTexture({
    size: [w, h], format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT,
  });
  hdrView = hdrTex.createView();
  postBind = device.createBindGroup({ layout: postPipeline.getBindGroupLayout(0),
    entries: [{ binding: 0, resource: hdrView }, { binding: 1, resource: postSampler }] });
}

Common pitfalls

  • Pass order. The cardinal rule of a multi-pass renderer: shadow first, then the main scene into an offscreen HDR target, then post to the swapchain. The order isn't a style choice — it's forced by the data flow (each pass reads what the previous one wrote). Render the main pass straight to the screen and you can't post-process it; run post before the main pass and you blur an empty texture.
  • Per-object uniform offsets must be 256-aligned. WebGPU's minUniformBufferOffsetAlignment defaults to 256. When you sub-allocate one big uniform buffer across many objects, round each object's stride up to a multiple of 256 (even if the struct is only ~150 bytes). Forget it and bind-group/draw validation throws. The same applies to dynamic offsets passed to setBindGroup.
  • Recreating targets on resize. The HDR target, the scene depth, and the bind groups that sample them are all sized to the canvas. When the canvas changes size you must destroy and rebuild them and rebuild every bind group that references the old views — a stale view is a silent source of "it renders at the wrong size" or a validation error. Guard with a size check so you don't rebuild every frame.
  • HDR target format. The main pass must render into a float format (rgba16float) for bloom to have anything to extract — an 8-bit bgra8unorm target clamps highlights to 1.0 and your bloom is anemic. The swapchain, by contrast, is 8-bit sRGB-ish; the tonemap in the post pass is what bridges the two.
  • Shadow-map depth format must be comparison-filterable. The shadow map is sampled through a sampler_comparison with linear filtering (for soft PCF). depth32float is not guaranteed filterable — on Dawn (Chrome's backend) a linear comparison sampler bound against a depth32float texture can silently invalidate the pipeline, and because every object's bind group shares that layout, the whole scene goes black with no console error — at every stage, even the ones that don't draw shadows. Use depth24plus for the shadow map (it's universally filterable) and the comparison path just works. This is the single nastiest bug in the whole season precisely because it's invisible in the console.
  • Keep it tight — don't over-engineer. The temptation in a "make an engine" episode is to build a material system with hot-reload, a full render-graph compiler, an ECS. Resist it. A renderer is "data in, passes in order, pixels out." The value here is that you can read the whole thing. Add abstraction only when a second use case demands it, not in anticipation.
  • The graceful fallback. The entire engine sits behind initWebGPU(), which never throws. No WebGPU (Safari/Firefox/older) → set the badge to fallback, show a notice, and draw a Canvas2D stand-in of the scene so the page is never a black rectangle. A renderer that crashes on an unsupported browser isn't shippable.

Exercises

  1. Add a second shadow-casting light. Right now only the sun casts shadows. Give one of the point lights its own shadow map: add a second depth32float texture, a second light view-projection (a persp frustum for a point/spot light), a second shadow pass, and a second sampler_comparison bound into the main shader. In the fragment shader, multiply the two shadow factors per light. You'll feel why engines budget shadow casters carefully — each one is another full scene pass.
  2. A material editor. The whole point of materials-as-data is that you can edit them live. Add a small panel (or reuse the controls grid) that, when an object is selected, exposes sliders for its metallic, roughness, and base color, writing straight into that material object. Because render() reads the data every frame, your edits appear instantly with no pipeline changes — that's the payoff of the data model from Stage 5.
  3. Export the engine as a reusable module (note). You don't have to do it here, but sketch the API. Everything WebGPU-specific (init, pipelines, passes, targets) becomes a createRenderer(canvas) that returns { render, resize, device }; everything scene-specific (the data model from code-block (a)) stays in the caller. Write the import { createRenderer } from './engine.js' usage you'd want, then note which of our globals would need to become closures over device. That refactor — drawing the line between "renderer" and "scene" — is the last 10% that turns this file into something you'd actually reuse.

What's next

That's a wrap on Season 2 — Rendering for Real. Across eight episodes we went from a flat triangle to a perspective camera and depth (09), physically-based materials (10), real-time shadows (11), textures and mipmaps (12), a post-processing stack, MSAA, loaded geometry — and today bolted them all into a tiny but real renderer. You now have, from scratch and with zero dependencies, the core of a 3D engine you understand line by line.

Next is Season 3 — GPGPU & Frontiers, where we point all this GPU power at simulation: a real-time stable-fluids solver you paint smoke into, SPH particle liquids, mass-spring cloth, Gray-Scott reaction-diffusion at full resolution, a bitonic GPU sort (the block behind splat sorting and order-independent transparency), and ray marching SDF scenes entirely in a compute shader. Season 1 taught the pipeline; Season 2 made it look real; Season 3 makes it compute. See you there.