Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by Claude Haiku 5.5

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

index.html

partly works · auto-checked (Checked by an automated pass. Not hand-played yet.)27.7 KB · 769 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.module.js, cdn.jsdelivr.net/npm/[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">
<title>Jelly Orange Slice</title>
<style>
:root{--bg:#f4ede3;--ink:#2a1f16;--card:rgba(255,255,255,.78);--line:#e3d4bf;--btn:#ff9a1f;--btn-ink:#2a1400;--btn-shade:#c26309}
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#1c1711;--ink:#f5ece0;--card:rgba(34,27,20,.82);--line:#4a3c2c}}
:root[data-theme="dark"]{--bg:#1c1711;--ink:#f5ece0;--card:rgba(34,27,20,.82);--line:#4a3c2c}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:var(--bg);color:var(--ink);font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}
#c{position:fixed;left:0;top:0;width:100%;height:100%;display:block;touch-action:none;outline:none}
#top{position:fixed;left:16px;right:16px;top:14px;pointer-events:none}
#top h1{margin:0;font-size:20px;font-weight:800}
#top p{margin:4px 0 0;font-size:14px;opacity:.8}
#hud{position:fixed;left:0;right:0;bottom:0;padding:10px 16px calc(14px + env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;align-items:center;gap:10px;pointer-events:none}
#hud>*{pointer-events:auto}
#status{pointer-events:none;font-size:15px;font-weight:700;background:var(--card);padding:6px 14px;border-radius:999px}
.row{display:flex;gap:12px;justify-content:center;flex-wrap:wrap;width:100%;max-width:560px}
button{min-height:56px;min-width:150px;flex:1 1 150px;max-width:260px;padding:0 20px;border-radius:16px;border:2px solid transparent;font:inherit;font-size:19px;font-weight:800;cursor:pointer;touch-action:manipulation}
#squeeze{background:var(--btn);color:var(--btn-ink);box-shadow:0 6px 0 var(--btn-shade)}
#squeeze:active{transform:translateY(4px);box-shadow:0 2px 0 var(--btn-shade)}
#reset{background:var(--card);color:var(--ink);border-color:var(--line)}
#reset:active{transform:translateY(2px)}
#fbox{display:flex;align-items:center;gap:12px;width:100%;max-width:560px;background:var(--card);border:1px solid var(--line);border-radius:16px;padding:8px 16px}
#fbox label{font-weight:800;font-size:16px;white-space:nowrap}
#fbox output{min-width:2.4em;text-align:right;font-weight:800;font-variant-numeric:tabular-nums}
input[type=range]{-webkit-appearance:none;appearance:none;flex:1;height:44px;margin:0;background:transparent;touch-action:pan-x}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#ffd9a0,#ff8a1f)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;margin-top:-10px;border-radius:50%;background:#fff;border:3px solid #ff8a1f;box-shadow:0 2px 6px rgba(0,0,0,.25)}
input[type=range]::-moz-range-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#ffd9a0,#ff8a1f)}
input[type=range]::-moz-range-thumb{width:26px;height:26px;border-radius:50%;background:#fff;border:3px solid #ff8a1f}
</style>
</head>
<body>
<canvas id="c" tabindex="-1"></canvas>
<div id="top"><h1>Jelly orange slice</h1><p id="hint">Poke it. Drag to stretch it, then let go.</p></div>
<div id="hud">
  <div id="status">Juice left: 6 drops</div>
  <div class="row">
    <button id="squeeze" type="button">Squeeze</button>
    <button id="reset" type="button">Reset</button>
  </div>
  <div id="fbox">
    <label for="firm">Firmness</label>
    <input id="firm" type="range" min="0" max="100" step="1" value="45">
    <output id="firmOut" for="firm">45</output>
  </div>
</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">
(async () => {
const $ = (id) => document.getElementById(id);
const canvas = $('c');
const statusEl = $('status');
const hintEl = $('hint');
const squeezeBtn = $('squeeze');
const resetBtn = $('reset');
const firmIn = $('firm');
const firmOut = $('firmOut');

let THREE = null;
let RoomEnvironment = null;
try {
  THREE = await import('three');
} catch (err) {
  statusEl.textContent = 'The 3D library did not load. Check the connection and reload.';
  return;
}
try {
  RoomEnvironment = (await import('three/addons/environments/RoomEnvironment.js')).RoomEnvironment;
} catch (err) {
  RoomEnvironment = null;
}

let renderer = null;
try {
  renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
} catch (err) {
  statusEl.textContent = 'WebGL is not available in this browser.';
  return;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.0;

const darkMode = !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
const scene = new THREE.Scene();
scene.background = new THREE.Color(darkMode ? 0x1c1711 : 0xf4ede3);
if (RoomEnvironment) {
  try {
    const pmrem = new THREE.PMREMGenerator(renderer);
    scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
  } catch (err) { /* the direct lights below still work */ }
}
scene.add(new THREE.HemisphereLight(0xfff6ea, 0x8a6a4a, 0.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 1.5);
keyLight.position.set(2.5, 5, 3);
scene.add(keyLight);
const backLight = new THREE.DirectionalLight(0xffb55c, 2.4);
backLight.position.set(-2.5, 2.2, -3.5);
scene.add(backLight);

const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 60);
const view = { yaw: 0.35, pitch: 0.62 };
const TARGET = new THREE.Vector3(0, 0.1, 0);
function placeCamera() {
  const aspect = window.innerWidth / Math.max(1, window.innerHeight);
  camera.aspect = aspect;
  camera.fov = aspect < 0.9 ? 50 : 35;
  camera.updateProjectionMatrix();
  const need = 1.9 / (Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2) * aspect);
  const dist = Math.max(4.1, need);
  const cp = Math.cos(view.pitch);
  camera.position.set(
    TARGET.x + Math.sin(view.yaw) * cp * dist,
    TARGET.y + Math.sin(view.pitch) * dist,
    TARGET.z + Math.cos(view.yaw) * cp * dist
  );
  camera.lookAt(TARGET);
  camera.updateMatrixWorld();
}

// ---------- shape and constants ----------
const NA = 40, NR = 6, NZ = 3, SEG = 10, PER = NA / SEG;
const RAD = 1.0, THICK = 0.3, PLATE_TOP = 0.02, Y0 = PLATE_TOP + 0.012;
const PLATE_R = 1.5, GRAV = -9.0, FIX_DT = 1 / 480, ITER = 5;
const KG = 50, RG = 0.5, PICK = 0.26, POKE_R = 0.36, POKE_V = 2.6;
const PR = 0.55, SQ_BOTTOM = Y0 + THICK - 0.16, SQ_DROPS = [1.45, 1.8, 2.15];
const JUICE_MAX = 6, DEMO_LEN = 20;
const NC = NA * NR * NZ, NP = NC + NZ, GJ = NA + 1, GI = NR + 1;

const pIdx = (j, i, k) => {
  if (i === 0) return NC + k;
  const jj = ((j % NA) + NA) % NA;
  return (k * NR + (i - 1)) * NA + jj;
};
const gId = (s, j, i) => (s * GJ + j) * GI + i;
const clamp01 = (x) => Math.min(1, Math.max(0, x));
const smooth = (x) => { const s = clamp01(x); return s * s * (3 - 2 * s); };
const lerp = (a, b, t) => a + (b - a) * t;

// ---------- rest shape and springs (position-based dynamics) ----------
const RX = new Float64Array(NP), RY = new Float64Array(NP), RZ = new Float64Array(NP);
for (let k = 0; k < NZ; k++) {
  const y = Y0 + THICK * k / (NZ - 1);
  for (let i = 1; i <= NR; i++) {
    const r = RAD * i / NR;
    for (let j = 0; j < NA; j++) {
      const a = 2 * Math.PI * j / NA, p = pIdx(j, i, k);
      RX[p] = r * Math.cos(a); RY[p] = y; RZ[p] = r * Math.sin(a);
    }
  }
  const c = pIdx(0, 0, k);
  RX[c] = 0; RY[c] = y; RZ[c] = 0;
}

const cA = [], cB = [], cM = [];
const link = (a, b, m) => { cA.push(a); cB.push(b); cM.push(m); };
for (let k = 0; k < NZ; k++) {
  for (let j = 0; j < NA; j++) {
    for (let i = 1; i <= NR; i++) {
      const p = pIdx(j, i, k);
      if (i === 1) link(p, pIdx(0, 0, k), 1);
      if (i < NR) link(p, pIdx(j, i + 1, k), 1);
      link(p, pIdx(j + 1, i, k), 1);
      link(p, pIdx(j + 2, i, k), 0.45);
      if (i < NR) {
        link(p, pIdx(j + 1, i + 1, k), 0.7);
        link(pIdx(j + 1, i, k), pIdx(j, i + 1, k), 0.7);
      }
      if (k < NZ - 1) {
        link(p, pIdx(j, i, k + 1), 1);
        link(p, pIdx(j + 1, i, k + 1), 0.6);
        link(pIdx(j + 1, i, k), pIdx(j, i, k + 1), 0.6);
      }
    }
  }
  if (k < NZ - 1) link(pIdx(0, 0, k), pIdx(0, 0, k + 1), 1);
}
const NCON = cA.length;
const CA = Int32Array.from(cA), CB = Int32Array.from(cB), CM = Float64Array.from(cM);
const CL = new Float64Array(NCON);
for (let c = 0; c < NCON; c++) {
  const a = CA[c], b = CB[c];
  CL[c] = Math.hypot(RX[b] - RX[a], RY[b] - RY[a], RZ[b] - RZ[a]);
}

// ---------- simulation state ----------
const PX = new Float64Array(NP), PY = new Float64Array(NP), PZ = new Float64Array(NP);
const OX = new Float64Array(NP), OY = new Float64Array(NP), OZ = new Float64Array(NP);
const VX = new Float64Array(NP), VY = new Float64Array(NP), VZ = new Float64Array(NP);
const CONTACT = new Uint8Array(NP);
let kS = 0.59;
let juiceLeft = JUICE_MAX;
let grab = null, offX = 0, offY = 0, offZ = 0;
let presserOn = false, presserY = 2.0, squeeze = null;
const drops = [], puddles = [];
const tmpV = new THREE.Vector3();

// ---------- textures ----------
function radialTex(inner, outer) {
  const cv = document.createElement('canvas');
  cv.width = 256; cv.height = 256;
  const g = cv.getContext('2d');
  const gr = g.createRadialGradient(128, 128, 0, 128, 128, 128);
  gr.addColorStop(0, inner);
  gr.addColorStop(1, outer);
  g.fillStyle = gr;
  g.fillRect(0, 0, 256, 256);
  const t = new THREE.CanvasTexture(cv);
  t.colorSpace = THREE.SRGBColorSpace;
  return t;
}
function makeJuiceTexture() {
  const W = 512, H = 512;
  const cv = document.createElement('canvas');
  cv.width = W; cv.height = H;
  const g = cv.getContext('2d');
  g.fillStyle = '#ff9f2e';
  g.fillRect(0, 0, W, H);
  let seed = 12345;
  const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
  for (let n = 0; n < 380; n++) {
    const x = rnd() * W, y = rnd() * H;
    const rx = 8 + rnd() * 9, ry = rx * (1.25 + rnd() * 0.9);
    for (const ox of [-W, 0, W]) {
      const cx = x + ox;
      const gr = g.createRadialGradient(cx - rx * 0.3, y - ry * 0.3, rx * 0.1, cx, y, ry);
      gr.addColorStop(0, '#fff3cf');
      gr.addColorStop(0.4, '#ffc760');
      gr.addColorStop(1, '#ff8418');
      g.beginPath();
      g.ellipse(cx, y, rx, ry, 0, 0, Math.PI * 2);
      g.fillStyle = gr;
      g.fill();
      g.lineWidth = 1.2;
      g.strokeStyle = 'rgba(190,70,0,0.45)';
      g.stroke();
    }
  }
  const t = new THREE.CanvasTexture(cv);
  t.wrapS = THREE.RepeatWrapping;
  t.wrapT = THREE.ClampToEdgeWrapping;
  t.repeat.set(SEG, 1);
  t.colorSpace = THREE.SRGBColorSpace;
  t.anisotropy = 4;
  return t;
}

// ---------- plate and shadow ----------
const plate = new THREE.Mesh(
  new THREE.LatheGeometry([
    new THREE.Vector2(0, -0.12), new THREE.Vector2(1.35, -0.12), new THREE.Vector2(1.58, -0.09),
    new THREE.Vector2(1.72, -0.035), new THREE.Vector2(1.77, 0.0), new THREE.Vector2(1.72, 0.012),
    new THREE.Vector2(1.6, PLATE_TOP), new THREE.Vector2(0, PLATE_TOP)
  ], 96),
  new THREE.MeshPhysicalMaterial({ color: 0xf8f6f2, roughness: 0.25, clearcoat: 0.6, clearcoatRoughness: 0.18, side: THREE.DoubleSide })
);
scene.add(plate);
const shadow = new THREE.Mesh(
  new THREE.PlaneGeometry(2.7, 2.7),
  new THREE.MeshBasicMaterial({ map: radialTex('rgba(90,50,15,0.5)', 'rgba(90,50,15,0)'), transparent: true, depthWrite: false })
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = PLATE_TOP + 0.002;
scene.add(shadow);

// ---------- slice meshes ----------
const juiceTex = makeJuiceTexture();
const fleshMat = new THREE.MeshPhysicalMaterial({
  map: juiceTex, color: 0xffffff, roughness: 0.1, metalness: 0,
  transmission: 0.6, thickness: 0.45, ior: 1.36,
  attenuationColor: new THREE.Color(0xff7a14), attenuationDistance: 0.35,
  clearcoat: 1, clearcoatRoughness: 0.05,
  emissive: new THREE.Color(0x4a1d00), emissiveIntensity: 0.3,
  side: THREE.DoubleSide
});
const pithMat = new THREE.MeshStandardMaterial({ color: 0xfff7e8, roughness: 0.6, side: THREE.DoubleSide });
const peelMat = new THREE.MeshPhysicalMaterial({
  color: 0xff8c1a, roughness: 0.3, clearcoat: 0.8, clearcoatRoughness: 0.12,
  emissive: new THREE.Color(0x2a0d00), emissiveIntensity: 0.4, side: THREE.DoubleSide
});
const membraneMat = new THREE.MeshStandardMaterial({
  color: 0xfffaf0, roughness: 0.5, transparent: true, opacity: 0.85, side: THREE.DoubleSide
});

// flesh: top and bottom grids (seam column included)
const fleshPos = new Float32Array(2 * GJ * GI * 3);
const fleshUV = new Float32Array(2 * GJ * GI * 2);
const fleshIdx = [];
for (let s = 0; s < 2; s++) {
  for (let j = 0; j < GJ; j++) {
    for (let i = 0; i < GI; i++) {
      const v = gId(s, j, i);
      fleshUV[2 * v] = j / NA;
      fleshUV[2 * v + 1] = i / NR;
    }
  }
}
for (let j = 0; j < NA; j++) {
  for (let i = 0; i < NR; i++) {
    const a = gId(0, j, i), b = gId(0, j + 1, i), c = gId(0, j + 1, i + 1), d = gId(0, j, i + 1);
    fleshIdx.push(a, b, c, a, c, d);
    const A = gId(1, j, i), B = gId(1, j + 1, i), C = gId(1, j + 1, i + 1), D = gId(1, j, i + 1);
    fleshIdx.push(A, C, B, A, D, C);
  }
}
const fleshGeo = new THREE.BufferGeometry();
fleshGeo.setAttribute('position', new THREE.BufferAttribute(fleshPos, 3));
fleshGeo.setAttribute('uv', new THREE.BufferAttribute(fleshUV, 2));
fleshGeo.setIndex(fleshIdx);
const flesh = new THREE.Mesh(fleshGeo, fleshMat);
flesh.frustumCulled = false;
scene.add(flesh);

// rind bands: white pith, then bright peel just outside it
const bandIdx = [];
for (let j = 0; j < NA; j++) {
  for (let k = 0; k < NZ - 1; k++) {
    const a = j * NZ + k, b = (j + 1) * NZ + k, c = (j + 1) * NZ + k + 1, d = j * NZ + k + 1;
    bandIdx.push(a, c, b, a, d, c);
  }
}
const pithPos = new Float32Array((NA + 1) * NZ * 3);
const peelPos = new Float32Array((NA + 1) * NZ * 3);
const pithGeo = new THREE.BufferGeometry();
pithGeo.setAttribute('position', new THREE.BufferAttribute(pithPos, 3));
pithGeo.setIndex(bandIdx);
const peelGeo = new THREE.BufferGeometry();
peelGeo.setAttribute('position', new THREE.BufferAttribute(peelPos, 3));
peelGeo.setIndex(bandIdx);
const pith = new THREE.Mesh(pithGeo, pithMat);
const peel = new THREE.Mesh(peelGeo, peelMat);
pith.frustumCulled = false;
peel.frustumCulled = false;
scene.add(pith, peel);

// membranes: white walls between the 10 segments
const membPos = new Float32Array(SEG * GI * NZ * 3);
const membIdx = [];
for (let b = 0; b < SEG; b++) {
  for (let i = 0; i < NR; i++) {
    for (let k = 0; k < NZ - 1; k++) {
      const a = (b * GI + i) * NZ + k, bb = (b * GI + i + 1) * NZ + k;
      const c = (b * GI + i + 1) * NZ + k + 1, d = (b * GI + i) * NZ + k + 1;
      membIdx.push(a, bb, c, a, c, d);
    }
  }
}
const membGeo = new THREE.BufferGeometry();
membGeo.setAttribute('position', new THREE.BufferAttribute(membPos, 3));
membGeo.setIndex(membIdx);
const membranes = new THREE.Mesh(membGeo, membraneMat);
membranes.frustumCulled = false;
scene.add(membranes);

// ---------- drops, puddles, squeezer ----------
const dropGeo = new THREE.SphereGeometry(0.035, 14, 10);
const dropMat = new THREE.MeshStandardMaterial({ color: 0xff9d2a, emissive: 0x3d1a00, roughness: 0.12 });
const puddleGeo = new THREE.CircleGeometry(1, 28);
const puddleMat = new THREE.MeshBasicMaterial({ color: 0xffa52e, transparent: true, opacity: 0.85, depthWrite: false });

const presser = new THREE.Group();
const pDisc = new THREE.Mesh(
  new THREE.CylinderGeometry(PR, PR, 0.12, 56),
  new THREE.MeshPhysicalMaterial({ color: 0xe6edf3, roughness: 0.3, clearcoat: 0.6 })
);
pDisc.position.y = 0.06;
const pStem = new THREE.Mesh(
  new THREE.CylinderGeometry(0.07, 0.09, 1.0, 24),
  new THREE.MeshStandardMaterial({ color: 0xb8c2cc, roughness: 0.4 })
);
pStem.position.y = 0.62;
presser.add(pDisc, pStem);
presser.visible = false;
scene.add(presser);

// ---------- physics ----------
function physicsStep(dt) {
  const damp = Math.exp(-1.6 * dt);
  for (let p = 0; p < NP; p++) {
    VX[p] *= damp;
    VY[p] = VY[p] * damp + GRAV * dt;
    VZ[p] *= damp;
    CONTACT[p] = 0;
  }
  if (grab) {
    for (let g = 0; g < grab.n; g++) {
      const p = grab.id[g], w = grab.w[g], s = KG * w * dt;
      VX[p] += (grab.sx[g] + offX * w - PX[p]) * s;
      VY[p] += (grab.sy[g] + offY * w - PY[p]) * s;
      VZ[p] += (grab.sz[g] + offZ * w - PZ[p]) * s;
    }
  }
  for (let p = 0; p < NP; p++) {
    OX[p] = PX[p]; OY[p] = PY[p]; OZ[p] = PZ[p];
    PX[p] += VX[p] * dt; PY[p] += VY[p] * dt; PZ[p] += VZ[p] * dt;
  }
  for (let it = 0; it < ITER; it++) {
    for (let c = 0; c < NCON; c++) {
      const a = CA[c], b = CB[c];
      const dx = PX[b] - PX[a], dy = PY[b] - PY[a], dz = PZ[b] - PZ[a];
      const d = Math.sqrt(dx * dx + dy * dy + dz * dz);
      if (d < 1e-9) continue;
      const s = 0.5 * kS * CM[c] * (d - CL[c]) / d;
      const ex = dx * s, ey = dy * s, ez = dz * s;
      PX[a] += ex; PY[a] += ey; PZ[a] += ez;
      PX[b] -= ex; PY[b] -= ey; PZ[b] -= ez;
    }
    collide();
  }
  for (let p = 0; p < NP; p++) {
    let vx = (PX[p] - OX[p]) / dt, vy = (PY[p] - OY[p]) / dt, vz = (PZ[p] - OZ[p]) / dt;
    if (CONTACT[p]) { vx *= 0.96; vz *= 0.96; }
    const sp = vx * vx + vy * vy + vz * vz;
    if (sp > 36) { const sc = 6 / Math.sqrt(sp); vx *= sc; vy *= sc; vz *= sc; }
    VX[p] = vx; VY[p] = vy; VZ[p] = vz;
  }
}

function collide() {
  const pr2 = PR * PR;
  const lim2 = PLATE_R * PLATE_R;
  for (let p = 0; p < NP; p++) {
    if (PY[p] < PLATE_TOP) { PY[p] = PLATE_TOP; CONTACT[p] = 1; }
    const r2 = PX[p] * PX[p] + PZ[p] * PZ[p];
    if (r2 > lim2) { const s = PLATE_R / Math.sqrt(r2); PX[p] *= s; PZ[p] *= s; }
    if (presserOn && r2 < pr2 && PY[p] > presserY) PY[p] = presserY;
  }
}

function setFirmness(v) {
  firmIn.value = String(v);
  firmOut.textContent = String(v);
  kS = 0.3 + 0.65 * (v / 100);
}

function updateStatus() {
  if (squeeze) statusEl.textContent = 'Squeezing...';
  else if (juiceLeft > 0) statusEl.textContent = 'Juice left: ' + juiceLeft + (juiceLeft === 1 ? ' drop' : ' drops');
  else statusEl.textContent = 'Out of juice. Press Reset to refill.';
}

// ---------- interaction ----------
function pickParticle(ray) {
  let best = -1, bestD = PICK * PICK;
  for (let p = 0; p < NP; p++) {
    tmpV.set(PX[p], PY[p], PZ[p]);
    const d = ray.distanceSqToPoint(tmpV);
    if (d < bestD) { bestD = d; best = p; }
  }
  return best;
}
function beginGrab(hit) {
  const ids = [], ws = [];
  for (let p = 0; p < NP; p++) {
    const d = Math.hypot(PX[p] - hit.x, PY[p] - hit.y, PZ[p] - hit.z);
    if (d < RG) { ids.push(p); ws.push((1 - d / RG) ** 2); }
  }
  grab = {
    n: ids.length,
    id: Int32Array.from(ids),
    w: Float64Array.from(ws),
    sx: Float64Array.from(ids, (p) => PX[p]),
    sy: Float64Array.from(ids, (p) => PY[p]),
    sz: Float64Array.from(ids, (p) => PZ[p])
  };
  offX = 0; offY = 0; offZ = 0;
}
function setGrabOffset(x, y, z) {
  const L = Math.hypot(x, y, z);
  const m = L > 1.2 ? 1.2 / L : 1;
  offX = x * m; offY = y * m; offZ = z * m;
}
function endGrab() {
  grab = null;
  offX = 0; offY = 0; offZ = 0;
}
function poke(point, dir) {
  const r2 = POKE_R * POKE_R;
  for (let p = 0; p < NP; p++) {
    const dx = PX[p] - point.x, dy = PY[p] - point.y, dz = PZ[p] - point.z;
    const d2 = dx * dx + dy * dy + dz * dz;
    if (d2 < r2) {
      const w = (1 - d2 / r2) ** 2 * POKE_V;
      VX[p] += dir.x * w; VY[p] += dir.y * w; VZ[p] += dir.z * w;
    }
  }
}

// ---------- squeeze and juice ----------
function startSqueeze() {
  if (squeeze) return;
  squeeze = { t: 0, next: 0 };
  presserOn = true;
  presser.visible = true;
  presserY = 2.0;
  presser.position.y = presserY;
  updateStatus();
}
function spawnDrop() {
  const a = Math.random() * Math.PI * 2;
  const m = new THREE.Mesh(dropGeo, dropMat);
  m.position.set(Math.cos(a) * 1.04, Y0 + THICK * 0.55, Math.sin(a) * 1.04);
  scene.add(m);
  drops.push({ m, vx: Math.cos(a) * 0.5, vy: 1.3, vz: Math.sin(a) * 0.5, life: 0 });
}
function addPuddle(x, z) {
  const pd = new THREE.Mesh(puddleGeo, puddleMat);
  pd.rotation.x = -Math.PI / 2;
  const s = 0.05 + Math.random() * 0.05;
  pd.scale.set(s, s, 1);
  pd.position.set(x, PLATE_TOP + 0.004, z);
  scene.add(pd);
  puddles.push(pd);
  if (puddles.length > 14) scene.remove(puddles.shift());
}
function updateDrops(dt) {
  for (let i = drops.length - 1; i >= 0; i--) {
    const d = drops[i];
    d.life += dt;
    d.vy += GRAV * dt;
    const pos = d.m.position;
    pos.x += d.vx * dt; pos.y += d.vy * dt; pos.z += d.vz * dt;
    const landed = pos.y <= PLATE_TOP + 0.03;
    if (landed || d.life > 4) {
      if (landed && Math.hypot(pos.x, pos.z) < PLATE_R) addPuddle(pos.x, pos.z);
      scene.remove(d.m);
      drops.splice(i, 1);
    }
  }
}
function updateSqueeze(dt) {
  if (!squeeze) return;
  squeeze.t += dt;
  const t = squeeze.t;
  if (t < 1.2) presserY = lerp(2.0, SQ_BOTTOM, smooth(t / 1.2));
  else if (t < 2.6) presserY = SQ_BOTTOM;
  else if (t < 3.8) presserY = lerp(SQ_BOTTOM, 2.0, smooth((t - 2.6) / 1.2));
  else {
    squeeze = null;
    presserOn = false;
    presser.visible = false;
    updateStatus();
    return;
  }
  presser.position.y = presserY;
  while (squeeze.next < SQ_DROPS.length && t >= SQ_DROPS[squeeze.next]) {
    squeeze.next++;
    if (juiceLeft > 0) { juiceLeft--; spawnDrop(); }
  }
  updateStatus();
}

function resetJelly() {
  for (let p = 0; p < NP; p++) {
    PX[p] = RX[p]; PY[p] = RY[p] + 0.12; PZ[p] = RZ[p];
    OX[p] = PX[p]; OY[p] = PY[p]; OZ[p] = PZ[p];
    VX[p] = 0; VY[p] = 0; VZ[p] = 0;
    CONTACT[p] = 0;
  }
  endGrab();
  squeeze = null;
  presserOn = false;
  presser.visible = false;
  for (const d of drops) scene.remove(d.m);
  drops.length = 0;
  for (const pd of puddles) scene.remove(pd);
  puddles.length = 0;
  juiceLeft = JUICE_MAX;
  setFirmness(45);
  updateStatus();
}

// ---------- hands-free demo (#demo) ----------
const demo = { on: false, t: 0, idx: 0 };
const DEMO_EVENTS = [
  { t: 0.8, run: () => poke(new THREE.Vector3(-0.55, Y0 + THICK, 0.3), new THREE.Vector3(0, -1, 0)) },
  { t: 3.0, run: () => beginGrab(new THREE.Vector3(0.85, Y0 + THICK * 0.5, 0.05)) },
  { t: 5.6, run: () => endGrab() },
  { t: 11.0, run: () => startSqueeze() },
  { t: 15.0, run: () => startSqueeze() },
  { t: 19.0, run: () => resetJelly() }
];
function demoUpdate(dt) {
  if (!demo.on) return;
  demo.t += dt;
  if (demo.t >= DEMO_LEN) { demo.t -= DEMO_LEN; demo.idx = 0; }
  while (demo.idx < DEMO_EVENTS.length && demo.t >= DEMO_EVENTS[demo.idx].t) {
    DEMO_EVENTS[demo.idx].run();
    demo.idx++;
  }
  if (grab && demo.t >= 3.0 && demo.t < 5.6) {
    const u = smooth((demo.t - 3.0) / 1.4);
    setGrabOffset(0.55 * u, 0.42 * u, 0);
  }
  if (demo.t >= 7.5 && demo.t < 10.5) {
    const v = demo.t < 9.0
      ? 45 + 45 * smooth((demo.t - 7.5) / 1.5)
      : 90 - 45 * smooth((demo.t - 9.0) / 1.5);
    setFirmness(Math.round(v));
  }
}
function stopDemo() {
  if (!demo.on) return;
  demo.on = false;
  endGrab();
  hintEl.textContent = 'Poke it. Drag to stretch it, then let go.';
}

// ---------- pointer input ----------
let ptr = null;
const planeN = new THREE.Vector3();
const dragPlane = new THREE.Plane();
const grabHit = new THREE.Vector3();
const tmpOut = new THREE.Vector3();
function rayFrom(e) {
  const r = canvas.getBoundingClientRect();
  const nx = ((e.clientX - r.left) / r.width) * 2 - 1;
  const ny = -((e.clientY - r.top) / r.height) * 2 + 1;
  const far = new THREE.Vector3(nx, ny, 0.5).unproject(camera);
  const origin = camera.position.clone();
  return new THREE.Ray(origin, far.sub(origin).normalize());
}
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
canvas.addEventListener('pointerdown', (e) => {
  if (e.pointerType === 'mouse' && e.button !== 0) return;
  try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* optional */ }
  const ray = rayFrom(e);
  const p = pickParticle(ray);
  if (p >= 0) {
    grabHit.set(PX[p], PY[p], PZ[p]);
    camera.getWorldDirection(planeN);
    dragPlane.setFromNormalAndCoplanarPoint(planeN, grabHit);
    beginGrab(grabHit);
    ptr = { id: e.pointerId, x: e.clientX, y: e.clientY, lx: e.clientX, ly: e.clientY, mode: 'grab', moved: false, dir: ray.direction.clone() };
  } else {
    ptr = { id: e.pointerId, x: e.clientX, y: e.clientY, lx: e.clientX, ly: e.clientY, mode: 'orbit', moved: false };
  }
});
canvas.addEventListener('pointermove', (e) => {
  if (!ptr || e.pointerId !== ptr.id) return;
  const dx = e.clientX - ptr.lx, dy = e.clientY - ptr.ly;
  if (!ptr.moved && Math.hypot(e.clientX - ptr.x, e.clientY - ptr.y) > 8) ptr.moved = true;
  ptr.lx = e.clientX; ptr.ly = e.clientY;
  if (ptr.mode === 'grab') {
    if (ptr.moved && grab) {
      const ray = rayFrom(e);
      if (ray.intersectPlane(dragPlane, tmpOut)) {
        setGrabOffset(tmpOut.x - grabHit.x, tmpOut.y - grabHit.y, tmpOut.z - grabHit.z);
      }
    }
  } else {
    view.yaw -= dx * 0.008;
    view.pitch = Math.min(1.3, Math.max(0.15, view.pitch + dy * 0.004));
    placeCamera();
  }
});
function endPointer(e) {
  if (!ptr || e.pointerId !== ptr.id) return;
  if (ptr.mode === 'grab') {
    if (!ptr.moved) poke(grabHit, ptr.dir);
    endGrab();
  }
  ptr = null;
}
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer);
document.addEventListener('pointerdown', (e) => {
  if (e.isTrusted) stopDemo();
}, true);

squeezeBtn.addEventListener('click', () => startSqueeze());
resetBtn.addEventListener('click', () => resetJelly());
firmIn.addEventListener('input', () => setFirmness(Number(firmIn.value)));

// ---------- rendering ----------
function fillBand(arr, off) {
  for (let j = 0; j <= NA; j++) {
    for (let k = 0; k < NZ; k++) {
      const p = pIdx(j, NR, k), c = pIdx(0, 0, k);
      let dx = PX[p] - PX[c], dz = PZ[p] - PZ[c];
      const L = Math.hypot(dx, dz) || 1;
      dx /= L; dz /= L;
      const bulge = off * Math.sin(Math.PI * k / (NZ - 1));
      const v = (j * NZ + k) * 3;
      arr[v] = PX[p] + dx * bulge;
      arr[v + 1] = PY[p];
      arr[v + 2] = PZ[p] + dz * bulge;
    }
  }
}
function syncMeshes() {
  let sum = 0;
  for (let p = 0; p < NP; p++) sum += PX[p] + PY[p] + PZ[p];
  if (!Number.isFinite(sum)) { resetJelly(); }
  for (let s = 0; s < 2; s++) {
    const k = s === 0 ? NZ - 1 : 0;
    for (let j = 0; j < GJ; j++) {
      for (let i = 0; i < GI; i++) {
        const p = pIdx(j, i, k), v = gId(s, j, i) * 3;
        fleshPos[v] = PX[p]; fleshPos[v + 1] = PY[p]; fleshPos[v + 2] = PZ[p];
      }
    }
  }
  fleshGeo.attributes.position.needsUpdate = true;
  fleshGeo.computeVertexNormals();
  fillBand(pithPos, 0.016);
  pithGeo.attributes.position.needsUpdate = true;
  pithGeo.computeVertexNormals();
  fillBand(peelPos, 0.04);
  peelGeo.attributes.position.needsUpdate = true;
  peelGeo.computeVertexNormals();
  for (let b = 0; b < SEG; b++) {
    for (let i = 0; i <= NR; i++) {
      for (let k = 0; k < NZ; k++) {
        const p = pIdx(b * PER, i, k), v = ((b * GI + i) * NZ + k) * 3;
        membPos[v] = PX[p]; membPos[v + 1] = PY[p]; membPos[v + 2] = PZ[p];
      }
    }
  }
  membGeo.attributes.position.needsUpdate = true;
  membGeo.computeVertexNormals();
}

function resize() {
  renderer.setSize(window.innerWidth, window.innerHeight, false);
  placeCamera();
}
window.addEventListener('resize', resize);

let wantDemo = false;
try { wantDemo = location.hash === '#demo'; } catch (err) { wantDemo = false; }
demo.on = wantDemo;
if (demo.on) hintEl.textContent = 'Demo running. Touch the slice to play.';

resize();
resetJelly();

let last = performance.now();
let acc = 0;
function loop(now) {
  requestAnimationFrame(loop);
  const dtF = Math.min(0.05, Math.max(0, (now - last) / 1000));
  last = now;
  demoUpdate(dtF);
  updateSqueeze(dtF);
  acc += dtF;
  let steps = 0;
  while (acc >= FIX_DT && steps < 12) {
    physicsStep(FIX_DT);
    acc -= FIX_DT;
    steps++;
  }
  if (steps >= 12) acc = 0;
  updateDrops(dtF);
  syncMeshes();
  renderer.render(scene, camera);
}
requestAnimationFrame(loop);
})();
</script>
</body>
</html>