Three.js Depth Peeling (Exact Transparency)
Depth peeling in Three.js, rendering transparent geometry in N passes where each peels the next-nearest layer using the previous layer's depth texture, then compositing back to front for correctly ordered transparency.
Key topics: three.js depth peeling, transparency, depth texture, multi-pass rendering, layers
Game Over
What this code does
- Peeling: pass k discards fragments at or in front of pass k−1's depth, so the depth test keeps the next surface behind.
- Depth Textures: every layer target has a `DepthTexture` that the next pass samples with gl_FragCoord.
- Opaque Depth: each pass first renders opaque depth, so glass hidden by solid objects is never peeled.
- Composite: layers are blended back to front with premultiplied "over" onto the opaque image.
- Cost vs Accuracy: results are exact but cost one scene pass per layer; too few layers drop the deepest surfaces.
- Layer Views: show a single layer, or tint each layer, to see what every pass captured.
- Controls: layer count, opacity, view, layer tint and spin.
Related Demos
Continue Learning
JavaScript Implementation
// Depth peeling: each pass discards fragments at or in front of the previous pass's depth
const peel = `
uniform sampler2D uPrevDepth; uniform vec2 uResolution; uniform bool uFirst;
void main () {
if (!uFirst && gl_FragCoord.z <= texture2D(uPrevDepth, gl_FragCoord.xy / uResolution).r + 1e-5) discard;
gl_FragColor = vec4(color * alpha, alpha); // premultiplied, normal depth test + depth write
}`
for (let k = 0; k < layers; k++) {
material.uniforms.uFirst.value = k === 0
material.uniforms.uPrevDepth.value = k ? targets[k - 1].depthTexture : null
renderer.setRenderTarget(targets[k]); renderer.render(scene, camera)
}
// then draw targets[layers-1 … 0] over the opaque image with blending One / OneMinusSrcAlpha