Three.js Environment Map Arrays (Cubemap Arrays Emulated)

Many environment maps in one sampler in Three.js, with eight procedural skies stored as equirectangular layers of a mipmapped texture array so 40 reflective spheres pick their own environment and roughness in one draw call.

Key topics: three.js environment map, cubemap array, texture array, reflections, roughness mip, equirectangular

What this code does

- No samplerCubeArray: WebGL2 can't array cube maps, so each environment is stored as an equirect layer of a `DataArrayTexture`.
- Lookup: the reflection vector becomes (longitude, latitude) uv, and the layer comes from a per-instance attribute.
- Roughness: `textureLod` reads blurrier mips for rougher spheres, a cheap stand-in for prefiltered IBL.
- One Draw: eight environments × five roughness levels render as a single instanced mesh.
- Shared Data: the sky dome samples the same array, so switching background is just a uniform change.
- Controls: sky layer and sky cycling.

Continue Learning

JavaScript Implementation

ES6+
// WebGL2 lacks samplerCubeArray — store environments as equirect layers of a texture array instead
const envs = new THREE.DataArrayTexture(bytes, 512, 256, 8) // 8 environments
envs.generateMipmaps = true
envs.minFilter = THREE.LinearMipmapLinearFilter
envs.needsUpdate = true
const glsl = `
  precision highp sampler2DArray;
  uniform sampler2DArray uEnvs;
  vec2 equirect (vec3 d) { return vec2(atan(d.z, d.x) / 6.2831853 + 0.5, 0.5 - asin(d.y) / 3.14159265); }
  // per instance: env layer + roughness (→ mip level)
  vec3 env = textureLod(uEnvs, vec3(equirect(reflect(-viewDir, n)), vEnv), vRough * 7.0).rgb;`