HAMMERHEAD WORM 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: Hammerhead Worm</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: #020305; }
#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 = 5550123;
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 (a rain-soaked garden bed at night)
===================================================================== */
const canvas = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas, antialias: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=0x05080c;
scene.background = new T.Color(FOG);
scene.fog = new T.FogExp2(FOG, 0.085);
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,'#26304a'); g.addColorStop(.45,'#10141c'); g.addColorStop(.55,'#1c1a14'); g.addColorStop(1,'#050403');
x.fillStyle=g; x.fillRect(0,0,1024,512);
[[200,120,200,'#7a55ff',.5],[780,110,220,'#22d3ff',.5],[540,300,260,'#ff3fa4',.32],[940,220,140,'#ffb060',.55],[80,330,240,'#2affc2',.25],[600,60,90,'#ffffff',.6]].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 (wet, glossy; hue cycles with time and view angle)
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??.2, metalness:o.metal??.45, side:o.side??T.FrontSide, envMapIntensity:o.env??1.6 });
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??.52}, uIri:{value:o.iri??1}, uFilm:{value:o.film??.6}, uGlow:{value:o.glow??.05} };
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.85, iriS*0.5);
roughnessFactor = mix(roughnessFactor, 0.1, iriS*0.5);
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){ const v=(p[i]+p[i+1]+p[i+2])/3; p[i]=p[i+1]=p[i+2]=v; 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, 20, 14), SPH_LO = new T.SphereGeometry(1, 10, 8);
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; }
/* =====================================================================
GROUND: wet garden soil with a burrow, fallen autumn leaves lying on it
heightAt() is shared by everything that touches the ground.
===================================================================== */
function H(x,z){ return .1*Math.sin(x*.55+.3)*Math.sin(z*.47+1.1)+.04*Math.sin(x*1.7+z*1.3)+.015*Math.sin(x*4.1-z*3.7); }
const burrow={x:0,z:0,r:.13,open:0};
function holeDepth(x,z){ const d=Math.hypot(x-burrow.x,z-burrow.z); return d<.32?-.65*smooth(1-d/burrow.r)+.035*smooth(1-Math.abs(d-.2)/.12)*burrow.open:0; }
const LEAVES=[];
function leafSurf(L,x,z){ const dx=x-L.x, dz=z-L.z, c=Math.cos(L.a), s=Math.sin(L.a), u=(dx*c+dz*s)/L.L, v=(-dx*s+dz*c)/L.W;
if(u<-1||u>1) return -9; const hw=Math.sqrt(1-u*u)*(1-.28*u); if(Math.abs(v)>hw) return -9; return .012+L.curl*v*v+L.bow*(1-u*u); }
function heightAt(x,z){ let h=H(x,z)+holeDepth(x,z); for(const L of LEAVES){ const s=leafSurf(L,x,z); if(s>-1) h=Math.max(h,H(x,z)+s+L.layer); } return h; }
function groundNormal(x,z,out){ const e=.05; return out.set(heightAt(x-e,z)-heightAt(x+e,z),2*e,heightAt(x,z-e)-heightAt(x,z+e)).normalize(); }
const soilC=makeCanvas(1024,1024,(g,W,Hh)=>{ g.fillStyle='#2a1d14'; g.fillRect(0,0,W,Hh);
for(let i=0;i<9000;i++){ const x=rnd()*W, y=rnd()*Hh, r=rr(1,4.5), l=rnd(); g.fillStyle=l<.4?`rgba(14,9,6,${rr(.4,.9)})`:l<.8?`rgba(70,50,34,${rr(.3,.7)})`:`rgba(120,100,80,${rr(.2,.5)})`; g.beginPath(); g.ellipse(x,y,r,r*rr(.5,1),rnd()*3,0,TAU); g.fill(); }
for(let i=0;i<220;i++){ g.strokeStyle=`rgba(${rnd()<.5?'60,42,26':'20,14,10'},.6)`; g.lineWidth=rr(1,2.5); const x=rnd()*W, y=rnd()*Hh, a=rnd()*TAU, l=rr(8,30); g.beginPath(); g.moveTo(x,y); g.lineTo(x+Math.cos(a)*l,y+Math.sin(a)*l); g.stroke(); } });
const soilT=dataTex(soilC); soilT.encoding=T.sRGBEncoding; soilT.wrapS=soilT.wrapT=T.RepeatWrapping; soilT.repeat.set(5,5);
const soilB=bumpOf(soilC); soilB.wrapS=soilB.wrapT=T.RepeatWrapping; soilB.repeat.set(5,5);
// wet patches: low roughness where water pools
const wetC=makeCanvas(256,256,(g,W,Hh)=>{ g.fillStyle='#b0b0b0'; g.fillRect(0,0,W,Hh); for(let i=0;i<26;i++){ const gr=g.createRadialGradient(0,0,0,0,0,1); const x=rnd()*W, y=rnd()*Hh, r=rr(10,34);
const rg=g.createRadialGradient(x,y,0,x,y,r); rg.addColorStop(0,'rgba(10,10,10,1)'); rg.addColorStop(1,'rgba(10,10,10,0)'); g.fillStyle=rg; g.fillRect(x-r,y-r,2*r,2*r); } });
const wetT=dataTex(wetC);
const GS=26, GN=300;
const groundGeo=new T.PlaneGeometry(GS,GS,GN,GN).rotateX(-Math.PI/2);
const groundMat=new T.MeshStandardMaterial({map:soilT,bumpMap:soilB,bumpScale:.03,roughness:1,roughnessMap:wetT,metalness:0,envMapIntensity:1.2});
const ground=new T.Mesh(groundGeo,groundMat); ground.receiveShadow=true; scene.add(ground);
function rebuildGround(){ 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)+holeDepth(x,z)); } p.needsUpdate=true; groundGeo.computeVertexNormals(); }
// worm castings around the burrow mouth
const castMat=new T.MeshStandardMaterial({color:lin(0x3a2a1e),roughness:.45,envMapIntensity:1.3});
const castings=new T.Group(); scene.add(castings);
function buildCastings(){ while(castings.children.length) castings.remove(castings.children[0]);
for(let k=0;k<5;k++){ const a=rr(0,TAU), r=rr(.2,.38), x=burrow.x+Math.cos(a)*r, z=burrow.z+Math.sin(a)*r; const pts=[]; let px=x,pz=z,pa=rnd()*TAU;
for(let j=0;j<6;j++){ pts.push(V3(px,H(px,pz)+.025,pz)); pa+=rr(-1.2,1.2); px+=Math.cos(pa)*.04; pz+=Math.sin(pa)*.04; }
mesh(sweep(pts,t=>.026*(1-.3*t),16,6),castMat,castings); } }
// fallen leaves (each drapes over the soil; the worms glide over them)
const leafTex=[['#9a4a18','#c8761e','#6a3010'],['#b88a20','#e0b030','#7a5a10'],['#7a2a14','#a84020','#4a1a0a'],['#5a4a24','#8a7a3a','#3a2e14']].map(([b0,b1,v])=>{
const c=makeCanvas(512,256,(g,W,Hh)=>{ g.clearRect(0,0,W,Hh);
g.beginPath(); for(let i=0;i<=80;i++){ const u=i/80*2-1, hw=Math.sqrt(Math.max(0,1-u*u))*(1-.28*u)*(1+.06*Math.sin(u*28)); const x=(u+1)/2*W, y=Hh/2-hw*Hh/2*.96; i?g.lineTo(x,y):g.moveTo(x,y); }
for(let i=80;i>=0;i--){ const u=i/80*2-1, hw=Math.sqrt(Math.max(0,1-u*u))*(1-.28*u)*(1+.06*Math.sin(u*28)); g.lineTo((u+1)/2*W,Hh/2+hw*Hh/2*.96); } g.closePath();
const gr=g.createLinearGradient(0,0,W,Hh); gr.addColorStop(0,b0); gr.addColorStop(.5,b1); gr.addColorStop(1,b0); g.fillStyle=gr; g.fill(); g.save(); g.clip();
for(let i=0;i<80;i++){ g.fillStyle=`rgba(${rnd()<.5?'30,16,6':'200,150,60'},${rr(.1,.35)})`; g.beginPath(); g.arc(rnd()*W,rnd()*Hh,rr(3,18),0,TAU); g.fill(); }
g.strokeStyle=v; g.lineWidth=4; g.beginPath(); g.moveTo(0,Hh/2); g.lineTo(W,Hh/2); g.stroke();
g.lineWidth=2; for(let k=1;k<9;k++){ const x=k/9*W; [-1,1].forEach(s=>{ g.beginPath(); g.moveTo(x,Hh/2); g.quadraticCurveTo(x+30,Hh/2+s*Hh*.2,x+55,Hh/2+s*Hh*.42); g.stroke(); }); }
g.restore(); });
const t=dataTex(c); t.encoding=T.sRGBEncoding; return new T.MeshPhysicalMaterial({map:t,alphaTest:.5,side:DS,roughness:.35,clearcoat:.8,clearcoatRoughness:.15,bumpMap:bumpOf(c),bumpScale:.01}); });
[[-1.6,1.2,.4,.9,.5],[1.8,-.6,2.1,.75,.42],[-.4,-2.2,-.7,1,.55],[2.6,2,1.2,.7,.4],[-3,-1,2.6,.85,.45],[.6,3.2,-1.4,.9,.5],[-3.4,2.8,.9,.65,.38],[3.6,-2.8,-.3,.8,.46]].forEach(([x,z,a,L,W],i)=>{
LEAVES.push({x,z,a,L,W,curl:rr(.05,.12),bow:rr(-.02,.04),layer:i*.002,mat:leafTex[i%4]}); });
LEAVES.forEach(L=>{ const geo=gridGeo(30,14,(u,v)=>{ const uu=u*2-1, vv=v*2-1, c=Math.cos(L.a), s=Math.sin(L.a), lx=uu*L.L, lz=vv*L.W, x=L.x+lx*c-lz*s, z=L.z+lx*s+lz*c;
return [x,H(x,z)+.012+L.curl*vv*vv+L.bow*(1-uu*uu)+L.layer,z]; }); mesh(geo,L.mat,scene); });
// twigs, pebbles, moss
const barkMat=new T.MeshStandardMaterial({color:lin(0x3a2c22),roughness:.6,envMapIntensity:1});
[[[-4,0,-3],[-2.6,0,-3.4],[-1.4,0,-3.1]],[[3,0,3.4],[4.2,0,2.6],[5,0,2.9]],[[-5,0,1],[-4.4,0,2.2]]].forEach(pts=>{ const P=pts.map(a=>V3(a[0],heightAt(a[0],a[2])+.04,a[2])); mesh(sweep(P,t=>.045*(1-.4*t),30,8),barkMat,scene); });
(function(){ const N=140, im=new T.InstancedMesh(new T.IcosahedronGeometry(1,2),new T.MeshStandardMaterial({color:0xffffff,roughness:.3,envMapIntensity:1.5}),N), c=new T.Color();
for(let i=0;i<N;i++){ const x=rr(-10,10), z=rr(-10,10); if(Math.hypot(x,z)<1) continue; const s=rr(.03,.12); _q.setFromEuler(new T.Euler(rr(0,3),rr(0,3),rr(0,3)));
_m.compose(V3(x,H(x,z)+s*.35,z),_q,V3(s,s*rr(.5,.9),s*rr(.7,1.1))); im.setMatrixAt(i,_m); c.setHSL(rr(.05,.12),rr(.05,.25),rr(.18,.45)).convertSRGBToLinear(); im.setColorAt(i,c); }
im.castShadow=im.receiveShadow=true; scene.add(im); })();
(function(){ const N=900, im=new T.InstancedMesh(new T.ConeGeometry(.012,.09,4).translate(0,.045,0),new T.MeshStandardMaterial({color:0xffffff,roughness:.7}),N), c=new T.Color();
let k=0; for(let cl=0;cl<10;cl++){ const cx=rr(-9,9), cz=rr(-9,9); if(Math.hypot(cx,cz)<2.5) continue; for(let i=0;i<90&&k<N;i++,k++){ const x=cx+rr(-.5,.5), z=cz+rr(-.5,.5);
_q.setFromUnitVectors(UP,V3(rr(-.4,.4),1,rr(-.4,.4)).normalize()); _m.compose(V3(x,H(x,z),z),_q,V3(1,rr(.6,1.4),1)); im.setMatrixAt(k,_m); c.setHSL(rr(.22,.3),rr(.4,.7),rr(.15,.32)).convertSRGBToLinear(); im.setColorAt(k,c); } }
im.count=k; scene.add(im); })();
// distant garden lights (bokeh)
(function(){ const N=50,pos=new Float32Array(N*3),col=new Float32Array(N*3); const cs=[[1,.7,.35],[1,.85,.6],[.5,.7,1],[1,.5,.8]];
for(let i=0;i<N;i++){ const a=rnd()*TAU, r=rr(16,28); pos.set([Math.cos(a)*r,rr(.5,6),Math.sin(a)*r],i*3); col.set(cs[(rnd()*4)|0],i*3); }
const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,3)); g.setAttribute('color',new T.BufferAttribute(col,3));
const sp=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(.7,'rgba(255,255,255,.3)'); gr.addColorStop(1,'rgba(255,255,255,0)'); x.fillStyle=gr; x.fillRect(0,0,64,64); }));
scene.add(new T.Points(g,new T.PointsMaterial({size:3,map:sp,vertexColors:true,transparent:true,depthWrite:false,blending:T.AdditiveBlending,opacity:.4,fog:false}))); })();
/* =====================================================================
THE MUCUS TRAIL: a glossy ribbon laid down where the head has glided, slowly drying
===================================================================== */
const TR=600, trail=[]; let trailDist=0;
const trGeo=new T.BufferGeometry(), trPos=new Float32Array(TR*2*3), trA=new Float32Array(TR*2);
trGeo.setAttribute('position',new T.BufferAttribute(trPos,3)); trGeo.setAttribute('aA',new T.BufferAttribute(trA,1));
{ const idx=[]; for(let i=0;i<TR-1;i++){ const a=i*2; idx.push(a,a+1,a+2,a+1,a+3,a+2); } trGeo.setIndex(idx); trGeo.setAttribute('normal',new T.BufferAttribute(new Float32Array(TR*2*3).fill(0).map((v,i)=>i%3===1?1:0),3)); }
const trMat=new T.MeshStandardMaterial({color:lin(0xa8c0d8),roughness:.04,metalness:.3,envMapIntensity:2.4,transparent:true,depthWrite:false,side:DS});
trMat.onBeforeCompile=sh=>{ sh.vertexShader='attribute float aA; varying float vA;\n'+sh.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\n vA=aA;');
sh.fragmentShader='varying float vA;\n'+sh.fragmentShader.replace('#include <map_fragment>','#include <map_fragment>\n diffuseColor.a*=vA;'); };
const trailMesh=new T.Mesh(trGeo,trMat); trailMesh.frustumCulled=false; trailMesh.renderOrder=2; scene.add(trailMesh);
function trailAdd(p,dir,t){ trail.push({x:p.x,z:p.z,dx:dir.x,dz:dir.z,t}); if(trail.length>TR) trail.shift(); }
function trailUpdate(t){ for(let i=0;i<TR;i++){ const P=trail[i]; if(!P){ trA[i*2]=trA[i*2+1]=0; trPos.fill(0,i*6,i*6+6); continue; }
const sx=-P.dz*.11, sz=P.dx*.11, a=clamp(1-(t-P.t)/40,0,1)*.45*Math.min(1,(trail.length-i)/4+.0);
trPos.set([P.x+sx,heightAt(P.x+sx,P.z+sz)+.006,P.z+sz,P.x-sx,heightAt(P.x-sx,P.z-sz)+.006,P.z-sz],i*6); trA[i*2]=trA[i*2+1]=a; }
trGeo.attributes.position.needsUpdate=trGeo.attributes.aA.needsUpdate=true; }
/* =====================================================================
HAMMERHEAD (Bipalium) PATTERN
body tube texture: u along (canvas x, 0 = neck), v around (canvas y; v=.25 is the dorsal midline)
===================================================================== */
const bodyC=makeCanvas(1024,256,(g,W,Hh)=>{ g.fillStyle=D(.56,.0,1); g.fillRect(0,0,W,Hh);
const band=(v,w,r,gg,b)=>{ g.fillStyle=D(r,gg,b); g.fillRect(0,(1-v-w/2)*Hh,W,w*Hh); }; // canvas y is flipped relative to v
g.fillStyle=D(.82,.35,.35); g.fillRect(0,.05*Hh,W,.4*Hh); // pale creeping sole
band(.25,.025,.1,.05,.7); // thin median stripe
[.17,.33].forEach(v=>band(v,.05,.14,.04,.75)); // broad paired stripes
[.06,.44].forEach(v=>band(v,.03,.18,.03,.8)); // faint lateral stripes
// dark neck collar
const gr=g.createLinearGradient(0,0,W*.08,0); gr.addColorStop(0,D(.12,.1,.7)); gr.addColorStop(.5,D(.12,.1,.7)); gr.addColorStop(1,D(.56,0,1,0)); g.fillStyle=gr; g.fillRect(0,Hh*.48,W*.08,Hh*.52);
for(let i=0;i<4000;i++){ g.fillStyle=D(rr(.45,.75),.03,1,.35); g.fillRect(rnd()*W,rnd()*Hh,1.5,1.5); } });
const bodyT=dataTex(bodyC), bodyB=bumpOf(bodyC);
const headC=makeCanvas(256,256,(g,W,Hh)=>{ g.fillStyle=D(.54,.05,1); g.fillRect(0,0,W,Hh);
let gr=g.createRadialGradient(W/2,Hh,0,W/2,Hh,Hh*.9); gr.addColorStop(0,D(.14,.1,.75)); gr.addColorStop(.6,D(.3,.05,.9)); gr.addColorStop(1,D(.56,0,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,Hh);
for(let i=0;i<1500;i++){ g.fillStyle=D(rr(.4,.8),.05,1,.4); g.fillRect(rnd()*W,rnd()*Hh,1.5,1.5); } });
const headT=dataTex(headC);
/* =====================================================================
THE HAMMERHEAD: a soft flattened tube rebuilt each frame around a follow-the-leader spine
===================================================================== */
const HN=72, HSEG=.062; // ≈4.4 units long
const hp=[]; for(let i=0;i<HN;i++) hp.push(V3());
const bodyMat=iriMat({pat:bodyT,bump:bodyB,bumpScale:.003,hue:.05,light:.36,rough:.16,metal:.42,film:.7,side:DS});
const NV=24, bodyGeo=gridGeo(HN-1,NV,()=>[0,0,0]);
const hBody=mesh(bodyGeo,bodyMat,scene); hBody.frustumCulled=false;
let plump=1;
function hW(u){ const neck=u<.07?.62+.38*smooth(u/.07):1, tail=u>.5?Math.pow(Math.max(0,1-(u-.5)/.5),.65):1; return Math.max(.012,.19*neck*tail*(1+.04*Math.sin(u*40))); }
const HF=[], HUP=[], HS=[], HTn=[], PROX=new Float32Array(HN); for(let i=0;i<HN;i++){ HF.push(V3()); HUP.push(V3()); HS.push(V3()); HTn.push(V3()); }
// head: a crescent "hammer" with auricles and a fringe of eyespots
const head=new T.Group(); scene.add(head);
const headShape=(a,b)=>{ const Wh=.42, fz=.11*Math.cos(a*Math.PI/2*1.05)-.13*Math.pow(Math.abs(a),3), depth=.16*(1-.55*Math.abs(a)); return [a*Wh*(1-.12*b), fz-b*depth]; };
const headTop=gridGeo(28,8,(u,v)=>{ const a=u*2-1, b=v, [x,z]=headShape(a,b), y=.045*Math.sin(Math.PI*Math.min(1,b*1.1+.05))*Math.pow(1-a*a,.35)+.004; return [x,y,z]; });
const headBot=gridGeo(28,8,(u,v)=>{ const a=u*2-1, b=v, [x,z]=headShape(a,b); return [x,-.006*Math.pow(1-a*a,.3),z]; });
const headMat=iriMat({pat:headT,hue:.02,light:.36,rough:.16,metal:.42,film:.7,side:DS});
mesh(headTop,headMat,head); mesh(headBot,iriMat({hue:.05,light:.5,sat:.4,iri:.5,side:DS}),head);
(function(){ const N=60, im=new T.InstancedMesh(SPH_LO,new T.MeshStandardMaterial({color:lin(0x0a0604),roughness:.3}),N);
for(let i=0;i<N;i++){ const a=(i/(N-1))*2-1, [x,z]=headShape(a*.98,.04); _m.compose(V3(x,.02,z+.008),_q.identity(),V3(.008,.006,.008)); im.setMatrixAt(i,_m); } head.add(im); })();
// glistening mucus beads on the back
const NBEAD=36, beads=new T.InstancedMesh(SPH,new T.MeshPhysicalMaterial({color:0xffffff,roughness:0,metalness:0,clearcoat:1,transparent:true,opacity:.5,envMapIntensity:3}),NBEAD);
const beadP=[]; for(let i=0;i<NBEAD;i++) beadP.push([rr(.06,.85),rr(.1,.4),rr(.008,.018)]); beads.frustumCulled=false; scene.add(beads);
// the pharynx: everted from the middle of the underside while feeding
const pharMat=iriMat({hue:.9,light:.48,sat:.5,iri:.7,rough:.15,side:DS});
const phar=new T.Group(); scene.add(phar);
const pharTube=mesh(new T.CylinderGeometry(.045,.035,1,16,8,true).translate(0,.5,0),pharMat,phar);
const pharLip=mesh(new T.TorusGeometry(.05,.018,8,20).rotateX(Math.PI/2),pharMat,phar);
phar.visible=false;
/* =====================================================================
THE EARTHWORM (natural colours): emerges from its burrow, crawls, is caught
===================================================================== */
const EN=44, ESEG=.058, ER=.1;
const ep=[]; for(let i=0;i<EN;i++) ep.push(V3());
const ewC=makeCanvas(512,64,(g,W,Hh)=>{ const gr=g.createLinearGradient(0,0,0,Hh); gr.addColorStop(0,'#8a4a44'); gr.addColorStop(.25,'#6a2e2c'); gr.addColorStop(.6,'#b77a6a'); gr.addColorStop(1,'#8a4a44'); g.fillStyle=gr; g.fillRect(0,0,W,Hh);
g.fillStyle='rgba(220,120,90,.55)'; g.fillRect(W*.24,0,W*.1,Hh); // clitellum
for(let x=0;x<W;x+=4){ g.fillStyle='rgba(40,14,12,.45)'; g.fillRect(x,0,1.2,Hh); } });
const ewT=dataTex(ewC); ewT.encoding=T.sRGBEncoding;
const ewMat=new T.MeshPhysicalMaterial({map:ewT,bumpMap:bumpOf(ewC),bumpScale:.004,roughness:.35,clearcoat:1,clearcoatRoughness:.08,envMapIntensity:1.5,sheen:new T.Color(0x553333)});
const EV=16, ewGeo=gridGeo(EN-1,EV,()=>[0,0,0]);
const ew=mesh(ewGeo,ewMat,scene); ew.frustumCulled=false; ew.visible=false;
const ewS=[]; for(let i=0;i<EN;i++) ewS.push({T:V3(),S:V3(),U:V3()});
const worm={mode:'none',t:0,head:0,cap:-1,eaten:0,wr:[] ,anchor:V3()};
/* =====================================================================
RAIN: falling streaks, splash rings on soil and leaves, a few drops on the worm
===================================================================== */
const RN=520, rPos=new Float32Array(RN*6), rV=new Float32Array(RN);
const rGeo=new T.BufferGeometry(); rGeo.setAttribute('position',new T.BufferAttribute(rPos,3));
const rain=new T.LineSegments(rGeo,new T.LineBasicMaterial({color:0x9fb8d8,transparent:true,opacity:.35,depthWrite:false})); rain.frustumCulled=false; scene.add(rain);
const NSPL=80, splash=new T.InstancedMesh(new T.RingGeometry(.8,1,24).rotateX(-Math.PI/2),new T.MeshBasicMaterial({color:0xffffff,transparent:true,depthWrite:false,blending:T.AdditiveBlending,side:DS}),NSPL);
splash.instanceColor=new T.InstancedBufferAttribute(new Float32Array(NSPL*3),3); splash.frustumCulled=false; scene.add(splash);
const spl=[]; for(let i=0;i<NSPL;i++) spl.push({p:V3(),t:9}); let splI=0;
function resetDrop(i,c,top){ rPos[i*6]=c.x+rr(-7,7); rPos[i*6+2]=c.z+rr(-7,7); rPos[i*6+1]=top?rr(1,9):9; rV[i]=rr(7,9); }
/* lights: cool night key with shadows, warm garden lamp, iridescent rims */
scene.add(new T.HemisphereLight(0x8aa0d0,0x1a120a,.42));
const key=new T.DirectionalLight(0xc8d8ff,1.25); 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:30}); key.shadow.bias=-.0004; key.shadow.normalBias=.02; scene.add(key,key.target);
const lamp=new T.PointLight(0xffa860,1.2,18,1.6); scene.add(lamp);
const rim=new T.PointLight(0x33ccff,1.1,25); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,.9,25); scene.add(rim2);
const glint=new T.PointLight(0xffffff,.8,20); scene.add(glint);
/* =====================================================================
BEHAVIOUR
glide & search (head fan sweeping) → track the earthworm's scent → climb onto it and coil around it →
evert the pharynx from mid-body and feed while the earthworm shrinks → unwind and glide away
===================================================================== */
const hs={mode:'glide',t:0,head:rr(0,TAU),speed:.26,search:0,nextSearch:4,coil:0,wrapK:0,axis:V3(),c0:V3(),nrm:V3(),bin:V3(),feedIdx:-1};
const go=(m)=>{ hs.mode=m; hs.t=0; };
let nextWorm=6;
const _a=V3(),_b=V3(),_c=V3(),_d=V3(),_n=V3(),_t=V3(),_tmp=V3(),_tmp2=V3();
// init hammerhead lying along a gentle curve
(function(){ let x=-1.5,z=1,a=hs.head; for(let i=0;i<HN;i++){ hp[i].set(x,heightAt(x,z)+.03,z); a+=.02; x-=Math.cos(a)*HSEG; z-=Math.sin(a)*HSEG; } })();
function spawnWorm(){
const hx=hp[0].x, hz=hp[0].z;
for(let k=0;k<40;k++){ const a=rr(0,TAU), r=rr(2.2,3.4); burrow.x=hx+Math.cos(a)*r; burrow.z=hz+Math.sin(a)*r; if(Math.hypot(burrow.x,burrow.z)<6&&LEAVES.every(L=>leafSurf(L,burrow.x,burrow.z)<-1&&Math.hypot(L.x-burrow.x,L.z-burrow.z)>L.L+.3)) break; }
burrow.open=1; rebuildGround(); buildCastings();
const y0=heightAt(burrow.x,burrow.z); for(let i=0;i<EN;i++) ep[i].set(burrow.x,y0-.05-i*ESEG,burrow.z);
worm.mode='emerge'; worm.t=0; worm.head=Math.atan2(hp[0].z-burrow.z,hp[0].x-burrow.x)+rr(-1.6,1.6); worm.cap=-1; worm.eaten=0; ew.visible=true; ew.scale.setScalar(1);
}
const hist=[]; const _hp=V3();
function recordHead(){ if(!hist.length||hist[0].distanceTo(hp[0])>.008){ hist.unshift(hp[0].clone()); let L=0; for(let k=1;k<hist.length;k++){ L+=hist[k].distanceTo(hist[k-1]); if(L>HN*HSEG+.6){ hist.length=k+1; break; } } } }
function samplePath(){ hp[0].copy(hist.length?hp[0]:hp[0]); let k=0, acc=0, prev=hp[0];
// segment from the live head position to the newest recorded point, then along the history
for(let i=1;i<HN;i++){ let want=i*HSEG;
while(true){ const nxt=hist[k]; if(!nxt){ hp[i].copy(prev); break; } const L=prev.distanceTo(nxt);
if(acc+L>=want){ hp[i].lerpVectors(prev,nxt,(want-acc)/Math.max(L,1e-6)); break; } acc+=L; prev=nxt; k++; } } }
for(let i=HN-1;i>=0;i--) hist.unshift(hp[i].clone());
function followLeader(P,seg,start){ for(let i=start;i<P.length;i++){ _d.subVectors(P[i],P[i-1]); const L=_d.length(); if(L>seg) P[i].copy(P[i-1]).addScaledVector(_d,seg/L); } }
function segDist(p,a,b,out){ _t.subVectors(b,a); const L2=_t.lengthSq()||1e-6, k=clamp(_tmp2.subVectors(p,a).dot(_t)/L2,0,1); out.copy(a).addScaledVector(_t,k); return p.distanceTo(out); }
function nearestOnWorm(p,out,lo=0,hi=EN-1){ let best=1e9, bi=0; for(let i=lo;i<hi;i++){ const d=segDist(p,ep[i],ep[i+1],_c); if(d<best){ best=d; bi=i; out.copy(_c); } } return {d:best,i:bi}; }
function ewRadius(i){ const u=i/(EN-1); return ER*(u<.05?.55+.45*smooth(u/.05):1)*(u>.85?Math.max(.35,1-(u-.85)/.2):1)*(1+.15*Math.exp(-(((u-.29)/.05)**2))); }
function update(dt,t){
hs.t+=dt; worm.t+=dt;
// ---------- earthworm
if(worm.mode==='none'){ if(hs.mode==='glide'&&!reduceMotion){ nextWorm-=dt; if(nextWorm<=0) spawnWorm(); } }
else if(worm.mode==='emerge'||worm.mode==='crawl'){
const sp=worm.mode==='emerge'?.16:.11*(.6+.4*Math.sin(t*2));
if(worm.mode==='emerge'){ const out=ep[0].distanceTo(_a.set(burrow.x,heightAt(burrow.x,burrow.z),burrow.z)); if(worm.t>1.5&&ep[EN-1].y>heightAt(ep[EN-1].x,ep[EN-1].z)-.02) worm.mode='crawl';
const up=Math.min(1,worm.t/1.2); ep[0].x+=Math.cos(worm.head)*sp*dt*up; ep[0].z+=Math.sin(worm.head)*sp*dt*up; ep[0].y=lerp(ep[0].y,heightAt(ep[0].x,ep[0].z)+ER*.8,1-Math.exp(-dt*3)); }
else { worm.head+=.5*Math.sin(t*.4)*dt; const r=Math.hypot(ep[0].x,ep[0].z); if(r>6) worm.head=lerp(worm.head,Math.atan2(-ep[0].z,-ep[0].x),dt);
ep[0].x+=Math.cos(worm.head)*sp*dt; ep[0].z+=Math.sin(worm.head)*sp*dt; ep[0].y=heightAt(ep[0].x,ep[0].z)+ER*.8; }
followLeader(ep,ESEG,1);
for(let i=1;i<EN;i++){ const g=heightAt(ep[i].x,ep[i].z)+ER*.8, inHole=Math.hypot(ep[i].x-burrow.x,ep[i].z-burrow.z)<burrow.r*1.1; if(!inHole||ep[i].y>g) ep[i].y=Math.max(ep[i].y-dt*.5,g); }
}
else if(worm.mode==='caught'||worm.mode==='eaten'||worm.mode==='remains'){
// the seized section lifts a little; the free ends writhe (weaker as the venom/enzymes act)
const k=worm.cap, life=worm.mode==='caught'?1-.85*smooth(hs.mode==='feed'?hs.t/4:0):0;
for(let i=0;i<EN;i++){ const g=heightAt(ep[i].x,ep[i].z)+ER*.8, dk=Math.abs(i-k), lift=.2*smooth(1-dk/9);
ep[i].y=lerp(ep[i].y,g+lift,1-Math.exp(-dt*3));
if(dk>9&&life>0){ const ph=t*7+i*.45, a=.25*life*dt*Math.sin(ph)*Math.min(1,(dk-9)/6); ep[i].x+=-Math.sin(worm.head)*a; ep[i].z+=Math.cos(worm.head)*a; } }
// keep the body connected (both ways from the captured section)
for(let it=0;it<2;it++){ for(let i=k+1;i<EN;i++){ _d.subVectors(ep[i],ep[i-1]); const L=_d.length(); if(L>ESEG) ep[i].copy(ep[i-1]).addScaledVector(_d,ESEG/L); }
for(let i=k-1;i>=0;i--){ _d.subVectors(ep[i],ep[i+1]); const L=_d.length(); if(L>ESEG) ep[i].copy(ep[i+1]).addScaledVector(_d,ESEG/L); } }
}
if(worm.mode==='remains'){ worm.eaten=Math.min(1,worm.eaten+dt/8); if(worm.t>8){ worm.mode='none'; ew.visible=false; nextWorm=rr(5,8); burrow.open=0; } }
// ---------- hammerhead
const H0=hp[0];
if(hs.mode==='glide'){
let target=null; if(worm.mode==='crawl'||worm.mode==='emerge'){ const r=nearestOnWorm(H0,_b,0,Math.floor(EN*.75)); if(r.d<5.5) target=_b; if(r.d<.16&&worm.mode==='crawl'){ startWrap(r.i); } }
hs.nextSearch-=dt; if(hs.nextSearch<=0){ hs.search=hs.search?0:1; hs.nextSearch=hs.search?rr(2,3.5):rr(4,8); }
let want=hs.head+.35*Math.sin(t*.23)*dt*3;
if(target){ want=Math.atan2(target.z-H0.z,target.x-H0.x); hs.search=0; }
const r=Math.hypot(H0.x,H0.z); if(r>6.2) want=Math.atan2(-H0.z,-H0.x);
const v=(hs.search?.07:target?.3:.22)*(1-.25*Math.max(0,Math.sin(t*1.3))), turn=v/.6+.04;
hs.head+=clamp(angWrap(want-hs.head),-turn*dt,turn*dt);
H0.x+=Math.cos(hs.head)*v*dt; H0.z+=Math.sin(hs.head)*v*dt; H0.y=heightAt(H0.x,H0.z)+.03;
trailDist+=v*dt; if(trailDist>.05){ trailDist=0; trailAdd(H0,_a.set(Math.cos(hs.head),0,Math.sin(hs.head)),t); }
}
else if(hs.mode==='wrap'){
if(hs.sub===0){ helixAt(0,_b); _a.subVectors(_b,H0); const d=_a.length(), step=Math.min(d,.26*dt); H0.addScaledVector(_a.normalize(),step);
H0.y=Math.max(H0.y,heightAt(H0.x,H0.z)+.03); if(d<.02) hs.sub=1; }
else { const rc=coilR(), dth=.24/Math.hypot(rc,COIL.pitch/TAU); hs.coil=Math.min(COIL.turns*TAU,hs.coil+dth*dt); helixAt(hs.coil,H0); }
if(hs.coil>=COIL.turns*TAU){ go('feed'); worm.mode='caught'; }
}
else if(hs.mode==='feed'){
helixAt(COIL.turns*TAU,H0);
worm.eaten=Math.min(1,worm.eaten+dt/14); plump=lerp(1,1.22,worm.eaten);
if(hs.t>15){ go('leave'); worm.mode='eaten'; helixAt(COIL.turns*TAU-.05,_a); helixAt(COIL.turns*TAU,_b); hs.head=Math.atan2(_b.z-_a.z,_b.x-_a.x); hs.leaveHead=Math.atan2(hs.axis.z,hs.axis.x)+(rnd()<.5?1:-1)*rr(.9,1.3); }
}
else if(hs.mode==='leave'){ hs.head+=clamp(angWrap(hs.leaveHead-hs.head),-.45*dt,.45*dt); H0.x+=Math.cos(hs.head)*.26*dt; H0.z+=Math.sin(hs.head)*.26*dt; H0.y=lerp(H0.y,heightAt(H0.x,H0.z)+.03,1-Math.exp(-dt*3));
trailDist+=.26*dt; if(trailDist>.05){ trailDist=0; trailAdd(H0,_a.set(Math.cos(hs.head),0,Math.sin(hs.head)),t); }
worm.eaten=Math.min(.75,worm.eaten+dt/30);
const tailFree=nearestOnWorm(hp[HN-1],_b,0,EN-1).d>.45&&nearestOnWorm(hp[HN>>1],_b,0,EN-1).d>.45;
if(hs.t>4&&tailFree){ go('glide'); worm.mode='remains'; worm.t=0; hs.coil=0; } }
if(hs.mode!=='feed') plump=lerp(plump,1,dt*.01);
// body follows the head; pushed out of the earthworm where coiled; otherwise rests on the ground
recordHead(); samplePath();
const coiled=hs.mode==='wrap'||hs.mode==='feed'||hs.mode==='leave';
for(let i=1;i<HN;i++){ const P=hp[i], g=heightAt(P.x,P.z)+.03;
if(coiled&&ew.visible){ const r=nearestOnWorm(P,_b,Math.max(0,worm.cap-14),Math.min(EN-1,worm.cap+14)), need=ewRadius(r.i)*(1-.45*worm.eaten)+.05;
if(r.d<need+.05){ _c.subVectors(P,_b); if(_c.lengthSq()<1e-8) _c.copy(UP); P.copy(_b).addScaledVector(_c.normalize(),need); P.y=Math.max(P.y,g); continue; } }
P.y=Math.max(g,P.y); }
selfCollide(coiled);
// ---------- pharynx: from the mid-body underside to the earthworm
if(hs.mode==='feed'||(hs.mode==='leave'&&hs.t<1.2)){ let bi=-1, bd=1e9; for(let i=18;i<52;i++){ const r=nearestOnWorm(hp[i],_b,0,EN-1); if(r.d<bd){ bd=r.d; bi=i; _c.copy(_b); } }
const ext=hs.mode==='feed'?smooth((hs.t-1)/2):1-smooth(hs.t/1.2); phar.visible=ext>.02&&bi>=0;
if(phar.visible){ _a.copy(hp[bi]); _d.subVectors(_c,_a); const L=Math.min(.32,_d.length())*ext; phar.position.copy(_a); phar.quaternion.setFromUnitVectors(UP,_d.normalize());
const pump=1+.15*Math.sin(t*6); pharTube.scale.set(pump,Math.max(.01,L),pump); pharLip.position.y=L; pharLip.scale.setScalar(1.2*pump); } }
else phar.visible=false;
}
// self-collision: where the body crosses itself the head-ward part rides up over the older part;
// around the prey, overlapping turns of the coil are pushed apart in 3D and slide along the earthworm
function selfCollide(coiled){
for(let it=0;it<3;it++) for(let i=0;i<HN;i++){ const wi=hW(i/(HN-1))*plump, hi=wi*.42, Pi=hp[i];
for(let j=i+6;j<HN;j++){ const wj=hW(j/(HN-1))*plump, hj=wj*.42, Pj=hp[j];
const dx=Pj.x-Pi.x, dz=Pj.z-Pi.z, dy=Pj.y-Pi.y, rh=Math.hypot(dx,dz), lim=(wi+wj)*.78, need=(hi+hj)*.95;
let nearPrey=false; if(coiled&&ew.visible){ const r=nearestOnWorm(Pi,_b,Math.max(0,worm.cap-14),Math.min(EN-1,worm.cap+14)); nearPrey=r.d<ewRadius(r.i)+.2; }
if(nearPrey){ _c.set(-dx,-dy,-dz); const d3=_c.length(), m3=Math.max(need,(wi+wj)*.55); if(d3<m3){ if(d3<1e-5) _c.copy(hs.axis); _c.normalize().multiplyScalar((m3-d3)*.5); Pi.add(_c); Pj.sub(_c); } continue; }
if(rh>=lim||Math.abs(dy)>=need) continue;
// stack: the newer (head-ward) section climbs over the older one, with a smooth ramp onto it
const k=smooth(1-rh/lim); Pi.y=Math.max(Pi.y,Pj.y+need*k+.004);
} }
}
const COIL={turns:1.3,pitch:.78};
function coilR(){ return ewRadius(worm.cap)*(1-.45*worm.eaten)+.05; }
function helixAt(th,out){ const thMax=COIL.turns*TAU, span=COIL.pitch*COIL.turns, adv=th/thMax, rc=coilR();
return out.copy(ep[worm.cap]).addScaledVector(hs.axis,(adv-.5)*span).addScaledVector(hs.nrm,Math.cos(th*hs.dir)*rc).addScaledVector(hs.bin,Math.sin(th*hs.dir)*rc); }
function startWrap(i){ worm.cap=clamp(i,10,EN-16); worm.mode='caught'; go('wrap'); hs.coil=0; hs.sub=0; hs.dir=rnd()<.5?1:-1;
hs.axis.copy(ep[worm.cap-3]).sub(ep[worm.cap+3]); hs.axis.y=0; hs.axis.normalize();
// wind starting from the end nearest the head, travelling along the earthworm
_a.subVectors(hp[0],ep[worm.cap]); if(_a.dot(hs.axis)>0) hs.axis.negate();
hs.nrm.set(0,1,0); hs.bin.crossVectors(hs.axis,hs.nrm); }
/* ---------- mesh building ---------- */
function buildHammer(t){
const p=bodyGeo.attributes.position;
for(let i=0;i<HN;i++){ const a=hp[Math.max(0,i-1)], b=hp[Math.min(HN-1,i+1)]; HTn[i].subVectors(a,b).normalize();
// up: the ground normal, or pointing away from the earthworm where the body presses its sole against it
groundNormal(hp[i].x,hp[i].z,HUP[i]); PROX[i]=0;
if(ew.visible&&(hs.mode!=='glide')){ const r=nearestOnWorm(hp[i],_b,0,EN-1), lim=ewRadius(r.i)+.16; if(r.d<lim){ _c.subVectors(hp[i],_b).normalize(); PROX[i]=smooth(1-(r.d-.06)/(lim-.06)); HUP[i].lerp(_c,PROX[i]).normalize(); } } }
for(let pass=0;pass<3;pass++) for(let i=1;i<HN-1;i++) PROX[i]=Math.max(PROX[i],(PROX[i-1]+PROX[i+1])*.45);
for(let pass=0;pass<4;pass++) for(let i=1;i<HN-1;i++) HUP[i].add(HUP[i-1]).add(HUP[i+1]).normalize();
for(let i=0;i<HN;i++){ HS[i].crossVectors(HUP[i],HTn[i]).normalize(); HUP[i].crossVectors(HTn[i],HS[i]).normalize();
const u=i/(HN-1), w=hW(u)*plump*(1+.04*Math.sin(t*2-u*14))*(1-.4*PROX[i]), h=w*.42*(1+.5*PROX[i]), ctr=_a.copy(hp[i]).addScaledVector(HUP[i],h*.3);
for(let j=0;j<=NV;j++){ const ang=j/NV*TAU, c=Math.cos(ang), s=Math.sin(ang), yy=s>0?h*s:h*.35*s, xx=w*Math.sign(c)*Math.pow(Math.abs(c),.8), k=i*(NV+1)+j;
p.setXYZ(k,ctr.x+HS[i].x*xx+HUP[i].x*yy,ctr.y+HS[i].y*xx+HUP[i].y*yy,ctr.z+HS[i].z*xx+HUP[i].z*yy); } }
p.needsUpdate=true; bodyGeo.computeVertexNormals();
// head on the front frame; the fan sweeps while searching and lifts when sensing
_x.copy(HS[0]).negate(); _y.copy(HUP[0]); _z.copy(HTn[0]); _m.makeBasis(_x,_y,_z); head.quaternion.setFromRotationMatrix(_m);
head.position.copy(hp[0]).addScaledVector(HUP[0],.012).addScaledVector(HTn[0],.02);
const sweepA=(hs.search?.45:.08)*Math.sin(t*(hs.search?1.6:2.4))+(hs.mode==='wrap'?.2*Math.sin(t*4):0);
head.rotateY(sweepA); head.rotateX(-(hs.search?.18+.12*Math.sin(t*.9):.04)); head.scale.set(1+.05*Math.sin(t*3),1,1);
// beads
for(let i=0;i<NBEAD;i++){ const [u,vv,s]=beadP[i], k=Math.round(u*(HN-1)), w=hW(u)*plump, h=w*.42, ang=vv*Math.PI;
_a.copy(hp[k]).addScaledVector(HUP[k],h*.3+Math.sin(ang)*h*.95).addScaledVector(HS[k],Math.cos(ang)*w*.9); _m.compose(_a,_q.identity(),_b.setScalar(s)); beads.setMatrixAt(i,_m); }
beads.instanceMatrix.needsUpdate=true;
}
function buildWorm(t){
if(!ew.visible) return; const p=ewGeo.attributes.position, sh=1-.62*worm.eaten;
for(let i=0;i<EN;i++){ const S=ewS[i]; S.T.subVectors(ep[Math.max(0,i-1)],ep[Math.min(EN-1,i+1)]).normalize(); S.S.crossVectors(UP,S.T); if(S.S.lengthSq()<1e-6) S.S.set(1,0,0); S.S.normalize(); S.U.crossVectors(S.T,S.S);
const crawl=worm.mode==='crawl'||worm.mode==='emerge', R=ewRadius(i)*sh*(1+(crawl?.18*Math.sin(t*5+i*.55):0)+(worm.mode==='caught'?.06*Math.sin(t*9+i):0));
for(let j=0;j<=EV;j++){ const a=j/EV*TAU, k=i*(EV+1)+j; p.setXYZ(k,ep[i].x+(S.S.x*Math.cos(a)+S.U.x*Math.sin(a)*.92)*R,ep[i].y+(S.S.y*Math.cos(a)+S.U.y*Math.sin(a)*.92)*R,ep[i].z+(S.S.z*Math.cos(a)+S.U.z*Math.sin(a)*.92)*R); } }
p.needsUpdate=true; ewGeo.computeVertexNormals();
ewMat.color.setRGB(1,1,1).lerp(new T.Color(.45,.38,.36),worm.eaten);
}
function updateRain(dt,t,c){
for(let i=0;i<RN;i++){ const k=i*6; let y=rPos[k+1]-rV[i]*dt; const x=rPos[k], z=rPos[k+2];
if(y<=heightAt(x,z)){ if(Math.hypot(x-c.x,z-c.z)<5){ const S=spl[splI]; splI=(splI+1)%NSPL; S.p.set(x,heightAt(x,z)+.008,z); S.t=0; } resetDrop(i,c,false); continue; }
rPos[k+1]=y; rPos[k+3]=x+.01; rPos[k+4]=y+.22; rPos[k+5]=z; }
rGeo.attributes.position.needsUpdate=true;
for(let i=0;i<NSPL;i++){ const S=spl[i]; S.t+=dt; const k=S.t/.5, a=Math.max(0,1-k); _m.compose(S.p,_q.identity(),_a.setScalar(.02+.12*k)); splash.setMatrixAt(i,_m); splash.instanceColor.setXYZ(i,.28*a,.34*a,.4*a); }
splash.instanceMatrix.needsUpdate=true; splash.instanceColor.needsUpdate=true;
}
/* =====================================================================
CAMERA / INPUT
===================================================================== */
const cam={dist:5.2,yaw:.6,pitch:.55,tYaw:.6,tPitch:.55,tDist:5.2,auto:0}; let dragging=false;
const camTarget=V3();
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,7.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,1.6,14); pinch=d; return; }
cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.06,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,1.6,14); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });
const clock=new T.Clock(); let time=0, TS=1;
rebuildGround(); for(let i=0;i<RN;i++) resetDrop(i,V3(),true);
camTarget.copy(hp[20]);
function frame(){
requestAnimationFrame(frame);
const dt=Math.min(clock.getDelta(),1/30)*TS; time+=dt; U_TIME.value=time;
update(dt,time); buildHammer(time); buildWorm(time); trailUpdate(time); updateRain(dt,time,camTarget);
// follow the front half of the worm (and the prey when there is one)
_tmp.copy(hp[14]); if(ew.visible&&hs.mode==='glide') _tmp.lerp(ep[10],.3);
camTarget.lerp(_tmp,1-Math.exp(-dt*1.2));
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=heightAt(camera.position.x,camera.position.z)+.3; if(camera.position.y<gy) camera.position.y=gy;
camera.lookAt(camTarget);
key.position.copy(camTarget).add(V3(-3,8,4)); key.target.position.copy(camTarget);
lamp.position.copy(camTarget).add(V3(4,2.5,-3)); rim.position.copy(camTarget).add(V3(-4,2.5,-3)); rim2.position.copy(camTarget).add(V3(4,1.2,-2.5)); glint.position.copy(camTarget).add(V3(1.5,3,4));
renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>