GameCrew AIEarly access
Sign in
Three.jsatmosphereRevision 2 · By @maddmann

Neural Multiple-Scattering Shader for Volumetric Clouds in Three.js (WebGL 2)

Updated

Raymarched cumulus whose in-scatter term is a 16-16-16-3 squared-ReLU MLP trained against a path tracer: within about 8% of path-traced brightness across a full sun sweep where the classic phase-plus-octaves model sits near 0.3x. Includes trained weights, GLSL ES 3.0 inference, and the TypeScript path tracer and trainer.

  • clouds
  • volumetric
  • neural shader
  • mlp
  • multiple scattering
  • raymarch
  • path tracing
  • glsl
  • webgl2
  • machine learning
The demo of Neural Multiple-Scattering Shader for Volumetric Clouds in Three.js (WebGL 2), as its check took it

Play the demo

Demo passed on r2: a small game that shows only this technique, built and checked by GameCrew AI's engine.

Play the demo

When to Use

A hero cloud seen close up (one cumulus in a bounding box) that should look right from every sun angle. An ordinary raymarcher is kept; exactly one quantity, the light scattered toward the camera at each step, comes from a tiny trained network instead of a tuned approximation. Not for a whole sky of clouds (volumetric-clouds-sky-shaders, baked-volumetric-cloud-sea-taa) or stylised clouds.

Measured

Everything below was measured on this code; its demo is the same four files. Mean image brightness against a path-traced reference, sun swept around the cloud at 30 degrees elevation, at the demo's light levels (1.000 = matches the reference):

| sun angle | classic | neural | neural, unseen cloud | |---|---|---|---| | 0 (behind camera) | 0.29 | 1.03 | 1.06 | | 30 | 0.29 | 1.08 | 1.05 | | 60 | 0.31 | 1.05 | 0.99 | | 90 | 0.32 | 0.96 | 0.95 | | 120 | 0.28 | 0.96 | 1.01 | | 150 | 0.21 | 0.96 | 1.07 | | 180 (behind cloud) | 0.20 | 0.96 | 0.99 |

"Classic" is Henyey-Greenstein plus three Wrenninge octaves (all falloffs 0.5) with flat ambient, fed by the same density reads. Held-out correlation of the network with the path tracer on clouds it never saw: sun 0.82, sky 0.87, ground 0.87. The GLSL below, run in WebGL 2, reproduces a line-for-line JavaScript march of the same network to four decimals.

The Idea

Per march step two things are needed: how much light is blocked (local density) and the source function, the light scattered toward the camera through every bounce path:

$J(p, ω) = varpi int Phi(ω' · ω)\, L(p, ω')\, dω'$

A path tracer computes $J$ offline. A 16-16-16-3 MLP learns it from a description of the neighbourhood, never of the object, so it carries over to other clouds of the same medium:

  • inputs 0-5: mean density around the point at radii 6 / 12 / 24 / 48 / 96 / 192 metres (one read of a mip each)
  • inputs 6-11: the same radii, read at p + toSun * r
  • input 12: cos(view, sun); 13: view direction y; 14: sun direction y; 15: the 96 m mean density 96 m above

Inputs 13-15 go beyond Grassi's 13: the sky/ground split depends on which way is up, which the first 13 cannot see. In an ablation on an earlier training set they lifted held-out sky and ground correlation from 0.62 to 0.88 for one extra read. Outputs are sun, sky and ground terms sharing both hidden layers. Activation is squared ReLU and the output is squared, which keeps the field smooth and non-negative.

$C mathrel+= T\,(1 - e^-σ rho Δ s)\,(E_sun\, y_0 + L_sky\, y_1 + L_ground\, y_2), T mathrel*= e^-σ rho Δ s$

E_sun is the sun's irradiance: in three.js a DirectionalLight's color times intensity, with no factor of pi.

Implementation

Four files beside main.ts. Only the first three ship to players.

1. Shape, volume and descriptor (Assets/Game/neuralCloudVolume.ts)

The CPU twin of what the shader reads. The mip chain is built here and each level is uploaded as its own texture, because three.js does not upload custom mips for a Data3DTexture and GPU-generated ones are not guaranteed to match the trainer.

// Pure TypeScript (no imports): the cloud shape, its density volume with a box-filtered mip chain, and the 16-number
// descriptor the network reads. The trainer and the shader must agree on every number here.

export interface CloudShape {
  lobes: number[][]; // [x, y, z, radius] in metres
  base: number; // flat base height
  seed: number;
  erosion: number; // metres the billows push the surface in and out
  feature: number; // billow size in metres
  edge: number; // metres over which density ramps from 0 to 1
}

export const DEFAULT_SHAPE: CloudShape = {
  lobes: [
    [0, 104, 0, 70], [-76, 92, 10, 52], [72, 95, -14, 56], [-34, 100, -56, 48], [42, 98, 50, 50],
    [-10, 150, 4, 50], [32, 140, -26, 40], [-46, 134, 22, 38], [6, 184, 0, 30],
  ],
  base: 60, seed: 7, erosion: 56, feature: 60, edge: 9,
};

function hash(x: number, y: number, z: number, s: number): number {
  let h = Math.imul(x, 374761393) ^ Math.imul(y, 668265263) ^ Math.imul(z, 1274126177) ^ Math.imul(s, 2246822519);
  h = Math.imul(h ^ (h >>> 13), 1540483477);
  return ((h ^ (h >>> 15)) >>> 8) / 16777216;
}

/** 1 - distance to the nearest feature point: round puffs, the cauliflower look of a cumulus. */
function puff(x: number, y: number, z: number, s: number): number {
  const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
  let best = 4;
  for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
    const cx = xi + dx, cy = yi + dy, cz = zi + dz;
    const ex = cx + hash(cx, cy, cz, s) - x, ey = cy + hash(cx, cy, cz, s + 1) - y, ez = cz + hash(cx, cy, cz, s + 2) - z;
    const d2 = ex * ex + ey * ey + ez * ez;
    if (d2 < best) best = d2;
  }
  return 1 - Math.min(1, Math.sqrt(best));
}

function billow(x: number, y: number, z: number, s: number): number {
  return (puff(x, y, z, s) + 0.5 * puff(x * 2.1 + 5.3, y * 2.1 + 1.7, z * 2.1 + 9.1, s + 3) + 0.25 * puff(x * 4.3 + 2.9, y * 4.3 + 7.7, z * 4.3 + 4.1, s + 6)) / 1.75;
}

function smax(a: number, b: number, k: number): number {
  const h = Math.max(k - Math.abs(a - b), 0) / k;
  return Math.max(a, b) + h * h * k * 0.25;
}

/** Density 0..1 at a world point: welded spheres, flat base, billows pushed through the surface. */
export function shapeDensity(s: CloudShape, x: number, y: number, z: number): number {
  if (y < s.base - 12) return 0;
  let d = -1e9;
  for (const l of s.lobes) d = smax(d, l[3] - Math.hypot(x - l[0], y - l[1], z - l[2]), 16);
  if (d < -s.erosion * 0.6) return 0;
  d = -smax(-d, -(y - s.base), 8);
  const t = Math.min(Math.max((y - s.base) / 30, 0), 1), fade = 0.15 + 0.85 * t * t * (3 - 2 * t); // the base stays flat
  d += (billow(x / s.feature, y / s.feature, z / s.feature, s.seed) - 0.5) * s.erosion * fade;
  return Math.min(Math.max(d / s.edge, 0), 1);
}

export const DESC_RADII = [6, 12, 24, 48, 96, 192];

export class CloudVolume {
  n: number; // voxels per side, power of two
  voxel: number; // metres per voxel: 6, 3 or 1.5 so descriptor radii land on whole mips
  minX: number; minY: number; minZ: number;
  size: number;
  lod0: number; // mip whose texel is 6 m
  mips: Float32Array[];

  constructor(n: number, voxel: number, min: number[], shape: CloudShape) {
    this.n = n; this.voxel = voxel; this.minX = min[0]; this.minY = min[1]; this.minZ = min[2];
    this.size = n * voxel; this.lod0 = Math.round(Math.log2(6 / voxel));
    const m0 = new Float32Array(n * n * n);
    for (let z = 1; z < n - 1; z++) for (let y = 1; y < n - 1; y++) for (let x = 1; x < n - 1; x++)
      m0[(z * n + y) * n + x] = shapeDensity(shape, min[0] + (x + 0.5) * voxel, min[1] + (y + 0.5) * voxel, min[2] + (z + 0.5) * voxel);
    this.mips = [m0];
    for (let s = n >> 1; s >= 1; s >>= 1) {
      const src = this.mips[this.mips.length - 1], ps = s * 2, dst = new Float32Array(s * s * s);
      for (let z = 0; z < s; z++) for (let y = 0; y < s; y++) for (let x = 0; x < s; x++) {
        let sum = 0;
        for (let k = 0; k < 8; k++) sum += src[((2 * z + (k >> 2)) * ps + 2 * y + ((k >> 1) & 1)) * ps + 2 * x + (k & 1)];
        dst[(z * s + y) * s + x] = sum * 0.125;
      }
      this.mips.push(dst);
    }
  }

  /** Trilinear read of one mip at a world point, zero outside the box (same as the shader). */
  sample(level: number, x: number, y: number, z: number): number {
    const u = (x - this.minX) / this.size, v = (y - this.minY) / this.size, w = (z - this.minZ) / this.size;
    if (u <= 0 || v <= 0 || w <= 0 || u >= 1 || v >= 1 || w >= 1) return 0;
    const s = this.n >> level, d = this.mips[level], m = s - 1;
    let fx = u * s - 0.5, fy = v * s - 0.5, fz = w * s - 0.5;
    fx = fx < 0 ? 0 : fx > m ? m : fx; fy = fy < 0 ? 0 : fy > m ? m : fy; fz = fz < 0 ? 0 : fz > m ? m : fz;
    const x0 = fx | 0, y0 = fy | 0, z0 = fz | 0;
    const x1 = x0 < m ? x0 + 1 : m, y1 = y0 < m ? y0 + 1 : m, z1 = z0 < m ? z0 + 1 : m;
    const tx = fx - x0, ty = fy - y0, tz = fz - z0;
    const r00 = (z0 * s + y0) * s, r10 = (z0 * s + y1) * s, r01 = (z1 * s + y0) * s, r11 = (z1 * s + y1) * s;
    const c00 = d[r00 + x0] + (d[r00 + x1] - d[r00 + x0]) * tx, c10 = d[r10 + x0] + (d[r10 + x1] - d[r10 + x0]) * tx;
    const c01 = d[r01 + x0] + (d[r01 + x1] - d[r01 + x0]) * tx, c11 = d[r11 + x0] + (d[r11 + x1] - d[r11 + x0]) * tx;
    const a = c00 + (c10 - c00) * ty, b = c01 + (c11 - c01) * ty;
    return a + (b - a) * tz;
  }

  /**
   * The 16 network inputs at p for a ray travelling along v with the sun toward s: mean density at 6 radii here, the
   * same 6 toward the sun, cos(view, sun), view y, sun y, and the 96 m mean density 96 m above.
   */
  descriptor(px: number, py: number, pz: number, sx: number, sy: number, sz: number, vx: number, vy: number, vz: number, out: Float32Array, o: number): void {
    for (let i = 0; i < 6; i++) {
      const r = DESC_RADII[i], l = this.lod0 + i;
      out[o + i] = this.sample(l, px, py, pz);
      out[o + 6 + i] = this.sample(l, px + sx * r, py + sy * r, pz + sz * r);
    }
    out[o + 12] = vx * sx + vy * sy + vz * sz;
    out[o + 13] = vy;
    out[o + 14] = sy;
    out[o + 15] = this.sample(this.lod0 + 4, px, py + 96, pz);
  }
}

2. Trained weights (Assets/Game/neuralCloudWeights.ts)

640 numbers in the shader's vec4 uNet[160] layout: W0 rows at 0-63 (four per neuron), W1 at 64-127, W2 at 128-139, biases at 140-148, input mean at 149-152, input 1/std at 153-156, output clamp at 157, sentinel 1234.5 at 159.x. Trained by file 4 on 12 random cumulus shapes (20,000 samples each, 128 paths per sample, 40 epochs). Valid for this medium only.

// Trained weights for the neural cloud shader, packed as 160 vec4 (neuralCloudTrainer.ts writes this layout).
// Trained on 12 cumulus shapes against the path tracer; valid only for this medium.
export const NEURAL_CLOUD_MEDIUM = { extinction: 0.25, g: 0.85, albedo: 0.999 };

export const NEURAL_CLOUD_WEIGHTS: number[] = [
  -0.057598, -0.086757, -0.18598, -0.11672, 0.011137, -0.040122, 0.11815, 0.12481, 0.050611, 0.22431, 0.073688, -0.060984, -0.43119, 0.098735, 0.21716, -0.21031,
  -0.01574, -0.15055, -0.19423, 0.15153, 0.10939, -0.014707, 0.20678, -0.046023, -0.04107, 0.027936, -0.093223, -0.029663, -0.010961, 0.086269, -0.076207, -0.40013,
  -0.01222, 0.011386, 0.018279, -0.11727, -0.056821, 0.51522, 0.039732, 0.0048303, 0.085062, -0.16557, -0.11617, 0.0092088, 0.030517, -0.066554, 0.055834, -0.12845,
  -0.028711, -0.072801, -0.050948, 0.071105, -0.082494, -0.21062, 0.046639, 0.046643, 0.01689, -0.086662, -0.1271, 0.01322, 0.0056762, -0.11765, 0.022998, 0.2319,
  -0.030989, -0.06616, -0.018655, -0.083663, 0.018406, -0.063832, -0.036752, 0.022055, -0.0097865, -0.18937, 0.2675, -0.041467, -0.029959, -0.20802, -0.089011, -0.014054,
  -0.0048953, -0.0095309, -0.0057583, 0.013606, -0.19194, -0.12943, 0.013002, -0.010984, 0.054931, -0.071763, -0.017323, 0.018153, 0.00029924, -0.050472, -0.016247, 0.92522,
  -0.043238, -0.014028, 0.0072891, -0.14701, -0.046862, 0.014698, -0.057568, 0.055547, 0.01056, -0.064982, 0.069829, -0.011124, -0.061182, 0.53926, 0.00070028, 0.054062,
  0.036714, 0.013226, -0.011404, -0.038868, -0.044584, -0.069273, 0.0058643, -0.010583, 0.15651, 0.20841, 0.18686, -0.12669, 0.01576, -0.088824, 0.1336, -0.067833,
  -0.019898, 0.029658, 0.064086, 0.0061009, 0.014428, 0.055001, 0.013709, -0.085273, -0.17455, -0.43105, -0.10138, 0.0019994, 0.24557, -0.069305, -0.026101, -0.059095,
  -0.027396, -0.030204, 0.0069257, -0.0031261, -0.0022815, -0.040632, 0.02743, -0.064114, -0.11903, -0.25658, 0.00001208, 0.0037311, 0.80573, 0.067599, -0.0022666, 0.13387,
  0.021513, 0.012416, 0.10339, 0.057502, 0.040562, -0.012975, -0.026153, -0.035456, -0.051347, -0.1571, -0.065057, 0.0049583, 0.12794, 0.068686, 0.018568, 0.12625,
  0.042581, 0.013026, -0.028054, -0.015747, 0.01463, -0.0004179, -0.11806, -0.31261, -0.5105, -0.52663, -0.23042, 0.010526, 0.10009, -0.00085531, 0.062615, -0.0078059,
  0.063984, 0.056572, 0.048962, 0.046928, -0.035798, 0.091594, -0.073518, -0.14578, -0.12893, -0.055751, 0.043316, 0.049171, 0.35813, 0.041742, 0.1069, -0.42791,
  -0.014011, -0.027479, 0.097751, 0.0047781, -0.18931, -0.041303, -0.0024982, -0.0013025, 0.08531, 0.11373, -0.13175, -0.070886, -0.018098, 0.041202, -0.095791, -0.71192,
  0.042746, 0.043286, -0.07272, 0.11896, 0.02529, -0.063629, -0.11584, 0.001598, -0.20924, 0.015231, 0.23556, 0.16322, -0.11924, 0.091045, 0.18974, -0.60786,
  -0.096084, -0.014897, 0.0099727, -0.0040084, -0.038901, -0.0011672, 0.16146, -0.0012314, -0.0096478, -0.50539, 0.33686, 0.019786, 0.032822, -0.029617, 0.24016, 0.10489,
  -0.18749, -0.25629, 0.1152, 0.13496, 0.10953, -0.033571, -0.12443, -0.052479, 0.027802, 0.034389, -0.1513, 0.17727, 0.0048501, -0.21681, -0.22476, 0.14727,
  -0.2329, -0.085406, -0.23116, 0.15106, 0.046662, -1.7413, -0.024782, -0.14499, 0.037371, -0.025493, -0.11439, -0.061323, -0.037444, 0.19054, 0.20046, 0.058623,
  0.12886, -0.02677, 0.01485, -0.024481, 0.11219, 0.014646, 0.014459, -0.0020097, -0.30728, -0.017125, -0.20523, -0.20914, 0.039646, 0.047719, 0.068521, -0.12126,
  0.27366, -0.0066053, 0.11311, 0.017594, 0.23482, 0.034243, -0.29068, 0.068227, -0.20836, 0.12174, 0.06788, -0.34101, -0.37997, 0.091123, -0.16131, -0.1711,
  0.11612, 0.066417, -0.046927, -0.093544, -0.023207, -0.059306, -0.027566, -0.022819, 0.12309, -0.039259, -0.021669, 0.0039671, 0.11819, -0.28221, -0.04534, -0.12109,
  -0.10517, 0.20523, 0.015853, -0.28093, -0.12344, -0.038269, -0.03146, 0.0068806, -0.080571, -0.022044, 0.084318, 0.21191, 0.12141, 0.048203, -0.0080967, 0.10297,
  0.37475, -0.13975, -0.014248, 0.03847, 0.17566, 0.0020931, -0.32558, -0.70933, 0.19717, 0.33852, -0.16636, -0.26272, -0.013282, 0.081824, 0.20219, -0.29263,
  -0.067537, -0.65214, 0.13863, 0.34056, 0.20091, 0.0040812, -0.21893, -0.02844, 0.11147, -0.024487, -0.35928, 0.079922, 0.10013, -0.68792, -0.42332, 0.050261,
  0.20248, 0.17977, -0.14728, -0.22275, -0.1093, 0.025281, 0.23827, -0.14319, 0.23587, -0.16987, -0.3701, -0.39533, 0.072916, 0.060384, 0.09254, -0.26161,
  -0.0050461, 0.087652, 0.044222, -0.0011697, -0.19462, -0.034993, 0.03962, -0.1167, 0.013936, 0.24294, 0.11417, -0.24649, 0.11507, 0.047668, 0.023115, 0.013564,
  -0.26067, 0.29474, -0.074184, 0.068585, -0.2039, -0.19652, -0.40847, -1.232, 0.20968, 0.043067, -0.27651, 0.53799, -0.11956, 0.15623, -0.15393, 0.10675,
  -0.15701, -0.27877, -0.10325, -0.34445, -0.10507, 0.013193, 0.016898, -0.019579, -0.84194, 0.078924, -0.038099, 0.035856, 0.12575, -0.1758, 0.061965, 0.13662,
  0.20184, 0.014943, -0.13359, 0.017457, 0.067228, 0.012731, 0.23045, -0.22314, 0.13327, 0.20286, -0.088649, 0.28294, -0.41044, 0.19008, 0.12425, 0.085698,
  -0.016932, 0.027355, -0.12934, -0.10287, -0.050259, -0.18216, 0.016822, -0.024846, 0.046901, -0.013924, -0.16271, -0.16935, 0.0054733, 0.013733, -0.061348, 0.14832,
  0.10538, 0.0031847, -0.042245, -0.26583, -0.16417, -0.024363, -0.098603, -0.82503, -0.1639, 0.63216, -0.27477, -0.26672, 0.21465, 0.0027947, -0.25054, -0.24171,
  -0.026487, -0.18477, -0.89039, 0.32671, -0.15311, -1.2851, -0.050755, -0.23029, -0.086783, 0.019987, -0.023864, 0.033014, 0.14799, -0.019375, -0.10968, -0.45058,
  0.025013, 0.065423, -0.37779, 0.051875, 0.13885, -0.035111, 0.10662, -0.12328, 0.0098221, 0.14089, -0.11202, -0.31107, -0.054572, -0.037774, 0.62751, 0.085249,
  0.087335, 0.27793, -0.015913, -0.15292, 0.025486, 0.22473, -0.12744, -0.23811, 0.15256, 0.08168, -0.34785, -0.086198, 0.10645, 0.23242, 0.070062, 0.31399,
  0.10857, -0.31372, 0.051594, 0.059581, 0.021276, -0.26308, 0.1362, 0.057522, -0.18955, -0.096471, 0.32207, 0.029212, -0.09877, -0.18458, -0.084877, -0.3314,
  0.20815, 0.054181, 0.2619, 0.60494, 0.36849, 0.33712, 0.11487, 0.14724, 0.33138, -0.35642, 0.59232, -0.62088, 0.086657, 0.23654, 0.16502, 0.4158,
  0.30646, 0.40277, 0.62793, 0.12402, 0.47431, 0.57121, 0.052728, 0.41008, 0.36047, 0.28193, -0.36763, 0.42329, -0.15325, 0.55566, -0.45591, 0.35231,
  0.33773, 0.53502, 0.85476, 0, 0.55132, 0.51207, 0.46002, 0.38557, 0.26778, 0.058635, 0.4937, 0.43542, 0.36938, 0.27425, 0.12057, 0.018634,
  -0.17507, -0.33255, 0.52277, 0.09067, 3.8412, 4.9063, 6.8224, 9.877, 12.645, 53.364, 3.1368, 3.1759, 3.2753, 3.7565, 7.5994, 47.831,
  1.8192, 2.5499, 3.6319, 9.9144, 4.671, 1.2365, 1.2481, 0, 0, 0, 0, 0, 1234.5, 0, 0, 0,
];

Checksums a unit test can assert, so a mistyped number never goes unnoticed: the 640 values sum to 1415.8259, and the sum of w[i] * (i % 7 + 1) is 9158.8349.

3. The material (Assets/Game/neuralCloud.ts)

A back-face box is marched in world space. With scale below 1 the march runs into a smaller half-float target inside the composite quad's onBeforeRender (once per drawn frame, never during headless steps) and is composited premultiplied. setMode('split') lights the left half with the classic model for comparison.

// A raymarched cloud whose in-scatter term is a small trained network (13 density reads + ~600 multiply-adds per lit
// step) instead of a hand-tuned approximation. The volume, descriptor and weights must stay in step with the trainer.
import * as THREE from 'three';
import { CloudVolume, DEFAULT_SHAPE, type CloudShape } from './neuralCloudVolume.js';
import { NEURAL_CLOUD_MEDIUM, NEURAL_CLOUD_WEIGHTS } from './neuralCloudWeights.js';

export type CloudMode = 'neural' | 'classic' | 'split';

export interface NeuralCloudOptions {
  shape?: CloudShape;
  /** Voxels per side (power of two) and metres per voxel (6, 3 or 1.5). */
  voxels?: number;
  voxel?: number;
  /** World position of the box's minimum corner. */
  min?: [number, number, number];
  /** Offscreen resolution scale. 1 draws straight into the scene; below 1 marches into a smaller target and composites. */
  scale?: number;
  /** March step in voxels, and the most steps a ray takes. */
  stepScale?: number;
  maxSteps?: number;
  weights?: ArrayLike<number>;
}

export interface NeuralCloud {
  /** Add this to the scene. */
  object: THREE.Object3D;
  uniforms: Record<string, THREE.IUniform>;
  volume: CloudVolume;
  /** Direction toward the sun, and its irradiance (a three DirectionalLight's color times intensity). */
  setSun(toSun: THREE.Vector3, irradiance: THREE.Color): void;
  setMode(mode: CloudMode, split?: number): void;
  dispose(): void;
}

const VERT = /* glsl */ `
varying vec3 vWorld;
void main() {
  vec4 w = modelMatrix * vec4(position, 1.0);
  vWorld = w.xyz;
  gl_Position = projectionMatrix * viewMatrix * w;
}`;

const FRAG = /* glsl */ `
precision highp float;
precision highp sampler3D;
uniform sampler3D uDensity, uSkip, uR0, uR1, uR2, uR3, uR4, uR5;
uniform vec4 uNet[160];
uniform vec3 uBoxMin, uSunDir, uSunColor, uSkyColor, uGroundColor;
uniform vec2 uResolution;
uniform float uBoxSize, uVoxel, uSkipCell, uExtinction, uPhaseG, uStepScale, uMode, uSplit;
uniform int uMaxSteps;
varying vec3 vWorld;

// Zero outside the box, so coarse levels never smear cloud past the walls (the trainer does the same).
float dens(sampler3D t, vec3 p) {
  vec3 u = (p - uBoxMin) / uBoxSize;
  if (any(lessThanEqual(u, vec3(0.0))) || any(greaterThanEqual(u, vec3(1.0)))) return 0.0;
  return textureLod(t, u, 0.0).r;
}

// Four neurons at once: weight rows start at uNet[w], biases are uNet[b].
vec4 quad(vec4 a0, vec4 a1, vec4 a2, vec4 a3, int w, int b) {
  vec4 s = uNet[b];
  for (int c = 0; c < 4; c++)
    s[c] += dot(a0, uNet[w + 4 * c]) + dot(a1, uNet[w + 4 * c + 1]) + dot(a2, uNet[w + 4 * c + 2]) + dot(a3, uNet[w + 4 * c + 3]);
  s = max(s, 0.0);
  return s * s; // squared ReLU: smooth, so no shell-shaped creases
}

vec3 cloudNet(vec4 x0, vec4 x1, vec4 x2, vec4 x3) {
  x0 = (x0 - uNet[149]) * uNet[153]; x1 = (x1 - uNet[150]) * uNet[154];
  x2 = (x2 - uNet[151]) * uNet[155]; x3 = (x3 - uNet[152]) * uNet[156];
  vec4 a0 = quad(x0, x1, x2, x3, 0, 140), a1 = quad(x0, x1, x2, x3, 16, 141);
  vec4 a2 = quad(x0, x1, x2, x3, 32, 142), a3 = quad(x0, x1, x2, x3, 48, 143);
  vec4 b0 = quad(a0, a1, a2, a3, 64, 144), b1 = quad(a0, a1, a2, a3, 80, 145);
  vec4 b2 = quad(a0, a1, a2, a3, 96, 146), b3 = quad(a0, a1, a2, a3, 112, 147);
  vec3 y;
  for (int k = 0; k < 3; k++) {
    float s = uNet[148][k] + dot(b0, uNet[128 + 4 * k]) + dot(b1, uNet[129 + 4 * k]) + dot(b2, uNet[130 + 4 * k]) + dot(b3, uNet[131 + 4 * k]);
    y[k] = s * s; // non-negative by construction
  }
  return min(y, uNet[157].xyz);
}

float hg(float c, float g) {
  float k = max(1e-3, 1.0 + g * g - 2.0 * g * c);
  return (1.0 - g * g) / (12.566371 * k * sqrt(k));
}

// The classic real-time model, from the same reads: Henyey-Greenstein, three Wrenninge octaves, flat ambient.
vec3 classic(vec4 x1, vec4 x2, float mu) {
  float tau = uExtinction * (9.0 * (x1.z + x1.w) + 18.0 * x2.x + 36.0 * x2.y + 72.0 * x2.z + 144.0 * x2.w);
  float s = 0.0, a = 1.0;
  for (int i = 0; i < 3; i++) { s += a * hg(mu, uPhaseG * a) * exp(-a * tau); a *= 0.5; }
  return vec3(s, 0.5, 0.5);
}

// (sun, sky, ground) source terms per unit light: THE ONE QUANTITY THE NETWORK REPLACES.
vec3 shade(vec3 p, vec3 rd, float mu, bool neural) {
  vec3 s = uSunDir;
  vec4 x0 = vec4(dens(uR0, p), dens(uR1, p), dens(uR2, p), dens(uR3, p));
  vec4 x1 = vec4(dens(uR4, p), dens(uR5, p), dens(uR0, p + s * 6.0), dens(uR1, p + s * 12.0));
  vec4 x2 = vec4(dens(uR2, p + s * 24.0), dens(uR3, p + s * 48.0), dens(uR4, p + s * 96.0), dens(uR5, p + s * 192.0));
  vec4 x3 = vec4(mu, rd.y, s.y, dens(uR4, p + vec3(0.0, 96.0, 0.0)));
  if (neural && abs(uNet[159].x - 1234.5) < 0.01) return cloudNet(x0, x1, x2, x3);
  return classic(x1, x2, mu);
}

float ign(vec2 px) { return fract(52.9829189 * fract(dot(px, vec2(0.06711056, 0.00583715)))); }

void main() {
  vec3 ro = cameraPosition, rd = normalize(vWorld - cameraPosition);
  vec3 safe = vec3(abs(rd.x) < 1e-6 ? 1e-6 : rd.x, abs(rd.y) < 1e-6 ? 1e-6 : rd.y, abs(rd.z) < 1e-6 ? 1e-6 : rd.z);
  vec3 ta = (uBoxMin - ro) / safe, tb = (uBoxMin + uBoxSize - ro) / safe;
  vec3 lo = min(ta, tb), hi = max(ta, tb);
  float tNear = max(max(lo.x, lo.y), max(lo.z, 0.0)), tFar = min(hi.x, min(hi.y, hi.z));
  vec3 col = vec3(0.0);
  float T = 1.0;
  if (tFar > tNear) {
    bool neural = uMode > 1.5 ? gl_FragCoord.x / uResolution.x > uSplit : uMode > 0.5;
    float ds = uVoxel * uStepScale, mu = dot(rd, uSunDir);
    float t = tNear + ds * ign(gl_FragCoord.xy);
    for (int i = 0; i < 192; i++) {
      if (i >= uMaxSteps || t >= tFar || T < 0.01) break;
      vec3 p = ro + rd * t;
      if (dens(uSkip, p) <= 0.0) { t += uSkipCell * 0.5; continue; } // provably empty for half a coarse cell
      float d = dens(uDensity, p);
      if (d > 1e-4) {
        vec3 y = shade(p, rd, mu, neural);
        float stepT = exp(-d * uExtinction * ds);
        col += T * (1.0 - stepT) * (uSunColor * y.x + uSkyColor * y.y + uGroundColor * y.z);
        T *= stepT;
      }
      t += ds;
    }
  }
  // Tone map the un-premultiplied colour, then premultiply again: tone mapping a premultiplied edge leaves a bright halo.
  float alpha = 1.0 - T;
  gl_FragColor = vec4(col / max(alpha, 1e-4), alpha);
  #include <tonemapping_fragment>
  #include <colorspace_fragment>
  gl_FragColor.rgb *= alpha;
}`;

const COMPOSITE_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;

const COMPOSITE_FRAG = /* glsl */ `
uniform sampler2D tCloud;
uniform vec2 uResolution;
uniform float uMode, uSplit;
varying vec2 vUv;
void main() {
  vec4 c = texture2D(tCloud, vUv);
  if (uMode > 1.5 && abs(vUv.x - uSplit) * uResolution.x < 1.0) c = vec4(0.85, 0.85, 0.85, 1.0);
  gl_FragColor = vec4(c.rgb / max(c.a, 1e-4), c.a);
  #include <tonemapping_fragment>
  #include <colorspace_fragment>
  gl_FragColor.rgb *= c.a;
}`;

function levelTexture(data: Float32Array, n: number): THREE.Data3DTexture {
  const half = new Uint16Array(data.length);
  for (let i = 0; i < data.length; i++) half[i] = THREE.DataUtils.toHalfFloat(data[i]);
  const tex = new THREE.Data3DTexture(half, n, n, n);
  tex.format = THREE.RedFormat;
  tex.type = THREE.HalfFloatType;
  tex.minFilter = tex.magFilter = THREE.LinearFilter;
  tex.wrapS = tex.wrapT = tex.wrapR = THREE.ClampToEdgeWrapping;
  tex.generateMipmaps = false;
  tex.unpackAlignment = 1;
  tex.needsUpdate = true;
  return tex;
}

const MODES: Record<CloudMode, number> = { classic: 0, neural: 1, split: 2 };

export function createNeuralCloud(renderer: THREE.WebGLRenderer, opts: NeuralCloudOptions = {}): NeuralCloud {
  const n = opts.voxels ?? 128, voxel = opts.voxel ?? 3, min = opts.min ?? [-192, 0, -192];
  const volume = new CloudVolume(n, voxel, min, opts.shape ?? DEFAULT_SHAPE);
  // One texture per mip the shader reads: its own box-filtered levels, never GPU-generated ones.
  const cache = new Map<number, THREE.Data3DTexture>();
  const level = (l: number): THREE.Data3DTexture => {
    let t = cache.get(l);
    if (!t) cache.set(l, (t = levelTexture(volume.mips[l], n >> l)));
    return t;
  };
  const skipLevel = volume.lod0 + 2; // 24 m cells
  const U = (value: unknown): THREE.IUniform => ({ value });
  const net = new Float32Array(640);
  net.set(Array.from(opts.weights ?? NEURAL_CLOUD_WEIGHTS).slice(0, 640)); // always all 160 vectors
  const uniforms: Record<string, THREE.IUniform> = {
    uDensity: U(level(0)), uSkip: U(level(skipLevel)), uSkipCell: U(voxel * (1 << skipLevel)),
    uNet: U(net), uBoxMin: U(new THREE.Vector3(min[0], min[1], min[2])), uBoxSize: U(volume.size), uVoxel: U(voxel),
    uSunDir: U(new THREE.Vector3(0.4, 0.5, 0.76).normalize()), uSunColor: U(new THREE.Color(16, 15, 13.6)),
    uSkyColor: U(new THREE.Color(0.18, 0.28, 0.47)), uGroundColor: U(new THREE.Color(0.075, 0.075, 0.07)),
    uExtinction: U(NEURAL_CLOUD_MEDIUM.extinction), uPhaseG: U(NEURAL_CLOUD_MEDIUM.g),
    uStepScale: U(opts.stepScale ?? 1), uMaxSteps: U(opts.maxSteps ?? 160),
    uMode: U(1), uSplit: U(0.5), uResolution: U(new THREE.Vector2(1, 1)),
  };
  for (let i = 0; i < 6; i++) uniforms[`uR${i}`] = U(level(volume.lod0 + i));

  const boxGeo = new THREE.BoxGeometry(volume.size, volume.size, volume.size);
  const material = new THREE.ShaderMaterial({
    vertexShader: VERT, fragmentShader: FRAG, uniforms, side: THREE.BackSide, transparent: true, premultipliedAlpha: true, depthWrite: false, depthTest: false,
  });
  const box = new THREE.Mesh(boxGeo, material);
  box.position.set(min[0] + volume.size / 2, min[1] + volume.size / 2, min[2] + volume.size / 2);
  box.frustumCulled = false;
  box.renderOrder = 1000;
  box.name = 'NeuralCloud';

  const canFloat = renderer.extensions.has('EXT_color_buffer_float') || renderer.extensions.has('EXT_color_buffer_half_float');
  const scale = canFloat ? Math.min(1, Math.max(0.25, opts.scale ?? 1)) : 1;
  let object: THREE.Object3D = box;
  const owned: { dispose(): void }[] = [boxGeo, material];
  const size = new THREE.Vector2();
  if (scale < 1) {
    // March into a smaller HDR target once per drawn frame, then composite it over the scene.
    const target = new THREE.WebGLRenderTarget(64, 64, { type: THREE.HalfFloatType, format: THREE.RGBAFormat, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, depthBuffer: false, generateMipmaps: false });
    const inner = new THREE.Scene();
    inner.add(box);
    const quadGeo = new THREE.PlaneGeometry(2, 2);
    const quadMat = new THREE.ShaderMaterial({
      vertexShader: COMPOSITE_VERT, fragmentShader: COMPOSITE_FRAG, transparent: true, premultipliedAlpha: true, depthWrite: false, depthTest: false,
      uniforms: { tCloud: U(target.texture), uMode: uniforms.uMode, uSplit: uniforms.uSplit, uResolution: U(new THREE.Vector2(1, 1)) },
    });
    const quad = new THREE.Mesh(quadGeo, quadMat);
    quad.frustumCulled = false;
    quad.renderOrder = 1000;
    quad.name = 'NeuralCloudComposite';
    const clear = new THREE.Color();
    let busy = false;
    quad.onBeforeRender = (r, _scene, camera) => {
      if (busy) return;
      r.getDrawingBufferSize(size);
      const w = Math.max(64, Math.round(size.x * scale)), h = Math.max(64, Math.round(size.y * scale));
      if (target.width !== w || target.height !== h) target.setSize(w, h);
      (uniforms.uResolution.value as THREE.Vector2).set(w, h);
      (quadMat.uniforms.uResolution.value as THREE.Vector2).copy(size);
      const prevTarget = r.getRenderTarget(), prevAlpha = r.getClearAlpha(), prevAuto = r.autoClear, prevXr = r.xr.enabled;
      r.getClearColor(clear);
      busy = true;
      r.xr.enabled = false;
      r.autoClear = true;
      r.setRenderTarget(target);
      r.setClearColor(0x000000, 0);
      r.render(inner, camera);
      r.setRenderTarget(prevTarget);
      r.setClearColor(clear, prevAlpha);
      r.autoClear = prevAuto;
      r.xr.enabled = prevXr;
      busy = false;
    };
    object = quad;
    owned.push(target, quadGeo, quadMat);
  } else {
    box.onBeforeRender = (r) => {
      r.getDrawingBufferSize(size);
      (uniforms.uResolution.value as THREE.Vector2).copy(size);
    };
  }

  return {
    object, uniforms, volume,
    setSun(toSun: THREE.Vector3, irradiance: THREE.Color): void {
      (uniforms.uSunDir.value as THREE.Vector3).copy(toSun).normalize();
      (uniforms.uSunColor.value as THREE.Color).copy(irradiance);
    },
    setMode(mode: CloudMode, split = 0.5): void {
      uniforms.uMode.value = MODES[mode];
      uniforms.uSplit.value = split;
    },
    dispose(): void {
      object.removeFromParent();
      for (const o of owned) o.dispose();
      for (const t of cache.values()) t.dispose();
    },
  };
}

Using it:

import { createNeuralCloud } from './neuralCloud.js';

camera.far = 4000; // the box (384 m, at y 0..384 by default) must sit inside the far plane
camera.updateProjectionMatrix();
const cloud = createNeuralCloud(game.renderer, { scale: game.headless ? 0.75 : 0.5 });
game.scene.add(cloud.object);
cloud.setSun(toSun, new THREE.Color(1, 0.94, 0.85).multiplyScalar(11)); // every time the sun moves

4. Path tracer and trainer (Assets/Game/neuralCloudTrainer.ts)

Only needed to change the medium (extinction, phase g, albedo) or the descriptor. Labels come from a backward path tracer: at each scatter vertex add w * phase * sunTransmittance to the sun label, sample a new direction from the phase function, find the next collision by delta tracking; on escape add w to the sky label if heading up, else to the ground label.

// Offline side of the neural cloud: a backward volumetric path tracer that labels points with their true
// (sun, sky, ground) source terms, and an Adam trainer that fits the 16-16-16-3 squared-ReLU network to them and packs
// it for the shader. Pure TypeScript: it runs in any JS runtime (a worker, a test, Node). Nothing here ships to players.
import { CloudVolume, type CloudShape } from './neuralCloudVolume.js';
import { NEURAL_CLOUD_MEDIUM } from './neuralCloudWeights.js';

const SIGMA = NEURAL_CLOUD_MEDIUM.extinction, G = NEURAL_CLOUD_MEDIUM.g, ALBEDO = NEURAL_CLOUD_MEDIUM.albedo;
const IN = 16, H = 16, OUT = 3, W0 = 0, B0 = 256, W1 = 272, B1 = 528, W2 = 544, B2 = 592, P = 595;

export class Rng {
  s: number;
  constructor(seed: number) {
    this.s = (Math.imul(seed, 747796405) + 2891336453) >>> 0 || 1;
  }
  next(): number {
    let s = this.s;
    s ^= s << 13; s >>>= 0; s ^= s >>> 17; s ^= s << 5; s >>>= 0;
    this.s = s;
    return (s >>> 8) / 16777216;
  }
}

let t0 = 0, t1 = 0;
function box(v: CloudVolume, ox: number, oy: number, oz: number, dx: number, dy: number, dz: number): boolean {
  t0 = 0; t1 = Infinity;
  const o = [ox, oy, oz], d = [dx, dy, dz], mn = [v.minX, v.minY, v.minZ];
  for (let a = 0; a < 3; a++) {
    const inv = 1 / (Math.abs(d[a]) < 1e-6 ? 1e-6 : d[a]);
    const ta = (mn[a] - o[a]) * inv, tb = (mn[a] + v.size - o[a]) * inv;
    t0 = Math.max(t0, Math.min(ta, tb)); t1 = Math.min(t1, Math.max(ta, tb));
  }
  return t1 > t0;
}

export const hit = [0, 0, 0];
/** Delta (Woodcock) tracking to the next collision; the majorant is SIGMA because density never exceeds 1. */
export function track(v: CloudVolume, ox: number, oy: number, oz: number, dx: number, dy: number, dz: number, rng: Rng): boolean {
  if (!box(v, ox, oy, oz, dx, dy, dz)) return false;
  let t = t0;
  const end = t1;
  for (;;) {
    t -= Math.log(1 - rng.next()) / SIGMA;
    if (t >= end) return false;
    hit[0] = ox + dx * t; hit[1] = oy + dy * t; hit[2] = oz + dz * t;
    if (rng.next() < v.sample(0, hit[0], hit[1], hit[2])) return true;
  }
}

/** Transmittance toward the sun as a half-resolution volume, so a bounce costs one read instead of a march. */
export function sunVolume(v: CloudVolume, sx: number, sy: number, sz: number): CloudVolume {
  const g = Object.create(CloudVolume.prototype) as CloudVolume;
  const m = v.n >> 1, cell = v.voxel * 2, data = new Float32Array(m * m * m);
  for (let z = 0; z < m; z++) for (let y = 0; y < m; y++) for (let x = 0; x < m; x++) {
    const px = v.minX + (x + 0.5) * cell, py = v.minY + (y + 0.5) * cell, pz = v.minZ + (z + 0.5) * cell;
    let tau = 0;
    if (box(v, px, py, pz, sx, sy, sz)) for (let t = cell * 0.5, end = t1; t < end; t += cell) tau += v.sample(1, px + sx * t, py + sy * t, pz + sz * t);
    data[(z * m + y) * m + x] = Math.exp(-tau * SIGMA * cell);
  }
  return Object.assign(g, { n: m, voxel: cell, minX: v.minX, minY: v.minY, minZ: v.minZ, size: v.size, lod0: 0, mips: [data] });
}

function phase(c: number): number {
  const k = 1 + G * G - 2 * G * c;
  return (1 - G * G) / (12.566370614 * k * Math.sqrt(k));
}

export const est = [0, 0, 0];
/** Source function at p for a camera ray travelling along v: (sun, sky, ground) per unit light, into est. */
export function estimate(vol: CloudVolume, sun: CloudVolume, sx: number, sy: number, sz: number, px: number, py: number, pz: number, vx: number, vy: number, vz: number, paths: number, rng: Rng): void {
  est[0] = est[1] = est[2] = 0;
  for (let n = 0; n < paths; n++) {
    let x = px, y = py, z = pz, dx = vx, dy = vy, dz = vz, w = ALBEDO;
    for (let b = 0; b < 512; b++) {
      // next-event estimation: sunlight scattering once more, toward the camera
      est[0] += w * phase(dx * sx + dy * sy + dz * sz) * Math.max(sun.sample(0, x, y, z), 0);
      // a new direction from the Henyey-Greenstein phase function, around (dx, dy, dz)
      const s = (1 - G * G) / (1 - G + 2 * G * rng.next()), c = Math.min(1, Math.max(-1, (1 + G * G - s * s) / (2 * G)));
      const sn = Math.sqrt(1 - c * c), ph = 6.283185307 * rng.next(), ax = Math.abs(dy) > 0.99 ? 1 : 0, ay = 1 - ax;
      let tx = ay * dz, ty = -ax * dz, tz = ax * dy - ay * dx;
      const tl = 1 / Math.hypot(tx, ty, tz);
      tx *= tl; ty *= tl; tz *= tl;
      const bx = dy * tz - dz * ty, by = dz * tx - dx * tz, bz = dx * ty - dy * tx, ca = Math.cos(ph) * sn, sa = Math.sin(ph) * sn;
      const nx = tx * ca + bx * sa + dx * c, ny = ty * ca + by * sa + dy * c, nz = tz * ca + bz * sa + dz * c, nl = 1 / Math.hypot(nx, ny, nz);
      dx = nx * nl; dy = ny * nl; dz = nz * nl;
      if (!track(vol, x, y, z, dx, dy, dz, rng)) { est[dy > 0 ? 1 : 2] += w; break; } // escaped to the sky or the ground
      x = hit[0]; y = hit[1]; z = hit[2]; w *= ALBEDO;
    }
  }
  est[0] /= paths; est[1] /= paths; est[2] /= paths;
}

/** A random cumulus of the same family as DEFAULT_SHAPE, so the network sees more than one cloud. */
export function randomShape(seed: number): CloudShape {
  const r = new Rng(seed * 977 + 13), lobes: number[][] = [], base = 50 + r.next() * 22;
  const count = 4 + Math.floor(r.next() * 7), spread = 40 + r.next() * 50;
  for (let i = 0; i < count; i++) {
    const rad = 28 + r.next() * 46, a = r.next() * 6.2832, d = i === 0 ? 0 : Math.sqrt(r.next()) * spread;
    lobes.push([Math.cos(a) * d, base + 25 + r.next() * 100, Math.sin(a) * d, i === 0 ? 55 + r.next() * 25 : rad]);
  }
  return { lobes, base, seed: seed + 100, erosion: 30 + r.next() * 36, feature: 40 + r.next() * 40, edge: 6 + r.next() * 10 };
}

/** Fills X (16 per sample) and Y (3 per sample) from offset o: `count` samples on one cloud, over `sunDirs` sun directions. */
export function makeSamples(vol: CloudVolume, count: number, sunDirs: number, paths: number, seed: number, X: Float32Array, Y: Float32Array, o = 0): void {
  const rs = new Rng(seed), cx = vol.minX + vol.size / 2, cz = vol.minZ + vol.size / 2, cy = vol.minY + 110;
  for (let k = 0; k < sunDirs; k++) {
    const sy = 0.05 + 0.95 * (k + rs.next()) / sunDirs, sr = Math.sqrt(1 - sy * sy), sa = rs.next() * 6.2832;
    const sx = sr * Math.cos(sa), sz = sr * Math.sin(sa), sun = sunVolume(vol, sx, sy, sz);
    for (let i = k; i < count; i += sunDirs) {
      const rng = new Rng(seed * 100003 + i + 1);
      let px = cx, py = cy, pz = cz, dx = 0, dy = 0, dz = 1;
      // Sample the way a camera does: where a ray from outside first collides, not evenly through the interior.
      for (let attempt = 0; attempt < 64; attempt++) {
        const h = 1 - 1.3 * rng.next(), cr = Math.sqrt(Math.max(0, 1 - h * h)), ca = rng.next() * 6.2832, dist = 300 + 200 * rng.next();
        const ox = cx + cr * Math.cos(ca) * dist, oy = cy + h * dist, oz = cz + cr * Math.sin(ca) * dist;
        dx = cx + (rng.next() - 0.5) * 220 - ox; dy = cy + (rng.next() - 0.5) * 180 - oy; dz = cz + (rng.next() - 0.5) * 220 - oz;
        const l = 1 / Math.hypot(dx, dy, dz);
        dx *= l; dy *= l; dz *= l;
        if (track(vol, ox, oy, oz, dx, dy, dz, rng)) { px = hit[0]; py = hit[1]; pz = hit[2]; break; }
      }
      vol.descriptor(px, py, pz, sx, sy, sz, dx, dy, dz, X, (o + i) * IN);
      estimate(vol, sun, sx, sy, sz, px, py, pz, dx, dy, dz, paths, rng);
      Y.set(est, (o + i) * OUT);
    }
  }
}

export interface Trained {
  /** 640 floats in the shader's 160-vec4 layout. */
  packed: Float32Array;
  /** Mean brightness ratio and correlation of each head on samples [from, to) of a labelled set. */
  score(X: Float32Array, Y: Float32Array, from: number, to: number): { ratio: number; correlation: number }[];
}

/** Fits the network to the first n samples with Adam on plain squared error of the raw labels. */
export function train(X: Float32Array, Y: Float32Array, n: number, epochs: number, seed = 1): Trained {
  const mean = new Float64Array(IN), inv = new Float64Array(IN), wOut = new Float64Array(OUT), clamp = new Float64Array(OUT);
  const th = new Float64Array(P), g = new Float64Array(P), m1 = new Float64Array(P), m2 = new Float64Array(P), rng = new Rng(seed);
  for (let q = 0; q < P; q++) th[q] = (rng.next() * 2 - 1) * 0.25;
  for (let j = 0; j < H; j++) th[B0 + j] = th[B1 + j] = 0.3;
  for (let m = 0; m < IN; m++) {
    let s = 0, s2 = 0;
    for (let i = 0; i < n; i++) { s += X[i * IN + m]; s2 += X[i * IN + m] ** 2; }
    mean[m] = s / n; inv[m] = 1 / Math.max(1e-4, Math.sqrt(Math.max(0, s2 / n - mean[m] ** 2)));
  }
  for (let k = 0; k < OUT; k++) {
    let s = 0, s2 = 0, mx = 0;
    for (let i = 0; i < n; i++) { const y = Y[i * OUT + k]; s += y; s2 += y * y; mx = Math.max(mx, y); }
    wOut[k] = 1 / Math.max(1e-6, s2 / n - (s / n) ** 2); // only balances the three heads
    clamp[k] = mx * 1.25;
    th[B2 + k] = Math.sqrt(Math.max(1e-4, s / n)); // start alive, not at zero
  }
  const x = new Float64Array(IN), r0 = new Float64Array(H), h0 = new Float64Array(H), r1 = new Float64Array(H), h1 = new Float64Array(H);
  const s3 = new Float64Array(OUT), dz0 = new Float64Array(H), dz1 = new Float64Array(H);
  const forward = (src: Float32Array, i: number): void => {
    for (let m = 0; m < IN; m++) x[m] = (src[i * IN + m] - mean[m]) * inv[m];
    for (let j = 0; j < H; j++) { let z = th[B0 + j]; for (let m = 0; m < IN; m++) z += th[W0 + j * IN + m] * x[m]; r0[j] = Math.max(z, 0); h0[j] = r0[j] * r0[j]; }
    for (let j = 0; j < H; j++) { let z = th[B1 + j]; for (let a = 0; a < H; a++) z += th[W1 + j * H + a] * h0[a]; r1[j] = Math.max(z, 0); h1[j] = r1[j] * r1[j]; }
    for (let k = 0; k < OUT; k++) { let z = th[B2 + k]; for (let a = 0; a < H; a++) z += th[W2 + k * H + a] * h1[a]; s3[k] = z; }
  };
  const batch = 256, steps = Math.max(1, Math.floor(epochs * n / batch));
  for (let step = 1; step <= steps; step++) {
    g.fill(0);
    for (let b = 0; b < batch; b++) {
      const i = Math.min(n - 1, Math.floor(rng.next() * n));
      forward(X, i); dz1.fill(0); dz0.fill(0);
      for (let k = 0; k < OUT; k++) {
        // L = w (s^2 - y)^2 on the RAW label, so dL/ds = 4 w (s^2 - y) s. Never fit a transformed label.
        const ds = 4 * wOut[k] * (s3[k] * s3[k] - Y[i * OUT + k]) * s3[k];
        g[B2 + k] += ds;
        for (let a = 0; a < H; a++) { g[W2 + k * H + a] += ds * h1[a]; dz1[a] += ds * th[W2 + k * H + a]; }
      }
      for (let j = 0; j < H; j++) {
        const dz = dz1[j] * 2 * r1[j];
        g[B1 + j] += dz;
        for (let a = 0; a < H; a++) { g[W1 + j * H + a] += dz * h0[a]; dz0[a] += dz * th[W1 + j * H + a]; }
      }
      for (let j = 0; j < H; j++) {
        const dz = dz0[j] * 2 * r0[j];
        g[B0 + j] += dz;
        for (let m = 0; m < IN; m++) g[W0 + j * IN + m] += dz * x[m];
      }
    }
    let norm = 0;
    for (let q = 0; q < P; q++) { g[q] /= batch; norm += g[q] * g[q]; }
    const clip = Math.min(1, 1 / Math.max(1e-8, Math.sqrt(norm))), lr = 1e-5 + 1e-3 * (1 + Math.cos(Math.PI * step / steps));
    const c1 = 1 - Math.pow(0.9, step), c2 = 1 - Math.pow(0.999, step);
    for (let q = 0; q < P; q++) {
      const gq = g[q] * clip;
      m1[q] = 0.9 * m1[q] + 0.1 * gq; m2[q] = 0.999 * m2[q] + 0.001 * gq * gq;
      th[q] -= lr * (m1[q] / c1) / (Math.sqrt(m2[q] / c2) + 1e-8);
    }
  }
  // W0 rows at vec4 0-63, W1 64-127, W2 128-139, b0 140-143, b1 144-147, b2 148, mean 149-152, 1/std 153-156, clamp 157, sentinel 159.x
  const packed = new Float32Array(640);
  packed.set(th.subarray(W0, B0), 0); packed.set(th.subarray(W1, B1), 256); packed.set(th.subarray(W2, B2), 512);
  packed.set(th.subarray(B0, W1), 560); packed.set(th.subarray(B1, W2), 576); packed.set(th.subarray(B2, P), 592);
  packed.set(mean, 596); packed.set(inv, 612); packed.set(clamp, 628);
  packed[636] = 1234.5;
  return {
    packed,
    score(Xs, Ys, from, to) {
      return [0, 1, 2].map((k) => {
        let sp = 0, st = 0, spp = 0, stt = 0, spt = 0;
        const c = to - from;
        for (let i = from; i < to; i++) {
          forward(Xs, i);
          const p = Math.min(s3[k] * s3[k], clamp[k]), y = Ys[i * OUT + k];
          sp += p; st += y; spp += p * p; stt += y * y; spt += p * y;
        }
        const cov = spt / c - (sp / c) * (st / c), vp = spp / c - (sp / c) ** 2, vt = stt / c - (st / c) ** 2;
        return { ratio: sp / st, correlation: cov / Math.sqrt(Math.max(1e-12, vp * vt)) };
      });
    },
  };
}

Retraining, in any JS runtime (under a minute per cloud for the labels, about 20 s for the fit, on one thread):

const shapes = 12, per = 20000, X = new Float32Array(shapes * per * 16), Y = new Float32Array(shapes * per * 3);
for (let s = 0; s < shapes; s++) {
  const vol = new CloudVolume(128, 3, [-192, 0, -192], s === 0 ? DEFAULT_SHAPE : randomShape(s));
  makeSamples(vol, per, 12, 128, 1000 + s, X, Y, s * per);
}
const net = train(X, Y, shapes * per, 40); // shuffle first to hold some samples out
const weights = Array.from(net.packed);   // the contents of NEURAL_CLOUD_WEIGHTS

Traps

  • Descriptor mismatch is silent. CloudVolume.descriptor and shade() must read the same numbers: same levels, radii, zero-outside-box rule and signs. Changing one side means retraining.
  • The medium is baked in. Extinction 0.25 per metre, g 0.85 and albedo 0.999 are not inputs; other values need new weights. Other *shapes* are fine: the unseen-cloud column above used these weights.
  • Never transform the label. Labels are Monte Carlo estimates; fitting a root or log of noisy values biases the mean (Grassi lost half the light this way). The trainer fits raw values.
  • ReLU draws seams. A piecewise-flat network marched through shows shell-shaped creases; squared ReLU does not. Leaky ReLU does not help.
  • Sky and ground labels are coin flips (a path escapes up or it does not). Few paths per sample hide half the signal while mean brightness still looks right; judge by correlation and use 64 or more paths.
  • Sample like a camera. Points where a ray first collides, not uniform through the interior nobody sees.
  • Tone map un-premultiplied. Tone mapping a premultiplied colour leaves a bright halo on soft edges; both shaders divide by alpha first.
  • Always upload all 160 vectors. The shader falls back to the classic model when the sentinel is missing.
  • Far plane. The kit camera's 600 m far plane clips the box's back faces; raise it.
  • Volume build is about 0.7 s of main-thread JavaScript at 128 voxels; it happens once in createNeuralCloud.

Budgets

  • Per lit step: 15 half-float 3D reads (density, skip level, 13 descriptor reads) and about 600 multiply-adds, as 4-wide dot products. The descriptor reads do not depend on each other.
  • 160 uniform vectors for the weights; the GLES 3.0 minimum for fragment shaders is 224.
  • Memory: about 4.8 MB of R16F 3D textures at 128 voxels (64 voxels at 6 m: 0.6 MB).
  • Resolution: scale 0.5 on high-density displays and 0.7 otherwise holds up because clouds are soft. uStepScale 1.5 to 2 trades banding for speed.
  • Software renderers (headless captures): the demo's five capture views render in under a minute in total at scale 0.75.

Limits

One cloud in one axis-aligned box, no depth test against scene geometry (add a scene-depth clamp on tFar for that), a two-band sky (above and below the horizon), sun elevation of 3 degrees and up in training. Looking into the sun is the hardest case for the sun head; computing the first bounce analytically and training on the remainder is the known remedy.

Verification Checklist

  1. Unit tests: the weight checksums, the default cloud's total density and one golden descriptor all match, so the volume code and weights are the trained ones.
  2. setMode('split'): the neural half is clearly brighter and whiter than the classic half at every sun angle.
  3. Sweep the sun through 0, 90 and 180 degrees; neural brightness stays steady instead of collapsing.
  4. No bright halo on the silhouette, no banding (the march start is dithered), no creases.
  5. Zero the weights: the cloud falls back to the classic look rather than white or black.

Official references

  • Charles Grassi (2026) — Neural Shaders, Explained With Clouds
  • Simon Kallweit et al. (SIGGRAPH Asia 2017) — Deep Scattering: Rendering Atmospheric Clouds with Radiance-Predicting Neural Networks
  • Magnus Wrenninge, Chris Kulla, Viktor Lundqvist (SIGGRAPH 2013) — Oz: The Great and Volumetric
  • Jan Novák et al. (Eurographics 2018 STAR) — Monte Carlo Methods for Volumetric Light Transport Simulation

Open-source sources

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.

Who made it

This guide is by @maddmann.

More Three.js games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.

More Three.js techniques

physics

Voronoi Mesh Shattering, FABRIK Inverse Kinematics & XPBD Verlet Ropes in Three.js →

Zero-dependency Three.js r183 procedural motion and destruction toolkit combining Voronoi-jittered breakable box shards, multi-bone FABRIK inverse kinematics, and unconditionally stable fixed-step XPBD Verlet ropes and capes.

atmosphere

Baked 3D Volumetric Cloud Sea, World-Anchored Marching & TAA in Three.js →

Endless fly-above volumetric cloud sea in Three.js r183 WebGL 2 using a GPU-baked WebGL3DRenderTarget SDF and lighting volume, anti-boiling world-anchored z-plane marching, 3-octave Henyey-Greenstein scattering, and variance-clamped depth-packed TAA.

atmosphere

Physical Night Sky, Phase-Accurate Moon, Starfield & God Rays in Three.js →

Physically grounded WebGL 2 night sky dome in Three.js r183 featuring Lommel-Seeliger lunar shading, analytic 1D-integrated phase-shaped moon halo, Kasten-Young air-mass extinction, boundary-free 2x2x2-cell twinkling stars, great-circle meteors, and phase-aware radial light shafts.

gameplay

Multiplayer Room State Sync & 60 Hz Avatars in Three.js →

Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP