Skip to content
VibeCodeBench
Back to the app

The code

Jelly Cat by Claude Opus 5.5

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)35.4 KB · 437 lines · loads unpkg.com/[email protected]/build/three.module.js, unpkg.com/[email protected]/examples/jsm/
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Jelly Cat</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#e9f1f3;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#2b3a44;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
#top{position:fixed;left:0;right:0;top:0;padding:max(10px,env(safe-area-inset-top)) 16px 0;text-align:center;pointer-events:none}
#top h1{margin:0;font-size:21px;font-weight:800;letter-spacing:.5px;color:#e0661a}
#hint{margin-top:3px;font-size:14px;opacity:.75}
#panel{position:fixed;left:50%;transform:translateX(-50%);bottom:max(12px,env(safe-area-inset-bottom));width:min(720px,calc(100% - 24px));box-sizing:border-box;display:flex;gap:12px;align-items:center;padding:12px;border-radius:22px;background:rgba(255,255,255,.66);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);box-shadow:0 8px 30px rgba(40,70,90,.18)}
button{font:inherit;border:0;cursor:pointer;touch-action:manipulation}
#drop{flex:0 0 auto;min-height:58px;padding:0 22px;border-radius:16px;background:linear-gradient(#ffa24a,#ff7a1c);color:#fff;font-size:18px;font-weight:800;box-shadow:0 4px 0 #d85f0c,0 8px 18px rgba(255,120,30,.35)}
#drop:active,#drop.pressed{transform:translateY(3px);box-shadow:0 1px 0 #d85f0c}
#snd{flex:0 0 auto;width:58px;height:58px;border-radius:16px;background:#fff;color:#e0661a;box-shadow:0 2px 8px rgba(0,0,0,.12);display:grid;place-items:center}
.sl{flex:1 1 auto;min-width:0}
.lab{display:flex;justify-content:space-between;font-size:13px;font-weight:700;opacity:.8;margin:0 4px}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:44px;background:transparent;margin:0;touch-action:none}
input[type=range]::-webkit-slider-runnable-track{height:14px;border-radius:8px;background:linear-gradient(90deg,#ffe2b8,#ff7a1c)}
input[type=range]::-moz-range-track{height:14px;border-radius:8px;background:linear-gradient(90deg,#ffe2b8,#ff7a1c)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:36px;height:36px;margin-top:-11px;border-radius:50%;background:#fff;border:4px solid #ff8a2a;box-shadow:0 2px 6px rgba(0,0,0,.25)}
input[type=range]::-moz-range-thumb{width:28px;height:28px;border-radius:50%;background:#fff;border:4px solid #ff8a2a}
@media (max-width:560px){#panel{flex-wrap:wrap}#drop{flex:1 1 auto}.sl{flex:1 1 100%;order:3}}
#finger{position:fixed;left:0;top:0;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;background:rgba(255,255,255,.5);border:3px solid rgba(255,255,255,.95);box-shadow:0 2px 10px rgba(0,0,0,.25);pointer-events:none;display:none;transition:transform .08s,background .08s;z-index:5}
#finger.down{transform:scale(.78);background:rgba(255,170,90,.65)}
#msg{position:fixed;inset:0;display:grid;place-items:center;font-size:18px;pointer-events:none}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="top"><h1>Jelly Cat</h1><div id="hint">Tap to poke &middot; hold to squeeze &middot; drag ears, cheeks or tail &middot; rub its head</div></div>
<div id="panel">
  <button id="drop" type="button">Drop from above</button>
  <div class="sl"><div class="lab"><span>Soft pudding</span><span>Firm gummy</span></div><input id="firm" type="range" min="0" max="100" value="30" aria-label="Jelly firmness"></div>
  <button id="snd" type="button" aria-label="Sound on or off"></button>
</div>
<div id="finger"></div>
<div id="msg">Making jelly&hellip;</div>
<script type="importmap">{"imports":{"three":"https://unpkg.com/[email protected]/build/three.module.js","three/addons/":"https://unpkg.com/[email protected]/examples/jsm/"}}</script>
<script type="module">
import * as THREE from 'three';
import {RoomEnvironment} from 'three/addons/environments/RoomEnvironment.js';

const V3=THREE.Vector3,$=i=>document.getElementById(i),msg=$('msg');
const clamp=(v,a,b)=>v<a?a:v>b?b:v,lerp=(a,b,t)=>a+(b-a)*t,ease=t=>{t=clamp(t,0,1);return t*t*(3-2*t);};
const lerp2=(a,b,t)=>[lerp(a[0],b[0],t),lerp(a[1],b[1],t)];
let stiff=0.3,time=0,flash=0,pokeSq=0,rub=0,purr=0,earT=3,eo=1,blinkT=2.5,blinkA=0;
const look={x:0,y:0,until:-1};
const tA=new V3(),tB=new V3(),tC=new V3(),tV=new V3();

let renderer;
try{renderer=new THREE.WebGLRenderer({canvas:$('c'),antialias:true,powerPreference:'high-performance'});}
catch(e){msg.textContent='Sorry, this device cannot show 3D (WebGL is off).';throw e;}
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,1.75));
renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
const scene=new THREE.Scene();
const camera=new THREE.PerspectiveCamera(30,1,0.1,150);
const pmrem=new THREE.PMREMGenerator(renderer);
scene.environment=pmrem.fromScene(new RoomEnvironment(renderer),0.04).texture;

/* ---------- cat shape (signed distance field) ---------- */
function sdE(px,py,pz,cx,cy,cz,rx,ry,rz){const x=(px-cx)/rx,y=(py-cy)/ry,z=(pz-cz)/rz;const k0=Math.sqrt(x*x+y*y+z*z),k1=Math.sqrt(x*x/(rx*rx)+y*y/(ry*ry)+z*z/(rz*rz));return k1<1e-9?-Math.min(rx,ry,rz):k0*(k0-1)/k1;}
function smin(a,b,k){const h=Math.max(k-Math.abs(a-b),0)/k;return Math.min(a,b)-h*h*k*0.25;}
function catSDF(x,y,z){const ax=Math.abs(x);
  let d=sdE(x,y,z,0,0.6,0,0.7,0.62,0.6);
  d=smin(d,sdE(x,y,z,0,0.34,-0.04,0.84,0.38,0.7),0.22);
  d=smin(d,sdE(x,y,z,0,0.78,0.22,0.46,0.44,0.38),0.18);
  d=smin(d,sdE(ax,y,z,0.27,0.13,0.47,0.17,0.13,0.21),0.12);
  d=smin(d,sdE(x,y,z,0,1.45,0.1,0.64,0.5,0.52),0.28);
  d=smin(d,sdE(ax,y,z,0.34,1.3,0.3,0.27,0.22,0.26),0.12);
  d=smin(d,sdE(ax,y,z,0.085,1.31,0.56,0.12,0.095,0.1),0.06);
  return -smin(-d,y,0.04);}
function proj(c,d,p,n){let t=2.6,prev=t;
  for(let i=0;i<140;i++){const v=catSDF(c.x+d.x*t,c.y+d.y*t,c.z+d.z*t);if(v<4e-4)break;prev=t;t-=Math.max(v*0.85,0.002);if(t<=0){t=0;break;}}
  let lo=t,hi=prev;for(let i=0;i<10;i++){const m=(lo+hi)/2;if(catSDF(c.x+d.x*m,c.y+d.y*m,c.z+d.z*m)>0)hi=m;else lo=m;}
  t=(lo+hi)/2;p.set(c.x+d.x*t,c.y+d.y*t,c.z+d.z*t);const e=0.002;
  n.set(catSDF(p.x+e,p.y,p.z)-catSDF(p.x-e,p.y,p.z),catSDF(p.x,p.y+e,p.z)-catSDF(p.x,p.y-e,p.z),catSDF(p.x,p.y,p.z+e)-catSDF(p.x,p.y,p.z-e)).normalize();
  return p;}

/* ---------- soft-body control nodes ---------- */
const tailCurve=new THREE.CatmullRomCurve3([[0.2,0.3,-0.5],[0.55,0.17,-0.45],[0.82,0.14,-0.1],[0.8,0.14,0.3],[0.56,0.15,0.6],[0.27,0.2,0.74]].map(a=>new V3(a[0],a[1],a[2])));
const ND=[[0,0.55,0,.45],[0,0.55,0.5,.34],[0,0.62,-0.5,.36],[-0.6,0.42,0,.34],[0.6,0.42,0,.34],[0,1.02,0.12,.32],[-0.28,0.14,0.52,.2],[0.28,0.14,0.52,.2],
 [0,1.45,0.1,.34],[0,1.86,0.08,.26],[-0.42,1.3,0.32,.21],[0.42,1.3,0.32,.21],[-0.47,2.07,0.03,.2],[0.47,2.07,0.03,.2],[0,1.34,0.6,.2]];
[0.36,0.6,0.8,0.97].forEach((q,k)=>{const p=tailCurve.getPointAt(q);ND.push([p.x,p.y,p.z,.17,k>0?1:0]);});
const NN=ND.length,EARL=12,EARR=13,TIP=NN-1,TAIL0=NN-4;
const R=new Float32Array(NN*3),IS=new Float32Array(NN),TO=new Float32Array(NN);
const u=new Float32Array(NN*3),vel=new Float32Array(NN*3),off=new Float32Array(NN*3),tgt=new Float32Array(NN*3),gk=new Float32Array(NN);
ND.forEach((n,i)=>{R[i*3]=n[0];R[i*3+1]=n[1];R[i*3+2]=n[2];IS[i]=1/(n[3]*n[3]);TO[i]=n[4]||0;});
const NB=[];
for(let i=0;i<NN;i++){const l=[];let s=0;for(let j=0;j<NN;j++){if(j===i)continue;const dx=R[i*3]-R[j*3],dy=R[i*3+1]-R[j*3+1],dz=R[i*3+2]-R[j*3+2];let a=Math.exp(-(dx*dx+dy*dy+dz*dz)/0.25);if(TO[i]!==TO[j])a*=0.25;if(a>0.03){l.push(j,a);s+=a;}}NB.push({l,inv:s>0?1/s:0});}
const G={sq:0,sqv:0,sx:0,sxv:0,sz:0,szv:0,sqT:0,sxT:0,szT:0};
function F(x,y,z,t,o){let dx=0,dy=0,dz=0,ws=0;
  for(let i=0;i<NN;i++){if(TO[i]&&!t)continue;const i3=i*3,rx=x-R[i3],ry=y-R[i3+1],rz=z-R[i3+2];const w=Math.exp(-(rx*rx+ry*ry+rz*rz)*IS[i]);dx+=w*u[i3];dy+=w*u[i3+1];dz+=w*u[i3+2];ws+=w;}
  const s=1/Math.max(ws,1);let px=x+dx*s,py=y+dy*s,pz=z+dz*s;const h=Math.max(py,0);
  py*=1-G.sq;px*=1+G.sq*0.55;pz*=1+G.sq*0.55;px+=G.sx*h*h*0.5;pz+=G.sz*h*h*0.5;
  return o.set(px,Math.max(py,0),pz);}

/* ---------- jelly material with GPU deformation ---------- */
const U={uRest:{value:R},uDisp:{value:u},uIS:{value:IS},uTO:{value:TO},uGlob:{value:new THREE.Vector4()},uGlow:{value:0.45},uGlowCol:{value:new THREE.Color(0xffa040)}};
const DEF=`#define NN ${NN}
uniform vec3 uRest[NN];
uniform vec3 uDisp[NN];
uniform float uIS[NN];
uniform float uTO[NN];
uniform vec4 uGlob;
attribute float aT;
vec3 dfP(vec3 x){
  vec3 d=vec3(0.0);float ws=0.0;
  for(int i=0;i<NN;i++){vec3 r=x-uRest[i];float w=exp(-dot(r,r)*uIS[i])*(1.0-uTO[i]*(1.0-aT));d+=w*uDisp[i];ws+=w;}
  vec3 p=x+d/max(ws,1.0);
  float h=max(p.y,0.0);
  p.y*=1.0-uGlob.x;p.xz*=1.0+uGlob.x*0.55;
  p.x+=uGlob.y*h*h*0.5;p.z+=uGlob.z*h*h*0.5;
  p.y=max(p.y,0.0);
  return p;
}
vec3 dfN(vec3 x,vec3 n,vec3 p0){
  vec3 a=abs(n.y)<0.9?vec3(0.0,1.0,0.0):vec3(1.0,0.0,0.0);
  vec3 t1=normalize(cross(n,a));vec3 t2=cross(n,t1);
  vec3 c=cross(dfP(x+t1*0.012)-p0,dfP(x+t2*0.012)-p0);
  float l=length(c);
  return l>1e-10?c/l:n;
}
`;
const jelly=new THREE.MeshPhysicalMaterial({color:0xffa850,metalness:0,roughness:0.09,transmission:1,thickness:0.7,ior:1.35,attenuationColor:new THREE.Color(0xff6a00),attenuationDistance:0.8,clearcoat:1,clearcoatRoughness:0.04,specularIntensity:1,envMapIntensity:1.25});
jelly.customProgramCacheKey=()=>'jellycat1';
jelly.onBeforeCompile=sh=>{
  Object.assign(sh.uniforms,U);
  sh.vertexShader=DEF+sh.vertexShader.replace('#include <beginnormal_vertex>','vec3 dP0=dfP(position);\nvec3 objectNormal=dfN(position,normal,dP0);').replace('#include <begin_vertex>','vec3 transformed=dP0;');
  sh.fragmentShader='uniform float uGlow;\nuniform vec3 uGlowCol;\n'+sh.fragmentShader.replace('#include <emissivemap_fragment>','#include <emissivemap_fragment>\nfloat gNV=clamp(dot(normal,normalize(vViewPosition)),0.0,1.0);\ntotalEmissiveRadiance+=uGlowCol*uGlow*(0.1+pow(gNV,2.0));');
};
const softCol=new THREE.Color(0xffbb66),firmCol=new THREE.Color(0xff8424);
function applyFirm(){jelly.color.copy(softCol).lerp(firmCol,stiff);jelly.attenuationDistance=1.0-0.45*stiff;jelly.roughness=0.1-0.04*stiff;}

/* ---------- build the cat ---------- */
const cat=new THREE.Group();scene.add(cat);
function addAT(g,v){g.setAttribute('aT',new THREE.BufferAttribute(new Float32Array(g.attributes.position.count).fill(v),1));return g;}
const C0=new V3(0,0.95,0.05);
const bg=new THREE.SphereGeometry(1,144,108);
{const P=bg.attributes.position,Nn=bg.attributes.normal,d=new V3(),p=new V3(),n=new V3();
 for(let i=0;i<P.count;i++){d.fromBufferAttribute(P,i).normalize();proj(C0,d,p,n);P.setXYZ(i,p.x,p.y,p.z);Nn.setXYZ(i,n.x,n.y,n.z);}
 bg.computeBoundingSphere();addAT(bg,0);}
const body=new THREE.Mesh(bg,jelly);body.frustumCulled=false;cat.add(body);
function earGeo(s){const pts=[];for(let i=0;i<=18;i++){const t=i/18;pts.push(new THREE.Vector2(Math.max(0.0005,0.205*Math.pow(1-t,0.7)),-0.12+0.54*t));}
  const g=new THREE.LatheGeometry(pts,40);
  g.applyMatrix4(new THREE.Matrix4().compose(new V3(s*0.33,1.8,0.06),new THREE.Quaternion().setFromEuler(new THREE.Euler(-0.12,0,-s*0.42)),new V3(1,1,0.55)));
  g.computeBoundingSphere();return addAT(g,0);}
const earL=new THREE.Mesh(earGeo(-1),jelly),earR=new THREE.Mesh(earGeo(1),jelly);
earL.frustumCulled=earR.frustumCulled=false;cat.add(earL,earR);
const TS=110,TR=18,tg=new THREE.TubeGeometry(tailCurve,TS,0.115,TR,false);
{const P=tg.attributes.position,Nn=tg.attributes.normal,L=tailCurve.getLength();
 const rr=q=>{let r=0.115*(1-0.42*q);if(q>0.9){const k=(q-0.9)/0.1;r*=Math.sqrt(Math.max(0,1-k*k));}return Math.max(r,0.0005);};
 const c=new V3(),tn=new V3(),n=new V3();
 for(let i=0;i<=TS;i++){const q=i/TS;tailCurve.getPointAt(q,c);tailCurve.getTangentAt(q,tn);const r=rr(q),e=0.004;
  const dr=(rr(Math.min(1,q+e))-rr(Math.max(0,q-e)))/(2*e*L);
  for(let j=0;j<=TR;j++){const k=i*(TR+1)+j;n.fromBufferAttribute(Nn,k);P.setXYZ(k,c.x+n.x*r,c.y+n.y*r,c.z+n.z*r);n.addScaledVector(tn,-dr).normalize();Nn.setXYZ(k,n.x,n.y,n.z);}}
 tg.computeBoundingSphere();addAT(tg,1);}
const tail=new THREE.Mesh(tg,jelly);tail.frustumCulled=false;cat.add(tail);
const HIT=[body,earL,earR,tail];

/* face */
const HC=new V3(0,1.45,0.1),sph=new THREE.SphereGeometry(1,28,18),FACE=[];
function anchor(c,dir,inset){const p=new V3(),n=new V3();proj(c,dir.normalize(),p,n);p.addScaledVector(n,inset||0);return {p,n};}
function place(o,a){o.quaternion.setFromUnitVectors(new V3(0,0,1),a.n);o.position.copy(a.p);cat.add(o);FACE.push({o,r:a.p});return o;}
const mScl=new THREE.MeshPhysicalMaterial({color:0xfffaf2,roughness:0.15,clearcoat:1,clearcoatRoughness:0.05});
const mIris=new THREE.MeshPhysicalMaterial({color:0x3b2412,roughness:0.1,clearcoat:1});
const mPup=new THREE.MeshPhysicalMaterial({color:0x080503,roughness:0.08,clearcoat:1});
const mWhite=new THREE.MeshBasicMaterial({color:0xffffff});
const mDark=new THREE.MeshStandardMaterial({color:0x4a2210,roughness:0.4});
const arcGeo=new THREE.TubeGeometry(new THREE.QuadraticBezierCurve3(new V3(-0.09,-0.02,0.035),new V3(0,0.07,0.05),new V3(0.09,-0.02,0.035)),20,0.017,8);
const EYES=[-1,1].map(s=>{const g=new THREE.Group(),open=new THREE.Group(),irisG=new THREE.Group();g.add(open);open.add(irisG);
  const sc=new THREE.Mesh(sph,mScl);sc.scale.set(0.115,0.13,0.055);open.add(sc);
  const ir=new THREE.Mesh(sph,mIris);ir.scale.set(0.08,0.088,0.03);ir.position.z=0.036;irisG.add(ir);
  const pu=new THREE.Mesh(sph,mPup);pu.scale.set(0.046,0.054,0.02);pu.position.z=0.052;irisG.add(pu);
  const c1=new THREE.Mesh(sph,mWhite);c1.scale.setScalar(0.022);c1.position.set(0.03,0.045,0.068);open.add(c1);
  const c2=new THREE.Mesh(sph,mWhite);c2.scale.setScalar(0.011);c2.position.set(-0.03,-0.032,0.066);open.add(c2);
  const arc=new THREE.Mesh(arcGeo,mDark);arc.visible=false;g.add(arc);
  place(g,anchor(HC,new V3(s*0.25,0.07,0.9),-0.012));
  return {g,open,irisG,arc,qi:g.quaternion.clone().invert(),ox:0,oy:0};});
const nose=new THREE.Mesh(sph,new THREE.MeshPhysicalMaterial({color:0xff7f93,roughness:0.2,clearcoat:1}));
nose.scale.set(0.058,0.04,0.035);place(nose,anchor(HC,new V3(0,-0.07,0.9),0.008));
{const mouth=new THREE.Group(),mc=new THREE.CatmullRomCurve3([new V3(-0.1,0.012,-0.01),new V3(-0.05,-0.035,0.004),new V3(0,0.005,0.01)]);
 const ml=new THREE.Mesh(new THREE.TubeGeometry(mc,16,0.011,6),mDark),mr=ml.clone();mr.scale.x=-1;
 mouth.add(ml,mr,new THREE.Mesh(new THREE.TubeGeometry(new THREE.LineCurve3(new V3(0,0.05,0.004),new V3(0,0.005,0.01)),2,0.01,6),mDark));
 place(mouth,anchor(HC,new V3(0,-0.17,0.9),0.002));}
const mWh=new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0.75});
const WHISK=[-1,1].map(s=>{const g=new THREE.Group();[0.06,0,-0.06].forEach(dy=>g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.LineCurve3(new V3(0,0,0),new V3(s*0.44,dy*1.6,-0.06)),1,0.0055,5),mWh)));
  const a=anchor(HC,new V3(s*0.3,-0.16,0.9),0.005);g.position.copy(a.p);cat.add(g);FACE.push({o:g,r:a.p});return g;});
const mBl=new THREE.MeshBasicMaterial({color:0xff6f86,transparent:true,opacity:0.28,depthWrite:false});
[-1,1].forEach(s=>{const m=new THREE.Mesh(new THREE.CircleGeometry(0.085,24),mBl);m.scale.x=1.4;place(m,anchor(HC,new V3(s*0.56,-0.24,0.72),0.012));});
/* bubbles */
const bubM=new THREE.MeshStandardMaterial({color:0xfff3e0,roughness:0.05,metalness:0.1,emissive:0xffb060,emissiveIntensity:0.4});
const BUB=[];
for(let tries=0;BUB.length<16&&tries<5000;tries++){const x=(Math.random()*2-1)*0.7,y=0.12+Math.random()*1.75,z=(Math.random()*2-1)*0.6;
  if(catSDF(x,y,z)<-0.09&&!(y>1.15&&z>0.32)){const m=new THREE.Mesh(sph,bubM);m.scale.setScalar(0.012+Math.random()*Math.random()*0.035);cat.add(m);BUB.push({m,r:new V3(x,y,z),ph:Math.random()*6.28});}}

/* ---------- plate, table, light ---------- */
const prof=[[0,-0.06],[1.0,-0.06],[1.04,-0.1],[1.16,-0.1],[1.2,-0.07],[1.45,0.0],[1.62,0.085],[1.66,0.1],[1.64,0.112],[1.58,0.1],[1.42,0.04],[1.25,0.0],[0.001,0.0]].map(a=>new THREE.Vector2(a[0],a[1]));
const plate=new THREE.Mesh(new THREE.LatheGeometry(prof,96),new THREE.MeshPhysicalMaterial({color:0xfdfaf6,roughness:0.3,clearcoat:0.9,clearcoatRoughness:0.12,side:THREE.DoubleSide}));scene.add(plate);
const ring=new THREE.Mesh(new THREE.TorusGeometry(1.42,0.011,8,128),new THREE.MeshStandardMaterial({color:0x6f9fd8,roughness:0.3}));ring.rotation.x=Math.PI/2;ring.position.y=0.042;scene.add(ring);
const floor=new THREE.Mesh(new THREE.CircleGeometry(60,64),new THREE.MeshBasicMaterial({color:0xe9f1f3,toneMapped:false}));floor.rotation.x=-Math.PI/2;floor.position.y=-0.1;scene.add(floor);
{const g=new THREE.SphereGeometry(70,32,20),P=g.attributes.position,cols=[],c0=new THREE.Color(0xe9f1f3),c1=new THREE.Color(0xbcd8ec),c=new THREE.Color();
 for(let i=0;i<P.count;i++){c.copy(c0).lerp(c1,ease(P.getY(i)/70*1.6));cols.push(c.r,c.g,c.b);}
 g.setAttribute('color',new THREE.Float32BufferAttribute(cols,3));
 scene.add(new THREE.Mesh(g,new THREE.MeshBasicMaterial({vertexColors:true,side:THREE.BackSide,toneMapped:false,depthWrite:false})));}
function radTex(st){const c=document.createElement('canvas');c.width=c.height=128;const x=c.getContext('2d'),g=x.createRadialGradient(64,64,0,64,64,64);st.forEach(s=>g.addColorStop(s[0],s[1]));x.fillStyle=g;x.fillRect(0,0,128,128);const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;return t;}
function flat(tex,size,x,y,z,add){const m=new THREE.Mesh(new THREE.PlaneGeometry(size,size),new THREE.MeshBasicMaterial({map:tex,transparent:true,depthWrite:false,toneMapped:false,blending:add?THREE.AdditiveBlending:THREE.NormalBlending}));m.rotation.x=-Math.PI/2;m.position.set(x,y,z);scene.add(m);return m;}
flat(radTex([[0,'rgba(60,80,100,0.35)'],[0.6,'rgba(60,80,100,0.15)'],[1,'rgba(60,80,100,0)']]),4.6,0,-0.098,0);
const shadow=flat(radTex([[0,'rgba(170,70,0,0.5)'],[0.55,'rgba(200,90,10,0.22)'],[1,'rgba(200,90,10,0)']]),2.5,-0.08,0.003,-0.1);
const caustic=flat(radTex([[0,'rgba(255,190,80,0.85)'],[0.45,'rgba(255,140,30,0.3)'],[1,'rgba(255,120,20,0)']]),1.7,0.1,0.005,0.42,true);
scene.add(new THREE.HemisphereLight(0xffffff,0xf3d9c0,0.5));
const key=new THREE.DirectionalLight(0xfff4e6,2.3);key.position.set(2.5,5,3.5);scene.add(key);
const rimL=new THREE.DirectionalLight(0xffe2c4,1.4);rimL.position.set(-3,2.5,-4);scene.add(rimL);
const inner=new THREE.PointLight(0xff8a24,1.5,4,2);inner.position.set(0,0.35,0.15);cat.add(inner);

/* ---------- camera fit ---------- */
const camDir=new V3(0.2,0.3,1).normalize(),LOOK=new V3(0,1.0,0);
function fit(){const w=innerWidth,h=innerHeight;renderer.setSize(w,h,false);camera.aspect=w/h;
  const top=$('top').getBoundingClientRect().bottom+4,bot=h-$('panel').getBoundingClientRect().top+6;
  const usable=Math.max(0.35,(h-top-bot)/h),t=Math.tan(camera.fov*Math.PI/360);
  const d=Math.max(2.75/(2*t*usable),3.55/(2*t*camera.aspect));
  camera.position.copy(LOOK).addScaledVector(camDir,d);camera.lookAt(LOOK);
  camera.setViewOffset(w,h,0,(bot-top)/2,w,h);camera.updateMatrixWorld();}
addEventListener('resize',fit);fit();

/* ---------- sound (all synthesized) ---------- */
let AC=null,master=null,NZ=null,purrG=null,purrAM=null,muted=false;
function audio(){
  if(!AC){try{const A=window.AudioContext||window.webkitAudioContext;if(!A)return;AC=new A();master=AC.createGain();master.gain.value=muted?0:0.9;
    const comp=AC.createDynamicsCompressor();master.connect(comp);comp.connect(AC.destination);
    NZ=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=NZ.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1;
    const src=AC.createBufferSource();src.buffer=NZ;src.loop=true;const lp=AC.createBiquadFilter();lp.type='lowpass';lp.frequency.value=320;lp.Q.value=0.8;
    purrG=AC.createGain();purrG.gain.value=0;const am=AC.createOscillator();am.frequency.value=26;purrAM=AC.createGain();purrAM.gain.value=0;am.connect(purrAM);purrAM.connect(purrG.gain);
    const sw=AC.createOscillator();sw.type='sawtooth';sw.frequency.value=52;const swg=AC.createGain();swg.gain.value=0.25;const lp2=AC.createBiquadFilter();lp2.type='lowpass';lp2.frequency.value=160;
    src.connect(lp);lp.connect(purrG);sw.connect(swg);swg.connect(lp2);lp2.connect(purrG);purrG.connect(master);src.start();am.start();sw.start();
  }catch(e){AC=null;return;}}
  if(AC.state==='suspended')AC.resume().catch(()=>{});}
const ok=()=>AC&&AC.state==='running'&&!muted;
function env(g,t,a,pk,d){g.gain.setValueAtTime(0.0001,t);g.gain.exponentialRampToValueAtTime(Math.max(pk,0.0002),t+a);g.gain.exponentialRampToValueAtTime(0.0001,t+a+d);}
function tone(f0,f1,dur,vol,type,dl){if(!ok())return;const t=AC.currentTime+(dl||0),o=AC.createOscillator(),g=AC.createGain();o.type=type||'sine';o.frequency.setValueAtTime(f0,t);o.frequency.exponentialRampToValueAtTime(f1,t+dur);env(g,t,0.006,vol,dur);o.connect(g);g.connect(master);o.start(t);o.stop(t+dur+0.05);}
function noise(dur,f0,f1,q,vol,dl,type){if(!ok())return;const t=AC.currentTime+(dl||0),s=AC.createBufferSource(),f=AC.createBiquadFilter(),g=AC.createGain();s.buffer=NZ;f.type=type||'bandpass';f.Q.value=q;f.frequency.setValueAtTime(f0,t);f.frequency.exponentialRampToValueAtTime(f1,t+dur);env(g,t,0.008,vol,dur);s.connect(f);f.connect(g);g.connect(master);s.start(t,Math.random()*1.5);s.stop(t+dur+0.05);}
const pitch=()=>0.8+stiff*0.7;
function sPoke(a){const p=pitch()*(0.9+Math.random()*0.2);tone(520*p,150*p,0.14,0.34*a);tone(1100*p,380*p,0.05,0.07*a,'triangle');noise(0.07,2400,700,1.4,0.13*a);}
function sSquish(){const p=pitch();noise(0.45,320*p,1700*p,5,0.32);noise(0.3,1000*p,260*p,3,0.16,0.14);tone(140*p,80*p,0.38,0.2,'triangle');}
function sRelease(){const p=pitch();tone(260*p,520*p,0.12,0.22);noise(0.08,1600,3000,2,0.08);}
function sSnap(a){if(!ok())return;const t=AC.currentTime,p=pitch(),o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();
  o.frequency.setValueAtTime(180*p,t);o.frequency.exponentialRampToValueAtTime(420*p,t+0.06);o.frequency.exponentialRampToValueAtTime(260*p,t+0.45);
  l.frequency.value=10+6*stiff;lg.gain.value=60*p;l.connect(lg);lg.connect(o.frequency);env(g,t,0.015,0.32*a+0.05,0.48);
  o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+0.55);l.stop(t+0.55);noise(0.06,2600,900,1.5,0.14*a);}
function sSplat(a){noise(0.55,1500,140,0.8,0.55*a+0.05,0,'lowpass');tone(170,42,0.42,0.75*a+0.05);for(let i=0;i<4;i++)tone(500+Math.random()*700,180,0.09,0.12*a,'sine',0.05+i*0.07+Math.random()*0.03);}
function sTink(){tone(2600,2500,0.3,0.1);tone(5200,5100,0.15,0.035);}
function sWhee(){tone(1200,420,0.75,0.05);}
const sndBtn=$('snd'),SPK='<path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor"/>';
function sndIcon(){sndBtn.innerHTML='<svg viewBox="0 0 24 24" width="30" height="30">'+SPK+(muted?'<path d="M16 9l5 6M21 9l-5 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>':'<path d="M16 8.5a5 5 0 0 1 0 7M18.5 6a8.5 8.5 0 0 1 0 12" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/>')+'</svg>';}
sndIcon();
sndBtn.addEventListener('click',()=>{muted=!muted;audio();if(master)master.gain.value=muted?0:0.9;sndIcon();});

/* ---------- touch interaction ---------- */
const ndc=new THREE.Vector2(),ray=new THREE.Raycaster();
function setNDC(x,y){ndc.set(x/innerWidth*2-1,-(y/innerHeight)*2+1);ray.setFromCamera(ndc,camera);}
const T={on:false,mode:'gen',state:'',t:0,sq:0,sx:0,sy:0,lx:0,ly:0,n:new V3(),start:new V3(),last:new V3(),drag:new V3(),rubV:new V3(),local:new V3(),plane:new THREE.Plane(),gr:new Float32Array(NN),boost:1,tail:0};
function weights(p,tl){const a=T.gr;let ws=0;
  for(let i=0;i<NN;i++){const i3=i*3;let w=Math.exp(-((p.x-R[i3])**2+(p.y-R[i3+1])**2+(p.z-R[i3+2])**2)*IS[i]);if(TO[i]&&!tl)w=0;a[i]=w;ws+=w;}
  const s=1/Math.max(ws,1);let mx=0;for(let i=0;i<NN;i++){a[i]*=s;mx=Math.max(mx,a[i]);}
  let dot=0;for(let i=0;i<NN;i++){const ai=a[i],g=mx>0?ai/mx:0;a[i]=g>0.06?g:0;dot+=ai*a[i];}
  T.boost=clamp(1/Math.max(dot,0.05),1,1.8);}
const GRAB=[EARL,EARR,TIP,TIP-1];
function nearNode(x,y){let best=-1,bd=36*36;
  for(const i of GRAB){F(R[i*3],R[i*3+1],R[i*3+2],i>=TAIL0?1:0,tA).add(cat.position).project(camera);
    const d=((tA.x+1)/2*innerWidth-x)**2+((1-tA.y)/2*innerHeight-y)**2;if(d<bd){bd=d;best=i;}}
  return best;}
function plateTap(p){G.sxv-=(p.x-cat.position.x)*0.5;G.szv-=p.z*0.5;G.sqv+=0.4;for(let i=0;i<NN;i++)vel[i*3+1]+=0.3;sTink();}
function beginTouch(x,y){
  audio();setNDC(x,y);look.x=x;look.y=y;look.until=time+1.5;T.on=false;
  const n=new V3();let hitP=null,tl=0,mode='gen';
  const ni=nearNode(x,y);
  if(ni>=0){tl=ni>=TAIL0?1:0;T.local.set(R[ni*3],R[ni*3+1],R[ni*3+2]);hitP=F(T.local.x,T.local.y,T.local.z,tl,new V3()).add(cat.position);n.copy(camDir);}
  else{const hs=ray.intersectObjects(HIT,false);
    if(hs.length){const h=hs[0];hitP=h.point.clone();T.local.copy(h.point).sub(cat.position);n.copy(h.face.normal);tl=h.object===tail?1:0;
      const q=T.local;if(h.object===body&&q.y>1.62&&q.z<0.62&&Math.abs(q.x)<0.5)mode='rub';}
    else{const hp=ray.intersectObject(plate,false);if(hp.length)plateTap(hp[0].point);return;}}
  T.on=true;T.mode=mode;T.state='pending';T.t=0;T.sq=0;T.sx=T.lx=x;T.sy=T.ly=y;T.n.copy(n);T.start.copy(hitP);T.last.copy(hitP);T.drag.set(0,0,0);T.rubV.set(0,0,0);T.tail=tl;
  T.plane.setFromNormalAndCoplanarPoint(camDir,hitP);weights(T.local,tl);
  const P=mode==='rub'?0.8:(ni>=0?1.2:2.3-0.7*stiff);
  for(let i=0;i<NN;i++){const g=T.gr[i];if(g>0){vel[i*3]-=n.x*P*g;vel[i*3+1]-=n.y*P*g;vel[i*3+2]-=n.z*P*g;}}
  G.sxv-=n.x*0.5;G.szv-=n.z*0.5;G.sqv+=0.35;flash=Math.max(flash,0.3);if(mode!=='rub')pokeSq=0.22;
  sPoke(mode==='rub'?0.5:1);}
function moveTouch(x,y){
  setNDC(x,y);look.x=x;look.y=y;look.until=time+1.5;if(!T.on)return;
  const hit=ray.ray.intersectPlane(T.plane,tC);
  if(T.mode==='rub'){if(hit){T.rubV.addScaledVector(tV.copy(hit).sub(T.last),1.4).clampLength(0,0.15);T.last.copy(hit);}rub=Math.min(2,rub+Math.hypot(x-T.lx,y-T.ly)*0.0045);}
  else{if(T.state!=='pull'&&Math.hypot(x-T.sx,y-T.sy)>9)T.state='pull';if(T.state==='pull'&&hit)T.drag.copy(hit).sub(T.start);}
  T.lx=x;T.ly=y;}
function endTouch(){if(!T.on)return;
  if(T.state==='pull'){const L=T.drag.length();if(L>0.08){sSnap(Math.min(1,L/0.7));flash=Math.max(flash,0.25);}}
  else if(T.state==='squeeze')sRelease();
  T.on=false;}
const cv=$('c');let pid=null;
cv.addEventListener('pointerdown',e=>{if(e.pointerType==='mouse'&&e.button!==0)return;e.preventDefault();if(pid!==null)return;pid=e.pointerId;try{cv.setPointerCapture(pid);}catch(_){}beginTouch(e.clientX,e.clientY);});
cv.addEventListener('pointermove',e=>{if(e.pointerId===pid)moveTouch(e.clientX,e.clientY);else if(e.pointerType==='mouse'&&pid===null&&!demo.on){look.x=e.clientX;look.y=e.clientY;look.until=time+2;}});
const up=e=>{if(e.pointerId===pid){pid=null;endTouch();}};
cv.addEventListener('pointerup',up);cv.addEventListener('pointercancel',up);
cv.addEventListener('contextmenu',e=>e.preventDefault());

/* ---------- firmness, drop ---------- */
const sl=$('firm'),dropBtn=$('drop');
function setStiff(v){stiff=clamp(v,0,1);sl.value=Math.round(stiff*100);applyFirm();}
sl.addEventListener('input',()=>{stiff=sl.value/100;applyFirm();});
applyFirm();
const D={on:false,y:0,vy:0};
function drop(){if(D.on)return;audio();if(T.on)endTouch();D.on=true;D.y=7.5;D.vy=0;G.sq=0;G.sqv=0;sWhee();}
dropBtn.addEventListener('click',drop);
function land(a){G.sqv+=4.2*a+0.3;G.sxv+=(Math.random()-0.5)*2.4*a;G.szv+=(Math.random()-0.5)*2.4*a;
  for(let i=0;i<NN;i++){vel[i*3]+=(Math.random()-0.5)*1.4*a;vel[i*3+1]-=R[i*3+1]*1.3*a;vel[i*3+2]+=(Math.random()-0.5)*1.4*a;}
  vel[EARL*3+1]-=1.5*a;vel[EARR*3+1]-=1.5*a;vel[TIP*3+1]+=2*a;flash=Math.max(flash,0.6*a);pokeSq=0.35;sSplat(a);}
function dropStep(dt){if(!D.on)return;D.vy-=18*dt;D.y+=D.vy*dt;
  if(D.y<=0){D.y=0;if(-D.vy>1.2){land(Math.min(1,-D.vy/16));D.vy=-D.vy*0.16;}else{D.on=false;D.vy=0;}}
  cat.position.y=D.y;}

/* ---------- per-frame behaviour ---------- */
function setOff(i,x,y,z){off[i*3]=x;off[i*3+1]=y;off[i*3+2]=z;}
function idle(dt){
  G.sqT=(1-stiff)*0.035+Math.sin(time*2.3)*0.007*(1-0.5*stiff);
  const falling=D.on&&D.y>0.02;if(falling)G.sqT=-0.1;
  const tw=T.on&&T.tail?0.2:1,a=Math.sin(time*1.3),b=Math.sin(time*0.9+1);
  setOff(TIP,0.07*a*tw,0.02+0.015*b,0.05*b*tw);setOff(TIP-1,0.035*a*tw,0.01,0.02*b*tw);
  const fl=falling?0.08:0;setOff(EARL,0,fl,0);setOff(EARR,0,fl,0);
  earT-=dt;if(earT<0){earT=2+Math.random()*5;const e=Math.random()<0.5?EARL:EARR;vel[e*3]+=(e===EARL?-1:1)*0.6;vel[e*3+1]+=0.4;}
  rub=Math.max(0,rub-dt*(T.on&&T.mode==='rub'?0.2:0.5));purr+=(ease((rub-0.4)/0.7)-purr)*Math.min(1,dt*3);
  flash=Math.max(0,flash-dt*1.5);pokeSq=Math.max(0,pokeSq-dt);}
function interact(dt){
  gk.fill(0);G.sxT=0;G.szT=0;if(!T.on)return;T.t+=dt;
  if(T.mode!=='rub'&&T.state==='pending'&&T.t>0.3){T.state='squeeze';sSquish();}
  if(T.state==='squeeze')T.sq=Math.min(1,T.sq+dt*2.4);
  let tv=null;
  if(T.mode==='rub'){T.rubV.multiplyScalar(Math.pow(0.02,dt));tv=tV.copy(T.rubV).clampLength(0,0.1);tv.y-=0.05;G.sxT=tv.x*0.4;G.szT=tv.z*0.4;}
  else if(T.state==='pull'){const L=T.drag.length(),mx=0.95-0.5*stiff;tv=tV.copy(T.drag);if(L>1e-5)tv.multiplyScalar(mx*Math.tanh(L/mx)/L);G.sxT=tv.x*0.12;G.szT=tv.z*0.12;}
  else if(T.state==='squeeze'){tv=tV.copy(T.n).multiplyScalar(-(0.3-0.14*stiff)*T.sq);G.sqT+=0.16*T.sq;}
  if(tv)for(let i=0;i<NN;i++){const g=T.gr[i];if(g>0){gk[i]=g;tgt[i*3]=tv.x*g*T.boost;tgt[i*3+1]=tv.y*g*T.boost;tgt[i*3+2]=tv.z*g*T.boost;}}}
function physics(dt){
  const K=28+202*stiff,B=1.6+5.4*stiff,C=K*0.5,KG=700,n=Math.min(12,Math.ceil(dt/0.0042)),h=dt/n;
  for(let it=0;it<n;it++){
    for(let i=0;i<NN;i++){const i3=i*3,nb=NB[i],l=nb.l;let cx=0,cy=0,cz=0;
      for(let k=0;k<l.length;k+=2){const j3=l[k]*3,a=l[k+1];cx+=a*(u[j3]-u[i3]);cy+=a*(u[j3+1]-u[i3+1]);cz+=a*(u[j3+2]-u[i3+2]);}
      const g=gk[i]*KG,bd=B+gk[i]*9,ci=C*nb.inv;
      vel[i3]+=(-K*(u[i3]-off[i3])+ci*cx+g*(tgt[i3]-u[i3])-bd*vel[i3])*h;
      vel[i3+1]+=(-K*(u[i3+1]-off[i3+1])+ci*cy+g*(tgt[i3+1]-u[i3+1])-bd*vel[i3+1])*h;
      vel[i3+2]+=(-K*(u[i3+2]-off[i3+2])+ci*cz+g*(tgt[i3+2]-u[i3+2])-bd*vel[i3+2])*h;}
    for(let q=0;q<NN*3;q++)u[q]+=vel[q]*h;
    G.sqv+=(-K*1.3*(G.sq-G.sqT)-B*0.9*G.sqv)*h;G.sq+=G.sqv*h;
    G.sxv+=(-K*0.9*(G.sx-G.sxT)-B*0.9*G.sxv)*h;G.sx+=G.sxv*h;
    G.szv+=(-K*0.9*(G.sz-G.szT)-B*0.9*G.szv)*h;G.sz+=G.szv*h;}
  if(G.sq>0.55){G.sq=0.55;if(G.sqv>0)G.sqv*=-0.3;}if(G.sq<-0.3){G.sq=-0.3;if(G.sqv<0)G.sqv*=-0.3;}
  G.sx=clamp(G.sx,-0.2,0.2);G.sz=clamp(G.sz,-0.2,0.2);
  for(let i=0;i<NN;i++){const i3=i*3,l=Math.hypot(u[i3],u[i3+1],u[i3+2]);if(l>1.2){const s=1.2/l;u[i3]*=s;u[i3+1]*=s;u[i3+2]*=s;}}}
const lookPlane=new THREE.Plane(),lookT=new V3();
function updateFace(dt){
  for(const f of FACE)F(f.r.x,f.r.y,f.r.z,0,f.o.position);
  for(const b of BUB)F(b.r.x,b.r.y+Math.sin(time*0.8+b.ph)*0.012,b.r.z,0,b.m.position);
  lookPlane.setFromNormalAndCoplanarPoint(camDir,tA.copy(HC).add(cat.position).addScaledVector(camDir,1.3));
  let follow=T.on||time<look.until;
  if(follow){setNDC(look.x,look.y);if(!ray.ray.intersectPlane(lookPlane,lookT))follow=false;}
  if(!follow){lookT.copy(camera.position);lookT.x+=Math.sin(time*0.5)*1.5;lookT.y+=Math.sin(time*0.37)*0.6;}
  blinkT-=dt;if(blinkT<0){blinkA=0.14;blinkT=2.5+Math.random()*4;}
  let target=1;if(blinkA>0){blinkA-=dt;target=0.05;}
  if(pokeSq>0||rub>0.45)target=0;if(D.on&&D.y>0.05)target=1.18;
  eo+=(target-eo)*Math.min(1,dt*18);
  const k=Math.min(1,dt*14);
  for(const e of EYES){tB.copy(e.g.position).add(cat.position);tC.copy(lookT).sub(tB).normalize().applyQuaternion(e.qi);
    let ox=tC.x*0.07,oy=tC.y*0.07;const l=Math.hypot(ox,oy);if(l>0.042){ox*=0.042/l;oy*=0.042/l;}
    e.ox+=(ox-e.ox)*k;e.oy+=(oy-e.oy)*k;e.irisG.position.set(e.ox,e.oy,0);
    e.open.scale.y=Math.max(0.05,eo);e.open.visible=eo>0.12;e.arc.visible=eo<0.3;}
  WHISK.forEach((w,i)=>{w.rotation.z=(i?-1:1)*(Math.sin(time*31)*0.05*purr+Math.sin(time*1.7+i)*0.02);});
  mBl.opacity=0.26+purr*0.3;
  U.uGlow.value=0.42+flash*0.6+purr*0.14*(0.5+0.5*Math.sin(time*26));
  inner.intensity=1.4+flash*2.5+purr*0.6;
  const hs=1/(1+D.y*0.45);shadow.scale.setScalar(hs*(1+G.sq*0.5));shadow.material.opacity=hs;
  caustic.scale.setScalar(hs*(1+G.sq*0.4));caustic.material.opacity=hs*(0.75+flash*0.5);}
function audioStep(){if(!AC||!purrG)return;const t=AC.currentTime,lv=purr*(0.6+0.4*Math.sin(time*3.1))*0.45;purrG.gain.setTargetAtTime(lv,t,0.06);purrAM.gain.setTargetAtTime(lv,t,0.06);}

/* ---------- #demo: hands-free 20 s loop ---------- */
const fin=$('finger'),DEMO_LEN=20,CEN=new V3(0,1.1,0.3);
const ANCH={belly:anchor(new V3(0,0.6,0),new V3(0,0.12,1)).p,cheek:anchor(HC,new V3(-0.62,-0.28,0.7)).p,ear:new V3(0.49,2.1,0.03),tail:tailCurve.getPointAt(0.93),head:anchor(HC,new V3(0,1,0.35)).p};
const SEG=[{a:2,b:2.22,k:'tap',an:'belly'},{a:2.7,b:2.9,k:'tap',an:'cheek'},{a:3.3,b:5,k:'drag',an:'ear',dx:80,dy:-75},{a:5.6,b:7.4,k:'hold',an:'belly'},
 {a:7.9,b:9.6,k:'drag',an:'tail',dx:110,dy:35},{a:10.1,b:13.3,k:'rub',an:'head'},{a:13.8,b:14.3,k:'sl',v:0.95},{a:14.6,b:14.8,k:'tap',an:'belly'},
 {a:15.2,b:15.6,k:'sl',v:0.1},{a:15.9,b:16.15,k:'btn'},{a:17.6,b:19.2,k:'drag',an:'cheek',dx:-95,dy:10},{a:19.4,b:19.75,k:'sl',v:0.35}];
const demo={on:location.hash==='#demo',t:0,down:false,loop:0,dropped:false,sc:1};
function scr(v){tB.copy(v).add(cat.position).project(camera);return [(tB.x+1)/2*innerWidth,(1-tB.y)/2*innerHeight];}
function slVal(s,t){const f=(s.loop===demo.loop&&s.from!==undefined)?s.from:stiff;return lerp(f,s.v,ease((t-s.a)/(s.b-s.a)));}
function segPos(s,t){
  if(s.k==='btn'){const r=dropBtn.getBoundingClientRect();return [r.left+r.width/2,r.top+r.height/2];}
  if(s.k==='sl'){const r=sl.getBoundingClientRect();return [r.left+18+(r.width-36)*slVal(s,t),r.top+r.height/2];}
  const p=scr(ANCH[s.an]);
  if(s.k==='drag'){const e=ease((t-s.a)/((s.b-s.a)*0.55));return [p[0]+s.dx*e*demo.sc,p[1]+s.dy*e*demo.sc];}
  if(s.k==='rub'){const q=t-s.a;return [p[0]+Math.sin(q*12)*30*demo.sc,p[1]+Math.cos(q*24)*4];}
  return p;}
function demoFinger(t){
  for(const s of SEG)if(t>=s.a&&t<s.b)return {down:true,k:s.k,s,p:segPos(s,t)};
  let prev=null,next=null;for(const s of SEG){if(s.b<=t)prev=s;else if(!next&&s.a>t)next=s;}
  const c=scr(CEN),hov=[c[0]+Math.sin(t*2.513)*120*demo.sc,c[1]-Math.cos(t*1.885)*80*demo.sc];
  if(!prev)return {down:false,p:lerp2(hov,segPos(next,next.a),ease((t-(next.a-0.5))/0.5))};
  const pA=segPos(prev,prev.b);
  if(!next)return {down:false,p:lerp2(pA,hov,ease((t-prev.b)/0.5))};
  return {down:false,p:lerp2(pA,segPos(next,next.a),ease((t-prev.b)/(next.a-prev.b)))};}
function demoStep(dt){
  demo.t+=dt;if(demo.t>=DEMO_LEN){demo.t-=DEMO_LEN;demo.loop++;demo.dropped=false;}
  const t=demo.t,c0=scr(new V3(0,0,0)),c1=scr(new V3(0,2.2,0));demo.sc=clamp(Math.abs(c0[1]-c1[1])/420,0.45,1.6);
  const st=demoFinger(t);
  if(st.k==='sl'){const s=st.s;if(s.loop!==demo.loop){s.loop=demo.loop;s.from=stiff;}setStiff(slVal(s,t));}
  if(st.k==='btn'&&!demo.dropped&&t>st.s.a+0.15){demo.dropped=true;drop();}
  const cd=st.down&&(st.k==='tap'||st.k==='hold'||st.k==='drag'||st.k==='rub');
  if(cd&&!demo.down){beginTouch(st.p[0],st.p[1]);demo.down=true;}
  else if(cd&&demo.down)moveTouch(st.p[0],st.p[1]);
  else if(!cd&&demo.down){endTouch();demo.down=false;}
  if(!st.down){look.x=st.p[0];look.y=st.p[1];look.until=time+0.4;}
  fin.style.left=st.p[0]+'px';fin.style.top=st.p[1]+'px';fin.classList.toggle('down',!!st.down);dropBtn.classList.toggle('pressed',st.k==='btn');}
function stopDemo(){if(!demo.on)return;demo.on=false;fin.style.display='none';dropBtn.classList.remove('pressed');if(demo.down){endTouch();demo.down=false;}}
addEventListener('pointerdown',e=>{if(demo.on&&e.isTrusted)stopDemo();},true);
if(demo.on)fin.style.display='block';

/* ---------- loop ---------- */
msg.remove();
let last=performance.now();
function frame(now){
  requestAnimationFrame(frame);
  const dt=Math.min(0.05,Math.max(0.0005,(now-last)/1000));last=now;time+=dt;
  if(demo.on)demoStep(dt);
  idle(dt);interact(dt);dropStep(dt);physics(dt);
  U.uGlob.value.set(G.sq,G.sx,G.sz,0);
  updateFace(dt);audioStep();
  renderer.render(scene,camera);}
requestAnimationFrame(frame);
</script>
</body>
</html>