WebGPU From Zero · Episode 13

Post-Processing

Post-Processing is Episode 13 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 13 · WebGPU From Zero · Season 2

Here is the dirty secret of every game trailer, every CG shot, every "how is this real-time?" demo you've ever gasped at: the 3D render that comes out of the rasterizer is flat. It's correct, but it's not a shot. The thing that makes it cinematic — the soft glow around bright lights, the warm filmic roll-off in the highlights, the gentle darkening at the corners, the faint living grain — none of that is in the geometry. It's a stack of full-screen passes bolted on at the very end. The post stack.

So this episode we stop drawing to the screen and start drawing to a texture. Once the scene lives in a texture, it's just an image — and we can run image filters over it as many times as we like before it ever reaches the glass. We'll build the round-trip, then layer on tone mapping, bloom, a vignette, and grain, each with a live toggle. By the last stage you'll have a glowing, graded scene with a real, switchable post pipeline — the cinematic layer, from zero.

0 fps
rendering…
initializing…
Scene rendered to an offscreen texture, then blitted to screen. Should look identical — that's the point.

Six stages, one machine. The same emissive scene — a slow-spinning ring of glowing cubes around a bright core — is rendered once into an offscreen HDR texture every frame. Everything you see after that is post. Step through the stage dropdown and watch the same pixels become a shot.

What you're looking at

A bright, emissive 3D scene: a central glowing octahedron and a carousel of cubes that pulse past full white. It auto-rotates, so there's always motion. The fps counter is top-left; the backend badge bottom-left tells you whether you're on real WebGPU or the Canvas2D fallback. Three live controls drive the post stack: a bloom intensity slider, an exposure slider (how much HDR light we let through before tone mapping), and a vignette toggle. The stages layer the pipeline up one pass at a time so you can feel each contribution in isolation.

The architecture never changes between stages — only how many post passes run, and what they do:

3D scene ──▶ [ HDR texture ] rgba16float ← drawn ONCE per frame │ ├─▶ bright-pass ─▶ blur H ─▶ blur V (bloom, ping-pong) │ │ ▼ ▼ [ composite pass ] ◀── scene + bloom ── add │ ├─ tone map (ACES) × exposure ├─ vignette ├─ film grain ▼ context.getCurrentTexture() ── the screen (sRGB)

Stage 1 — Render to a texture, then blit it back

Before any effect, we have to prove the round-trip. Instead of pointing the scene's render pass at context.getCurrentTexture(), we point it at an offscreen GPUTexture we created ourselves. Then a second pass — a full-screen triangle — samples that texture and writes it to the screen. Nothing is altered. The image should look pixel-identical to a direct render, which is exactly the confidence check we want: if Stage 1 looks right, the plumbing is correct and every later stage is "just" a different fragment shader.

The offscreen texture is the foundation of the whole episode. Two things matter: its format and its usage flags. We make it rgba16float — a half-float HDR target — so colors can go above 1.0 (we'll need that headroom for bloom). And the usage must say it's both a thing we render into (RENDER_ATTACHMENT) and a thing we later sample (TEXTURE_BINDING). Forget the second flag and bind-group creation throws.

// One offscreen HDR color target the size of the canvas.
function makeHDRTarget(w, h) {
  return device.createTexture({
    size: [w, h],
    format: 'rgba16float',              // HDR: values can exceed 1.0
    usage: GPUTextureUsage.RENDER_ATTACHMENT     // we draw the scene into it
         | GPUTextureUsage.TEXTURE_BINDING,      // …and sample it in a post pass
  });
}

// The fullscreen-triangle post pass: sample one texture, write it out.
const blitModule = device.createShaderModule({ code: BLIT_WGSL });
const blitPipeline = device.createRenderPipeline({
  layout: 'auto',
  vertex:   { module: blitModule, entryPoint: 'vs' },
  fragment: { module: blitModule, entryPoint: 'fs',
              targets: [{ format }] },          // `format` = swap-chain (sRGB-ish)
  primitive: { topology: 'triangle-list' },
});

And the shader. No vertex buffer — the three corners come straight from vertex_index, the classic over-sized triangle that covers the screen. The fragment shader samples the HDR texture at the screen UV and emits it. (Note: a blit pass has no depth — depth is for the 3D scene pass only. The post passes are pure 2D image work.)

// BLIT_WGSL — fullscreen triangle + a 1:1 texture copy.
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

struct VSOut { @builtin(position) pos: vec4f, @location(0) uv: vec2f };

@vertex fn vs(@builtin(vertex_index) i: u32) -> VSOut {
  // (-1,-1) (3,-1) (-1,3): one triangle bigger than the screen.
  var p = array<vec2f,3>(vec2f(-1,-1), vec2f(3,-1), vec2f(-1,3));
  var o: VSOut;
  o.pos = vec4f(p[i], 0, 1);
  o.uv  = p[i] * vec2f(0.5, -0.5) + vec2f(0.5, 0.5);  // flip Y for texture space
  return o;
}

@fragment fn fs(in: VSOut) -> @location(0) vec4f {
  return textureSample(src, samp, in.uv);            // straight through
}

Stage 2 — A pass that actually does something

Now that the round-trip works, the punchline lands: a post effect is just a different fragment shader in that second pass. To make the concept undeniable, Stage 2 runs an invert/grayscale process over the sampled image. Same plumbing as the blit — sample the HDR texture, but instead of returning the color unchanged, transform it. This is the entire mental model for everything that follows. Bloom, tone mapping, vignette: they're all "sample the scene texture and return a function of it."

// A "process" fragment shader: desaturate, then invert. Concept demo.
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
  let c = textureSample(src, samp, in.uv).rgb;
  let g = dot(c, vec3f(0.299, 0.587, 0.114));   // luma → grayscale
  let inv = 1.0 - vec3f(g);                      // invert it
  return vec4f(inv, 1.0);
}

That's it. The 3D scene has no idea this is happening — it rendered the same colorful cubes into the same texture. We reached in afterward and rewrote every pixel. Once you internalize "the scene is an image I can edit," post-processing stops being mysterious.

Stage 3 — Tone mapping & exposure

Here's why we bothered with a rgba16float target. Our scene is HDR: the emissive cubes peak well above 1.0 — the core might be 8.0 or more. A normal 8-bit screen can only show 0→1, so if we just clamped, every bright thing would be a flat white blob with no shape. Tone mapping is the curve that gracefully squashes that unbounded HDR range down into displayable 0→1, keeping detail in the highlights instead of clipping it. It's what makes bright things look bright instead of just white.

First we multiply by exposure (a single scalar — like the aperture on a camera; drag the slider and watch the scene brighten or darken), then we run the HDR color through the ACES filmic curve, then we're in display range. Crucially, tone mapping happens after we'd add bloom and before the final sRGB write — get that order wrong and bloom either has nothing to grab (if you tonemapped too early and clamped away the headroom) or looks muddy.

// ACES filmic approximation (Narkowicz). HDR in, ~[0,1] out.
fn aces(x: vec3f) -> vec3f {
  let a = 2.51; let b = 0.03; let c = 2.43; let d = 0.59; let e = 0.14;
  return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3f(0.0), vec3f(1.0));
}

@fragment fn fs(in: VSOut) -> @location(0) vec4f {
  var hdr = textureSample(src, samp, in.uv).rgb;
  hdr = hdr * post.exposure;        // camera "aperture"
  let mapped = aces(hdr);            // filmic roll-off in the highlights
  return vec4f(mapped, 1.0);
}

Compare Stage 1 (raw, clipped) to Stage 3: the bright cores stop being featureless white discs and gain a warm shoulder. Push exposure up and the whole scene lifts without the highlights instantly blowing out — that's the curve doing its job. (If your swap chain is an -srgb format, the hardware applies the final gamma encoding for you on write, so we leave the tone-mapped value linear here. If you target a non-sRGB format you'd apply pow(c, 1/2.2) yourself.)

Stage 4 — Bloom

Bloom is the glow that bleeds out of bright objects — light scattering in a real lens, faked. It is the single most "cinematic" effect and it's three sub-passes:

  1. Bright-pass / threshold. Sample the HDR scene, keep only the parts brighter than a threshold (the dim midtones contribute no glow), into a small texture.
  2. Separable Gaussian blur. Blur that bright texture — but a 2D Gaussian is expensive, so we exploit that it's separable: blur horizontally into a temp texture, then blur that vertically. Two cheap 1D passes equal one expensive 2D blur. This is the ping-pong: texture A → texture B → A.
  3. Composite. Add the blurred bright texture back onto the original scene, scaled by the bloom intensity slider, then tone map the sum.

We run the bloom textures at half resolution — blur is wide and forgiving, nobody can tell, and it's 4× cheaper. The threshold pass:

// BRIGHT-PASS — keep only what's bright enough to glow.
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
  let c = textureSample(src, samp, in.uv).rgb;
  let luma = dot(c, vec3f(0.2126, 0.7152, 0.0722));
  let k = max(luma - post.threshold, 0.0) / max(luma, 1e-4);
  return vec4f(c * k, 1.0);     // soft knee: dim pixels → ~0
}

The separable blur. One shader, run twice with a different direction uniform — horizontal (dir = (1,0)) then vertical (dir = (0,1)). A small 9-tap Gaussian kernel is plenty for a glow:

// BLUR — 1D Gaussian along `post.dir`. Run H then V (ping-pong).
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
  let texel = post.dir / post.texSize;       // step in UV, along H or V
  let w = array<f32,5>(0.227, 0.194, 0.121, 0.054, 0.016);
  var sum = textureSample(src, samp, in.uv).rgb * w[0];
  for (var i = 1; i < 5; i = i + 1) {
    let o = texel * f32(i);
    sum = sum + textureSample(src, samp, in.uv + o).rgb * w[i];
    sum = sum + textureSample(src, samp, in.uv - o).rgb * w[i];
  }
  return vec4f(sum, 1.0);
}

On the JS side, that's three render passes feeding three textures. The ping-pong — drawing from one texture into another, then swapping — is the whole trick of multi-pass blur:

// Per frame, after the scene is in `hdr`:
drawPass(brightPipeline, brightBind(hdr),     bloomA);  // threshold → A
drawPass(blurPipeline,   blurBind(bloomA, H), bloomB);  // blur horizontal → B
drawPass(blurPipeline,   blurBind(bloomB, V), bloomA);  // blur vertical  → A (ping-pong)
// `bloomA` now holds the soft glow; composite adds it to `hdr`.

Crank the bloom slider up: the glowing cubes start to bleed light into the dark around them, and as a cube pulses past white its halo swells. Drop it to 0 and you're back to a clean render. The threshold is what stops the whole image from glowing — only the genuinely bright pixels get a halo.

Stage 5 — Vignette & film grain

The finishing touches. A vignette darkens the corners, pulling your eye to the center the way a real lens falls off toward its edges — it instantly reads as "photographed." And film grain is a faint, animated, per-pixel noise: counter-intuitively, a tiny bit of noise makes a digital image feel more organic and hides banding in smooth gradients. Both are dirt-cheap — a couple of lines each at the very end of the composite shader:

// Applied to the tone-mapped LDR color, just before output.
fn hash(p: vec2f) -> f32 {                       // cheap per-pixel noise
  return fract(sin(dot(p, vec2f(12.9898, 78.233))) * 43758.5453);
}

// `uv` is 0..1 across the screen, `col` is LDR rgb after tonemap:
if (post.vignette > 0.5) {
  let d = distance(in.uv, vec2f(0.5, 0.5));     // 0 at center, ~0.7 at corner
  let vig = smoothstep(0.85, 0.35, d);          // 1 center → 0 corner
  col = col * mix(0.55, 1.0, vig);
}
let grain = (hash(in.uv * post.texSize + post.time) - 0.5) * 0.04;
col = col + vec3f(grain);                       // animated, ±2% — barely there

Note grain uses post.time so it shimmers frame-to-frame (static grain looks like dirt on the lens). Toggle the vignette checkbox to feel how much focus those darkened corners add — it's a small change with an outsized effect on how "shot" the frame feels.

Stage 6 — The full post stack

Now everything runs together in one composite pass: sample the scene, sample the bloom, add bloom × intensity, multiply by exposure, run ACES tone mapping, apply the vignette, add the grain — then let the sRGB swap chain encode the final gamma. The order is the whole ballgame: bloom is added in HDR (so the glow itself has headroom), tone mapping comes after the add (so the combined brightness rolls off together), and the cosmetic vignette/grain go last on the display-range color.

// COMPOSITE — the full stack, in order. `scene` = HDR, `bloomTex` = glow.
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
  var hdr = textureSample(scene,    samp, in.uv).rgb;
  let glow = textureSample(bloomTex, samp, in.uv).rgb;
  hdr = hdr + glow * post.bloom;        // 1. add bloom in HDR
  hdr = hdr * post.exposure;            // 2. exposure
  var col = aces(hdr);                   // 3. tone map → LDR
  if (post.vignette > 0.5) {             // 4. vignette
    let d = distance(in.uv, vec2f(0.5));
    col = col * mix(0.55, 1.0, smoothstep(0.85, 0.35, d));
  }
  col = col + vec3f((hash(in.uv * post.texSize + post.time) - 0.5) * 0.04); // 5. grain
  return vec4f(col, 1.0);               // sRGB swap chain encodes gamma
}

Toggle between Stage 1 and Stage 6 with the same camera angle. Stage 1 is "a render." Stage 6 is "a shot." The geometry is byte-for-byte identical — the entire difference is four image filters stacked on the end. That's the cinematic layer, and now it's yours to tune with three sliders.

Common pitfalls

  • Bloom with no headroom. If your scene target is 8-bit (rgba8unorm), bright pixels are already clamped to 1.0 before the bright-pass ever sees them — so the threshold has nothing above it and bloom barely shows. Bloom needs a float target (rgba16float) so colors can exceed 1.0 and the bright-pass has something to extract.
  • One blur pass instead of two. A separable Gaussian is H then V — two passes. Run only one and you get a directional streak (motion blur), not a round glow. Same shader, swap the dir uniform between calls.
  • Tone mapping in the wrong place. Tone map after adding bloom and before the sRGB write. Tonemap too early (before bloom) and the glow gets crushed; skip it entirely and bright areas clip to flat white.
  • Forgetting TEXTURE_BINDING. An offscreen target you sample later needs both RENDER_ATTACHMENT | TEXTURE_BINDING in its usage. Miss the second and bind-group creation throws a validation error.
  • Ping-pong aliasing. You can't read and write the same texture in one pass. Blur reads A → writes B, then reads B → writes A. Two textures, alternated — never sample the texture you're currently rendering into.
  • Double gamma. If the swap-chain format ends in -srgb, the hardware encodes gamma on write — don't pow(c,1/2.2) yourself too, or the image washes out. Pick one place to do it.
  • Static grain. Drive the noise with a per-frame time value. A fixed noise pattern looks like a dirty sensor, not film.

Exercises

  1. Chromatic aberration. In the composite, sample the scene three times — R, G, B — each at a slightly offset UV that grows toward the screen edge (uv + (uv-0.5)*amount for red, the negative for blue). You'll get the colored-fringe lens look that screams "cinematic." Add an amount slider.
  2. A LUT color grade. Replace ACES with a color-grade lookup: bake a tiny 16×16×16 color cube as an inline data texture (or build it procedurally in a one-time pass) and use the tone-mapped RGB as 3D texture coordinates. This is exactly how film LUTs ship in real engines — instant "teal-and-orange" or "bleach bypass."
  3. Depth of field (note). You already render to a texture — render a depth texture too, then in a post pass blur each pixel by an amount derived from how far its depth is from a focus distance. A real DoF needs a circle-of-confusion and careful near/far handling, but a "blur by depth difference" gets you a convincing first version. Reuse this episode's separable blur as the kernel.

What's next

Episode 14 — MSAA & render targets. Our crisp cube edges are secretly jagged — every render-to-texture pass we just built samples those aliased edges. Next we add multisample anti-aliasing: a multisampled color target that the GPU averages down into a clean resolve target, the sibling technique to the offscreen targets we leaned on all episode. Smooth edges, then back to making them glow.