TExcelTAD
Home › 3D Web Games with Three.js › Environment Maps & PBR

Environment Maps & PBR

Real objects are lit by everything around them, not just by a few lamps: the blue sky, the bright ground, the walls of a room. Physically based materials (MeshStandardMaterial, MeshPhysicalMaterial) can use an environment map, a 360° picture of the surroundings, for exactly that. It gives soft ambient light from every direction and the reflections that make metal, plastic and wet surfaces look real. This is called image-based lighting (IBL), and it is the single biggest step from "3D demo" to "looks like a game".

scene.environment and scene.background

Two scene properties, often set to the same thing, do different jobs:

Property Effect
scene.environment lighting and reflections for every PBR material in the scene
scene.background what is drawn behind everything (a color, a texture, or an environment)
scene.environmentIntensity scales the environment's contribution (default 1)
scene.backgroundBlurriness / backgroundIntensity blur (0–1) and brightness of an environment used as background
scene.environmentRotation / backgroundRotation turn the environment (an Euler), e.g. to line the sun up with your light
material.envMap, material.envMapIntensity per-material override and strength

Environment maps for PBR must be pre-filtered: a rough surface reflects a blurry version of the surroundings, a smooth one a sharp version. THREE.PMREMGenerator builds that pre-filtered map (a Prefiltered, Mipmapped Radiance Environment Map). When you assign an equirectangular or cube texture to scene.environment, WebGLRenderer runs it through PMREM for you; when you generate an environment from a scene, call it yourself.

Where environment maps come from

  1. HDR images: equirectangular .hdr or .exr panoramas (free ones at Poly Haven). Load them with HDRLoader (the older RGBELoader is deprecated since r180) or EXRLoader, and set texture.mapping = THREE.EquirectangularReflectionMapping.
  2. A generated scene: RoomEnvironment (a simple lit studio box from the addons) or any scene you build, captured with pmrem.fromScene(scene).
  3. A procedural sky: the Sky addon (an analytic daylight model) rendered into an environment.
  4. A CubeCamera: renders the live scene from a point into a cube texture, for dynamic reflections (expensive: six renders).
js
// Option 1 in a real project (not runnable here: needs an .hdr file).
import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
const hdr = await new HDRLoader().loadAsync('env/meadow_2k.hdr');
hdr.mapping = THREE.EquirectangularReflectionMapping;
scene.environment = hdr;           // lighting + reflections
scene.background = hdr;            // optional: show it
scene.backgroundBlurriness = 0.3;  // soften a low-resolution background

A sky that lights the scene

This scene uses the Sky addon twice: once as the visible background, and once (captured with PMREMGenerator.fromScene) as the environment that lights and reflects. Drag the sun slider from noon to sunset and watch the metal, the plastic and the ground change with the sky. The directional light follows the same sun direction so shadows and highlights agree with the sky.

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
#ui { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; text-shadow: 0 1px 2px #000 }</style>
<div id="ui">sun <input id="elev" type="range" min="1" max="60" value="25"> <span id="deg"></span></div>
<script type="module">
import * as THREE from 'three';
import { Sky } from 'three/addons/objects/Sky.js';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;   // the sky is HDR: map it to the screen
renderer.toneMappingExposure = 0.3;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 1000);
camera.position.set(0, 1.6, 7);
camera.lookAt(0, 0.9, 0);

const sky = new Sky();
sky.scale.setScalar(500);
Object.assign(sky.material.uniforms.turbidity, { value: 3 });
Object.assign(sky.material.uniforms.rayleigh, { value: 1.5 });
scene.add(sky);

// A separate scene with just the sky, captured into the environment map.
const envScene = new THREE.Scene();
const envSky = new Sky();
envSky.scale.setScalar(500);
envSky.material.uniforms.showSunDisc.value = false;   // a tiny bright disc only adds noise to the env map
envScene.add(envSky);
const pmrem = new THREE.PMREMGenerator(renderer);
let envTarget = null;

const sunLight = new THREE.DirectionalLight('#ffffff', 2);
scene.add(sunLight);
const ground = new THREE.Mesh(new THREE.CircleGeometry(30, 48), new THREE.MeshStandardMaterial({ color: '#8a8070', roughness: 0.95 }));
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
const geo = new THREE.SphereGeometry(0.8, 64, 32);
[['#e8c26a', 1, 0.15], ['#d0d4da', 1, 0.45], ['#3f7fd6', 0, 0.2], ['#eeeeee', 0, 0.9]].forEach(([color, metalness, roughness], i) => {
  const s = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color, metalness, roughness }));
  s.position.set((i - 1.5) * 2, 0.8, 0);
  scene.add(s);
});

const sunDir = new THREE.Vector3();
function setSun(elevationDeg) {
  sunDir.setFromSphericalCoords(1, THREE.MathUtils.degToRad(90 - elevationDeg), THREE.MathUtils.degToRad(200));
  sky.material.uniforms.sunPosition.value.copy(sunDir);
  envSky.material.uniforms.sunPosition.value.copy(sunDir);
  sunLight.position.copy(sunDir).multiplyScalar(20);
  sunLight.intensity = 3 * Math.min(1, elevationDeg / 15);    // a low sun is weaker
  envTarget?.dispose();                                        // free the previous env map
  envTarget = pmrem.fromScene(envScene);
  scene.environment = envTarget.texture;
  document.getElementById('deg').textContent = `${elevationDeg}°`;
}
const slider = document.getElementById('elev');
slider.oninput = () => setSun(+slider.value);
setSun(25);

addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});
renderer.setAnimationLoop(() => renderer.render(scene, camera));
</script>

Note the envTarget?.dispose(): each fromScene call allocates a new render target on the GPU. Regenerating an environment map is cheap enough for a slider or a day–night cycle that updates every few seconds, but not something to do every frame.

PBR in practice

Physically based rendering works because materials and lights describe physical quantities, so assets look right in any lighting if a few rules hold:

  • Albedo (base color) has no lighting in it. No baked shadows or highlights in the color texture; the renderer adds those. Real albedos are neither pure black nor pure white (charcoal is about sRGB 50, fresh snow about 240).
  • Metalness is binary in practice. 0 for non-metals, 1 for metals. A metal's albedo is its reflection color (gold is yellow, copper orange); a non-metal reflects a small, uncolored amount.
  • Roughness carries the character. Most surface variation (worn edges, fingerprints, puddles) is a roughness map.
  • Light the scene with an environment first, then add a key light for direction and shadows. Without an environment, PBR materials look flat and metals look black.
  • Use tone mapping. Sky and sun values exceed the 0–1 a screen can show; tone mapping (next lesson) compresses them gracefully.

Dynamic reflections with CubeCamera

For a mirror ball or a car that reflects the live scene, render a cube map from the object's position:

js
const cubeTarget = new THREE.WebGLCubeRenderTarget(256, { type: THREE.HalfFloatType });
const cubeCamera = new THREE.CubeCamera(0.1, 100, cubeTarget);
chromeBall.material.envMap = cubeTarget.texture;
scene.add(cubeCamera);

// in the loop: hide the object, capture, show it again
chromeBall.visible = false;
cubeCamera.position.copy(chromeBall.position);
cubeCamera.update(renderer, scene);   // six renders of the scene
chromeBall.visible = true;

Six extra scene renders per update is a lot. Update every few frames, at a low resolution, for the one hero object, or fake it with a static environment map, which players rarely notice.

Test yourself

What is the difference between scene.environment and scene.background?

  1. None; they are aliases
  2. environment lights and reflects in PBR materials; background is only what is drawn behind the scene
  3. background lights the scene; environment is drawn behind it
  4. environment only works with HDR files

Why are environment maps for PBR pre-filtered with PMREM?

  1. To compress them
  2. So rough surfaces can sample a blurred version and smooth surfaces a sharp one, quickly
  3. To convert them to sRGB
  4. WebGL can't sample cube maps otherwise

Which loader does r186 recommend for .hdr environment images?

  1. RGBELoader
  2. HDRLoader
  3. TextureLoader
  4. GLTFLoader