TExcelTAD
Home › Shaders & Graphics Programming › Render Targets

Render Targets

Every effect so far has been computed pixel by pixel from scratch: a fragment shader cannot read what its neighbors drew. Post-processing gets around that with a second pass. First you render the scene into an off-screen image, a render target, instead of the screen. Then you draw one full-screen rectangle whose fragment shader samples that image as a texture, and now each pixel can read any other pixel of the finished frame. Blur, bloom, color grading, outlines from depth, motion blur, depth of field, anti-aliasing (FXAA, TAA) and screen-space reflections are all built this way.

What a render target is

API Name What it holds
OpenGL / WebGL framebuffer object (FBO) with texture or renderbuffer attachments one or more color attachments, optional depth/stencil
Direct3D 12 a resource with a render target view (RTV) color; depth in a separate DSV
Vulkan an image + image view used as a color attachment the same, rendered with a render pass or dynamic rendering
Three.js WebGLRenderTarget a .texture you can sample, plus a depth buffer by default
Unity / Unreal / Godot RenderTexture / Render Target asset / SubViewport the same idea with an editor asset

In raw WebGL2 it is a texture attached to a framebuffer:

js
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

const fbo = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
// + a depth renderbuffer if the pass needs depth testing
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) console.error('incomplete FBO');

// pass 1: draw the scene into tex
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.viewport(0, 0, width, height);
drawScene();
// pass 2: draw a full-screen triangle to the canvas, sampling tex
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindTexture(gl.TEXTURE_2D, tex);
drawFullscreenPass();

A texture cannot be read and written in the same pass (that is a feedback loop, an error in WebGL and undefined behavior elsewhere). Effects that need several passes therefore alternate between two targets: ping-pong buffers, which the Blur lesson uses.

A post-processing pass in Three.js

Three.js renders into a WebGLRenderTarget when you call renderer.setRenderTarget(target) before render. The second pass is a PlaneGeometry(2, 2) whose vertex shader writes the corners straight to clip space, so the camera does not matter. This one pixelates the image and adds scanlines; move the pointer left or right to change the pixel size.

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());

// --- the 3D scene (pass 1) ---
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x203040);
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 1.2, 6);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight(0xbbddff, 0x332211, 1.5));
const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(3, 4, 2);
scene.add(sun);
const knot = new THREE.Mesh(new THREE.TorusKnotGeometry(0.9, 0.3, 160, 24),
  new THREE.MeshStandardMaterial({ color: 0xff7a3d, roughness: 0.35 }));
scene.add(knot);

// --- the render target: an off-screen color texture + depth buffer ---
const target = new THREE.WebGLRenderTarget(size.x, size.y);

// --- the post pass (pass 2) ---
const postScene = new THREE.Scene();
const postCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);   // unused by the shader, required by render()
const postMaterial = new THREE.ShaderMaterial({
  uniforms: {
    tScene: { value: target.texture },
    uResolution: { value: size },
    uPixel: { value: 6 },
  },
  vertexShader: /* glsl */ `
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = vec4(position.xy, 0.0, 1.0);    // the 2x2 plane already covers clip space
    }`,
  fragmentShader: /* glsl */ `
    uniform sampler2D tScene;
    uniform vec2 uResolution;
    uniform float uPixel;
    varying vec2 vUv;
    void main() {
      vec2 grid = uResolution / uPixel;
      vec2 uv = (floor(vUv * grid) + 0.5) / grid;           // snap to the center of a big pixel
      vec3 color = texture2D(tScene, uv).rgb;
      float scan = 0.85 + 0.15 * sin(vUv.y * uResolution.y * 3.14159 / uPixel * 2.0);
      gl_FragColor = vec4(color * scan, 1.0);
      #include <colorspace_fragment>
    }`,
});
postScene.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), postMaterial));

addEventListener('pointermove', (e) => { postMaterial.uniforms.uPixel.value = 1 + Math.round(e.clientX / innerWidth * 15); });

renderer.setAnimationLoop((ms) => {
  knot.rotation.set(ms / 2000, ms / 3000, 0);
  renderer.setRenderTarget(target);      // pass 1: into the texture
  renderer.render(scene, camera);
  renderer.setRenderTarget(null);        // pass 2: to the canvas
  renderer.render(postScene, postCamera);
});
</script>

Three details matter in every post pass:

  • Color space. Three.js writes linear values into render targets and converts to sRGB only when it renders to the screen. A custom ShaderMaterial does not convert by itself; the #include <colorspace_fragment> line at the end does it (it calls linearToOutputTexel on gl_FragColor). Without it the output looks dark and contrasty.
  • Size. Create the target at the drawing-buffer size (CSS size × devicePixelRatio), and call target.setSize() in your resize handler, or the image gets blurry or stretched.
  • Filtering. Render targets default to linear filtering, so sampling between texels blends them. That is useful for blur and up-sampling, but you want the exact texel (texelFetch, or nearest filtering) for things like depth reads or ID buffers.

Render to texture, inside the scene

A render target does not have to end up on the full screen. Here a second camera looks at the scene from above, renders into a target, and that target's texture is the map of a "monitor" in the scene. Security cameras, mirrors, portals, minimaps and in-game TV screens all work like this.

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({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x15151c);
scene.add(new THREE.HemisphereLight(0xffffff, 0x222233, 2));
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 1.8, 6.5);
camera.lookAt(0, 1.2, 0);

const floor = new THREE.Mesh(new THREE.PlaneGeometry(30, 30), new THREE.MeshStandardMaterial({ color: 0x334455 }));
floor.rotation.x = -Math.PI / 2;
scene.add(floor);
const movers = [];
for (let i = 0; i < 5; i++) {
  const m = new THREE.Mesh(new THREE.BoxGeometry(0.5, 0.5, 0.5),
    new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(i / 5, 0.7, 0.55) }));
  scene.add(m);
  movers.push(m);
}

// The "security camera" and its render target.
const target = new THREE.WebGLRenderTarget(512, 256);
const topCamera = new THREE.PerspectiveCamera(60, 2, 0.1, 20);
topCamera.position.set(0, 3.2, 0.01);
topCamera.lookAt(0, 0, 0);

const monitor = new THREE.Mesh(new THREE.PlaneGeometry(4.4, 2.2), new THREE.MeshBasicMaterial({ map: target.texture }));
monitor.position.set(0, 2.3, -2.5);
scene.add(monitor);

renderer.setAnimationLoop((ms) => {
  const t = ms / 1000;
  movers.forEach((m, i) => {
    const a = t * 0.6 + i * 1.2566;
    m.position.set(Math.cos(a) * 2, 0.25, Math.sin(a) * 1.4);
    m.rotation.y = a;
  });
  monitor.visible = false;               // never draw the target into itself
  renderer.setRenderTarget(target);
  renderer.render(scene, topCamera);
  monitor.visible = true;
  renderer.setRenderTarget(null);
  renderer.render(scene, camera);
});
</script>

The line monitor.visible = false is the feedback-loop rule again: the monitor samples target.texture, so it must not be drawn while target is being written.

Formats and costs

Target format Bytes per pixel Use
RGBA8 (Three.js UnsignedByteType) 4 final LDR image, UI, masks
RGBA16F (HalfFloatType) 8 HDR scene color before tone mapping, bloom chains
RGBA32F (FloatType) 16 precise data (positions, simulations); filtering needs the OES_texture_float_linear extension
R11F_G11F_B10F 4 compact HDR color on desktop and console
depth (DEPTH24_STENCIL8, DEPTH32F) 4 depth testing, SSAO, fog, soft particles

A 1920×1080 RGBA16F target is about 16 MB, and every full-screen pass reads and writes every pixel. Post-processing is limited by memory bandwidth more than by math, which is why effects run at half or quarter resolution whenever they can, and why mobile GPUs (tile-based, with little bandwidth) are the first place to cut passes.

Test yourself

Why can't a post-processing shader sample the render target it is currently writing to?

  1. Textures can only be sampled in vertex shaders
  2. It creates a read/write feedback loop, which is an error in WebGL and undefined elsewhere
  3. Render targets have no texture
  4. It only works with float formats

Your Three.js post pass looks darker than the scene rendered directly. What is the most likely cause?

  1. The target is too small
  2. The pass outputs linear values without converting them to sRGB
  3. The camera is orthographic
  4. The plane is 2x2

What usually limits the speed of full-screen post-processing passes?

  1. Vertex count
  2. Memory bandwidth: reading and writing every pixel
  3. The number of uniforms
  4. CPU draw-call overhead