Three.js Volumetric Clouds (Ray-Marched)

Real-time volumetric clouds in a Three.js shader with fBm density in a cloud slab, self-shadowing light marches, Beer–Lambert transmittance, a powder effect and dual-lobe Henyey–Greenstein scattering.

Key topics: three.js volumetric clouds, ray marching, henyey greenstein, beer lambert, sky rendering, glsl

What this code does

- Cloud Slab: density is 3D fBm minus a coverage threshold, shaped with rounded bottoms and wispy tops between two altitudes.
- Light Marching: at each sample a few steps toward the sun estimate optical depth for self-shadowing.
- Beer–Lambert: transmittance falls as e^(−density·distance), accumulated front to back with early exit.
- Phase Function: a forward Henyey–Greenstein lobe makes silver linings when looking toward the sun.
- Powder Effect: thin edges facing the sun darken slightly, which gives clouds their cauliflower look.
- Controls: coverage, density, sun elevation and azimuth, forward scattering, wind and ray steps (drag to look around).

Continue Learning

JavaScript Implementation

ES6+
// Core of a volumetric cloud ray march (fragment shader excerpt)
const cloudMarch = `
  vec3 trans = vec3(1.0), light = vec3(0.0);
  for (int i = 0; i < 64; i++) {
    vec3 p = ro + rd * (t0 + float(i) * stepLen);
    float d = density(p);                     // fBm noise inside a height slab
    if (d <= 0.0) continue;
    float shadow = 0.0;                       // march a few steps toward the sun
    for (int j = 1; j <= 6; j++) shadow += density(p + sunDir * float(j * j) * 1.6);
    vec3 lit = sunColor * exp(-shadow * 1.8) * henyeyGreenstein(dot(rd, sunDir), 0.6) + ambient;
    float a = exp(-d * stepLen * 0.08);        // Beer–Lambert transmittance for this step
    light += trans * lit * (1.0 - a);
    trans *= a;
  }
  color = background * trans + light;`