• 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

SCORPION 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: Desert Scorpion</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(#02030a 0%, #070a1a 45%, #121628 70%, #0b0d1a 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); };
const angWrap = a => Math.atan2(Math.sin(a), Math.cos(a));
let seed = 913377;
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 / ENVIRONMENT  (a moonlit desert clay pan)
   ===================================================================== */
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.2;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = T.PCFSoftShadowMap;
const ANISO = renderer.capabilities.getMaxAnisotropy();

const scene = new T.Scene();
const FOG = 0x0d1020;
scene.fog = new T.FogExp2(FOG, 0.072);
const camera = new T.PerspectiveCamera(42, innerWidth/innerHeight, 0.03, 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,'#2a3260'); g.addColorStop(.35,'#141a38'); g.addColorStop(.5,'#2a2030'); g.addColorStop(.56,'#3a2c26'); g.addColorStop(1,'#0c0806');
  x.fillStyle=g; x.fillRect(0,0,1024,512);
  [[300,120,170,'#dfe8ff',.7],[800,90,230,'#22d3ff',.45],[560,250,260,'#ff3fa4',.3],[960,230,200,'#7a55ff',.4],[80,300,240,'#2affc2',.22],[420,420,300,'#ffb46e',.2]].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  (hue cycles over time and with view angle; faint UV-style glow)
   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??.28, metalness:o.metal??.55, side:o.side??T.FrontSide, envMapIntensity:o.env??1.35 });
  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}, 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 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`).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;
    metalnessFactor = mix(metalnessFactor, 0.9, iriS*0.5);
    roughnessFactor = mix(roughnessFactor, 0.14, iriS*0.45);
    totalEmissiveRadiance += c * (0.16 * 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})`;
function lathe(len,rf,n=12,rs=12){ const p=[]; for(let i=0;i<=rs;i++){ const s=i/rs; p.push(new T.Vector2(Math.max(rf(s),.0005), s*len)); } return new T.LatheGeometry(p,n); }
const alongX = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateZ(-Math.PI/2);
const alongZ = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateX(Math.PI/2);
const SPH = new T.SphereGeometry(1, 32, 24), SPH_LO = new T.SphereGeometry(1, 10, 8);
const CONE = new T.ConeGeometry(1,1,5).translate(0,.5,0);
const HAIR = new T.CylinderGeometry(0, 1, 1, 3, 1).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 orient(o,from,to,up){ _x.subVectors(to,from).normalize(); _z.crossVectors(_x,up).normalize(); _y.crossVectors(_z,_x); _m.makeBasis(_x,_y,_z); o.quaternion.setFromRotationMatrix(_m); o.position.copy(from); }
function instanced(parent,geo,mat,list){ const im=new T.InstancedMesh(geo,mat,list.length), m4=new T.Matrix4();
  list.forEach(([p,d,len,rad],i)=>{ _q.setFromUnitVectors(UP,d.clone().normalize()); m4.compose(p,_q,V3(rad,len,rad)); im.setMatrixAt(i,m4); });
  im.instanceMatrix.needsUpdate=true; im.castShadow=true; parent.add(im); return im; }
const randDir = () => V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize();
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; }
// tube along a curve with a radius profile r(t)
function sweep(pts,rf,seg=24,rad=8){ 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 bez2(a,b,c,s){ const u=1-s; return a.clone().multiplyScalar(u*u).addScaledVector(b,2*u*s).addScaledVector(c,s*s); }

/* =====================================================================
   GROUND: a dried clay pan of curled, cracked mud polygons
   H(x,z) is shared by the mesh, the texture, the feet, the prey and the debris.
   ===================================================================== */
const CS=1.05, CN=44, CO=22, cellX=new Float32Array(CN*CN), cellZ=new Float32Array(CN*CN), cellR=new Float32Array(CN*CN), cellT=new Float32Array(CN*CN*2);
for(let i=0;i<CN;i++) for(let j=0;j<CN;j++){ const k=i*CN+j; cellX[k]=(i-CO+.14+.72*rnd())*CS; cellZ[k]=(j-CO+.14+.72*rnd())*CS; cellR[k]=rnd(); cellT[k*2]=rr(-.035,.035); cellT[k*2+1]=rr(-.035,.035); }
const VO={e:0,id:0,cx:0,cz:0};
function vor(x,z){
  { const wx=x+.13*Math.sin(z*2.3+1.1)+.06*Math.sin(z*5.7+x*1.3), wz=z+.13*Math.sin(x*2.1+.4)+.06*Math.sin(x*6.1-z*1.7); x=wx; z=wz; }
  const ix=clamp(Math.floor(x/CS)+CO,2,CN-3), iz=clamp(Math.floor(z/CS)+CO,2,CN-3);
  let md=1e9,mx=0,mz=0,mid=0;
  for(let a=-1;a<=1;a++) for(let b=-1;b<=1;b++){ const k=(ix+a)*CN+iz+b, dx=cellX[k]-x, dz=cellZ[k]-z, d=dx*dx+dz*dz; if(d<md){ md=d; mx=dx; mz=dz; mid=k; } }
  let e=1e9;
  for(let a=-2;a<=2;a++) for(let b=-2;b<=2;b++){ const k=(ix+a)*CN+iz+b; if(k===mid) continue; const dx=cellX[k]-x, dz=cellZ[k]-z, ex=dx-mx, ez=dz-mz, l=Math.hypot(ex,ez);
    const d=((mx+dx)*.5*ex+(mz+dz)*.5*ez)/l; if(d<e) e=d; }
  VO.e=e; VO.id=mid; VO.cx=-mx; VO.cz=-mz; return VO;
}
const CRACK=.05;
function H(x,z){
  const v=vor(x,z), e=v.e;
  let h=.16*Math.sin(x*.19+1.3)*Math.sin(z*.16+.4)+.04*Math.sin(x*.53+z*.41);
  h+=cellT[v.id*2]*v.cx+cellT[v.id*2+1]*v.cz+(cellR[v.id]-.5)*.03;   // each plate tilts a little
  h+=.045*Math.exp(-e/.16);                                             // plate edges curl upward
  h-=.05*smooth(1-e/.13)+.035*smooth(1-e/CRACK);                       // the crack: a soft groove with a narrow floor
  return h;
}
const GS=32, GN=470;
const groundGeo=new T.PlaneGeometry(GS,GS,GN,GN).rotateX(-Math.PI/2);
{ const p=groundGeo.attributes.position; for(let i=0;i<p.count;i++){ const x=p.getX(i), z=p.getZ(i); p.setY(i,H(x,z)); } groundGeo.computeVertexNormals(); }
const TEXN=2048;
const groundC=document.createElement('canvas'); groundC.width=groundC.height=TEXN;
const bumpC=document.createElement('canvas'); bumpC.width=bumpC.height=TEXN;
{
  const g=groundC.getContext('2d'), gb=bumpC.getContext('2d'), id=g.createImageData(TEXN,TEXN), ib=gb.createImageData(TEXN,TEXN), P=id.data, B=ib.data;
  for(let py=0;py<TEXN;py++){ const z=(py/TEXN-.5)*GS;
    for(let px=0;px<TEXN;px++){ const x=(px/TEXN-.5)*GS, v=vor(x,z), e=v.e, cr=cellR[v.id], k=(py*TEXN+px)*4;
      const n=rnd(), dust=.5+.5*Math.sin(x*.7+Math.sin(z*.9)*1.5)*Math.sin(z*.45-x*.2);
      let r=.34+.07*cr+.05*dust, gg=.29+.05*cr+.04*dust, b=.23+.035*cr+.03*dust;
      const rim=Math.exp(-e/.09); r+=.09*rim; gg+=.075*rim; b+=.055*rim;                        // bleached curled rims
      const sh=smooth((e-CRACK)/.06)*.0+smooth(1-(e-CRACK)/.05)*.25; r-=sh*.4; gg-=sh*.4; b-=sh*.4; // shadowed lip
      const c=smooth(1-e/(CRACK*.8)); r=lerp(r,.08,c); gg=lerp(gg,.055,c); b=lerp(b,.04,c);
      const sp=(n-.5)*.09; r+=sp; gg+=sp; b+=sp;
      P[k]=clamp(r,0,1)*255; P[k+1]=clamp(gg,0,1)*255; P[k+2]=clamp(b,0,1)*255; P[k+3]=255;
      const hb=.55+.25*rim-.5*c+(n-.5)*.18; B[k]=B[k+1]=B[k+2]=clamp(hb,0,1)*255; B[k+3]=255; } }
  g.putImageData(id,0,0); gb.putImageData(ib,0,0);
  // hairline cracks inside the plates, and a scatter of grit
  for(let i=0;i<900;i++){ let x=rnd()*TEXN, y=rnd()*TEXN, a=rnd()*TAU; g.strokeStyle='rgba(30,20,14,.5)'; gb.strokeStyle='rgba(40,40,40,.7)'; g.lineWidth=gb.lineWidth=rr(.6,1.4);
    g.beginPath(); gb.beginPath(); g.moveTo(x,y); gb.moveTo(x,y); const n=4+(rnd()*6|0); for(let j=0;j<n;j++){ a+=rr(-.7,.7); x+=Math.cos(a)*rr(3,9); y+=Math.sin(a)*rr(3,9); g.lineTo(x,y); gb.lineTo(x,y); } g.stroke(); gb.stroke(); }
  for(let i=0;i<9000;i++){ const x=rnd()*TEXN, y=rnd()*TEXN, s=rr(.8,2.4), l=rnd(); g.fillStyle=l<.5?`rgba(40,30,22,${rr(.3,.7)})`:`rgba(200,180,150,${rr(.2,.6)})`; g.fillRect(x,y,s,s); gb.fillStyle=l<.5?'rgba(60,60,60,.7)':'rgba(230,230,230,.7)'; gb.fillRect(x,y,s,s); }
}
const groundT=new T.CanvasTexture(groundC); groundT.encoding=T.sRGBEncoding; groundT.anisotropy=ANISO;
const groundB=new T.CanvasTexture(bumpC); groundB.anisotropy=ANISO;
const groundMat=new T.MeshStandardMaterial({map:groundT,bumpMap:groundB,bumpScale:.035,roughness:.93,metalness:0});
const ground=new T.Mesh(groundGeo,groundMat); ground.receiveShadow=true; scene.add(ground);
function groundNormal(x,z,out){ const e=.06; return out.set(H(x-e,z)-H(x+e,z),2*e,H(x,z-e)-H(x,z+e)).normalize(); }

// sky dome blending into the fog at the horizon
(function(){ const m=new T.ShaderMaterial({side:T.BackSide,depthWrite:false,fog:false,uniforms:{uFog:{value:new T.Color(FOG)},uMoon:{value:V3(-.55,.42,-.72).normalize()}},
  vertexShader:'varying vec3 vD; void main(){ vD=normalize(position); gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }',
  fragmentShader:'uniform vec3 uFog; uniform vec3 uMoon; varying vec3 vD; void main(){ float h=clamp(vD.y,0.,1.); vec3 c=mix(uFog,vec3(.008,.012,.035),smoothstep(0.,.45,h)); c+=vec3(.06,.05,.09)*pow(max(dot(vD,uMoon),0.),6.)*(1.-h); c+=vec3(.05,.03,.02)*exp(-h*14.); gl_FragColor=vec4(c,1.); }'});
  const d=new T.Mesh(new T.SphereGeometry(180,32,16),m); d.renderOrder=-1; d.onBeforeRender=(r,s,c)=>d.position.copy(c.position); scene.add(d); })();
// sky: stars and the moon
(function(){ const N=1800,pos=new Float32Array(N*3),col=new Float32Array(N*3); for(let i=0;i<N;i++){ const a=rnd()*TAU, el=Math.asin(rr(.04,1)), r=150;
  pos.set([Math.cos(a)*Math.cos(el)*r,Math.sin(el)*r,Math.sin(a)*Math.cos(el)*r],i*3); const w=rr(.5,1); col.set([w*rr(.8,1),w*rr(.85,1),w],i*3); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,3)); g.setAttribute('color',new T.BufferAttribute(col,3));
  scene.add(new T.Points(g,new T.PointsMaterial({size:1.6,sizeAttenuation:false,vertexColors:true,fog:false,transparent:true,opacity:.9,depthWrite:false}))); })();
const MOON_DIR=V3(-.55,.42,-.72).normalize();
(function(){ const tex=new T.CanvasTexture(makeCanvas(256,256,(x)=>{ let g=x.createRadialGradient(128,128,0,128,128,128); g.addColorStop(0,'rgba(255,255,255,1)'); g.addColorStop(.17,'rgba(240,244,255,1)'); g.addColorStop(.2,'rgba(190,205,255,.35)'); g.addColorStop(.5,'rgba(120,140,220,.08)'); g.addColorStop(1,'rgba(0,0,0,0)'); x.fillStyle=g; x.fillRect(0,0,256,256);
    x.fillStyle='rgba(150,160,190,.35)'; [[118,120,8],[138,134,6],[126,142,5],[112,136,4]].forEach(([a,b,r])=>{ x.beginPath(); x.arc(a,b,r,0,7); x.fill(); }); }));
  const s=new T.Sprite(new T.SpriteMaterial({map:tex,fog:false,depthWrite:false,transparent:true})); s.position.copy(MOON_DIR).multiplyScalar(140); s.scale.setScalar(48); scene.add(s); })();

/* =====================================================================
   PROPS: a flat sandstone slab (the scorpion's shelter), a dead twig, pebbles, loose mud flakes
   ===================================================================== */
const stoneC=makeCanvas(512,512,(g,W,Hh)=>{ g.fillStyle='#5e5044'; g.fillRect(0,0,W,Hh); for(let i=0;i<80;i++){ g.fillStyle=`rgba(${rnd()<.5?'120,90,62':'50,36,26'},.25)`; g.beginPath(); g.arc(rnd()*W,rnd()*Hh,rr(10,60),0,7); g.fill(); }
  for(let i=0;i<9000;i++){ g.fillStyle=`rgba(${rnd()<.5?'40,28,20':'210,180,140'},${rr(.1,.4)})`; g.fillRect(rnd()*W,rnd()*Hh,rr(1,3),rr(1,3)); }
  for(let i=0;i<40;i++){ g.fillStyle=`rgba(${rnd()<.5?'90,110,70':'170,160,120'},.35)`; g.beginPath(); g.arc(rnd()*W,rnd()*Hh,rr(4,16),0,7); g.fill(); } });
const stoneT=dataTex(stoneC); stoneT.encoding=T.sRGBEncoding;
const stoneMat=new T.MeshStandardMaterial({map:stoneT,bumpMap:bumpOf(stoneC),bumpScale:.03,roughness:.88,vertexColors:true});
function rock(x,z,sx,sy,sz,ry){ const g=new T.IcosahedronGeometry(1,5), p=g.attributes.position, q=V3(), uvs=[], col=[];
  for(let i=0;i<p.count;i++){ q.fromBufferAttribute(p,i); const n=1+.1*Math.sin(q.x*3.1+q.z*2.3)+.05*Math.sin(q.y*7+q.x*5)+.025*Math.sin(q.z*13+q.x*4);
    q.multiplyScalar(n); if(q.y>.45) q.y=.45+(q.y-.45)*.25; if(q.y<-.2) q.y=-.2; p.setXYZ(i,q.x,q.y,q.z);
    uvs.push(q.x*.45+.5,q.z*.45+.5+q.y*.5); const band=.82+.18*Math.sin(q.y*26+Math.sin(q.x*3)*1.5); col.push(band,band*.97,band*.94); }
  g.setAttribute('uv',new T.Float32BufferAttribute(uvs,2)); g.setAttribute('color',new T.Float32BufferAttribute(col,3)); g.computeVertexNormals();
  const m=mesh(g,stoneMat,scene,V3(x,H(x,z)+sy*.1,z),V3(sx,sy,sz)); m.rotation.y=ry; return m; }
const SLAB={x:-3.6,z:-2.6,r:2.1};
rock(SLAB.x,SLAB.z,1.9,.6,1.3,.5); rock(4.4,-3.6,.7,.38,.55,1.2); rock(3.2,4.2,.45,.3,.4,2.1);
const woodC=makeCanvas(128,512,(g,W,Hh)=>{ g.fillStyle='#4e463e'; g.fillRect(0,0,W,Hh); for(let i=0;i<120;i++){ g.strokeStyle=`rgba(${rnd()<.5?'50,44,38':'190,182,168'},.5)`; g.lineWidth=rr(1,3); const x=rnd()*W; g.beginPath(); g.moveTo(x,0); g.lineTo(x+rr(-4,4),Hh); g.stroke(); } });
const woodT=dataTex(woodC); woodT.encoding=T.sRGBEncoding; woodT.wrapS=woodT.wrapT=T.RepeatWrapping; woodT.repeat.set(1,3);
const woodMat=new T.MeshStandardMaterial({color:0x8a8075,map:woodT,bumpMap:woodT,bumpScale:.02,roughness:.9});
[[[2.6,0,-2.2],[3.6,0,-1.6],[4.8,0,-1.9],[6.2,0,-1.3]],[[3.6,0,-1.6],[3.9,0,-.7],[4.5,0,-.1]],[[-4.2,0,2.8],[-3,0,3.3],[-1.9,0,3.9]]].forEach((pts,i)=>{
  const P=pts.map(a=>V3(a[0],H(a[0],a[2])+.05,a[2])); mesh(sweep(P,t=>(.07-i*.012)*(1-.5*t),40,8),woodMat,scene); });
// pebbles
(function(){ const N=160, im=new T.InstancedMesh(new T.IcosahedronGeometry(1,2),new T.MeshStandardMaterial({color:0xffffff,roughness:.75}),N), m4=new T.Matrix4(), c=new T.Color();
  for(let i=0;i<N;i++){ const x=rr(-11,11), z=rr(-11,11); if(Math.hypot(x,z)<1.2) continue; const s=rr(.025,.09); _q.setFromEuler(new T.Euler(rr(0,3),rr(0,3),rr(0,3)));
    m4.compose(V3(x,H(x,z)+s*.4,z),_q,V3(s,s*rr(.5,.9),s*rr(.7,1.1))); im.setMatrixAt(i,m4); c.setHSL(rr(.05,.1),rr(.08,.22),rr(.18,.45)).convertSRGBToLinear(); im.setColorAt(i,c); }
  im.castShadow=im.receiveShadow=true; scene.add(im); })();
// loose curled mud flakes the scorpion can kick about
const flakeMat=new T.MeshStandardMaterial({color:lin(0x7a6656),bumpMap:groundB,bumpScale:.01,roughness:.92,side:DS});
const flakes=[];
for(let i=0;i<70;i++){ const sx=rr(.06,.16), sz=sx*rr(.6,1.1), curl=rr(.3,1.2);
  const g=gridGeo(6,6,(u,v)=>{ const a=(u-.5)*2, b=(v-.5)*2, r=Math.hypot(a,b); const k=r>1?1/r:1; return [a*k*sx, (a*a+b*b)*curl*sx*.35, b*k*sz]; });
  const uv=g.attributes.uv, o=[rnd(),rnd()]; for(let j=0;j<uv.count;j++) uv.setXY(j,o[0]+uv.getX(j)*.01,o[1]+uv.getY(j)*.01);
  const m=mesh(g,flakeMat,scene); const a=rnd()*TAU, r=rr(.8,7.5); const f={m,x:Math.cos(a)*r,z:Math.sin(a)*r,vx:0,vz:0,ry:rnd()*TAU,w:0,tilt:rr(-.2,.2),hop:0,vy:0,y:0}; flakes.push(f); }
function nudgeFlakes(x,z,rad,force){ for(const f of flakes){ const dx=f.x-x, dz=f.z-z, d=Math.hypot(dx,dz); if(d<rad&&d>1e-4){ const k=force*(1-d/rad); f.vx+=dx/d*k; f.vz+=dz/d*k; f.w+=rr(-8,8)*k; f.vy=Math.max(f.vy,k*.9); } } }

/* =====================================================================
   PARTICLES: dust puffs from footfalls and lunges, crumbs while feeding
   ===================================================================== */
const PN=420, pPos=new Float32Array(PN*3), pA=new Float32Array(PN), pS=new Float32Array(PN), pC=new Float32Array(PN*3), pV=new Float32Array(PN*3), pL=new Float32Array(PN), pK=new Uint8Array(PN);
const pGeo=new T.BufferGeometry(); pGeo.setAttribute('position',new T.BufferAttribute(pPos,3)); pGeo.setAttribute('aA',new T.BufferAttribute(pA,1)); pGeo.setAttribute('aS',new T.BufferAttribute(pS,1)); pGeo.setAttribute('aC',new T.BufferAttribute(pC,3));
const pMat=new T.ShaderMaterial({uniforms:{uScale:{value:600}},transparent:true,depthWrite:false,
  vertexShader:`uniform float uScale; attribute float aA; attribute float aS; attribute vec3 aC; varying float vA; varying vec3 vC;
    void main(){ vA=aA; vC=aC; vec4 mv=modelViewMatrix*vec4(position,1.); gl_PointSize=aS*uScale/max(.1,-mv.z); gl_Position=projectionMatrix*mv; }`,
  fragmentShader:`varying float vA; varying vec3 vC; void main(){ vec2 d=gl_PointCoord-.5; float r=length(d); if(r>.5) discard; gl_FragColor=vec4(vC, vA*smoothstep(.5,.05,r)); }`});
const parts=new T.Points(pGeo,pMat); parts.frustumCulled=false; scene.add(parts);
let pI=0;
function emit(p,v,size,life,col,kind){ const i=pI; pI=(pI+1)%PN; pPos.set([p.x,p.y,p.z],i*3); pV.set([v.x,v.y,v.z],i*3); pS[i]=size; pL[i]=life; pA[i]=0; pC.set(col,i*3); pK[i]=kind; }
function dust(p,n,str){ for(let k=0;k<n;k++) emit(p,V3(rr(-1,1)*.25*str,rr(.1,.35)*str,rr(-1,1)*.25*str),rr(.05,.12)*(.6+str*.6),rr(.8,1.6),[.55,.48,.42],0); }
function crumb(p){ emit(p,V3(rr(-.15,.15),rr(-.05,.1),rr(-.15,.15)),rr(.012,.022),3,[.12,.08,.05],1); }
for(let i=0;i<PN;i++) pPos[i*3+1]=-99;
function updParts(dt){ for(let i=0;i<PN;i++){ if(pL[i]<=0){ pA[i]=0; continue; } pL[i]-=dt; const k=i*3;
  if(pK[i]===0){ pV[k+1]-=dt*.05; pV[k]*=1-dt*1.5; pV[k+2]*=1-dt*1.5; pV[k+1]*=1-dt*1.2; pS[i]+=dt*.09; pA[i]=Math.min(.42,pL[i]*.35); }
  else { const gy=H(pPos[k],pPos[k+2])+.006; if(pPos[k+1]>gy){ pV[k+1]-=dt*4.5; } else { pPos[k+1]=gy; pV[k]=pV[k+1]=pV[k+2]=0; } pA[i]=Math.min(1,pL[i]); }
  pPos[k]+=pV[k]*dt; pPos[k+1]+=pV[k+1]*dt; pPos[k+2]+=pV[k+2]*dt; }
  pGeo.attributes.position.needsUpdate=pGeo.attributes.aA.needsUpdate=pGeo.attributes.aS.needsUpdate=pGeo.attributes.aC.needsUpdate=true; }

/* =====================================================================
   SCORPION PATTERNS (data textures)
   ===================================================================== */
function granules(g,W,Hh,n,r0,r1,bright,hue){ for(let i=0;i<n;i++){ const x=rnd()*W, y=rnd()*Hh, r=rr(r0,r1); g.fillStyle=D(bright*.6,hue,1,.8); g.beginPath(); g.arc(x+r*.3,y+r*.3,r,0,7); g.fill(); g.fillStyle=D(bright,hue,1); g.beginPath(); g.arc(x,y,r*.8,0,7); g.fill(); } }
function keel(g,y,W,n,r,bright,hue){ for(let i=0;i<n;i++){ const x=(i+.5)/n*W; g.fillStyle=D(bright,hue,1); g.beginPath(); g.arc(x,y+rr(-1,1),r*rr(.8,1.2),0,7); g.fill(); } }
// carapace: u = back→front (canvas x), v = across (canvas y)
const caraC=makeCanvas(512,256,(g,W,Hh)=>{ g.fillStyle=D(.46,.0,1); g.fillRect(0,0,W,Hh);
  granules(g,W,Hh,1400,1,3.2,.66,.03);
  g.fillStyle=D(.22,.05,1); g.fillRect(0,Hh*.49,W*.55,Hh*.02);                     // median furrow
  [-1,1].forEach(s=>{ g.strokeStyle=D(.24,.05,1); g.lineWidth=5; g.beginPath(); g.moveTo(W*.05,Hh*(.5+s*.32)); g.quadraticCurveTo(W*.4,Hh*(.5+s*.12),W*.55,Hh*(.5+s*.05)); g.stroke(); });
  let gr=g.createRadialGradient(W*.62,Hh*.5,0,W*.62,Hh*.5,W*.08); gr.addColorStop(0,D(.12,.1,.6)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh);   // ocular tubercle
  [0,1].forEach(e=>{ gr=g.createLinearGradient(0,e?Hh:0,0,e?Hh*.85:Hh*.15); gr.addColorStop(0,D(.75,.12,1)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh); }); });
const caraT=dataTex(caraC), caraB=bumpOf(caraC);
// tergites: u = back→front, v = across; three granular keels and a dark posterior margin
const tergC=makeCanvas(256,256,(g,W,Hh)=>{ g.fillStyle=D(.48,.0,1); g.fillRect(0,0,W,Hh);
  granules(g,W,Hh,500,1,2.4,.62,.02);
  let gr=g.createLinearGradient(0,0,W*.25,0); gr.addColorStop(0,D(.2,.08,.9)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh);
  [.5,.36,.64].forEach((v,i)=>keel(g,Hh*v,W*.8,i?10:13,i?3.5:4.5,.8,.05));
  [0,1].forEach(e=>{ gr=g.createLinearGradient(0,e?Hh:0,0,e?Hh*.82:Hh*.18); gr.addColorStop(0,D(.72,.15,1)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh); }); });
const tergT=dataTex(tergC), tergB=bumpOf(tergC);
// tail segments: u = along (canvas x), v = around (canvas y): eight granular carinae
const tailC=makeCanvas(256,512,(g,W,Hh)=>{ g.fillStyle=D(.5,.0,1); g.fillRect(0,0,W,Hh); granules(g,W,Hh,600,1,2.2,.6,.02);
  [.06,.19,.31,.44,.56,.69,.81,.94].forEach((v,i)=>keel(g,Hh*v,W,12,i%2?3:4.2,.85,.06));
  [0,1].forEach(e=>{ const gr=g.createLinearGradient(e?W:0,0,e?W*.86:W*.14,0); gr.addColorStop(0,D(.18,.1,.9)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh); }); });
const tailT=dataTex(tailC), tailB=bumpOf(tailC);
// lathe parts (u = around, v = along): pedipalps with granular carinae, legs with darker joints
const palpC=makeCanvas(256,256,(g,W,Hh)=>{ g.fillStyle=D(.5,.0,1); g.fillRect(0,0,W,Hh); granules(g,W,Hh,700,1,2.6,.64,.03);
  for(let k=0;k<6;k++){ const x=(k+.5)/6*W; for(let j=0;j<14;j++){ g.fillStyle=D(.85,.06,1); g.beginPath(); g.arc(x+rr(-1,1),(j+.5)/14*Hh,3.2,0,7); g.fill(); } }
  [0,1].forEach(e=>{ const gr=g.createLinearGradient(0,e?Hh:0,0,e?Hh*.88:Hh*.12); gr.addColorStop(0,D(.2,.1,.9)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh); }); });
const palpT=dataTex(palpC), palpB=bumpOf(palpC);
const legC=makeCanvas(64,256,(g,W,Hh)=>{ g.fillStyle=D(.56,.08,1); g.fillRect(0,0,W,Hh);
  [0,1].forEach(e=>{ const gr=g.createLinearGradient(0,e?Hh:0,0,e?Hh*.8:Hh*.2); gr.addColorStop(0,D(.22,.0,.9)); gr.addColorStop(1,D(.4,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh); });
  for(let i=0;i<300;i++){ g.fillStyle=D(.72,.05,1,.5); g.fillRect(rnd()*W,rnd()*Hh,2,2); } });
const legT=dataTex(legC);

/* =====================================================================
   THE SCORPION   (local: +z = front, +y = dorsal, origin at the prosoma/mesosoma junction)
   ===================================================================== */
const scorp=new T.Group(); scene.add(scorp);
const body=new T.Group(); scorp.add(body);
const BODY_H=.33;
const M={
  cara: iriMat({pat:caraT,bump:caraB,bumpScale:.004,hue:.5,light:.5,rough:.24,metal:.62,glow:.08}),
  terg: iriMat({pat:tergT,bump:tergB,bumpScale:.004,hue:.56,light:.5,rough:.24,metal:.62,glow:.08}),
  tail: iriMat({pat:tailT,bump:tailB,bumpScale:.004,hue:.62,light:.5,rough:.22,metal:.62,glow:.08}),
  palp: iriMat({pat:palpT,bump:palpB,bumpScale:.004,hue:.42,light:.52,rough:.2,metal:.66,glow:.08}),
  hand: iriMat({pat:palpT,bump:palpB,bumpScale:.005,hue:.36,light:.54,rough:.16,metal:.7,glow:.09}),
  finger:iriMat({hue:.3,light:.24,iri:.9,rough:.18,metal:.7,glow:.03}),
  leg:  iriMat({pat:legT,hue:.46,light:.5,rough:.26,metal:.55,glow:.1}),
  dark: iriMat({hue:.6,light:.2,iri:.8,rough:.3,metal:.55,glow:.03}),
  memb: iriMat({hue:.7,light:.3,sat:.5,iri:.4,rough:.55,metal:.2,glow:.04}),
  stern:iriMat({hue:.45,light:.56,sat:.6,iri:.7,rough:.35,metal:.4,glow:.1}),
  vesicle:iriMat({pat:tailT,hue:.75,light:.52,rough:.14,metal:.7,glow:.1}),
  sting:iriMat({hue:.8,light:.12,iri:.9,rough:.12,metal:.8,glow:.0}),
  eye:  new T.MeshPhysicalMaterial({color:lin(0x050408),roughness:.04,metalness:.3,clearcoat:1,clearcoatRoughness:.02,envMapIntensity:2.2}),
  gloss:new T.MeshStandardMaterial({color:0xffffff,roughness:.05,envMapIntensity:2}),
  seta: iriMat({hue:.1,light:.3,sat:.4,iri:.5,rough:.5,glow:0}),
  pect: iriMat({hue:.15,light:.62,sat:.5,iri:.6,rough:.4,metal:.3,glow:.12}),
};

// ---- prosoma: granular carapace with median eyes on a tubercle and lateral eye groups
const caraGeo=gridGeo(28,30,(u,v)=>{ const z=.3+u*.95, w=.47-.13*u*u+.02*Math.sin(u*Math.PI), a=Math.PI*v, h=.2*(1-.35*u)*(1+.12*Math.exp(-(((u-.6)/.12)**2)));
  let notch=u>.92?.05*Math.exp(-(((v-.5)/.08)**2))*(u-.92)/.08:0;
  const sa=Math.sin(a); return [-w*Math.cos(a), h*Math.pow(sa,.6)-.03-.02*(1-sa), z-notch*1.2]; });
mesh(caraGeo, M.cara, body);
mesh(SPH, M.stern, body, V3(0,-.1,.78), V3(.42,.09,.46));                                     // ventral prosoma
mesh(SPH, M.cara, body, V3(0,.205,.86), V3(.1,.05,.09));                                       // ocular tubercle
[-1,1].forEach(s=>{ mesh(SPH, M.eye, body, V3(s*.055,.235,.88), .042); mesh(SPH_LO, M.gloss, body, V3(s*.06,.268,.9), .012);
  [[.37,.08,1.1,.024],[.39,.07,1.06,.022],[.4,.06,1.02,.02],[.385,.05,.985,.016],[.355,.075,1.14,.018]].forEach(([x,y,z,r])=>{ mesh(SPH, M.eye, body, V3(s*x,y,z), r); mesh(SPH_LO, M.gloss, body, V3(s*(x+.004),y+r*.5,z+r*.3), r*.3); }); });
instanced(body, HAIR, M.seta, Array.from({length:60},()=>{ const u=rnd(), v=rr(.1,.9), z=.3+u*.95, w=.47-.13*u*u, a=Math.PI*v; return [V3(-w*Math.cos(a)*.97,.2*(1-.35*u)*Math.pow(Math.sin(a),.6)-.03,z),V3(-Math.cos(a)*.5,1,.4),rr(.025,.05),.004]; }));
// chelicerae: small pincers that tear food
const chel=[];
[-1,1].forEach(s=>{ const g=new T.Group(); g.position.set(s*.065,.02,1.2); body.add(g);
  mesh(alongZ(.14,u=>.05*(1-.25*u)+.01,10,5), M.hand, g);
  mesh(sweep([V3(s*.02,0,.13),V3(s*.008,-.005,.2),V3(-s*.02,-.02,.25)],t=>.02*(1-t)+.004,8,6), M.finger, g);
  const mv=new T.Group(); mv.position.set(-s*.025,-.01,.12); g.add(mv);
  mesh(sweep([V3(),V3(-s*.01,-.015,.06),V3(s*.005,-.035,.11)],t=>.016*(1-t)+.003,8,6), M.finger, mv);
  instanced(g, HAIR, M.seta, Array.from({length:12},()=>[V3(rr(-.03,.03),rr(-.03,.04),rr(.02,.13)),V3(rr(-.3,.3),.3,1),rr(.02,.04),.003]));
  chel.push({g,mv,s}); });

// ---- mesosoma: soft pleural body, seven overlapping tergites, sternites, pectines
mesh(alongZ(2.05,t=>.44*Math.pow(Math.sin(Math.PI*(.06+.88*t)),.45)*(1-.25*(1-t)),24,16), M.memb, body, V3(0,-.01,-1.65), V3(1,.48,1));
const TERG=[[.44,.3],[.48,.02],[.5,-.26],[.5,-.54],[.48,-.82],[.43,-1.1],[.33,-1.38]];
const tergites=[];
TERG.forEach(([w,zc],i)=>{ const last=i===6, L=last?.4:.33;
  const g=gridGeo(10,24,(u,v)=>{ const z=zc-L/2+u*L, a=Math.PI*v, ww=w*(last?(.6+.4*u):1)*(1+.03*Math.sin(Math.PI*u)), sa=Math.sin(a);
    return [-ww*Math.cos(a), .25*Math.pow(sa,.7)*(last?(.75+.25*u):1)-.04*u-.04*(1-sa)+.03, z]; });
  const m=mesh(g, M.terg, body); tergites.push(m);
  const st=mesh(SPH, M.stern, body, V3(0,-.165,zc), V3(w*.62,.045,L*.66)); st.rotation.x=-.04;
  if(i>0&&i<5) [-1,1].forEach(s=>mesh(SPH_LO, M.dark, body, V3(s*w*.42,-.235,zc+.02), V3(.05,.012,.03)));          // spiracles
});
instanced(body, HAIR, M.seta, Array.from({length:90},()=>{ const i=rnd()*7|0, [w,zc]=TERG[i], a=rr(.05,.95)*Math.PI; return [V3(-w*Math.cos(a),.25*Math.pow(Math.sin(a),.7)+.02,zc+rr(-.12,.12)),V3(-Math.cos(a)*.6,1,-.3),rr(.03,.06),.004]; }));
// pectines: comb-like sense organs that sweep the ground
const pectines=[];
[-1,1].forEach(s=>{ const g=new T.Group(); g.position.set(s*.08,-.2,.36); body.add(g);
  const P=[V3(),V3(s*.16,-.04,-.08),V3(s*.32,-.07,-.12)]; mesh(sweep(P,t=>.028*(1-.4*t),12,6), M.pect, g);
  const teeth=[]; for(let k=0;k<16;k++){ const t=k/15, p=bez2(P[0],P[1],P[2],.08+.9*t); teeth.push([p,V3(-s*.25,-1,-.3),.07*(1-.3*t),.011]); }
  instanced(g, CONE, M.pect, teeth); pectines.push({g,s}); });

// ---- metasoma: five keeled segments, then the telson (vesicle + aculeus)
const TAILL=[.46,.5,.55,.6,.7], TAILR=[.2,.19,.18,.175,.17], TAILREST=[.78,.74,.7,.68,.62,.7];
const tailBase=new T.Group(); tailBase.position.set(0,.06,-1.55); body.add(tailBase);
const tailJ=[];
let tp=tailBase;
TAILL.forEach((L,i)=>{ const j=new T.Group(); j.rotation.x=TAILREST[i]; tp.add(j); tailJ.push(j);
  const R=TAILR[i], k8=a=>.06*Math.pow(Math.max(0,Math.cos(a*4)),12);   // eight carinae
  const g=gridGeo(14,32,(u,v)=>{ const a=v*TAU, z=-u*L, flare=1+.08*Math.exp(-(((u-.9)/.08)**2))-.12*Math.exp(-((u/.06)**2))+.04*Math.sin(Math.PI*u),
    r=R*flare*(1+k8(a)), sx=Math.cos(a), sy=Math.sin(a); return [r*sx*1.05, r*sy*(sy>0?.92:.85), z]; });
  mesh(g, M.tail, j);
  mesh(SPH, M.memb, j, V3(0,0,0), V3(R*.85,R*.78,R*.5));                                      // articular membrane
  instanced(j, HAIR, M.seta, Array.from({length:26},()=>{ const a=rnd()*TAU; return [V3(Math.cos(a)*R,Math.sin(a)*R,-rnd()*L),V3(Math.cos(a),Math.sin(a),-.5),rr(.04,.08),.005]; }));
  const n=new T.Group(); n.position.z=-L; j.add(n); tp=n; });
const telson=new T.Group(); telson.rotation.x=TAILREST[5]; tp.add(telson); tailJ.push(telson);
mesh(SPH, M.memb, telson, V3(0,0,0), V3(.13,.12,.08));
mesh(alongZ(.42,t=>.17*Math.pow(Math.sin(Math.PI*Math.min(1,.12+t*.95)),.7)+.01,24,16).rotateY(Math.PI), M.vesicle, telson, V3(0,-.02,-.02), V3(1,.92,1));
const STING=[V3(0,-.05,-.38),V3(0,-.07,-.52),V3(0,-.16,-.62),V3(0,-.3,-.64)];
mesh(sweep(STING,t=>.06*Math.pow(1-t,1.2)+.003,16,8), M.sting, telson);
mesh(SPH, M.sting, telson, V3(0,-.13,-.4), V3(.035,.03,.035));                                  // subaculear tubercle
instanced(telson, HAIR, M.seta, Array.from({length:40},()=>{ const a=rnd()*TAU, z=-rr(.05,.38); return [V3(Math.cos(a)*.15,Math.sin(a)*.14-.02,z),V3(Math.cos(a),Math.sin(a),-.4),rr(.04,.08),.005]; }));
const stingTip=new T.Object3D(); stingTip.position.copy(STING[3]); telson.add(stingTip);
const venom=mesh(SPH, new T.MeshPhysicalMaterial({color:lin(0xe8f6ff),roughness:.02,transmission:.0,clearcoat:1,transparent:true,opacity:.85,envMapIntensity:2.5}), telson, STING[3].clone().add(V3(0,-.01,0)), .001);

// ---- pedipalps: trochanter, femur, patella (two-bone IK) and the chela (manus + fixed + movable finger)
const palps=[];
const PF=.56, PP=.6;
[-1,1].forEach(s=>{
  const sh=V3(s*.3,.02,1.1);
  mesh(SPH, M.palp, body, sh, V3(.1,.08,.1));
  const fem=new T.Group(), pat=new T.Group(), hand=new T.Group(); body.add(fem,pat,hand);
  mesh(alongX(PF,t=>.075*(1-.15*t)+.012*Math.sin(Math.PI*t),14,10), M.palp, fem);
  mesh(SPH, M.palp, fem, V3(PF,0,0), V3(.085,.08,.08));
  mesh(alongX(PP,t=>.08+.022*Math.sin(Math.PI*t)-.02*t,14,10), M.palp, pat);
  instanced(fem, HAIR, M.seta, Array.from({length:20},()=>{ const a=rnd()*TAU; return [V3(rnd()*PF,Math.cos(a)*.08,Math.sin(a)*.08),V3(.3,Math.cos(a),Math.sin(a)),rr(.04,.07),.004]; }));
  instanced(pat, HAIR, M.seta, Array.from({length:14},()=>{ const a=rnd()*TAU; return [V3(rnd()*PP,Math.cos(a)*.09,Math.sin(a)*.09),V3(.2,Math.cos(a),Math.sin(a)),rr(.1,.16),.0035]; }));   // trichobothria
  // chela: x = pointing, z: inner side = s*z. A swollen manus, then two curved, toothed fingers
  mesh(alongX(.56,t=>.17*Math.pow(Math.sin(Math.PI*(.06+.7*t)),.5)+.03-.03*t,26,16).scale(1,.72,1.08), M.hand, hand, V3(-.04,0,0));
  mesh(SPH, M.hand, hand, V3(.08,.0,-s*.04), V3(.16,.1,.13));
  const fixedPts=[V3(.44,.02,s*.07),V3(.6,.03,s*.075),V3(.76,.01,s*.045),V3(.88,-.02,-s*.005)];
  mesh(sweep(fixedPts,t=>.07*(1-.8*t)+.008,18,10), M.finger, hand);
  const mov=new T.Group(); mov.position.set(.42,.0,-s*.07); hand.add(mov);
  const movPts=[V3(),V3(.17,.01,-s*.015),V3(.33,0,s*.02),V3(.46,-.02,s*.075)];
  mesh(sweep(movPts,t=>.062*(1-.8*t)+.008,18,10), M.finger, mov);
  mesh(SPH, M.finger, mov, V3(), V3(.06,.055,.06));
  const dF=[], dM=[];
  for(let k=0;k<16;k++){ const t=.08+.84*k/15; const pf=new T.CatmullRomCurve3(fixedPts).getPointAt(t); dF.push([pf.clone().add(V3(0,0,-s*(.05*(1-.8*t)+.005))),V3(0,-.2,-s),.022,.008]);
    const pm=new T.CatmullRomCurve3(movPts).getPointAt(t); dM.push([pm.clone().add(V3(0,0,s*(.045*(1-.8*t)+.005))),V3(0,-.2,s),.022,.008]); }
  instanced(hand, CONE, M.dark, dF); instanced(mov, CONE, M.dark, dM);
  instanced(hand, HAIR, M.seta, Array.from({length:36},()=>{ const a=rnd()*TAU, x=rr(.05,.46); return [V3(x,Math.cos(a)*.13,Math.sin(a)*.17),V3(.3,Math.cos(a),Math.sin(a)),rr(.06,.14),.0035]; }));
  palps.push({s,sh,fem,pat,hand,mov,wrist:V3(s*.48,.08,1.85),dir:V3(-s*.3,-.1,1).normalize(),open:.2,
    tW:V3(),tD:V3(),tO:.2,vW:V3(),elbow:V3(),w2:V3()});
});

// ---- eight walking legs: coxa, trochanter, femur, patella+tibia, tarsi, claws (three-bone IK)
const legs=[];
const LEGDEF=[
  {z:1.02, a:.44,b:.47,c:.46, home:[.9,1.55], hip:.3},
  {z:.86,  a:.5, b:.54,c:.5,  home:[1.14,.98], hip:.34},
  {z:.68,  a:.56,b:.6, c:.56, home:[1.24,.22], hip:.36},
  {z:.5,   a:.63,b:.7, c:.66, home:[1.16,-.58], hip:.34},
];
function buildLeg(D,s,li){
  const hip=V3(s*.18,-.12,D.z), tro=V3(s*D.hip,-.1,D.z+(li-1.5)*-.03);
  const cg=new T.Group(); body.add(cg); orient(cg,hip,tro,UP); mesh(alongX(hip.distanceTo(tro)+.04,t=>.065*(1-.2*t)+.01,10,4), M.stern, cg);
  const fem=new T.Group(), tib=new T.Group(), tar=new T.Group(); body.add(fem,tib,tar);
  const r0=.07+li*.006;
  mesh(alongX(D.a,t=>r0*(1-.2*t)+.008*Math.sin(Math.PI*t),12,8), M.leg, fem);
  mesh(SPH, M.leg, fem, V3(D.a,0,0), V3(r0*.95,r0*.9,r0*.85));                                   // patella knee
  mesh(alongX(D.b,t=>r0*.8*(1-.25*t)+.006,12,8), M.leg, tib);
  mesh(alongX(D.c*.6,t=>r0*.55*(1-.25*t)+.004,10,6), M.leg, tar);
  mesh(alongX(D.c*.4,t=>r0*.4*(1-.45*t)+.003,8,4), M.dark, tar, V3(D.c*.6,0,0));
  [-1,1].forEach(cs=>{ const cl=mesh(alongX(.05,u=>.008*(1-u)+.001,5,3), M.dark, tar, V3(D.c-.01,0,cs*.008)); cl.rotation.set(0,cs*.4,-1.2); });
  // tibial spurs and setae
  instanced(tib, CONE, M.dark, [[V3(D.b*.96,-r0*.5,r0*.3),V3(1,-.6,.3),.06,.009],[V3(D.b*.96,-r0*.5,-r0*.3),V3(1,-.6,-.3),.06,.009]]);
  const hr=[]; [[fem,D.a,r0],[tib,D.b,r0*.8],[tar,D.c*.6,r0*.55]].forEach(([g,L,r])=>{ for(let k=0;k<16;k++){ const x=rnd()*L, a=rnd()*TAU; hr.push([g,V3(x,Math.cos(a)*r,Math.sin(a)*r),V3(.6,Math.cos(a),Math.sin(a)),rr(.03,.06),.0035]); } });
  [fem,tib,tar].forEach(g=>instanced(g,HAIR,M.seta,hr.filter(x=>x[0]===g).map(x=>x.slice(1))));
  const L={D,s,li,tro,fem,tib,tar,home:V3(s*D.home[0],-BODY_H,D.home[1]),toe:V3(),lift:V3(),target:V3(),step:-1,group:((li%2===0)===(s>0))?0:1};
  legs.push(L); return L;
}
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>buildLeg(D,s,i)));

/* =====================================================================
   PREY: a field cricket (natural colours)
   ===================================================================== */
const crC=makeCanvas(256,128,(g,W,Hh)=>{ g.fillStyle='#3a2a1c'; g.fillRect(0,0,W,Hh); g.strokeStyle='rgba(20,12,8,.9)'; g.lineWidth=2;
  for(let k=0;k<9;k++){ g.beginPath(); g.moveTo(0,Hh*(.1+k*.1)); g.bezierCurveTo(W*.3,Hh*(.1+k*.1)+rr(-10,10),W*.6,Hh*(.15+k*.09),W,Hh*(.12+k*.1)); g.stroke(); }
  for(let k=0;k<26;k++){ g.beginPath(); const x=rnd()*W; g.moveTo(x,0); g.lineTo(x+rr(-20,20),Hh); g.stroke(); }
  g.fillStyle='rgba(150,120,80,.35)'; g.fillRect(0,0,W,Hh*.18); });
const crT=dataTex(crC); crT.encoding=T.sRGBEncoding;
const CM={ body:new T.MeshPhysicalMaterial({color:lin(0x251a12),roughness:.35,clearcoat:.6,clearcoatRoughness:.3}),
  leg:new T.MeshStandardMaterial({color:lin(0x4a3424),roughness:.5}), wing:new T.MeshStandardMaterial({map:crT,roughness:.45,side:DS,transparent:true,opacity:.96}),
  eye:new T.MeshPhysicalMaterial({color:lin(0x110a06),roughness:.1,clearcoat:1}), spine:new T.MeshStandardMaterial({color:lin(0x18100a),roughness:.5}) };
function makeCricket(){
  const root=new T.Group(), b=new T.Group(); root.add(b);
  mesh(SPH, CM.body, b, V3(0,.03,.25), V3(.085,.09,.08));
  [-1,1].forEach(s=>mesh(SPH, CM.eye, b, V3(s*.068,.07,.27), .028));
  mesh(SPH, CM.body, b, V3(0,.045,.15), V3(.095,.075,.075));
  const abd=mesh(SPH, CM.body, b, V3(0,0,-.1), V3(.09,.075,.2));
  [-1,1].forEach(s=>{ const c=mesh(CONE, CM.leg, b, V3(s*.03,.01,-.27), V3(.012,.18,.012)); c.rotation.set(-1.75,0,s*.3); });
  const ov=mesh(CONE, CM.spine, b, V3(0,.0,-.28), V3(.01,.24,.01)); ov.rotation.x=-1.62;
  const wings=[]; [-1,1].forEach(s=>{ const p=new T.Group(); p.position.set(s*.01,.075,.12); b.add(p);
    mesh(gridGeo(10,6,(u,v)=>{ const w=.1; const x=v*w; return [s*x, -(x>.075?(x-.075)*1.6:0)-u*.01, -u*.42]; }), CM.wing, p); wings.push({p,s}); });
  const ants=[]; [-1,1].forEach(s=>{ const a=new T.Group(); a.position.set(s*.03,.08,.31); b.add(a);
    mesh(sweep([V3(),V3(s*.12,.12,.25),V3(s*.35,.15,.35),V3(s*.62,.08,.25),V3(s*.8,.0,.05)],t=>.006*(1-.7*t)+.0015,30,4), CM.leg, a); ants.push({a,s}); });
  const lg=[];
  [[.17,.55,.11,.13,.0],[.08,.15,.12,.14,.0],[-.02,-.25,.28,.3,1]].forEach(([z,yaw,lf,lt,hind])=>[-1,1].forEach(s=>{
    const r=new T.Group(); r.position.set(s*.06,-.01,z); r.rotation.y=s*(Math.PI/2-yaw)*(hind?1.25:1); b.add(r);
    const f=new T.Group(); r.add(f); mesh(alongX(lf,t=>hind?(.04*Math.sin(Math.PI*(.15+.8*t))+.01):(.014*(1-.3*t)+.004),10,6).scale(s,1,1), CM.leg, f);
    const t=new T.Group(); t.position.x=s*lf; f.add(t); mesh(alongX(lt,u=>(hind?.012:.009)*(1-.4*u)+.003,8,4).scale(s,1,1), CM.leg, t);
    if(hind) instanced(t, CONE, CM.spine, Array.from({length:8},(v,k)=>[V3(s*lt*(.2+k*.1),0,(k%2?1:-1)*.008),V3(s*.3,-.2,(k%2?1:-1)),.03,.005]));
    const ta=mesh(alongX(.07,u=>.006,5,2).scale(s,1,1), CM.leg, t, V3(s*lt,0,0)); ta.rotation.z=s*.6;
    lg.push({r,f,t,s,hind,z}); }));
  return {root,b,abd,wings,ants,lg};
}
const CRS=1.3, cr=makeCricket(); scene.add(cr.root); cr.root.visible=false; cr.b.position.y=0; cr.root.scale.setScalar(CRS);
let remains=null;
const CR_H=.13;
function poseCricket(t,mode,kick,jump){
  // jump: 0 crouched/standing, 1 fully extended (take-off)
  cr.lg.forEach(L=>{ const ph=t*14+L.z*20+(L.s>0?0:1.7);
    if(L.hind){ L.f.rotation.z=L.s*(.95-.8*jump+kick*.4*Math.sin(ph)); L.t.rotation.z=-L.s*(2.45-1.9*jump-kick*.6*Math.sin(ph+1)); }
    else { L.f.rotation.z=L.s*(.55+kick*.5*Math.sin(ph)); L.t.rotation.z=-L.s*(1.45+kick*.5*Math.sin(ph+1.3)); } });
  cr.ants.forEach(A=>{ A.a.rotation.set(.15*Math.sin(t*2.3+A.s)+(mode==='held'?.4*Math.sin(t*9+A.s):0),.25*Math.sin(t*1.7+A.s*2),0); });
  const chirp=mode==='chirp';
  cr.wings.forEach(W=>{ W.p.rotation.x=chirp?.32+.05*Math.sin(t*90):(mode==='air'?.15:0); W.p.rotation.z=W.s*(chirp?.12:0)+(mode==='held'?W.s*kick*.3*Math.sin(t*30):0); });
}

/* lights: moon key (shadows), cool sky fill, a UV-lamp style violet front light, iridescent rims */
scene.add(new T.HemisphereLight(0x5a6aa8,0x2a1c12,.55));
const moon=new T.DirectionalLight(0xc8d4ff,1.7); moon.castShadow=true; moon.shadow.mapSize.set(2048,2048);
Object.assign(moon.shadow.camera,{left:-4.5,right:4.5,top:4.5,bottom:-4.5,near:1,far:40}); moon.shadow.bias=-.0004; moon.shadow.normalBias=.02; scene.add(moon,moon.target);
const uv=new T.DirectionalLight(0xa58aff,.75); scene.add(uv,uv.target);
const rim=new T.PointLight(0x33ccff,1.6,40); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.2,40); scene.add(rim2);
const glint=new T.PointLight(0xffffff,.9,30); scene.add(glint);

/* =====================================================================
   BEHAVIOUR
   wander (pectines tasting the ground) → a cricket hops in and chirps → the scorpion freezes, turns,
   raises open chelae → stalks → lunges and seizes it → lifts it and stings over its head →
   tears and feeds with the chelicerae → drops the remains → wanders on
   ===================================================================== */
const sc={x:0,z:0,head:0,speed:0,pitch:0,roll:0,y:BODY_H,lunge:0,lungeV:0}, LUNGE_TO=2.0;
const st={mode:'wander',t:0,dur:3}, go=(m,d=99)=>{ st.mode=m; st.t=0; st.dur=d; };
const wp={x:0,z:0,pause:0}; pickWaypoint();
function pickWaypoint(){ for(let k=0;k<30;k++){ const a=rr(0,TAU), r=rr(1,4.2), x=Math.cos(a)*r, z=Math.sin(a)*r; if(Math.hypot(x-SLAB.x,z-SLAB.z)>SLAB.r+1.2&&Math.hypot(x-sc.x,z-sc.z)>1.5){ wp.x=x; wp.z=z; break; } } }
const prey={mode:'none',t:0,hops:[],hop:0,p0:V3(),p1:V3(),pos:V3(),head:0,kick:0,life:1,eaten:0,hold:V3(),holdFrom:V3(),q:new T.Quaternion()};
let nextCricket=4, stings=0;
const _f=V3(),_r=V3(),_n=V3(),_t=V3(),_ank=V3(),_d=V3(),_w=V3(),_kn=V3(),_a2=V3(),_toe=V3(),_hw=V3(),_tmp=V3(),_tmp2=V3(),_g=V3();
const fwd=()=>_f.set(Math.sin(sc.head),0,Math.cos(sc.head));
function placeScorp(dt){
  fwd(); _r.set(_f.z,0,-_f.x);
  const hF=H(sc.x+_f.x*1,sc.z+_f.z*1), hB=H(sc.x-_f.x*1,sc.z-_f.z*1), hL=H(sc.x+_r.x*.8,sc.z+_r.z*.8), hR=H(sc.x-_r.x*.8,sc.z-_r.z*.8), h0=H(sc.x,sc.z);
  const k=1-Math.exp(-dt*6);
  sc.pitch=lerp(sc.pitch,Math.atan2(hB-hF,2),k); sc.roll=lerp(sc.roll,Math.atan2(hL-hR,1.6),k);
  sc.y=lerp(sc.y,Math.max(h0,(hF+hB+hL+hR)/4)+BODY_H,k);
  scorp.position.set(sc.x,sc.y,sc.z); scorp.rotation.set(0,0,0); scorp.rotateY(sc.head); scorp.rotateX(sc.pitch); scorp.rotateZ(-sc.roll);
}
function solve2(root,target,l1,l2,bend,outKnee,outEnd){
  _d.subVectors(target,root); const c=clamp(_d.length(),Math.abs(l1-l2)+.01,(l1+l2)*.995); _d.normalize();
  _w.copy(bend).addScaledVector(_d,-bend.dot(_d)).normalize();
  const al=Math.acos(clamp((l1*l1+c*c-l2*l2)/(2*l1*c),-1,1));
  outKnee.copy(root).addScaledVector(_d,l1*Math.cos(al)).addScaledVector(_w,l1*Math.sin(al)); outEnd.copy(root).addScaledVector(_d,c); return _w;
}
function turnToward(ang,dt,rate){ const d=angWrap(ang-sc.head); sc.head+=clamp(d,-rate*dt,rate*dt); return Math.abs(d); }
function moveFwd(dt,v){ fwd(); sc.x+=_f.x*v*dt; sc.z+=_f.z*v*dt; sc.speed=v; }
const toLocal=(w,out)=>body.worldToLocal(out.copy(w));
const toWorld=(l,out)=>body.localToWorld(out.copy(l));

function spawnCricket(){
  fwd(); const side=rnd()<.5?1:-1, a=sc.head+side*rr(.5,1.1), land=V3(sc.x+Math.sin(a)*2.6,0,sc.z+Math.cos(a)*2.6);
  const from=Math.atan2(land.x-sc.x,land.z-sc.z)+side*rr(.6,1.2); prey.hops=[];
  let p=V3(land.x+Math.sin(from)*4.6,0,land.z+Math.cos(from)*4.6); for(let k=0;k<4;k++){ prey.hops.push(p.clone()); p.lerp(land,1/(4-k)); } prey.hops.push(land.clone());
  prey.hop=0; prey.mode='crouch'; prey.t=0; prey.pos.copy(prey.hops[0]); prey.pos.y=H(prey.pos.x,prey.pos.z)+CR_H; prey.kick=0; prey.life=1; prey.eaten=0;
  cr.root.visible=true; cr.b.scale.setScalar(1); cr.abd.scale.set(.09,.075,.2);
  if(remains) remains.userData.fade=1;
}
function cricketOnGround(dt,t){
  const p=prey.pos; p.y=H(p.x,p.z)+CR_H; cr.root.position.copy(p); groundNormal(p.x,p.z,_n);
  _q.setFromUnitVectors(UP,_n); cr.root.quaternion.setFromAxisAngle(UP,prey.head).premultiply(_q);
}
function cricketWorldPoint(local,out){ return cr.b.localToWorld(out.copy(local)); }

// tail: planar CCD toward a goal, blended from the rest pose
const restTip=V3();
function solveTail(goal,w){
  tailBase.updateMatrixWorld(true); stingTip.getWorldPosition(restTip);
  if(w<=.001) return; _g.lerpVectors(restTip,goal,w);
  // yaw the tail base toward the goal
  const gl=tailBase.parent.worldToLocal(_tmp2.copy(_g)); tailBase.rotation.y=lerp(tailBase.rotation.y,clamp(Math.atan2(gl.x,Math.max(.3,gl.z-tailBase.position.z)),-.6,.6),w);
  for(let it=0;it<8;it++) for(let k=tailJ.length-1;k>=0;k--){ const j=tailJ[k]; tailBase.updateMatrixWorld(true);
    j.getWorldPosition(_t); stingTip.getWorldPosition(_tmp); _x.setFromMatrixColumn(j.matrixWorld,0).normalize();
    _tmp.sub(_t); _d.copy(_g).sub(_t); _tmp.addScaledVector(_x,-_tmp.dot(_x)); _d.addScaledVector(_x,-_d.dot(_x));
    if(_tmp.lengthSq()<1e-8||_d.lengthSq()<1e-8) continue;
    const ang=Math.atan2(_x.dot(_y.crossVectors(_tmp,_d)),_tmp.dot(_d)); j.rotation.x=clamp(j.rotation.x+ang*.7,-.6,1.3); }
  tailBase.updateMatrixWorld(true);
}

const strike={w:0,phase:'none',t:0}, STING_HOLD=V3(0,.72,1.42);
function update(dt,t){
  st.t+=dt; prey.t+=dt; sc.speed=0;
  // ---------- cricket
  if(prey.mode==='none'){ if(st.mode==='wander'&&!reduceMotion){ nextCricket-=dt; if(nextCricket<=0) spawnCricket(); } }
  else if(prey.mode==='crouch'||prey.mode==='air'){
    const a=prey.hops[prey.hop], b=prey.hops[prey.hop+1]; prey.head=Math.atan2(b.x-a.x,b.z-a.z);
    if(prey.mode==='crouch'){ poseCricket(t,'idle',0,-.1*smooth(prey.t/.3)); cricketOnGround(dt,t); if(prey.t>.35){ prey.mode='air'; prey.t=0; dust(prey.pos,4,.6); nudgeFlakes(prey.pos.x,prey.pos.z,.2,.4); } }
    else { const s=Math.min(1,prey.t/.48); prey.pos.lerpVectors(a,b,s); prey.pos.y=lerp(H(a.x,a.z),H(b.x,b.z),s)+CR_H+Math.sin(Math.PI*s)*.75;
      cr.root.position.copy(prey.pos); cr.root.rotation.set(0,prey.head,0); cr.root.rotateX(-.5*Math.cos(Math.PI*s)); poseCricket(t,'air',0,1-.6*s);
      if(s>=1){ prey.hop++; prey.t=0; dust(b,5,.7); nudgeFlakes(b.x,b.z,.25,.5);
        if(prey.hop>=prey.hops.length-1){ prey.mode='chirp'; prey.head=Math.atan2(sc.x-b.x,sc.z-b.z)+rr(-1.4,1.4); if(st.mode==='wander') go('alert',1.2); } else prey.mode='crouch'; } } }
  else if(prey.mode==='chirp'){ poseCricket(t,Math.sin(t*1.3)>-.2?'chirp':'idle',0,0); cricketOnGround(dt,t); }
  else if(prey.mode==='held'){ prey.kick=lerp(prey.kick,prey.life*(.6+.4*Math.sin(t*3)),1-Math.exp(-dt*5)); poseCricket(t,prey.life>.2?'held':'limp',prey.kick,.3); }
  else if(prey.mode==='drop'){ prey.pos.y-=dt*2.2*Math.min(1,prey.t*3); const gy=H(prey.pos.x,prey.pos.z)+.03; cr.root.position.copy(prey.pos);
    if(prey.pos.y<=gy){ prey.pos.y=gy; cr.root.position.copy(prey.pos); dust(prey.pos,3,.4);
      remains=cr.root.clone(); remains.userData.fade=0; scene.add(remains); cr.root.visible=false; prey.mode='none'; nextCricket=rr(6,9); } }
  if(remains&&remains.userData.fade){ remains.userData.fade-=dt*.6; remains.scale.setScalar(Math.max(.001,remains.userData.fade)); remains.position.y-=dt*.02; if(remains.userData.fade<=0){ scene.remove(remains); remains=null; } }

  // ---------- scorpion
  const cp=prey.pos, toPrey=Math.atan2(cp.x-sc.x,cp.z-sc.z), dPrey=Math.hypot(cp.x-sc.x,cp.z-sc.z);
  let palpMode='rest';
  if(st.mode==='wander'){
    const dx=wp.x-sc.x, dz=wp.z-sc.z, d=Math.hypot(dx,dz);
    if(wp.pause>0){ wp.pause-=dt; palpMode='rest'; }
    else { const left=turnToward(Math.atan2(dx,dz),dt,1.4); if(left<.7) moveFwd(dt,.55*smooth(1-left/.7)*Math.min(1,d/.4+.3)); if(d<.25){ wp.pause=rr(1.5,3.5); pickWaypoint(); } }
  }
  else if(st.mode==='alert'){ palpMode='raise'; turnToward(toPrey,dt,1.6); if(st.t>st.dur&&Math.abs(angWrap(toPrey-sc.head))<.15) go('stalk'); }
  else if(st.mode==='stalk'){ palpMode='raise'; turnToward(toPrey,dt,1.5); const v=dPrey>2.5?.38:(dPrey<2.15?-.3:0); moveFwd(dt,v*(.6+.4*Math.max(0,Math.sin(t*3))));
    if(dPrey<=2.52&&dPrey>=2.1&&Math.abs(angWrap(toPrey-sc.head))<.08){ go('lunge',.32); sc.lungeV=(dPrey-LUNGE_TO)/(st.dur*.7); } }
  else if(st.mode==='lunge'){ palpMode='grab'; const s=st.t/st.dur; turnToward(toPrey,dt,2); moveFwd(dt,s<.7?sc.lungeV:0); sc.lunge=Math.sin(Math.PI*Math.min(1,s));
    if(st.t>.05&&st.t-dt<=.05){ fwd(); dust(_tmp.set(sc.x+_f.x*1.2,sc.y-BODY_H,sc.z+_f.z*1.2),8,1.2); }
    if(st.t>=st.dur){ go('lift',.8); prey.mode='held'; toLocal(cp,prey.holdFrom); prey.hold.copy(prey.holdFrom); dust(cp,6,1); nudgeFlakes(cp.x,cp.z,.4,.8);
      _q.copy(scorp.quaternion).invert(); prey.q.copy(_q.multiply(cr.root.quaternion)); stings=0; } }
  else if(st.mode==='lift'){ palpMode='hold'; prey.hold.lerpVectors(prey.holdFrom,STING_HOLD,smooth(st.t/st.dur)); if(st.t>=st.dur){ go('sting',1.5); strike.t=0; } }
  else if(st.mode==='sting'){ palpMode='hold'; prey.hold.copy(STING_HOLD);
    if(st.t>=st.dur){ stings++; if(stings<2) go('sting',1.3); else go('eat',9); } }
  else if(st.mode==='eat'){ palpMode='eat'; prey.hold.lerp(V3(0,.12,1.55),1-Math.exp(-dt*3)); prey.eaten=Math.min(1,prey.eaten+dt/st.dur*1.1);
    if(rnd()<dt*10){ toWorld(_tmp.set(rr(-.1,.1),.0,1.4),_tmp); crumb(_tmp); }
    if(st.t>=st.dur){ go('release',.7); } }
  else if(st.mode==='release'){ palpMode='release'; if(st.t>=st.dur){ prey.mode='drop'; prey.t=0; toWorld(prey.hold,prey.pos); go('back',1.2); } }
  else if(st.mode==='back'){ palpMode='rest'; moveFwd(dt,-.35); if(st.t>=st.dur){ go('wander'); wp.pause=rr(1,2); pickWaypoint(); } }
  if(st.mode!=='lunge') sc.lunge=lerp(sc.lunge,0,1-Math.exp(-dt*6));
  sc.x=clamp(sc.x,-8,8); sc.z=clamp(sc.z,-8,8);
  placeScorp(dt); scorp.updateMatrixWorld(true);

  // the held cricket follows the chelae
  if(prey.mode==='held'){ const wig=prey.life*.25; cr.root.position.copy(toWorld(prey.hold,_tmp));
    const qq=new T.Quaternion().setFromEuler(new T.Euler(wig*Math.sin(t*11),wig*.6*Math.sin(t*7),wig*Math.sin(t*9)));
    const turnIn=new T.Quaternion().setFromAxisAngle(UP,Math.PI/2*smooth(st.mode==='lift'?st.t/st.dur:1)*(['lift','sting','eat','release'].includes(st.mode)?1:0));
    const base=prey.q.clone().slerp(turnIn,(['sting','eat','release'].includes(st.mode)?1:smooth(st.mode==='lift'?st.t/st.dur:0)));
    if(st.mode==='eat') base.multiply(new T.Quaternion().setFromAxisAngle(V3(1,0,0),.9*smooth(st.t/2)));
    cr.root.quaternion.copy(scorp.quaternion).multiply(base).multiply(qq);
    const e=prey.eaten; cr.abd.scale.set(.09*(1-.5*e),.075*(1-.6*e),.2*(1-.55*e)); cr.b.scale.setScalar(1-.25*e);
    cr.root.updateMatrixWorld(true); }

  // ---------- pedipalps
  palps.forEach(P=>{ const s=P.s;
    if(palpMode==='rest'){ P.tW.set(s*.5,.1+.03*Math.sin(t*.9+s),1.78+.03*Math.sin(t*.7+s)); P.tD.set(-s*.3,-.12,1); P.tO=.18+.1*Math.max(0,Math.sin(t*.8+s*2)); }
    else if(palpMode==='raise'){ P.tW.set(s*.62,.32,1.82); P.tD.set(-s*.12,.08,1); P.tO=.95; }
    else if(palpMode==='grab'){ const s1=st.t/st.dur; cricketWorldPoint(_tmp.set(0,0,s>0?.13:-.13),_tmp); toLocal(_tmp,_tmp2);
      // reach out around the cricket and snap shut
      P.tD.set(-s*.6,-.15,.8).normalize(); P.tW.copy(_tmp2).addScaledVector(P.tD,-.66); P.tO=s1<.75?1:0; }
    else if(palpMode==='hold'||palpMode==='eat'||palpMode==='release'){
      // pinch whichever end of the cricket is on this side
      const loc=toLocal(cricketWorldPoint(_tmp.set(0,0,.13),_tmp),V3()), loc2=toLocal(cricketWorldPoint(_g.set(0,0,-.13),_g),V3());
      const mine=(loc.x*s>loc2.x*s)?loc:loc2; P.tD.set(-s*.7,-.1,.7).normalize(); P.tW.copy(mine).addScaledVector(P.tD,-.64); P.tO=palpMode==='release'?.9:(palpMode==='eat'?.05+.05*Math.sin(t*3+s):0); }
    const k=1-Math.exp(-dt*(palpMode==='grab'?22:7));
    P.wrist.lerp(P.tW,k); P.dir.lerp(P.tD,k).normalize(); P.open=lerp(P.open,P.tO,1-Math.exp(-dt*(P.tO<P.open?30:8)));
    const w=solve2(P.sh,P.wrist,PF,PP,V3(s*1,.7,-.3),P.elbow,P.w2);
    orient(P.fem,P.sh,P.elbow,w); orient(P.pat,P.elbow,P.w2,w);
    _tmp.copy(P.w2).add(P.dir); orient(P.hand,P.w2,_tmp,UP);
    P.mov.rotation.y=s*(.02+.6*P.open);
  });

  // ---------- tail: rest arch with sway, cocked when alert, CCD strikes during stinging
  const alertA=['alert','stalk','lunge'].includes(st.mode)?1:0;
  tailJ.forEach((j,i)=>{ j.rotation.x=TAILREST[i]+.05*Math.sin(t*1.1-i*.5)+alertA*.06*(i<3?1:-1)+(st.mode==='lunge'?.1:0); });
  tailBase.rotation.y=.08*Math.sin(t*.7);
  if(st.mode==='sting'){ const s=st.t; strike.w= s<.22?smooth(s/.22): s<.85?1: Math.max(0,1-smooth((s-.85)/.4));
    if(s>.22&&s<.85&&prey.life>0){ prey.life=Math.max(0,prey.life-dt*(stings?1.6:.9)); } }
  else strike.w=lerp(strike.w,0,1-Math.exp(-dt*8));
  if(strike.w>.001&&prey.mode==='held'){ cricketWorldPoint(_tmp.set(0,.06,.05),_tmp); const pump=st.mode==='sting'&&st.t>.22&&st.t<.85?.03*Math.sin(st.t*40):0; _tmp.y+=.02+pump; solveTail(_tmp,strike.w); }
  else solveTail(_tmp,0);
  venom.scale.setScalar(st.mode==='sting'&&st.t>.5&&st.t<1.1?.03*smooth((st.t-.5)/.2):(st.mode==='alert'||st.mode==='stalk')?.02+.004*Math.sin(t*3):.001);

  // ---------- legs: feet planted on the clay; alternating tetrapod gait
  const fast=st.mode==='lunge';
  for(const L of legs){
    if(L.step>=0){ L.step+=dt/(fast?.1:.2); 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))*.16;
      if(L.step>=1){ L.step=-1; L.toe.copy(L.target); if(rnd()<.6) dust(L.toe,1,.25); nudgeFlakes(L.toe.x,L.toe.z,.12,.35); } }
    else { toWorld(L.home,_hw); _hw.y=H(_hw.x,_hw.z); const busy=legs.some(o=>o.step>=0&&o.group!==L.group), dist=L.toe.distanceTo(_hw);
      if((!busy&&dist>.26)||dist>.75){ L.step=0; L.lift.copy(L.toe); fwd(); L.target.copy(_hw).addScaledVector(_f,Math.sign(sc.speed)*.12); L.target.y=H(L.target.x,L.target.z); } }
  }
  for(const L of legs){ const {a,b,c}=L.D;
    toLocal(L.toe,_toe);
    _tmp.set(L.tro.x-_toe.x,0,L.tro.z-_toe.z).normalize().multiplyScalar(.55).add(V3(0,.85,0)).normalize();
    _ank.copy(_toe).addScaledVector(_tmp,c);
    const w=solve2(L.tro,_ank,a,b,V3(L.s*.75,1,0),_kn,_a2);
    orient(L.fem,L.tro,_kn,w); orient(L.tib,_kn,_a2,w); orient(L.tar,_a2,_toe,w);
  }

  // ---------- small details
  pectines.forEach(({g,s})=>{ const sweepA=sc.speed>.05||st.mode==='wander'?.25*Math.sin(t*5+s):.08*Math.sin(t*2+s); g.rotation.set(-.15+.1*Math.sin(t*3),s*sweepA,s*(.2+.12*Math.sin(t*4))); });
  chel.forEach(({g,mv,s})=>{ const eating=st.mode==='eat'; g.rotation.x=eating?.18*Math.sin(t*7+(s>0?0:Math.PI)):.03*Math.sin(t*3+s); g.position.z=1.2+(eating?.03*Math.sin(t*7+(s>0?0:Math.PI)):0); mv.rotation.y=s*(eating?.5*Math.max(0,Math.sin(t*14+s)):.1); });
  body.position.y=sc.speed?.012*Math.sin(t*16):.004*Math.sin(t*1.3); sc.rear=lerp(sc.rear||0,(st.mode==='alert'||st.mode==='stalk'?.05:0)+(['lift','sting'].includes(st.mode)?.12:0),1-Math.exp(-dt*4)); body.rotation.x=-sc.lunge*.06-sc.rear;

  // ---------- flakes
  for(const f of flakes){ if(Math.abs(f.vx)+Math.abs(f.vz)+Math.abs(f.w)+f.y+Math.abs(f.vy)>1e-4){ f.x+=f.vx*dt; f.z+=f.vz*dt; f.ry+=f.w*dt; const dmp=Math.exp(-dt*(f.y>0?.5:7)); f.vx*=dmp; f.vz*=dmp; f.w*=Math.exp(-dt*5);
      f.vy-=dt*6; f.y=Math.max(0,f.y+f.vy*dt); if(f.y<=0) f.vy=Math.max(0,f.vy); }
    f.m.position.set(f.x,H(f.x,f.z)+.012+f.y,f.z); groundNormal(f.x,f.z,_n); _q.setFromUnitVectors(UP,_n); f.m.quaternion.setFromAxisAngle(UP,f.ry).premultiply(_q); f.m.rotateX(f.tilt); }
  updParts(dt);
}

/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:7.5,yaw:.7,pitch:.42,tYaw:.7,tPitch:.42,tDist:7.5,auto:0}; let dragging=false;
const camTarget=V3(0,.4,0);
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,10);
  pMat.uniforms.uScale.value=renderer.getDrawingBufferSize(new T.Vector2()).y/(2*Math.tan(camera.fov*Math.PI/360)); }
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.5,16); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.05,1.35); 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*.008,2.5,16); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });

const clock=new T.Clock(); let time=0, TS=1;
placeScorp(1); scorp.updateMatrixWorld(true); legs.forEach(L=>{ toWorld(L.home,L.toe); L.toe.y=H(L.toe.x,L.toe.z); });
function frame(){
  requestAnimationFrame(frame);
  const dt=Math.min(clock.getDelta(),1/30)*TS; time+=dt; U_TIME.value=time;
  update(dt,time);
  // follow the scorpion, leaning toward the cricket when there is one
  _tmp.set(sc.x,sc.y+.15,sc.z); if(prey.mode!=='none'&&prey.mode!=='held') _tmp.lerp(_t.copy(prey.pos),.3);
  camTarget.lerp(_tmp,1-Math.exp(-dt*1.5));
  if(!dragging&&!reduceMotion) cam.auto+=dt*.045;
  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=H(camera.position.x,camera.position.z)+.35; if(camera.position.y<gy) camera.position.y=gy;
  camera.lookAt(camTarget);
  // lights travel with the scorpion so its shadow stays sharp
  moon.position.copy(camTarget).addScaledVector(MOON_DIR,20).add(V3(4,6,8)); moon.target.position.copy(camTarget);
  uv.position.copy(camera.position).add(V3(0,3,0)); uv.target.position.copy(camTarget);
  rim.position.set(camTarget.x-5,camTarget.y+3,camTarget.z-4); rim2.position.set(camTarget.x+5,camTarget.y+1.5,camTarget.z-3); glint.position.set(camTarget.x+2,camTarget.y+3,camTarget.z+5);
  renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.