• 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

BUTTERFLY 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: Butterfly</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  html, body { height: 100%; overflow: hidden; background: radial-gradient(ellipse at 50% 48%, #150b22 0%, #07040c 55%, #000 100%); }
  #c { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; }
  #c:active { cursor: grabbing; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<script>
{
"use strict";
if (typeof THREE === 'undefined') throw new Error('three missing');
const T = THREE;
const V3 = (x=0,y=0,z=0) => new T.Vector3(x,y,z);
const clamp = (x,a,b) => Math.max(a, Math.min(b, x));
const lerp = (a,b,t) => a + (b-a)*t;
const smooth = t => { t = clamp(t,0,1); return t*t*(3-2*t); };
let seed = 4242;
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
   ===================================================================== */
const canvas = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas, antialias:true, alpha:true, powerPreference:'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputEncoding = T.sRGBEncoding;
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const ANISO = renderer.capabilities.getMaxAnisotropy();

const scene = new T.Scene();
scene.fog = new T.FogExp2(0x07040c, 0.028);
const camera = new T.PerspectiveCamera(44, innerWidth/innerHeight, 0.05, 200);

function makeEnvironment(){
  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,'#3a2a63'); g.addColorStop(.3,'#1a1030'); g.addColorStop(.5,'#0a0612'); g.addColorStop(.62,'#1c1024'); g.addColorStop(1,'#040208');
  x.fillStyle = g; x.fillRect(0,0,1024,512);
  [[190,110,210,'#7a55ff',.6],[800,80,230,'#22d3ff',.5],[560,300,280,'#ff3fa4',.34],[960,250,200,'#ffd36e',.3],[80,340,240,'#2affc2',.2],[400,400,300,'#5522ff',.22]].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(); });
  x.globalAlpha = 1;
  const tex = new T.CanvasTexture(c); tex.mapping = T.EquirectangularReflectionMapping; tex.encoding = T.sRGBEncoding;
  const pm = new T.PMREMGenerator(renderer); pm.compileEquirectangularShader();
  const env = pm.fromEquirectangular(tex).texture; pm.dispose(); tex.dispose(); return env;
}
scene.environment = makeEnvironment();

/* =====================================================================
   IRIDESCENT MATERIAL
   Hue cycles over time (as before) and also shifts with viewing angle,
   like thin-film structural colour. Wing materials read a data texture:
   R = brightness, G = hue offset, B = structural-colour strength, A = cut-out.
   Wing materials also flex in the vertex shader (span bend + chord twist).
   ===================================================================== */
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??.32, metalness:o.metal??.5,
    side:o.side??T.FrontSide, envMapIntensity:o.env??1.25, transparent:!!o.transparent, opacity:o.opacity??1 });
  m.defines = {};
  if (o.pat){ m.map = o.pat; m.defines.USE_PAT = ''; m.alphaTest = .5; }
  if (o.bump){ m.bumpMap = o.bump; m.bumpScale = o.bumpScale ?? .003; }
  if (o.flex) m.defines.USE_FLEX = '';
  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},
              uBend:{value:0}, uTwist:{value:0}, uSpan:{value:o.span??1} };
  m.userData.u = u;
  m.onBeforeCompile = sh => {
    Object.assign(sh.uniforms, u);
    sh.vertexShader = 'uniform float uBend; uniform float uTwist; uniform float uSpan;\n' + sh.vertexShader.replace('#include <begin_vertex>', `#include <begin_vertex>
#ifdef USE_FLEX
  float sx = max(transformed.x, 0.0) / uSpan;
  transformed.y += uBend * sx * sx * uSpan + uTwist * transformed.z * sx;
#endif`);
    sh.fragmentShader = 'uniform float uTime; uniform float uHue; uniform float uSat; uniform float uLight; uniform float uIri;\n' + HSL_GLSL +
      sh.fragmentShader.replace('#include <map_fragment>', `
#ifdef USE_PAT
  vec4 patS = texture2D(map, vUv); diffuseColor.a *= patS.a;
#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)*0.45*iriS);
    float L = clamp(uLight * patS.r * 1.9, 0.0, 0.8);
    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.55);
    roughnessFactor = mix(roughnessFactor, 0.16, iriS*0.5);
    totalEmissiveRadiance += c * 0.14 * iriS * pow(1.0-ndv, 1.5);
  }`);
  };
  m.customProgramCacheKey = () => 'iri' + (o.pat?'p':'') + (o.flex?'f':'') + (o.bump?'b':'');
  return m;
}

/* =====================================================================
   SHARED 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 colTex(c,repeat){ const t=new T.CanvasTexture(c); t.encoding=T.sRGBEncoding; t.anisotropy=ANISO; if(repeat){ t.wrapS=t.wrapT=T.RepeatWrapping; t.repeat.set(repeat,repeat);} 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 alongNegZ = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateX(-Math.PI/2);
const SPH = new T.SphereGeometry(1, 24, 16), SPH_LO = new T.SphereGeometry(1, 10, 8);
const HAIR = new T.CylinderGeometry(0, 1, 1, 3, 1);
const _q = new T.Quaternion();
function mesh(geo,mat,parent,pos,scl){ const m=new T.Mesh(geo,mat); if(pos) m.position.copy(pos); if(scl!==undefined) (typeof scl==='number'?m.scale.setScalar(scl):m.scale.copy(scl)); parent&&parent.add(m); return m; }
function hairs(parent, n, sampler, mat, l0, l1, rad){
  const im = new T.InstancedMesh(HAIR, mat, n), m4 = new T.Matrix4();
  for (let i=0;i<n;i++){ const [p,d] = sampler(i); const len = rr(l0,l1); d.normalize(); _q.setFromUnitVectors(UP,d);
    m4.compose(p.clone().addScaledVector(d,len*.5), _q, V3(rad,len,rad)); im.setMatrixAt(i,m4); }
  im.instanceMatrix.needsUpdate = true; parent.add(im); return im;
}
function randDir(){ return V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize(); }
function ellipsoidSampler(c, a, b, cz, bias, filter){
  return () => { let d; do { d = randDir(); } while (filter && !filter(d));
    const p = V3(c.x + d.x*a, c.y + d.y*b, c.z + d.z*cz); const n = V3(d.x/a, d.y/b, d.z/cz).normalize().add(bias); return [p, n]; };
}

/* hex facet bump for compound eyes */
const eyeBump = (()=>{ const c = makeCanvas(256,256,(g,w,h)=>{ g.fillStyle='#000'; g.fillRect(0,0,w,h); const r=4;
  for (let row=0; row*r*1.5<h+r; row++) for (let col=0; col*r*1.75<w+r; col++){
    const x=col*r*1.75+(row%2)*r*.87, y=row*r*1.5, gr=g.createRadialGradient(x,y,0,x,y,r);
    gr.addColorStop(0,'#fff'); gr.addColorStop(.75,'#999'); gr.addColorStop(1,'#000'); g.fillStyle=gr; g.beginPath(); g.arc(x,y,r*.95,0,7); g.fill(); } });
  const t = new T.CanvasTexture(c); t.wrapS=t.wrapT=T.RepeatWrapping; t.repeat.set(3,3); return t; })();

/* =====================================================================
   WING SHAPES  (x = span outward, y = forward)
   ===================================================================== */
function foreShape(){
  const s = new T.Shape();
  s.moveTo(0, .12);
  s.bezierCurveTo(.6,.42, 1.6,.64, 2.5,.58);          // 0 costa
  s.bezierCurveTo(2.72,.56, 2.82,.42, 2.76,.26);      // 1 apex
  s.bezierCurveTo(2.6,-.05, 2.3,-.45, 1.88,-.74);     // 2 outer margin
  s.bezierCurveTo(1.3,-.7, .55,-.42, .05,-.18);       // 3 inner margin
  s.lineTo(0, .12);                                   // 4
  return s;
}
function hindShape(){
  const s = new T.Shape();
  s.moveTo(0, .16);
  s.bezierCurveTo(.7,.38, 1.5,.38, 1.96,.06);         // 0 anterior margin
  s.bezierCurveTo(2.22,-.14, 2.18,-.54, 1.98,-.8);    // 1 outer margin
  s.bezierCurveTo(1.88,-.94, 1.78,-1.0, 1.7,-1.05);   // 2
  s.bezierCurveTo(1.74,-1.4, 1.66,-1.76, 1.52,-1.98); // 3 tail (outer side)
  s.bezierCurveTo(1.45,-2.03, 1.37,-1.97, 1.4,-1.84); // 4 tail tip
  s.bezierCurveTo(1.43,-1.52, 1.45,-1.27, 1.34,-1.12);// 5 tail (inner side)
  s.bezierCurveTo(1.1,-1.06, .86,-.97, .7,-.82);      // 6 tornus
  s.bezierCurveTo(.45,-.56, .2,-.2, 0,.16);           // 7 anal margin
  return s;
}

/* =====================================================================
   WING TEXTURES (pattern data + scale relief) AND GEOMETRY
   ===================================================================== */
function makeWing(def){
  const shape = def.shape;
  const outline = shape.getPoints(90);
  let minX=Infinity,maxX=-Infinity,minY=Infinity,maxY=-Infinity, cx=0, cy=0;
  outline.forEach(p=>{ minX=Math.min(minX,p.x); maxX=Math.max(maxX,p.x); minY=Math.min(minY,p.y); maxY=Math.max(maxY,p.y); cx+=p.x; cy+=p.y; });
  cx/=outline.length; cy/=outline.length;
  const pad=.09; minX-=pad; maxX+=pad; minY-=pad; maxY+=pad;
  const w=maxX-minX, h=maxY-minY, W=1600, H=Math.round(W*h/w), k=W/w;
  const C = (x,y) => [(x-minX)*k, (maxY-y)*k];

  // margin polyline with inward normals
  const marg=[];
  def.outer.forEach(i=>{ const c=shape.curves[i]; const n=Math.max(6,Math.round(c.getLength()*60)); c.getSpacedPoints(n).forEach((p,j)=>{ if(marg.length&&j===0) return; marg.push(p); }); });
  const mn = marg.map((p,i)=>{ const a=marg[Math.max(0,i-1)], b=marg[Math.min(marg.length-1,i+1)];
    let nx=-(b.y-a.y), ny=b.x-a.x; const l=Math.hypot(nx,ny)||1; nx/=l; ny/=l; if(nx*(cx-p.x)+ny*(cy-p.y)<0){nx=-nx;ny=-ny;} return {p,nx,ny}; });
  const inset = (dist, step) => { const out=[]; let acc=step; for(let i=1;i<mn.length;i++){ acc+=mn[i].p.distanceTo(mn[i-1].p); if(acc>=step){ acc=0; out.push([mn[i].p.x+mn[i].nx*dist, mn[i].p.y+mn[i].ny*dist, mn[i]]); } } return out; };

  const H_ = {
    C, k, inset, mn,
    path(g,pts){ g.beginPath(); pts.forEach((p,i)=>{ const [x,y]=C(p[0]??p.x,p[1]??p.y); i?g.lineTo(x,y):g.moveTo(x,y); }); g.closePath(); },
    circ(g,x,y,r,col){ const [px,py]=C(x,y); g.fillStyle=col; g.beginPath(); g.arc(px,py,r*k,0,7); g.fill(); },
    ell(g,x,y,rx,ry,rot,col){ const [px,py]=C(x,y); g.fillStyle=col; g.beginPath(); g.ellipse(px,py,rx*k,ry*k,rot,0,7); g.fill(); },
    radial(g,x,y,r,c0,c1){ const [px,py]=C(x,y), gr=g.createRadialGradient(px,py,0,px,py,r*k); gr.addColorStop(0,c0); gr.addColorStop(1,c1); g.fillStyle=gr; g.fillRect(0,0,W,H); },
    soft(g,fn,col,blur){ g.save(); g.shadowColor=col; g.shadowBlur=blur*k; g.shadowOffsetX=20000; g.translate(-20000,0); g.fillStyle=col; fn(); g.fill(); g.restore(); },
    stroke(g,pts,wu,col){ g.strokeStyle=col; g.lineWidth=wu*k; g.lineJoin=g.lineCap='round'; g.beginPath(); pts.forEach((p,i)=>{ const [x,y]=C(p.x??p[0],p.y??p[1]); i?g.lineTo(x,y):g.moveTo(x,y); }); g.stroke(); },
    veins(g,col,scale=1){ g.lineCap='round'; def.veins.forEach(v=>{ g.strokeStyle=col; g.lineWidth=v[6]*k*scale; g.beginPath(); g.moveTo(...C(v[0],v[1])); g.quadraticCurveTo(...C(v[2],v[3]),...C(v[4],v[5])); g.stroke(); }); }
  };

  const patC = makeCanvas(W,H,g=>{
    g.save(); H_.path(g,outline); g.clip();
    def.paint(g,H_,W,H);
    // scale-level brightness noise (touches only the R channel)
    g.globalCompositeOperation='multiply';
    for(let i=0;i<26000;i++){ const v=Math.round(rr(180,255)); g.fillStyle=`rgb(${v},255,255)`; g.fillRect(rnd()*W,rnd()*H,rr(2,4),rr(1.5,3)); }
    g.globalCompositeOperation='screen';
    for(let i=0;i<9000;i++){ const v=Math.round(rr(10,45)); g.fillStyle=`rgb(${v},0,0)`; g.fillRect(rnd()*W,rnd()*H,rr(2,4),rr(1.5,3)); }
    g.globalCompositeOperation='source-over';
    H_.veins(g,D(.05,.1,.28));
    g.restore();
    // marginal fringe (cilia) — chequered light/dark strands outside the outline
    let acc=0, light=true;
    for(let i=1;i<mn.length;i++){
      const a=mn[i-1], b=mn[i], seg=a.p.distanceTo(b.p), steps=Math.max(1,Math.round(seg*k/2.2));
      for(let s=0;s<steps;s++){ const t=s/steps, x=lerp(a.p.x,b.p.x,t), y=lerp(a.p.y,b.p.y,t); acc+=seg/steps;
        if(acc>.07){ acc=0; light=!light; }
        const L=rr(.035,.055), [x0,y0]=C(x+b.nx*.01,y+b.ny*.01), [x1,y1]=C(x-b.nx*L+rr(-.01,.01),y-b.ny*L+rr(-.01,.01));
        g.strokeStyle=light?D(.85,.12,.15):D(.06,.1,.12); g.lineWidth=2.2; g.beginPath(); g.moveTo(x0,y0); g.lineTo(x1,y1); g.stroke(); } }
  });

  const bumpC = makeCanvas(W,H,g=>{
    g.fillStyle='#808080'; g.fillRect(0,0,W,H);
    // overlapping scale rows, like roof tiles
    const sx=7, sy=5;
    for(let row=0; row*sy<H+sy; row++) for(let col=-1; col*sx<W+sx; col++){
      const x=col*sx+(row%2)*sx*.5+rr(-.8,.8), y=row*sy;
      g.fillStyle=`rgba(255,255,255,${rr(.18,.3)})`; g.beginPath(); g.ellipse(x,y,4.2,2.8,0,0,7); g.fill();
      g.fillStyle='rgba(0,0,0,.28)'; g.fillRect(x+2.6,y-2.5,1.3,5); }
    H_.veins(g,'rgba(255,255,255,.9)',1.25);
  });

  const patT = dataTex(patC), bumpT = new T.CanvasTexture(bumpC); bumpT.anisotropy=ANISO;

  // grid geometry covering the bounding box (alpha-cut to the outline)
  const NU=56, NV=Math.round(NU*h/w)+4, pos=[], uv=[], idx=[];
  for(let j=0;j<=NV;j++) for(let i=0;i<=NU;i++){ const u=i/NU, v=j/NV; pos.push(minX+u*w, 0, minY+v*h); uv.push(u,v); }
  for(let j=0;j<NV;j++) for(let i=0;i<NU;i++){ const a=j*(NU+1)+i, b=a+NU+1; idx.push(a,b,a+1, b,b+1,a+1); }
  const geo = new T.BufferGeometry(); geo.setAttribute('position',new T.Float32BufferAttribute(pos,3)); geo.setAttribute('uv',new T.Float32BufferAttribute(uv,2)); geo.setIndex(idx); geo.computeVertexNormals();
  const mat = iriMat({ pat:patT, bump:bumpT, bumpScale:.0025, flex:true, span:maxX, side:DS, hue:def.hue, light:.5, sat:.88, rough:.34, metal:.3 });
  return { geo, mat };
}

const FORE = makeWing({
  shape: foreShape(), outer:[1,2], hue:.05,
  veins: [
    [.03,.05, .6,.22, 1.22,.26, .022], [.03,.0, .6,-.12, 1.12,-.18, .022], [1.22,.26, 1.18,.04, 1.12,-.18, .016],   // discal cell
    [.03,.08, .7,.4, 1.5,.62, .02],                       // Sc
    [1.0,.24, 1.4,.4, 1.85,.66, .016], [1.22,.26, 1.7,.44, 2.2,.64, .016],
    [1.5,.32, 2.0,.48, 2.55,.62, .014], [1.5,.32, 2.2,.4, 2.85,.42, .014], [1.5,.32, 2.3,.28, 2.85,.2, .014],
    [1.2,.1, 1.9,.08, 2.75,-.02, .016], [1.17,-.04, 1.8,-.12, 2.55,-.32, .016], [1.12,-.18, 1.7,-.32, 2.32,-.58, .016],
    [.95,-.17, 1.5,-.4, 2.05,-.8, .016], [.7,-.15, 1.3,-.4, 1.8,-.85, .016], [.05,-.08, .9,-.38, 1.75,-.8, .018],
  ],
  paint(g,h,W,H){
    g.fillStyle=D(.44,.1,1); g.fillRect(0,0,W,H);
    h.radial(g,0,0,1.15,D(.22,.06,.55,1),D(.22,.06,.55,0));
    h.soft(g,()=>h.path(g,[[.95,.75],[1.75,.75],[1.55,-.95],[.7,-.95]]),D(.7,.24,1),.32);
    h.radial(g,2.8,.42,.75,D(.06,.12,.25,1),D(.06,.12,.25,0));
    h.stroke(g,h.mn.map(m=>m.p),.52,D(.06,.12,.24));
    h.stroke(g,[[.2,.3],[1,.5],[2.,.62],[2.6,.58]],.1,D(.1,.1,.35));
    h.inset(.14,.16).forEach(([x,y,m])=>h.ell(g,x,y,.05,.03,Math.atan2(-m.ny,m.nx)+Math.PI/2,D(.86,.55,.72)));
    h.inset(.3,.3).slice(0,4).forEach(([x,y])=>h.circ(g,x,y,.035,D(.9,.62,.5)));
    [[2.24,.42,.055],[2.43,.34,.05],[2.06,.46,.042],[2.55,.24,.038]].forEach(([x,y,r])=>h.circ(g,x,y,r,D(.85,.32,.15)));
    h.stroke(g,[[1.22,.26],[1.12,-.18]],.08,D(.08,.1,.3));
  }
});
const HIND = makeWing({
  shape: hindShape(), outer:[1,2,3,4,5,6], hue:.52,
  veins: [
    [.03,.12, .5,.24, .98,.2, .02], [.03,.05, .5,-.12, .92,-.26, .02], [.98,.2, .95,0, .92,-.26, .015],
    [.03,.14, .8,.36, 1.55,.42, .018], [.98,.2, 1.5,.25, 2.05,.12, .016], [.97,.05, 1.6,-.05, 2.25,-.32, .016],
    [.95,-.12, 1.5,-.4, 2.1,-.72, .016], [.92,-.26, 1.45,-.9, 1.55,-1.95, .016], [.8,-.3, 1.1,-.75, 1.3,-1.15, .016],
    [.6,-.28, .85,-.7, 1.0,-1.1, .016], [.05,.08, .4,-.4, .74,-.88, .016],
  ],
  paint(g,h,W,H){
    g.fillStyle=D(.44,.1,1); g.fillRect(0,0,W,H);
    h.radial(g,0,.1,1.0,D(.22,.06,.55,1),D(.22,.06,.55,0));
    h.soft(g,()=>{ const [x,y]=h.C(.95,-.15); g.beginPath(); g.ellipse(x,y,.55*h.k,.45*h.k,0,0,7); },D(.7,.24,1),.3);
    h.stroke(g,h.mn.map(m=>m.p),.62,D(.06,.12,.22));
    h.soft(g,()=>h.path(g,[[1.38,-1.1],[1.75,-1.05],[1.6,-2.1],[1.35,-2.1]]),D(.06,.12,.22),.03);
    h.inset(.2,.2).forEach(([x,y,m])=>{ if(y>-1.15) h.ell(g,x,y,.065,.03,Math.atan2(-m.ny,m.nx)+Math.PI/2,D(.82,.56,.95)); });
    h.stroke(g,[[1.47,-1.2],[1.5,-1.55],[1.48,-1.85]],.035,D(.86,.18,.3));
    h.stroke(g,[[.05,.1],[.25,-.25],[.5,-.6],[.72,-.84]],.2,D(.72,.68,.35));
    [[.17,D(.04,.1,.15)],[.14,D(.88,.42,.55)],[.09,D(.04,.1,.2)],[.052,D(.9,.62,.95)],[.018,D(1,.1,0)]].forEach(([r,c],i)=>h.circ(g,1.12-(i===4?.02:0),-.93+(i===4?.02:0),r,c));
  }
});

/* =====================================================================
   BUTTERFLY
   ===================================================================== */
const fly = new T.Group(); scene.add(fly);       // world pose
const body = new T.Group(); fly.add(body);       // flight bob
fly.scale.setScalar(.7);
const leftSide = new T.Group(); leftSide.scale.x = -1; body.add(leftSide);
const sides = [body, leftSide];                   // build right-side parts into both

// --- wings
const wingPivots = { fore:[], hind:[] };
sides.forEach(parent=>{
  const fp = new T.Group(); fp.position.set(.1,.24,.46); parent.add(fp); mesh(FORE.geo,FORE.mat,fp); wingPivots.fore.push(fp);
  const hp = new T.Group(); hp.position.set(.09,.19,.22); parent.add(hp); mesh(HIND.geo,HIND.mat,hp); wingPivots.hind.push(hp);
  // tegula (shoulder scale-plate covering the forewing base)
  const teg = mesh(SPH, iriMat({hue:.92,light:.34,iri:.7,rough:.5}), parent, V3(.15,.27,.48), V3(.07,.035,.15)); teg.rotation.y=-.25;
});

// --- thorax with dense pile
const mThor = iriMat({ hue:.9, light:.3, iri:.6, rough:.45, metal:.4 });
const mFuzz = iriMat({ hue:.86, light:.3, sat:.6, iri:.55, rough:.7, metal:.1 });
mesh(SPH, mThor, body, V3(0,.12,.38), V3(.25,.26,.4));
mesh(SPH, mThor, body, V3(0,.14,.7), V3(.16,.15,.1));   // prothorax collar
hairs(body, 1800, ellipsoidSampler(V3(0,.12,.38),.25,.26,.4,V3(0,.25,-.7)), mFuzz, .05,.11,.006);
hairs(body, 260, ellipsoidSampler(V3(0,.14,.7),.16,.15,.1,V3(0,.4,.6)), mFuzz, .04,.08,.005);

// --- abdomen: articulated chain of 9 segments
const abdJoints=[];
(function(){
  let parent = new T.Group(); parent.position.set(0,.1,.05); body.add(parent);
  const N=9, L=.15;
  for(let i=0;i<N;i++){
    const t=i/(N-1), r0=lerp(.15,.06,t**1.1), r1=lerp(.15,.06,Math.min(1,(t+1/N))**1.1)*.94;
    const j=new T.Group(); parent.add(j); abdJoints.push(j);
    const m=iriMat({ hue:.3+t*.42, light:i%2?.5:.42, iri:.8, rough:.34, metal:.5 });
    mesh(alongNegZ(L, s=>lerp(r0,r1,s)*(.9+.12*Math.sin(Math.PI*Math.min(1,s*1.1))), 16, 8), m, j).scale.y=.95;
    mesh(SPH_LO, iriMat({hue:.2,light:.08,iri:.3}), j, V3(r0*.92,-.01,-L*.5), V3(.012,.016,.022));
    mesh(SPH_LO, iriMat({hue:.2,light:.08,iri:.3}), j, V3(-r0*.92,-.01,-L*.5), V3(.012,.016,.022));
    hairs(j, 70, ()=>{ const a=rr(0,6.28), s=rr(0,1); const r=lerp(r0,r1,s); return [V3(Math.cos(a)*r,Math.sin(a)*r,-s*L), V3(Math.cos(a),Math.sin(a),-1.4)]; }, mFuzz, .025,.05,.004);
    const nx=new T.Group(); nx.position.z=-L*.92; j.add(nx); parent=nx;
  }
  [-1,1].forEach(s=>mesh(alongNegZ(.07,u=>.018*(1-u)+.003,6,4), mThor, parent, V3(s*.025,-.01,0)).rotation.y=s*.25);   // claspers
})();

// --- head
const head = new T.Group(); head.position.set(0,.16,.84); body.add(head);
mesh(SPH, iriMat({hue:.94,light:.3,iri:.6,rough:.4}), head, null, V3(.14,.14,.13));
const mEye = iriMat({ hue:.62, light:.13, sat:.7, iri:1, rough:.08, metal:.75, bump:eyeBump, bumpScale:.002, env:1.8 });
[-1,1].forEach(s=>{ mesh(SPH, mEye, head, V3(s*.095,.02,.04), V3(.105,.12,.115));
  mesh(SPH_LO, new T.MeshStandardMaterial({color:0xffffff,roughness:.05,metalness:.2,envMapIntensity:2}), head, V3(s*.13,.1,.1), .014); });
hairs(head, 320, ellipsoidSampler(V3(0,0,0),.13,.13,.12,V3(0,.3,.3),d=>Math.abs(d.x)<.55), mFuzz, .03,.07,.004);
// labial palps: hairy, curving up in front of the face
const mPalp = iriMat({ hue:.88, light:.42, iri:.6, rough:.55 });
[-1,1].forEach(s=>{
  const pts=[V3(s*.035,-.09,.1),V3(s*.05,-.08,.18),V3(s*.05,-.01,.24),V3(s*.04,.08,.24)];
  const curve=new T.CatmullRomCurve3(pts);
  mesh(new T.TubeGeometry(curve,20,.022,8,false), mPalp, head);
  hairs(head, 90, ()=>{ const p=curve.getPoint(rnd()); return [p, randDir().add(V3(0,.6,.8))]; }, mFuzz, .03,.06,.004);
});
// coiled proboscis (rebuilt as it uncoils)
const mProb = iriMat({ hue:.02, light:.45, iri:.8, rough:.35, metal:.5 });
const prob = mesh(new T.BufferGeometry(), mProb, head, V3(0,-.1,.12));
let probU=-1;
function setProboscis(u){
  if (Math.abs(u-probU)<.004) return; probU=u;
  const N=56, Lp=.9, ds=Lp/N, pts=[V3()]; let y=0,z=0,th=lerp(-.25,.3,u);
  for(let i=0;i<N;i++){ const s=i/N, kc=1/(.085*(1-.88*s)+.008), k=lerp(kc,.6,smooth(u)); th+=k*ds; y-=Math.cos(th)*ds; z+=Math.sin(th)*ds; pts.push(V3(0,y,z)); }
  prob.geometry.dispose(); prob.geometry=new T.TubeGeometry(new T.CatmullRomCurve3(pts),90,.0095,6,false);
}
setProboscis(0);

// --- antennae: ringed shaft, gradual club, slightly hooked tip
const antennae=[];
const mAntA = iriMat({ hue:.88, light:.48, iri:.7, rough:.4 }), mAntB = iriMat({ hue:.9, light:.18, iri:.5, rough:.45 });
const mClub = iriMat({ hue:.95, light:.5, iri:1, rough:.28, metal:.6 });
[-1,1].forEach(s=>{
  const root=new T.Group(); root.position.set(s*.04,.12,.08); head.add(root);
  root.quaternion.setFromUnitVectors(V3(0,0,1), V3(s*.32,.55,1).normalize());
  const joints=[]; let parent=root; const N=40;
  for(let i=0;i<N;i++){
    const t=i/(N-1), club=smooth((t-.72)/.2), tip=t>.95?(t-.95)/.05:0;
    const L=.042, r=.0105+club*.022*(1-tip*.7);
    const j=new T.Group(); j.userData.bx=-.008+(t>.9?.06:0); j.userData.by=s*.006; j.rotation.set(j.userData.bx,j.userData.by,0); parent.add(j);
    mesh(alongZ(L,u=>r*(.9+.1*Math.sin(u*Math.PI)),8,3), club>.05?mClub:(i%2?mAntA:mAntB), j);
    const nx=new T.Group(); nx.position.z=L; j.add(nx); parent=nx; joints.push(j);
  }
  mesh(SPH_LO, mClub, parent, null, V3(.012,.012,.018));
  antennae.push({joints,s});
});

// --- legs (built for the right side, mirrored for the left)
const mLeg = iriMat({ hue:.85, light:.42, iri:.7, rough:.4, metal:.45 }), mLegD = iriMat({ hue:.8, light:.2, iri:.5, rough:.5 });
const mClaw = new T.MeshStandardMaterial({ color:lin(0x0e0805), roughness:.3, metalness:.6 });
const LEGS=[ {pos:[.1,-.05,.6],yaw:-.75,f:.3,t:.28,ts:.24}, {pos:[.13,-.08,.43],yaw:.05,f:.34,t:.32,ts:.26}, {pos:[.13,-.08,.25],yaw:.55,f:.36,t:.36,ts:.28} ];
const legs=[];
sides.forEach(parentSide=>LEGS.forEach((d,li)=>{
  const root=new T.Group(); root.position.set(...d.pos); root.rotation.y=d.yaw; parentSide.add(root);
  const segs=[[.09,.03,mLegD],[d.f,.024,mLeg],[d.t,.018,mLeg],[d.ts,.011,mLegD]];
  let parent=root; const joints=[];
  segs.forEach(([L,r,m],si)=>{
    const j=new T.Group(); parent.add(j); joints.push(j);
    if(si<3) mesh(alongX(L,u=>r*(.85+.25*Math.sin(Math.PI*u))*(1-.25*u),8,6), m, j);
    else { let x=0; [.34,.18,.16,.14,.18].forEach((f,k)=>{ mesh(alongX(L*f,u=>r*(1-k*.1)*(.8+.2*u),6,3), m, j, V3(x,0,0)); x+=L*f; });
      [-1,1].forEach(cs=>{ const c=mesh(alongX(.04,u=>.006*(1-u)+.001,5,3), mClaw, j, V3(L,0,cs*.006)); c.rotation.set(0,cs*.3,-1.0); }); }
    if(si===1||si===2) hairs(j, si===1?40:26, ()=>{ const x=rnd()*L, a=rr(0,6.28); return [V3(x,Math.cos(a)*r,Math.sin(a)*r), V3(.8,Math.cos(a),Math.sin(a))]; }, mFuzz, .02,.045,.003);
    if(si===2) [-1,1].forEach(cs=>mesh(alongX(.05,u=>.007*(1-u)+.001,5,3), mLegD, j, V3(L*.97,-.01,cs*.012)).rotation.set(0,cs*.4,-.5));   // tibial spurs
    const nx=new T.Group(); nx.position.x=L; j.add(nx); parent=nx;
  });
  legs.push({joints, li});
}));
const POSE = {
  tuck:  [[-1.3,-.2,-1.9,.3],[-1.35,-.15,-2.0,.3],[-1.4,-.1,-2.1,.3]],
  stand: [[-1.0,.75,-1.45,.75],[-1.1,.8,-1.4,.7],[-1.1,.75,-1.35,.65]],
  yawT:  [.55,.45,.35],
};

/* =====================================================================
   FLOWER (purple coneflower)
   ===================================================================== */
const flower = new T.Group(); flower.position.set(0,-.6,0); scene.add(flower);
(function(){
  // central cone of spiky florets
  const dome = mesh(new T.SphereGeometry(.55,40,20,0,Math.PI*2,0,Math.PI/2), new T.MeshStandardMaterial({color:lin(0x3a160a),roughness:.6}), flower, V3(0,-.3,0), V3(1,.55,1));
  const N=560, im=new T.InstancedMesh(new T.ConeGeometry(.032,.11,5).translate(0,.055,0), new T.MeshStandardMaterial({color:0xffffff,roughness:.45,metalness:.1}), N);
  const m4=new T.Matrix4(), col=new T.Color(), gold=Math.PI*(3-Math.sqrt(5));
  for(let i=0;i<N;i++){ const r=Math.sqrt((i+.5)/N), a=i*gold, x=Math.cos(a)*r*.53, z=Math.sin(a)*r*.53;
    const y=-.3+.55*.55*Math.sqrt(Math.max(0,1-(r*.53/.55)**2)); const n=V3(x/.55,(y+.3)/(.55*.55)*.55,z/.55).normalize();
    _q.setFromUnitVectors(UP,n.lerp(UP,.35).normalize()); m4.compose(V3(x,y,z),_q,V3(1,rr(.8,1.2),1)); im.setMatrixAt(i,m4);
    col.set(r<.25?0x5a6a22:0x9a3f14).lerp(new T.Color(0xd8741f), rnd()*.5*r).convertSRGBToLinear(); im.setColorAt(i,col); }
  flower.add(im);
  // petals
  const petalC = makeCanvas(512,128,(g,w,h)=>{ let gr=g.createLinearGradient(0,0,w,0); gr.addColorStop(0,'#5e1239'); gr.addColorStop(.25,'#a8336f'); gr.addColorStop(1,'#c65c93');
    g.fillStyle=gr; g.fillRect(0,0,w,h); for(let i=0;i<22;i++){ g.strokeStyle=`rgba(120,20,70,${rr(.15,.35)})`; g.lineWidth=rr(1,2); const y=h*(i+.5)/22; g.beginPath(); g.moveTo(0,h/2+(y-h/2)*.3); g.quadraticCurveTo(w*.4,y,w,y+(y-h/2)*.1); g.stroke(); }
    for(let i=0;i<500;i++){ g.fillStyle=`rgba(255,220,240,${rr(.03,.08)})`; g.fillRect(rnd()*w,rnd()*h,2,2); } });
  const mPetal = new T.MeshStandardMaterial({ map:colTex(petalC), roughness:.55, side:DS });
  const NP=16;
  for(let p=0;p<NP;p++){
    const pos=[],uv=[],idx=[],NU=18,NV=6,L=1.45+rr(-.1,.1);
    let x=0,y=0; const droop=rr(.8,1.05);
    for(let i=0;i<=NU;i++){ const s=i/NU, ang=-.2-droop*s*s, wd=.17*Math.pow(Math.sin(Math.PI*Math.min(1,s*1.15+.08)),.5)*(1-.25*s)+.02;
      if(i){ x+=Math.cos(ang)*L/NU; y+=Math.sin(ang)*L/NU; }
      for(let j=0;j<=NV;j++){ const v=j/NV*2-1; const notch=s>.95?-.03*Math.abs(Math.sin(v*Math.PI*1.5)):0; pos.push(x+notch, y+.05*v*v, v*wd); uv.push(s,j/NV); } }
    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();
    const pg=new T.Group(); pg.rotation.y=p/NP*Math.PI*2+rr(-.08,.08); pg.position.y=-.2; flower.add(pg);
    const pm=mesh(g,mPetal,pg,V3(.42,0,0)); pm.rotation.x=rr(-.15,.15);
  }
  // stem & leaves
  const mGreen = new T.MeshStandardMaterial({ color:lin(0x2c4a1e), roughness:.6 });
  mesh(new T.TubeGeometry(new T.CatmullRomCurve3([V3(0,-.3,0),V3(.04,-2,.02),V3(.2,-5,.1),V3(.45,-11,.25)]),40,.06,10,false), mGreen, flower);
  mesh(new T.CylinderGeometry(.18,.06,.2,16), mGreen, flower, V3(0,-.38,0));
  [[-2.6,.6],[-4.2,3.4]].forEach(([y,a])=>{ const pos=[],idx=[],NU=14; for(let i=0;i<=NU;i++){ const s=i/NU, wd=.28*Math.sin(Math.PI*s)**.8; const px=s*1.8, py=.5*s-.6*s*s;
      pos.push(px,py,-wd, px,py+.04,0, px,py,wd); }
    for(let i=0;i<NU;i++){ const a0=i*3; idx.push(a0,a0+3,a0+1, a0+1,a0+3,a0+4, a0+1,a0+4,a0+2, a0+2,a0+4,a0+5); }
    const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setIndex(idx); g.computeVertexNormals();
    const lf=mesh(g,new T.MeshStandardMaterial({color:lin(0x34561f),roughness:.55,side:DS}),flower,V3(.06,y,0)); lf.rotation.y=a; });
})();

/* drifting pollen motes */
const motes = (()=>{ const N=320, pos=new Float32Array(N*3); for(let i=0;i<N;i++){ pos[i*3]=rr(-9,9); pos[i*3+1]=rr(-5,6); pos[i*3+2]=rr(-9,9); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,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,240,220,1)'); gr.addColorStop(.3,'rgba(255,200,240,.35)'); gr.addColorStop(1,'rgba(0,0,0,0)'); x.fillStyle=gr; x.fillRect(0,0,64,64); }));
  const p=new T.Points(g,new T.PointsMaterial({size:.07,map:sp,transparent:true,depthWrite:false,blending:T.AdditiveBlending,opacity:.55})); scene.add(p); return p; })();

/* lights */
scene.add(new T.HemisphereLight(0xbfd8ff,0x1a1030,.5));
const key=new T.DirectionalLight(0xffffff,1.1); key.position.set(4,7,6); scene.add(key);
const rim=new T.PointLight(0x33ccff,2.2,70); rim.position.set(-6,3,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.8,70); rim2.position.set(6,-2,-3); scene.add(rim2);
const under=new T.PointLight(0x8855ff,.8,45); under.position.set(0,-5,3); scene.add(under);
const glint=new T.PointLight(0xffffff,1.0,45); glint.position.set(2,4,8); scene.add(glint);

/* =====================================================================
   BEHAVIOUR: wander-flight around the flower, land, sip, bask, take off
   ===================================================================== */
const FLOWER_TOP = () => flower.localToWorld(V3(0,.05,0));
let tau = 0;
function wander(t){
  const c=FLOWER_TOP(), a=t*.42, R=3.1+.8*Math.sin(t*.33);
  return V3(c.x+Math.cos(a)*R+.3*Math.sin(t*2.3), c.y+1.3+.9*Math.sin(t*.7)+.35*Math.sin(t*1.9), c.z+Math.sin(a)*R+.3*Math.cos(t*1.7));
}
const st = { mode:'fly', t:0, dur:rr(7,11), p0:V3(), p1:V3(), c0:V3(), c1:V3(), q0:new T.Quaternion(), q1:new T.Quaternion(), perchYaw:0 };
const bez=(a,b,c,d,s)=>{ const u=1-s; return a.clone().multiplyScalar(u*u*u).addScaledVector(b,3*u*u*s).addScaledVector(c,3*u*s*s).addScaledVector(d,s*s*s); };
const eul=new T.Euler(0,0,0,'YXZ');
function perchPose(){ const top=FLOWER_TOP(), fwd=V3(Math.sin(st.perchYaw),0,Math.cos(st.perchYaw));
  return { p: top.add(V3(0,.37,0)).addScaledVector(fwd,-.28), q: new T.Quaternion().setFromEuler(eul.set(-.06,st.perchYaw,0)) }; }

let flapPh=0, amp=1, mid=.35, freq=3.6, wingOpen=0, legStand=0, probT=0, probCur=0;
let prevPos=wander(0), velS=V3(), roll=0, glideT=0, baskT=0;
fly.position.copy(prevPos);

function setTargets(mode,dt,t){
  let tAmp=1.05, tMid=.35, tFreq=3.6;
  if(mode==='fly'){ glideT-=dt; if(glideT<-rr(1.5,4)) glideT=rr(.4,.9); if(glideT>0){ tAmp=.04; tMid=.2; } }
  else if(mode==='approach'){ const s=st.t/st.dur; tAmp=lerp(1.0,.5,s); tFreq=lerp(3.6,4.4,s); if(s>.82){ tAmp=lerp(.5,.0,(s-.82)/.18); tMid=lerp(.35,1.45,(s-.82)/.18); } }
  else if(mode==='perch'){ baskT-=dt; if(baskT<-rr(2.5,5)) baskT=rr(2.5,4); const bask=baskT>0;
    tAmp=bask?.18:.03; tFreq=bask?.55:.8; tMid=bask?.25:1.42; }
  else if(mode==='takeoff'){ tAmp=1.25; tFreq=4.6; tMid=.4; }
  const k=1-Math.exp(-dt*4); amp+=(tAmp-amp)*k; mid+=(tMid-mid)*(1-Math.exp(-dt*(mode==='perch'?1.6:5))); freq+=(tFreq-freq)*k;
}

function updateFlight(dt,t){
  st.t+=dt;
  if(st.mode==='fly'){
    tau+=dt; const p=wander(tau); fly.position.copy(p);
    if(st.t>st.dur){ st.mode='approach'; st.t=0; st.dur=2.8; st.p0.copy(p); st.c0.copy(p).addScaledVector(velS,1.1);
      st.perchYaw=Math.atan2(velS.x,velS.z)+rr(-.6,.6); const pp=perchPose(); st.p1.copy(pp.p); st.c1.copy(pp.p).add(V3(0,1.1,0)); st.q0.copy(fly.quaternion); }
  } else if(st.mode==='approach'){
    const s=smooth(st.t/st.dur), pp=perchPose(); st.p1.copy(pp.p);
    fly.position.copy(bez(st.p0,st.c0,st.c1,st.p1,Math.min(1,st.t/st.dur*1.0)));
    if(st.t>=st.dur){ st.mode='perch'; st.t=0; st.dur=rr(8,12); baskT=-1; }
  } else if(st.mode==='perch'){
    const pp=perchPose(); fly.position.copy(pp.p); fly.quaternion.slerp(pp.q,1-Math.exp(-dt*3));
    if(st.t>st.dur){ st.mode='takeoff'; st.t=0; st.dur=1.8; tau+=2.2; st.p0.copy(fly.position); st.c0.copy(fly.position).add(V3(0,1.3,0));
      const w=wander(tau); st.p1.copy(w); st.c1.copy(w).sub(wander(tau+.15)).multiplyScalar(6).add(w); }
  } else if(st.mode==='takeoff'){
    const w=wander(tau); st.p1.copy(w); fly.position.copy(bez(st.p0,st.c0,st.c1,st.p1,smooth(st.t/st.dur)));
    if(st.t>=st.dur){ st.mode='fly'; st.t=0; st.dur=rr(8,13); }
  }
  // velocity-aligned orientation while airborne
  const v=fly.position.clone().sub(prevPos).divideScalar(Math.max(dt,1e-4)); prevPos.copy(fly.position);
  velS.lerp(v,1-Math.exp(-dt*4));
  if(st.mode!=='perch'){
    const hs=Math.hypot(velS.x,velS.z), yaw=Math.atan2(velS.x,velS.z);
    let pitch=-.38-Math.atan2(velS.y,hs+.2)*.45;
    const fq=fly.quaternion.clone(); const cur=new T.Euler().setFromQuaternion(fq,'YXZ');
    let dy=yaw-cur.y; dy=Math.atan2(Math.sin(dy),Math.cos(dy)); roll+=(clamp(-dy*1.4,-.5,.5)-roll)*(1-Math.exp(-dt*3));
    let q=new T.Quaternion().setFromEuler(eul.set(pitch,yaw,roll));
    if(st.mode==='approach'){ const s=smooth((st.t/st.dur-.55)/.45); q.slerp(perchPose().q,s); }
    if(hs>.05||st.mode==='approach') fly.quaternion.slerp(q,1-Math.exp(-dt*(st.mode==='approach'?4:3)));
  }
}

/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:8,yaw:.6,pitch:.28,tYaw:.6,tPitch:.28,tDist:8,auto:0};
const camTarget=FLOWER_TOP().add(V3(0,.8,0));
let dragging=false;
function fitCam(){ const w=innerWidth; camera.fov=w<480?58:w<768?50:44; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,10); }
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,3,18); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,-.9,1.3); lx=e.clientX; ly=e.clientY; });
const up=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,up));
canvas.addEventListener('wheel',e=>{ e.preventDefault(); cam.tDist=clamp(cam.tDist+e.deltaY*.007,3,18); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });

/* =====================================================================
   FRAME
   ===================================================================== */
const clock=new T.Clock(); let time=0;
function frame(){
  requestAnimationFrame(frame);
  const dt=Math.min(clock.getDelta(),1/20); time+=dt; const t=time;
  U_TIME.value=t;

  flower.rotation.z=.025*Math.sin(t*.6)+.012*Math.sin(t*1.7); flower.rotation.x=.02*Math.sin(t*.45);
  updateFlight(dt,t);
  setTargets(st.mode,dt,t);

  // wings
  flapPh+=freq*dt*Math.PI*2;
  const fa=mid+amp*Math.sin(flapPh), ha=mid+amp*.92*Math.sin(flapPh-.38);
  wingPivots.fore.forEach(p=>{ p.rotation.set(.05*amp*Math.sin(flapPh-.3), -.18+.1*amp*Math.cos(flapPh), fa); });
  wingPivots.hind.forEach(p=>{ p.rotation.set(.04*amp*Math.sin(flapPh-.6), .22+.06*amp*Math.cos(flapPh), ha); });
  FORE.mat.userData.u.uBend.value=-.22*amp*Math.cos(flapPh); FORE.mat.userData.u.uTwist.value=.2*amp*Math.cos(flapPh+.3);
  HIND.mat.userData.u.uBend.value=-.26*amp*Math.cos(flapPh-.38); HIND.mat.userData.u.uTwist.value=.16*amp*Math.cos(flapPh-.1);

  // body response to the stroke
  const airborne=st.mode!=='perch';
  body.position.y=airborne?.12*amp*Math.cos(flapPh):0;
  body.rotation.x=airborne?.06*amp*Math.sin(flapPh+.5):0;
  abdJoints.forEach((j,i)=>{ j.rotation.x=(airborne?.05*amp*Math.sin(flapPh-.4-i*.25):0)+.03*Math.sin(t*1.3-i*.4)+(i===0?(airborne?.12:-.05):.01); });

  // legs: tucked in flight, planted when perched
  legStand+=((st.mode==='perch'||(st.mode==='approach'&&st.t/st.dur>.6))?1:0)-legStand; legStand=clamp(legStand,0,1);
  const ls=smooth(legStandS+=(legStand-legStandS)*(1-Math.exp(-dt*4)));
  legs.forEach(L=>{ const a=POSE.tuck[L.li], b=POSE.stand[L.li]; L.joints.forEach((j,k)=>j.rotation.z=lerp(a[k],b[k],ls)+(k===2?.04*Math.sin(t*2+L.li):0));
    L.joints[0].rotation.y=lerp(POSE.yawT[L.li],0,ls); });

  // proboscis: uncoils into the flower while perched
  probT=st.mode==='perch'&&st.t>1&&st.t<st.dur-1.2?1:0; probCur+=(probT-probCur)*(1-Math.exp(-dt*1.6));
  setProboscis(probCur+(probT?.02*Math.sin(t*3):0));
  head.rotation.x=lerp(0,.22,probCur)+.03*Math.sin(t*1.3); head.rotation.y=.04*Math.sin(t*.65);

  // antennae
  antennae.forEach(({joints,s})=>joints.forEach((j,i)=>{ const u=i/joints.length;
    j.rotation.x=j.userData.bx+Math.sin(t*2.2-i*.35)*.012*u+(airborne?.004:0);
    j.rotation.y=j.userData.by+Math.sin(t*1.7-i*.3+s*1.3)*.016*u; }));

  // motes drift
  const mp=motes.geometry.attributes.position; for(let i=0;i<mp.count;i++){ let y=mp.getY(i)+dt*.06; if(y>6) y=-5; mp.setY(i,y); mp.setX(i,mp.getX(i)+Math.sin(t*.3+i)*.002); } mp.needsUpdate=true;

  // camera follows a point between the flower and the butterfly
  const want=FLOWER_TOP().add(V3(0,.7,0)).lerp(fly.position,.5);
  camTarget.lerp(want,1-Math.exp(-dt*1.5));
  if(!dragging&&!reduceMotion) cam.auto+=dt*.08;
  cam.yaw+=(cam.tYaw-cam.yaw)*.08; cam.pitch+=(cam.tPitch-cam.pitch)*.08; cam.dist+=(cam.tDist-cam.dist)*.08;
  const y=cam.yaw+cam.auto, p=cam.pitch;
  camera.position.set(camTarget.x+Math.sin(y)*Math.cos(p)*cam.dist, camTarget.y+Math.sin(p)*cam.dist, camTarget.z+Math.cos(y)*Math.cos(p)*cam.dist);
  camera.lookAt(camTarget);

  renderer.render(scene,camera);
}
let legStandS=0;
frame();
}
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.