• 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

TARDIGRADE 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: Tardigrade</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: radial-gradient(ellipse at 50% 40%, #0a1a1c 0%, #040a0e 55%, #000 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 = 271828;
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  (dark-field microscope look)
   ===================================================================== */
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;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = T.PCFSoftShadowMap;
const ANISO = renderer.capabilities.getMaxAnisotropy();
const scene = new T.Scene();
scene.fog = new T.FogExp2(0x030a0c, 0.07);
const camera = new T.PerspectiveCamera(42, innerWidth/innerHeight, 0.03, 200);
(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,'#1c3a40'); g.addColorStop(.45,'#0a1416'); g.addColorStop(.55,'#123018'); g.addColorStop(1,'#020604');
  x.fillStyle=g; x.fillRect(0,0,1024,512);
  [[200,120,200,'#7a55ff',.55],[780,90,220,'#22d3ff',.55],[540,300,260,'#ff3fa4',.32],[960,260,200,'#ffd36e',.3],[80,330,240,'#2affc2',.3],[640,60,90,'#ffffff',.5]].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 MATERIAL (optionally translucent with an opaque rim)
   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??.3, metalness:o.metal??.5, side:o.side??T.FrontSide, envMapIntensity:o.env??1.35,
    transparent:!!o.transparent, depthWrite:o.depthWrite??true });
  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??.5}, uIri:{value:o.iri??1}, uFilm:{value:o.film??.5},
    uAlpha:{value:o.alpha??1}, uRimA:{value:o.rimA??0}, uGlow:{value:o.glow??.04} };
  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, 1.0);
#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.85);
    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);
    metalnessFactor = mix(metalnessFactor, 0.9, iriS*0.5);
    roughnessFactor = mix(roughnessFactor, 0.14, iriS*0.45);
    totalEmissiveRadiance += c * (0.18 * 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; }
function bumpOf(c){ const o=makeCanvas(c.width,c.height,g=>g.drawImage(c,0,0)); const g=o.getContext('2d'), d=g.getImageData(0,0,o.width,o.height), p=d.data;
  for(let i=0;i<p.length;i+=4){ p[i]=p[i+1]=p[i+2]=p[i]; p[i+3]=255; } g.putImageData(d,0,0); const t=new T.CanvasTexture(o); 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, 28, 20), 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(), _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)); m.castShadow=true; m.receiveShadow=true; parent&&parent.add(m); return m; }
function gridGeo(NU,NV,fn){ const pos=[],uv=[],idx=[];
  for(let i=0;i<=NU;i++) for(let j=0;j<=NV;j++){ const u=i/NU, v=j/NV, p=fn(u,v); pos.push(p[0],p[1],p[2]); uv.push(u,v); }
  for(let i=0;i<NU;i++) for(let j=0;j<NV;j++){ const a=i*(NV+1)+j,b=a+NV+1; idx.push(a,b,a+1,b,b+1,a+1); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setAttribute('uv',new T.Float32BufferAttribute(uv,2)); g.setIndex(idx); g.computeVertexNormals(); return g; }
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 basisFrom(o,pos,fwd,up){ _z.copy(fwd).normalize(); _x.crossVectors(up,_z).normalize(); _y.crossVectors(_z,_x); _m.makeBasis(_x,_y,_z); o.quaternion.setFromRotationMatrix(_m); o.position.copy(pos); }

/* =====================================================================
   THE MOSS LEAF  (a single leaf blade seen at ~400×; it scrolls under the walking tardigrade)
   one texture tile = 10 units across × 20 units along; the costa (midrib) runs at x = -2.2
   ===================================================================== */
const LW=10, LL=20, TW=1024, TH=2048, PXU=TW/LW;
const COSTA=-2.2;
function S(x){ return -.032*x*x + .13*Math.exp(-(((x-COSTA)/.32)**2)); }      // leaf surface height
const leafC=document.createElement('canvas'); leafC.width=TW; leafC.height=TH; const lg=leafC.getContext('2d');
const cells=[];
(function buildCells(){
  let x=0;
  while(x<TW){ const inCosta=Math.abs((x/PXU-LW/2)-COSTA)<.38, w=inCosta?rr(11,14):rr(26,34), h=inCosta?rr(130,170):rr(62,84);
    let y=-rnd()*h; while(y<TH){ const hh=h*rr(.85,1.15); const c={x,y,w,h:hh,costa:inCosta,chl:[],drain:0,s0:0};
      const n=inCosta?4:Math.round(rr(9,15)); for(let k=0;k<n;k++) c.chl.push([rr(.2,.8),rr(.12,.88),rr(3.2,5.2),rr(0,TAU)]);
      cells.push(c); y+=hh; }
    x+=w; }
})();
function drawCell(c){
  const g=lg, d=c.drain, x=c.x+2, y=c.y+2, w=c.w-4, h=c.h-4;
  g.save(); g.beginPath(); g.rect(c.x,c.y,c.w,c.h); g.clip();
  g.fillStyle=c.costa?'#1e3410':'#26401a'; g.fillRect(c.x,c.y,c.w,c.h);                    // cell walls
  const r=Math.min(w,h)*.3; g.beginPath(); g.moveTo(x+r,y); g.arcTo(x+w,y,x+w,y+h,r); g.arcTo(x+w,y+h,x,y+h,r); g.arcTo(x,y+h,x,y,r); g.arcTo(x,y,x+w,y,r); g.closePath();
  const gr=g.createLinearGradient(x,y,x+w,y+h);
  gr.addColorStop(0,`rgb(${lerp(92,200,d)|0},${lerp(162,206,d)|0},${lerp(70,160,d)|0})`); gr.addColorStop(1,`rgb(${lerp(62,170,d)|0},${lerp(122,184,d)|0},${lerp(44,136,d)|0})`);
  g.fillStyle=gr; g.fill();
  // chloroplasts pressed against the cell wall, fading as the cell is emptied
  for(const [u,v,rad,a] of c.chl){ const cx=x+u*w, cy=y+v*h, k=1-d; if(k<=.02) continue;
    g.fillStyle=`rgba(30,110,26,${.9*k})`; g.beginPath(); g.ellipse(cx,cy,rad*1.15,rad*.8,a,0,TAU); g.fill();
    g.fillStyle=`rgba(110,210,70,${.8*k})`; g.beginPath(); g.ellipse(cx-rad*.2,cy-rad*.15,rad*.6,rad*.4,a,0,TAU); g.fill(); }
  if(d>.05){ g.fillStyle=`rgba(40,30,20,${.7*Math.min(1,d*3)})`; g.beginPath(); g.arc(x+w*.5,y+h*.45,2.5,0,TAU); g.fill(); }    // the stylet puncture
  g.restore();
}
function drawLeaf(){
  lg.clearRect(0,0,TW,TH); cells.forEach(drawCell);
  // serrated margins: transparent outside the teeth
  [0,1].forEach(side=>{ lg.save(); lg.globalCompositeOperation='destination-out'; lg.beginPath();
    const x0=side?TW:0, dir=side?-1:1; lg.moveTo(x0,0);
    for(let y=0;y<=TH;y+=26){ lg.lineTo(x0+dir*(10+rnd()*4),y); lg.lineTo(x0+dir*2,y+13); }
    lg.lineTo(x0,TH); lg.closePath(); lg.fill(); lg.restore(); });
}
drawLeaf();
const leafT=new T.CanvasTexture(leafC); leafT.encoding=T.sRGBEncoding; leafT.anisotropy=ANISO; leafT.wrapT=T.RepeatWrapping;
const leafB=bumpOf(leafC); leafB.wrapT=T.RepeatWrapping;
const U_SCROLL={value:0}, U_WET={value:1};
const leafMat=new T.MeshStandardMaterial({map:leafT,bumpMap:leafB,bumpScale:.025,roughness:.25,metalness:0,emissive:0xffffff,emissiveMap:leafT,emissiveIntensity:.2,alphaTest:.5,side:DS});
leafMat.onBeforeCompile=sh=>{
  sh.uniforms.uTime=U_TIME; sh.uniforms.uScroll=U_SCROLL; sh.uniforms.uWet=U_WET;
  sh.vertexShader='varying vec3 vW;\n'+sh.vertexShader.replace('#include <project_vertex>','#include <project_vertex>\n vW=(modelMatrix*vec4(transformed,1.)).xyz;');
  sh.fragmentShader='uniform float uTime; uniform float uScroll; uniform float uWet; varying vec3 vW;\n'+sh.fragmentShader.replace('#include <emissivemap_fragment>',`#include <emissivemap_fragment>
  { vec2 p=vec2(vW.x, vW.z+uScroll)*1.7; float c=0.;
    for(int i=0;i<3;i++){ float fi=float(i); vec2 q=p*(1.+fi*.6)+vec2(sin(uTime*.4+fi*2.1),cos(uTime*.33+fi*1.3))*1.5;
      c+=pow(abs(sin(q.x+sin(q.y*1.3+uTime*.7))*sin(q.y+sin(q.x*1.1-uTime*.6))),6.); }
    totalEmissiveRadiance += vec3(.55,.9,1.)*c*.16*uWet; }`);
};
const leafGeo=gridGeo(120,200,(u,v)=>{ const x=(u-.5)*LW, z=(v-.5)*26; return [x,S(x),z]; });
{ const uv=leafGeo.attributes.uv, p=leafGeo.attributes.position; for(let i=0;i<uv.count;i++) uv.setXY(i,(p.getX(i)+LW/2)/LW,p.getZ(i)/LL); }
const leaf=new T.Mesh(leafGeo,leafMat); leaf.receiveShadow=true; scene.add(leaf);
// out-of-focus leaves deeper in the moss cushion
[[-6,-3.2,-4,.5,.25],[7,-4,2,-.4,.2],[0,-5.5,-9,.1,.15]].forEach(([x,y,z,ry,br])=>{ const m=new T.MeshBasicMaterial({map:leafT,color:new T.Color(br,br*1.3,br),alphaTest:.5,side:DS});
  const g=gridGeo(20,30,(u,v)=>{ const xx=(u-.5)*LW, zz=(v-.5)*22; return [xx,S(xx),zz]; }); const l=new T.Mesh(g,m); l.position.set(x,y,z); l.rotation.set(rr(-.2,.2),ry,rr(-.3,.3)); scene.add(l); });

/* =====================================================================
   THE WATER FILM  (its level drops when the moss dries out, then returns)
   ===================================================================== */
const waveC=makeCanvas(256,256,(g,W,H)=>{ const d=g.createImageData(W,H); for(let y=0;y<H;y++) for(let x=0;x<W;x++){ const a=x/W*TAU, b=y/H*TAU;
  const nx=.5+.25*Math.cos(a*3+Math.sin(b*2))+.12*Math.cos(a*7+b*5), ny=.5+.25*Math.cos(b*3+Math.sin(a*2))+.12*Math.sin(b*6-a*4), k=(y*W+x)*4;
  d.data[k]=nx*255; d.data[k+1]=ny*255; d.data[k+2]=255; d.data[k+3]=255; } g.putImageData(d,0,0); });
const waveT=new T.CanvasTexture(waveC); waveT.wrapS=waveT.wrapT=T.RepeatWrapping; waveT.repeat.set(4,4);
const waterMat=new T.MeshPhysicalMaterial({color:lin(0x9fdcff),transparent:true,opacity:.14,roughness:.04,metalness:0,normalMap:waveT,normalScale:new T.Vector2(.25,.25),envMapIntensity:2.2,clearcoat:1,depthWrite:false,side:DS});
const water=new T.Mesh(new T.PlaneGeometry(30,30).rotateX(-Math.PI/2),waterMat); water.renderOrder=5; scene.add(water);
let WATER=1.75;

/* =====================================================================
   MICRO-FLORA: diatoms, green algae, sand grains, bacteria and drifting detritus
   ===================================================================== */
const props=[];
const diaC=makeCanvas(64,256,(g,W,H)=>{ g.fillStyle='#c9a45a'; g.fillRect(0,0,W,H); for(let y=0;y<H;y+=6){ g.fillStyle='rgba(90,60,20,.55)'; g.fillRect(0,y,W,2); } g.fillStyle='rgba(60,40,10,.8)'; g.fillRect(W/2-1,0,2,H); });
const diaT=dataTex(diaC); diaT.encoding=T.sRGBEncoding;
const diaMat=new T.MeshPhysicalMaterial({map:diaT,roughness:.15,clearcoat:1,transparent:true,opacity:.88,envMapIntensity:1.8,emissive:0x5a3a10,emissiveIntensity:.25});
const algMat=new T.MeshPhysicalMaterial({color:lin(0x3aa53a),roughness:.3,clearcoat:.6,emissive:lin(0x0f4a10),emissiveIntensity:.6,transparent:true,opacity:.92});
const sandMat=new T.MeshPhysicalMaterial({color:lin(0xd8d0c0),roughness:.1,metalness:0,clearcoat:1,transparent:true,opacity:.6,envMapIntensity:2.5});
const BAC=new T.CylinderGeometry(.012,.012,.08,6);
const bacMat=new T.MeshStandardMaterial({color:lin(0x9aa89a),roughness:.5,emissive:lin(0x203020),emissiveIntensity:.5});
function addProp(kind){ const g=new T.Group(); scene.add(g); let r=.1;
  if(kind===0){ r=.08; mesh(SPH,diaMat,g,V3(0,r*.6,0),V3(.09,.06,rr(.3,.42))); }
  else if(kind===1){ const n=1+(rnd()*4|0); r=.12; for(let k=0;k<n;k++){ const s=rr(.05,.09); mesh(SPH,algMat,g,V3(rr(-.07,.07),s,rr(-.07,.07)),s); } }
  else if(kind===2){ const s=rr(.1,.24); r=s; const m=mesh(new T.IcosahedronGeometry(1,0),sandMat,g,V3(0,s*.6,0),V3(s,s*rr(.6,.9),s*rr(.8,1.2))); m.rotation.set(rr(0,3),rr(0,3),rr(0,3)); }
  else { r=.05; for(let k=0;k<3;k++){ const b=mesh(BAC,bacMat,g,V3(rr(-.06,.06),.015,rr(-.06,.06))); b.rotation.set(Math.PI/2,0,rr(0,3)); } }
  const p={g,kind,r,x:0,z:0,ry:rnd()*TAU,vx:0,vz:0,glide:kind===0?rr(.02,.06):0}; respawn(p,true); props.push(p); }
function respawn(p,init){ for(let k=0;k<20;k++){ p.x=rr(-4.2,4.2); p.z=init?rr(-12,12):rr(9,13); if(Math.abs(p.x)>1.4||!init) break; } p.vx=p.vz=0; }
for(let i=0;i<14;i++) addProp(0); for(let i=0;i<16;i++) addProp(1); for(let i=0;i<14;i++) addProp(2); for(let i=0;i<12;i++) addProp(3);
props.forEach(p=>{ if(Math.abs(p.x)<1.3&&Math.abs(p.z)<4) p.x+=Math.sign(p.x||1)*1.5; });
function nudgeProps(x,z,rad,force){ for(const p of props){ const dx=p.x-x, dz=p.z-z, d=Math.hypot(dx,dz); if(d<rad+p.r&&d>1e-4){ const k=force*(1-d/(rad+p.r)); p.vx+=dx/d*k; p.vz+=dz/d*k; } } }
// drifting detritus
const DN=500, dPos=new Float32Array(DN*3), dBase=[]; for(let i=0;i<DN;i++){ dBase.push([rr(-8,8),rr(0,2.2),rr(-12,12),rnd()*TAU]); }
const dGeo=new T.BufferGeometry(); dGeo.setAttribute('position',new T.BufferAttribute(dPos,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,.9)'); gr.addColorStop(.5,'rgba(255,255,255,.25)'); gr.addColorStop(1,'rgba(255,255,255,0)'); x.fillStyle=gr; x.fillRect(0,0,64,64); }));
scene.add(new T.Points(dGeo,new T.PointsMaterial({size:.06,map:dotT,color:0xbfe8d8,transparent:true,opacity:.5,depthWrite:false,blending:T.AdditiveBlending})));
// chloroplasts sucked up through the stylets while feeding
const CN=40, cPos=new Float32Array(CN*3), cLife=new Float32Array(CN), cFrom=[]; for(let i=0;i<CN;i++){ cFrom.push(V3()); cPos[i*3+1]=-99; }
const cGeo=new T.BufferGeometry(); cGeo.setAttribute('position',new T.BufferAttribute(cPos,3));
scene.add(new T.Points(cGeo,new T.PointsMaterial({size:.07,map:dotT,color:0x58ff4a,transparent:true,opacity:.95,depthWrite:false,blending:T.AdditiveBlending})));

/* =====================================================================
   TARDIGRADE PATTERNS
   ===================================================================== */
// body (u = tail→head along canvas x, v = around along canvas y; v=.25 is dorsal)
const bodyC=makeCanvas(512,256,(g,W,H)=>{ g.fillStyle=D(.5,.0,1,.5); g.fillRect(0,0,W,H);
  // dorsal sheen
  let gr=g.createLinearGradient(0,0,0,H); gr.addColorStop(0,D(.55,.02,1,.5)); gr.addColorStop(.25,D(.62,.05,1,.58)); gr.addColorStop(.5,D(.5,0,1,.48)); gr.addColorStop(.75,D(.42,.0,.9,.42)); gr.addColorStop(1,D(.55,.02,1,.5)); g.fillStyle=gr; g.fillRect(0,0,W,H);
  // segmental folds and fine transverse wrinkles
  [.2,.38,.56,.74,.86].forEach(u=>{ g.fillStyle=D(.3,.08,1,.85); g.fillRect(u*W-3,0,6,H); g.fillStyle=D(.75,.12,1,.75); g.fillRect(u*W+3,0,2,H); });
  for(let i=0;i<160;i++){ const x=rnd()*W; g.strokeStyle=D(.38,.04,1,.5); g.lineWidth=1; g.beginPath(); g.moveTo(x,0); for(let y=0;y<=H;y+=16) g.lineTo(x+Math.sin(y*.05+i)*3,y); g.stroke(); }
  // cuticular papillae
  for(let i=0;i<1800;i++){ g.fillStyle=D(.8,.1,1,.75); g.beginPath(); g.arc(rnd()*W,rnd()*H,rr(.8,1.8),0,7); g.fill(); } });
const bodyT=dataTex(bodyC), bodyB=bumpOf(bodyC);
const legC=makeCanvas(128,64,(g,W,H)=>{ g.fillStyle=D(.52,.05,1,.55); g.fillRect(0,0,W,H);
  [.22,.45,.68].forEach(u=>{ g.fillStyle=D(.3,.1,1,.85); g.fillRect(u*W-2,0,4,H); g.fillStyle=D(.78,.14,1,.75); g.fillRect(u*W+2,0,2,H); });
  for(let i=0;i<300;i++){ g.fillStyle=D(.8,.1,1,.7); g.fillRect(rnd()*W,rnd()*H,1.5,1.5); } });
const legT=dataTex(legC);

/* =====================================================================
   THE TARDIGRADE  (water bear: translucent cuticle over visible organs)
   the body is a soft tube rebuilt each frame around a bending spine (u = 0 tail … 1 head)
   ===================================================================== */
const M={
  body: iriMat({pat:bodyT,bump:bodyB,bumpScale:.004,hue:.08,light:.52,rough:.3,metal:.45,transparent:true,depthWrite:false,rimA:.55,alpha:.72,glow:.05,film:.7}),
  leg:  iriMat({pat:legT,hue:.12,light:.52,rough:.3,metal:.45,transparent:true,depthWrite:false,rimA:.55,alpha:.85,glow:.05,film:.7}),
  claw: iriMat({hue:.55,light:.68,sat:.4,iri:.7,rough:.2,metal:.4,glow:.12}),
  bulb: iriMat({hue:.85,light:.5,rough:.25,metal:.55,glow:.1}),
  stylet:iriMat({hue:.6,light:.62,sat:.5,iri:.8,rough:.15,metal:.6,glow:.12}),
  cellS:iriMat({hue:.3,light:.66,sat:.7,iri:.8,rough:.3,metal:.3,glow:.22}),
  mouth:iriMat({hue:.02,light:.55,rough:.3,metal:.4,glow:.06}),
  dark: new T.MeshStandardMaterial({color:lin(0x0a0605),roughness:.6}),
  eye:  new T.MeshPhysicalMaterial({color:lin(0x120806),roughness:.15,clearcoat:1}),
  gut:  new T.MeshStandardMaterial({color:lin(0xb89a6a),roughness:.55,emissive:0x000000}),
};
const tg=new T.Group(); scene.add(tg);
const NB=56, NR=40;
const bodyGeo=gridGeo(NB,NR,()=>[0,0,0]);
const bodyMesh=mesh(bodyGeo,M.body,tg); bodyMesh.renderOrder=3; bodyMesh.frustumCulled=false;
const gutGeo=gridGeo(36,18,()=>[0,0,0]);
const gutMesh=mesh(gutGeo,M.gut,tg); gutMesh.frustumCulled=false;
// spine samples
const SP=[], STn=[], SS=[], SU=[], SR=new Float32Array(NB+1);
for(let i=0;i<=NB;i++){ SP.push(V3()); STn.push(V3()); SS.push(V3()); SU.push(V3()); }
const pose={L:1.45,y:.56,dip:0,sway:0,swayPh:0,tun:0,roll:0,pitchFront:0};
function radiusAt(u,tun){
  const tail=Math.pow(smooth(u/.13),.55), head=lerp(1,.34,smooth((u-.8)/.2));
  let r=(.52+.05*Math.sin(Math.PI*u))*tail*head;
  [.2,.38,.56,.74].forEach(f=>{ r*=1-.07*Math.exp(-(((u-f)/.025)**2)); });
  r*=1+.012*Math.sin(u*120)*(1+tun*3);
  const tr=.5*Math.pow(Math.max(0,Math.sin(Math.PI*clamp((u-.04)/.92,0,1))),.42)*(1+.04*Math.sin(u*48));   // the tun: a wrinkled barrel
  return lerp(r,tr,tun);
}
function spineAt(u,out){
  const L=pose.L*(1-.42*pose.tun), z=(u-.5)*2*L;
  const dip=pose.dip*Math.pow(smooth((u-.5)/.5),2), sway=pose.sway*Math.sin(pose.swayPh+u*2.4)*(u-.25);
  return out.set(sway, pose.y-dip+.05*pose.tun*Math.sin(Math.PI*u), z);
}
function frameAt(u,P,Tn,Sd,Up){ const i=clamp(u*NB,0,NB), a=Math.floor(Math.min(i,NB-1)), f=i-a;
  P.lerpVectors(SP[a],SP[a+1],f); if(Tn) Tn.lerpVectors(STn[a],STn[a+1],f).normalize(); if(Sd) Sd.lerpVectors(SS[a],SS[a+1],f).normalize(); if(Up) Up.lerpVectors(SU[a],SU[a+1],f).normalize();
  return lerp(SR[a],SR[a+1],f); }
function buildBody(){
  for(let i=0;i<=NB;i++){ spineAt(i/NB,SP[i]); SR[i]=radiusAt(i/NB,pose.tun); }
  for(let i=0;i<=NB;i++){ STn[i].subVectors(SP[Math.min(NB,i+1)],SP[Math.max(0,i-1)]).normalize(); SS[i].crossVectors(UP,STn[i]).normalize(); SU[i].crossVectors(STn[i],SS[i]).normalize();
    if(pose.roll){ SS[i].applyAxisAngle(STn[i],pose.roll); SU[i].applyAxisAngle(STn[i],pose.roll); } }
  const p=bodyGeo.attributes.position;
  for(let i=0;i<=NB;i++){ const R=SR[i];
    for(let j=0;j<=NR;j++){ const a=j/NR*TAU, c=Math.cos(a), s=Math.sin(a), wy=s>0?.9:.72;
      const k=i*(NR+1)+j; p.setXYZ(k,SP[i].x+SS[i].x*R*c+SU[i].x*R*s*wy, SP[i].y+SS[i].y*R*c+SU[i].y*R*s*wy, SP[i].z+SS[i].z*R*c+SU[i].z*R*s*wy); } }
  p.needsUpdate=true; bodyGeo.computeVertexNormals();
  // gut: an inner tube from u .18 to .8
  const gp=gutGeo.attributes.position, P=V3(), Sd=V3(), Up=V3();
  for(let i=0;i<=36;i++){ const u=.18+.62*i/36, R=frameAt(u,P,null,Sd,Up)*.42*Math.pow(Math.sin(Math.PI*i/36),.6)*(1+.12*Math.sin(u*40+U_TIME.value*1.5));
    for(let j=0;j<=18;j++){ const a=j/18*TAU, k=i*19+j; gp.setXYZ(k,P.x+Sd.x*R*Math.cos(a)+Up.x*R*Math.sin(a)*.8,P.y-.04+Sd.y*R*Math.cos(a)+Up.y*R*Math.sin(a)*.8,P.z+Sd.z*R*Math.cos(a)+Up.z*R*Math.sin(a)*.8); } }
  gp.needsUpdate=true; gutGeo.computeVertexNormals();
}
// head: mouth cone with peribuccal lamellae, stylets, buccal tube; pharyngeal bulb; eyespots
const head=new T.Group(); tg.add(head);
mesh(new T.CylinderGeometry(.1,.17,.16,24,1,true).rotateX(Math.PI/2),M.mouth,head,V3(0,0,.02));
mesh(new T.TorusGeometry(.1,.03,10,24),M.mouth,head,V3(0,0,.1));
mesh(new T.CircleGeometry(.07,20),M.dark,head,V3(0,0,.105));
const lamellae=[]; for(let k=0;k<10;k++){ const a=k/10*TAU, l=mesh(CONE,M.mouth,head,V3(Math.cos(a)*.11,Math.sin(a)*.11,.1),V3(.025,.07,.018)); l.rotation.set(Math.PI/2,0,0); l.rotateOnWorldAxis(V3(0,0,1),a); lamellae.push(l); }
[[.14,.06],[-.14,.06],[0,.15],[.1,-.1],[-.1,-.1]].forEach(([x,y])=>mesh(SPH_LO,M.mouth,head,V3(x,y,.05),.03));     // sensory papillae
const stylets=new T.Group(); head.add(stylets);
[-1,1].forEach(s=>{ const st=mesh(new T.CylinderGeometry(.006,.016,.62,6).rotateX(Math.PI/2),M.stylet,stylets,V3(s*.03,0,-.25)); st.rotation.y=-s*.05;
  mesh(CONE,M.stylet,stylets,V3(s*.026,0,.06),V3(.008,.06,.008)).rotation.x=Math.PI/2; });
const buccal=mesh(new T.CylinderGeometry(.025,.025,1,8,1,true).translate(0,.5,0),M.stylet,tg); buccal.renderOrder=1;
const bulb=new T.Group(); tg.add(bulb);
mesh(SPH,M.bulb,bulb,null,V3(.12,.11,.16));
for(let k=0;k<3;k++){ const a=k/3*TAU; mesh(SPH_LO,M.stylet,bulb,V3(Math.cos(a)*.07,Math.sin(a)*.07,0),V3(.025,.025,.09)); }   // placoids
const eyes=[-1,1].map(s=>mesh(SPH,M.eye,tg,null,.045));
// storage cells drifting in the body cavity
const NSC=56, scParams=[]; for(let i=0;i<NSC;i++) scParams.push([rr(.12,.82),rnd()*TAU,rr(.3,.7),rr(.03,.055),rnd()*TAU]);
const storage=new T.InstancedMesh(SPH_LO,M.cellS,NSC); storage.frustumCulled=false; tg.add(storage);

// legs: telescopic lobopods (tube along a bezier rebuilt each frame) with two double claws
const LEGS=[]; const NLU=12, NLV=14;
const clawGeo=(()=>{ const a=sweep([V3(0,0,0),V3(0,.05,.06),V3(0,.04,.14),V3(0,-.035,.18)],t=>.024*(1-.85*t)+.003,14,6);
  const b=sweep([V3(0,.02,.03),V3(0,.07,.07),V3(0,.05,.11)],t=>.014*(1-.8*t)+.002,10,5);
  const pos=[...a.attributes.position.array,...b.attributes.position.array], nor=[...a.attributes.normal.array,...b.attributes.normal.array], off=a.attributes.position.count;
  const idx=[...a.index.array,...b.index.array.map(i=>i+off)]; const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setAttribute('normal',new T.Float32BufferAttribute(nor,3)); g.setIndex(idx); return g; })();
[[.7,-1,.0],[.53,-1,.0],[.36,-1,.0],[.1,-1,1]].forEach(([u,_,iv],li)=>[-1,1].forEach(s=>{
  const geo=gridGeo(NLU,NLV,()=>[0,0,0]); const m=mesh(geo,M.leg,tg); m.renderOrder=4; m.frustumCulled=false;
  const foot=new T.Group(); tg.add(foot); const claws=[];
  [-.055,-.02,.02,.055].forEach((cx,k)=>{ const g=new T.Group(); g.position.set(cx,0,0); g.rotation.y=cx*2.2; foot.add(g); mesh(clawGeo,M.claw,g,null,1.3); claws.push(g); });
  LEGS.push({u,s,li,iv:!!iv,geo,foot,claws,toe:V3(),lift:V3(),target:V3(),step:-1,group:(li+(s>0?0:1))%2,grip:1,home:V3(),wig:rnd()*TAU});
}));
const _P=V3(),_Tn=V3(),_Sd=V3(),_Up=V3(),_h=V3(),_k=V3(),_a=V3(),_t=V3(),_tmp=V3(),_tmp2=V3();
function legHip(L,out){ const R=frameAt(L.u,_P,_Tn,_Sd,_Up), ang=L.iv?-.55:-.85; return out.copy(_P).addScaledVector(_Sd,L.s*Math.cos(ang)*R*.82).addScaledVector(_Up,Math.sin(ang)*R*.7); }
function legHome(L,out){ legHip(L,out); out.x+=L.s*(L.iv?.24:.3); out.z+=L.iv?-.42:(L.li===0?.12:0); out.y=S(out.x); return out; }
function buildLeg(L,ext){
  legHip(L,_h); const p=L.geo.attributes.position;
  // retracted legs fold back into the body
  _a.lerpVectors(_h,L.toe,ext); _a.y=lerp(_h.y,L.toe.y,ext)+.05*ext;
  _k.lerpVectors(_h,_a,.5).add(_tmp.set(L.s*.1*ext,.12*ext,0));
  const rs=lerp(.35,1,ext);
  for(let i=0;i<=NLU;i++){ const t=i/NLU, u=1-t;
    _P.set(u*u*_h.x+2*u*t*_k.x+t*t*_a.x, u*u*_h.y+2*u*t*_k.y+t*t*_a.y, u*u*_h.z+2*u*t*_k.z+t*t*_a.z);
    _Tn.set(2*u*(_k.x-_h.x)+2*t*(_a.x-_k.x), 2*u*(_k.y-_h.y)+2*t*(_a.y-_k.y), 2*u*(_k.z-_h.z)+2*t*(_a.z-_k.z)).normalize();
    _Sd.crossVectors(_Tn,UP); if(_Sd.lengthSq()<1e-6) _Sd.set(1,0,0); _Sd.normalize(); _Up.crossVectors(_Sd,_Tn);
    const R=(.16-.05*t+.012*Math.sin(t*Math.PI*6))*rs;
    for(let j=0;j<=NLV;j++){ const a=j/NLV*TAU, k=i*(NLV+1)+j; p.setXYZ(k,_P.x+(_Sd.x*Math.cos(a)+_Up.x*Math.sin(a))*R,_P.y+(_Sd.y*Math.cos(a)+_Up.y*Math.sin(a))*R,_P.z+(_Sd.z*Math.cos(a)+_Up.z*Math.sin(a))*R); } }
  p.needsUpdate=true; L.geo.computeVertexNormals();
  // the foot and claws: facing forward (back for leg IV), hooks dug in during stance
  _t.set(L.s*.25,0,L.iv?-1:1).normalize(); basisFrom(L.foot,_tmp.copy(_a).add(_tmp2.set(0,-.06*ext,0)),_t,UP);
  L.foot.scale.setScalar(Math.max(.001,ext));
  L.claws.forEach((c,k)=>{ c.rotation.x=lerp(-.7,.32,L.grip)+.05*Math.sin(k); });
}

/* =====================================================================
   LIGHTS: dark-field — strong oblique rims, soft key, green glow through the leaf
   ===================================================================== */
scene.add(new T.HemisphereLight(0x9fd8ff,0x0a2a0a,.45));
const key=new T.DirectionalLight(0xfff4e8,1.25); key.position.set(3,8,5); key.castShadow=true; key.shadow.mapSize.set(2048,2048);
Object.assign(key.shadow.camera,{left:-4,right:4,top:4,bottom:-4,near:1,far:25}); key.shadow.bias=-.0004; key.shadow.normalBias=.02; scene.add(key);
const rim=new T.PointLight(0x33ccff,2.2,30); rim.position.set(-5,3,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.8,30); rim2.position.set(5,2,-3); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1,30); glint.position.set(2,3,6); scene.add(glint);
const under=new T.PointLight(0x7aff6a,.8,12); under.position.set(0,-1.2,0); scene.add(under);

/* =====================================================================
   BEHAVIOUR
   walk (claws hooking into the leaf) → feed (head down, stylets pierce a leaf cell, the pharynx pumps,
   the cell empties and the gut turns green) → walk … → the film dries: the water bear withdraws its legs
   and head and shrivels into a tun → water returns, it swells and walks again
   ===================================================================== */
const st={mode:'walk',t:0,dur:6,picked:false}, go=(m,d)=>{ st.mode=m; st.t=0; st.dur=d; st.picked=false; };
let scroll=0, speed=0, feeds=0, gutFill=.15, feedCell=null, drawT=0, feedTip=V3();
const drained=[];
function cellAt(x,z){ const px=(x+LW/2)*PXU, v=((z+scroll)/LL)%1, py=(1-((v+1)%1))*TH;
  for(const c of cells) if(px>=c.x&&px<c.x+c.w&&py>=c.y&&py<c.y+c.h) return c; return null; }
function update(dt,t){
  st.t+=dt; const m=st.mode; let vT=0, ext=1;
  if(m==='walk'){ vT=.3; if(st.t>st.dur&&!reduceMotion){ if(feeds>=2&&rnd()<.6){ feeds=0; go('dry',4.5); } else go('feed',6.5); } }
  else if(m==='feed'){ const s=st.t;
    if(!st.picked){ st.picked=true; spineAt(1,feedTip); feedTip.z+=.08; feedCell=cellAt(feedTip.x,feedTip.z); if(feedCell){ feedCell.s0=scroll; } }
    pose.dip=lerp(pose.dip,s<5.4?pose.y-.16-S(0):0,1-Math.exp(-dt*3));
    const thrust=s>1.2&&s<5.3?1:0; stylets.position.z=lerp(stylets.position.z,thrust?.16+.03*Math.sin(t*12):0,1-Math.exp(-dt*10));
    const pumping=s>1.6&&s<5.2;
    bulb.userData.pump=pumping?1+.18*Math.max(0,Math.sin(t*14)):1;
    if(pumping&&feedCell){ feedCell.drain=Math.min(1,feedCell.drain+dt/3.4); gutFill=Math.min(1,gutFill+dt*.16); drawT-=dt;
      if(drawT<=0){ drawT=.25; drawCell(feedCell); leafT.needsUpdate=true; }
      if(rnd()<dt*14){ const i=(rnd()*CN)|0; cLife[i]=1; cFrom[i].set(feedTip.x+rr(-.12,.12),S(feedTip.x)+.02,feedTip.z+rr(-.12,.12)); } }
    if(s>=st.dur){ if(feedCell){ drawCell(feedCell); leafT.needsUpdate=true; drained.push(feedCell); } feedCell=null; feeds++; go('walk',rr(6,9)); } }
  else if(m==='dry'){ WATER=lerp(1.75,-.35,smooth(st.t/3.2)); pose.tun=smooth((st.t-1.2)/3.2); if(st.t>=st.dur) go('tun',4.5); }
  else if(m==='tun'){ WATER=-.35; pose.tun=1; if(st.t>=st.dur) go('wake',5); }
  else if(m==='wake'){ WATER=lerp(-.35,1.75,smooth(st.t/2.6)); pose.tun=1-smooth((st.t-1.4)/3.4); if(st.t>=st.dur){ pose.tun=0; go('walk',rr(6,9)); } }
  if(m!=='feed'){ pose.dip=lerp(pose.dip,0,1-Math.exp(-dt*3)); stylets.position.z=lerp(stylets.position.z,0,1-Math.exp(-dt*6)); bulb.userData.pump=1; }
  ext=1-smooth(pose.tun*1.4);
  speed=lerp(speed,vT,1-Math.exp(-dt*2.5)); scroll+=speed*dt;
  // restore emptied cells once they are far behind (the tile repeats every 20 units)
  for(let i=drained.length-1;i>=0;i--){ const c=drained[i]; if(scroll-c.s0>8){ c.drain=0; drawCell(c); leafT.needsUpdate=true; drained.splice(i,1); } }
  leafT.offset.y=scroll/LL; leafB.offset.y=scroll/LL; U_SCROLL.value=scroll;

  // body pose: lumbering sway while walking, lower in the tun
  pose.swayPh+=dt*speed*4; pose.sway=lerp(pose.sway,.09*speed/.3*(1-pose.tun),1-Math.exp(-dt*2)) + (m==='feed'?0:0);
  pose.y=lerp(.56,.4,pose.tun)+.02*Math.sin(t*speed*12)*(speed/.3);
  pose.roll=.04*Math.sin(t*speed*6)*(speed/.3);
  buildBody();

  // head, internal organs
  const R1=frameAt(1,_P,_Tn,_Sd,_Up); basisFrom(head,_P,_Tn,_Up); head.scale.setScalar(lerp(1,.05,smooth(pose.tun*1.6)));
  head.position.addScaledVector(_Tn,-.05-.25*pose.tun);
  frameAt(.86,_P,_Tn,_Sd,_Up); basisFrom(bulb,_P,_Tn,_Up); const pp=bulb.userData.pump||1; bulb.scale.set(pp,pp,1/pp*(1-.3*pose.tun));
  _tmp.copy(head.position); _tmp2.copy(bulb.position); _t.subVectors(_tmp,_tmp2); buccal.position.copy(_tmp2); buccal.quaternion.setFromUnitVectors(UP,_t.clone().normalize()); buccal.scale.set(1,_t.length(),1);
  stylets.visible=pose.tun<.5; const inside=pose.tun<.6; gutMesh.visible=storage.visible=bulb.visible=buccal.visible=inside; eyes.forEach(e=>e.visible=inside);
  [-1,1].forEach((s,i)=>{ const R=frameAt(.9,_P,_Tn,_Sd,_Up); eyes[i].position.copy(_P).addScaledVector(_Sd,s*R*.62).addScaledVector(_Up,R*.5); });
  for(let i=0;i<NSC;i++){ const [u0,a0,rf,sz,ph]=scParams[i]; const u=u0+.02*Math.sin(t*.4+ph), a=a0+.3*Math.sin(t*.3+ph*2);
    const R=frameAt(u,_P,_Tn,_Sd,_Up)*rf; _tmp.copy(_P).addScaledVector(_Sd,Math.cos(a)*R).addScaledVector(_Up,Math.sin(a)*R*.8);
    _m.compose(_tmp,_q.identity(),_tmp2.setScalar(sz*(1+.15*Math.sin(t+ph))*(1-.4*pose.tun))); storage.setMatrixAt(i,_m); }
  storage.instanceMatrix.needsUpdate=true;
  M.gut.color.copy(lin(0xb89a6a)).lerp(lin(0x2f9a2a),gutFill); M.gut.emissive.copy(lin(0x0a3a08)).multiplyScalar(gutFill);
  M.body.userData.u.uAlpha.value=lerp(.72,2.4,smooth(pose.tun*1.6)); M.body.userData.u.uRimA.value=lerp(.55,1,pose.tun); if(m==='walk') gutFill=Math.max(.1,gutFill-dt*.008); M.body.userData.u.uLight.value=lerp(.52,.42,pose.tun);

  // legs: stance feet ride the scrolling leaf; steps follow a slow alternating wave
  for(const L of LEGS){ legHome(L,L.home);
    if(ext<.98){ L.toe.lerp(L.home,1-Math.exp(-dt*4)); L.step=-1; L.grip=lerp(L.grip,0,1-Math.exp(-dt*3)); continue; }
    if(L.step>=0){ L.step+=dt/.42; const s=smooth(L.step); L.toe.lerpVectors(L.lift,L.target,s); L.toe.y=lerp(L.lift.y,L.target.y,s)+Math.sin(Math.PI*Math.min(1,L.step))*.2;
      L.grip=Math.max(0,1-Math.sin(Math.PI*Math.min(1,L.step))*2);
      if(L.step>=1){ L.step=-1; L.toe.copy(L.target); L.grip=1; nudgeProps(L.toe.x,L.toe.z,.18,.35); } }
    else { L.toe.z-=speed*dt; L.toe.y=S(L.toe.x); L.grip=lerp(L.grip,1,1-Math.exp(-dt*8));
      const busy=LEGS.some(o=>o.step>=0&&o.group!==L.group), d=L.toe.distanceTo(L.home);
      if((!busy&&d>.24)||d>.6){ L.step=0; L.lift.copy(L.toe); L.target.copy(L.home); L.target.z+=speed>.05?.2:0; L.target.y=S(L.target.x); } }
  }
  for(const L of LEGS){ const w=m==='wake'&&ext>.05&&ext<.98?.08*Math.sin(t*9+L.wig):0; if(w){ L.toe.x+=w*dt*4; } buildLeg(L,ext); }

  // water, props, detritus, chloroplast stream
  WATER=clamp(WATER,-.4,2); water.position.y=WATER; water.visible=WATER>-.39; waveT.offset.set(t*.012,-scroll/7.5+t*.008);
  U_WET.value=smooth((WATER+.1)/1.2); leafMat.roughness=lerp(.75,.22,U_WET.value); leafMat.emissiveIntensity=lerp(.1,.2,U_WET.value);
  for(const p of props){ p.z-=speed*dt; if(p.glide&&U_WET.value>.5) p.z+=p.glide*dt*Math.sin(t*.2+p.x); p.x+=p.vx*dt; p.z+=p.vz*dt; const dmp=Math.exp(-dt*4); p.vx*=dmp; p.vz*=dmp;
    if(p.z<-13) respawn(p,false); p.g.position.set(p.x,S(p.x),p.z); p.g.rotation.y=p.ry; }
  for(let i=0;i<DN;i++){ const b=dBase[i]; let z=b[2]-scroll+.05*Math.sin(t*.3+b[3]); z=((z+12)%24+24)%24-12; const x=b[0]+.1*Math.sin(t*.25+b[3]);
    const y=Math.max(S(x)+.02,Math.min(b[1]+.08*Math.sin(t*.4+b[3]),WATER-.04)); dPos.set([x,y,z],i*3); }
  dGeo.attributes.position.needsUpdate=true;
  const mouth=head.position;
  for(let i=0;i<CN;i++){ if(cLife[i]<=0){ cPos[i*3+1]=-99; continue; } cLife[i]-=dt*1.6; const k=smooth(1-cLife[i]); _tmp.lerpVectors(cFrom[i],mouth,k); cPos.set([_tmp.x,_tmp.y,_tmp.z],i*3); }
  cGeo.attributes.position.needsUpdate=true;
}

/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:6.2,yaw:.75,pitch:.42,tYaw:.75,tPitch:.42,tDist:6.2,auto:0}; let dragging=false;
const camTarget=V3(0,.45,.1);
function fitCam(){ const w=innerWidth; camera.fov=w<480?60:w<768?50:42; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,8.5); }
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)*.02,2.2,14); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.02,1.4); 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*.006,2.2,14); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });

const clock=new T.Clock(); let time=0, TS=1;
buildBody(); LEGS.forEach(L=>{ legHome(L,L.toe); L.toe.z+=rr(-.15,.15); });
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*.05;
  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);
  const gy=S(camera.position.x)+.3; if(camera.position.y<gy) camera.position.y=gy;
  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.