Three.js Deferred vs Forward Rendering (256 Lights)

Compare deferred and forward shading in Three.js, using a 3-target MRT G-buffer (albedo, normal, position) lit by up to 256 point lights in one full-screen pass, against standard forward point lights.

Key topics: three.js deferred rendering, g-buffer, mrt, forward rendering, many lights, rendering pipeline

What this code does

- Forward: every mesh's fragment shader loops over every light, so cost is objects × lights and shaders recompile per light count.
- Deferred: a geometry pass writes albedo, view normal and view position to three targets at once (`count: 3` MRT).
- Lighting Pass: one full-screen quad reads the G-buffer and accumulates attenuated Blinn-Phong for each light within range.
- Decoupling: lighting cost depends on pixels × lights, not scene complexity, which is why deferred handles hundreds of lights.
- G-Buffer Views: inspect albedo, normals and positions directly.
- Tradeoffs: deferred struggles with transparency and MSAA, which is why Forward+ (tiled) exists.
- Controls: pipeline, light count, light radius, G-buffer view and light speed.

Continue Learning

JavaScript Implementation

ES6+
// Deferred shading: write surface attributes once, then light in screen space
const gbuffer = new THREE.WebGLRenderTarget(width, height, { count: 3, type: THREE.HalfFloatType })
const gbufMaterial = new THREE.ShaderMaterial({
  glslVersion: THREE.GLSL3,
  vertexShader: 'out vec3 vN; out vec3 vP; void main () { vec4 mv = modelViewMatrix * vec4(position, 1.0); vP = mv.xyz; vN = normalMatrix * normal; gl_Position = projectionMatrix * mv; }',
  fragmentShader: `
    in vec3 vN; in vec3 vP;
    layout(location = 0) out vec4 gAlbedo; layout(location = 1) out vec4 gNormal; layout(location = 2) out vec4 gPosition;
    void main () { gAlbedo = vec4(0.8); gNormal = vec4(normalize(vN), 1.0); gPosition = vec4(vP, 1.0); }`
})
// lighting pass (full-screen quad): for each light, read gPosition/gNormal/gAlbedo and accumulate Blinn-Phong
renderer.setRenderTarget(gbuffer); renderer.render(scene, camera)
renderer.setRenderTarget(null); renderer.render(lightingQuadScene, quadCamera)