• 01 - Games
  • 02 - Creative Instruments & Explorers
  • 03 - Language, Signals & Text
  • 04 - Developer & Web Utilities
  • 05 - Generators & Data
  • 06 - Colour Theory
  • 07 - Music 26
  • 08 - 3D, Shaders & Visuals
ARCHIVE
  • Locust
  • Butterfly
  • Cockroach
  • Spider
  • Scorpion
  • Dragon
  • Brazilian Treehopper
  • Tardigrade
  • Diatoms
  • Bumblebee
  • Wasp
  • Hammerhead Worm
  • Giraffe Weevil
  • Trilobite Beetle

DIATOMS SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThreeJS: Diatoms</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  html, body { height: 100%; overflow: hidden; background: linear-gradient(#1d6b86 0%, #0b3a58 30%, #06223a 60%, #020a16 100%); }
  #c { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; }
  #c:active { cursor: grabbing; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<script>
{
"use strict";
if (typeof THREE === 'undefined') throw new Error('three missing');
const T = THREE, TAU = Math.PI*2;
const V3 = (x=0,y=0,z=0) => new T.Vector3(x,y,z);
const clamp = (x,a,b) => Math.max(a, Math.min(b, x));
const lerp = (a,b,t) => a + (b-a)*t;
const smooth = t => { t = clamp(t,0,1); return t*t*(3-2*t); };
let seed = 161803;
const rnd = () => (seed = (seed*16807) % 2147483647, (seed-1)/2147483646);
const rr = (a,b) => a + (b-a)*rnd();
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const UP = V3(0,1,0), DS = T.DoubleSide;
const lin = h => new T.Color(h).convertSRGBToLinear();

/* =====================================================================
   RENDERER / SCENE  (the sunlit upper ocean)
   ===================================================================== */
const canvas = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas, antialias:true, alpha:true, powerPreference:'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputEncoding = T.sRGBEncoding;
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const ANISO = renderer.capabilities.getMaxAnisotropy();
const scene = new T.Scene();
const FOGC = 0x0a3048;
scene.fog = new T.FogExp2(FOGC, 0.034);
const camera = new T.PerspectiveCamera(45, innerWidth/innerHeight, 0.05, 300);

(function(){
  const c=document.createElement('canvas'); c.width=1024; c.height=512; const x=c.getContext('2d');
  const g=x.createLinearGradient(0,0,0,512); g.addColorStop(0,'#bff4ff'); g.addColorStop(.25,'#3fa6c8'); g.addColorStop(.5,'#0c4a6a'); g.addColorStop(1,'#020c1a');
  x.fillStyle=g; x.fillRect(0,0,1024,512);
  [[220,110,200,'#7a55ff',.5],[780,90,220,'#22d3ff',.5],[540,300,260,'#ff3fa4',.35],[960,240,200,'#ffd36e',.35],[80,330,240,'#2affc2',.3],[520,40,120,'#ffffff',.7]].forEach(b=>{
    const rg=x.createRadialGradient(b[0],b[1],0,b[0],b[1],b[2]); rg.addColorStop(0,b[3]); rg.addColorStop(1,'rgba(0,0,0,0)'); x.globalAlpha=b[4]; x.fillStyle=rg; x.beginPath(); x.arc(b[0],b[1],b[2],0,7); x.fill(); });
  const tex=new T.CanvasTexture(c); tex.mapping=T.EquirectangularReflectionMapping; tex.encoding=T.sRGBEncoding;
  const pm=new T.PMREMGenerator(renderer); pm.compileEquirectangularShader(); scene.environment=pm.fromEquirectangular(tex).texture; pm.dispose(); tex.dispose();
})();

/* =====================================================================
   IRIDESCENT GLASS (silica frustules: hue cycles with time and view angle; alpha from the lace pattern)
   Data textures: R = brightness, G = hue offset, B = film strength, A = alpha.
   ===================================================================== */
const U_TIME = { value: 0 };
const HSL_GLSL = `
vec3 hsl2rgb(vec3 c){ vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.,4.,2.),6.)-3.)-1.,0.,1.);
  return c.z + c.y*(rgb-0.5)*(1.0-abs(2.0*c.z-1.0)); }
`;
function iriMat(o={}){
  const m = new T.MeshStandardMaterial({ color:0xffffff, roughness:o.rough??.12, metalness:o.metal??.6, side:o.side??DS, envMapIntensity:o.env??1.6,
    transparent:o.transparent??true, depthWrite:o.depthWrite??false });
  m.defines = {};
  if (o.pat){ m.map = o.pat; m.defines.USE_PAT = ''; }
  if (o.bump){ m.bumpMap = o.bump; m.bumpScale = o.bumpScale ?? .002; }
  const u = { uTime:U_TIME, uHue:{value:o.hue??0}, uSat:{value:o.sat??.85}, uLight:{value:o.light??.58}, uIri:{value:o.iri??1}, uFilm:{value:o.film??.8},
    uAlpha:{value:o.alpha??1}, uRimA:{value:o.rimA??.45}, uGlow:{value:o.glow??.06} };
  m.userData.u=u;
  m.onBeforeCompile = sh => {
    Object.assign(sh.uniforms, u);
    sh.fragmentShader = 'uniform float uTime; uniform float uHue; uniform float uSat; uniform float uLight; uniform float uIri; uniform float uFilm; uniform float uAlpha; uniform float uRimA; uniform float uGlow;\n' + HSL_GLSL +
      sh.fragmentShader.replace('#include <map_fragment>', `
#ifdef USE_PAT
  vec4 patS = texture2D(map, vUv);
#else
  vec4 patS = vec4(0.5263, 0.0, 1.0, 0.5);
#endif
  diffuseColor.a *= patS.a * uAlpha;`).replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
  {
    float ndv = clamp(abs(dot(normal, normalize(vViewPosition))), 0.0, 1.0);
    float iriS = patS.b * uIri;
    float h = fract(uTime*0.05 + uHue + patS.g + (1.0-ndv)*uFilm*iriS);
    float L = clamp(uLight * patS.r * 1.9, 0.0, 0.88);
    vec3 c = pow(hsl2rgb(vec3(h, uSat*(0.3+0.7*patS.b), L)), vec3(2.2));
    diffuseColor.rgb = c;
    diffuseColor.a = clamp(diffuseColor.a + pow(1.0-ndv, 2.0)*uRimA, 0.0, 1.0) * uAlpha;
    metalnessFactor = mix(metalnessFactor, 0.9, iriS*0.5);
    roughnessFactor = mix(roughnessFactor, 0.08, iriS*0.45);
    totalEmissiveRadiance += c * (0.22 * iriS * pow(1.0-ndv, 1.5) + uGlow);
  }`);
  };
  m.customProgramCacheKey = () => 'iri' + (o.pat?'p':'') + (o.bump?'b':'');
  return m;
}

/* =====================================================================
   HELPERS
   ===================================================================== */
function makeCanvas(w,h,draw){ const c=document.createElement('canvas'); c.width=w; c.height=h; draw(c.getContext('2d'),w,h); return c; }
function dataTex(c){ const t=new T.CanvasTexture(c); t.anisotropy=ANISO; return t; }
const D = (r,g,b,a=1) => `rgba(${Math.round(clamp(r,0,1)*255)},${Math.round(clamp(g,0,1)*255)},${Math.round(clamp(b,0,1)*255)},${a})`;
const SPH = new T.SphereGeometry(1, 24, 18), SPH_LO = new T.SphereGeometry(1, 10, 8);
const CONE = new T.ConeGeometry(1,1,6).translate(0,.5,0);
const _q = new T.Quaternion(), _m = new T.Matrix4(), _v=V3(), _w=V3(), _x=V3(), _y=V3(), _z=V3();
function mesh(geo,mat,parent,pos,scl){ const m=new T.Mesh(geo,mat); if(pos) m.position.copy(pos); if(scl!==undefined) (typeof scl==='number'?m.scale.setScalar(scl):m.scale.copy(scl)); parent&&parent.add(m); return m; }
function sweep(pts,rf,seg=16,rad=6){ const c=new T.CatmullRomCurve3(pts), g=new T.TubeGeometry(c,seg,1,rad,false), p=g.attributes.position, P=V3(), Q=V3();
  for(let i=0;i<=seg;i++){ c.getPointAt(i/seg,P); const r=rf(i/seg); for(let j=0;j<=rad;j++){ const k=i*(rad+1)+j; Q.fromBufferAttribute(p,k).sub(P).multiplyScalar(r).add(P); p.setXYZ(k,Q.x,Q.y,Q.z); } }
  g.computeVertexNormals(); return g; }
function mergeGeos(list){ let pos=[],nor=[],uv=[],idx=[],off=0; for(const g0 of list){ const g=g0.index?g0:g0; const p=g.attributes.position, n=g.attributes.normal, u=g.attributes.uv;
    pos.push(...p.array); nor.push(...n.array); uv.push(...(u?u.array:new Float32Array(p.count*2))); if(g.index) idx.push(...Array.from(g.index.array,i=>i+off)); else for(let i=0;i<p.count;i++) idx.push(i+off); off+=p.count; }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setAttribute('normal',new T.Float32BufferAttribute(nor,3)); g.setAttribute('uv',new T.Float32BufferAttribute(uv,2)); g.setIndex(idx); return g; }

/* =====================================================================
   THE OCEAN: rippling surface far above, light shafts, marine snow
   ===================================================================== */
{ const bg=new T.CanvasTexture(makeCanvas(16,512,(g,W,H)=>{ const gr=g.createLinearGradient(0,0,0,H); gr.addColorStop(0,'#2a8aa8'); gr.addColorStop(.3,'#0f4e6e'); gr.addColorStop(.6,'#082c46'); gr.addColorStop(1,'#020a18'); g.fillStyle=gr; g.fillRect(0,0,W,H); }));
  bg.encoding=T.sRGBEncoding; scene.background=bg; }
const SURF_Y=16;
const surfMat=new T.ShaderMaterial({ uniforms:{uTime:U_TIME}, side:DS, transparent:true, depthWrite:false, fog:false,
  vertexShader:'varying vec2 vP; void main(){ vP=position.xz; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }',
  fragmentShader:`uniform float uTime; varying vec2 vP;
    void main(){ vec2 p=vP*.09; float c=0.; for(int i=0;i<4;i++){ float fi=float(i); vec2 q=p*(1.+fi*.7)+vec2(sin(uTime*.25+fi*1.7),cos(uTime*.2+fi*2.3));
      c+=pow(abs(sin(q.x*3.+sin(q.y*2.1+uTime*.6))*sin(q.y*3.+sin(q.x*1.7-uTime*.5))),4.); }
      float r=length(vP)/70.; vec3 col=mix(vec3(.55,.95,1.),vec3(.06,.3,.45),smoothstep(.0,1.,r)); col+=vec3(.9,1.,1.)*c*.35*(1.-r);
      gl_FragColor=vec4(col,(1.-smoothstep(.6,1.,r))*.95); }`});
const surf=new T.Mesh(new T.PlaneGeometry(160,160,1,1).rotateX(Math.PI/2),surfMat); surf.position.y=SURF_Y; scene.add(surf);
// god rays: soft additive shafts hanging from the surface
const rayMat=new T.ShaderMaterial({ uniforms:{uTime:U_TIME}, transparent:true, depthWrite:false, blending:T.AdditiveBlending, side:DS, fog:false,
  vertexShader:'varying float vY; varying vec3 vN; varying vec3 vV; void main(){ vY=uv.y; vec4 w=modelMatrix*vec4(position,1.); vN=normalize(mat3(modelMatrix)*normal); vV=normalize(cameraPosition-w.xyz); gl_Position=projectionMatrix*viewMatrix*w; }',
  fragmentShader:'uniform float uTime; varying float vY; varying vec3 vN; varying vec3 vV; void main(){ float e=pow(abs(dot(vN,vV)),2.5); float f=smoothstep(0.,.55,vY)*(1.-smoothstep(.85,1.,vY)); gl_FragColor=vec4(vec3(.55,.9,1.)*e*f*.06,1.); }'});
const rays=[]; for(let i=0;i<9;i++){ const r=new T.Mesh(new T.CylinderGeometry(rr(.8,1.6),rr(2.2,4),44,24,1,true),rayMat); r.position.set(rr(-14,14),SURF_Y-20,rr(-14,10)); r.rotation.set(rr(-.12,.12),0,rr(-.15,.15)); r.userData.ph=rnd()*TAU; scene.add(r); rays.push(r); }
// marine snow
const SN=1600, snPos=new Float32Array(SN*3); for(let i=0;i<SN;i++) snPos.set([rr(-22,22),rr(-14,14),rr(-22,22)],i*3);
const snGeo=new T.BufferGeometry(); snGeo.setAttribute('position',new T.BufferAttribute(snPos,3));
const dotT=new T.CanvasTexture(makeCanvas(64,64,x=>{ const gr=x.createRadialGradient(32,32,0,32,32,32); gr.addColorStop(0,'rgba(255,255,255,.95)'); gr.addColorStop(.45,'rgba(255,255,255,.3)'); gr.addColorStop(1,'rgba(255,255,255,0)'); x.fillStyle=gr; x.fillRect(0,0,64,64); }));
scene.add(new T.Points(snGeo,new T.PointsMaterial({size:.07,map:dotT,color:0xd8f2ff,transparent:true,opacity:.55,depthWrite:false})));

/* =====================================================================
   FRUSTULE PATTERNS
   ===================================================================== */
// lathe valve profile: s ∈ [0,1] — face (0–.75), rounded margin (.75–.82), mantle (.82–1)
function valveProfile(R,dome,mantle,n=48){ const pts=[]; const rc=.08*R;
  for(let i=0;i<=n;i++){ const s=i/n; let r,y;
    if(s<=.75){ r=s/.75*(R-rc); y=dome*(1-(r/R)**2)+mantle*0; }
    else if(s<=.82){ const a=(s-.75)/.07*Math.PI/2, y0=dome*(1-((R-rc)/R)**2); r=R-rc+Math.sin(a)*rc; y=y0-(1-Math.cos(a))*rc; }
    else { const y0=dome*(1-((R-rc)/R)**2)-rc; r=R; y=y0-(s-.82)/.18*mantle; }
    pts.push(new T.Vector2(Math.max(r,.001),y)); }
  return pts; }
function valveGeo(R,dome,mantle,seg=96){ return new T.LatheGeometry(valveProfile(R,dome,mantle),seg); }
// lace texture for a centric valve: x = angle, y = profile (canvas top = mantle edge)
function valveTex(W,H,o){ return makeCanvas(W,H,(g)=>{
  const R=o.R, faceR=R*.92, spacing=o.spacing, hole=o.hole, sectors=o.sectors;
  g.fillStyle=D(.55,0,1,.55); g.fillRect(0,0,W,H);
  const Y=s=>(1-s)*H;
  // central hyaline area and annulus
  g.fillStyle=D(.75,.05,1,.7); g.fillRect(0,Y(.07),W,Y(0)-Y(.07));
  g.fillStyle=D(.95,.1,1,.85); g.fillRect(0,Y(.075),W,3);
  // rows of hexagonally packed areolae (perforations with a fine sieve membrane)
  let row=0;
  for(let s=.09;s<.72;s+=spacing*.75/faceR*.88){ const r=s/.75*faceR, n=Math.max(6,Math.round(TAU*r/spacing)), rx=hole/(TAU*r)*W, ry=hole*.75/faceR*H*1.0;
    for(let k=0;k<n;k++){ const a=(k+(row%2?.5:0))/n; if(sectors){ const sa=(a*sectors)%1; if(sa<.06||sa>.94) continue; }
      const x=a*W, y=Y(s);
      g.globalCompositeOperation='destination-out'; g.fillStyle='rgba(0,0,0,.72)'; g.beginPath(); g.ellipse(x,y,rx,ry,0,0,TAU); g.fill();
      g.globalCompositeOperation='source-over'; g.strokeStyle=D(.92,.06,1,.9); g.lineWidth=Math.max(1,ry*.35); g.beginPath(); g.ellipse(x,y,rx*1.08,ry*1.08,0,0,TAU); g.stroke();
      if(o.cribra){ g.fillStyle=D(.85,.1,1,.3); for(let q=0;q<3;q++){ g.beginPath(); g.arc(x+(q-1)*rx*.45,y,Math.max(.6,ry*.18),0,TAU); g.fill(); } } }
    row++; }
  // radial ribs between sectors
  if(sectors) for(let k=0;k<sectors;k++){ const x=k/sectors*W; g.fillStyle=D(1,.12,1,.95); g.fillRect(x-W/sectors*.035,Y(.74),W/sectors*.07,Y(.08)-Y(.74)); }
  // marginal ring, then mantle with vertical striae
  g.fillStyle=D(1,.1,1,.95); g.fillRect(0,Y(.8),W,Y(.73)-Y(.8));
  for(let k=0;k<W;k+=W/(o.striae||180)){ g.fillStyle=D(.35,.05,1,.5); g.fillRect(k,0,2,Y(.84)); }
  g.fillStyle=D(1,.15,1,.95); g.fillRect(0,0,W,Y(.985));
}); }
const girdleTex=(n)=>makeCanvas(512,128,(g,W,H)=>{ g.fillStyle=D(.5,0,1,.42); g.fillRect(0,0,W,H);
  for(let k=0;k<n;k++){ const y=(k+.5)/n*H; g.fillStyle=D(.95,.08,1,.85); g.fillRect(0,y-1.5,W,3); }
  for(let x=0;x<W;x+=3){ g.fillStyle=D(.7,.04,1,.35); g.fillRect(x,0,1,H); } });
// pennate (boat-shaped) valve: x along the apical axis, y across; striae with a central raphe
const pennC=makeCanvas(512,128,(g,W,H)=>{ g.fillStyle=D(.55,0,1,.6); g.fillRect(0,0,W,H);
  for(let x=10;x<W-10;x+=6){ for(let y=6;y<H-6;y+=6){ if(Math.abs(y-H/2)<9) continue; g.globalCompositeOperation='destination-out'; g.fillStyle='rgba(0,0,0,.6)'; g.beginPath(); g.arc(x,y+(Math.abs(y-H/2)*.06),1.6,0,TAU); g.fill(); g.globalCompositeOperation='source-over'; } }
  g.fillStyle=D(1,.1,1,.95); g.fillRect(16,H/2-2,W*.45-16,4); g.fillRect(W*.55,H/2-2,W*.45-16,4);
  g.beginPath(); g.arc(W/2,H/2,9,0,TAU); g.fill(); [16,W-16].forEach(x=>{ g.beginPath(); g.arc(x,H/2,5,0,TAU); g.fill(); }); });
const pennT=dataTex(pennC);

/* =====================================================================
   THE HERO: a large centric diatom that divides
   each daughter: epivalve + epicingulum, hypovalve + hypocingulum, parietal chloroplasts, nucleus
   ===================================================================== */
const HR=1.7, HDOME=.22, HMANT=.24, HL=.46;
const heroValveC=valveTex(2048,512,{R:HR,spacing:.075,hole:.026,sectors:24,cribra:true,striae:260});
const heroValveT=dataTex(heroValveC);
const heroGirT=dataTex(girdleTex(7)); heroGirT.wrapS=T.RepeatWrapping; heroGirT.repeat.x=3;
function heroMats(){ return { valve:iriMat({pat:heroValveT,hue:.52,light:.6,rimA:.35}),
  gir:iriMat({pat:heroGirT,hue:.6,light:.58,rimA:.5}), rib:iriMat({hue:.48,light:.72,alpha:.9,rimA:.1}),
  chl:new T.MeshStandardMaterial({color:lin(0xa8731c),roughness:.45,emissive:lin(0x5a3206),emissiveIntensity:.55,transparent:true,opacity:.92}),
  nuc:new T.MeshPhysicalMaterial({color:lin(0xd8e0c8),roughness:.3,transparent:true,opacity:.55,clearcoat:.5}),
  nucl:new T.MeshStandardMaterial({color:lin(0x7a5a8a),roughness:.4,transparent:true}),
  strand:new T.MeshStandardMaterial({color:lin(0xc8d8c0),transparent:true,opacity:.35,depthWrite:false}) }; }
const HMA=heroMats(), HMB=heroMats();
function fadeMats(H,f){ H.valve.userData.u.uAlpha.value=f; H.gir.userData.u.uAlpha.value=f; H.rib.userData.u.uAlpha.value=.9*f; H.chl.opacity=.92*f; H.nuc.opacity=.55*f; H.nucl.opacity=f; H.strand.opacity=.35*f; }
const hValveGeo=valveGeo(HR,HDOME,HMANT,128);
// raised radial ribs + marginal processes, merged with the valve's own decoration
const ribGeo=(()=>{ const list=[]; for(let k=0;k<24;k++){ const a=k/24*TAU, pts=[]; for(let i=0;i<=8;i++){ const r=HR*(.1+.82*i/8); pts.push(V3(Math.cos(a)*r,HDOME*(1-(r/HR)**2)+.012,Math.sin(a)*r)); }
    list.push(sweep(pts,t=>.018*(1-.4*t)+.006,12,4)); }
  for(let k=0;k<48;k++){ const a=k/48*TAU, r=HR*.97, y=HDOME*(1-(.92)**2)-.02; const c=CONE.clone().scale(.018,.09,.018); c.applyMatrix4(new T.Matrix4().compose(V3(Math.cos(a)*r,y,Math.sin(a)*r),new T.Quaternion().setFromUnitVectors(UP,V3(Math.cos(a),.9,Math.sin(a)).normalize()),V3(1,1,1))); list.push(c); }
  list.push(new T.TorusGeometry(HR*.06*1.2,.02,6,24).rotateX(Math.PI/2).translate(0,HDOME+.01,0));
  return mergeGeos(list); })();
function makeHeroCell(HM){
  const g=new T.Group();
  const top=new T.Group(), bot=new T.Group(); g.add(top,bot); bot.rotation.x=Math.PI;
  [top,bot].forEach(v=>{ const m=mesh(hValveGeo,HM.valve,v); m.renderOrder=6; const r=mesh(ribGeo,HM.rib,v); r.renderOrder=7; });
  const epi=mesh(new T.CylinderGeometry(HR*.985,HR*.985,1,96,1,true).translate(0,-.5,0),HM.gir,g); epi.renderOrder=5;
  const hypo=mesh(new T.CylinderGeometry(HR*.955,HR*.955,1,96,1,true).translate(0,.5,0),HM.gir,g); hypo.renderOrder=4;
  // parietal chloroplasts: lobed plates lying against the valve faces and girdle
  const NC=46, chl=new T.InstancedMesh(SPH_LO,HM.chl,NC), cp=[];
  for(let i=0;i<NC;i++){ const onFace=rnd()<.55, a=rnd()*TAU; cp.push(onFace?{a,r:rr(.25,.85),y:rr(.55,.85),face:1,s:rr(.12,.2),rot:rnd()*TAU}:{a,r:.88,y:rr(-.7,.7),face:0,s:rr(.12,.2),rot:rnd()*TAU}); }
  chl.renderOrder=2; g.add(chl);
  const nuc=mesh(SPH,HM.nuc,g,null,.26); nuc.renderOrder=3; mesh(SPH_LO,HM.nucl,nuc,V3(.25,.2,0),.32);
  // cytoplasmic strands from nucleus to the periphery
  const strands=mesh(mergeGeos(Array.from({length:12},(v,k)=>{ const a=k/12*TAU+rr(-.2,.2); return sweep([V3(),V3(Math.cos(a)*.6,rr(-.1,.1),Math.sin(a)*.6),V3(Math.cos(a)*1.4,rr(-.2,.2),Math.sin(a)*1.4)],t=>.012,10,4); })),
    HM.strand,g);
  return {g,top,bot,epi,hypo,chl,cp,nuc,strands};
}
const hero=new T.Group(); scene.add(hero);
const cellA=makeHeroCell(HMA), cellB=makeHeroCell(HMB); hero.add(cellA.g,cellB.g);
function layoutCell(C,o,showTop,showBot,gE,gH,half,dirSign){
  C.top.position.y=half; C.bot.position.y=-half;
  C.top.scale.set(showTop,1,showTop); C.bot.scale.set(showBot,1,showBot); C.top.visible=showTop>.01; C.bot.visible=showBot>.01;
  const yTop=half+HDOME*(1-.92**2)-.08*HR-.0, yBot=-yTop;
  C.epi.position.y=yTop; C.epi.scale.y=Math.max(.001,gE); C.epi.visible=gE>.01;
  C.hypo.position.y=yBot; C.hypo.scale.y=Math.max(.001,gH); C.hypo.visible=gH>.01;
  for(let i=0;i<C.cp.length;i++){ const c=C.cp[i];
    if(c.face){ const sideY=(c.y>0?1:-1); if((sideY>0&&showTop<.5&&dirSign>0)||(sideY<0&&showBot<.5&&dirSign<0)){}
      const fy=(c.a>Math.PI?1:-1); const yy=fy>0?half*.55+.08:-(half*.55+.08);
      _v.set(Math.cos(c.a)*c.r*HR*.9,yy,Math.sin(c.a)*c.r*HR*.9); _q.setFromEuler(new T.Euler(0,c.rot,0)); _w.set(c.s*1.25,.035,c.s); }
    else { _v.set(Math.cos(c.a)*HR*.86,c.y*half*.8,Math.sin(c.a)*HR*.86); _q.setFromUnitVectors(UP,_w.set(Math.cos(c.a),0,Math.sin(c.a))); _w.set(c.s,.035,c.s*1.4); }
    _m.compose(_v,_q,_w); C.chl.setMatrixAt(i,_m); }
  C.chl.instanceMatrix.needsUpdate=true;
}

/* =====================================================================
   OTHER DIATOMS
   ===================================================================== */
const smallValveC=valveTex(1024,256,{R:.5,spacing:.05,hole:.018,sectors:0,striae:90}), smallValveT=dataTex(smallValveC);
const smGirT=dataTex(girdleTex(4)); smGirT.wrapS=T.RepeatWrapping; smGirT.repeat.x=2;
const chlMat=new T.MeshStandardMaterial({color:lin(0xa8731c),roughness:.45,emissive:lin(0x5a3206),emissiveIntensity:.5});
function centricCell(R,H,hue,o={}){ // pervalvar axis = local y
  const g=new T.Group(), vm=iriMat({pat:smallValveT,hue,light:.6}), gm=iriMat({pat:smGirT,hue:hue+.06,light:.58});
  const vg=valveGeo(R,R*.12,H*.25,48);
  [1,-1].forEach(s=>{ const v=mesh(vg,vm,g,V3(0,s*H/2,0)); if(s<0) v.rotation.x=Math.PI; v.renderOrder=5; });
  mesh(new T.CylinderGeometry(R,R,H,48,1,true),gm,g).renderOrder=4;
  const n=o.chl??6; for(let k=0;k<n;k++){ const a=k/n*TAU+rnd(); mesh(SPH_LO,chlMat,g,V3(Math.cos(a)*R*.7,rr(-H*.3,H*.3),Math.sin(a)*R*.7),V3(R*.22,R*.06,R*.18)).rotation.set(rr(0,3),rr(0,3),0); }
  return g;
}
function pennateCell(L,W,hue){ // apical axis = local x, valve face = ±y
  const g=new T.Group(), m=iriMat({pat:pennT,hue,light:.6});
  const shape=(u)=>Math.pow(Math.max(0,1-(2*u-1)**2),.55);
  const geo=new T.SphereGeometry(1,40,16); const p=geo.attributes.position, uv=geo.attributes.uv;
  for(let i=0;i<p.count;i++){ const x=p.getX(i), y=p.getY(i), z=p.getZ(i); p.setXYZ(i,x*L/2,y*W*.32,z*W/2*1); uv.setXY(i,(x+1)/2,(z+1)/2); }
  geo.computeVertexNormals(); mesh(geo,m,g).renderOrder=5;
  [-1,1].forEach(s=>mesh(SPH_LO,chlMat,g,V3(0,0,s*W*.22),V3(L*.38,W*.08,W*.12)));
  return g;
}
// --- chains of Chaetoceros (long crossing setae) and Skeletonema (linked by marginal processes),
//     simulated as soft ropes carried by the current
const setaMat=iriMat({hue:.3,light:.7,alpha:.9,rimA:.1,depthWrite:true,transparent:false});
function chaetoCell(hue){ const g=centricCell(.32,.34,hue,{chl:3}); g.scale.set(1,1,.62);
  [1,-1].forEach(s=>[-1,1].forEach(side=>{ const pts=[V3(side*.3,s*.17,0),V3(side*.55,s*.32,0),V3(side*1.0,s*.28,rr(-.1,.1)),V3(side*1.5,s*.05,rr(-.2,.2))];
    mesh(sweep(pts,t=>.016*(1-.6*t)+.004,16,4),setaMat,g); }));
  return g; }
function skelCell(hue){ const g=centricCell(.16,.24,hue,{chl:2});
  for(let k=0;k<10;k++){ const a=k/10*TAU; mesh(new T.CylinderGeometry(.006,.006,.16,4),setaMat,g,V3(Math.cos(a)*.14,.19,Math.sin(a)*.14)); }
  return g; }
const chains=[];
function addChain(n,make,len,ring,yb,a0){ const nodes=[], cells=[];
  const dir=V3(rr(-1,1),rr(-.4,.4),rr(-1,1)).normalize(), c=V3(Math.cos(a0)*ring,yb,Math.sin(a0)*ring);
  for(let i=0;i<=n;i++) nodes.push({p:c.clone().addScaledVector(dir,(i-n/2)*len),v:V3()});
  for(let i=0;i<n;i++){ const cell=make(rr(0,1)); scene.add(cell); cells.push({g:cell,roll:i*.4}); }
  chains.push({nodes,cells,len,ring,yb,a0,w:rr(.02,.05)*(rnd()<.5?1:-1)}); }
for(let i=0;i<3;i++) addChain(7,chaetoCell,.42,rr(5,8),rr(-2.5,3),i/3*TAU+.4);
for(let i=0;i<3;i++) addChain(12,skelCell,.27,rr(4.5,7.5),rr(-3,3),i/3*TAU+1.4);
// --- rigid drifters: Asterionellopsis stars, Thalassionema zigzags, single centrics, Triceratium, pennates
const drifters=[];
function addDrifter(g,ring,yb,a0){ scene.add(g); drifters.push({g,ring,yb,a0,w:rr(.015,.04)*(rnd()<.5?1:-1),spin:V3(rr(-.3,.3),rr(-.3,.3),rr(-.3,.3)),p:V3(Math.cos(a0)*ring,yb,Math.sin(a0)*ring),v:V3()}); }
function star(n,hue){ const g=new T.Group(); for(let k=0;k<n;k++){ const arm=new T.Group(); arm.rotation.z=k/n*TAU; g.add(arm); const c=pennateCell(1.1,.12,hue+k*.03); c.position.x=.62; arm.add(c);
    mesh(SPH_LO,iriMat({hue,light:.66}),arm,V3(.1,0,0),V3(.1,.07,.09)); } return g; }
function zigzag(n,hue){ const g=new T.Group(); let x=0; for(let k=0;k<n;k++){ const c=pennateCell(.8,.1,hue+k*.04); c.position.x=x; c.rotation.z=(k%2?1:-1)*.6; g.add(c); x+=.62; } g.children.forEach(c=>c.position.x-=x/2); return g; }
function triceratium(R,hue){ const g=new T.Group(), m=iriMat({pat:smallValveT,hue,light:.6}); const geo=new T.CylinderGeometry(R,R,R*.4,3,1); mesh(geo,m,g).renderOrder=5;
  for(let k=0;k<3;k++){ const a=k/3*TAU; mesh(SPH_LO,iriMat({hue:hue+.1,light:.7}),g,V3(Math.cos(a)*R,0,Math.sin(a)*R),R*.16); } return g; }
for(let i=0;i<3;i++) addDrifter(star(8,rnd()),rr(6,9),rr(-3,3),rnd()*TAU);
for(let i=0;i<2;i++) addDrifter(zigzag(7,rnd()),rr(6,9),rr(-3,3),rnd()*TAU);
for(let i=0;i<7;i++){ const c=centricCell(rr(.35,.6),rr(.2,.32),rnd()); c.rotation.set(rr(0,3),0,rr(0,3)); const w=new T.Group(); w.add(c); addDrifter(w,rr(4,10),rr(-4,4),rnd()*TAU); }
for(let i=0;i<5;i++) addDrifter(triceratium(rr(.3,.5),rnd()),rr(4,10),rr(-4,4),rnd()*TAU);
for(let i=0;i<8;i++) addDrifter(pennateCell(rr(.6,1.1),rr(.14,.22),rnd()),rr(4,11),rr(-4,4),rnd()*TAU);

/* =====================================================================
   A MARINE SNOW AGGREGATE with raphid diatoms gliding over it and leaving mucilage trails
   ===================================================================== */
const agg=new T.Group(); scene.add(agg);
const AGR=1.05;
const aggGeo=(()=>{ const g=new T.SphereGeometry(1,72,54), p=g.attributes.position, q=V3(); for(let i=0;i<p.count;i++){ q.fromBufferAttribute(p,i); const n=1+.14*Math.sin(q.x*4+q.y*3)+.08*Math.sin(q.z*7+q.x*5)+.05*Math.sin(q.y*11);
  q.multiplyScalar(AGR*n); p.setXYZ(i,q.x,q.y,q.z); } g.computeVertexNormals(); return g; })();
function aggR(d){ return AGR*(1+.14*Math.sin(d.x*4+d.y*3)+.08*Math.sin(d.z*7+d.x*5)+.05*Math.sin(d.y*11)); }
mesh(aggGeo,new T.MeshPhysicalMaterial({color:lin(0xb8d0c0),roughness:.9,transparent:true,opacity:.3,depthWrite:false,side:DS,emissive:lin(0x203028),emissiveIntensity:.4}),agg).renderOrder=1;
(function(){ const N=220, im=new T.InstancedMesh(new T.IcosahedronGeometry(1,0),new T.MeshStandardMaterial({color:0xffffff,roughness:.8}),N), c=new T.Color();
  for(let i=0;i<N;i++){ const d=V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize(), r=aggR(d)*rr(.3,.98), s=rr(.02,.07); _q.setFromEuler(new T.Euler(rr(0,3),rr(0,3),rr(0,3)));
    _m.compose(d.multiplyScalar(r),_q,V3(s,s*rr(.4,1),s*rr(.5,1.5))); im.setMatrixAt(i,_m); c.setHSL(rr(.05,.15),rr(.2,.5),rr(.2,.55)).convertSRGBToLinear(); im.setColorAt(i,c); }
  agg.add(im); })();
mesh(mergeGeos(Array.from({length:40},()=>{ const d=V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize(); const p0=d.clone().multiplyScalar(aggR(d)*rr(.2,.9)); const pts=[p0]; for(let k=0;k<3;k++) pts.push(pts[k].clone().add(V3(rr(-.25,.25),rr(-.25,.25),rr(-.25,.25))));
  return sweep(pts,t=>.008,10,3); })),new T.MeshStandardMaterial({color:lin(0x9a8a6a),roughness:.8}),agg);
const gliders=[], TRAIL=90;
const trailDots=new T.PointsMaterial({size:.09,map:dotT,vertexColors:true,transparent:true,opacity:.9,blending:T.AdditiveBlending,depthWrite:false});
const trailMat=new T.LineBasicMaterial({vertexColors:true,transparent:true,opacity:.85,blending:T.AdditiveBlending,depthWrite:false});
for(let i=0;i<7;i++){ const g=pennateCell(rr(.36,.5),rr(.1,.13),rnd()); agg.add(g);
  const d=V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize(), h=V3(rr(-1,1),rr(-1,1),rr(-1,1)); h.addScaledVector(d,-h.dot(d)).normalize();
  const tg=new T.BufferGeometry(), tp=new Float32Array(TRAIL*3), tc=new Float32Array(TRAIL*3); tg.setAttribute('position',new T.BufferAttribute(tp,3)); tg.setAttribute('color',new T.BufferAttribute(tc,3));
  const line=new T.Line(tg,trailMat); line.frustumCulled=false; agg.add(line);
  const dots=new T.Points(tg,trailDots); dots.frustumCulled=false; agg.add(dots);
  const G={g,d,h,v:rr(.12,.2),dir:1,flip:rr(3,8),tp,tc,tg,n:0,acc:0}; for(let k=0;k<TRAIL;k++){ _v.copy(d).multiplyScalar(aggR(d)+.02); tp.set([_v.x,_v.y,_v.z],k*3); } gliders.push(G); }
const aggState={p:V3(-5.6,-1.6,3.2),rot:V3(.05,.08,.03)};

// oxygen micro-bubbles from photosynthesis
const NBUB=70, bubbles=new T.InstancedMesh(SPH,new T.MeshPhysicalMaterial({color:0xffffff,roughness:0,metalness:0,transmission:0,transparent:true,opacity:.35,clearcoat:1,envMapIntensity:3}),NBUB);
bubbles.frustumCulled=false; scene.add(bubbles); const bub=[]; for(let i=0;i<NBUB;i++) bub.push({p:V3(0,-99,0),s:0,life:0,ph:rnd()*TAU});
let bubI=0; function spawnBubble(p){ const b=bub[bubI]; bubI=(bubI+1)%NBUB; b.p.copy(p); b.s=rr(.025,.06); b.life=1; }

/* lights */
scene.add(new T.HemisphereLight(0xbff0ff,0x062030,.7));
const sun=new T.DirectionalLight(0xfff6e0,1.5); sun.position.set(3,14,4); scene.add(sun);
const rim=new T.PointLight(0x33ccff,2,40); rim.position.set(-8,3,-6); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.6,40); rim2.position.set(8,-2,-5); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1.1,40); glint.position.set(3,5,9); scene.add(glint);
const under=new T.PointLight(0x55ffcc,.7,30); under.position.set(0,-7,3); scene.add(under);

/* =====================================================================
   SIMULATION
   ===================================================================== */
function flow(p,t,out){ return out.set(
  .22*Math.sin(.32*p.y+t*.13)+.14*Math.sin(.21*p.z-t*.07)+.05*Math.sin(.9*p.z+t*.4),
  .1*Math.sin(.3*p.x+t*.11)+.07*Math.cos(.27*p.z+t*.05)-.02,
  .22*Math.sin(.33*p.x-t*.09)+.14*Math.cos(.24*p.y+t*.1)+.05*Math.cos(.8*p.x-t*.35)); }
const div={t:0,phase:'idle'};      // hero division cycle
const CYCLE={idle:9,elong:5,form:6,split:4,drift:7};
let bDrift=V3(), bSpin=V3();
const _f=V3(),_a=V3(),_b=V3(),_c=V3();
function update(dt,t){
  // ---------- the dividing hero
  div.t+=dt; const P=div.phase, s=div.t;
  let o=0, newV=0, gEA=2*HL*.72, gHB=2*HL*.72, gHA=0, gEB=0, sepA=0, sepB=0, fadeB=1;
  if(P==='idle'){ if(s>CYCLE.idle&&!reduceMotion){ div.phase='elong'; div.t=0; } }
  if(P==='elong'){ o=.5*smooth(s/CYCLE.elong); if(s>CYCLE.elong){ div.phase='form'; div.t=0; } }
  if(P==='form'){ o=.5; newV=smooth(s/CYCLE.form); if(s>CYCLE.form){ div.phase='split'; div.t=0; } }
  if(P==='split'){ o=.5; newV=1; sepA=.9*smooth(s/CYCLE.split); sepB=sepA; if(s>CYCLE.split){ div.phase='drift'; div.t=0; bDrift.set(rr(-1,1),-.4,rr(-1,1)).normalize(); bSpin.set(rr(-.6,.6),rr(-.6,.6),rr(-.6,.6)); } }
  if(P==='drift'){ o=.5; newV=1; const k=smooth(s/CYCLE.drift); sepA=.9*(1-k); sepB=.9+k*6; fadeB=1-smooth((s-2)/(CYCLE.drift-2));
    if(s>CYCLE.drift){ div.phase='idle'; div.t=0; } }
  if(P==='elong'||P==='form'){ gEA=gHB=lerp(2*HL*.72,2*(HL+o)+.25,smooth(o/.5)); }
  if(P==='form'){ gHA=gEB=2*HL*.72*newV; }
  if(P==='split'||P==='drift'){ const k=P==='split'?smooth(s/CYCLE.split):1; gEA=gHB=lerp(2*(HL+.5)+.25,2*HL*.72,k); gHA=gEB=2*HL*.72; }
  // A: original epivalve + new hypovalve; B: original hypovalve + new valve
  const idle=P==='idle';
  cellA.g.position.set(0,o+sepA,0); cellB.g.position.set(0,-o-sepB,0);
  if(P==='drift'){ const k=smooth(s/CYCLE.drift); cellB.g.position.addScaledVector(bDrift,k*5); cellB.g.rotation.set(bSpin.x*k*3,bSpin.y*k*3,bSpin.z*k*3); }
  else cellB.g.rotation.set(0,0,0);
  layoutCell(cellA,o,1,idle?0:newV,gEA,gHA,HL,1);
  layoutCell(cellB,o,idle?0:newV,1,gEB,gHB,HL,-1);
  // the two nuclei sit together until the cell elongates, then part; strands follow
  cellA.nuc.position.y=-.0; cellB.nuc.position.y=0;
  [cellA,cellB].forEach(C=>{ C.nuc.scale.setScalar(.26*(1+.04*Math.sin(t*1.3))); });
  fadeMats(HMB,fadeB);
  cellB.g.visible=fadeB>.02||P!=='drift';
  hero.rotation.set(.55+.12*Math.sin(t*.11),t*.06,.2*Math.sin(t*.08)); hero.position.y=.15*Math.sin(t*.2);
  // photosynthetic oxygen bubbles rise from the chloroplasts
  if(rnd()<dt*4){ const C=rnd()<.5||!cellB.g.visible?cellA:cellB, i=(rnd()*C.cp.length)|0; C.chl.getMatrixAt(i,_m); _v.setFromMatrixPosition(_m); C.g.localToWorld(_v); spawnBubble(_v); }
  for(let i=0;i<NBUB;i++){ const b=bub[i]; if(b.life<=0){ _m.makeScale(0,0,0); bubbles.setMatrixAt(i,_m); continue; }
    b.life-=dt*.07; b.p.y+=dt*(.35+b.s*3); b.p.x+=Math.sin(t*3+b.ph)*dt*.05; b.p.z+=Math.cos(t*2.6+b.ph)*dt*.05; const s2=b.s*Math.min(1,(1-b.life)*8);
    _m.compose(b.p,_q.identity(),_v.setScalar(s2)); bubbles.setMatrixAt(i,_m); }
  bubbles.instanceMatrix.needsUpdate=true;

  // ---------- chains: soft ropes carried by the current, gently held around the hero
  for(const C of chains){ const N=C.nodes, aa=C.a0+t*C.w, anchor=_a.set(Math.cos(aa)*C.ring,C.yb+.6*Math.sin(t*.13+C.a0),Math.sin(aa)*C.ring);
    N.forEach((n,i)=>{ flow(n.p,t,_f); _f.multiplyScalar(1+.25*Math.sin(i*.9+t*.7));
      n.v.addScaledVector(_f.sub(n.v),dt*1.5);
      if(i===N.length>>1) n.v.addScaledVector(_b.subVectors(anchor,n.p),dt*.12);
      const d=n.p.length(); if(d<3.4) n.v.addScaledVector(_c.copy(n.p).normalize(),dt*(3.4-d)*1.5);
      n.p.addScaledVector(n.v,dt); });
    for(let it=0;it<4;it++) for(let i=0;i<N.length-1;i++){ const a=N[i].p, b=N[i+1].p; _b.subVectors(b,a); const L=_b.length(), k=(L-C.len)/L*.5; a.addScaledVector(_b,k); b.addScaledVector(_b,-k); }
    // light bending stiffness
    for(let i=1;i<N.length-1;i++){ _c.addVectors(N[i-1].p,N[i+1].p).multiplyScalar(.5); N[i].p.lerp(_c,.08); }
    C.cells.forEach((c,i)=>{ const a=N[i].p, b=N[i+1].p; c.g.position.addVectors(a,b).multiplyScalar(.5); _b.subVectors(b,a).normalize();
      _q.setFromUnitVectors(UP,_b); c.g.quaternion.copy(_q); c.g.rotateY(c.roll+t*.05); }); }
  // ---------- rigid drifters
  for(const Dd of drifters){ const aa=Dd.a0+t*Dd.w; _a.set(Math.cos(aa)*Dd.ring,Dd.yb+.8*Math.sin(t*.1+Dd.a0),Math.sin(aa)*Dd.ring);
    flow(Dd.p,t,_f); Dd.v.addScaledVector(_f.sub(Dd.v),dt*1.2).addScaledVector(_b.subVectors(_a,Dd.p),dt*.1);
    const d=Dd.p.length(); if(d<3.2) Dd.v.addScaledVector(_c.copy(Dd.p).normalize(),dt*(3.2-d)*1.5);
    Dd.p.addScaledVector(Dd.v,dt); Dd.g.position.copy(Dd.p); Dd.g.rotation.x+=Dd.spin.x*dt; Dd.g.rotation.y+=Dd.spin.y*dt; Dd.g.rotation.z+=Dd.spin.z*dt; }
  // ---------- marine snow aggregate and its gliders
  agg.position.copy(aggState.p).add(_v.set(.4*Math.sin(t*.07),.3*Math.sin(t*.11),.4*Math.cos(t*.06)));
  agg.rotation.x+=aggState.rot.x*dt; agg.rotation.y+=aggState.rot.y*dt; agg.rotation.z+=aggState.rot.z*dt;
  for(const G of gliders){
    G.flip-=dt; if(G.flip<=0){ G.dir*=-1; G.flip=rr(3,9); }                                    // raphid diatoms glide back and forth
    _a.crossVectors(G.d,G.h).normalize(); const ang=G.v*G.dir*dt/AGR;
    G.d.applyAxisAngle(_a,ang).normalize(); G.h.applyAxisAngle(_a,ang); G.h.applyAxisAngle(G.d,.15*Math.sin(t*.5+G.v*40)*dt); G.h.addScaledVector(G.d,-G.h.dot(G.d)).normalize();
    const R=aggR(G.d); _b.copy(G.d).multiplyScalar(R+.05);
    _x.copy(G.h); _y.copy(G.d); _z.crossVectors(_x,_y); _m.makeBasis(_x,_y,_z); G.g.quaternion.setFromRotationMatrix(_m); G.g.position.copy(_b);
    // mucilage trail: newest point at the cell, older points fade
    G.acc+=dt; if(G.acc>.08){ G.acc=0; G.tp.copyWithin(3,0,(TRAIL-1)*3); _c.copy(G.d).multiplyScalar(R+.035); G.tp.set([_c.x,_c.y,_c.z],0); }
    for(let k=0;k<TRAIL;k++){ const f=Math.pow(1-k/TRAIL,1.6); G.tc.set([.7*f,1.2*f,1.1*f],k*3); }
    G.tg.attributes.position.needsUpdate=G.tg.attributes.color.needsUpdate=true; }
  // ---------- environment
  for(let i=0;i<SN;i++){ let y=snPos[i*3+1]-dt*.08; if(y<-14) y+=28; snPos[i*3+1]=y; snPos[i*3]+=Math.sin(t*.2+i)*dt*.02; }
  snGeo.attributes.position.needsUpdate=true;
  rays.forEach(r=>{ r.scale.x=r.scale.z=1+.15*Math.sin(t*.3+r.userData.ph); });
}
/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:10.5,yaw:.5,pitch:.12,tYaw:.5,tPitch:.12,tDist:10.5,auto:0}; let dragging=false;
const camTarget=V3(0,0,0);
function fitCam(){ const w=innerWidth; camera.fov=w<480?62:w<768?52:45; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,15); }
fitCam();
const pts=new Map(); let pinch=0,lx=0,ly=0;
canvas.addEventListener('pointerdown',e=>{ pts.set(e.pointerId,[e.clientX,e.clientY]); canvas.setPointerCapture(e.pointerId); dragging=true; lx=e.clientX; ly=e.clientY; pinch=0; });
canvas.addEventListener('pointermove',e=>{ if(!pts.has(e.pointerId)) return; pts.set(e.pointerId,[e.clientX,e.clientY]);
  if(pts.size===2){ const [a,b]=[...pts.values()], d=Math.hypot(a[0]-b[0],a[1]-b[1]); if(pinch) cam.tDist=clamp(cam.tDist+(pinch-d)*.03,3.5,26); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,-1.3,1.3); lx=e.clientX; ly=e.clientY; });
const upH=e=>{ pts.delete(e.pointerId); pinch=0; if(!pts.size) dragging=false; else { const [p]=[...pts.values()]; lx=p[0]; ly=p[1]; } };
['pointerup','pointercancel'].forEach(n=>canvas.addEventListener(n,upH));
canvas.addEventListener('wheel',e=>{ e.preventDefault(); cam.tDist=clamp(cam.tDist+e.deltaY*.01,3.5,26); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });

const clock=new T.Clock(); let time=0, TS=1;
function frame(){
  requestAnimationFrame(frame);
  const dt=Math.min(clock.getDelta(),1/30)*TS; time+=dt; U_TIME.value=time;
  update(dt,time);
  if(!dragging&&!reduceMotion) cam.auto+=dt*.04;
  cam.yaw+=(cam.tYaw-cam.yaw)*.08; cam.pitch+=(cam.tPitch-cam.pitch)*.08; cam.dist+=(cam.tDist-cam.dist)*.08;
  const y=cam.yaw+cam.auto, p=cam.pitch;
  camera.position.set(camTarget.x+Math.sin(y)*Math.cos(p)*cam.dist, camTarget.y+Math.sin(p)*cam.dist, camTarget.z+Math.cos(y)*Math.cos(p)*cam.dist);
  camera.lookAt(camTarget);
  renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.