Generated banner for Threejs Weather
Generated logo for Threejs Weather

Threejs Weather

Meng ToCommunityCreated by Meng To

  • Skill
  • Guidelines
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

Put weather into a Three.js scene that reads as weather — rain anchored inside the frustum, a storm that is the rain leaned on rather than a second system, lightning on its own light with thunder scheduled by distance, snow that blows up into blizzards and keeps settling until the ground goes white, wet ground with puddles and splashes, and looping ambience that has no seam. Use for scene atmosphere, seasonal states, hero backdrops, or any world where clear/rain/storm/snow needs to be a control the viewer can turn.
— the description by Meng To

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This guide provides architectural patterns for creating dynamic weather effects in Three.js, focusing on performance and visual realism. It covers frustum-anchored particle systems, efficient buffer management, lightning light-flashing, snow accumulation, and seamless audio looping. By treating weather as a set of controlled variables rather than disparate systems, it enables smooth transitions between clear, rain, storm, and snow states.

What it does

  • Anchors particle volumes to the camera frustum to optimize rendering.
  • Uses draw ranges to manage particle density without reallocating buffers.
  • Implements dynamic lightning with randomized strikes and distance-based audio delays.
  • Simulates snow accumulation on surfaces using shader-based color mixing.
  • Provides a method for seamless audio looping via cross-fading.
  • Offers strategies for gating expensive scene relighting operations.

When to use it

  • When building immersive 3D environments requiring dynamic atmospheric changes.
  • When you need to transition between weather states like rain, storms, and snow without performance hitches.
  • When optimizing particle systems to ensure they remain visible within the camera's view.
  • When implementing environmental effects that interact with the ground, such as snow accumulation or wet surfaces.

Advantages

  • Prevents frame drops by avoiding buffer reallocation during weather changes.
  • Ensures visual consistency by using a unified system for different weather intensities.
  • Increases realism through distance-based audio and varied lightning strike patterns.
  • Reduces CPU overhead by gating expensive relighting calculations.

Usage examples

“How do I optimize a rain system in Three.js so it doesn't lag when changing intensity?”
The guide recommends allocating a maximum buffer size once and using setDrawRange to adjust the number of active particles, avoiding costly buffer reallocations.
“How can I make lightning feel more realistic in my 3D scene?”
It suggests using a dedicated light source for flashes, randomizing strike positions, and implementing a delay for thunder that correlates with the strike's distance.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/mengto/threejs-weather/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip threejs-weather.zip -d .agents/skills

Documentation by Meng To

Three.js Weather

Weather fails in two ways: the particles miss the camera entirely, or every state is a separate system that shares nothing. Both are avoidable.

Pairs with threejs-landscape for the ground it falls on, and threejs-towers for something to fall against.

Anchor the volume in the frustum

The first version of any rain system puts a world-sized box of particles around the origin and looks empty. With a long lens the camera sees a narrow cone, so almost every drop is off-camera.

Build a small volume and carry it in front of the camera, facing the way the camera faces:

const WX_W = 17, WX_D = 50, WX_TOP = 40;         // narrow, deep, tall
function anchor(o) {
  const fx = -Math.sin(camAz), fz = -Math.cos(camAz);
  o.position.set(cam.position.x + fx * 46, 0, cam.position.z + fz * 46);
  o.rotation.y = camAz;
}

Set frustumCulled = false on it — you are moving it every frame and the bounding sphere will fight you.

Float32BufferAttribute copies your array

This one costs an afternoon. The attribute takes a copy of whatever you hand it, so the array you kept a reference to is not the one the GPU reads:

const attr = new THREE.Float32BufferAttribute(pos, 3);
attr.setUsage(THREE.DynamicDrawUsage);
geo.setAttribute('position', attr);
return { pts, pos: attr.array, n };              // keep the attribute's array

Symptom: everything is correct, nothing moves, no error anywhere.

Density is a draw range, not a new buffer

Allocate the worst case once — a full storm, a full blizzard — and thin it by drawing less:

RAIN.geo.setDrawRange(0, Math.round(RAIN.n * density));

A storm then costs no more memory than drizzle; it just stops hiding most of the drops. Reallocating buffers when weather changes causes a hitch exactly when the viewer is watching.

A storm is the rain leaned on

Do not write a second particle system. Take the rain state and push every dial:

rainstorm
drops drawn60% of pool100%
fall speed×1.0×1.42
slant2.4scales with speed²
sun30%14%
fog far×0.52×0.38

Slant should grow faster than speed — slant = base * v * v — because that is what sells wind rather than "rain, but quicker".

Lightning is its own light

Do not modify the time-of-day state to flash. Add a light nobody else touches, so a strike can flash over whatever the sky happens to be doing:

const bolt = new THREE.DirectionalLight(0xe8eeff, 0);

One strike is several flashes — a leader and two or three return strokes — each an exponential decay:

function strike() {
  const near = Math.random();                    // 0 distant … 1 close
  const s = 0.42 + near * 0.58;
  pulses = [{ t: 0, a: s }];
  let tt = 0;
  for (let i = 0, n = 1 + (Math.random() * 2.6 | 0); i < n; i++) {
    tt += 0.05 + Math.random() * 0.14;
    pulses.push({ t: tt, a: s * (0.30 + Math.random() * 0.65) });
  }
  setTimeout(() => sfx(near > 0.5 ? 'thunder_near' : 'thunder_far',
                      { gain: 0.30 + near * 0.60 }),
             (0.32 + (1 - near) * 2.7) * 1000);  // sound arrives late
}
function step(dt) {
  let v = 0;
  for (const p of pulses) if (age >= p.t) v += p.a * Math.exp(-(age - p.t) / 0.085);
  bolt.intensity = v * 3.2;
  skyMat.color.setScalar(1 + v * 0.80);          // multiplies the sky map
  flashEl.style.opacity = (v * 0.15).toFixed(3);
}

Two details do most of the work. Thunder is delayed by distance and quieter the longer it takes — that single correlation is what makes a strike feel far away. And the DOM flash belongs under the type, not over it: a full-screen white overlay above your typography washes the page out, so put it directly above the canvas and keep it under about 0.18 opacity.

Reposition the light on every strike. A flash that always comes from the same side stops reading after the second one.

A blizzard is a slow envelope, not a state

Snow does not fall at one rate forever. Run a cycle — calm, build, blow, ease — and modulate the snow state with it:

const BLIZ = [12, 6, 15, 8];                     // seconds
function blizzardAt(t) {
  let u = t % TOTAL; if (u < 0) u += TOTAL;
  if (u < BLIZ[0]) return 0;
  ...                                            // smoothstep in, hold, out
}

During the blow, open the flake pool, thicken the flakes, drive them sideways and pull the fog in. Reset the phase clock to zero when you leave the snow state, or arriving in snow drops you into the middle of a whiteout — a negative start offset wraps into the wrong phase and looks like a bug you cannot find.

Falling snow and settled snow are two variables

The one people forget. Track what has already landed on its own slow timer, rising while snow falls and melting back when the weather turns:

snowPack += (target - snowPack) * (target > snowPack ? dt / 24 : dt / 13);

Then let it keep whitening the ground, the stones and the grass for as long as it falls. Arriving in snow and standing in it for a minute should not look the same.

If the surface colour is mixed inside a shader — instanced grass usually is — the material colour cannot reach it. Give that mix its own uniform, and let snow lie on the tips first and work down:

gBase = mix(gBase, vec3(0.60, 0.65, 0.72), uSnow * 0.86);
gTip  = mix(gTip,  vec3(0.90, 0.94, 1.00), uSnow);

Re-light only when the slow values move

Relighting the scene is not free, and blizzard strength and snow depth drift continuously. Gate it:

const look = blizK + snowPack;
if (Math.abs(look - lastLook) > 0.006) { lastLook = look; refreshLook(); }

That fires a few times a second instead of sixty, and nothing on screen can tell.

Wet ground

Three cheap things, in order of payoff: drop roughness and add a little metalness so the ground catches the sky; add flat translucent puddle decals in the hollows; then instance a splash ring sprite with a short life, spawned in proportion to rain intensity. The splashes are what make it read as falling rain rather than a rain texture.

Ambience that loops with no seam

Generated audio never loops cleanly. Fold the tail back over the head with an equal-power cross-fade and throw the overlap away — the clip then ends where it starts:

for i in range(f):
    t = i / f
    out[i] = a[i] * sin(t * pi / 2) + a[n - f + i] * cos(t * pi / 2)

Fading the clip in and out instead means it dips to silence every lap, which everyone hears and nobody mentions.

Give weather its own gain bus, separate from music, and run the blizzard as a second layer swelling over the base bed rather than a cross-fade to a different clip — a hard swap in the middle of a storm is obvious.

What to check before you call it done

  • Watch a single drop from spawn to ground. If you cannot find one, your volume is outside the frustum.

  • Leave it in snow for two minutes. The ground should be visibly whiter at the end, and you should have seen at least one blizzard arrive and pass.

  • Enter snow from clear five times. It must start calm every time.

  • Stand in a storm for a minute. Strikes should come from different sides, and thunder should never land on the flash.

  • Profile with the storm running. Particles are cheap; the relight you forgot to gate is not.

Files

demo/index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Three.js Weather — rain, storm, lightning, blizzard</title>
<style>
:root{
  --paper:#ecdcbc; --ink:#2e2515; --ink2:#8b7c5c; --accent:#a8621f;
  --hair:rgba(58,40,14,.40);
  --sans:"Helvetica Neue",Helvetica,Arial,system-ui,sans-serif;
  --serif:"Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;
}
*{margin:0;padding:0;box-sizing:border-box}
html,body{height:100%}
body{background:var(--paper);color:var(--ink);font-family:var(--sans);overflow:hidden;
  -webkit-font-smoothing:antialiased;transition:background-color .6s ease,color .6s ease}
#app{position:fixed;inset:0}
/* a canvas is a replaced element, so inset:0 does NOT stretch it — without
   an explicit size it falls back to its intrinsic width/height attributes,
   which at DPR 2 is twice the viewport, and the page shows a corner of it */
#stage{position:absolute;inset:0;width:100%;height:100%;display:block;
  cursor:grab;touch-action:none}
#stage.drag{cursor:grabbing}
header{position:absolute;left:0;right:0;top:0;height:54px;padding:0 30px;display:flex;
  align-items:center;gap:22px;border-bottom:1px solid var(--hair);
  transition:border-color .6s ease}
.brand{font-weight:700;font-size:15px;letter-spacing:2.4px}
.spacer{margin-left:auto}
.btn{font-size:11px;font-weight:700;letter-spacing:.9px;color:var(--ink);background:none;
  border:0;font-family:inherit;padding:0 0 6px;border-bottom:1px solid var(--hair);
  cursor:pointer;white-space:nowrap;transition:color .18s,border-color .18s}
.btn:hover{color:var(--accent);border-color:var(--accent)}
.note{position:absolute;left:30px;top:80px;max-width:320px;font-family:var(--serif);
  font-size:14px;line-height:23px;color:var(--ink);opacity:.86}
.note b{display:block;font-family:var(--sans);font-size:11px;font-weight:700;
  letter-spacing:1.3px;color:var(--accent);margin-bottom:9px}
.flash{position:absolute;inset:0;pointer-events:none;opacity:0;
  background:#dce6ff;mix-blend-mode:screen}
.stat{position:absolute;right:30px;top:80px;font-size:11px;letter-spacing:.6px;
  color:var(--ink);opacity:.6;font-variant-numeric:tabular-nums;text-align:right;line-height:18px}
@media (max-width:720px){
  header{padding:0 16px;gap:14px;overflow-x:auto;scrollbar-width:none}
  header::-webkit-scrollbar{display:none}
  .note{left:16px;right:16px;top:66px;max-width:none;font-size:13px;line-height:21px}
  .stat{right:16px;top:66px}
}
</style>
</head>
<body>
<div id="app">
  <canvas id="stage"></canvas>
  <div class="flash" id="flash"></div>
  <header>
    <div class="brand">WEATHER</div>
    <div class="spacer"></div>
    <button class="btn" id="wxBtn">WEATHER / CLEAR</button>
    <button class="btn" id="timeBtn">TIME / MORNING</button>
    <button class="btn" id="strikeBtn">⚡ STRIKE</button>
  </header>
  <div class="note"><b>WHAT YOU ARE LOOKING AT</b>
    Four weather states over one landscape. The storm is the rain state leaned
    on, not a second system. Lightning is its own light, so it flashes over
    whatever the sky is doing, and the thunder arrives late. Snow runs a
    calm/build/blow/ease cycle and keeps settling. Drag to orbit.</div>
  <div class="stat" id="stat"></div>
</div>

<script src="assets/three.min.js"></script>
<script>
/* =====================================================================
   Three.js Weather — the reference build for the threejs-weather skill.
   A minimal landscape carrying four weather states: clear, rain, a storm with
   lightning and thunder timing, and snow that blows up into blizzards and
   keeps settling until the field goes white. All procedural, no assets.
   ===================================================================== */
(function(){
"use strict";
const T=THREE;

/* ------------------------------------------------------------------ *
 * 1.  noise — 2-D simplex, plus fBm and a ridged variant
 * ------------------------------------------------------------------ */
const NZ=(function(){
  const p=new Uint8Array(512),perm=new Uint8Array(512);
  let s=1337; const rnd=()=>{s=(s*1664525+1013904223)>>>0;return s/4294967296;};
  for(let i=0;i<256;i++)p[i]=i;
  for(let i=255;i>0;i--){const j=(rnd()*(i+1))|0;const t=p[i];p[i]=p[j];p[j]=t;}
  for(let i=0;i<512;i++)perm[i]=p[i&255];
  const G=[[1,1],[-1,1],[1,-1],[-1,-1],[1,0],[-1,0],[0,1],[0,-1]];
  const F2=0.5*(Math.sqrt(3)-1), G2=(3-Math.sqrt(3))/6;
  function snoise(xin,yin){
    const s2=(xin+yin)*F2;
    let i=Math.floor(xin+s2), j=Math.floor(yin+s2);
    const t=(i+j)*G2, X0=i-t, Y0=j-t, x0=xin-X0, y0=yin-Y0;
    const i1=x0>y0?1:0, j1=x0>y0?0:1;
    const x1=x0-i1+G2, y1=y0-j1+G2, x2=x0-1+2*G2, y2=y0-1+2*G2;
    i&=255; j&=255;
    let n=0;
    const c=(x,y,gi)=>{
      let t2=0.5-x*x-y*y;
      if(t2<0)return 0;
      t2*=t2; const g=G[gi&7];
      return t2*t2*(g[0]*x+g[1]*y);
    };
    n+=c(x0,y0,perm[i+perm[j]]);
    n+=c(x1,y1,perm[i+i1+perm[j+j1]]);
    n+=c(x2,y2,perm[i+1+perm[j+1]]);
    return 70*n;
  }
  function fbm(x,y,oct,gain){
    let a=1,f=1,sum=0,norm=0; gain=gain||0.5;
    for(let i=0;i<oct;i++){sum+=snoise(x*f,y*f)*a;norm+=a;a*=gain;f*=2.02;}
    return sum/norm;
  }
  function ridged(x,y,oct){
    let a=1,f=1,sum=0,norm=0;
    for(let i=0;i<oct;i++){
      const v=1-Math.abs(snoise(x*f,y*f));
      sum+=v*v*a; norm+=a; a*=0.5; f*=2.07;
    }
    return sum/norm;
  }
  return {snoise,fbm,ridged};
})();

/* the analytic ground. Everything scattered on the terrain samples this,
   never the mesh, or it floats and sinks. */
function landH(x,z){
  /* domain warp first — this is what stops fBm reading as crumpled paper */
  const wx=x+NZ.fbm(x*0.0125,z*0.0125,3)*24;
  const wz=z+NZ.fbm(x*0.0125+41,z*0.0125-17,3)*24;
  let h=NZ.fbm(wx*0.0040,wz*0.0040,5)*30;
  h+=NZ.ridged(wx*0.0105,wz*0.0105,3)*8.5;
  h+=NZ.fbm(wx*0.052,wz*0.052,2)*0.32;
  /* hold the whole near field dead flat — the camera orbits at 80 units and
     must never end up inside a hill — and let the landforms rise beyond it */
  const d=Math.hypot(x,z);
  const t=Math.max(0,Math.min(1,(d-110)/170));
  h*=t*t*(3-2*t);
  return h-0.5;
}
function landN(x,z){
  const e=0.9;
  const hx=landH(x+e,z)-landH(x-e,z), hz=landH(x,z+e)-landH(x,z-e);
  const n=new T.Vector3(-hx,2*e,-hz); n.normalize(); return n;
}

/* ------------------------------------------------------------------ *
 * 2.  scene
 * ------------------------------------------------------------------ */
const cvs=document.getElementById('stage');
const renderer=new T.WebGLRenderer({canvas:cvs,antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio||1,2));
renderer.shadowMap.enabled=true;
renderer.shadowMap.type=T.PCFSoftShadowMap;
renderer.outputEncoding=T.sRGBEncoding!==undefined?T.sRGBEncoding:renderer.outputEncoding;
const scene=new T.Scene();
scene.fog=new T.Fog(0xf0d6a8,60,560);
const camera=new T.PerspectiveCamera(12,1,0.5,2000);

const key=new T.DirectionalLight(0xffffff,1);
key.castShadow=true;
key.shadow.mapSize.set(2048,2048);
key.shadow.camera.near=1;key.shadow.camera.far=180;
key.shadow.bias=-0.0016;
scene.add(key,key.target);
const hemi=new T.HemisphereLight(0xffffff,0x604020,0.5);
const amb=new T.AmbientLight(0xffffff,0.1);
const fill=new T.DirectionalLight(0xffffff,0.08);
fill.position.set(-40,18,-30);
scene.add(hemi,amb,fill);

/* ------------------------------------------------------------------ *
 * 3.  sky dome — a six-stop gradient on an 8x512 canvas
 * ------------------------------------------------------------------ */
const SKY_STOPS=[0,0.30,0.52,0.68,0.84,1];
const skyCan=document.createElement('canvas');skyCan.width=8;skyCan.height=512;
function paintSky(cols){
  const g=skyCan.getContext('2d');
  const grd=g.createLinearGradient(0,0,0,512);
  cols.forEach((c,i)=>grd.addColorStop(SKY_STOPS[i],'#'+('000000'+c.getHexString()).slice(-6)));
  g.fillStyle=grd;g.fillRect(0,0,8,512);
  if(skyMat.map)skyMat.map.needsUpdate=true;
}
const skyMat=new T.MeshBasicMaterial({side:T.BackSide,fog:false,depthWrite:false});
skyMat.map=new T.CanvasTexture(skyCan);
const sky=new T.Mesh(new T.SphereGeometry(900,32,24),skyMat);
sky.renderOrder=-20;scene.add(sky);

/* stars, confined to the band the camera can actually reach */
const starLayers=[];
(function(){
  const S=64,c=document.createElement('canvas');c.width=c.height=S;
  const g=c.getContext('2d');
  const gr=g.createRadialGradient(S/2,S/2,0,S/2,S/2,S/2);
  gr.addColorStop(0,'rgba(255,255,255,1)');
  gr.addColorStop(0.28,'rgba(255,255,255,.85)');
  gr.addColorStop(0.60,'rgba(255,255,255,.16)');
  gr.addColorStop(1,'rgba(255,255,255,0)');
  g.fillStyle=gr;g.fillRect(0,0,S,S);
  const tex=new T.CanvasTexture(c);
  const DPR=Math.min(devicePixelRatio||1,2);
  let seed=20260811;
  const rnd=()=>{seed=(seed*1664525+1013904223)>>>0;return seed/4294967296;};
  /* three size classes so brightness varies; sizes scale with DPR or they
     disappear entirely on a retina display */
  [[22000,1.7*DPR],[6000,2.7*DPR],[1400,4.6*DPR]].forEach(([N,px])=>{
    const pos=new Float32Array(N*3),col=new Float32Array(N*3);
    for(let i=0;i<N;i++){
      const th=rnd()*Math.PI*2;
      const u=Math.max(-0.06,Math.min(0.85,-0.06+rnd()*0.91));
      const R=760,s=Math.sqrt(Math.max(0,1-u*u));
      pos[i*3]=Math.cos(th)*s*R;pos[i*3+1]=u*R;pos[i*3+2]=Math.sin(th)*s*R;
      const w=rnd();
      const cc=w>0.88?[1,0.87,0.70]:w<0.13?[0.74,0.84,1]:[0.97,0.97,0.93];
      const b=0.46+Math.pow(rnd(),1.7)*0.54;
      col[i*3]=cc[0]*b;col[i*3+1]=cc[1]*b;col[i*3+2]=cc[2]*b;
    }
    const g2=new T.BufferGeometry();
    g2.setAttribute('position',new T.Float32BufferAttribute(pos,3));
    g2.setAttribute('color',new T.Float32BufferAttribute(col,3));
    const m=new T.PointsMaterial({size:px,map:tex,vertexColors:true,transparent:true,
      opacity:0,depthWrite:false,fog:false,sizeAttenuation:false,blending:T.AdditiveBlending});
    const pts=new T.Points(g2,m);pts.renderOrder=-15;pts.frustumCulled=false;
    scene.add(pts);starLayers.push(m);
  });
})();

/* ------------------------------------------------------------------ *
 * 4.  terrain — a polar grid so resolution follows the lens
 * ------------------------------------------------------------------ */
const AN=620,RN=48,R0=1.6,R1=760;
const terrainMat=new T.MeshLambertMaterial({vertexColors:true});
const ROCK=new T.Color(0x8a8272),GRASS=new T.Color(0x66703c),
      SAND=new T.Color(0xbcae86),DARK=new T.Color(0x4a5230);
const terrain=(function(){
  const pos=[],col=[],idx=[],c=new T.Color();
  for(let r=0;r<=RN;r++){
    const t=r/RN, rad=R0+(R1-R0)*Math.pow(t,2.4);
    for(let a=0;a<AN;a++){
      const th=a/AN*Math.PI*2;
      const x=Math.cos(th)*rad, z=Math.sin(th)*rad;
      const y=landH(x,z);
      pos.push(x,y,z);
      const n=landN(x,z);
      const slope=1-n.y;
      const moist=Math.max(0,Math.min(1,(3.0-y)/12));
      const tint=NZ.fbm(x*0.02,z*0.02,2)*0.5+0.5;
      c.copy(ROCK)
       .lerp(GRASS,Math.max(0,Math.min(1,1-slope*3.4))*(0.34+moist*0.66))
       .lerp(SAND,Math.max(0,0.42-moist)*0.55)
       .lerp(DARK,tint*0.22);
      /* fade the far rings toward the fog so the horizon has no edge */
      const fade=Math.min(1,Math.pow(t,2.6));
      c.lerp(new T.Color(0xd8c9a4),fade*0.55);
      col.push(c.r,c.g,c.b);
    }
  }
  for(let r=0;r<RN;r++)for(let a=0;a<AN;a++){
    const a1=(a+1)%AN;
    const a0=r*AN+a, b0=r*AN+a1, a2=(r+1)*AN+a, b2=(r+1)*AN+a1;
    /* wind it this way round or you see the sky through the ground */
    idx.push(a0,b2,b0, a0,a2,b2);
  }
  const g=new T.BufferGeometry();
  g.setAttribute('position',new T.Float32BufferAttribute(pos,3));
  g.setAttribute('color',new T.Float32BufferAttribute(col,3));
  g.setIndex(idx);g.computeVertexNormals();
  const m=new T.Mesh(g,terrainMat);
  m.receiveShadow=true;scene.add(m);return m;
})();


/* ------------------------------------------------------------------ *
 * 5.  grass — one instanced ribbon, shaped in the vertex shader
 * ------------------------------------------------------------------ */
const grassUni={uTime:{value:0},uWind:{value:new T.Vector2(0.84,0.54)},
  uWindAmp:{value:0.30},uSnow:{value:0},uOrigin:{value:new T.Vector2()},
  uRadius:{value:64}};
const GRASS_N=150000, GRASS_R=64, GRASS_AHEAD=74;
const grassMesh=(function(){
  const BSEG=5,pos=[],idx=[];
  for(let s=0;s<BSEG;s++){const t=s/BSEG;pos.push(-0.5,t,0, 0.5,t,0);}
  pos.push(0,1,0);
  for(let s=0;s<BSEG-1;s++){const a=s*2;idx.push(a,a+1,a+2, a+1,a+3,a+2);}
  idx.push((BSEG-1)*2,(BSEG-1)*2+1,BSEG*2);
  const bg=new T.BufferGeometry();
  bg.setAttribute('position',new T.Float32BufferAttribute(pos,3));
  bg.setIndex(idx);

  const mat=new T.MeshLambertMaterial({color:0xffffff,side:T.DoubleSide});
  mat.onBeforeCompile=sh=>{
    Object.assign(sh.uniforms,grassUni);
    sh.vertexShader=`
      uniform float uTime,uWindAmp,uRadius;
      uniform vec2 uWind,uOrigin;
      attribute vec4 aParams;      /* height, phase, tint, lean */
      varying float vT; varying float vTint;
    `+sh.vertexShader.replace('#include <begin_vertex>',`
      float gT=position.y;
      vT=gT; vTint=aParams.z;
      vec3 gRoot=vec3(instanceMatrix[3][0],instanceMatrix[3][1],instanceMatrix[3][2]);
      /* phase from the WORLD position, not the local one, or the gust
         pattern travels along with the patch as the camera moves */
      vec2 gWorld=gRoot.xz+uOrigin;
      float gW=sin(uTime*1.35+aParams.y+gWorld.x*0.09+gWorld.y*0.07);
      float gBend=(aParams.w+gW*uWindAmp)*pow(gT,1.7);
      /* fade the blades out at the rim of the patch, or its edge reads as a
         ruled line across the field */
      float gEdge=1.0-smoothstep(0.74,1.0,length(gRoot.xz)/uRadius);
      vec2 gDir=normalize(uWind);
      vec2 gRib=gDir*gBend*aParams.x
               +vec2(-gDir.y,gDir.x)*position.x*0.072*(1.0-gT*0.70);
      /* three.js applies instanceMatrix itself further down the chain, so the
         blade is built about the origin — gRoot is only read to decorrelate
         the wind phase. Adding it here translates every blade twice. */
      vec3 transformed=vec3(gRib.x,gT*aParams.x*gEdge*(1.0-gBend*gBend*0.22),gRib.y);
    `).replace('#include <beginnormal_vertex>',`
      vec3 objectNormal=normalize(vec3(-normalize(uWind).y,0.55,normalize(uWind).x));
    `);
    sh.fragmentShader=`
      uniform float uSnow;
      varying float vT; varying float vTint;
    `+sh.fragmentShader.replace('#include <color_fragment>',`
      #include <color_fragment>
      vec3 gBase=vec3(0.150,0.180,0.092)*(0.74+vTint*0.54);
      vec3 gTip =vec3(0.560,0.630,0.330)*(0.76+vTint*0.56);
      /* the blade colour is mixed here, so anything that has to recolour the
         grass — settled snow, a season — needs this uniform, not the material */
      gBase=mix(gBase,vec3(0.60,0.65,0.72),uSnow*0.86);
      gTip =mix(gTip ,vec3(0.90,0.94,1.00),uSnow);
      diffuseColor.rgb*=mix(gBase,gTip,pow(vT,0.78))*1.30;
    `);
  };
  mat.customProgramCacheKey=()=>'landscape-grass';

  const im=new T.InstancedMesh(bg,mat,GRASS_N);
  const par=new Float32Array(GRASS_N*4);
  const m4=new T.Matrix4(),q=new T.Quaternion(),v=new T.Vector3(),one=new T.Vector3(1,1,1);
  let n=0,guard=0;
  /* the field is a patch carried in front of the camera rather than a disc
     laid over the whole world — you only pay for the grass in shot, and the
     blades nearest the lens are large enough to read as blades. The near
     ground is flat by construction, so moving the patch is a translation and
     nothing has to be re-sampled. */
  while(n<GRASS_N&&guard<GRASS_N*8){
    guard++;
    const rad=Math.sqrt(Math.random())*GRASS_R;  /* uniform by area */
    /* placed about the patch origin; the patch itself is carried below */
    const th=Math.random()*Math.PI*2;
    const x=Math.cos(th)*rad, z=Math.sin(th)*rad;
    v.set(x,0,z);m4.compose(v,q,one);
    im.setMatrixAt(n,m4);
    par[n*4]  =0.30+Math.random()*0.36;          /* height */
    par[n*4+1]=Math.random()*6.283;              /* phase */
    par[n*4+2]=Math.random();                    /* tint */
    par[n*4+3]=0.10+Math.random()*0.26;          /* rest lean */
    n++;
  }
  im.count=n;
  bg.setAttribute('aParams',new T.InstancedBufferAttribute(par,4));
  im.frustumCulled=false;im.castShadow=false;im.receiveShadow=false;
  im.position.y=-0.5;
  scene.add(im);return im;
})();

/* ------------------------------------------------------------------ *
 * 6.  stones — scattered by the same height function
 * ------------------------------------------------------------------ */
const stoneMat=new T.MeshLambertMaterial({color:0xffffff});
const stoneMesh=(function(){
  const g=new T.IcosahedronGeometry(0.5,1);
  g.scale(1,0.62,1);g.translate(0,0.3,0);        /* sunk, not resting */
  const N=1600,im=new T.InstancedMesh(g,stoneMat,N);
  const m4=new T.Matrix4(),q=new T.Quaternion(),
        v=new T.Vector3(),s=new T.Vector3(),e=new T.Euler();
  let n=0,guard=0;
  while(n<N&&guard<N*20){
    guard++;
    const rad=2.0+Math.pow(Math.random(),0.55)*95;
    const th=Math.random()*Math.PI*2;
    const x=Math.cos(th)*rad, z=Math.sin(th)*rad;
    if(landN(x,z).y<0.80)continue;
    const sc=0.10+Math.pow(Math.random(),2.4)*0.42;
    e.set(Math.random()*0.4,Math.random()*6.28,Math.random()*0.4);
    q.setFromEuler(e);
    v.set(x,landH(x,z)-sc*0.12,z);
    s.set(sc*(0.8+Math.random()*0.6),sc*(0.6+Math.random()*0.5),sc*(0.8+Math.random()*0.6));
    m4.compose(v,q,s);im.setMatrixAt(n,m4);n++;
  }
  im.count=n;im.castShadow=true;im.receiveShadow=true;
  scene.add(im);return im;
})();


/* ------------------------------------------------------------------ *
 * 6b.  weather — one rain pool, one snow pool, and a light of its own
 * ------------------------------------------------------------------ */
function streakSprite(){
  const c=document.createElement('canvas');c.width=64;c.height=128;
  const g=c.getContext('2d'),gr=g.createLinearGradient(0,0,0,128);
  gr.addColorStop(0,'rgba(255,255,255,0)');
  gr.addColorStop(0.28,'rgba(255,255,255,.90)');
  gr.addColorStop(0.74,'rgba(255,255,255,.90)');
  gr.addColorStop(1,'rgba(255,255,255,0)');
  g.fillStyle=gr;g.fillRect(31,0,2.6,128);return c;
}
function flakeSprite(){
  const c=document.createElement('canvas');c.width=c.height=64;
  const g=c.getContext('2d'),gr=g.createRadialGradient(32,32,0,32,32,32);
  gr.addColorStop(0,'rgba(255,255,255,1)');
  gr.addColorStop(0.42,'rgba(255,255,255,.72)');
  gr.addColorStop(1,'rgba(255,255,255,0)');
  g.fillStyle=gr;g.fillRect(0,0,64,64);return c;
}
/* the lens is long, so a world-sized box of particles would put almost every
   drop off camera. Keep a narrow volume and carry it in front of the lens. */
/* sized to the frustum wedge, not to the world: with an 11-degree lens a
   loose box puts almost every drop out of shot */
const WX_W=5,WX_D=40,WX_TOP=7,WX_AHEAD=26;
function makeField(n,tex,size,opacity){
  const pos=new Float32Array(n*3),dat=new Float32Array(n*3);
  for(let i=0;i<n;i++){
    pos[i*3]=(Math.random()-0.5)*2*WX_W;
    pos[i*3+1]=Math.random()*WX_TOP;
    pos[i*3+2]=(Math.random()-0.5)*2*WX_D;
    dat[i*3]=Math.random();dat[i*3+1]=Math.random()*6.283;dat[i*3+2]=0.6+Math.random()*0.8;
  }
  const g=new T.BufferGeometry();
  /* Float32BufferAttribute COPIES the array you give it, so keep the
     attribute's own array — writing to `pos` would never reach the GPU */
  const attr=new T.Float32BufferAttribute(pos,3);
  attr.setUsage(T.DynamicDrawUsage);
  g.setAttribute('position',attr);
  const m=new T.PointsMaterial({map:new T.CanvasTexture(tex),size:size,
    transparent:true,opacity:opacity,depthWrite:false,sizeAttenuation:true,color:0xffffff});
  const pts=new T.Points(g,m);
  pts.frustumCulled=false;pts.visible=false;pts.renderOrder=6;
  scene.add(pts);
  return {pts,geo:g,pos:attr.array,dat,n};
}
/* the pool has to be sized against the frustum, not against intuition: a
   long lens sees a thin wedge of the volume, so a few thousand drops put a
   few hundred on screen and read as nothing at all */
const RAIN=makeField(34000,streakSprite(),0.26,0.78);
const SNOW=makeField(30000,flakeSprite(),0.115,0.95);
let wxTime=0,rainFall=1;

/* puddles for the wet ground, and a splash ring that spawns with the rain */
const puddleMat=new T.MeshBasicMaterial({color:0x2a2f33,transparent:true,opacity:0,
  depthWrite:false});
const puddles=(()=>{
  const g=new T.CircleGeometry(1,14);g.rotateX(-Math.PI/2);
  const N=90,im=new T.InstancedMesh(g,puddleMat,N);
  const m4=new T.Matrix4(),q=new T.Quaternion(),v=new T.Vector3(),sc=new T.Vector3();
  for(let i=0;i<N;i++){
    const r=Math.sqrt(Math.random())*70,th=Math.random()*6.283;
    v.set(Math.cos(th)*r,-0.47,Math.sin(th)*r);
    const w=0.7+Math.random()*2.6;
    sc.set(w,1,w*(0.5+Math.random()*0.7));
    m4.compose(v,q,sc);im.setMatrixAt(i,m4);
  }
  im.visible=false;im.frustumCulled=false;scene.add(im);return im;
})();

/* lightning is a light nobody else touches, so a strike can flash over
   whatever the time of day happens to be doing */
const bolt=new T.DirectionalLight(0xe8eeff,0);
bolt.position.set(-46,72,-30);bolt.target.position.set(0,4,0);
scene.add(bolt,bolt.target);
const flashEl=document.getElementById('flash');
let boltK=0,boltNext=4.0,boltAge=0,pulses=[];
function strike(){
  /* one strike is several flashes: the leader, then the return strokes */
  const near=Math.random(),s=0.42+near*0.58;
  pulses=[{t:0,a:s}];
  let tt=0;
  for(let i=0,m=1+(Math.random()*2.6|0);i<m;i++){
    tt+=0.05+Math.random()*0.14;
    pulses.push({t:tt,a:s*(0.30+Math.random()*0.65)});
  }
  boltAge=0;
  const az=Math.random()*6.283;
  bolt.position.set(Math.sin(az)*74,58+Math.random()*34,Math.cos(az)*74);
  /* the thunder would be scheduled here, late and quieter the further off:
     setTimeout(() => sfx(near > 0.5 ? 'near' : 'far', {gain: 0.3 + near*0.6}),
                (0.32 + (1 - near) * 2.7) * 1000); */
}
function stepBolt(dt){
  const en=wxN('bolt');
  if(en>0.55){ boltNext-=dt; if(boltNext<=0){strike();boltNext=3.4+Math.random()*7.0;} }
  if(pulses.length){
    boltAge+=dt;
    let v=0;
    for(let i=0;i<pulses.length;i++){
      const q=pulses[i];
      if(boltAge>=q.t)v+=q.a*Math.exp(-(boltAge-q.t)/0.085);
    }
    boltK=Math.min(1.4,v);
    if(boltAge>2.4){pulses.length=0;boltK=0;}
  }else if(boltK>0.0005)boltK*=Math.max(0,1-dt*7); else boltK=0;
  const k=boltK*Math.max(en,pulses.length?1:0);
  bolt.intensity=k*3.2;
  skyMat.color.setScalar(1+k*0.80);
  flashEl.style.opacity=k>0.002?(k*0.15).toFixed(3):'0';
}

/* a blizzard is a slow envelope over the snow state, not a state of its own */
let blizK=0,blizT=0;
const BLIZ=[10,6,14,8];                       /* calm, build, blow, ease */
const BLIZ_CYC=BLIZ[0]+BLIZ[1]+BLIZ[2]+BLIZ[3];
const smoothstep=x=>{x=Math.max(0,Math.min(1,x));return x*x*(3-2*x);};
function blizzardAt(tt){
  let u=tt%BLIZ_CYC; if(u<0)u+=BLIZ_CYC;
  if(u<BLIZ[0])return 0;
  u-=BLIZ[0]; if(u<BLIZ[1])return smoothstep(u/BLIZ[1]);
  u-=BLIZ[1]; if(u<BLIZ[2])return 1;
  return 1-smoothstep((u-BLIZ[2])/BLIZ[3]);
}
/* what has already landed, on its own much slower clock */
let snowPack=0;

const WEATHER=[
 {id:'CLEAR',fogK:1.00,fogC:null,fogM:0,sunK:1.00,ambK:1.00,skyC:null,skyM:0,
  groundC:null,groundM:0,starK:1.00,rain:0,rainN:0,rainV:1,snow:0,snowN:0,wet:0,dust:0,bolt:0},
 {id:'RAIN' ,fogK:0.52,fogC:0x6a7480,fogM:0.55,sunK:0.30,ambK:1.55,skyC:0x717c88,skyM:0.52,
  groundC:0x59594e,groundM:0.52,starK:0,rain:1,rainN:0.60,rainV:1.00,snow:0,snowN:0,wet:1,dust:0,bolt:0},
 {id:'STORM',fogK:0.38,fogC:0x515a67,fogM:0.72,sunK:0.14,ambK:1.30,skyC:0x4b535f,skyM:0.74,
  groundC:0x43443e,groundM:0.62,starK:0,rain:1,rainN:1.00,rainV:1.42,snow:0,snowN:0,wet:1,dust:0,bolt:1},
 {id:'SNOW' ,fogK:0.58,fogC:0xdfe4ea,fogM:0.60,sunK:0.52,ambK:1.45,skyC:0xc9d2dc,skyM:0.46,
  groundC:0xf4f8fc,groundM:0.40,starK:0.30,rain:0,rainN:0,rainV:1,snow:1,snowN:0.52,wet:0,dust:1,bolt:0}
];
let wxIdx=0,wxMix=1,wxFrom=null,wxTo=null;
const _wc=new T.Color();
const wxN=k=>wxFrom?wxFrom[k]+(wxTo[k]-wxFrom[k])*wxMix:0;
function wxBlend(target,kf,kc){
  const a=wxFrom[kc]===null?0:wxFrom[kf], b=wxTo[kc]===null?0:wxTo[kf];
  const m=a+(b-a)*wxMix;
  if(m<=0.001)return;
  _wc.setHex(wxTo[kc]!==null?wxTo[kc]:wxFrom[kc]);
  target.lerp(_wc,m);
}
function wxApply(){
  if(!wxFrom)return;
  const bz=blizK*wxN('snow');
  scene.fog.near*=wxN('fogK')*(1-0.34*bz);
  scene.fog.far *=wxN('fogK')*(1-0.52*bz);
  key.intensity*=wxN('sunK')*(1-0.45*bz);
  amb.intensity*=wxN('ambK');
  wxBlend(scene.fog.color,'fogM','fogC');
  wxBlend(terrainMat.color,'groundM','groundC');
  wxBlend(grassMesh.material.color,'groundM','groundC');
  wxBlend(stoneMat.color,'groundM','groundC');
  for(let i=0;i<6;i++)wxBlend(CUR.sky[i],'skyM','skyC');
  paintSky(CUR.sky);
  const stk=wxN('starK');
  starLayers.forEach(m=>{m.opacity*=stk;m.visible=m.opacity>0.005;});
  const rn=wxN('rain'),sn=wxN('snow'),wet=wxN('wet');
  RAIN.pts.visible=rn>0.01;RAIN.pts.material.opacity=0.82*rn;
  SNOW.pts.visible=sn>0.01;
  /* density is a draw range over one fixed pool: a storm costs no more
     memory than drizzle, it just stops hiding most of the drops */
  RAIN.geo.setDrawRange(0,Math.round(RAIN.n*Math.min(1,wxN('rainN'))));
  SNOW.geo.setDrawRange(0,Math.round(SNOW.n*Math.min(1,wxN('snowN')+0.62*bz)));
  SNOW.pts.material.size=0.115*(1+0.60*bz);
  SNOW.pts.material.opacity=Math.min(1,0.88*sn*(1+0.18*bz));
  rainFall=wxN('rainV');
  puddles.visible=wet>0.02;puddleMat.opacity=0.34*wet;
  /* falling snow and settled snow are two different variables */
  const pk=snowPack,g=pk*sn;
  grassUni.uSnow.value=g;
  if(g>0.002){
    terrainMat.color.lerp(SNOWY,g*0.80);
    stoneMat.color.lerp(SNOWY,g*0.74);
  }
}
const SNOWY=new T.Color(0xf2f6fa);
function applyWeather(i,instant){
  wxIdx=((i%WEATHER.length)+WEATHER.length)%WEATHER.length;
  wxFrom=(wxMix>=1&&wxTo)?wxTo:(wxFrom||WEATHER[0]);
  wxTo=WEATHER[wxIdx];
  wxMix=instant?1:0;
  document.getElementById('wxBtn').textContent='WEATHER / '+wxTo.id;
  if(themeFrom)applyState(themeFrom,themeTo,themeE);
}
function wxAnchor(o){
  const fx=-Math.sin(curAz),fz=-Math.cos(curAz);
  /* close enough to sit in FRONT of the grass — a volume further out than
     the field is simply hidden behind it */
  o.position.set(camera.position.x+fx*WX_AHEAD,-1.5,camera.position.z+fz*WX_AHEAD);
  o.rotation.y=curAz;
}
let _lastLook=0;
function stepWeather(dt){
  wxTime+=dt;
  if(wxMix<1){wxMix=Math.min(1,wxMix+dt/1.35);applyState(themeFrom,themeTo,themeE);}
  const snowing=wxN('snow');
  if(snowing>0.02){blizT+=dt;blizK=blizzardAt(blizT);}
  else{blizK=Math.max(0,blizK-dt*0.6);blizT=0;}   /* rewind, or you arrive mid-whiteout */
  const packT=snowing>0.5?1:0;
  snowPack+=(packT-snowPack)*(packT>snowPack?dt/20:dt/11);
  /* re-lighting is not free, so only redo it when the slow values have moved */
  const look=blizK*(snowing>0.02?1:0)+snowPack;
  if(Math.abs(look-_lastLook)>0.006){_lastLook=look;applyState(themeFrom,themeTo,themeE);}
  stepBolt(dt);
  if(RAIN.pts.visible){
    wxAnchor(RAIN.pts);
    const p=RAIN.pos,d=RAIN.dat,v=rainFall,slant=2.4*v*v;
    for(let i=0;i<RAIN.n;i++){
      p[i*3+1]-=(34+d[i*3]*26)*v*dt;
      p[i*3]-=slant*dt;
      if(p[i*3+1]<-2){p[i*3+1]=WX_TOP;
        p[i*3]=(Math.random()-0.5)*2*WX_W;p[i*3+2]=(Math.random()-0.5)*2*WX_D;}
    }
    RAIN.geo.attributes.position.needsUpdate=true;
  }
  if(SNOW.pts.visible){
    wxAnchor(SNOW.pts);
    const p=SNOW.pos,d=SNOW.dat;
    const fall=1+1.9*blizK,drift=1.1+7.2*blizK,gust=1+2.4*blizK;
    for(let i=0;i<SNOW.n;i++){
      p[i*3+1]-=(1.5+d[i*3]*2.2)*fall*dt;
      p[i*3]+=(Math.sin(wxTime*0.7+d[i*3+1])*drift-6.4*blizK*d[i*3+2])*dt;
      p[i*3+2]+=Math.cos(wxTime*0.5+d[i*3+1])*0.8*gust*dt;
      if(p[i*3+1]<-2||p[i*3]<-WX_W*1.6){p[i*3+1]=WX_TOP;
        p[i*3]=(Math.random()-0.5)*2*WX_W;p[i*3+2]=(Math.random()-0.5)*2*WX_D;}
    }
    SNOW.geo.attributes.position.needsUpdate=true;
  }
}

/* ------------------------------------------------------------------ *
 * 7.  times of day — full states, cross-faded
 * ------------------------------------------------------------------ */
const THEMES=[
 {id:'MORNING',
  css:{paper:'#ecdcbc',ink:'#2e2515',ink2:'#8b7c5c',accent:'#a8621f',hair:'rgba(58,40,14,.40)'},
  sky:[0xf7ecd0,0xf3e2bd,0xeed7ab,0xe7cb9a,0xdcbd8c,0xd2b184],
  fog:0xf0d6a8,fogN:56,fogF:520,ground:0xb9a882,grass:0xf2e6c6,
  sun:{az:0.50,el:0.30,color:0xffe0ad,int:2.0},
  hemiC:[0xfff0d4,0x6d5a34,0.52],ambC:[0xffe9c8,0.10],fillC:[0xffdcb0,0.07],
  stars:0},
 {id:'NOON',
  css:{paper:'#e7ecee',ink:'#22282c',ink2:'#75828a',accent:'#2f6f96',hair:'rgba(24,34,42,.36)'},
  sky:[0x9fc6e4,0xaed0e8,0xc0dcee,0xd2e6f2,0xe2eef5,0xeef4f6],
  fog:0xdde7ec,fogN:56,fogF:560,ground:0xaeb0a4,grass:0xf4f6f2,
  sun:{az:0.30,el:0.86,color:0xffffff,int:2.3},
  hemiC:[0xdcecff,0x5a6248,0.62],ambC:[0xe6f2ff,0.13],fillC:[0xcfe4f6,0.09],
  stars:0},
 {id:'SUNSET',
  css:{paper:'#f0d0aa',ink:'#3a2010',ink2:'#8f6244',accent:'#c2551b',hair:'rgba(66,24,6,.42)'},
  sky:[0xf6b268,0xf0a05c,0xe58a52,0xd4744e,0xb85f4a,0x8d4d44],
  fog:0xef9a52,fogN:50,fogF:480,ground:0xa8794e,grass:0xe8c8a0,
  sun:{az:1.28,el:0.10,color:0xffa05a,int:2.4},
  hemiC:[0xffc089,0x6a3a24,0.50],ambC:[0xffb98c,0.11],fillC:[0xff9e6a,0.09],
  stars:0.12},
 {id:'NIGHT',
  css:{paper:'#151a24',ink:'#e9e2d2',ink2:'#8b8fa0',accent:'#c98a4a',hair:'rgba(233,226,210,.20)'},
  sky:[0x0c1120,0x101733,0x151d3d,0x1b2647,0x243050,0x2d3a5c],
  fog:0x131c2e,fogN:52,fogF:480,ground:0x2b3140,grass:0x7182a6,
  sun:{az:0.50,el:0.62,color:0x9fb6de,int:0.42},
  hemiC:[0x2e3a54,0x0d0f14,0.24],ambC:[0x5c6a8c,0.06],fillC:[0x7286ac,0.08],
  stars:1.0}
];
function themeState(th){
  return {sunAz:th.sun.az,sunEl:th.sun.el,sunC:new T.Color(th.sun.color),sunI:th.sun.int,
    hemiS:new T.Color(th.hemiC[0]),hemiG:new T.Color(th.hemiC[1]),hemiI:th.hemiC[2],
    ambC:new T.Color(th.ambC[0]),ambI:th.ambC[1],
    fillC:new T.Color(th.fillC[0]),fillI:th.fillC[1],
    fog:new T.Color(th.fog),fogN:th.fogN,fogF:th.fogF,
    ground:new T.Color(th.ground),grass:new T.Color(th.grass),
    sky:th.sky.map(c=>new T.Color(c)),stars:th.stars};
}
const CUR={sun:new T.Color(),hemiS:new T.Color(),hemiG:new T.Color(),amb:new T.Color(),
  fill:new T.Color(),fog:new T.Color(),ground:new T.Color(),grass:new T.Color(),
  sky:[0,0,0,0,0,0].map(()=>new T.Color())};
const lerpN=(a,b,t)=>a+(b-a)*t;
function applyState(A,B,t){
  const az=lerpN(A.sunAz,B.sunAz,t), el=lerpN(A.sunEl,B.sunEl,t);
  const D=90,ce=Math.cos(el),se=Math.sin(el);
  key.position.set(D*ce*Math.sin(az),6+D*se,D*ce*Math.cos(az));
  const ext=22+34*Math.cos(el),c=key.shadow.camera;
  c.left=-34;c.right=34;c.top=ext;c.bottom=-ext;c.updateProjectionMatrix();
  key.color.copy(CUR.sun.copy(A.sunC).lerp(B.sunC,t));
  key.intensity=lerpN(A.sunI,B.sunI,t);
  hemi.color.copy(CUR.hemiS.copy(A.hemiS).lerp(B.hemiS,t));
  hemi.groundColor.copy(CUR.hemiG.copy(A.hemiG).lerp(B.hemiG,t));
  hemi.intensity=lerpN(A.hemiI,B.hemiI,t);
  amb.color.copy(CUR.amb.copy(A.ambC).lerp(B.ambC,t));amb.intensity=lerpN(A.ambI,B.ambI,t);
  fill.color.copy(CUR.fill.copy(A.fillC).lerp(B.fillC,t));fill.intensity=lerpN(A.fillI,B.fillI,t);
  scene.fog.color.copy(CUR.fog.copy(A.fog).lerp(B.fog,t));
  scene.fog.near=lerpN(A.fogN,B.fogN,t);scene.fog.far=lerpN(A.fogF,B.fogF,t);
  terrainMat.color.copy(CUR.ground.copy(A.ground).lerp(B.ground,t));
  stoneMat.color.copy(CUR.ground).multiplyScalar(0.50);
  grassMesh.material.color.copy(CUR.grass.copy(A.grass).lerp(B.grass,t));
  for(let i=0;i<6;i++)CUR.sky[i].copy(A.sky[i]).lerp(B.sky[i],t);
  paintSky(CUR.sky);
  const st=lerpN(A.stars,B.stars,t);
  starLayers.forEach(m=>{m.opacity=st;m.visible=st>0.005;});
  wxApply();                     /* weather is a modifier, never a preset */
}
let themeIdx=0,themeMix=1,themeFrom=null,themeTo=null,themeE=1;
function applyTheme(i,instant){
  const prev=themeTo;
  themeIdx=((i%THEMES.length)+THEMES.length)%THEMES.length;
  const th=THEMES[themeIdx],root=document.documentElement;
  for(const k in th.css)root.style.setProperty('--'+k,th.css[k]);
  document.getElementById('timeBtn').textContent='TIME / '+th.id;
  themeTo=themeState(th);
  if(instant||!prev){themeFrom=themeTo;themeMix=1;}
  else{
    /* freeze the current interpolated look as the new starting point, so a
       switch mid-transition never jumps */
    const A=Object.assign({},themeFrom),B=prev,t=themeMix;
    A.sunAz=lerpN(A.sunAz,B.sunAz,t);A.sunEl=lerpN(A.sunEl,B.sunEl,t);
    A.sunC=A.sunC.clone().lerp(B.sunC,t);A.sunI=lerpN(A.sunI,B.sunI,t);
    A.hemiS=A.hemiS.clone().lerp(B.hemiS,t);A.hemiG=A.hemiG.clone().lerp(B.hemiG,t);
    A.hemiI=lerpN(A.hemiI,B.hemiI,t);
    A.ambC=A.ambC.clone().lerp(B.ambC,t);A.ambI=lerpN(A.ambI,B.ambI,t);
    A.fillC=A.fillC.clone().lerp(B.fillC,t);A.fillI=lerpN(A.fillI,B.fillI,t);
    A.fog=A.fog.clone().lerp(B.fog,t);A.fogN=lerpN(A.fogN,B.fogN,t);A.fogF=lerpN(A.fogF,B.fogF,t);
    A.ground=A.ground.clone().lerp(B.ground,t);A.grass=A.grass.clone().lerp(B.grass,t);
    A.sky=A.sky.map((c,i2)=>c.clone().lerp(B.sky[i2],t));
    A.stars=lerpN(A.stars,B.stars,t);
    themeFrom=A;themeMix=0;
  }
  themeE=themeMix;
  applyState(themeFrom,themeTo,themeMix);
}

/* ------------------------------------------------------------------ *
 * 8.  camera, controls, loop
 * ------------------------------------------------------------------ */
let orbAz=0.35,orbEl=0.012,curAz=0.35,curEl=0.012,zoomT=1,zoom=1;
const CAM_D=80,CAM_H=3.6,UNITS_TALL=16,LOOK_Y=2.0;
const EL_MIN=-0.004,EL_MAX=0.20,ZMIN=0.6,ZMAX=2.4;
function placeCamera(k){
  curAz+=(orbAz-curAz)*k;
  curEl+=(Math.max(EL_MIN,Math.min(EL_MAX,orbEl))-curEl)*k;
  zoom+=(zoomT-zoom)*k;
  const ce=Math.cos(curEl),se=Math.sin(curEl);
  camera.position.set(CAM_D*ce*Math.sin(curAz),CAM_H+CAM_D*se,CAM_D*ce*Math.cos(curAz));
  camera.lookAt(0,LOOK_Y,0);
  camera.fov=2*Math.atan((UNITS_TALL/2)/CAM_D/zoom)*180/Math.PI;
  camera.updateProjectionMatrix();
  /* far enough ahead that no blade is close enough to the lens to become a
     wall across the bottom of the frame */
  const fx=-Math.sin(curAz),fz=-Math.cos(curAz),CELL=2;
  const gx=Math.round((camera.position.x+fx*GRASS_AHEAD)/CELL)*CELL;
  const gz=Math.round((camera.position.z+fz*GRASS_AHEAD)/CELL)*CELL;
  grassMesh.position.x=gx;grassMesh.position.z=gz;
  grassUni.uOrigin.value.set(gx,gz);
  key.target.position.set(0,0,0);key.target.updateMatrixWorld();
}
function layout(){
  const w=innerWidth,h=innerHeight;
  renderer.setSize(w,h,false);
  camera.aspect=w/h;placeCamera(1);
}
addEventListener('resize',layout);
/* an embedded or background browser view can report a zero-size viewport at
   load, and a resize event never comes. Re-layout whenever the size the page
   reports stops matching the size the renderer was built for. */
let _lw=0,_lh=0;
function checkSize(){
  const w=innerWidth,h=innerHeight;
  if(w>0&&h>0&&(w!==_lw||h!==_lh)){_lw=w;_lh=h;layout();}
}

const ptrs=new Map();
let dragging=false,lastX=0,lastY=0,pinchD=0,pinchZ=1;
const dist=()=>{const a=[...ptrs.values()];return Math.hypot(a[0].x-a[1].x,a[0].y-a[1].y);};
cvs.addEventListener('pointerdown',e=>{
  ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
  try{cvs.setPointerCapture(e.pointerId);}catch(_){}
  if(ptrs.size===2){dragging=false;pinchD=dist();pinchZ=zoomT;return;}
  dragging=true;lastX=e.clientX;lastY=e.clientY;cvs.classList.add('drag');
});
cvs.addEventListener('pointermove',e=>{
  if(ptrs.has(e.pointerId))ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
  if(ptrs.size>=2){const d=dist();if(pinchD>8)zoomT=Math.max(ZMIN,Math.min(ZMAX,pinchZ*(d/pinchD)));return;}
  if(!dragging)return;
  orbAz-=(e.clientX-lastX)*0.005;
  orbEl=Math.max(EL_MIN,Math.min(EL_MAX,orbEl-(e.clientY-lastY)*0.0032));
  lastX=e.clientX;lastY=e.clientY;
});
function end(e){
  if(e&&ptrs.has(e.pointerId))ptrs.delete(e.pointerId);
  if(ptrs.size<2)pinchD=0;
  if(ptrs.size===0){dragging=false;cvs.classList.remove('drag');}
  else{const a=[...ptrs.values()][0];lastX=a.x;lastY=a.y;dragging=true;}
}
cvs.addEventListener('pointerup',end);
cvs.addEventListener('pointercancel',end);
cvs.addEventListener('wheel',e=>{
  e.preventDefault();
  const d=e.deltaMode===1?e.deltaY*16:e.deltaY;
  zoomT=Math.max(ZMIN,Math.min(ZMAX,zoomT*Math.exp(-d*0.0016)));
},{passive:false});

document.getElementById('timeBtn').addEventListener('click',()=>applyTheme(themeIdx+1));
document.getElementById('wxBtn').addEventListener('click',()=>applyWeather(wxIdx+1));
document.getElementById('strikeBtn').addEventListener('click',()=>strike());

const statEl=document.getElementById('stat');
let frames=0,acc=0,fps=0;
applyWeather(0,true);applyTheme(0,true);layout();
let prev=performance.now();
(function frame(now){
  const dt=Math.min(0.05,(now-prev)/1000);prev=now;
  checkSize();
  if(themeMix<1){
    themeMix=Math.min(1,themeMix+dt/1.25);
    const e=themeMix<.5?2*themeMix*themeMix:1-Math.pow(-2*themeMix+2,2)/2;
    themeE=e;applyState(themeFrom,themeTo,e);
  }
  grassUni.uTime.value=now*0.001;
  stepWeather(dt);
  placeCamera(1-Math.pow(0.0016,dt));
  renderer.render(scene,camera);
  frames++;acc+=dt;
  if(acc>0.5){fps=Math.round(frames/acc);frames=0;acc=0;
    const info=renderer.info.render;
    statEl.textContent=fps+' fps\n'+info.triangles.toLocaleString()+' triangles\n'+
      info.calls+' draw calls';
    statEl.style.whiteSpace='pre-line';}
  requestAnimationFrame(frame);
})(performance.now());

/* headless hooks, so the demo can be verified without a human */
window.__theme=i=>{applyTheme(i,true);renderer.render(scene,camera);};
window.__wx=i=>{applyWeather(i,true);renderer.render(scene,camera);};
window.__strike=()=>strike();
window.__bliz=v=>{blizT=BLIZ[0]+BLIZ[1]+v*BLIZ[2];};
window.__pack=v=>{snowPack=v;applyState(themeFrom,themeTo,themeE);};
window.__wxDbg=()=>({wx:WEATHER[wxIdx].id,bolt:+boltK.toFixed(3),bliz:+blizK.toFixed(3),
  pack:+snowPack.toFixed(3),rainN:RAIN.geo.drawRange.count,snowN:SNOW.geo.drawRange.count,
  fogF:Math.round(scene.fog.far)});
window.__stats=()=>({fps,tri:renderer.info.render.triangles,calls:renderer.info.render.calls,
  grass:grassMesh.count,theme:THEMES[themeIdx].id,weather:WEATHER[wxIdx].id});
window.__scene=scene;window.__camera=camera;window.__renderer=renderer;
})();
</script>
</body>
</html>

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Meng To
Publisher
Meng To (Community)
Source
MengTo/Skills · agent-skills/web-design/threejs-weather · commit 5ea1661
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Meng To or Meng To.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download threejs-weather.zip