# 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.

- **Canonical page:** https://gamecrew.ai/techniques/three/baked-volumetric-cloud-sea-taa
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** atmosphere
- **Tags:** `clouds`, `volumetric`, `raymarching`, `taa`, `temporal`, `3d-texture`, `baking`, `sdf`, `anti-boiling`, `flight`, `atmosphere`, `webgl2`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-13)
- **Demo:** No demo

## When to Use & Core Rules

Use `volumetric-clouds-sky-shaders` for ground sky slabs; use **this** for fly-above cumulus/cumulonimbus seas:
1. **Direct GPU 3D bake (`WebGL3DRenderTarget`)**: Bake `R`=light optical depth, `G`=sky AO, `B`=macro SDF, `A`=downward gap openness into slices via `setRenderTarget(bakeRT, slice)` (zero `readRenderTargetPixels` stall).
2. **World-anchored Z-planes**: Snap samples to world `z` planes doubling at `5,10,20,40,80,160` and cross-fade odd/even weights across each band's far half to eliminate boiling.
3. **Safe SDF skip + `textureLod`**: Skip `min(-sd*0.2, 2.0)`, refine `2x` near surfaces, call `textureLod(...,0.0)` inside loops, and normalize 3D Perlin-Worley channels to `[0.5%, 99.5%]`.
4. **Depth-packed TAA + sky overlay**: Pack `floor(depth*32)+T*0.999` in `FloatType` alpha, clamp history to `3x3` `m1+/-1.7*sig`, keep `carry` across resizes, and pass `compositeOverSky: true` to blend (`OneFactor`/`SrcAlphaFactor`) over `createNightSky`.

## Math

- **Toroidal tile (`TILE=320`)**: Integer cycles `k/TILE`; 2nd billow rotates `(2x+z, 2y, 2z-x)`.
- **Band-blended planes**: $\Delta z(d_z)=0.06\cdot 2^{\max(0,\lfloor\log_2(d_z/5)\rfloor+1)}$, $w=\Delta t(1\mp f)$, $f=\mathrm{smoothstep}(0.5,1,\mathrm{fract}(\log_2(d_z/5)+1))$.
- **3-octave scattering**: 2 local light steps + far bake (`55..80`), extinction `(1.0, 0.40, 0.17)`, dual-lobe HG `(0.80/-0.22, 0.42/-0.11, 0.20/-0.05)`.

## Engine Implementation (`Assets/Game/cloudSea.ts`)

```ts
import * as THREE from 'three';
import type { Game } from 'ccgd';

export interface CloudSeaOptions {
  lightDirection?: THREE.Vector3;
  scale?: number;
  bakeSize?: number;
  bakeSlices?: number;
  noiseSize?: number;
  underglowStrength?: number;
  compositeOverSky?: boolean;
}
export interface CloudSeaController {
  mesh: THREE.Mesh;
  bakeTexture: THREE.Data3DTexture;
  cloudUniforms: Record<string, THREE.IUniform>;
  setLightDirection(dir: THREE.Vector3): void;
  setResolutionScale(scale: number): void;
  dispose(): void;
}

const QUAD_VERT = `varying vec2 vUv;void main(){vUv=uv;gl_Position=vec4(position.xy,0.,1.);}`;
const SHARED = `const float TILE=320.,Y_MIN=-8.5,Y_MAX=52.,C_BASE=-1.75,F_BIL=26./TILE,F_DET=42./TILE;
float densL(float sd){return clamp((sd+.1)*1.3,0.,1.);}`;

const BAKE_FRAG = /* glsl */ `
precision highp float;precision highp sampler3D;
uniform sampler3D uNoise;uniform vec3 uLightDir;uniform float uSliceY;uniform int uShadowSteps;
varying vec2 vUv;${SHARED}
const float CELL=TILE/13.,CB=TILE/3.;const vec2 WIND=vec2(.8,-.6);
float h12(vec2 p){vec3 q=fract(p.xyx*.1031);q+=dot(q,q.yzx+33.33);return fract((q.x+q.y)*q.z);}
vec4 h42(vec2 p){vec4 q=fract(p.xyxy*vec4(.1031,.1030,.0973,.1099));q+=dot(q,q.wzxy+33.33);return fract((q.xxyz+q.yzzw)*q.zywx);}
float pd(float a){return abs(mod(a+.5*TILE,TILE)-.5*TILE);}
float pX(float z){return 4.5*sin(z*.019635)+1.6*sin(z*.03927+1.3);}
float smax(float a,float b,float k){float h=clamp(.5+.5*(a-b)/k,0.,1.);return mix(b,a,h)+k*h*(1.-h);}
vec4 N3(vec3 p){return textureLod(uNoise,p,0.);}
float seaSD(vec3 p,float bil){
  float a=N3(vec3(p.xz*3./TILE,.137)).b,b=N3(vec3(p.zx*11./TILE+.31,.583)).b;
  float h=mix(-4.2,-1.05+a*1.75+b*.85,smoothstep(.43,.57,.6*N3(vec3(p.xz*2./TILE+.21,.713)).b+.4*a+(b-.5)*.24));
  float off=mix(-5.2,4.6,smoothstep(.16,.84,N3(vec3(p.xz*2./TILE+.47,.391)).b))+(N3(vec3(p.zx*6./TILE+.13,.857)).b-.5)*2.8;
  float al=mix(-1.2,5.5,smoothstep(6.,20.,pd(p.x-pX(p.z)))),t=clamp(.5+.5*(al-off)/1.4,0.,1.);
  off=mix(al,off,t)-1.4*t*(1.-t);return min(h+off+(bil-.5)*2.-p.y,p.y-(C_BASE+off*.8-(bil-.5)*.9));
}
float billow(vec3 p){vec3 q=p*F_BIL;return .64*N3(q).r+.36*N3(vec3(2.*q.x+q.z,2.*q.y,2.*q.z-q.x)+.37).r;}
float lobes(vec3 p){return .62*N3(p*9./TILE+vec3(.53,.11,.29)).r+.38*N3(p*18./TILE+vec3(.17,.71,.41)).r;}
float cumulus(vec3 p,float bil,float lob){
  vec2 i0=floor(p.xz/CELL-.5);float best=-8.;
  for(int j=0;j<2;j++)for(int i=0;i<2;i++){
    vec2 id=i0+vec2(float(i),float(j)),w=mod(id,13.);vec4 h=h42(w+31.7);if(h.x<.38)continue;
    vec2 c=(id+.2+.6*h.yz)*CELL;float Rb=2.8+3.*h.w,H=Rb*(.5+1.3*h12(w*1.37+7.1));
    if(pd(c.x-pX(c.y))<Rb*2.+3.)continue;vec2 dc=p.xz-c;float rc=Rb*2.3+3.;
    if(dot(dc,dc)>rc*rc||p.y>H+Rb+2.)continue;float cl=-1e3;
    for(int k=0;k<6;k++){
      vec4 hk=h42(w*3.7+float(k)*11.3+5.1);float tk=float(k)/5.,rk=Rb*mix(1.,.5,tk)*(.75+.5*hk.x);
      vec2 cx=c+vec2(cos(hk.y*6.283),sin(hk.y*6.283))*Rb*.75*(1.-.6*tk)*sqrt(hk.z)+WIND*tk*Rb*.4;
      vec3 d=p-vec3(cx.x,-.5+tk*H+rk*.2,cx.y);d.y*=1.15;cl=smax(cl,rk-length(d),rk*.45);
    }
    best=max(best,min(cl,p.y-(C_BASE-.4))+(lob-.5)*Rb*.7+(bil-.5)*(2.4+.2*Rb));
  }
  return best;
}
float anvil(vec3 p,float bil,float lob){
  vec2 i0=floor(p.xz/CB-.5);float best=-40.;
  for(int j=0;j<2;j++)for(int i=0;i<2;i++){
    vec2 id=i0+vec2(float(i),float(j)),w=mod(id,3.);vec4 h=h42(w*7.31+113.7);if(h.x<.55)continue;
    vec2 c=(id+.3+.4*h.yz)*CB;float R0=9.+6.*h.w;if(pd(c.x-pX(c.y))<R0*2.2+9.)continue;
    float h2=h12(w*3.17+41.3),H=16.+30.*h2*h2,A=4.+4.*fract(h2*7.13),Ra=R0*(1.6+.8*fract(h2*13.7));
    float tt=clamp((p.y-C_BASE)/(H-C_BASE),0.,1.),an=smoothstep(H-A-4.,H-A+1.,p.y)*smoothstep(24.,34.,H);
    vec2 col=c+WIND*tt*tt*R0*.7,ctr=mix(col,c+WIND*(Ra-R0)*.6,an);
    float rad=mix(R0*(.9+.3*tt+.15*exp(-tt*7.)),Ra*(.8+.4*lob),an);
    float sd=max(min(rad-length(p.xz-ctr),H-p.y),R0*.85-length(vec3(p.x-col.x,(p.y-(H+.5))*1.6,p.z-col.y)));
    best=max(best,min(sd,p.y-(C_BASE-1.))+(lob-.5)*2.*mix(R0*.55,1.2,an)+(bil-.5)*(4.-2.6*an));
  }
  return best;
}
float sceneSD(vec3 p,bool full){float bil=billow(p),lob=lobes(p);return smax(smax((!full&&p.y>8.2)?min(8.2-p.y,-.4):seaSD(p,bil),cumulus(p,bil,lob),.9),anvil(p,bil,lob),1.2);}
void main(){
  vec3 p=vec3(vUv.x*TILE,mix(Y_MIN,Y_MAX,uSliceY),vUv.y*TILE);float od=0.,ds=.18,tt=0.;
  for(int i=0;i<96;i++){if(i>=uShadowSteps)break;vec3 q=p+uLightDir*(tt+ds*.5);if(q.y>Y_MAX)break;od+=densL(sceneSD(q,false))*ds*exp(-tt*.02);tt+=ds;ds=min(ds*1.09,3.5);}
  float up=0.,dn=0.;ds=.35;tt=0.;
  for(int i=0;i<12;i++){up+=densL(sceneSD(p+vec3(0.,tt+ds*.5,0.),false))*ds;vec3 qd=p-vec3(0.,tt+ds*.5,0.);if(qd.y>=Y_MIN)dn+=densL(sceneSD(qd,false))*ds;tt+=ds;ds*=1.18;}
  gl_FragColor=vec4(1.-exp(-od*.25),1.-exp(-up*.4),clamp((sceneSD(p,true)+10.)/16.,0.,1.),exp(-dn*1.2));
}
`;

const CLOUD_FRAG = /* glsl */ `
precision highp float;precision highp sampler3D;
uniform sampler3D uNoise,uBake;
uniform vec3 uCamPos,uCamR,uCamU,uCamF,uLightDir,uLightTint,uSkyHorizon,uSkyZenith,uUnderglowCol;
uniform float uTanHalf,uAspect,uFrame,uUnderglow,uPackDepth;uniform int uMaxSteps;
varying vec2 vUv;${SHARED}
float ign(vec2 p){return fract(52.9829189*fract(dot(p,vec2(.06711056,.00583715))));}
float bSD(vec3 p){float w=(p.y-Y_MIN)/(Y_MAX-Y_MIN);return w>=1.?-4.-(p.y-Y_MAX):w<0.?-6.:textureLod(uBake,vec3(p.x/TILE,p.z/TILE,w),0.).b*16.-10.;}
float shapeSD(vec3 p){float sd=bSD(p);if(sd<-1.2)return sd+.6;vec3 q=p*F_BIL;return sd+(textureLod(uNoise,vec3(2.*q.x+q.z,2.*q.y,2.*q.z-q.x)+.37,0.).r-.5)*.9;}
vec3 bL(vec3 p){vec4 b=textureLod(uBake,vec3(p.x/TILE,p.z/TILE,clamp((p.y-Y_MIN)/(Y_MAX-Y_MIN),0.,1.)),0.);return vec3(-log(max(1.-b.r,2e-3))*4.,-log(max(1.-b.g,2e-3))*2.5,b.a);}
vec3 lightAt(vec3 p,float t){
  float f=smoothstep(55.,80.,t);vec3 farL=f>0.?bL(p+uLightDir*.3):vec3(0.);if(f>=1.)return farL;
  float od=densL(shapeSD(p+uLightDir*.15))*.3+densL(shapeSD(p+uLightDir*.45))*.3;vec3 b=bL(p+uLightDir*.6);return mix(vec3(od+b.x,b.yz),farL,f);
}
float pSp(float dz){return .06*exp2(max(0.,floor(log2(max(dz,1e-3)/5.))+1.));}
float nSp(float roz,float rz,float t,float sp){float zp=roz-t*rz,zn=(ceil(zp/sp)-1.)*sp;if(zn>zp-1e-4)zn-=sp;return(roz-zn)/rz;}
float nT(float roz,float rz,float t,float sp,float spB,bool r){float tn=nSp(roz,rz,t,sp);return tn*rz>=spB*(5./.06)?nSp(roz,rz,t,r?spB:2.*spB):tn;}
float hg(float c,float g){float g2=g*g;return(1.-g2)/(12.56637*pow(max(1e-3,1.+g2-2.*g*c),1.5));}
void main(){
  vec2 ndc=vUv*2.-1.;vec3 rd=normalize(uCamF+uCamR*ndc.x*uTanHalf*uAspect+uCamU*ndc.y*uTanHalf),ro=uCamPos;
  float tFar=mix(200.,320.,smoothstep(-.05,-.02,rd.y)),tMax=tFar;
  if(rd.y>.001)tMax=min(tMax,max(0.,(Y_MAX-ro.y)/rd.y));else if(rd.y<-.001)tMax=min(tMax,max(0.,(Y_MIN-ro.y)/rd.y));
  float cT=dot(rd,uLightDir),ph0=mix(hg(cT,-.22),hg(cT,.80),.7),ph1=mix(hg(cT,-.11),hg(cT,.42),.7),ph2=mix(hg(cT,-.05),hg(cT,.20),.7);
  float back=smoothstep(.35,.97,cT),jit=ign(gl_FragCoord.xy+mod(uFrame,64.)*5.588238),rz=-rd.z;bool pl=rz>.25;
  vec3 fogC=mix(uSkyHorizon,uSkyZenith,smoothstep(-.02,.4,rd.y)),lCol=mix(vec3(.74,.84,1.),vec3(1.,.88,.70),smoothstep(.55,.985,cT))*uLightTint;
  float t=pl?nSp(ro.z,rz,.05,pSp(.05*rz)):.05+jit*.22,T=1.,dS=0.,wS=0.;vec3 S=vec3(0.);
  for(int i=0;i<200;i++){
    if(i>=uMaxSteps||t>tMax||T<.015)break;vec3 p=ro+rd*t;float sd=shapeSD(p),spB=pl?pSp(t*rz):0.;
    bool ref=pl&&spB>.13&&sd>-1.5*spB;float sp=ref?spB*.5:spB,dt=pl?sp/rz:.12+t*.02,dtW=dt;
    if(pl){float lam=log2(max(t*rz,1e-3)/5.)+1.,f=lam>0.?smoothstep(.5,1.,fract(lam)):0.;dtW=dt*(mod(floor((ro.z-t*rz)/sp+.5),2.)>.5?1.-f:1.+f);}
    if(sd<-.32){
      float sk=min(-sd*.2,2.);
      if(!pl)t+=max(dt,sk);else if(sk<=dt)t=nT(ro.z,rz,t,sp,spB,ref);
      else{float ts=t+sk,spL=ts*rz>=spB*(5./.06)?2.*spB:spB;t=nSp(ro.z,rz,ts-1e-3,ref?.5*spL:spL);}
      continue;
    }
    float d=0.;
    if(sd>-.3){
      float er=(1.-textureLod(uNoise,p*F_DET,0.).g)*.36*smoothstep(170.,100.,t);
      d=clamp((sd+.14-er*(1.-clamp(sd*.4,0.,.7)))*(2./max(1.,.048*t*max(rz,.25))),0.,1.)*(1.-smoothstep(tFar-45.,tFar-4.,t));
    }
    if(d>.004){
      vec3 lt=lightAt(p,t);float od=lt.x,e=ph0*exp(-od*4.)+.34*ph1*exp(-od*1.6)+.14*ph2*exp(-od*.68);
      float pf=mix(mix(.42,1.,1.-exp(-max(sd,0.)*2.6-d*.5)),1.,back),occ=exp(-max(sd,0.)*.5)*mix(.15,1.,exp(-lt.y*.5));
      vec3 amb=mix(uSkyHorizon*.4,uSkyZenith*1.4+vec3(.03,.045,.09),sqrt(clamp((p.y+6.)/15.,0.,1.)))*(.28+.72*occ),L=lCol*(3.*e*pf)+amb;
      if(uUnderglow>0.)L+=uUnderglowCol*(uUnderglow*.08*lt.z*lt.z*exp(-max(p.y-(C_BASE-1.),0.)/2.5));
      L=mix(L,mix(uSkyHorizon,fogC,smoothstep(100.,250.,t)),1.-exp(-t*.014*mix(1.,.3,smoothstep(4.,30.,p.y))));
      float tr=exp(-d*4.*dtW),w=T*(1.-tr);S+=w*L;dS+=w*t;wS+=w;T*=tr;
    }
    t=pl?nT(ro.z,rz,t,sp,spB,ref):t+dt*(.85+.3*fract(jit+float(i)*.754878));
  }
  float far=smoothstep(-.002,-.03,rd.y);vec3 farC=mix(fogC*vec3(.4,.44,.52),fogC*.8,smoothstep(-.05,-.002,rd.y));
  S+=T*farC*far;dS+=T*far*250.;wS+=T*far;T*=1.-far;
  float dp=wS>.02?dS/wS:250.;gl_FragColor=vec4(S,uPackDepth>.5?floor(clamp(dp,0.,250.)*32.)+clamp(T,0.,1.)*.999:T);
}
`;

const TAA_FRAG = /* glsl */ `
precision highp float;uniform sampler2D tCur,tHist;uniform vec2 uSize;
uniform vec3 uCamPos,uCamR,uCamU,uCamF,uPrevPos,uPrevR,uPrevU,uPrevF;
uniform float uTanHalf,uAspect,uPrevTanHalf,uPrevAspect,uReset;varying vec2 vUv;
vec4 unpack(vec4 c,out float d){float q=floor(c.a);d=q/32.;return vec4(c.rgb,(c.a-q)/.999);}
void main(){
  ivec2 ip=ivec2(gl_FragCoord.xy),mx=ivec2(uSize)-1;vec4 m1=vec4(0.),m2=vec4(0.),cur=vec4(0.);float dM=1e9;
  for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++){float d;vec4 c=unpack(texelFetch(tCur,clamp(ip+ivec2(i,j),ivec2(0),mx),0),d);if(i==0&&j==0)cur=c;dM=min(dM,d);m1+=c;m2+=c*c;}
  m1/=9.;m2/=9.;vec4 sig=sqrt(max(m2-m1*m1,0.));vec2 uv=(vec2(ip)+.5)/uSize,ndc=uv*2.-1.;
  vec3 rd=normalize(uCamF+uCamR*ndc.x*uTanHalf*uAspect+uCamU*ndc.y*uTanHalf),v=dM>240.?rd:(uCamPos+rd*dM-uPrevPos);
  float z=dot(v,uPrevF);vec4 o=cur;
  if(uReset<.5&&z>1e-4){
    vec2 pu=.5+.5*vec2(dot(v,uPrevR)/(z*uPrevTanHalf*uPrevAspect),dot(v,uPrevU)/(z*uPrevTanHalf));
    if(pu.x>=0.&&pu.y>=0.&&pu.x<=1.&&pu.y<=1.)o=mix(clamp(texture2D(tHist,pu),m1-1.7*sig,m1+1.7*sig),cur,mix(.06,.18,clamp(length((pu-uv)*uSize)/8.,0.,1.)));
  }
  gl_FragColor=max(o,vec4(0.));
}
`;

const DISPLAY_VERT = `varying vec3 vW;varying vec4 vC;void main(){vW=position;vC=projectionMatrix*modelViewMatrix*vec4(position,1.);gl_Position=vC;}`;
const DISPLAY_FRAG = `precision highp float;uniform sampler2D tCloud;uniform vec3 uSkyHorizon,uSkyZenith;uniform float uOverlay;varying vec3 vW;varying vec4 vC;
void main(){vec4 c=texture2D(tCloud,clamp(vC.xy/max(vC.w,1e-4)*.5+.5,vec2(0.),vec2(1.)));
gl_FragColor=uOverlay>.5?vec4(c.rgb,c.a):vec4(c.rgb+mix(uSkyHorizon,uSkyZenith,smoothstep(-.02,.45,normalize(vW).y))*c.a,1.);
#include <colorspace_fragment>
}`;

function buildNoise3D(N: number): THREE.Data3DTexture {
  const H = (x: number, y: number, z: number, s: number) => {
    let n = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(z, 2147483647) + Math.imul(s, 1274126177);
    n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967296;
  };
  const mod = (n: number, p: number) => ((n % p) + p) % p, L = (a: number, b: number, t: number) => a + (b - a) * t;
  const vn = (x: number, y: number, z: number, p: number, s: number) => {
    const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z), fx = x - xi, fy = y - yi, fz = z - zi;
    const u = fx * fx * (3 - 2 * fx), v = fy * fy * (3 - 2 * fy), w = fz * fz * (3 - 2 * fz);
    const x0 = mod(xi, p), y0 = mod(yi, p), z0 = mod(zi, p), x1 = (x0 + 1) % p, y1 = (y0 + 1) % p, z1 = (z0 + 1) % p;
    const xy = (zk: number) => L(L(H(x0, y0, zk, s), H(x1, y0, zk, s), u), L(H(x0, y1, zk, s), H(x1, y1, zk, s), u), v);
    return L(xy(z0), xy(z1), w);
  };
  const wo = (x: number, y: number, z: number, p: number) => {
    const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z); let md = 1e9;
    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, wx = mod(cx, p), wy = mod(cy, p), wz = mod(cz, p);
      md = Math.min(md, (cx + H(wx, wy, wz, 1) - x) ** 2 + (cy + H(wx, wy, wz, 2) - y) ** 2 + (cz + H(wx, wy, wz, 3) - z) ** 2);
    }
    return Math.min(Math.sqrt(md), 1);
  };
  const T = N * N * N, R = new Float32Array(T), G = new Float32Array(T), B = new Float32Array(T);
  for (let iz = 0, i = 0; iz < N; iz++) for (let iy = 0; iy < N; iy++) for (let ix = 0; ix < N; ix++, i++) {
    const x = (ix + 0.5) / N, y = (iy + 0.5) / N, z = (iz + 0.5) / N;
    const p = (vn(x * 4, y * 4, z * 4, 4, 7) + 0.5 * vn(x * 8, y * 8, z * 8, 8, 19)) / 1.5;
    const w4 = 1 - wo(x * 4, y * 4, z * 4, 4), w8 = 1 - wo(x * 8, y * 8, z * 8, 8), w16 = 1 - wo(x * 16, y * 16, z * 16, 16);
    R[i] = 0.6 * (0.65 * w4 + 0.35 * w8) + 0.4 * p; G[i] = 0.6 * w8 + 0.4 * w16; B[i] = vn(x * 2, y * 2, z * 2, 2, 3) + 0.5 * p;
  }
  const rng = (a: Float32Array) => { const s = Float32Array.from(a).sort(); return [s[Math.floor(T * 0.005)], s[Math.floor(T * 0.995)]]; };
  const rr = rng(R), gr = rng(G), br = rng(B), data = new Uint8Array(T * 4);
  const q = (v: number, r: number[]) => THREE.MathUtils.clamp(Math.round(((v - r[0]) / Math.max(1e-4, r[1] - r[0])) * 255), 0, 255);
  for (let i = 0; i < T; i++) data.set([q(R[i], rr), q(G[i], gr), q(B[i], br), 255], i * 4);
  const tex = new THREE.Data3DTexture(data, N, N, N);
  tex.minFilter = tex.magFilter = THREE.LinearFilter; tex.wrapS = tex.wrapT = tex.wrapR = THREE.RepeatWrapping;
  tex.generateMipmaps = false; tex.unpackAlignment = 1; tex.needsUpdate = true;
  return tex;
}

const U = (v: unknown): THREE.IUniform => ({ value: v });
function makePass(fragmentShader: string, uniforms: Record<string, THREE.IUniform>, quadGeo: THREE.PlaneGeometry) {
  const material = new THREE.ShaderMaterial({ vertexShader: QUAD_VERT, fragmentShader, uniforms, depthTest: false, depthWrite: false });
  const scene = new THREE.Scene(), quad = new THREE.Mesh(quadGeo, material); quad.frustumCulled = false; scene.add(quad);
  return { material, scene, uniforms };
}
const makeRT = (w: number, h: number, type: THREE.TextureDataType, filter: THREE.MagnificationTextureFilter) =>
  new THREE.WebGLRenderTarget(w, h, { type, format: THREE.RGBAFormat, minFilter: filter, magFilter: filter, depthBuffer: false, stencilBuffer: false, generateMipmaps: false });

export function createBakedCloudSea(game: Game, opts: CloudSeaOptions = {}): CloudSeaController {
  const ren = game.renderer, useTaa = !game.headless && ren.extensions.has('EXT_color_buffer_float');
  const rtType = ren.extensions.has('EXT_color_buffer_float') || ren.extensions.has('EXT_color_buffer_half_float') ? THREE.HalfFloatType : THREE.UnsignedByteType;
  const bN = opts.bakeSize ?? (game.headless ? 32 : 128), bZ = opts.bakeSlices ?? (game.headless ? 16 : 48);
  const noiseTex = buildNoise3D(opts.noiseSize ?? (game.headless ? 16 : 64));
  const bakeRT = new THREE.WebGL3DRenderTarget(bN, bN, bZ, {
    type: THREE.UnsignedByteType, format: THREE.RGBAFormat, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, depthBuffer: false, stencilBuffer: false, generateMipmaps: false,
  });
  bakeRT.texture.wrapS = bakeRT.texture.wrapT = THREE.RepeatWrapping; bakeRT.texture.wrapR = THREE.ClampToEdgeWrapping;

  const quadGeo = new THREE.PlaneGeometry(2, 2), quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  const lightDir = (opts.lightDirection ?? new THREE.Vector3(-0.25, 0.21, -0.94)).clone().normalize();
  const bakePass = makePass(BAKE_FRAG, { uNoise: U(noiseTex), uLightDir: U(lightDir), uSliceY: U(0), uShadowSteps: U(game.headless ? 16 : 64) }, quadGeo);
  const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
  const camP = v3(), camR = v3(1, 0, 0), camU = v3(0, 1, 0), camF = v3(0, 0, -1);
  const prevP = v3(), prevR = v3(1, 0, 0), prevU = v3(0, 1, 0), prevF = v3(0, 0, -1);
  const cloudUniforms: Record<string, THREE.IUniform> = {
    uNoise: U(noiseTex), uBake: U(bakeRT.texture), uLightDir: U(lightDir),
    uCamPos: U(camP), uCamR: U(camR), uCamU: U(camU), uCamF: U(camF),
    uLightTint: U(new THREE.Color(0xdce8ff)), uSkyHorizon: U(new THREE.Color(0x0b162d)), uSkyZenith: U(new THREE.Color(0x020612)), uUnderglowCol: U(new THREE.Color(0xff4c0d)),
    uTanHalf: U(0.55), uAspect: U(16 / 9), uFrame: U(0),
    uUnderglow: U(opts.underglowStrength ?? 0.35), uPackDepth: U(useTaa ? 1 : 0), uMaxSteps: U(game.headless ? 28 : 140),
  };
  const cloudPass = makePass(CLOUD_FRAG, cloudUniforms, quadGeo);
  const taaSize = new THREE.Vector2(320, 180);
  const taaU: Record<string, THREE.IUniform> = {
    tCur: U(null), tHist: U(null), uSize: U(taaSize),
    uCamPos: cloudUniforms.uCamPos, uCamR: cloudUniforms.uCamR, uCamU: cloudUniforms.uCamU, uCamF: cloudUniforms.uCamF, uTanHalf: cloudUniforms.uTanHalf, uAspect: cloudUniforms.uAspect,
    uPrevPos: U(prevP), uPrevR: U(prevR), uPrevU: U(prevU), uPrevF: U(prevF), uPrevTanHalf: U(0.55), uPrevAspect: U(16 / 9), uReset: U(1),
  };
  const taaPass = makePass(TAA_FRAG, taaU, quadGeo);

  let scale = THREE.MathUtils.clamp(opts.scale ?? (game.headless ? 0.35 : 0.55), 0.25, 1), tw = 0, th = 0;
  let cloudRT: THREE.WebGLRenderTarget | null = null, histA: THREE.WebGLRenderTarget | null = null, histB: THREE.WebGLRenderTarget | null = null, carry: THREE.WebGLRenderTarget | null = null;
  function alloc(w: number, h: number): void {
    const cw = Math.max(64, Math.round(w * scale)), ch = Math.max(64, Math.round(h * scale));
    if (cw === tw && ch === th && cloudRT) return;
    tw = cw; th = ch; cloudRT?.dispose(); carry?.dispose(); carry = histA; histB?.dispose(); histA = histB = null;
    if (useTaa) {
      cloudRT = makeRT(cw, ch, THREE.FloatType, THREE.NearestFilter);
      histA = makeRT(cw, ch, rtType, THREE.LinearFilter); histB = makeRT(cw, ch, rtType, THREE.LinearFilter);
      taaSize.set(cw, ch); if (!carry) taaU.uReset.value = 1;
    } else cloudRT = makeRT(cw, ch, rtType, THREE.LinearFilter);
  }

  const over = Boolean(opts.compositeOverSky);
  const displayMat = new THREE.ShaderMaterial({
    vertexShader: DISPLAY_VERT, fragmentShader: DISPLAY_FRAG, side: THREE.BackSide, depthWrite: false,
    ...(over ? { transparent: true, blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.SrcAlphaFactor, blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneFactor } : {}),
    uniforms: { tCloud: U(null), uSkyHorizon: cloudUniforms.uSkyHorizon, uSkyZenith: cloudUniforms.uSkyZenith, uOverlay: U(over ? 1 : 0) },
  });
  const domeGeo = new THREE.SphereGeometry(Math.min(500, game.camera.far * 0.85), 20, 12);
  const mesh = new THREE.Mesh(domeGeo, displayMat);
  mesh.name = 'BakedVolumetricCloudSea'; mesh.renderOrder = -1000; mesh.frustumCulled = false;
  game.scene.add(mesh);

  let nextSlice = 0, frameNum = 0; const sz = new THREE.Vector2();
  function bakeBatch(n: number): void {
    const prev = ren.getRenderTarget(), end = Math.min(bZ, nextSlice + n);
    for (let s = nextSlice; s < end; s++) { bakePass.uniforms.uSliceY.value = (s + 0.5) / bZ; ren.setRenderTarget(bakeRT, s); ren.render(bakePass.scene, quadCam); }
    ren.setRenderTarget(prev); nextSlice = end;
  }
  if (game.headless) bakeBatch(bZ);

  game.onAlways(() => {
    if (game.xr.active) return;
    if (nextSlice < bZ) bakeBatch(4);
    ren.getDrawingBufferSize(sz); const dpr = ren.getPixelRatio();
    const w = Math.max(64, Math.round((game.canvas.clientWidth || sz.x || 640) * dpr)), h = Math.max(64, Math.round((game.canvas.clientHeight || sz.y || 360) * dpr));
    alloc(w, h); if (!cloudRT) return;
    game.camera.updateMatrixWorld(); game.camera.matrixWorld.extractBasis(camR, camU, camF); camF.negate(); camP.copy(game.camera.position);
    cloudUniforms.uTanHalf.value = Math.tan(THREE.MathUtils.degToRad(game.camera.fov * 0.5));
    cloudUniforms.uAspect.value = w / h; cloudUniforms.uFrame.value = frameNum++; mesh.position.copy(camP);
    const prev = ren.getRenderTarget(); ren.setRenderTarget(cloudRT); ren.render(cloudPass.scene, quadCam);
    let outTex: THREE.Texture = cloudRT.texture;
    if (useTaa && histA && histB) {
      taaU.tCur.value = cloudRT.texture; taaU.tHist.value = (carry ?? histA).texture;
      ren.setRenderTarget(histB); ren.render(taaPass.scene, quadCam);
      if (carry) { carry.dispose(); carry = null; }
      outTex = histB.texture; [histA, histB] = [histB, histA];
      prevP.copy(camP); prevR.copy(camR); prevU.copy(camU); prevF.copy(camF);
      taaU.uPrevTanHalf.value = cloudUniforms.uTanHalf.value; taaU.uPrevAspect.value = cloudUniforms.uAspect.value; taaU.uReset.value = 0;
    }
    ren.setRenderTarget(prev); displayMat.uniforms.tCloud.value = outTex;
  });

  return {
    mesh, bakeTexture: bakeRT.texture, cloudUniforms,
    setLightDirection(dir: THREE.Vector3) { lightDir.copy(dir).normalize(); nextSlice = 0; },
    setResolutionScale(next: number) { scale = THREE.MathUtils.clamp(next, 0.25, 1); },
    dispose() {
      game.scene.remove(mesh);
      for (const r of [domeGeo, quadGeo, displayMat, bakePass.material, cloudPass.material, taaPass.material, bakeRT, noiseTex, cloudRT, histA, histB, carry]) r?.dispose();
    },
  };
}
```

## Verification
- **Zero readback**: `WebGL3DRenderTarget` + `setRenderTarget(bakeRT, slice)` bakes directly on GPU.
- **Headless/VR**: Drops to `16^3` noise / `32x16x32` bake / `28` steps under `game.headless`; skips offscreen passes in `game.xr.active`.
- **Check**: Run `compile` (`threeCompile`) for 0 shader/TS errors, then inspect `Captures/*.png`.

## Official references

- Weeb Labs — Nightscape (MIT)
- Andrew Schneider & Nathan Vos (SIGGRAPH 2015 / 2017, Guerrilla Games — Horizon: Zero Dawn Volumetric Cloudscapes)
- Sébastien Hillaire (SIGGRAPH 2016 — Physically Based Sky, Atmosphere and Cloud Rendering)
- Marco Salvi (GDC 2016 — Temporal Supersampling Variance Clipping)

## Open-source sources

- Adapts code from Nightscape by Weeb Labs (MIT License), https://github.com/WeebLabs/Nightscape (cloud-sea bake, raymarch, scattering and TAA adapted to Three.js 0.183 TypeScript and the ccgd kit)

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