TExcelTAD

Blur

Blur is the most common building block of post-processing. Bloom is a blurred copy of the bright pixels, depth of field blurs by distance, frosted-glass UI blurs what is behind it, soft shadows blur a shadow map, and SSAO blurs its noisy result. A good blur is also a lesson in GPU cost: the naive version is easy and far too slow, and the tricks that fix it apply to every image filter.

Box versus Gaussian

A blur replaces each pixel with a weighted average of its neighbors. The weights are the kernel.

Kernel Weights Look
box all equal cheap, but blocky; bright spots become squares and edges ring
Gaussian exp(-x² / (2σ²)), largest at the center smooth and round, the "natural" blur of a lens or a scattering medium
tent, Kawase, dual filter approximations built from repeated small blurs close to Gaussian, much cheaper for large radii

The weights must sum to 1, or the image gets brighter or darker. This program computes a 9-tap Gaussian kernel (offsets -4 to +4) and two tricks that make it cheap:

js · try it yourself
// Gaussian weights for a 9-tap kernel (offsets -4..4), normalized so they sum to 1.
function gaussianWeights(radius, sigma) {
  const w = [];
  for (let i = 0; i <= radius; i++) w.push(Math.exp(-(i * i) / (2 * sigma * sigma)));
  const total = w[0] + 2 * w.slice(1).reduce((a, b) => a + b, 0);   // center once, the rest twice
  return w.map((x) => x / total);
}

const w = gaussianWeights(4, 2.0);
console.log('offset  weight');
w.forEach((x, i) => console.log(`  ${i}     ${x.toFixed(5)}`));

// Linear-sampling trick: merge taps 1+2 and 3+4 into one bilinear fetch each.
// The fetch lands between the two texels, at the offset where the hardware blend gives the right mix.
console.log('\nmerged fetches (offset, weight):');
console.log(`  0.00000  ${w[0].toFixed(5)}`);
for (const [a, b] of [[1, 2], [3, 4]]) {
  const weight = w[a] + w[b];
  const offset = (a * w[a] + b * w[b]) / weight;
  console.log(`  ${offset.toFixed(5)}  ${weight.toFixed(5)}`);
}
console.log('\nfetches per pixel: 2D 9x9 =', 9 * 9, '| separable =', 9 + 9, '| separable + linear =', 5 + 5);
offset  weight
  0     0.20416
  1     0.18017
  2     0.12383
  3     0.06628
  4     0.02763

merged fetches (offset, weight):
  0.00000  0.20416
  1.40733  0.30401
  3.29421  0.09391

fetches per pixel: 2D 9x9 = 81 | separable = 18 | separable + linear = 10

Trick 1: separable passes

A 2D Gaussian is the product of a horizontal and a vertical 1D Gaussian. So instead of one pass that reads a 9×9 square (81 texture fetches per pixel), run two passes: blur horizontally into a temporary target, then blur that result vertically. Same image, 18 fetches. For a 33×33 kernel the difference is 1089 against 66. Box blurs are separable too; most other kernels (a hexagonal bokeh, for example) are not.

Trick 2: let the hardware blend

When you sample a texture between two texels with linear filtering, the GPU returns their weighted blend for free. Place the sample at the right fractional offset and one fetch does the work of two taps: that is the "merged fetches" table above. A 9-tap blur becomes 5 fetches per pass.

Trick 3: lower resolution and ping-pong

Blurred images have no fine detail, so they can be computed at half or quarter resolution and scaled up with linear filtering; a quarter-resolution target has 1/16 of the pixels. To blur more, run the pair of passes again: each round widens the blur. The passes alternate between two render targets, A and B, because a pass cannot read the target it writes (see Render Targets):

scene ──► A
A ──(horizontal)──► B ──(vertical)──► A     round 1
A ──(horizontal)──► B ──(vertical)──► A     round 2 …
A ──(upscale + composite)──► screen

Live: separable Gaussian with ping-pong

The scene is rendered into a full-resolution target, then blurred at half resolution with the 5-fetch kernel from above. Move the pointer horizontally to choose 0 to 8 rounds. The left half of the frame shows the sharp image for comparison.

html · try it yourself
<style>body { margin: 0 } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const size = renderer.getDrawingBufferSize(new THREE.Vector2());

// Scene
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0e1420);
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 0, 7);
scene.add(new THREE.HemisphereLight(0xffffff, 0x223344, 1.2));
const light = new THREE.DirectionalLight(0xffffff, 2);
light.position.set(2, 3, 4);
scene.add(light);
const shapes = [];
for (let i = 0; i < 7; i++) {
  const mesh = new THREE.Mesh(i % 2 ? new THREE.BoxGeometry(0.8, 0.8, 0.8) : new THREE.IcosahedronGeometry(0.5, 0),
    new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(i / 7, 0.8, 0.55), flatShading: true }));
  mesh.position.x = (i - 3) * 1.1;
  scene.add(mesh);
  shapes.push(mesh);
}

// Targets: full-res scene, two half-res ping-pong buffers
const sceneRT = new THREE.WebGLRenderTarget(size.x, size.y);
const half = size.clone().multiplyScalar(0.5).floor();
const rtA = new THREE.WebGLRenderTarget(half.x, half.y);
const rtB = new THREE.WebGLRenderTarget(half.x, half.y);

const vertexShader = /* glsl */ `
  varying vec2 vUv;
  void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;

// 9-tap Gaussian (sigma 2) as 5 bilinear fetches: weights and offsets from the table above.
const blurMaterial = new THREE.ShaderMaterial({
  uniforms: { tInput: { value: null }, uStep: { value: new THREE.Vector2() } },
  vertexShader,
  fragmentShader: /* glsl */ `
    uniform sampler2D tInput;
    uniform vec2 uStep;            // one texel along the blur direction
    varying vec2 vUv;
    void main() {
      vec3 c = texture2D(tInput, vUv).rgb * 0.20416;
      c += texture2D(tInput, vUv + uStep * 1.40733).rgb * 0.30401;
      c += texture2D(tInput, vUv - uStep * 1.40733).rgb * 0.30401;
      c += texture2D(tInput, vUv + uStep * 3.29421).rgb * 0.09391;
      c += texture2D(tInput, vUv - uStep * 3.29421).rgb * 0.09391;
      gl_FragColor = vec4(c, 1.0);
    }`,
});
const copyMaterial = new THREE.ShaderMaterial({        // downsample = draw into a smaller target
  uniforms: { tInput: { value: null } },
  vertexShader,
  fragmentShader: /* glsl */ `
    uniform sampler2D tInput; varying vec2 vUv;
    void main() { gl_FragColor = texture2D(tInput, vUv); }`,
});
const finalMaterial = new THREE.ShaderMaterial({
  uniforms: { tSharp: { value: sceneRT.texture }, tBlur: { value: rtA.texture } },
  vertexShader,
  fragmentShader: /* glsl */ `
    uniform sampler2D tSharp, tBlur;
    varying vec2 vUv;
    void main() {
      vec3 c = vUv.x < 0.5 ? texture2D(tSharp, vUv).rgb : texture2D(tBlur, vUv).rgb;
      if (abs(vUv.x - 0.5) < 0.001) c = vec3(1.0);
      gl_FragColor = vec4(c, 1.0);
      #include <colorspace_fragment>
    }`,
});

const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), copyMaterial);
const postScene = new THREE.Scene();
postScene.add(quad);
const postCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
function pass(material, output) {
  quad.material = material;
  renderer.setRenderTarget(output);
  renderer.render(postScene, postCamera);
}

let rounds = 3;
addEventListener('pointermove', (e) => { rounds = Math.round(e.clientX / innerWidth * 8); });

renderer.setAnimationLoop((ms) => {
  shapes.forEach((s, i) => { s.rotation.set(ms / 1500 + i, ms / 2000, 0); s.position.y = Math.sin(ms / 800 + i) * 0.6; });
  renderer.setRenderTarget(sceneRT);
  renderer.render(scene, camera);

  copyMaterial.uniforms.tInput.value = sceneRT.texture;
  pass(copyMaterial, rtA);                                    // downsample into A
  for (let i = 0; i < rounds; i++) {
    blurMaterial.uniforms.tInput.value = rtA.texture;
    blurMaterial.uniforms.uStep.value.set(1 / half.x, 0);     // horizontal: A -> B
    pass(blurMaterial, rtB);
    blurMaterial.uniforms.tInput.value = rtB.texture;
    blurMaterial.uniforms.uStep.value.set(0, 1 / half.y);     // vertical: B -> A
    pass(blurMaterial, rtA);
  }
  pass(finalMaterial, null);
});
</script>

Rounds add up like variances: two rounds of σ = 2 equal one round of σ = 2√2 ≈ 2.8, so the blur radius grows with the square root of the number of rounds. For big radii, real engines do not loop at one resolution; they downsample repeatedly (half, quarter, eighth…), blur a little at each level and add the levels back up. That mip-chain approach (Kawase blur, the "dual filter" from ARM's 2015 mobile talk, Call of Duty's bloom chain) gives huge, smooth blurs for a handful of fetches per pixel.

Pitfalls

  • Edges. Samples beyond the border read whatever the wrap mode says. Use ClampToEdgeWrapping (the render-target default) so edges do not bleed in from the opposite side.
  • Blurring in the wrong space. Blur linear HDR values, not sRGB-encoded ones; averaging gamma-encoded colors darkens bright edges.
  • Shimmering with movement. Downsampling by just picking every second pixel aliases; let bilinear filtering average 2×2 texels (sample at the shared corner) or use a 13-tap downsample filter as Call of Duty's bloom does.
  • Too many passes on mobile. Each pass is a full write and read of a render target. Two half-res passes are usually affordable; eight full-res ones are not.

A blur in a single fragment shader

For a quick effect where performance does not matter, or when the "image" is itself computed by a function, you can blur by sampling the function many times. Here a procedural image (sharp rings) is blurred with a 2D Gaussian by evaluating it 49 times per pixel. Watch the frame rate on a weak GPU and you will see why the separable version exists.

glsl · try it yourself
vec3 image(vec2 p) {
    float rings = step(0.5, fract(length(p) * 6.0 - iTime * 0.3));
    vec3 a = vec3(0.1, 0.2, 0.5), b = vec3(1.0, 0.8, 0.3);
    return mix(a, b, rings);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    float radius = 0.5 + 0.5 * sin(iTime * 0.7);                 // blur strength in pixels * 4
    vec2 px = 2.0 / iResolution.yy;                              // one pixel in p units

    vec3 sum = vec3(0.0);
    float total = 0.0;
    for (int y = -3; y <= 3; y++) {
        for (int x = -3; x <= 3; x++) {
            vec2 o = vec2(x, y);
            float w = exp(-dot(o, o) / 4.5);                     // sigma = 1.5 taps
            sum += image(p + o * px * radius * 4.0) * w;
            total += w;
        }
    }
    vec3 color = fragCoord.x < iResolution.x * 0.5 ? image(p) : sum / total;
    fragColor = vec4(color, 1.0);
}

Test yourself

Why is a Gaussian blur usually done as two passes?

  1. GPUs cannot read diagonal neighbors
  2. The 2D Gaussian is separable, so a horizontal then vertical 1D pass gives the same result with far fewer samples
  3. To keep the colors in gamma space
  4. To avoid using render targets

How can one bilinear texture fetch replace two Gaussian taps?

  1. By using a float texture
  2. By sampling at a fractional offset between the two texels so the hardware blend reproduces their weights
  3. By sampling the same texel twice
  4. It cannot

Why do blur passes ping-pong between two render targets?

  1. To double the resolution
  2. A pass cannot read from the same target it writes to
  3. Three.js requires exactly two targets
  4. To store the depth buffer