Real-Time Shadows in Complex Scenes: Balancing Quality and Performance in Three.js

Overview

Shadows enhance realism but are also one of the most expensive rendering features in 3D. In Three.js, real-time shadows are usually created using shadow maps, but their quality depends on many factors like resolution, bias, and camera settings.

Common Shadow Types in Three.js

  • BasicShadowMap: Fast, low-quality
  • PCFSoftShadowMap: Smooth edges, balanced quality
  • VSMShadowMap: For soft, light-bleeding shadows (but needs WebGL2)
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

Key Light Setup

const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(10, 20, 10);
light.castShadow = true;

light.shadow.mapSize.width = 2048;
light.shadow.mapSize.height = 2048;

light.shadow.camera.near = 0.5;
light.shadow.camera.far = 100;
light.shadow.camera.left = -20;
light.shadow.camera.right = 20;
light.shadow.camera.top = 20;
light.shadow.camera.bottom = -20;

scene.add(light);

Tuning Shadow Quality

1. Shadow Map Size

  • 1024 × 1024 (fast)
  • 2048 × 2048 (good balance)
  • 4096 × 4096 (best quality, slowest)

2. Camera Frustum

Make the shadow camera only cover what’s necessary to avoid precision errors.

3. Bias

Fixes “shadow acne”:

light.shadow.bias = -0.0005;

Soft Shadows with VSM (WebGL2 only)

renderer.shadowMap.type = THREE.VSMShadowMap;

Requires materials that support THREE.MeshStandardMaterial or higher.

Performance Tips

  • Use receiveShadow and castShadow only where needed
  • Bake shadows for static objects using lightmaps (Blender → Three.js)
  • Use LightShadowCameraHelper to debug frustum placement
  • For large worlds, implement Cascaded Shadow Maps (CSM) via three-csm

Bonus: Dynamic Shadow Swap for VR/Desktop

Disable soft shadows in VR mode to save GPU:

if (isVRMode) {
  renderer.shadowMap.enabled = false;
  light.castShadow = false;
}

Final Takeaways

  • Shadows are a trade-off: you get realism at a cost.
  • Use GPU resources wisely—often ambient occlusion and smart lighting can complement lower-res shadows.
  • For fast-paced experiences like VR or mobile, use baked lighting or shadow decals (simple textured planes with blur).

Leave a comment

Your email address will not be published. Required fields are marked *