Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by GPT-6.2 Sol

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.)39.1 KB · 885 lines · loads cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f8f5ed">
<title>Citrus Lab — Orange jelly</title>
<style>
:root{color-scheme:light;--paper:#f8f5ed;--white:#fffcf6;--ink:#30271f;--muted:#746557;--line:#e8ded0;--orange:#bf461b;--accent:#d35324}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink);font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
button,input{font:inherit}
button{cursor:pointer}
button:focus-visible,input:focus-visible{outline:3px solid #bf461b;outline-offset:4px}
.shell{width:min(1312px,calc(100% - clamp(36px,9vw,144px)));margin:0 auto}
header{height:76px;border-bottom:1px solid var(--line)}
.header{height:100%;display:flex;align-items:center;justify-content:space-between;gap:12px}
.wordmark{display:flex;align-items:center;gap:11px;font-size:16px;letter-spacing:-.025em;font-weight:750}
.mark{display:block;width:31px;height:31px;border:2px solid var(--accent);border-radius:50%;box-shadow:inset 0 0 0 2px var(--paper);background:conic-gradient(from 11deg,#dc5e26 0 43deg,#f8f5ed 43deg 47deg,#ef853d 47deg 88deg,#f8f5ed 88deg 92deg,#dc5e26 92deg 133deg,#f8f5ed 133deg 137deg,#ef853d 137deg 178deg,#f8f5ed 178deg 182deg,#dc5e26 182deg 223deg,#f8f5ed 223deg 227deg,#ef853d 227deg 268deg,#f8f5ed 268deg 272deg,#dc5e26 272deg 313deg,#f8f5ed 313deg 317deg,#ef853d 317deg 358deg,#f8f5ed 358deg)}
.header-note{font-size:11px;font-weight:700;letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
main{padding:clamp(26px,4vw,52px) 0 35px}
.intro{margin-bottom:clamp(22px,3vw,35px)}
h1{margin:0;font-family:Georgia,"Times New Roman",serif;font-size:clamp(52px,7.5vw,110px);font-weight:400;letter-spacing:-.075em;line-height:.94}
h1 em{color:var(--orange);font-weight:400;padding-right:.12em}
.intro p{margin:15px 0 0;color:var(--muted);font-size:clamp(14px,1.5vw,17px);letter-spacing:.005em}
.layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(248px,292px);gap:22px;align-items:start}
.stage{position:relative;isolation:isolate;overflow:hidden;height:clamp(440px,41vw,610px);border-radius:23px;border:1px solid #e8d8c4;background:radial-gradient(ellipse at 37% 24%,#fff1d9 0%,#f7e5cc 50%,#ead1b2 100%)}
.stage::before{content:"";position:absolute;inset:0;pointer-events:none;z-index:-1;opacity:.36;background-image:radial-gradient(#ac795b55 .56px,transparent .72px);background-size:13px 13px;mask-image:linear-gradient(120deg,#000,transparent 58%,#000)}
#scene{position:absolute;inset:0;touch-action:none;cursor:grab}
#scene.grabbing{cursor:grabbing}
#scene canvas{display:block;width:100%;height:100%}
.status{position:absolute;top:18px;left:19px;display:flex;align-items:center;gap:7px;background:#fff9eddf;color:#594536;border:1px solid #fffaf0;border-radius:99px;padding:8px 11px;font-size:11px;font-weight:700;letter-spacing:.015em;pointer-events:none}
.status i{width:7px;height:7px;border-radius:50%;background:#8a915b}
.status[data-moving="true"] i{background:#d75b2b;box-shadow:0 0 0 3px #d75b2b22}
.stage-bottom{position:absolute;bottom:15px;left:19px;right:17px;display:flex;align-items:center;justify-content:space-between;gap:8px;pointer-events:none}
.stage-hint{color:#66503c;font-size:11px;font-weight:650}
.demo{pointer-events:auto;display:inline-flex;align-items:center;gap:7px;min-height:44px;padding:0 12px;border-radius:99px;border:1px solid #fffaf0;background:#fff9eddf;color:#594536;font-size:12px;font-weight:700}
.demo:hover{background:#fffaf1}
.demo-icon{display:inline-block;width:10px;height:11px;background:currentColor;clip-path:polygon(12% 0,100% 50%,12% 100%)}
.demo[aria-pressed="true"] .demo-icon{clip-path:polygon(10% 0,37% 0,37% 100%,10% 100%,10% 0,63% 0,90% 0,90% 100%,63% 100%,63% 0)}
.demo-cursor{position:absolute;pointer-events:none;width:30px;height:30px;border:2px solid white;border-radius:50%;background:#fff4;box-shadow:0 0 0 5px #fff3,0 1px 10px #6e35194d;transform:translate(-50%,-50%);z-index:2}
.panel{padding:25px 22px 20px;background:var(--white);border:1px solid var(--line);border-radius:22px;box-shadow:0 9px 25px #69442207}
.panel h2{margin:0 0 23px;font-size:27px;font-family:Georgia,"Times New Roman",serif;font-weight:400;letter-spacing:-.035em}
.slider-label{display:flex;justify-content:space-between;align-items:center;font-size:14px;font-weight:700}
output{min-width:45px;padding:5px 7px;text-align:center;color:#a83e1b;background:#f9eadf;border-radius:6px;font-size:12px;font-variant-numeric:tabular-nums}
input[type="range"]{display:block;width:100%;margin:5px 0 2px;height:32px;appearance:none;background:transparent;cursor:pointer;touch-action:pan-y;--fill:48%}
input[type="range"]::-webkit-slider-runnable-track{height:6px;border-radius:9px;background:linear-gradient(to right,var(--accent) var(--fill),#eee3d6 var(--fill))}
input[type="range"]::-webkit-slider-thumb{appearance:none;width:22px;height:22px;margin-top:-8px;border-radius:50%;border:3px solid #fff9ef;background:var(--accent);box-shadow:0 0 0 1px #c34a1e,0 2px 5px #a9432145}
input[type="range"]::-moz-range-track{height:6px;border-radius:9px;background:linear-gradient(to right,var(--accent) var(--fill),#eee3d6 var(--fill))}
input[type="range"]::-moz-range-thumb{width:16px;height:16px;border-radius:50%;border:3px solid #fff9ef;background:var(--accent);box-shadow:0 0 0 1px #c34a1e,0 2px 5px #a9432145}
.scale{display:flex;justify-content:space-between;color:var(--muted);font-size:11px;font-weight:650}
.actions{display:grid;gap:9px;margin-top:24px}
.action{min-height:48px;display:flex;align-items:center;justify-content:center;gap:9px;border:1px solid var(--line);border-radius:10px;background:transparent;color:#554537;font-size:14px;font-weight:750}
.action:hover{background:#f7eee2}
.primary{background:var(--orange);border-color:var(--orange);color:#fffaf4;box-shadow:0 4px 9px #b4482223}
.primary:hover,.primary[aria-pressed="true"]{background:#a93b16}
.drop-icon{width:12px;height:12px;background:currentColor;transform:rotate(-45deg);border-radius:65% 0 65% 65%;display:block;margin-right:1px}
.reset-icon{font-size:20px;font-weight:500;line-height:1}
.guide{margin-top:19px;border:1px solid var(--line);border-radius:18px;padding:16px 18px;background:#f4eee3}
.guide-row{display:grid;grid-template-columns:29px 1fr;gap:10px;align-items:center;color:#5b4b3e;font-size:12px;line-height:1.4}
.guide-row+.guide-row{margin-top:12px}
.guide-icon{display:grid;place-items:center;width:29px;height:29px;background:#fcf5e9;border:1px solid #eadcce;border-radius:50%;color:#a64323;font-size:15px}
.guide strong{display:block;color:var(--ink);font-size:12px}
#fallback{position:absolute;inset:0;display:grid;place-content:center;text-align:center;padding:24px;color:#64462f;pointer-events:none}
#fallback[hidden],.demo-cursor[hidden]{display:none}
@media(max-width:900px){.layout{grid-template-columns:minmax(0,1fr) 232px;gap:15px}.panel{padding:21px 17px 16px}.stage{height:clamp(380px,53vw,510px)}}
@media(max-width:675px){header{height:59px}.header-note{font-size:9px;letter-spacing:.09em}.mark{width:27px;height:27px}.wordmark{gap:8px}.layout{grid-template-columns:1fr;gap:14px}.stage{height:clamp(290px,92vw,430px);border-radius:17px}.intro{margin-bottom:20px}.intro p{margin-top:9px}.status{top:12px;left:12px}.stage-bottom{bottom:10px;left:12px;right:11px}.panel{padding:17px}.panel h2{margin-bottom:13px;font-size:24px}.actions{grid-template-columns:1.2fr 1fr;margin-top:16px}.guide{display:none}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}}
</style>
</head>
<body>
<header><div class="shell header"><div class="wordmark"><span class="mark" aria-hidden="true"></span>Citrus Lab</div><span class="header-note">Soft-body playground</span></div></header>
<main class="shell">
  <div class="intro"><h1>Orange <em>jelly.</em></h1><p>A slice of citrus you can poke, stretch, and squeeze.</p></div>
  <div class="layout">
    <section class="stage" aria-label="Interactive 3D orange jelly">
      <div id="scene" aria-label="Orange jelly on a white plate"></div>
      <div id="fallback" hidden>WebGL is needed to show the orange jelly.</div>
      <div class="status" id="status" data-moving="false"><i></i><span id="state">At rest</span></div>
      <div class="demo-cursor" id="demoCursor" hidden></div>
      <div class="stage-bottom"><span class="stage-hint">Tap to poke · Drag to stretch</span><button class="demo" id="demo" type="button" aria-pressed="false"><span class="demo-icon" aria-hidden="true"></span><span id="demoText">Play demo</span></button></div>
    </section>
    <aside aria-label="Simulation controls">
      <section class="panel">
        <h2>Controls</h2>
        <label class="slider-label" for="firmness">Firmness <output id="firmOut" for="firmness">48%</output></label>
        <input id="firmness" type="range" min="0" max="100" value="48">
        <div class="scale" aria-hidden="true"><span>Soft</span><span>Firm</span></div>
        <div class="actions">
          <button class="action primary" type="button" id="squeeze" aria-pressed="false"><i class="drop-icon" aria-hidden="true"></i>Squeeze</button>
          <button class="action" type="button" id="reset"><span class="reset-icon" aria-hidden="true">↻</span> Reset</button>
        </div>
      </section>
      <div class="guide">
        <div class="guide-row"><span class="guide-icon" aria-hidden="true">◎</span><div><strong>Poke the pulp</strong>See the ripple travel across the slice.</div></div>
        <div class="guide-row"><span class="guide-icon" aria-hidden="true">↗</span><div><strong>Pull and release</strong>Let the jelly spring back into shape.</div></div>
      </div>
    </aside>
  </div>
</main>
<script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
<script>
(() => {
  "use strict";
  const byId = id => document.getElementById(id);
  const view = byId("scene"), firmInput = byId("firmness"), firmOut = byId("firmOut");
  const squeezeButton = byId("squeeze"), demoButton = byId("demo"), cursor = byId("demoCursor");
  if (!window.THREE) {
    byId("fallback").textContent = "The 3D library could not load.";
    byId("fallback").hidden = false;
    return;
  }

  const T = window.THREE, TAU = Math.PI * 2;
  const clamp = (n, low, high) => Math.max(low, Math.min(high, n));
  const smooth = value => {
    const t = clamp(value, 0, 1);
    return t * t * (3 - 2 * t);
  };
  let seed = 19271;
  function random() {
    seed = (Math.imul(1664525, seed) + 1013904223) >>> 0;
    return seed / 4294967296;
  }
  function canvas(w, h) {
    const image = document.createElement("canvas");
    image.width = w;
    image.height = h;
    return image;
  }
  function texture(image, color = true) {
    const tex = new T.CanvasTexture(image);
    if (color) tex.colorSpace = T.SRGBColorSpace;
    tex.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
    return tex;
  }

  let renderer;
  try {
    renderer = new T.WebGLRenderer({ antialias:true, alpha:true, powerPreference:"high-performance" });
  } catch (_) {
    byId("fallback").hidden = false;
    return;
  }
  renderer.setClearColor(0x000000, 0);
  renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 1.65));
  renderer.outputColorSpace = T.SRGBColorSpace;
  renderer.toneMapping = T.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.11;
  renderer.transmissionResolutionScale = .72;
  view.appendChild(renderer.domElement);

  const scene = new T.Scene();
  const camera = new T.OrthographicCamera(-3,3,2,-2,.1,50);
  camera.position.set(3.5,5.85,7.8);
  camera.lookAt(0,.19,0);
  scene.add(new T.HemisphereLight(0xfff8ee,0xe4a36c,1.34));
  function light(color, intensity, x, y, z) {
    const source = new T.DirectionalLight(color,intensity);
    source.position.set(x,y,z);
    scene.add(source);
  }
  light(0xfff1db,2.28,-3.5,7,2.4);
  light(0xffd5a0,1.45,2.2,4,-5);
  light(0xf5f5ff,.43,5,2,5);

  // A painted light rig supplies broad reflections to the glaze and wet pulp.
  const studio = canvas(768,384), sc = studio.getContext("2d");
  const studioFill = sc.createLinearGradient(0,0,0,384);
  studioFill.addColorStop(0,"#c9bcc2");
  studioFill.addColorStop(.45,"#817470");
  studioFill.addColorStop(.65,"#5e4843");
  studioFill.addColorStop(1,"#332628");
  sc.fillStyle = studioFill;
  sc.fillRect(0,0,768,384);
  sc.filter = "blur(8px)";
  sc.fillStyle = "#fff9f0";
  sc.fillRect(90,67,160,68);
  sc.fillStyle = "#fff0d5";
  sc.fillRect(415,112,99,91);
  sc.fillStyle = "#e4e5fc";
  sc.fillRect(630,88,50,143);
  const studioTex = texture(studio);
  studioTex.mapping = T.EquirectangularReflectionMapping;
  const pmrem = new T.PMREMGenerator(renderer);
  scene.environment = pmrem.fromEquirectangular(studioTex).texture;
  studioTex.dispose();
  pmrem.dispose();

  function shadowTexture(strength) {
    const image = canvas(128,128), ctx = image.getContext("2d");
    const g = ctx.createRadialGradient(64,64,4,64,64,63);
    g.addColorStop(0,"rgba(91,47,23,"+strength+")");
    g.addColorStop(.58,"rgba(105,58,26,"+strength*.66+")");
    g.addColorStop(.84,"rgba(116,66,32,"+strength*.19+")");
    g.addColorStop(1,"rgba(116,66,32,0)");
    ctx.fillStyle = g;
    ctx.fillRect(0,0,128,128);
    return texture(image);
  }
  function shadow(y, x, z, width, depth, strength) {
    const mesh = new T.Mesh(new T.PlaneGeometry(width,depth),new T.MeshBasicMaterial({
      map:shadowTexture(strength),transparent:true,depthWrite:false,toneMapped:false,
      polygonOffset:true,polygonOffsetFactor:-1,polygonOffsetUnits:-1
    }));
    mesh.rotation.x = -Math.PI/2;
    mesh.position.set(x,y,z);
    scene.add(mesh);
    return mesh;
  }
  shadow(-.047,.2,.21,5.95,5.5,.29);
  shadow(-.039,.07,.06,4.84,4.63,.29);
  const plateProfile = [
    [0,-.021],[.91,-.021],[1.23,-.029],[1.28,-.03],[1.34,-.018],[1.38,.018],
    [1.55,.034],[1.73,.062],[1.9,.107],[2.05,.163],[2.15,.213],[2.19,.25],
    [2.2,.272],[2.188,.289],[2.16,.297],[2.11,.29],[2.04,.265],[1.95,.223],
    [1.82,.172],[1.69,.139],[1.56,.121],[1.39,.115],[.8,.115],[0,.115]
  ].map(pair => new T.Vector2(...pair));
  const plate = new T.Mesh(new T.LatheGeometry(plateProfile,160),new T.MeshPhysicalMaterial({
    color:0xfffbf5,roughness:.24,clearcoat:.9,clearcoatRoughness:.16,envMapIntensity:.76
  }));
  scene.add(plate);
  const contact = shadow(.123,.022,.022,3.91,3.91,.37);

  const segmentSizes = [1.02,.96,1.07,.89,1.09,.94,1.1,.98,.95];
  const angles = [-.18];
  for (const size of segmentSizes) angles.push(angles.at(-1) + size * TAU / 9);
  const furrow = 1.68;

  function pulpTextures() {
    const size = 1024, image = canvas(size,size), bumps = canvas(size,size);
    const ctx = image.getContext("2d"), bx = bumps.getContext("2d");
    ctx.fillStyle = "#e86a17";
    ctx.fillRect(0,0,size,size);
    bx.fillStyle = "#777";
    bx.fillRect(0,0,size,size);
    const scale = size / (furrow * 2), half = size / 2;
    for (let i=0;i<9;i++) {
      const a0 = angles[i], a1 = angles[i+1];
      ctx.save();
      ctx.beginPath();
      ctx.moveTo(half,half);
      ctx.arc(half,half,half,a0-.005,a1+.005);
      ctx.closePath();
      ctx.clip();
      const tint = ctx.createRadialGradient(half,half,8,half,half,half);
      tint.addColorStop(0,i%3===1 ? "#ffbc4d" : "#ffad3a");
      tint.addColorStop(.29,"#f89028");
      tint.addColorStop(.75,i%3===1 ? "#e75a0d" : "#f26b0d");
      tint.addColorStop(.96,"#ff9a27");
      tint.addColorStop(1,"#ffc050");
      ctx.fillStyle = tint;
      ctx.fillRect(0,0,size,size);
      ctx.restore();
    }

    // Each vesicle is tapered along the natural radial grain of the flesh.
    function sacPath(context,l,w,bend) {
      context.beginPath();
      context.moveTo(-l*.51,w*bend);
      context.bezierCurveTo(-l*.37,-w*.37,l*.11,-w*.61,l*.39,-w*.33);
      context.bezierCurveTo(l*.57,-w*.19,l*.56,w*.16,l*.33,w*.37);
      context.bezierCurveTo(l*.08,w*.57,-l*.28,w*.44,-l*.51,w*bend);
      context.closePath();
    }
    for (let row=0;row<38;row++) {
      const r0 = .075 + row*.041;
      const count = Math.max(8,Math.round(TAU*r0/.0305));
      const offset = random();
      for (let i=0;i<count;i++) {
        const r = r0 + (random()-.5)*.035;
        const theta = TAU*(i+offset+(random()-.5)*.74)/count;
        const x = half + Math.cos(theta)*r*scale, y = half + Math.sin(theta)*r*scale;
        const direction = theta + (random()-.5)*.86;
        const l = (.036 + random()*.044) * scale * (.62+.27*r);
        const w = (.020 + random()*.021) * scale;
        const bend = (random()-.5)*.37, tone = random();
        ctx.save();
        ctx.translate(x,y);
        ctx.rotate(direction);
        const grad = ctx.createLinearGradient(0,-w*.51,0,w*.51);
        grad.addColorStop(0,tone>.78?"#fff0a6":"#ffbe65");
        grad.addColorStop(.24,tone>.58?"#ffb94f":"#f89129");
        grad.addColorStop(.65,tone>.54?"#ee710e":"#eb6208");
        grad.addColorStop(1,tone>.72?"#ffa136":"#c74a05");
        ctx.globalAlpha = .58 + random()*.38;
        sacPath(ctx,l,w,bend);
        ctx.fillStyle = grad;
        ctx.fill();
        ctx.strokeStyle = "rgba(149,44,0,.22)";
        ctx.lineWidth = .64;
        ctx.stroke();
        if (tone>.61) {
          ctx.beginPath();
          ctx.moveTo(-l*.25,-w*.09);
          ctx.quadraticCurveTo(l*.04,-w*.35,l*.28,-w*.20);
          ctx.strokeStyle = tone>.89?"rgba(255,247,192,.76)":"rgba(255,212,121,.61)";
          ctx.lineWidth = .6+tone*.45;
          ctx.stroke();
        }
        ctx.restore();

        bx.save();
        bx.translate(x,y);
        bx.rotate(direction);
        const lift = bx.createRadialGradient(-l*.06,0,0,0,0,l*.55);
        lift.addColorStop(0,tone>.7?"#d1d1d1":"#acacac");
        lift.addColorStop(1,"#6b6b6b");
        sacPath(bx,l,w,bend);
        bx.fillStyle = lift;
        bx.fill();
        bx.restore();
      }
    }
    return [texture(image),texture(bumps,false)];
  }

  function peelTextures() {
    const w = 1024,h = 192,image=canvas(w,h),bumps=canvas(w,h);
    const ctx=image.getContext("2d"), bx=bumps.getContext("2d");
    const g=ctx.createLinearGradient(0,0,0,h);
    g.addColorStop(0,"#ffbe4e");
    g.addColorStop(.24,"#ff9a22");
    g.addColorStop(.56,"#ef6609");
    g.addColorStop(.79,"#f07d10");
    g.addColorStop(1,"#ffb33c");
    ctx.fillStyle=g;
    ctx.fillRect(0,0,w,h);
    bx.fillStyle="#808080";
    bx.fillRect(0,0,w,h);
    for (let i=0;i<9700;i++) {
      const x=random()*w,y=random()*h,r=.42+random()*1.75;
      ctx.fillStyle=i%3 ? "rgba(179,50,0,.24)" : "rgba(255,230,135,.49)";
      ctx.beginPath();
      ctx.ellipse(x,y,r,r*.68,0,0,TAU);
      ctx.fill();
      bx.fillStyle=i%3 ? "#545454" : "#aa";
      if (!(i%3)) bx.fillStyle="#aaaaaa";
      bx.beginPath();
      bx.ellipse(x,y,r,r*.68,0,0,TAU);
      bx.fill();
    }
    return [texture(image),texture(bumps,false)];
  }

  const [pulpColor,pulpBump] = pulpTextures();
  const [peelColor,peelBump] = peelTextures();
  const pulpMaterial = new T.MeshPhysicalMaterial({
    color:0xffffff,map:pulpColor,bumpMap:pulpBump,bumpScale:.019,
    roughness:.28,ior:1.38,clearcoat:.69,clearcoatRoughness:.21,
    transmission:.27,thickness:.34,attenuationColor:new T.Color(0xff962b),
    attenuationDistance:.66,envMapIntensity:.74,emissive:0xff4900,emissiveIntensity:.072
  });
  const peelMaterial = new T.MeshPhysicalMaterial({
    color:0xffbf61,map:peelColor,bumpMap:peelBump,bumpScale:.018,
    roughness:.38,clearcoat:.49,clearcoatRoughness:.23,envMapIntensity:.52,
    emissive:0xe23d00,emissiveIntensity:.06
  });
  const pithMaterial = new T.MeshPhysicalMaterial({
    color:0xffe6b7,roughness:.54,transmission:.115,thickness:.12,
    attenuationColor:new T.Color(0xffd389),attenuationDistance:.52,envMapIntensity:.34
  });
  const membraneMaterial = new T.MeshPhysicalMaterial({
    color:0xffdda2,roughness:.38,transmission:.25,thickness:.10,
    attenuationColor:new T.Color(0xffad39),attenuationDistance:.37,envMapIntensity:.44
  });

  // A volumetric lattice deforms every part of the fruit in the same field.
  const side = 9, layers = 3, radius = 1.68, lowY = .149, highY = .658;
  const n = side*side*layers, rest = new Float32Array(n*3), pos = new Float32Array(n*3), prev = new Float32Array(n*3);
  const grid = (i,j,k) => ((j*side+k)*side+i)*3;
  for (let j=0;j<layers;j++) for (let k=0;k<side;k++) for (let i=0;i<side;i++) {
    const a = grid(i,j,k);
    rest[a] = -radius + 2*radius*i/(side-1);
    rest[a+1] = lowY + (highY-lowY)*j/(layers-1);
    rest[a+2] = -radius + 2*radius*k/(side-1);
  }
  pos.set(rest);
  prev.set(rest);
  const links = [], cells = [];
  function link(a,b,multiplier) {
    links.push([a,b,Math.hypot(rest[a]-rest[b],rest[a+1]-rest[b+1],rest[a+2]-rest[b+2]),multiplier]);
  }
  function tet(a,b,c,d) {
    const ux=rest[b]-rest[a],uy=rest[b+1]-rest[a+1],uz=rest[b+2]-rest[a+2];
    const vx=rest[c]-rest[a],vy=rest[c+1]-rest[a+1],vz=rest[c+2]-rest[a+2];
    const wx=rest[d]-rest[a],wy=rest[d+1]-rest[a+1],wz=rest[d+2]-rest[a+2];
    cells.push([a,b,c,d,ux*(vy*wz-vz*wy)+uy*(vz*wx-vx*wz)+uz*(vx*wy-vy*wx)]);
  }
  for (let j=0;j<layers;j++) for (let k=0;k<side;k++) for (let i=0;i<side;i++) {
    const a=grid(i,j,k);
    for (let dy=0;dy<=1;dy++) for (let dz=-1;dz<=1;dz++) for (let dx=-1;dx<=1;dx++) {
      if (!dy && (dz<0 || (!dz && dx<=0))) continue;
      if (i+dx<0 || i+dx>=side || k+dz<0 || k+dz>=side || j+dy>=layers) continue;
      link(a,grid(i+dx,j+dy,k+dz),dx&&dz&&dy?.69:1);
    }
    if (i+2<side) link(a,grid(i+2,j,k),.29);
    if (k+2<side) link(a,grid(i,j,k+2),.29);
    if (i+1<side && j+1<layers && k+1<side) {
      const b=grid(i+1,j,k), c=grid(i,j+1,k), d=grid(i,j,k+1);
      const e=grid(i+1,j+1,k), f=grid(i+1,j,k+1), h=grid(i,j+1,k+1), g=grid(i+1,j+1,k+1);
      tet(a,b,e,g);tet(a,e,c,g);tet(a,c,h,g);tet(a,h,d,g);tet(a,d,f,g);tet(a,f,b,g);
    }
  }

  const skins = [];
  function bind(x,y,z,indices,weights,start) {
    const fx=clamp((x+radius)/(2*radius)*(side-1),0,side-1);
    const fy=clamp((y-lowY)/(highY-lowY)*(layers-1),0,layers-1);
    const fz=clamp((z+radius)/(2*radius)*(side-1),0,side-1);
    const i=Math.min(Math.floor(fx),side-2),j=Math.min(Math.floor(fy),layers-2),k=Math.min(Math.floor(fz),side-2);
    const u=fx-i,v=fy-j,w=fz-k;
    for (let dy=0;dy<=1;dy++) for (let dz=0;dz<=1;dz++) for (let dx=0;dx<=1;dx++) {
      indices[start] = grid(i+dx,j+dy,k+dz);
      weights[start++] = (dx?u:1-u)*(dy?v:1-v)*(dz?w:1-w);
    }
  }
  function skin(geometry,material) {
    const mesh = new T.Mesh(geometry,material);
    const attribute=geometry.getAttribute("position"), original=attribute.array.slice();
    attribute.setUsage(T.DynamicDrawUsage);
    const indices=new Uint16Array(attribute.count*8),weights=new Float32Array(attribute.count*8);
    for (let i=0;i<attribute.count;i++) bind(original[i*3],original[i*3+1],original[i*3+2],indices,weights,i*8);
    geometry.computeBoundingSphere();
    geometry.boundingSphere.radius += 1.1;
    mesh.frustumCulled=false;
    skins.push({mesh,attribute,original,indices,weights});
    scene.add(mesh);
    return mesh;
  }
  function updateSkin() {
    for (const {mesh,attribute,original,indices,weights} of skins) {
      const dest=attribute.array;
      for (let i=0;i<attribute.count;i++) {
        const a=i*3, from=i*8;
        let x=original[a],y=original[a+1],z=original[a+2];
        for (let m=from;m<from+8;m++) {
          const p=indices[m],w=weights[m];
          x+=(pos[p]-rest[p])*w;
          y+=(pos[p+1]-rest[p+1])*w;
          z+=(pos[p+2]-rest[p+2])*w;
        }
        dest[a]=x;dest[a+1]=y;dest[a+2]=z;
      }
      attribute.needsUpdate=true;
      mesh.geometry.computeVertexNormals();
    }
  }
  function geometry(vertices,uv,triangles) {
    const geo=new T.BufferGeometry();
    geo.setAttribute("position",new T.Float32BufferAttribute(vertices,3));
    geo.setAttribute("uv",new T.Float32BufferAttribute(uv,2));
    geo.setIndex(triangles);
    geo.computeVertexNormals();
    return geo;
  }

  function ring(profile,ripple) {
    const vertices=[],uv=[],faces=[], steps=132;
    for (let j=0;j<profile.length;j++) {
      const [radius,y]=profile[j];
      for (let i=0;i<=steps;i++) {
        const a=i/steps*TAU, r=radius+ripple*(.51*Math.sin(7*a)+.32*Math.cos(11*a)+.17*Math.sin(19*a));
        vertices.push(r*Math.cos(a),y+.006*Math.sin(5*a),r*Math.sin(a));
        uv.push(i/steps,1-j/(profile.length-1));
      }
    }
    for (let j=0;j<profile.length-1;j++) for (let i=0;i<steps;i++) {
      const a=j*(steps+1)+i,b=a+steps+1;
      faces.push(a,b,a+1,a+1,b,b+1);
    }
    return geometry(vertices,uv,faces);
  }

  skin(ring([
    [1.517,.20],[1.549,.176],[1.583,.195],[1.606,.245],[1.615,.31],
    [1.615,.402],[1.608,.493],[1.592,.566],[1.568,.607],[1.537,.622],
    [1.508,.616],[1.498,.594],[1.503,.277],[1.517,.20]
  ],.011),peelMaterial);
  skin(ring([
    [1.449,.194],[1.498,.183],[1.538,.201],[1.548,.271],[1.545,.535],
    [1.539,.597],[1.522,.621],[1.491,.626],[1.463,.614],[1.448,.587],[1.449,.194]
  ],.010),pithMaterial);

  function polar(r,a) {
    return [Math.cos(a)*r, Math.sin(a)*r];
  }
  function wedge(a0,a1,offset) {
    const outline=[];
    const outer=1.482, inner=.075;
    const shapeRadius = angle => outer+.007*Math.sin(13*angle)+.006*Math.sin(5*angle);
    const from=a0+.014, to=a1-.014;
    const left=polar(shapeRadius(from),from), right=polar(shapeRadius(to),to);
    const nearLeft=polar(inner,a0+.19), nearRight=polar(inner,a1-.19);
    const edgeSamples=[0,.035,.095,.18,.29,.41,.54,.67,.78,.88,.95];
    function edge(start,end,amount) {
      return [start[0]*(1-amount)+end[0]*amount,start[1]*(1-amount)+end[1]*amount];
    }
    for (const amount of edgeSamples) outline.push(edge(nearLeft,left,amount));
    for (let i=0;i<=19;i++) {
      const a=from+(to-from)*i/19;
      outline.push(polar(shapeRadius(a),a));
    }
    for (const amount of edgeSamples.slice(1)) outline.push(edge(right,nearRight,amount));
    outline.push(nearRight);
    const rounded=[];
    for (let i=0;i<outline.length;i++) {
      const p=outline[i],q=outline[(i+1)%outline.length];
      rounded.push(edge(p,q,.25),edge(p,q,.75));
    }
    const center=polar(.91,(a0+a1)*.5);
    const shape=[
      [.014,.642],[.19,.642],[.37,.641],[.55,.638],[.72,.634],[.85,.628],
      [.94,.618],[.98,.602],[1,.575],[1,.512],[1,.386],[.994,.279],
      [.977,.220],[.95,.196],[.86,.181],[.59,.177],[.26,.177],[.014,.177]
    ];
    const vertices=[],uv=[],faces=[],count=rounded.length;
    for (const [scale,height] of shape) {
      for (const p of rounded) {
        const x=center[0]+(p[0]-center[0])*scale,z=center[1]+(p[1]-center[1])*scale;
        const noise=(Math.sin(x*9+offset)*Math.cos(z*11)+.35*Math.sin(x*27+z*15))*.0046;
        vertices.push(x,height+noise,z);
        uv.push(.5+x/(2*furrow),.5-z/(2*furrow));
      }
    }
    for (let j=0;j<shape.length-1;j++) for (let i=0;i<count;i++) {
      const a=j*count+i,b=j*count+(i+1)%count;
      faces.push(a,b,a+count,b,b+count,a+count);
    }
    const bottom=(shape.length-1)*count;
    for (let j=1;j<count-1;j++) faces.push(0,j+1,j,bottom,bottom+j,bottom+j+1);
    return geometry(vertices,uv,faces);
  }

  function placeEllipsoid(material,x,y,z,sx,sy,sz,rotation=0) {
    const geo=new T.SphereGeometry(1,20,12);
    geo.scale(sx,sy,sz);
    geo.rotateY(rotation);
    geo.translate(x,y,z);
    return skin(geo,material);
  }
  for (let i=0;i<9;i++) {
    skin(wedge(angles[i],angles[i+1],i*1.44),pulpMaterial);
    const a=angles[i];
    const [x,z]=polar(.778,a);
    placeEllipsoid(membraneMaterial,x,.387,z,.715,.228,.015,-a);
  }
  placeEllipsoid(pithMaterial,0,.385,0,.091,.249,.083);

  let firmness=.48, grab=null, squeeze=-1, dropCount=0, motion=0, drag=null;
  const drops=[], dt=1/120;
  const dropGeo=new T.SphereGeometry(1,18,12);
  const dropMat=new T.MeshPhysicalMaterial({
    color:0xf97913,roughness:.14,transmission:.20,thickness:.095,
    attenuationColor:new T.Color(0xff7c1b),attenuationDistance:.24,
    clearcoat:1,clearcoatRoughness:.12,envMapIntensity:.92
  });
  const floor = r => .141 + Math.max(0,Math.min(2.13,r)-1.58)*.27;
  function poke(x,z,strength=1) {
    for (let i=0;i<pos.length;i+=3) {
      const dx=rest[i]-x,dz=rest[i+2]-z, h=(rest[i+1]-lowY)/(highY-lowY);
      const local=Math.exp(-(dx*dx+dz*dz)/.25)*h;
      const rim=Math.exp(-(dx*dx+dz*dz)/.95)*h;
      prev[i]-=dx*rim*dt*.95*strength;
      prev[i+1]+=local*dt*4.3*strength;
      prev[i+2]-=dz*rim*dt*.95*strength;
    }
    motion=Math.max(.27,motion);
  }
  function startGrab(hit) {
    const weights = new Float32Array(n);
    for(let i=0;i<n;i++) {
      const a=i*3,dx=rest[a]-hit.x,dz=rest[a+2]-hit.z;
      const h=(rest[a+1]-lowY)/(highY-lowY);
      weights[i]=Math.exp(-(dx*dx+dz*dz)/.72)*(.045+.955*h*h);
    }
    grab={weights,offset:new T.Vector3(),current:new T.Vector3()};
  }
  function startSqueeze() {
    if (squeeze>=0) return;
    squeeze=0;
    dropCount=0;
    squeezeButton.setAttribute("aria-pressed","true");
  }
  function emitDrop() {
    const angle=.35+dropCount*.83+(random()-.5)*.23;
    const x=Math.cos(angle),z=Math.sin(angle),s=.029+random()*.023;
    const mesh=new T.Mesh(dropGeo,dropMat);
    mesh.position.set(x*1.60,.34+random()*.095,z*1.60);
    scene.add(mesh);
    drops.push({mesh,s,dx:x*(.88+random()*.35),dy:-.37-random()*.38,dz:z*(.88+random()*.35),age:0});
    if(drops.length>30) scene.remove(drops.shift().mesh);
  }
  function updateDrops() {
    for (const drop of drops) {
      const point=drop.mesh.position;
      drop.age+=dt;
      point.x+=drop.dx*dt;
      point.y+=drop.dy*dt;
      point.z+=drop.dz*dt;
      drop.dy-=5.3*dt;
      const r=Math.hypot(point.x,point.z), base=floor(r)+drop.s*.35-.022;
      if (point.y<=base || r>2.11) {
        if(r>2.11) {
          point.x*=2.11/r;
          point.z*=2.11/r;
          drop.dx*=.62;
          drop.dz*=.62;
        }
        point.y=base;
        drop.dy=0;
        drop.dx*=.87;
        drop.dz*=.87;
        const spread=1.05+.26*smooth(drop.age*1.25);
        drop.mesh.scale.set(drop.s*spread,drop.s*.47,drop.s*spread*.92);
      } else {
        drop.mesh.scale.set(drop.s*.88,drop.s*(1+Math.abs(drop.dy)*.32),drop.s*.91);
      }
    }
  }
  function preserveVolume(strength) {
    for (const [a,b,c,d,target] of cells) {
      const ux=pos[b]-pos[a],uy=pos[b+1]-pos[a+1],uz=pos[b+2]-pos[a+2];
      const vx=pos[c]-pos[a],vy=pos[c+1]-pos[a+1],vz=pos[c+2]-pos[a+2];
      const wx=pos[d]-pos[a],wy=pos[d+1]-pos[a+1],wz=pos[d+2]-pos[a+2];
      const bx=vy*wz-vz*wy,by=vz*wx-vx*wz,bz=vx*wy-vy*wx;
      const cx=wy*uz-wz*uy,cy=wz*ux-wx*uz,cz=wx*uy-wy*ux;
      const dx=uy*vz-uz*vy,dy=uz*vx-ux*vz,dz=ux*vy-uy*vx;
      const ax=-bx-cx-dx,ay=-by-cy-dy,az=-bz-cz-dz;
      const volume=ux*bx+uy*by+uz*bz;
      const denominator=ax*ax+ay*ay+az*az+bx*bx+by*by+bz*bz+cx*cx+cy*cy+cz*cz+dx*dx+dy*dy+dz*dz+.00001;
      const gain=clamp((target-volume)*strength/denominator,-.45,.45);
      pos[a]+=ax*gain;pos[a+1]+=ay*gain;pos[a+2]+=az*gain;
      pos[b]+=bx*gain;pos[b+1]+=by*gain;pos[b+2]+=bz*gain;
      pos[c]+=cx*gain;pos[c+1]+=cy*gain;pos[c+2]+=cz*gain;
      pos[d]+=dx*gain;pos[d+1]+=dy*gain;pos[d+2]+=dz*gain;
    }
  }
  function step() {
    let pressure=0;
    if (squeeze>=0) {
      squeeze+=dt;
      pressure=smooth(squeeze/.30)*(1-smooth((squeeze-.73)/.40));
      if(dropCount<6 && squeeze>.27+dropCount*.081) {
        emitDrop();
        dropCount++;
      }
      if(squeeze>1.16) {
        squeeze=-1;
        squeezeButton.setAttribute("aria-pressed","false");
      }
    }
    if(grab) grab.current.lerp(grab.offset,.23);

    const damping=.979-firmness*.013, recovery=11+firmness*24;
    let speed=0;
    for(let a=0;a<pos.length;a+=3) {
      const x=pos[a],y=pos[a+1],z=pos[a+2];
      const vx=(x-prev[a])*damping,vy=(y-prev[a+1])*damping,vz=(z-prev[a+2])*damping;
      prev[a]=x;prev[a+1]=y;prev[a+2]=z;
      const h=(rest[a+1]-lowY)/(highY-lowY), stick=1+1.2*(1-h);
      pos[a]=x+vx+(rest[a]-x)*recovery*stick*dt*dt;
      pos[a+1]=y+vy+((rest[a+1]-y)*recovery-4.5)*dt*dt;
      pos[a+2]=z+vz+(rest[a+2]-z)*recovery*stick*dt*dt;
      speed+=vx*vx+vy*vy+vz*vz;
    }

    // Position-based elasticity, signed tetrahedral volume, and unilateral plate contact.
    for(let iteration=0;iteration<4;iteration++) {
      const stiffness=.102+firmness*.25;
      for(const [a,b,length,weight] of links) {
        const x=pos[b]-pos[a],y=pos[b+1]-pos[a+1],z=pos[b+2]-pos[a+2];
        const d=Math.sqrt(x*x+y*y+z*z);
        const scale=(d-length)/(d+.000001)*stiffness*weight*.5;
        pos[a]+=x*scale;pos[a+1]+=y*scale;pos[a+2]+=z*scale;
        pos[b]-=x*scale;pos[b+1]-=y*scale;pos[b+2]-=z*scale;
      }
      preserveVolume(.16+firmness*.16);
      for(let a=0;a<pos.length;a+=3) {
        const h=(rest[a+1]-lowY)/(highY-lowY);
        if (grab) {
          const w=grab.weights[a/3],g=.32*w;
          pos[a]+=(rest[a]+grab.current.x-pos[a])*g;
          pos[a+1]+=(rest[a+1]+grab.current.y-pos[a+1])*g;
          pos[a+2]+=(rest[a+2]+grab.current.z-pos[a+2])*g;
        }
        if(pressure>0) {
          const r=Math.hypot(rest[a],rest[a+2]);
          const inside=1-smooth((r-1.07)/.91);
          const y=rest[a+1]-pressure*h*(.12+.21*inside);
          if(pos[a+1]>y) pos[a+1]+=(y-pos[a+1])*(.29+h*.13)*pressure;
          pos[a]+=(rest[a]*1.09-pos[a])*inside*pressure*h*.025;
          pos[a+2]+=(rest[a+2]*1.09-pos[a+2])*inside*pressure*h*.025;
        }
        const limit=.35+.36*h;
        pos[a]=clamp(pos[a],rest[a]-limit,rest[a]+limit);
        pos[a+2]=clamp(pos[a+2],rest[a+2]-limit,rest[a+2]+limit);
        const ground=floor(Math.hypot(pos[a],pos[a+2]));
        if(pos[a+1]<ground) {
          pos[a+1]=ground;
          if(iteration===3) {
            prev[a]+=(pos[a]-prev[a])*.24;
            prev[a+1]=ground;
            prev[a+2]+=(pos[a+2]-prev[a+2])*.24;
          }
        }
        pos[a+1]=Math.min(pos[a+1],rest[a+1]+.66);
      }
    }
    motion += (Math.sqrt(speed/n)/dt-motion)*.09;
    updateDrops();
  }

  function setFirmness(value) {
    firmness=value/100;
    firmInput.value=value;
    firmInput.style.setProperty("--fill",value+"%");
    firmOut.value=value+"%";
  }
  function resetFruit(resetFirmness) {
    pos.set(rest);
    prev.set(rest);
    grab=null;
    squeeze=-1;
    motion=0;
    dropCount=0;
    squeezeButton.setAttribute("aria-pressed","false");
    for (const drop of drops) scene.remove(drop.mesh);
    drops.length=0;
    if(resetFirmness) setFirmness(48);
    for(let i=0;i<18;i++) step();
    updateSkin();
  }
  firmInput.addEventListener("input",()=>setFirmness(Number(firmInput.value)));
  squeezeButton.addEventListener("click",startSqueeze);
  byId("reset").addEventListener("click",()=>resetFruit(true));

  const raycaster=new T.Raycaster(), ndc=new T.Vector2(), dragPlane=new T.Plane();
  const normal=new T.Vector3();
  function pointerRay(event) {
    const bounds=view.getBoundingClientRect();
    ndc.set(((event.clientX-bounds.left)/bounds.width)*2-1,-((event.clientY-bounds.top)/bounds.height)*2+1);
    raycaster.setFromCamera(ndc,camera);
  }
  view.addEventListener("pointerdown",event=>{
    if(drag || event.button>0) return;
    pointerRay(event);
    const found=raycaster.intersectObjects(skins.map(entry=>entry.mesh),false)[0];
    if(!found) return;
    event.preventDefault();
    const hit=found.point.clone();
    camera.getWorldDirection(normal);
    dragPlane.setFromNormalAndCoplanarPoint(normal,hit);
    drag={id:event.pointerId,hit,x:event.clientX,y:event.clientY,active:false};
    view.setPointerCapture(event.pointerId);
    view.classList.add("grabbing");
    poke(hit.x,hit.z);
  });
  view.addEventListener("pointermove",event=>{
    if(!drag || drag.id!==event.pointerId) return;
    if(!drag.active && Math.hypot(event.clientX-drag.x,event.clientY-drag.y)<5) return;
    if(!drag.active) {
      drag.active=true;
      startGrab(drag.hit);
    }
    pointerRay(event);
    const target=raycaster.ray.intersectPlane(dragPlane,new T.Vector3());
    if(target) {
      target.sub(drag.hit);
      target.y=clamp(target.y,-.32,.63);
      grab.offset.copy(target.clampLength(0,.84));
    }
  });
  function endPointer(event) {
    if(!drag || drag.id!==event.pointerId) return;
    grab=null;
    drag=null;
    view.classList.remove("grabbing");
  }
  for(const name of ["pointerup","pointercancel","lostpointercapture"]) view.addEventListener(name,endPointer);

  let demo=false,demoTime=0,lastDemoTime=-1;
  const demoPoint=new T.Vector3(.79,.61,.43), projection=new T.Vector3();
  function demoPosition(x,y,z) {
    projection.set(x,y,z).project(camera);
    cursor.style.left=(projection.x*.5+.5)*100+"%";
    cursor.style.top=(.5-projection.y*.5)*100+"%";
    cursor.hidden=false;
  }
  function setDemo(active) {
    demo=active;
    demoTime=0;
    lastDemoTime=-1;
    demoButton.setAttribute("aria-pressed",String(active));
    byId("demoText").textContent=active?"Stop demo":"Play demo";
    cursor.hidden=true;
    grab=null;
    if(active) resetFruit(true);
  }
  demoButton.addEventListener("click",()=>setDemo(!demo));
  document.addEventListener("pointerdown",event=>{
    if(demo&&!demoButton.contains(event.target)) setDemo(false);
  },true);
  document.addEventListener("keydown",event=>{
    if(demo&&!demoButton.contains(event.target) && ["Enter"," ","ArrowLeft","ArrowRight","Escape"].includes(event.key)) setDemo(false);
  });
  function playDemo() {
    demoTime+=dt;
    if(demoTime>=20) {
      resetFruit(true);
      demoTime=0;
      lastDemoTime=-1;
    }
    const t=demoTime;
    const crossed=time=>lastDemoTime<time&&t>=time;
    if (crossed(1.18)) poke(-.6,.15,1.24);
    if (crossed(3.12)) poke(.49,.55,.98);
    if (crossed(5.0)) startGrab(demoPoint);
    if (t>=5 && t<7.30 && grab) {
      const p=smooth((t-5)/1.20);
      grab.offset.set(.58*p,.46*p,.16*p);
      demoPosition(demoPoint.x+.42*p,demoPoint.y+.31*p,demoPoint.z+.12*p);
    } else if(t>=.95&&t<1.54) {
      demoPosition(-.6,.66,.15);
    } else if(t>=2.89&&t<3.47) {
      demoPosition(.49,.66,.55);
    } else if(t>=13.10&&t<13.65) {
      demoPosition(.51,.67,-.2);
    } else if(t>=16.28&&t<16.92) {
      demoPosition(.51,.67,-.2);
    } else {
      cursor.hidden=true;
    }
    if (crossed(7.30)) grab=null;
    if (crossed(9.40)) startSqueeze();
    if (crossed(12.20)) setFirmness(84);
    if (crossed(13.29)) poke(.51,-.2,1.23);
    if (crossed(15.40)) setFirmness(24);
    if (crossed(16.46)) poke(.51,-.2,1.23);
    if (crossed(19.10)) resetFruit(true);
    lastDemoTime=t;
  }

  function resize() {
    const width=Math.max(1,view.clientWidth),height=Math.max(1,view.clientHeight),aspect=width/height;
    const halfHeight=Math.max(1.77,2.45/aspect);
    camera.left=-halfHeight*aspect;
    camera.right=halfHeight*aspect;
    camera.top=halfHeight;
    camera.bottom=-halfHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(width,height,false);
  }
  new ResizeObserver(resize).observe(view);
  resize();
  resetFruit(true);
  if(location.hash==="#demo") setDemo(true);

  let last=performance.now(),accumulator=0,shown="";
  renderer.setAnimationLoop(now=>{
    accumulator+=clamp((now-last)/1000,0,.042);
    last=now;
    let changed=false;
    while(accumulator>=dt) {
      if(demo) playDemo();
      step();
      accumulator-=dt;
      changed=true;
    }
    if(changed) {
      updateSkin();
      contact.material.opacity=grab?.91:1;
      const state=grab?"Stretching":squeeze>=0?"Squeezing":motion>.025?"Jiggling":"At rest";
      if(shown!==state) {
        shown=state;
        byId("state").textContent=state;
        byId("status").dataset.moving=String(state!=="At rest");
      }
    }
    renderer.render(scene,camera);
  });
})();
</script>
</body>
</html>