Back to the app
The code
Jelly Orange Slice by Claude Sonnet 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.)<!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 Orange Slice</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#17303b;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;-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;outline:none}
.vig{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at 50% 42%,transparent 52%,rgba(0,0,0,.5))}
#hint{position:fixed;top:10px;left:0;right:0;text-align:center;color:#e6f2f5;font-size:15px;line-height:1.3;padding:0 16px;pointer-events:none;text-shadow:0 1px 4px rgba(0,0,0,.6);opacity:.9}
#cap{position:fixed;top:44px;left:0;right:0;text-align:center;pointer-events:none;color:#fff;font-weight:700;font-size:20px;padding:0 16px;text-shadow:0 2px 8px rgba(0,0,0,.8);opacity:0;transition:opacity .35s}
#ui{position:fixed;left:0;right:0;bottom:0;padding:26px 14px calc(14px + env(safe-area-inset-bottom));display:flex;flex-wrap:wrap;gap:10px 14px;justify-content:center;align-items:center;background:linear-gradient(rgba(8,18,24,0),rgba(8,18,24,.82) 42%)}
.fw{display:flex;flex-direction:column;align-items:center;color:#f1f7f9;font-weight:600;font-size:15px}
.fw span{display:flex;justify-content:space-between;width:100%;font-size:13px;opacity:.8;padding:0 6px;box-sizing:border-box}
button{min-height:56px;min-width:128px;padding:0 22px;border:0;border-radius:28px;font:700 19px system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;cursor:pointer;touch-action:manipulation;box-shadow:0 4px 14px rgba(0,0,0,.4)}
button:active{transform:scale(.96)}
#sq{background:linear-gradient(#ffc247,#ff7a00);color:#2b1200}
#rs{background:#e9f1f4;color:#17303b}
input[type=range]{-webkit-appearance:none;appearance:none;width:min(300px,76vw);height:40px;background:transparent;margin:0;touch-action:none}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:5px;background:linear-gradient(90deg,#ffe0a0,#ff7a00)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:34px;height:34px;border-radius:50%;background:#fff;border:3px solid #ff7a00;margin-top:-12px;box-shadow:0 2px 6px rgba(0,0,0,.5)}
input[type=range]::-moz-range-track{height:10px;border-radius:5px;background:linear-gradient(90deg,#ffe0a0,#ff7a00)}
input[type=range]::-moz-range-thumb{width:28px;height:28px;border-radius:50%;background:#fff;border:3px solid #ff7a00}
#err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;color:#fff;text-align:center;padding:24px;font-size:18px}
@media (max-height:520px){button{min-height:48px;font-size:17px}#ui{padding-top:14px}#hint{display:none}}
</style>
</head>
<body>
<canvas id="c" aria-label="Wobbly jelly orange slice on a plate"></canvas>
<div class="vig"></div>
<div id="hint">Poke it, or drag it to stretch · drag the table to look around</div>
<div id="cap"></div>
<div id="ui">
<button id="sq" type="button">Squeeze</button>
<div class="fw"><span><i style="font-style:normal">Soft</i><b>Firmness</b><i style="font-style:normal">Firm</i></span>
<input id="fm" type="range" min="0" max="100" value="50" aria-label="Firmness"></div>
<button id="rs" type="button">Reset</button>
</div>
<div id="err">Could not start 3D. Please allow WebGL and the three.js library from cdn.jsdelivr.net.</div>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"}}</script>
<script type="module" onerror="document.getElementById('err').style.display='flex'">
import * as THREE from 'three';
import {RoomEnvironment} from 'three/addons/environments/RoomEnvironment.js';
import {mergeGeometries} from 'three/addons/utils/BufferGeometryUtils.js';
const $=id=>document.getElementById(id), TAU=Math.PI*2;
const rng=s=>()=>{s|=0;s=s+0x6D2B79F5|0;let t=Math.imul(s^s>>>15,1|s);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296};
const rnd=rng(11);
const sstep=(a,b,x)=>{x=Math.min(1,Math.max(0,(x-a)/(b-a)));return x*x*(3-2*x)};
/* ---------- renderer / scene ---------- */
const canvas=$('c');
let renderer;
try{renderer=new THREE.WebGLRenderer({canvas,antialias:true,powerPreference:'high-performance'})}catch(e){$('err').style.display='flex';throw e}
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
const scene=new THREE.Scene();
const BG=0x17303b;scene.background=new THREE.Color(BG);scene.fog=new THREE.Fog(BG,14,40);
scene.environment=new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(),0.04).texture;
const camera=new THREE.PerspectiveCamera(38,1,.1,100);
const key=new THREE.DirectionalLight(0xfff0dc,2.4);key.position.set(3.5,7,4);key.castShadow=true;
key.shadow.mapSize.set(1024,1024);Object.assign(key.shadow.camera,{left:-4,right:4,top:4,bottom:-4,near:1,far:20});
key.shadow.bias=-.0006;key.shadow.normalBias=.02;key.shadow.radius=3;scene.add(key);
const back=new THREE.PointLight(0xffa04a,50,0,2);back.position.set(-3.2,1.5,-3);scene.add(back);
scene.add(new THREE.HemisphereLight(0xcfe8ff,0x2a3a40,.55));
const ground=new THREE.Mesh(new THREE.CircleGeometry(60,48),new THREE.MeshStandardMaterial({color:0x2a4856,roughness:.95}));
ground.rotation.x=-Math.PI/2;ground.position.y=-.14;ground.receiveShadow=true;scene.add(ground);
/* plate */
const platePts=[[0,0],[2.2,0],[2.6,.04],[2.95,.15],[3.07,.21],[3.14,.19],[3.14,.14],[2.9,.07],[2.5,-.05],[2.0,-.09],[1.4,-.09],[1.3,-.14],[0,-.14]].map(p=>new THREE.Vector2(p[0],p[1]));
const plate=new THREE.Mesh(new THREE.LatheGeometry(platePts,96),new THREE.MeshPhysicalMaterial({color:0xfbfbfb,roughness:.18,clearcoat:1,clearcoatRoughness:.08,side:THREE.DoubleSide}));
plate.castShadow=plate.receiveShadow=true;scene.add(plate);
/* ---------- textures ---------- */
function cellTex(){const c=document.createElement('canvas');c.width=c.height=256;const g=c.getContext('2d');g.fillStyle='#707070';g.fillRect(0,0,256,256);
for(let i=0;i<190;i++){const x=rnd()*256,y=rnd()*256,r=5+rnd()*6;for(const[ox,oy]of[[0,0],[256,0],[-256,0],[0,256],[0,-256]]){const gr=g.createRadialGradient(x+ox,y+oy,0,x+ox,y+oy,r);gr.addColorStop(0,'#ffffff');gr.addColorStop(1,'rgba(112,112,112,0)');g.fillStyle=gr;g.beginPath();g.arc(x+ox,y+oy,r,0,TAU);g.fill()}}
const t=new THREE.CanvasTexture(c);t.wrapS=t.wrapT=THREE.RepeatWrapping;return t}
const bump=cellTex();
const glowTex=(()=>{const c=document.createElement('canvas');c.width=c.height=128;const g=c.getContext('2d'),gr=g.createRadialGradient(64,64,0,64,64,64);gr.addColorStop(0,'rgba(255,150,30,.85)');gr.addColorStop(.6,'rgba(255,130,20,.35)');gr.addColorStop(1,'rgba(255,120,10,0)');g.fillStyle=gr;g.fillRect(0,0,128,128);return new THREE.CanvasTexture(c)})();
/* ---------- soft body lattice (polar grid, 3 layers) ---------- */
const NSEG=10,R=1.75,RP=1.62,RIN=1.5,PH=.3,NR=6,NA=30,NL=3,DR=.36,LY=[-.3,0,.3],JY=.305,FLOOR=.005,PRAD=1.3;
const NP=NL+(NR-1)*NA*NL;
const rest=new Float32Array(NP*3),pos=new Float32Array(NP*3),vel=new Float32Array(NP*3),pred=new Float32Array(NP*3),goal=new Float32Array(NP*3),disp=new Float32Array(NP*3);
const idx=(ir,ia,il)=>ir===0?il:NL+((ir-1)*NA+(((ia%NA)+NA)%NA))*NL+il;
for(let il=0;il<NL;il++){const k=idx(0,0,il)*3;rest[k+1]=JY+LY[il]}
for(let ir=1;ir<NR;ir++)for(let ia=0;ia<NA;ia++)for(let il=0;il<NL;il++){const k=idx(ir,ia,il)*3,a=ia*TAU/NA;rest[k]=ir*DR*Math.cos(a);rest[k+1]=JY+LY[il];rest[k+2]=ir*DR*Math.sin(a)}
pos.set(rest);
const CA=[],CB=[],CL=[],seen=new Set();
function addC(a,b){if(a===b)return;const k=a<b?a*1024+b:b*1024+a;if(seen.has(k))return;seen.add(k);CA.push(a);CB.push(b);CL.push(Math.hypot(rest[a*3]-rest[b*3],rest[a*3+1]-rest[b*3+1],rest[a*3+2]-rest[b*3+2]))}
for(let ir=0;ir<NR;ir++)for(let ia=0;ia<(ir?NA:1);ia++)for(let il=0;il<NL;il++){const a=idx(ir,ia,il);
for(let dr=0;dr<=1;dr++){if(ir+dr>=NR)continue;
for(let da=-1;da<=1;da++)for(let dl=-1;dl<=1;dl++){const l2=il+dl;if(l2<0||l2>=NL||(!dr&&!da&&!dl))continue;
if(ir===0){if(da)continue;if(dr===0)addC(a,idx(0,0,l2));else for(let j=0;j<NA;j++)addC(a,idx(1,j,l2))}
else addC(a,idx(ir+dr,ia+da,l2))}}}
const NC=CA.length,cA=Int32Array.from(CA),cB=Int32Array.from(CB),cL=Float32Array.from(CL);
const S={f:.5,kE:.07,g:.07,cd:8.5};
function setFirm(f){S.f=f;S.kE=.02+.2*f*f;S.g=.018+.1*f;S.cd=5+7*f}
setFirm(.5);
const press={t:-1,y:2.2,drops:0,next:0,on:false},PRESS_Y=.34;
let grab=null,hold=null;
function computeGoals(){
const c=press.on?Math.min(1,Math.max(.35,(press.y-FLOOR)/(JY+.3-FLOOR))):1,s=Math.pow(c,-.32);
for(let i=0;i<NP;i++){const k=i*3,x0=rest[k],y0=rest[k+1],z0=rest[k+2],r0=Math.hypot(x0,z0);
const ce=c+(1-c)*sstep(1.1,1.8,r0)*.55,se=1+(s-1)*(.35+.65*sstep(.3,1.5,r0));
goal[k]=x0*se;goal[k+1]=FLOOR+(y0-FLOOR)*ce;goal[k+2]=z0*se}}
function collide(){
for(let i=0;i<NP;i++){const k=i*3;let x=pred[k],y=pred[k+1],z=pred[k+2];const r2=x*x+z*z,r=Math.sqrt(r2);
if(r2>8.1){const s=2.85/r;x*=s;z*=s}
const fy=FLOOR+(r>2.3?(r-2.3)*.3:0);if(y<fy)y=fy;
if(press.on&&r<PRAD&&y>press.y)y=press.y;
pred[k]=x;pred[k+1]=y;pred[k+2]=z}}
const SUB=1/120,ITER=4;
function step(dt){
const dm=1-S.cd*dt,g=S.g,kE=S.kE;
for(let i=0;i<NP;i++){const k=i*3;
const vx=vel[k]*dm,vy=(vel[k+1]-9.8*dt)*dm,vz=vel[k+2]*dm;
let x=pos[k]+vx*dt,y=pos[k+1]+vy*dt,z=pos[k+2]+vz*dt;
x+=(goal[k]-x)*g;y+=(goal[k+1]-y)*g;z+=(goal[k+2]-z)*g;
pred[k]=x;pred[k+1]=y;pred[k+2]=z}
if(hold){const a=150*dt*dt;for(let j=0;j<hold.I.length;j++){const k=hold.I[j]*3,w=hold.W[j]*a;pred[k]+=hold.d.x*w;pred[k+1]+=hold.d.y*w;pred[k+2]+=hold.d.z*w}}
for(let it=0;it<ITER;it++){
for(let c=0;c<NC;c++){const a=cA[c]*3,b=cB[c]*3,dx=pred[a]-pred[b],dy=pred[a+1]-pred[b+1],dz=pred[a+2]-pred[b+2];
const d=Math.sqrt(dx*dx+dy*dy+dz*dz)||1e-6,f=(d-cL[c])/d*.5*kE;
pred[a]-=dx*f;pred[a+1]-=dy*f;pred[a+2]-=dz*f;pred[b]+=dx*f;pred[b+1]+=dy*f;pred[b+2]+=dz*f}
if(grab){const o=grab.off;for(let j=0;j<grab.I.length;j++){const k=grab.I[j]*3,P=grab.P[j],w=grab.W[j]*.28;
pred[k]+=(P[0]+o.x-pred[k])*w;pred[k+1]+=(P[1]+o.y-pred[k+1])*w;pred[k+2]+=(P[2]+o.z-pred[k+2])*w}}
collide()}
for(let i=0;i<NP;i++){const k=i*3;let vx=(pred[k]-pos[k])/dt,vy=(pred[k+1]-pos[k+1])/dt,vz=(pred[k+2]-pos[k+2])/dt;
const m=Math.hypot(vx,vy,vz);if(m>9){const s=9/m;vx*=s;vy*=s;vz*=s}
if(pred[k+1]<FLOOR+.004){vx*=.75;vz*=.75}
vel[k]=vx;vel[k+1]=vy;vel[k+2]=vz;pos[k]=pred[k];pos[k+1]=pred[k+1];pos[k+2]=pred[k+2]}}
/* ---------- skinned render meshes ---------- */
function embed(x,yl,z,I,W,o){
const r=Math.hypot(x,z);let fr=r/DR,ir=Math.min(Math.floor(fr),NR-2);fr=Math.min(1,fr-ir);
let th=Math.atan2(z,x);if(th<0)th+=TAU;let fa=th/(TAU/NA),ia=Math.floor(fa);fa-=ia;ia%=NA;
const yy=Math.max(-.3,Math.min(.3,yl));let fy=(yy+.3)/.3,il=Math.min(Math.floor(fy),NL-2);fy-=il;
let k=o;for(let dr=0;dr<2;dr++)for(let da=0;da<2;da++)for(let dl=0;dl<2;dl++){I[k]=idx(ir+dr,ia+da,il+dl);W[k]=(dr?fr:1-fr)*(da?fa:1-fa)*(dl?fy:1-fy);k++}}
function mkSkin(geo,pairs){
geo.translate(0,JY,0);const a=geo.attributes.position.array,n=a.length/3,I=new Uint16Array(n*8),W=new Float32Array(n*8);
for(let i=0;i<n;i++)embed(a[i*3],a[i*3+1]-JY,a[i*3+2],I,W,i*8);
geo.boundingSphere=new THREE.Sphere(new THREE.Vector3(0,.5,0),5);
return{geo,rest:a.slice(),I,W,pairs:pairs||[]}}
function skinUpdate(s){
const g=s.geo,a=g.attributes.position.array,rp=s.rest,I=s.I,W=s.W,n=a.length/3;
for(let i=0;i<n;i++){let dx=0,dy=0,dz=0;const o=i*8;
for(let k=0;k<8;k++){const w=W[o+k];if(w){const q=I[o+k]*3;dx+=w*disp[q];dy+=w*disp[q+1];dz+=w*disp[q+2]}}
const p=i*3;a[p]=rp[p]+dx;a[p+1]=rp[p+1]+dy;a[p+2]=rp[p+2]+dz}
g.attributes.position.needsUpdate=true;g.computeVertexNormals();
const nm=g.attributes.normal.array,P=s.pairs;
for(let i=0;i<P.length;i+=2){const p=P[i]*3,q=P[i+1]*3,x=nm[p]+nm[q],y=nm[p+1]+nm[q+1],z=nm[p+2]+nm[q+2],l=Math.hypot(x,y,z)||1;
nm[p]=nm[q]=x/l;nm[p+1]=nm[q+1]=y/l;nm[p+2]=nm[q+2]=z/l}
g.attributes.normal.needsUpdate=true}
/* juicy segments: pillow-shaped, thin and glowing at the edges */
const DTH=TAU/NSEG,RHO0=.27,RHO1=RIN-.012,MG=.032;
const qf=t=>Math.sqrt(Math.max(0,1-Math.pow(Math.abs(2*t-1),6)));
const pe=(u,v)=>qf(u)*qf(v)*(1-.1*(2*u-1)*(2*u-1));
function buildPillows(){
const pos=[],uv=[],gl=[],ix=[],pairs=[],GU=14,GV=14,B=(GU+1)*(GV+1);
for(let k=0;k<NSEG;k++)for(const s of[1,-1]){const base=pos.length/3;
for(let j=0;j<=GV;j++){const v=j/GV,rho=RHO0+(RHO1-RHO0)*v,hw=DTH/2-Math.asin(MG/rho);
for(let i=0;i<=GU;i++){const u=i/GU,a=(k+.5)*DTH+(2*u-1)*hw,e=pe(u,v),x=rho*Math.cos(a),z=rho*Math.sin(a);
pos.push(x,s*PH*e,z);uv.push(x*.9,z*.9);gl.push(.3+.7*Math.pow(1-e,1.3));
if(s<0&&(i===0||i===GU||j===0||j===GV))pairs.push(base-B+j*(GU+1)+i,base+j*(GU+1)+i)}}
for(let j=0;j<GV;j++)for(let i=0;i<GU;i++){const a=base+j*(GU+1)+i,b=a+1,c=a+GU+1,d=c+1;
if(s>0)ix.push(a,b,c,b,d,c);else ix.push(a,c,b,b,c,d)}}
const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));
g.setAttribute('uv',new THREE.Float32BufferAttribute(uv,2));g.setAttribute('glow',new THREE.Float32BufferAttribute(gl,1));g.setIndex(ix);
return mkSkin(g,pairs)}
/* rings (peel + pith) from a rounded-rectangle profile */
function rrect(r0,r1,h,b){const p=[];for(const[cr,cy,a0]of[[r1-b,h-b,0],[r0+b,h-b,90],[r0+b,-h+b,180],[r1-b,-h+b,270]])for(let s=0;s<=3;s++){const a=(a0+s*30)*Math.PI/180;p.push([cr+b*Math.cos(a),cy+b*Math.sin(a)])}p.push(p[0]);return p}
function buildRing(prof,N){
const P=prof.length,pos=[],uv=[],ix=[],pairs=[];
for(let i=0;i<=N;i++){const a=i/N*TAU,c=Math.cos(a),s=Math.sin(a);for(let j=0;j<P;j++){const[r,y]=prof[j];pos.push(r*c,y,r*s);uv.push(i/N*TAU*1.6,(y+r*.6)*.9)}}
for(let i=0;i<N;i++)for(let j=0;j<P-1;j++){const a=i*P+j,b=(i+1)*P+j;ix.push(a,b,a+1,b,b+1,a+1)}
for(let j=0;j<P;j++)pairs.push(j,N*P+j);
for(let i=0;i<=N;i++)pairs.push(i*P,i*P+P-1);
const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));g.setAttribute('uv',new THREE.Float32BufferAttribute(uv,2));g.setIndex(ix);
return mkSkin(g,pairs)}
const wl=[];for(let k=0;k<NSEG;k++){const len=RIN-.04,g=new THREE.BoxGeometry(len,.4,.04,10,3,1);g.translate(.04+len/2,0,0);g.rotateY(-k*DTH);wl.push(g)}
const skPill=buildPillows(),skPeel=buildRing(rrect(RP,R,.235,.06),96),skPithR=buildRing(rrect(RIN,RP+.01,.2,.03),96),skWall=mkSkin(mergeGeometries(wl));
const pillMat=new THREE.MeshPhysicalMaterial({color:0xff9a1c,transparent:true,opacity:.56,roughness:.06,metalness:0,clearcoat:1,clearcoatRoughness:.04,emissive:0xff5a00,emissiveIntensity:.3,envMapIntensity:1.6,side:THREE.DoubleSide,bumpMap:bump,bumpScale:.7,specularIntensity:1});
pillMat.onBeforeCompile=sh=>{
sh.vertexShader=sh.vertexShader.replace('#include <common>','#include <common>\nattribute float glow;\nvarying float vGlow;').replace('#include <begin_vertex>','#include <begin_vertex>\nvGlow=glow;');
sh.fragmentShader=sh.fragmentShader.replace('#include <common>','#include <common>\nvarying float vGlow;').replace('#include <emissivemap_fragment>','#include <emissivemap_fragment>\nfloat rim=pow(1.0-abs(dot(normalize(vViewPosition),normal)),2.0);\ntotalEmissiveRadiance+=vec3(1.0,0.5,0.06)*vGlow*0.85+vec3(1.0,0.62,0.12)*rim*0.45;\ndiffuseColor.a=clamp(diffuseColor.a+vGlow*0.22+rim*0.2,0.0,1.0);')};
pillMat.customProgramCacheKey=()=>'jellyglow';
const peelMat=new THREE.MeshPhysicalMaterial({color:0xff8c00,roughness:.38,clearcoat:.8,clearcoatRoughness:.2,emissive:0xff4d00,emissiveIntensity:.22,bumpMap:bump,bumpScale:2.2,envMapIntensity:1});
const pithMat=new THREE.MeshStandardMaterial({color:0xfff4df,roughness:.6,emissive:0x40321a,emissiveIntensity:.5,side:THREE.DoubleSide});
function mk(sk,mat,shadow){const m=new THREE.Mesh(sk.geo,mat);m.frustumCulled=false;m.castShadow=shadow;m.receiveShadow=true;scene.add(m);return m}
const pillMesh=mk(skPill,pillMat,true),peelMesh=mk(skPeel,peelMat,true),pithMesh=mk(skPithR,pithMat,true),wallMesh=mk(skWall,pithMat,false);
pillMesh.renderOrder=3;
const picks=[pillMesh,peelMesh,pithMesh,wallMesh];
const skins=[skPill,skPeel,skPithR,skWall];
/* tiny juice cells (instanced), each follows the lattice */
const NCELL=720,cellMat=new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:.22,clearcoat:1,emissive:0xff6a10,emissiveIntensity:.55,envMapIntensity:1.2});
const cells=new THREE.InstancedMesh(new THREE.SphereGeometry(1,8,6),cellMat,NCELL);cells.frustumCulled=false;scene.add(cells);
const cI=new Uint16Array(NCELL*8),cW=new Float32Array(NCELL*8),cR=new Float32Array(NCELL*3),cQ=[],cS=[];
{const pal=[0xff9a1a,0xffb52e,0xff7a00,0xffc94a,0xff8a10].map(c=>new THREE.Color(c)),Y=new THREE.Vector3(0,1,0);
for(let n=0;n<NCELL;n++){const k=Math.floor(rnd()*NSEG),v=.08+rnd()*.84,u=.1+rnd()*.8,rho=RHO0+(RHO1-RHO0)*v,hw=DTH/2-Math.asin(MG/rho),a=(k+.5)*DTH+(2*u-1)*hw*.92;
const e=pe(u,v),yl=(rnd()*2-1)*Math.max(0,PH*e-.05),x=rho*Math.cos(a),z=rho*Math.sin(a);
cR[n*3]=x;cR[n*3+1]=yl+JY;cR[n*3+2]=z;embed(x,yl,z,cI,cW,n*8);
cQ.push(new THREE.Quaternion().setFromAxisAngle(Y,-a));const sc=.7+rnd()*.6;cS.push(new THREE.Vector3(.11*sc,.05*sc,.05*sc));
cells.setColorAt(n,pal[Math.floor(rnd()*pal.length)])}}
const _m=new THREE.Matrix4(),_p=new THREE.Vector3();
function updateCells(){
for(let n=0;n<NCELL;n++){let dx=0,dy=0,dz=0;const o=n*8;
for(let k=0;k<8;k++){const w=cW[o+k];if(w){const q=cI[o+k]*3;dx+=w*disp[q];dy+=w*disp[q+1];dz+=w*disp[q+2]}}
_p.set(cR[n*3]+dx,cR[n*3+1]+dy,cR[n*3+2]+dz);_m.compose(_p,cQ[n],cS[n]);cells.setMatrixAt(n,_m)}
cells.instanceMatrix.needsUpdate=true}
/* glow decal under the jelly */
const decal=new THREE.Mesh(new THREE.CircleGeometry(1,48).rotateX(-Math.PI/2),new THREE.MeshBasicMaterial({map:glowTex,transparent:true,opacity:.5,depthWrite:false,fog:false}));
decal.position.y=.006;decal.renderOrder=1;scene.add(decal);
/* glass press for Squeeze */
const pressG=new THREE.Group();
{const disc=new THREE.Mesh(new THREE.CylinderGeometry(PRAD,PRAD,.14,56).translate(0,.07,0),new THREE.MeshPhysicalMaterial({color:0xd6edf5,roughness:.06,transparent:true,opacity:.3,clearcoat:1,envMapIntensity:1.5,depthWrite:false}));
const han=new THREE.Mesh(new THREE.CylinderGeometry(.13,.13,2.6,16).translate(0,1.44,0),new THREE.MeshStandardMaterial({color:0xcfd8dc,metalness:.9,roughness:.25}));
disc.renderOrder=5;pressG.add(disc,han);pressG.visible=false;scene.add(pressG)}
/* juice drops */
const dropMat=new THREE.MeshPhysicalMaterial({color:0xffa520,roughness:.05,clearcoat:1,transparent:true,opacity:.88,emissive:0xff6a00,emissiveIntensity:.35});
const dropGeo=new THREE.SphereGeometry(1,12,8),pudGeo=new THREE.CircleGeometry(1,28).rotateX(-Math.PI/2);
const drops=[];
for(let i=0;i<14;i++){const m=new THREE.Mesh(dropGeo,dropMat),p=new THREE.Mesh(pudGeo,dropMat.clone());m.visible=p.visible=false;m.castShadow=true;p.material.opacity=.75;scene.add(m,p);drops.push({m,p,s:0,v:new THREE.Vector3(),r:.06,t:0})}
const floorAt=r=>FLOOR+(r>2.3?(r-2.3)*.3:0);
function spawnDrop(){
let d=drops.find(q=>q.s===0);if(!d){d=drops.reduce((a,b)=>b.s===2&&(a.s!==2||b.t>a.t)?b:a);if(d.s!==2)return}
const ia=Math.floor(rnd()*NA),k=idx(NR-1,ia,1)*3,x=pos[k],y=pos[k+1],z=pos[k+2],r=Math.hypot(x,z)||1,nx=x/r,nz=z/r,sp=.5+rnd()*.7;
d.r=.05+rnd()*.04;d.m.position.set(x+nx*.08,Math.max(y,.12),z+nz*.08);d.m.scale.setScalar(d.r);d.v.set(nx*sp,.5+rnd()*.5,nz*sp);d.s=1;d.t=0;d.m.visible=true;d.p.visible=false}
function updateDrops(dt){
for(const d of drops){
if(d.s===1){d.v.y-=9.8*dt;d.m.position.addScaledVector(d.v,dt);const q=d.m.position,r=Math.hypot(q.x,q.z);
if(q.y<floorAt(r)+d.r*.7){d.s=2;d.t=0;d.m.visible=false;d.p.visible=true;d.p.position.set(q.x,floorAt(r)+.004,q.z);d.p.material.opacity=.75}}
else if(d.s===2){d.t+=dt;d.p.scale.setScalar(.02+d.r*3.6*(1-Math.exp(-d.t*5)));
if(d.t>5)d.p.material.opacity=.75*Math.max(0,1-(d.t-5)/2.5);if(d.t>7.5){d.s=0;d.p.visible=false}}}}
/* ---------- squeeze / reset ---------- */
const ease=x=>x*x*(3-2*x);
function startSqueeze(){if(press.t>=0)return;press.t=0;press.drops=0;press.next=0}
function pressUpdate(dt){
if(press.t<0){press.on=false;pressG.visible=false;return}
press.t+=dt;const t=press.t,T1=1.5,T2=.9,T3=1;
if(t<T1)press.y=2.2+(PRESS_Y-2.2)*ease(t/T1);else if(t<T1+T2)press.y=PRESS_Y;else if(t<T1+T2+T3)press.y=PRESS_Y+(2.2-PRESS_Y)*ease((t-T1-T2)/T3);else{press.t=-1;press.y=2.2;press.on=false;pressG.visible=false;return}
press.on=press.y<1.2;pressG.visible=true;pressG.position.y=press.y;
if(press.y<.5&&t<T1+T2+.2&&press.drops<9){press.next-=dt;if(press.next<=0){spawnDrop();press.drops++;press.next=.14+rnd()*.12}}}
function resetAll(){
endGrab();hold=null;press.t=-1;press.y=2.2;press.on=false;pressG.visible=false;
for(const d of drops){d.s=0;d.m.visible=d.p.visible=false}
for(let i=0;i<NP;i++){const k=i*3;pos[k]=rest[k];pos[k+1]=rest[k+1]+.25;pos[k+2]=rest[k+2];vel[k]=vel[k+1]=vel[k+2]=0}
$('fm').value=50;setFirm(.5);demo.slide=null}
/* ---------- interaction ---------- */
function nearList(pt,sig,minW){const I=[],W=[],s2=2*sig*sig;
for(let i=0;i<NP;i++){const k=i*3,dx=pos[k]-pt.x,dy=pos[k+1]-pt.y,dz=pos[k+2]-pt.z,w=Math.exp(-(dx*dx+dy*dy+dz*dz)/s2);if(w>minW){I.push(i);W.push(w)}}
return{I,W}}
function poke(pt,dir){const d=dir.clone().normalize(),n=nearList(pt,.42,.03);
for(let j=0;j<n.I.length;j++){const k=n.I[j]*3,w=n.W[j]*7;vel[k]+=d.x*w;vel[k+1]+=d.y*w;vel[k+2]+=d.z*w}}
function startGrab(pt){const n=nearList(pt,.4,.04);grab={I:n.I,W:n.W,P:n.I.map(i=>[pos[i*3],pos[i*3+1],pos[i*3+2]]),off:new THREE.Vector3(),pt:pt.clone()}}
function endGrab(){grab=null}
const ray=new THREE.Raycaster(),ndc=new THREE.Vector2(),plane=new THREE.Plane(),_d=new THREE.Vector3(),_o=new THREE.Vector3();
const cam={az:.55,ph:.95,d:8,base:8,zoom:1,ty:-.35};
let ptr=null;
function setRay(e){const r=canvas.getBoundingClientRect();ndc.set((e.clientX-r.left)/r.width*2-1,-((e.clientY-r.top)/r.height)*2+1);ray.setFromCamera(ndc,camera)}
window.addEventListener('pointerdown',e=>{if(demo.on&&e.isTrusted)endDemo()},true);
canvas.addEventListener('pointerdown',e=>{
try{canvas.setPointerCapture(e.pointerId)}catch(_){}
setRay(e);const h=ray.intersectObjects(picks,false)[0];
ptr={id:e.pointerId,x:e.clientX,y:e.clientY,lx:e.clientX,ly:e.clientY,mode:h?'jelly':'orbit',hit:h?h.point.clone():null,drag:false};
if(h){const d=ray.ray.direction.clone();poke(h.point,d);const n=nearList(h.point,.42,.04);hold={I:n.I,W:n.W,d:d.normalize()}}});
canvas.addEventListener('pointermove',e=>{
if(!ptr||e.pointerId!==ptr.id)return;
if(ptr.mode==='jelly'){
if(!ptr.drag&&Math.hypot(e.clientX-ptr.x,e.clientY-ptr.y)>8){ptr.drag=true;hold=null;startGrab(ptr.hit)}
if(ptr.drag&&grab){setRay(e);camera.getWorldDirection(_d);plane.setFromNormalAndCoplanarPoint(_d,grab.pt);
if(ray.ray.intersectPlane(plane,_o)){grab.off.copy(_o).sub(grab.pt);if(grab.off.length()>1.9)grab.off.setLength(1.9)}}}
else{cam.az-=(e.clientX-ptr.lx)*.008;cam.ph=Math.min(1.35,Math.max(.35,cam.ph-(e.clientY-ptr.ly)*.006))}
ptr.lx=e.clientX;ptr.ly=e.clientY});
function release(e){if(ptr&&e.pointerId===ptr.id){ptr=null;hold=null;if(!demo.g0)endGrab()}}
canvas.addEventListener('pointerup',release);canvas.addEventListener('pointercancel',release);
canvas.addEventListener('contextmenu',e=>e.preventDefault());
canvas.addEventListener('wheel',e=>{e.preventDefault();cam.zoom=Math.min(1.6,Math.max(.6,cam.zoom*(1+e.deltaY*.001)))},{passive:false});
$('sq').addEventListener('click',startSqueeze);
$('rs').addEventListener('click',resetAll);
$('fm').addEventListener('input',e=>setFirm(e.target.value/100));
/* ---------- #demo: hands-free loop (about 20 s) ---------- */
const demo={on:location.hash==='#demo',t:0,i:0,slide:null,g0:0};
const cap=$('cap');function say(t){cap.textContent=t;cap.style.opacity=t?1:0}
const V=(x,y,z)=>new THREE.Vector3(x,y,z);
const DEMO=[
[.3,()=>say('Hands-free demo: touch anywhere to play')],
[1.2,()=>{say('Poke it');poke(V(.4,.6,.3),V(.1,-1,0))}],
[3.2,()=>poke(V(1.6,.32,.5),V(-1,-.1,-.2))],
[5,()=>{say('Drag to stretch...');startGrab(V(1.5,.4,.2));demo.g0=1}],
[8.2,()=>{endGrab();demo.g0=0;say('...let go: it jiggles, then settles')}],
[11.2,()=>{say('Firmness slider: firm');demo.slide=[.5,.95,11.2,12.2]}],
[12.4,()=>poke(V(.2,.6,-.3),V(0,-1,.1))],
[13.8,()=>{say('Soft and wobbly');demo.slide=[.95,.08,13.8,14.8]}],
[15,()=>poke(V(.2,.6,-.3),V(0,-1,.1))],
[16.4,()=>{say('Squeeze: juice runs out');demo.slide=[.08,.5,16.4,16.9];startSqueeze()}],
[19.9,()=>say('')],
[20.7,()=>{resetAll();demo.t=0;demo.i=0}]
];
function demoUpdate(dt){
if(!demo.on)return;demo.t+=dt;cam.az+=dt*.05;
while(demo.i<DEMO.length&&demo.t>=DEMO[demo.i][0]){const f=DEMO[demo.i][1];demo.i++;f()}
if(demo.g0&&grab){const k=sstep(5.2,7.4,demo.t);grab.off.set(1.3*k,.9*k,.8*k)}
if(demo.slide){const[a,b,t0,t1]=demo.slide,v=a+(b-a)*sstep(t0,t1,demo.t);$('fm').value=Math.round(v*100);setFirm(v)}}
function endDemo(){demo.on=false;demo.g0=0;demo.slide=null;endGrab();say('')}
window.addEventListener('hashchange',()=>{if(location.hash==='#demo'){demo.on=true;demo.t=0;demo.i=0;resetAll()}else if(demo.on)endDemo()});
/* ---------- loop ---------- */
function resize(){
const w=window.innerWidth,h=window.innerHeight,a=w/h;renderer.setSize(w,h,false);camera.aspect=a;camera.updateProjectionMatrix();
cam.base=Math.max(7.6,3.4/(Math.tan(camera.fov*Math.PI/360)*a));cam.ty=a<1?-.95:-.4}
window.addEventListener('resize',resize);resize();
let last=performance.now(),acc=0;
function frame(now){
requestAnimationFrame(frame);
const dt=Math.min((now-last)/1000,1/20);last=now;
demoUpdate(dt);pressUpdate(dt);computeGoals();
acc+=dt;let n=0;while(acc>=SUB&&n<5){step(SUB);acc-=SUB;n++}if(n===5)acc=0;
if(!isFinite(pos[0]+pos[NP*3-1]+pos[NP]))resetAll();
for(let i=0;i<NP*3;i++)disp[i]=pos[i]-rest[i];
for(const s of skins)skinUpdate(s);
updateCells();updateDrops(dt);
let ar=0;for(let ia=0;ia<NA;ia++){const k=idx(NR-1,ia,0)*3;ar+=Math.hypot(pos[k],pos[k+2])}ar/=NA;
decal.scale.setScalar(ar*1.12);
cam.d=cam.base*cam.zoom;const sp=Math.sin(cam.ph);
camera.position.set(cam.d*sp*Math.sin(cam.az),cam.ty+cam.d*Math.cos(cam.ph),cam.d*sp*Math.cos(cam.az));camera.lookAt(0,cam.ty,0);
renderer.render(scene,camera)}
resetAll();
if(demo.on)resetAll();
requestAnimationFrame(frame);
</script>
</body>
</html>
