Skip to content
VibeCodeBench
Back to the app

The code

Jelly Cat by Gemini 4 Neon

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.)110.0 KB · 3,353 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.module.js
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Orange Jelly Cat</title>
<style>
  *, *::before, *::after {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    user-select: none;
    -webkit-user-select: none;
  }

  html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: radial-gradient(circle at 50% 35%, #fff8ef 0%, #f7e6d4 58%, #ead1b8 100%);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    color: #5b3218;
    touch-action: none;
  }

  #canvas-wrap {
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    touch-action: none;
  }

  canvas {
    display: block;
    width: 100%;
    height: 100%;
    touch-action: none;
    cursor: grab;
  }
  canvas.grabbing {
    cursor: grabbing;
  }

  /* HUD Layout */
  .hud-top {
    position: fixed;
    top: max(14px, env(safe-area-inset-top));
    left: max(14px, env(safe-area-inset-left));
    right: max(14px, env(safe-area-inset-right));
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 10px;
    pointer-events: none;
    z-index: 10;
  }

  .title-col {
    display: flex;
    flex-direction: column;
    gap: 6px;
    align-items: flex-start;
  }

  .brand-pill {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 14px;
    border-radius: 999px;
    background: rgba(255, 250, 243, 0.78);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border: 1px solid rgba(255, 168, 86, 0.35);
    box-shadow: 0 6px 20px rgba(154, 78, 22, 0.10);
    font-weight: 700;
    font-size: 15px;
    letter-spacing: 0.01em;
    color: #6b3512;
  }

  .brand-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: radial-gradient(circle at 32% 30%, #ffe6a8 0%, #ff9b2e 45%, #f05a08 100%);
    box-shadow: 0 0 8px rgba(255, 132, 24, 0.65);
    flex-shrink: 0;
  }

  .hint-pill {
    padding: 6px 12px;
    border-radius: 999px;
    background: rgba(255, 248, 238, 0.72);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 178, 108, 0.28);
    font-size: 12.5px;
    font-weight: 600;
    color: #8b5128;
    transition: opacity 0.45s ease, transform 0.45s ease;
    max-width: 260px;
    line-height: 1.3;
  }
  .hint-pill.hidden {
    opacity: 0;
    transform: translateY(-6px);
  }

  .top-right {
    display: flex;
    align-items: center;
    gap: 8px;
    pointer-events: auto;
  }

  .demo-badge {
    display: none;
    align-items: center;
    gap: 6px;
    padding: 9px 14px;
    border-radius: 999px;
    background: rgba(255, 138, 36, 0.90);
    color: #fffdf9;
    font-size: 13px;
    font-weight: 700;
    box-shadow: 0 6px 18px rgba(226, 98, 12, 0.28);
    pointer-events: none;
    white-space: nowrap;
  }
  .demo-badge.active {
    display: inline-flex;
  }
  .demo-pulse {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #fff9e6;
    animation: pulse 1.2s ease-in-out infinite;
  }
  @keyframes pulse {
    0%, 100% { transform: scale(0.8); opacity: 0.7; }
    50% { transform: scale(1.25); opacity: 1; }
  }

  .icon-btn {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    border: 1px solid rgba(255, 168, 86, 0.42);
    background: rgba(255, 250, 243, 0.84);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    box-shadow: 0 6px 20px rgba(154, 78, 22, 0.12);
    color: #7c3f14;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: transform 0.14s cubic-bezier(0.3, 1.5, 0.5, 1), background 0.15s ease;
    padding: 0;
  }
  .icon-btn:active {
    transform: scale(0.90);
  }
  .icon-btn.muted {
    color: #b58d70;
    background: rgba(255, 246, 236, 0.72);
  }

  /* Bottom Controls */
  .hud-bottom {
    position: fixed;
    left: max(12px, env(safe-area-inset-left));
    right: max(12px, env(safe-area-inset-right));
    bottom: max(14px, env(safe-area-inset-bottom));
    display: flex;
    justify-content: center;
    pointer-events: none;
    z-index: 10;
  }

  .dock {
    pointer-events: auto;
    width: 100%;
    max-width: 460px;
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 12px;
    border-radius: 26px;
    background: rgba(255, 250, 243, 0.82);
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    border: 1px solid rgba(255, 174, 96, 0.38);
    box-shadow: 0 12px 34px rgba(148, 72, 18, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.85);
  }

  .drop-btn {
    flex-shrink: 0;
    min-width: 104px;
    height: 54px;
    padding: 0 18px;
    border: none;
    border-radius: 18px;
    background: linear-gradient(180deg, #ffaa42 0%, #ff7a14 55%, #eb5e05 100%);
    color: #fffdf8;
    font-size: 16px;
    font-weight: 800;
    letter-spacing: 0.01em;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    cursor: pointer;
    box-shadow:
      0 7px 18px rgba(235, 96, 6, 0.34),
      inset 0 2px 3px rgba(255, 238, 198, 0.65),
      inset 0 -2px 4px rgba(176, 56, 0, 0.35);
    transition: transform 0.14s cubic-bezier(0.25, 1.8, 0.5, 1), filter 0.15s ease;
  }
  .drop-btn:active, .drop-btn.pressed {
    transform: scale(0.92, 0.86);
    filter: brightness(1.04);
  }

  .slider-panel {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 2px 6px 2px 2px;
  }

  .slider-labels {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    font-size: 12px;
    font-weight: 700;
    color: #8a4c20;
    gap: 6px;
  }
  .slider-labels .tag-mode {
    font-size: 11px;
    font-weight: 700;
    color: #d46312;
    background: rgba(255, 152, 56, 0.16);
    padding: 2px 7px;
    border-radius: 999px;
    white-space: nowrap;
  }

  .slider-wrap {
    position: relative;
    height: 34px;
    display: flex;
    align-items: center;
  }

  input[type="range"].jelly-slider {
    -webkit-appearance: none;
    appearance: none;
    width: 100%;
    height: 12px;
    border-radius: 999px;
    background: linear-gradient(90deg, #ffe0a8 0%, #ffa947 50%, #f06a0c 100%);
    box-shadow: inset 0 2px 4px rgba(140, 56, 4, 0.22);
    outline: none;
    margin: 0;
    cursor: pointer;
    touch-action: pan-x;
  }

  input[type="range"].jelly-slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: radial-gradient(circle at 34% 28%, #fff8e6 0%, #ffb752 40%, #f2680a 100%);
    border: 2.5px solid #fffdf8;
    box-shadow: 0 4px 12px rgba(196, 78, 8, 0.40);
    cursor: pointer;
    transition: transform 0.12s ease;
  }
  input[type="range"].jelly-slider:active::-webkit-slider-thumb {
    transform: scale(1.14);
  }

  input[type="range"].jelly-slider::-moz-range-thumb {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: radial-gradient(circle at 34% 28%, #fff8e6 0%, #ffb752 40%, #f2680a 100%);
    border: 2.5px solid #fffdf8;
    box-shadow: 0 4px 12px rgba(196, 78, 8, 0.40);
    cursor: pointer;
  }

  /* Demo Ghost Finger */
  #demo-cursor {
    position: fixed;
    left: 0;
    top: 0;
    width: 44px;
    height: 44px;
    margin-left: -22px;
    margin-top: -22px;
    border-radius: 50%;
    border: 3px solid rgba(255, 252, 245, 0.95);
    background: radial-gradient(circle at 35% 35%, rgba(255, 224, 168, 0.65), rgba(255, 134, 28, 0.42));
    box-shadow: 0 4px 18px rgba(212, 88, 10, 0.35), inset 0 0 8px rgba(255, 255, 255, 0.7);
    pointer-events: none;
    z-index: 20;
    opacity: 0;
    transform: translate3d(-100px, -100px, 0) scale(1);
    transition: opacity 0.2s ease;
  }
  #demo-cursor.down {
    background: radial-gradient(circle at 35% 35%, rgba(255, 240, 204, 0.85), rgba(255, 118, 16, 0.72));
    box-shadow: 0 2px 12px rgba(212, 88, 10, 0.50), 0 0 0 8px rgba(255, 152, 56, 0.20);
  }

  @media (max-width: 460px) {
    .dock {
      padding: 9px 10px;
      gap: 10px;
      border-radius: 22px;
    }
    .drop-btn {
      min-width: 90px;
      height: 50px;
      padding: 0 14px;
      font-size: 15px;
    }
    .slider-labels {
      font-size: 11px;
    }
    .slider-labels .tag-mode {
      display: none;
    }
    .hint-pill {
      font-size: 11.5px;
      max-width: 210px;
    }
  }
</style>
</head>
<body>
<div id="canvas-wrap"></div>

<div class="hud-top">
  <div class="title-col">
    <div class="brand-pill">
      <span class="brand-dot"></span>
      <span>Jelly Cat</span>
    </div>
    <div id="hint-pill" class="hint-pill">Poke, squish, pull ears &amp; tail, or rub head</div>
  </div>
  <div class="top-right">
    <div id="demo-badge" class="demo-badge">
      <span class="demo-pulse"></span>
      <span id="demo-label">Demo — tap to play</span>
    </div>
    <button id="mute-btn" class="icon-btn" type="button" aria-label="Toggle sound">
      <svg id="icon-sound-on" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
        <path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
        <path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
      </svg>
      <svg id="icon-sound-off" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="display:none">
        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
        <line x1="23" y1="9" x2="17" y2="15"></line>
        <line x1="17" y1="9" x2="23" y2="15"></line>
      </svg>
    </button>
  </div>
</div>

<div class="hud-bottom">
  <div class="dock">
    <button id="drop-btn" class="drop-btn" type="button">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round">
        <line x1="12" y1="4" x2="12" y2="16"></line>
        <polyline points="7 12 12 17 17 12"></polyline>
        <line x1="6" y1="20" x2="18" y2="20"></line>
      </svg>
      <span>Drop</span>
    </button>
    <div class="slider-panel">
      <div class="slider-labels">
        <span>Soft Pudding</span>
        <span id="firmness-tag" class="tag-mode">Wobbly Jelly</span>
        <span>Firm Gummy</span>
      </div>
      <div class="slider-wrap">
        <input id="firmness-slider" class="jelly-slider" type="range" min="0" max="100" value="40" aria-label="Jelly firmness from soft pudding to firm gummy">
      </div>
    </div>
  </div>
</div>

<div id="demo-cursor"></div>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';

// ============================================================================
// 1. MATH & SDF SCULPTING OF THE CHUBBY SITTING CAT
// ============================================================================
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
const lerp = (a, b, t) => a + (b - a) * t;
const smoothstep = (e0, e1, x) => {
  const t = clamp((x - e0) / (e1 - e0), 0, 1);
  return t * t * (3 - 2 * t);
};

function smin(a, b, k) {
  const h = Math.max(k - Math.abs(a - b), 0) / k;
  return Math.min(a, b) - h * h * k * 0.25;
}

function smax(a, b, k) {
  return -smin(-a, -b, k);
}

function sdEllipsoid(px, py, pz, rx, ry, rz) {
  const k0 = Math.hypot(px / rx, py / ry, pz / rz);
  if (k0 < 1e-6) return -Math.min(rx, ry, rz);
  const k1 = Math.hypot(px / (rx * rx), py / (ry * ry), pz / (rz * rz));
  return (k0 * (k0 - 1)) / k1;
}

function sdCapsuleTaper(px, py, pz, ax, ay, az, bx, by, bz, r1, r2) {
  const bax = bx - ax, bay = by - ay, baz = bz - az;
  const pax = px - ax, pay = py - ay, paz = pz - az;
  const len2 = bax * bax + bay * bay + baz * baz;
  const h = clamp((pax * bax + pay * bay + paz * baz) / len2, 0, 1);
  const dx = pax - bax * h;
  const dy = pay - bay * h;
  const dz = paz - baz * h;
  return Math.hypot(dx, dy, dz) - (r1 + (r2 - r1) * h);
}

// Curled tail spine polyline (wraps around cat's left / viewer's right +X side)
const TAIL_PTS = [
  [0.02, 0.22, -0.58, 0.155],
  [0.54, 0.18, -0.63, 0.140],
  [0.97, 0.18, -0.26, 0.128],
  [1.06, 0.25,  0.16, 0.122],
  [0.90, 0.40,  0.48, 0.120]
];

function evalTailDistAndT(px, py, pz) {
  let minD = 1e9;
  let bestT = 0;
  const segCount = TAIL_PTS.length - 1;
  for (let s = 0; s < segCount; s++) {
    const a = TAIL_PTS[s], b = TAIL_PTS[s + 1];
    const bax = b[0] - a[0], bay = b[1] - a[1], baz = b[2] - a[2];
    const pax = px - a[0], pay = py - a[1], paz = pz - a[2];
    const len2 = bax * bax + bay * bay + baz * baz;
    const h = clamp((pax * bax + pay * bay + paz * baz) / len2, 0, 1);
    const dx = pax - bax * h, dy = pay - bay * h, dz = paz - baz * h;
    const r = a[3] + (b[3] - a[3]) * h;
    const d = Math.hypot(dx, dy, dz) - r;
    if (d < minD) {
      minD = d;
      bestT = (s + h) / segCount;
    }
  }
  return { d: minD, t: bestT };
}

function catSDF(x, y, z) {
  const ax = Math.abs(x);

  // Chubby seated lower belly & hips
  let d = sdEllipsoid(x, y - 0.45, z + 0.02, 0.74, 0.50, 0.68);

  // Plump upper chest/shoulders
  const chest = sdEllipsoid(x, y - 0.87, z - 0.02, 0.58, 0.44, 0.54);
  d = smin(d, chest, 0.24);

  // Cute round front tummy bulge
  const tummy = sdEllipsoid(x, y - 0.37, z - 0.24, 0.44, 0.36, 0.42);
  d = smin(d, tummy, 0.25);

  // Seated tucked hind haunches (symmetric)
  const haunch = sdEllipsoid(ax - 0.47, y - 0.31, z + 0.10, 0.34, 0.30, 0.41);
  d = smin(d, haunch, 0.16);

  // Chubby round head nestled snugly on shoulders
  const head = sdEllipsoid(x, y - 1.32, z - 0.12, 0.56, 0.47, 0.50);
  d = smin(d, head, 0.19);

  // Puffy pullable cheeks
  const cheeks = sdEllipsoid(ax - 0.37, y - 1.19, z - 0.28, 0.265, 0.215, 0.245);
  d = smin(d, cheeks, 0.14);

  // Gentle cute muzzle puff
  const muzzle = sdEllipsoid(x, y - 1.18, z - 0.47, 0.21, 0.135, 0.165);
  d = smin(d, muzzle, 0.11);

  // Rounded triangular cat ears (flattened slightly front-to-back)
  const earZ = (z - 0.09) * 1.42 + 0.09;
  let ear = sdCapsuleTaper(ax, y, earZ, 0.31, 1.56, 0.09, 0.45, 1.95, 0.10, 0.215, 0.068) / 1.42;
  // Subtle cute inner-ear dimple on front
  const earHollow = sdEllipsoid(ax - 0.38, y - 1.72, z - 0.225, 0.088, 0.125, 0.065);
  ear = smax(ear, -earHollow, 0.045);
  d = smin(d, ear, 0.11);

  // Chubby stubby front paws resting side-by-side
  const paw = sdEllipsoid(ax - 0.23, y - 0.145, z - 0.61, 0.165, 0.135, 0.205);
  d = smin(d, paw, 0.095);

  // Curled chubby tail
  const tailD = evalTailDistAndT(x, y, z).d;
  d = smin(d, tailD, 0.12);

  // Smooth flat gelatin bottom sitting on the plate at y = 0 with a soft meniscus fillet
  d = smax(d, -y, 0.072);

  return d;
}

function catGrad(x, y, z, out) {
  const e = 0.0025;
  const gx = catSDF(x + e, y, z) - catSDF(x - e, y, z);
  const gy = catSDF(x, y + e, z) - catSDF(x, y - e, z);
  const gz = catSDF(x, y, z + e) - catSDF(x, y, z - e);
  const len = Math.hypot(gx, gy, gz) || 1;
  out[0] = gx / len;
  out[1] = gy / len;
  out[2] = gz / len;
  return len / (2 * e);
}

// Find exact front face surface point at (x, y) by marching inward from +Z
function findFaceSurface(x, y) {
  let z = 1.15;
  let prevZ = z;
  let prevD = catSDF(x, y, z);
  for (let i = 0; i < 120; i++) {
    z -= 0.012;
    const d = catSDF(x, y, z);
    if (d <= 0) {
      let lo = z, hi = prevZ;
      for (let b = 0; b < 10; b++) {
        const mid = 0.5 * (lo + hi);
        if (catSDF(x, y, mid) <= 0) lo = mid;
        else hi = mid;
      }
      const fz = 0.5 * (lo + hi);
      const n = [0, 0, 1];
      catGrad(x, y, fz, n);
      return { x, y, z: fz, nx: n[0], ny: n[1], nz: n[2] };
    }
    prevZ = z;
    prevD = d;
  }
  return { x, y, z: 0.58, nx: 0, ny: 0, nz: 1 };
}

// ============================================================================
// 2. SURFACE NETS WATER-TIGHT MESH GENERATOR + PART WEIGHTS
// ============================================================================
function computePartWeights(x, y, z) {
  // Left ear (+X), Right ear (-X)
  const earY = smoothstep(1.48, 1.82, y);
  const wEarL = earY * smoothstep(0.10, 0.30, x) * Math.exp(-Math.pow((z - 0.10) / 0.34, 2));
  const wEarR = earY * smoothstep(0.10, 0.30, -x) * Math.exp(-Math.pow((z - 0.10) / 0.34, 2));

  // Left cheek (+X), Right cheek (-X)
  const dCL2 = (x - 0.43) ** 2 + (y - 1.18) ** 2 + (z - 0.32) ** 2;
  const wCheekL = Math.exp(-dCL2 / (0.29 * 0.29)) * smoothstep(0.06, 0.24, x);
  const dCR2 = (x + 0.43) ** 2 + (y - 1.18) ** 2 + (z - 0.32) ** 2;
  const wCheekR = Math.exp(-dCR2 / (0.29 * 0.29)) * smoothstep(0.06, 0.24, -x);

  // Curled tail
  const tailInfo = evalTailDistAndT(x, y, z);
  const nearTail = Math.exp(-Math.pow(Math.max(0, tailInfo.d) / 0.14, 2));
  const wTail = nearTail * smoothstep(0.04, 0.28, tailInfo.t) * (0.25 + 0.75 * tailInfo.t);

  // Head secondary lag weight
  const wHead = smoothstep(0.82, 1.32, y);

  // Base plate anchor (0 at plate contact, 1 above)
  const wBase = smoothstep(0.0, 0.18, y);

  // Thinness heuristic for sunlit translucency (ears, tail, paws, cheeks glow extra!)
  const thinEar = Math.max(wEarL, wEarR) * 0.95;
  const thinTail = wTail * 0.85;
  const thinPaw = Math.exp(-((Math.abs(x) - 0.23) ** 2 + (y - 0.14) ** 2 + (z - 0.62) ** 2) / 0.09) * 0.55;
  const thinCheek = Math.max(wCheekL, wCheekR) * 0.42;
  const thinness = clamp(Math.max(thinEar, thinTail, thinPaw, thinCheek), 0, 1);

  return { wEarL, wEarR, wCheekL, wCheekR, wTail, wHead, wBase, thinness };
}

function buildJellyCatGeometry() {
  const H = 0.048;
  const XMIN = -1.25, YMIN = -0.14, ZMIN = -0.96;
  const NX = 57, NY = 50, NZ = 44;
  const total = NX * NY * NZ;
  const field = new Float32Array(total);
  const idx = (i, j, k) => i + NX * (j + NY * k);

  for (let k = 0; k < NZ; k++) {
    const z = ZMIN + k * H;
    for (let j = 0; j < NY; j++) {
      const y = YMIN + j * H;
      const base = NX * (j + NY * k);
      for (let i = 0; i < NX; i++) {
        field[base + i] = catSDF(XMIN + i * H, y, z);
      }
    }
  }

  const CUBE_EDGES = [
    [0, 1], [2, 3], [4, 5], [6, 7],
    [0, 2], [1, 3], [4, 6], [5, 7],
    [0, 4], [1, 5], [2, 6], [3, 7]
  ];
  const cVal = new Float32Array(8);
  const cellVert = new Int32Array(total);
  cellVert.fill(-1);
  const verts = [];

  for (let k = 0; k < NZ - 1; k++) {
    for (let j = 0; j < NY - 1; j++) {
      for (let i = 0; i < NX - 1; i++) {
        let mask = 0;
        for (let c = 0; c < 8; c++) {
          const v = field[idx(i + (c & 1), j + ((c >> 1) & 1), k + ((c >> 2) & 1))];
          cVal[c] = v;
          if (v < 0) mask |= 1 << c;
        }
        if (mask === 0 || mask === 255) continue;

        let sx = 0, sy = 0, sz = 0, cnt = 0;
        for (let e = 0; e < 12; e++) {
          const a = CUBE_EDGES[e][0], b = CUBE_EDGES[e][1];
          const va = cVal[a], vb = cVal[b];
          if ((va < 0) !== (vb < 0)) {
            const t = clamp(va / (va - vb), 0.01, 0.99);
            const ax = a & 1, ay = (a >> 1) & 1, az = (a >> 2) & 1;
            const bx = b & 1, by = (b >> 1) & 1, bz = (b >> 2) & 1;
            sx += ax + t * (bx - ax);
            sy += ay + t * (by - ay);
            sz += az + t * (bz - az);
            cnt++;
          }
        }
        const vi = verts.length / 3;
        cellVert[idx(i, j, k)] = vi;
        verts.push(
          XMIN + (i + sx / cnt) * H,
          YMIN + (j + sy / cnt) * H,
          ZMIN + (k + sz / cnt) * H
        );
      }
    }
  }

  const indices = [];
  const quadEdges = [];

  function emitQuad(a, b, c, d, flip) {
    if (a < 0 || b < 0 || c < 0 || d < 0) return;
    quadEdges.push(a, b, b, c, c, d, d, a);
    // Split along shorter diagonal for cleaner triangles
    const dax = verts[a * 3] - verts[c * 3], day = verts[a * 3 + 1] - verts[c * 3 + 1], daz = verts[a * 3 + 2] - verts[c * 3 + 2];
    const dbx = verts[b * 3] - verts[d * 3], dby = verts[b * 3 + 1] - verts[d * 3 + 1], dbz = verts[b * 3 + 2] - verts[d * 3 + 2];
    const diagAC = dax * dax + day * day + daz * daz;
    const diagBD = dbx * dbx + dby * dby + dbz * dbz;

    if (!flip) {
      if (diagAC <= diagBD) {
        indices.push(a, b, c, a, c, d);
      } else {
        indices.push(a, b, d, b, c, d);
      }
    } else {
      if (diagAC <= diagBD) {
        indices.push(a, c, b, a, d, c);
      } else {
        indices.push(a, d, b, b, d, c);
      }
    }
  }

  for (let k = 1; k < NZ - 1; k++) {
    for (let j = 1; j < NY - 1; j++) {
      for (let i = 1; i < NX - 1; i++) {
        const s0 = field[idx(i, j, k)] < 0;

        // X edge
        const sx = field[idx(i + 1, j, k)] < 0;
        if (s0 !== sx) {
          emitQuad(
            cellVert[idx(i, j - 1, k - 1)],
            cellVert[idx(i, j,     k - 1)],
            cellVert[idx(i, j,     k    )],
            cellVert[idx(i, j - 1, k    )],
            !s0
          );
        }

        // Y edge
        const sy = field[idx(i, j + 1, k)] < 0;
        if (s0 !== sy) {
          emitQuad(
            cellVert[idx(i - 1, j, k - 1)],
            cellVert[idx(i - 1, j, k    )],
            cellVert[idx(i,     j, k    )],
            cellVert[idx(i,     j, k - 1)],
            !s0
          );
        }

        // Z edge
        const sz = field[idx(i, j, k + 1)] < 0;
        if (s0 !== sz) {
          emitQuad(
            cellVert[idx(i - 1, j - 1, k)],
            cellVert[idx(i,     j - 1, k)],
            cellVert[idx(i,     j,     k)],
            cellVert[idx(i - 1, j,     k)],
            !s0
          );
        }
      }
    }
  }

  const vCount = verts.length / 3;
  const restPos = new Float32Array(verts);
  const smoothAcc = new Float32Array(vCount * 3);
  const smoothCnt = new Uint16Array(vCount);
  const gTmp = [0, 0, 0];

  // 2 passes of gentle Laplacian relaxation + exact Newton projection onto SDF=0
  for (let pass = 0; pass < 2; pass++) {
    smoothAcc.fill(0);
    smoothCnt.fill(0);
    for (let e = 0; e < quadEdges.length; e += 2) {
      const a = quadEdges[e], b = quadEdges[e + 1];
      smoothAcc[a * 3]     += restPos[b * 3];
      smoothAcc[a * 3 + 1] += restPos[b * 3 + 1];
      smoothAcc[a * 3 + 2] += restPos[b * 3 + 2];
      smoothCnt[a]++;
      smoothAcc[b * 3]     += restPos[a * 3];
      smoothAcc[b * 3 + 1] += restPos[a * 3 + 1];
      smoothAcc[b * 3 + 2] += restPos[a * 3 + 2];
      smoothCnt[b]++;
    }
    for (let i = 0; i < vCount; i++) {
      const c = smoothCnt[i];
      if (c > 0) {
        restPos[i * 3]     = lerp(restPos[i * 3],     smoothAcc[i * 3]     / c, 0.36);
        restPos[i * 3 + 1] = lerp(restPos[i * 3 + 1], smoothAcc[i * 3 + 1] / c, 0.36);
        restPos[i * 3 + 2] = lerp(restPos[i * 3 + 2], smoothAcc[i * 3 + 2] / c, 0.36);
      }
      // Project onto exact SDF isosurface
      for (let step = 0; step < 2; step++) {
        const px = restPos[i * 3], py = restPos[i * 3 + 1], pz = restPos[i * 3 + 2];
        const f = catSDF(px, py, pz);
        catGrad(px, py, pz, gTmp);
        const move = clamp(f, -0.35 * H, 0.35 * H);
        restPos[i * 3]     = px - gTmp[0] * move;
        restPos[i * 3 + 1] = Math.max(0, py - gTmp[1] * move);
        restPos[i * 3 + 2] = pz - gTmp[2] * move;
      }
    }
  }

  // Precompute part weights & thinness per vertex
  const wEarL = new Float32Array(vCount);
  const wEarR = new Float32Array(vCount);
  const wCheekL = new Float32Array(vCount);
  const wCheekR = new Float32Array(vCount);
  const wTail = new Float32Array(vCount);
  const wHead = new Float32Array(vCount);
  const wBase = new Float32Array(vCount);
  const thinAttr = new Float32Array(vCount);

  for (let i = 0; i < vCount; i++) {
    const w = computePartWeights(restPos[i * 3], restPos[i * 3 + 1], restPos[i * 3 + 2]);
    wEarL[i] = w.wEarL;
    wEarR[i] = w.wEarR;
    wCheekL[i] = w.wCheekL;
    wCheekR[i] = w.wCheekR;
    wTail[i] = w.wTail;
    wHead[i] = w.wHead;
    wBase[i] = w.wBase;
    thinAttr[i] = w.thinness;
  }

  const posArr = new Float32Array(restPos);
  const normArr = new Float32Array(vCount * 3);
  const idxArr = new Uint32Array(indices);

  const geo = new THREE.BufferGeometry();
  const posBuffer = new THREE.BufferAttribute(posArr, 3);
  posBuffer.setUsage(THREE.DynamicDrawUsage);
  const normBuffer = new THREE.BufferAttribute(normArr, 3);
  normBuffer.setUsage(THREE.DynamicDrawUsage);

  geo.setAttribute('position', posBuffer);
  geo.setAttribute('normal', normBuffer);
  geo.setAttribute('aThinness', new THREE.BufferAttribute(thinAttr, 1));
  geo.setIndex(new THREE.BufferAttribute(idxArr, 1));
  // Generous static bounding sphere so raycaster always hits stretched/dropped jelly
  geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 1.3, 0), 5.0);

  return {
    geo, vCount, restPos, posArr, normArr, idxArr, posBuffer, normBuffer,
    wEarL, wEarR, wCheekL, wCheekR, wTail, wHead, wBase
  };
}

// ============================================================================
// 3. SYNTHESIZED WET JELLY & PURR AUDIO ENGINE (WEB AUDIO API)
// ============================================================================
class JellyAudio {
  constructor() {
    this.ctx = null;
    this.master = null;
    this.noiseBuf = null;
    this.muted = false;
    this.ready = false;
    this.lastStretchTime = 0;
    this.purrGain = null;
    this.purrFilter = null;
    this.purrBreathPhase = 0;
  }

  unlock() {
    if (this.ready) {
      if (this.ctx && this.ctx.state === 'suspended') {
        this.ctx.resume().catch(() => {});
      }
      return;
    }
    try {
      const AC = window.AudioContext || window.webkitAudioContext;
      if (!AC) return;
      this.ctx = new AC();
      this.master = this.ctx.createGain();
      this.master.gain.value = this.muted ? 0 : 0.72;
      this.master.connect(this.ctx.destination);

      // Shared white noise buffer for wet plips, squelches & purr breath
      const len = this.ctx.sampleRate * 1.5;
      this.noiseBuf = this.ctx.createBuffer(1, len, this.ctx.sampleRate);
      const data = this.noiseBuf.getChannelData(0);
      for (let i = 0; i < len; i++) data[i] = Math.random() * 2 - 1;

      // Continuous velvety cat purr synth (26Hz pulsed rumble + warm octave + soft breath)
      this.purrGain = this.ctx.createGain();
      this.purrGain.gain.value = 0.0001;
      this.purrGain.connect(this.master);

      this.purrFilter = this.ctx.createBiquadFilter();
      this.purrFilter.type = 'lowpass';
      this.purrFilter.frequency.value = 165;
      this.purrFilter.Q.value = 2.6;
      this.purrFilter.connect(this.purrGain);

      const pOsc1 = this.ctx.createOscillator();
      pOsc1.type = 'sawtooth';
      pOsc1.frequency.value = 25.5;
      const g1 = this.ctx.createGain();
      g1.gain.value = 0.42;
      pOsc1.connect(g1).connect(this.purrFilter);
      pOsc1.start();

      const pOsc2 = this.ctx.createOscillator();
      pOsc2.type = 'triangle';
      pOsc2.frequency.value = 51.0;
      const g2 = this.ctx.createGain();
      g2.gain.value = 0.30;
      pOsc2.connect(g2).connect(this.purrFilter);
      pOsc2.start();

      // Soft rhythmic purr breath noise modulated at 25.5 Hz
      const breathSrc = this.ctx.createBufferSource();
      breathSrc.buffer = this.noiseBuf;
      breathSrc.loop = true;
      const breathBP = this.ctx.createBiquadFilter();
      breathBP.type = 'bandpass';
      breathBP.frequency.value = 340;
      breathBP.Q.value = 2.0;
      const breathModGain = this.ctx.createGain();
      breathModGain.gain.value = 0.05;
      const breathLfo = this.ctx.createOscillator();
      breathLfo.frequency.value = 25.5;
      const breathLfoAmp = this.ctx.createGain();
      breathLfoAmp.gain.value = 0.045;
      breathLfo.connect(breathLfoAmp).connect(breathModGain.gain);
      breathSrc.connect(breathBP).connect(breathModGain).connect(this.purrGain);
      breathSrc.start();
      breathLfo.start();

      this.ready = true;
      if (this.ctx.state === 'suspended') {
        this.ctx.resume().catch(() => {});
      }
    } catch (_) {}
  }

  setMuted(m) {
    this.muted = m;
    if (this.master && this.ctx) {
      this.master.gain.setTargetAtTime(m ? 0 : 0.72, this.ctx.currentTime, 0.03);
    }
  }

  updatePurr(level, dt) {
    if (!this.ready || !this.purrGain || !this.ctx || this.ctx.state !== 'running') return;
    this.purrBreathPhase += dt * 2.8;
    const breath = 0.62 + 0.38 * Math.sin(this.purrBreathPhase);
    const target = this.muted ? 0.0001 : Math.max(0.0001, level * 0.34 * breath);
    this.purrGain.gain.setTargetAtTime(target, this.ctx.currentTime, 0.08);
    this.purrFilter.frequency.setTargetAtTime(140 + 55 * breath, this.ctx.currentTime, 0.08);
  }

  playPoke(intensity = 0.7, firmness = 0.4) {
    if (!this.ready || this.muted || this.ctx.state !== 'running') return;
    const t = this.ctx.currentTime;
    const vol = clamp(intensity, 0.2, 1.0);

    // Rising wet bloop cavity chirp
    const osc = this.ctx.createOscillator();
    const g = this.ctx.createGain();
    osc.type = 'sine';
    const f0 = 175 + firmness * 170 + (Math.random() - 0.5) * 28;
    const f1 = f0 * (1.85 + firmness * 0.45);
    osc.frequency.setValueAtTime(f0, t);
    osc.frequency.exponentialRampToValueAtTime(f1, t + 0.055);
    osc.frequency.exponentialRampToValueAtTime(f0 * 1.15, t + 0.12);

    g.gain.setValueAtTime(0.0001, t);
    g.gain.linearRampToValueAtTime(0.20 * vol, t + 0.009);
    g.gain.exponentialRampToValueAtTime(0.0001, t + 0.13);

    osc.connect(g).connect(this.master);
    osc.start(t);
    osc.stop(t + 0.14);

    // Tiny wet finger-surface plip click
    const nSrc = this.ctx.createBufferSource();
    nSrc.buffer = this.noiseBuf;
    const bp = this.ctx.createBiquadFilter();
    bp.type = 'bandpass';
    bp.frequency.setValueAtTime(1600 + firmness * 1400, t);
    bp.frequency.exponentialRampToValueAtTime(3400 + firmness * 1200, t + 0.025);
    bp.Q.value = 6.0;
    const ng = this.ctx.createGain();
    ng.gain.setValueAtTime(0.0001, t);
    ng.gain.linearRampToValueAtTime(0.11 * vol, t + 0.004);
    ng.gain.exponentialRampToValueAtTime(0.0001, t + 0.032);
    nSrc.connect(bp).connect(ng).connect(this.master);
    nSrc.start(t, Math.random() * 0.8, 0.04);
  }

  playStretch(speed = 0.5, firmness = 0.4) {
    if (!this.ready || this.muted || this.ctx.state !== 'running') return;
    const now = performance.now();
    if (now - this.lastStretchTime < 95) return;
    this.lastStretchTime = now;

    const t = this.ctx.currentTime;
    const vol = clamp(speed, 0.15, 0.85) * 0.11;

    // Small wet gelatin squelch
    const nSrc = this.ctx.createBufferSource();
    nSrc.buffer = this.noiseBuf;
    const bp = this.ctx.createBiquadFilter();
    bp.type = 'bandpass';
    const fStart = 900 + firmness * 900 + Math.random() * 400;
    bp.frequency.setValueAtTime(fStart, t);
    bp.frequency.exponentialRampToValueAtTime(fStart * 1.7, t + 0.055);
    bp.Q.value = 8.5;
    const g = this.ctx.createGain();
    g.gain.setValueAtTime(0.0001, t);
    g.gain.linearRampToValueAtTime(vol, t + 0.012);
    g.gain.exponentialRampToValueAtTime(0.0001, t + 0.068);
    nSrc.connect(bp).connect(g).connect(this.master);
    nSrc.start(t, Math.random() * 0.9, 0.075);

    // Subtle tiny micro-bubble tone
    const osc = this.ctx.createOscillator();
    const og = this.ctx.createGain();
    osc.type = 'sine';
    const bf = 260 + firmness * 260 + Math.random() * 140;
    osc.frequency.setValueAtTime(bf, t);
    osc.frequency.exponentialRampToValueAtTime(bf * 1.45, t + 0.045);
    og.gain.setValueAtTime(0.0001, t);
    og.gain.linearRampToValueAtTime(vol * 0.55, t + 0.008);
    og.gain.exponentialRampToValueAtTime(0.0001, t + 0.055);
    osc.connect(og).connect(this.master);
    osc.start(t);
    osc.stop(t + 0.06);
  }

  playReleaseBoing(intensity = 0.7, firmness = 0.4) {
    if (!this.ready || this.muted || this.ctx.state !== 'running') return;
    const t = this.ctx.currentTime;
    const vol = clamp(intensity, 0.2, 1.0);
    const dur = lerp(0.46, 0.24, firmness);

    const carrier = this.ctx.createOscillator();
    const lfo = this.ctx.createOscillator();
    const lfoGain = this.ctx.createGain();
    const outGain = this.ctx.createGain();
    const lp = this.ctx.createBiquadFilter();

    const baseFreq = 105 + firmness * 135;
    const wobRate = 8.5 + firmness * 13;

    carrier.type = 'sine';
    carrier.frequency.setValueAtTime(baseFreq * 1.35, t);
    carrier.frequency.exponentialRampToValueAtTime(baseFreq, t + dur);

    lfo.type = 'sine';
    lfo.frequency.setValueAtTime(wobRate, t);
    lfoGain.gain.setValueAtTime(baseFreq * 0.36 * vol, t);
    lfoGain.gain.exponentialRampToValueAtTime(2.0, t + dur);

    lp.type = 'lowpass';
    lp.frequency.value = 950 + firmness * 800;

    outGain.gain.setValueAtTime(0.0001, t);
    outGain.gain.linearRampToValueAtTime(0.18 * vol, t + 0.015);
    outGain.gain.exponentialRampToValueAtTime(0.0001, t + dur);

    lfo.connect(lfoGain).connect(carrier.frequency);
    carrier.connect(lp).connect(outGain).connect(this.master);

    carrier.start(t);
    lfo.start(t);
    carrier.stop(t + dur + 0.02);
    lfo.stop(t + dur + 0.02);

    // Quick wet release schlup
    const nSrc = this.ctx.createBufferSource();
    nSrc.buffer = this.noiseBuf;
    const bp = this.ctx.createBiquadFilter();
    bp.type = 'bandpass';
    bp.frequency.setValueAtTime(2100 + firmness * 900, t);
    bp.frequency.exponentialRampToValueAtTime(750 + firmness * 450, t + 0.045);
    bp.Q.value = 5.5;
    const ng = this.ctx.createGain();
    ng.gain.setValueAtTime(0.0001, t);
    ng.gain.linearRampToValueAtTime(0.09 * vol, t + 0.006);
    ng.gain.exponentialRampToValueAtTime(0.0001, t + 0.055);
    nSrc.connect(bp).connect(ng).connect(this.master);
    nSrc.start(t, Math.random() * 0.8, 0.06);
  }

  playLift() {
    if (!this.ready || this.muted || this.ctx.state !== 'running') return;
    const t = this.ctx.currentTime;
    const osc = this.ctx.createOscillator();
    const g = this.ctx.createGain();
    osc.type = 'sine';
    osc.frequency.setValueAtTime(220, t);
    osc.frequency.exponentialRampToValueAtTime(520, t + 0.16);
    g.gain.setValueAtTime(0.0001, t);
    g.gain.linearRampToValueAtTime(0.10, t + 0.03);
    g.gain.exponentialRampToValueAtTime(0.0001, t + 0.18);
    osc.connect(g).connect(this.master);
    osc.start(t);
    osc.stop(t + 0.19);
  }

  playDropImpact(firmness = 0.4) {
    if (!this.ready || this.muted || this.ctx.state !== 'running') return;
    const t = this.ctx.currentTime;

    // 1. Soft chubby thump-splot
    const thump = this.ctx.createOscillator();
    const tg = this.ctx.createGain();
    thump.type = 'sine';
    thump.frequency.setValueAtTime(125 + firmness * 55, t);
    thump.frequency.exponentialRampToValueAtTime(46 + firmness * 20, t + 0.15);
    tg.gain.setValueAtTime(0.0001, t);
    tg.gain.linearRampToValueAtTime(0.32, t + 0.008);
    tg.gain.exponentialRampToValueAtTime(0.0001, t + 0.18);
    thump.connect(tg).connect(this.master);
    thump.start(t);
    thump.stop(t + 0.19);

    // 2. Wet porcelain-gelatin suction splat
    for (let k = 0; k < 2; k++) {
      const nSrc = this.ctx.createBufferSource();
      nSrc.buffer = this.noiseBuf;
      const bp = this.ctx.createBiquadFilter();
      bp.type = 'bandpass';
      const f0 = k === 0 ? 780 + firmness * 450 : 2100 + firmness * 900;
      bp.frequency.setValueAtTime(f0, t + k * 0.015);
      bp.frequency.exponentialRampToValueAtTime(f0 * 0.48, t + 0.075 + k * 0.02);
      bp.Q.value = k === 0 ? 4.2 : 6.5;
      const ng = this.ctx.createGain();
      ng.gain.setValueAtTime(0.0001, t + k * 0.015);
      ng.gain.linearRampToValueAtTime(k === 0 ? 0.17 : 0.11, t + 0.01 + k * 0.015);
      ng.gain.exponentialRampToValueAtTime(0.0001, t + 0.085 + k * 0.02);
      nSrc.connect(bp).connect(ng).connect(this.master);
      nSrc.start(t + k * 0.015, Math.random() * 0.7, 0.11);
    }

    // 3. Big gelatinous wub-wub-wub wobble tail
    const dur = lerp(0.75, 0.36, firmness);
    const wob = this.ctx.createOscillator();
    const lfo = this.ctx.createOscillator();
    const lfoG = this.ctx.createGain();
    const wg = this.ctx.createGain();
    const baseF = 88 + firmness * 115;
    wob.type = 'sine';
    wob.frequency.setValueAtTime(baseF * 1.4, t + 0.02);
    wob.frequency.exponentialRampToValueAtTime(baseF, t + dur);
    lfo.frequency.value = 7.0 + firmness * 13.5;
    lfoG.gain.setValueAtTime(baseF * 0.42, t + 0.02);
    lfoG.gain.exponentialRampToValueAtTime(2.0, t + dur);
    wg.gain.setValueAtTime(0.0001, t + 0.01);
    wg.gain.linearRampToValueAtTime(0.22, t + 0.035);
    wg.gain.exponentialRampToValueAtTime(0.0001, t + dur);
    lfo.connect(lfoG).connect(wob.frequency);
    wob.connect(wg).connect(this.master);
    wob.start(t + 0.01);
    lfo.start(t + 0.01);
    wob.stop(t + dur + 0.03);
    lfo.stop(t + dur + 0.03);

    // 4. Two tiny playful delayed wet droplet plips
    for (let d = 0; d < 2; d++) {
      const dt0 = t + 0.07 + d * 0.075 + Math.random() * 0.03;
      const p = this.ctx.createOscillator();
      const pg = this.ctx.createGain();
      p.type = 'sine';
      const pf = 460 + d * 210 + firmness * 260;
      p.frequency.setValueAtTime(pf, dt0);
      p.frequency.exponentialRampToValueAtTime(pf * 1.9, dt0 + 0.035);
      pg.gain.setValueAtTime(0.0001, dt0);
      pg.gain.linearRampToValueAtTime(0.065, dt0 + 0.005);
      pg.gain.exponentialRampToValueAtTime(0.0001, dt0 + 0.045);
      p.connect(pg).connect(this.master);
      p.start(dt0);
      p.stop(dt0 + 0.05);
    }
  }
}

const audio = new JellyAudio();

// ============================================================================
// 4. THREE.JS SCENE, STUDIO ENVMAP, LIGHTING, TABLE & PORCELAIN PLATE
// ============================================================================
const wrap = document.getElementById('canvas-wrap');
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.06;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
if ('transmissionResolutionScale' in renderer) {
  renderer.transmissionResolutionScale = 0.75;
}
wrap.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color('#f7e8d7');

const camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.1, 40);

// Procedural Sunlit Café Studio Environment Map for ultra-glossy jelly highlights
function buildStudioEnvMap() {
  const pmrem = new THREE.PMREMGenerator(renderer);
  const envScene = new THREE.Scene();

  // Warm studio dome
  const domeGeo = new THREE.SphereGeometry(18, 24, 16);
  const domeMat = new THREE.ShaderMaterial({
    side: THREE.BackSide,
    vertexShader: `
      varying vec3 vPos;
      void main() {
        vPos = normalize(position);
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      }
    `,
    fragmentShader: `
      varying vec3 vPos;
      void main() {
        float y = vPos.y;
        vec3 topCol = vec3(1.0, 0.98, 0.94);
        vec3 midCol = vec3(0.97, 0.89, 0.80);
        vec3 botCol = vec3(0.84, 0.70, 0.56);
        vec3 col = y > 0.0 ? mix(midCol, topCol, pow(y, 0.7)) : mix(midCol, botCol, pow(-y, 0.6));
        gl_FragColor = vec4(col, 1.0);
      }
    `
  });
  envScene.add(new THREE.Mesh(domeGeo, domeMat));

  // Softboxes & crisp sunlit window catchlight strips
  const addPanel = (w, h, color, intensity, pos, lookAt) => {
    const m = new THREE.Mesh(
      new THREE.PlaneGeometry(w, h),
      new THREE.MeshBasicMaterial({ color: new THREE.Color(color).multiplyScalar(intensity), side: THREE.DoubleSide })
    );
    m.position.set(pos[0], pos[1], pos[2]);
    m.lookAt(lookAt[0], lookAt[1], lookAt[2]);
    envScene.add(m);
  };

  // Big primary sunlit window upper-front-left
  addPanel(7.5, 6.0, '#fffdf8', 2.8, [-6.5, 7.2, 5.5], [0, 1, 0]);
  // Crisp narrow specular ribbon for wet jelly gleam
  addPanel(1.8, 5.5, '#ffffff', 4.5, [-3.8, 5.8, 7.2], [0, 1.1, 0]);
  // Warm golden backlight softbox behind-right
  addPanel(8.0, 5.5, '#ffe6bd', 2.4, [6.2, 5.5, -6.5], [0, 1, 0]);
  // Gentle fill reflection on right
  addPanel(5.0, 4.0, '#fff2df', 1.6, [7.5, 3.2, 3.5], [0, 1, 0]);
  // Soft overhead bounce
  addPanel(6.5, 6.5, '#fff9ef', 1.5, [0, 10.5, 0], [0, 0, 0]);

  const rt = pmrem.fromScene(envScene, 0.035);
  pmrem.dispose();
  domeGeo.dispose();
  domeMat.dispose();
  return rt.texture;
}

scene.environment = buildStudioEnvMap();

// Lights
const hemiLight = new THREE.HemisphereLight('#fff8ee', '#e6c3a3', 1.05);
scene.add(hemiLight);

const keyLight = new THREE.DirectionalLight('#fff5e6', 2.35);
keyLight.position.set(-4.2, 7.0, 4.6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.near = 1.0;
keyLight.shadow.camera.far = 18.0;
keyLight.shadow.camera.left = -3.4;
keyLight.shadow.camera.right = 3.4;
keyLight.shadow.camera.top = 3.8;
keyLight.shadow.camera.bottom = -2.8;
keyLight.shadow.bias = -0.0005;
keyLight.shadow.radius = 4;
scene.add(keyLight);

const rimLight = new THREE.DirectionalLight('#ffcb82', 2.1);
rimLight.position.set(4.5, 4.2, -5.2);
scene.add(rimLight);

const fillLight = new THREE.DirectionalLight('#ffe8cf', 0.85);
fillLight.position.set(4.0, 2.5, 4.0);
scene.add(fillLight);

// Cozy sunlit café tabletop
function createTabletopTexture() {
  const c = document.createElement('canvas');
  c.width = 512;
  c.height = 512;
  const g = c.getContext('2d');
  const grad = g.createRadialGradient(256, 256, 40, 256, 256, 256);
  grad.addColorStop(0, '#f5e2cc');
  grad.addColorStop(0.65, '#edd5bc');
  grad.addColorStop(1, '#e1c3a5');
  g.fillStyle = grad;
  g.fillRect(0, 0, 512, 512);

  // Subtle warm wood/linen weave grain
  g.globalAlpha = 0.045;
  for (let y = 0; y < 512; y += 3) {
    g.fillStyle = y % 6 === 0 ? '#a87246' : '#fff7eb';
    g.fillRect(0, y, 512, 1.5);
  }
  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  return tex;
}

const tableMesh = new THREE.Mesh(
  new THREE.CircleGeometry(14, 64),
  new THREE.MeshStandardMaterial({
    map: createTabletopTexture(),
    roughness: 0.78,
    metalness: 0.0
  })
);
tableMesh.rotation.x = -Math.PI / 2;
tableMesh.position.y = -0.145;
tableMesh.receiveShadow = true;
scene.add(tableMesh);

// Small glazed ceramic dessert plate
function createPlateTexture() {
  const c = document.createElement('canvas');
  c.width = 512;
  c.height = 512;
  const g = c.getContext('2d');
  // Radial mapping along Lathe UVs (v goes along profile from center 0 to rim 1)
  g.fillStyle = '#fff9f1';
  g.fillRect(0, 0, 512, 512);

  // Very subtle warm ceramic glaze variation
  const gr = g.createLinearGradient(0, 0, 0, 512);
  gr.addColorStop(0.0, '#fffaf3');
  gr.addColorStop(0.55, '#fdf4e8');
  gr.addColorStop(0.70, '#f9ebda');
  gr.addColorStop(1.0, '#f5e4d0');
  g.fillStyle = gr;
  g.fillRect(0, 0, 512, 512);

  // Delicate warm gold/terracotta accent lines near inner rim & outer lip
  g.fillStyle = 'rgba(218, 140, 72, 0.55)';
  g.fillRect(0, 512 * 0.44, 512, 5);
  g.fillStyle = 'rgba(210, 124, 58, 0.78)';
  g.fillRect(0, 512 * 0.655, 512, 10);

  // Subtle artisanal ceramic micro-speckles
  let seed = 1337;
  const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
  for (let i = 0; i < 420; i++) {
    g.fillStyle = `rgba(165, 118, 82, ${0.06 + rand() * 0.09})`;
    const x = rand() * 512;
    const y = rand() * 512;
    const r = 0.6 + rand() * 1.4;
    g.beginPath();
    g.arc(x, y, r, 0, Math.PI * 2);
    g.fill();
  }

  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.wrapS = THREE.RepeatWrapping;
  return tex;
}

function buildSmallPlate() {
  // Lathe profile: center flat well at y = 0.0, softly curving raised rim to r = 1.82
  const pts = [
    new THREE.Vector2(0.00,  0.000),
    new THREE.Vector2(0.80,  0.000),
    new THREE.Vector2(1.24,  0.006),
    new THREE.Vector2(1.42,  0.042),
    new THREE.Vector2(1.62,  0.125),
    new THREE.Vector2(1.78,  0.195),
    new THREE.Vector2(1.84,  0.202),
    new THREE.Vector2(1.86,  0.180),
    new THREE.Vector2(1.78,  0.115),
    new THREE.Vector2(1.52, -0.015),
    new THREE.Vector2(1.18, -0.105),
    new THREE.Vector2(1.12, -0.142),
    new THREE.Vector2(0.98, -0.142),
    new THREE.Vector2(0.92, -0.105),
    new THREE.Vector2(0.00, -0.102)
  ];
  const geo = new THREE.LatheGeometry(pts, 72);
  const mat = new THREE.MeshPhysicalMaterial({
    map: createPlateTexture(),
    color: '#fffcf7',
    roughness: 0.14,
    metalness: 0.0,
    clearcoat: 0.92,
    clearcoatRoughness: 0.07,
    envMapIntensity: 1.05
  });
  const mesh = new THREE.Mesh(geo, mat);
  mesh.receiveShadow = true;
  mesh.castShadow = true;
  return mesh;
}

const plateMesh = buildSmallPlate();
scene.add(plateMesh);

// Dynamic Orange Caustic Glow & Translucent Colored Shadow projected onto the plate
const causticUniforms = {
  uTime: { value: 0 },
  uOffset: { value: new THREE.Vector2(0, 0) },
  uSquash: { value: 0 },
  uDropY: { value: 0 },
  uEnergy: { value: 0 },
  uPurr: { value: 0 }
};

const causticMesh = new THREE.Mesh(
  new THREE.CircleGeometry(1.46, 56),
  new THREE.ShaderMaterial({
    transparent: true,
    depthWrite: false,
    uniforms: causticUniforms,
    vertexShader: `
      varying vec2 vUv;
      void main() {
        vUv = uv * 2.0 - 1.0;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      }
    `,
    fragmentShader: `
      uniform float uTime;
      uniform vec2 uOffset;
      uniform float uSquash;
      uniform float uDropY;
      uniform float uEnergy;
      uniform float uPurr;
      varying vec2 vUv;

      void main() {
        float spread = exp(uSquash * 0.45) * (1.0 + uDropY * 0.25);
        vec2 p = (vUv * 1.46 - uOffset * 0.22) / spread;

        // Cat footprint ellipse + tail lobe
        float dBody = length(p / vec2(0.84, 0.78));
        float dTail = length((p - vec2(0.86, 0.12)) / vec2(0.36, 0.56));
        float foot = min(dBody, dTail);

        // Soft orange translucent shadow (replaces harsh gray shadow)
        float airFade = exp(-uDropY * 0.55);
        float orangeShadow = smoothstep(1.30, 0.25, foot) * 0.44 * airFade;

        // Focused sunlit amber-gold caustic offset away from key light (+X, -Z in world -> +X, +Y in plane UV)
        vec2 cp = p - vec2(0.20, 0.14);
        float cDist = length(cp / vec2(0.68, 0.58));
        float ripple = sin(cDist * 14.0 - uTime * 5.0) * 0.5 + 0.5;
        float causticCore = smoothstep(1.05, 0.0, cDist);
        causticCore = pow(causticCore, 1.7) * (0.68 + 0.32 * ripple * (0.25 + uEnergy * 0.9)) * airFade;

        // Tight subtle warm contact ring right where jelly meets porcelain
        float contactRing = smoothstep(0.95, 0.74, dBody) * smoothstep(0.42, 0.72, dBody) * exp(-uDropY * 8.0) * 0.20;

        vec3 shadowCol = vec3(0.96, 0.44, 0.06);
        vec3 causticCol = vec3(1.0, 0.78, 0.26) * (1.0 + uPurr * 0.22);
        vec3 contactCol = vec3(0.78, 0.28, 0.03);

        float alpha = clamp(orangeShadow + causticCore * 0.45 + contactRing, 0.0, 0.78);
        vec3 col = mix(shadowCol, causticCol, clamp(causticCore * 1.35, 0.0, 1.0));
        col = mix(col, contactCol, contactRing * 1.5);

        gl_FragColor = vec4(col, alpha);
      }
    `
  })
);
causticMesh.rotation.x = -Math.PI / 2;
causticMesh.position.y = 0.004;
scene.add(causticMesh);

// ============================================================================
// 5. BUILD THE CLEAR ORANGE JELLY CAT + INNER GLOW + BUBBLES + FACE
// ============================================================================
const catData = buildJellyCatGeometry();

// Main translucent glossy orange jelly material
const jellyMat = new THREE.MeshPhysicalMaterial({
  color: new THREE.Color('#ffc470'),
  transmission: 0.93,
  opacity: 1.0,
  transparent: false,
  roughness: 0.055,
  metalness: 0.0,
  ior: 1.38,
  thickness: 1.48,
  attenuationColor: new THREE.Color('#ff8a20'),
  attenuationDistance: 1.52,
  clearcoat: 1.0,
  clearcoatRoughness: 0.028,
  specularIntensity: 1.0,
  specularColor: new THREE.Color('#fff7eb'),
  envMapIntensity: 1.42
});

const catMesh = new THREE.Mesh(catData.geo, jellyMat);
catMesh.frustumCulled = false;
catMesh.castShadow = false; // We render authentic orange translucent caustics instead of opaque gray shadows
catMesh.receiveShadow = false;
scene.add(catMesh);

// Subtle soft shadow caster proxy? No, our custom orange caustic + colored shadow looks WAY more like clear jelly!
// Add a subtle soft-light subsurface internal glow shell sharing the exact same deformed geometry
const glowUniforms = {
  uPurr: { value: 0 },
  uFirmness: { value: 0.4 },
  uTime: { value: 0 }
};

const jellyGlowMat = new THREE.ShaderMaterial({
  transparent: true,
  depthWrite: false,
  depthTest: true,
  depthFunc: THREE.LessEqualDepth,
  blending: THREE.AdditiveBlending,
  polygonOffset: true,
  polygonOffsetFactor: -1,
  polygonOffsetUnits: -1,
  uniforms: glowUniforms,
  vertexShader: `
    attribute float aThinness;
    varying vec3 vNormalW;
    varying vec3 vViewDir;
    varying float vThin;
    varying float vHeight;
    void main() {
      vec4 wp = modelMatrix * vec4(position, 1.0);
      vNormalW = normalize(mat3(modelMatrix) * normal);
      vViewDir = normalize(cameraPosition - wp.xyz);
      vThin = aThinness;
      vHeight = wp.y;
      gl_Position = projectionMatrix * viewMatrix * wp;
    }
  `,
  fragmentShader: `
    uniform float uPurr;
    uniform float uFirmness;
    uniform float uTime;
    varying vec3 vNormalW;
    varying vec3 vViewDir;
    varying float vThin;
    varying float vHeight;

    void main() {
      vec3 N = normalize(vNormalW);
      vec3 V = normalize(vViewDir);
      float ndotv = clamp(dot(N, V), 0.0, 1.0);

      // Soft warm golden light glowing from inside the thick jelly core
      float coreGlow = pow(ndotv, 1.45) * (0.16 + 0.06 * smoothstep(0.1, 1.3, vHeight));

      // Backlit sunlight scattering through thin ears, tail, cheeks & rim
      vec3 backSun = normalize(vec3(0.45, 0.55, -0.70));
      float backLight = pow(clamp(dot(V, -backSun) * 0.5 + 0.5, 0.0, 1.0), 2.0);
      float sss = (0.10 + 0.28 * vThin) * (0.55 + 0.45 * backLight);
      float rim = pow(1.0 - ndotv, 2.35) * (0.09 + 0.24 * vThin);

      // Softness modulation: soft pudding has slightly silkier scatter, firm gummy is crisper
      float softBoost = mix(1.12, 0.86, uFirmness);
      float purrWarm = 1.0 + uPurr * (0.34 + 0.06 * sin(uTime * 10.0));

      vec3 coreCol = vec3(1.0, 0.54, 0.09);
      vec3 rimCol  = vec3(1.0, 0.76, 0.24);
      vec3 col = (coreCol * (coreGlow + sss * 0.55) + rimCol * (rim + sss * 0.45)) * softBoost * purrWarm;

      gl_FragColor = vec4(col, 1.0);
    }
  `
});

const catGlowMesh = new THREE.Mesh(catData.geo, jellyGlowMat);
catGlowMesh.frustumCulled = false;
scene.add(catGlowMesh);

// Tiny shimmering trapped air bubbles inside the clear jelly (opaque hollow-bubble shader so transmission refracts them!)
function buildInternalBubbles() {
  const bubbles = [];
  let seed = 4207;
  const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);

  const bubbleGeo = new THREE.SphereGeometry(1, 16, 12);
  const bubbleMat = new THREE.ShaderMaterial({
    transparent: false,
    vertexShader: `
      varying vec3 vNormalW;
      varying vec3 vViewDir;
      void main() {
        vec4 wp = modelMatrix * vec4(position, 1.0);
        vNormalW = normalize(mat3(modelMatrix) * normal);
        vViewDir = normalize(cameraPosition - wp.xyz);
        gl_Position = projectionMatrix * viewMatrix * wp;
      }
    `,
    fragmentShader: `
      varying vec3 vNormalW;
      varying vec3 vViewDir;
      void main() {
        vec3 N = normalize(vNormalW);
        vec3 V = normalize(vViewDir);
        vec3 L = normalize(vec3(-0.5, 0.8, 0.55));
        vec3 H = normalize(L + V);

        float ndotv = clamp(dot(N, V), 0.0, 1.0);
        float fresnel = pow(1.0 - ndotv, 1.9);
        float spec = pow(max(dot(N, H), 0.0), 46.0);
        float bottomGlow = pow(max(dot(-N, L), 0.0), 2.4);

        // Luminous hollow air-pocket look inside backlit orange jelly
        vec3 centerCol = vec3(1.0, 0.66, 0.19);
        vec3 rimCol = vec3(1.0, 0.96, 0.82);
        vec3 col = mix(centerCol, rimCol, fresnel * 0.86);
        col += vec3(1.0, 0.99, 0.94) * spec * 1.45;
        col += vec3(1.0, 0.84, 0.42) * bottomGlow * 0.42;

        gl_FragColor = vec4(col, 1.0);
      }
    `
  });

  const group = new THREE.Group();
  let tries = 0;
  while (bubbles.length < 28 && tries < 2400) {
    tries++;
    const x = lerp(-0.72, 1.02, rand());
    const y = lerp(0.14, 1.76, rand());
    const z = lerp(-0.62, 0.62, rand());
    const r = bubbles.length < 6
      ? lerp(0.032, 0.044, rand())
      : bubbles.length < 16
        ? lerp(0.021, 0.031, rand())
        : lerp(0.013, 0.020, rand());

    // Keep face eyes crystal clear
    if (y > 1.18 && y < 1.46 && z > 0.30 && Math.abs(x) < 0.34) continue;
    // Must be cleanly embedded inside the jelly skin
    if (catSDF(x, y, z) > -(r + 0.055)) continue;

    let tooClose = false;
    for (let i = 0; i < bubbles.length; i++) {
      const b = bubbles[i];
      if (Math.hypot(x - b.x0, y - b.y0, z - b.z0) < r + b.r + 0.07) {
        tooClose = true;
        break;
      }
    }
    if (tooClose) continue;

    const mesh = new THREE.Mesh(bubbleGeo, bubbleMat);
    mesh.scale.setScalar(r);
    group.add(mesh);
    bubbles.push({
      mesh,
      x0: x, y0: y, z0: z,
      r,
      w: computePartWeights(x, y, z),
      phase: rand() * Math.PI * 2
    });
  }
  scene.add(group);
  return bubbles;
}

const bubbles = buildInternalBubbles();

// ============================================================================
// 6. EXPRESSIVE FACE: TRACKING GLOSSY EYES, SQUINT, NOSE, :3 MOUTH, WHISKERS, BLUSH
// ============================================================================
const darkCocoaMat = new THREE.MeshPhysicalMaterial({
  color: '#2b1006',
  roughness: 0.07,
  metalness: 0.0,
  clearcoat: 1.0,
  clearcoatRoughness: 0.04
});

const warmIrisMat = new THREE.MeshStandardMaterial({
  color: '#9c4311',
  emissive: '#591e04',
  emissiveIntensity: 0.55,
  roughness: 0.18
});

const catchlightMat = new THREE.MeshBasicMaterial({ color: '#ffffff' });

function createEye(side) {
  const surf = findFaceSurface(side * 0.215, 1.325);
  const root = new THREE.Group();

  // Open glossy eyeball container
  const openGroup = new THREE.Group();
  const baseSphere = new THREE.Mesh(new THREE.SphereGeometry(0.088, 24, 18), darkCocoaMat);
  baseSphere.scale.set(1.0, 1.06, 0.56);
  openGroup.add(baseSphere);

  // Moving pupil / iris / catchlights sub-group for finger tracking
  const trackGroup = new THREE.Group();
  const irisGlow = new THREE.Mesh(new THREE.SphereGeometry(0.064, 18, 14), warmIrisMat);
  irisGlow.scale.set(0.95, 0.62, 0.28);
  irisGlow.position.set(0, -0.022, 0.036);
  trackGroup.add(irisGlow);

  const pupil = new THREE.Mesh(new THREE.SphereGeometry(0.056, 18, 14), darkCocoaMat);
  pupil.scale.set(1.0, 1.05, 0.34);
  pupil.position.set(0, 0.004, 0.039);
  trackGroup.add(pupil);

  const hlBig = new THREE.Mesh(new THREE.SphereGeometry(0.025, 12, 10), catchlightMat);
  hlBig.scale.set(1.0, 1.0, 0.45);
  hlBig.position.set(-0.026, 0.030, 0.056);
  trackGroup.add(hlBig);

  const hlSmall = new THREE.Mesh(new THREE.SphereGeometry(0.011, 10, 8), catchlightMat);
  hlSmall.scale.set(1.0, 1.0, 0.45);
  hlSmall.position.set(0.024, -0.022, 0.054);
  trackGroup.add(hlSmall);

  openGroup.add(trackGroup);
  root.add(openGroup);

  // Cute happy-squint arc (⌒) shown when rubbing head / purring / wincing
  const arcPts = [];
  for (let i = 0; i <= 16; i++) {
    const t = i / 16;
    const ang = lerp(Math.PI * 0.14, Math.PI * 0.86, t);
    arcPts.push(new THREE.Vector3(
      Math.cos(ang) * 0.095,
      Math.sin(ang) * 0.058 - 0.028,
      0.028
    ));
  }
  const squintCurve = new THREE.CatmullRomCurve3(arcPts);
  const squintArc = new THREE.Mesh(
    new THREE.TubeGeometry(squintCurve, 18, 0.0165, 10, false),
    darkCocoaMat
  );
  squintArc.scale.setScalar(0.0001);
  root.add(squintArc);

  scene.add(root);

  return {
    side,
    root,
    openGroup,
    trackGroup,
    squintArc,
    rest: { x: surf.x, y: surf.y, z: surf.z },
    w: computePartWeights(surf.x, surf.y, surf.z)
  };
}

const eyes = [createEye(1), createEye(-1)];

// Cute tiny glossy button nose
const noseSurf = findFaceSurface(0, 1.235);
const noseMesh = new THREE.Mesh(
  new THREE.SphereGeometry(0.036, 16, 12),
  new THREE.MeshPhysicalMaterial({
    color: '#5a1e0c',
    roughness: 0.12,
    clearcoat: 1.0
  })
);
noseMesh.scale.set(1.22, 0.82, 0.68);
scene.add(noseMesh);
const noseAnchor = {
  rest: { x: noseSurf.x, y: noseSurf.y, z: noseSurf.z },
  w: computePartWeights(noseSurf.x, noseSurf.y, noseSurf.z)
};

// Deformable ':3' cat mouth (projected flush onto face surface, morphs with purr smile & cheek pulls!)
function buildDeformableMouth() {
  const basePts = [];
  const steps = 20;
  for (let i = 0; i <= steps; i++) {
    const u = (i / steps) * 2 - 1; // -1 to 1
    const au = Math.abs(u);
    const x = u * 0.135;
    // Classic cute ':3' double-dip cat smile curve
    const y = 1.182 - Math.sin(au * Math.PI) * 0.036 + au * au * 0.014;
    const s = findFaceSurface(x, y);
    basePts.push({
      x: s.x + s.nx * 0.008,
      y: s.y + s.ny * 0.008,
      z: s.z + s.nz * 0.008,
      au,
      w: computePartWeights(s.x, s.y, s.z)
    });
  }

  // Create tube around curve using rest points, storing each vertex's anchor index & local offset
  const ringSegs = 8;
  const radius = 0.0115;
  const vCount = (steps + 1) * ringSegs;
  const positions = new Float32Array(vCount * 3);
  const meta = [];
  const indices = [];

  for (let i = 0; i <= steps; i++) {
    const pPrev = basePts[Math.max(0, i - 1)];
    const pNext = basePts[Math.min(steps, i + 1)];
    const tx = pNext.x - pPrev.x, ty = pNext.y - pPrev.y, tz = pNext.z - pPrev.z;
    const tLen = Math.hypot(tx, ty, tz) || 1;
    const T = new THREE.Vector3(tx / tLen, ty / tLen, tz / tLen);
    const up = new THREE.Vector3(0, 0, 1);
    const B = new THREE.Vector3().crossVectors(T, up).normalize();
    const N = new THREE.Vector3().crossVectors(B, T).normalize();

    // Slightly taper ends of mouth
    const endTaper = 0.65 + 0.35 * Math.sin((i / steps) * Math.PI);
    for (let r = 0; r < ringSegs; r++) {
      const ang = (r / ringSegs) * Math.PI * 2;
      const ca = Math.cos(ang) * radius * endTaper;
      const sa = Math.sin(ang) * radius * endTaper;
      const ox = B.x * ca + N.x * sa;
      const oy = B.y * ca + N.y * sa;
      const oz = B.z * ca + N.z * sa;
      const rx = basePts[i].x + ox;
      const ry = basePts[i].y + oy;
      const rz = basePts[i].z + oz;
      meta.push({ x0: rx, y0: ry, z0: rz, au: basePts[i].au, w: basePts[i].w });
    }
    if (i < steps) {
      for (let r = 0; r < ringSegs; r++) {
        const rn = (r + 1) % ringSegs;
        const a = i * ringSegs + r;
        const b = i * ringSegs + rn;
        const c = (i + 1) * ringSegs + rn;
        const d = (i + 1) * ringSegs + r;
        indices.push(a, b, c, a, c, d);
      }
    }
  }

  const geo = new THREE.BufferGeometry();
  const posAttr = new THREE.BufferAttribute(positions, 3);
  posAttr.setUsage(THREE.DynamicDrawUsage);
  geo.setAttribute('position', posAttr);
  geo.setIndex(indices);

  const mesh = new THREE.Mesh(geo, darkCocoaMat);
  mesh.frustumCulled = false;
  scene.add(mesh);

  return { mesh, geo, posAttr, positions, meta };
}

const mouthObj = buildDeformableMouth();

// Delicate translucent jelly whiskers (flex & stretch with cheek pulls!)
function buildDeformableWhiskers() {
  const whiskerMat = new THREE.MeshPhysicalMaterial({
    color: '#fff4e0',
    transparent: true,
    opacity: 0.56,
    roughness: 0.15,
    clearcoat: 0.8
  });

  const whiskers = [];
  const specs = [
    { yOff: 0.045, angY: 0.15, droop: -0.010, len: 0.27 },
    { yOff: 0.000, angY: 0.02, droop: -0.022, len: 0.30 },
    { yOff: -0.042, angY: -0.14, droop: -0.036, len: 0.25 }
  ];

  for (const side of [-1, 1]) {
    for (const sp of specs) {
      const rootSurf = findFaceSurface(side * 0.37, 1.20 + sp.yOff);
      const segs = 6;
      const ring = 6;
      const pts = [];
      for (let i = 0; i <= segs; i++) {
        const t = i / segs;
        const wx = rootSurf.x + side * (t * sp.len);
        const wy = rootSurf.y + t * Math.sin(sp.angY) * sp.len + t * t * sp.droop;
        const wz = rootSurf.z + 0.015 - t * t * 0.055;
        pts.push({ x: wx, y: wy, z: wz, t, w: computePartWeights(rootSurf.x, rootSurf.y, rootSurf.z) });
      }
      const positions = new Float32Array((segs + 1) * ring * 3);
      const meta = [];
      const indices = [];
      for (let i = 0; i <= segs; i++) {
        const rad = lerp(0.0068, 0.0018, i / segs);
        for (let r = 0; r < ring; r++) {
          const ang = (r / ring) * Math.PI * 2;
          meta.push({
            x0: pts[i].x,
            y0: pts[i].y + Math.cos(ang) * rad,
            z0: pts[i].z + Math.sin(ang) * rad,
            w: pts[i].w
          });
        }
        if (i < segs) {
          for (let r = 0; r < ring; r++) {
            const rn = (r + 1) % ring;
            const a = i * ring + r, b = i * ring + rn, c = (i + 1) * ring + rn, d = (i + 1) * ring + r;
            indices.push(a, b, c, a, c, d);
          }
        }
      }
      const geo = new THREE.BufferGeometry();
      const posAttr = new THREE.BufferAttribute(positions, 3);
      posAttr.setUsage(THREE.DynamicDrawUsage);
      geo.setAttribute('position', posAttr);
      geo.setIndex(indices);
      const mesh = new THREE.Mesh(geo, whiskerMat);
      mesh.frustumCulled = false;
      scene.add(mesh);
      whiskers.push({ geo, posAttr, positions, meta });
    }
  }
  return whiskers;
}

const whiskers = buildDeformableWhiskers();

// Soft rosy cheek blush ovals (glow warmer when purring!)
function createBlushDiscs() {
  const c = document.createElement('canvas');
  c.width = 128;
  c.height = 128;
  const g = c.getContext('2d');
  const gr = g.createRadialGradient(64, 64, 4, 64, 64, 60);
  gr.addColorStop(0.0, 'rgba(255, 92, 92, 0.85)');
  gr.addColorStop(0.45, 'rgba(255, 110, 82, 0.45)');
  gr.addColorStop(1.0, 'rgba(255, 120, 80, 0.0)');
  g.fillStyle = gr;
  g.fillRect(0, 0, 128, 128);
  const tex = new THREE.CanvasTexture(c);
  tex.colorSpace = THREE.SRGBColorSpace;

  const mat = new THREE.MeshBasicMaterial({
    map: tex,
    transparent: true,
    opacity: 0.24,
    depthWrite: false
  });

  const discs = [];
  for (const side of [-1, 1]) {
    const s = findFaceSurface(side * 0.34, 1.21);
    const mesh = new THREE.Mesh(new THREE.PlaneGeometry(0.19, 0.125), mat);
    scene.add(mesh);
    discs.push({
      mesh,
      rest: { x: s.x, y: s.y, z: s.z },
      w: computePartWeights(s.x, s.y, s.z)
    });
  }
  return { discs, mat };
}

const blush = createBlushDiscs();

// Tiny wet orange jelly splash droplets triggered on big Drop impacts
const splashDrops = [];
{
  const dropGeo = new THREE.SphereGeometry(0.026, 10, 8);
  const dropMat = new THREE.MeshPhysicalMaterial({
    color: '#ffaa3b',
    transmission: 0.78,
    roughness: 0.05,
    ior: 1.38,
    clearcoat: 1.0,
    transparent: true,
    opacity: 0.92
  });
  for (let i = 0; i < 10; i++) {
    const m = new THREE.Mesh(dropGeo, dropMat);
    m.visible = false;
    scene.add(m);
    splashDrops.push({ mesh: m, x: 0, y: 0, z: 0, vx: 0, vy: 0, vz: 0, life: 0, maxLife: 0.65, size: 1 });
  }
}

function triggerSplashDroplets(strength = 1.0) {
  for (let i = 0; i < splashDrops.length; i++) {
    const d = splashDrops[i];
    const ang = (i / splashDrops.length) * Math.PI * 2 + (Math.random() - 0.5) * 0.45;
    const rad = 0.68 + Math.random() * 0.18;
    d.x = Math.cos(ang) * rad;
    d.z = Math.sin(ang) * rad;
    d.y = 0.06;
    const spd = (0.75 + Math.random() * 0.95) * strength;
    d.vx = Math.cos(ang) * spd;
    d.vz = Math.sin(ang) * spd;
    d.vy = (1.35 + Math.random() * 1.1) * strength;
    d.maxLife = 0.48 + Math.random() * 0.32;
    d.life = d.maxLife;
    d.size = 0.65 + Math.random() * 0.75;
    d.mesh.visible = true;
  }
}

// ============================================================================
// 7. JELLY SOFT-BODY SPRING PHYSICS ENGINE
// ============================================================================
const makeSpring1D = () => ({ p: 0, v: 0, t: 0 });
const makeSpring3D = () => ({ x: 0, y: 0, z: 0, vx: 0, vy: 0, vz: 0, tx: 0, ty: 0, tz: 0 });

const phys = {
  firmness: 0.40, // 0 = Soft Pudding, 1 = Firm Gummy
  time: 0,

  // Vertical drop state
  dropY: 0,
  dropVy: 0,
  dropPhase: 'idle', // 'idle' | 'lifting' | 'falling'
  dropLiftTimer: 0,

  // Global jelly modes
  squash: makeSpring1D(),
  leanX: makeSpring1D(),
  leanZ: makeSpring1D(),
  twistY: makeSpring1D(),
  rippleAmp: 0,
  ripplePhase: 0,

  // Part-specific elastic springs
  earL: makeSpring3D(),
  earR: makeSpring3D(),
  cheekL: makeSpring3D(),
  cheekR: makeSpring3D(),
  tail: makeSpring3D(),
  head: makeSpring3D(),

  // Active localized free-grab spring
  grabPos: { x: 0, y: 0.8, z: 0.4 },
  grab: makeSpring3D(),
  grabRadius: 0.40,

  // 4 overlapping localized poke dent ripples
  pokes: Array.from({ length: 4 }, () => ({
    cx: 0, cy: 0, cz: 0,
    nx: 0, ny: 1, nz: 0,
    val: 0, vel: 0,
    radius: 0.34,
    active: false
  })),
  pokeCursor: 0,

  // Expression & affection
  purrLevel: 0,
  rubEnergy: 0,
  wince: 0,
  surprise: 0,
  blinkTimer: 2.6,
  blinkVal: 0,

  // Eye look tracking (smoothed 3D target)
  lookTarget: new THREE.Vector3(0, 1.32, 3.2),
  lookCurrent: new THREE.Vector3(0, 1.32, 3.2),
  pointerActiveTimer: 0
};

function springParams(scaleK = 1.0, scaleZeta = 1.0) {
  const f = phys.firmness;
  // Soft pudding (0): slow, lush, long-ringing wobble (omega ~ 8.5, zeta ~ 0.068)
  // Firm gummy (1): fast, snappy, rubbery spring-back (omega ~ 28, zeta ~ 0.125)
  const omega = lerp(8.5, 28.0, f * f * 0.45 + f * 0.55) * scaleK;
  const zeta = lerp(0.068, 0.125, f) * scaleZeta;
  return { k: omega * omega, c: 2 * zeta * omega };
}

function step1D(s, dt, k, c) {
  const acc = k * (s.t - s.p) - c * s.v;
  s.v += acc * dt;
  s.p += s.v * dt;
}

function step3D(s, dt, k, c) {
  s.vx += (k * (s.tx - s.x) - c * s.vx) * dt;
  s.vy += (k * (s.ty - s.y) - c * s.vy) * dt;
  s.vz += (k * (s.tz - s.z) - c * s.vz) * dt;
  s.x += s.vx * dt;
  s.y += s.vy * dt;
  s.z += s.vz * dt;
}

function addPokeImpulse(rx, ry, rz, nx, ny, nz, strength = 0.24) {
  const comp = lerp(1.45, 0.62, phys.firmness);
  const p = phys.pokes[phys.pokeCursor];
  phys.pokeCursor = (phys.pokeCursor + 1) % phys.pokes.length;
  p.cx = rx; p.cy = ry; p.cz = rz;
  p.nx = nx; p.ny = ny; p.nz = nz;
  p.val = -strength * 0.45 * comp;
  p.vel = -strength * 4.4 * comp;
  p.radius = lerp(0.42, 0.28, phys.firmness);
  p.active = true;

  // Couple into global wobble & ripple
  phys.leanX.v -= nx * strength * 1.45 * comp;
  phys.leanZ.v -= nz * strength * 1.45 * comp;
  phys.squash.v += Math.max(0.08, -ny * 0.8 + 0.32) * strength * 1.6 * comp;
  phys.rippleAmp = Math.min(0.08, phys.rippleAmp + 0.032 * comp);
}

function triggerDrop() {
  if (phys.dropPhase === 'lifting') return;
  phys.dropPhase = 'lifting';
  phys.dropLiftTimer = 0;
  phys.dropVy = 0;
  phys.surprise = 1.0;
  phys.purrLevel *= 0.2;
  phys.rubEnergy = 0;
  audio.playLift();
}

function stepPhysics(dt) {
  phys.time += dt;
  const f = phys.firmness;
  const comp = lerp(1.45, 0.58, f);

  // Drop lifting & gravity falling
  if (phys.dropPhase === 'lifting') {
    phys.dropLiftTimer += dt;
    const t = clamp(phys.dropLiftTimer / 0.26, 0, 1);
    const ease = 1 - Math.pow(1 - t, 3);
    phys.dropY = ease * 2.45;
    // Playful upward anticipation stretch while rising
    phys.squash.t = -0.16 * Math.sin(t * Math.PI);
    phys.earL.ty = -0.08 * ease;
    phys.earR.ty = -0.08 * ease;
    phys.tail.ty = -0.10 * ease;
    if (t >= 1) {
      phys.dropPhase = 'falling';
      phys.dropVy = -0.4;
      phys.squash.t = 0;
      phys.earL.ty = 0;
      phys.earR.ty = 0;
      phys.tail.ty = 0;
    }
  } else if (phys.dropPhase === 'falling') {
    phys.dropVy -= 23.5 * dt;
    phys.dropY += phys.dropVy * dt;
    // Elongate vertically from air rush, ears/tail trail up
    phys.squash.p = lerp(phys.squash.p, -0.17, dt * 8);
    phys.earL.y = lerp(phys.earL.y, 0.14, dt * 8);
    phys.earR.y = lerp(phys.earR.y, 0.14, dt * 8);
    phys.tail.y = lerp(phys.tail.y, 0.18, dt * 8);

    if (phys.dropY <= 0) {
      // BIG JELLY IMPACT!
      const impact = clamp(Math.abs(phys.dropVy) / 10.5, 0.5, 1.25);
      phys.dropY = 0;
      phys.dropVy = 0;
      phys.dropPhase = 'idle';

      phys.squash.p = 0.22 * comp * impact;
      phys.squash.v = 5.4 * comp * impact;
      phys.leanX.v += (Math.random() - 0.5) * 3.2 * comp;
      phys.leanZ.v += (0.8 + (Math.random() - 0.5) * 2.2) * comp;
      phys.twistY.v += (Math.random() - 0.5) * 3.8 * comp;

      phys.head.vy -= 3.2 * comp * impact;
      phys.earL.vx += 2.6 * comp * impact;
      phys.earL.vy -= 3.8 * comp * impact;
      phys.earR.vx -= 2.6 * comp * impact;
      phys.earR.vy -= 3.8 * comp * impact;
      phys.cheekL.vx += 2.2 * comp * impact;
      phys.cheekL.vy -= 1.8 * comp * impact;
      phys.cheekR.vx -= 2.2 * comp * impact;
      phys.cheekR.vy -= 1.8 * comp * impact;
      phys.tail.vx += 3.0 * comp * impact;
      phys.tail.vy -= 3.4 * comp * impact;

      phys.rippleAmp = 0.115 * comp * impact;
      phys.ripplePhase = 0;
      phys.wince = 1.0;
      phys.surprise = 0;

      triggerSplashDroplets(lerp(1.15, 0.72, f));
      audio.playDropImpact(f);
    }
  }

  // Spring constants per body zone
  const pGlobal = springParams(1.0, 1.0);
  const pLean   = springParams(0.86, 0.92);
  const pPart   = springParams(1.24, 0.88);
  const pHead   = springParams(1.08, 0.95);
  const pPoke   = springParams(1.42, 0.95);

  step1D(phys.squash, dt, pGlobal.k, pGlobal.c);
  step1D(phys.leanX, dt, pLean.k, pLean.c);
  step1D(phys.leanZ, dt, pLean.k, pLean.c);
  step1D(phys.twistY, dt, pLean.k * 0.9, pLean.c);

  // Couple lean wobble playfully into head, ears & tail when idle
  step3D(phys.head, dt, pHead.k, pHead.c);
  step3D(phys.earL, dt, pPart.k, pPart.c);
  step3D(phys.earR, dt, pPart.k, pPart.c);
  step3D(phys.cheekL, dt, pPart.k * 1.08, pPart.c);
  step3D(phys.cheekR, dt, pPart.k * 1.08, pPart.c);
  step3D(phys.tail, dt, pPart.k * 0.86, pPart.c * 0.88);
  step3D(phys.grab, dt, pPart.k, pPart.c);

  // Subtle ambient happy tail swish when purring
  if (phys.purrLevel > 0.05 && dragState.zone !== 'tail') {
    const swish = Math.sin(phys.time * 4.2) * 0.09 * phys.purrLevel;
    phys.tail.tz = lerp(phys.tail.tz, swish, dt * 5);
  } else if (dragState.zone !== 'tail') {
    phys.tail.tz = lerp(phys.tail.tz, 0, dt * 6);
  }

  // Clamp spring excursions so jelly can NEVER turn inside-out
  phys.squash.p = clamp(phys.squash.p, -0.46, 0.62);
  phys.leanX.p = clamp(phys.leanX.p, -0.58, 0.58);
  phys.leanZ.p = clamp(phys.leanZ.p, -0.58, 0.58);

  // Traveling impact/poke belly ripple
  phys.ripplePhase += dt * lerp(11.0, 22.0, f);
  phys.rippleAmp *= Math.exp(-dt * lerp(2.2, 5.2, f));

  // Localized poke dent springs
  for (let i = 0; i < phys.pokes.length; i++) {
    const pk = phys.pokes[i];
    if (!pk.active) continue;
    const acc = -pPoke.k * pk.val - pPoke.c * pk.vel;
    pk.vel += acc * dt;
    pk.val += pk.vel * dt;
    if (Math.abs(pk.val) < 0.0006 && Math.abs(pk.vel) < 0.004) {
      pk.val = 0;
      pk.vel = 0;
      pk.active = false;
    }
  }

  // Purr & head-rub affection decay
  phys.rubEnergy = Math.max(0, phys.rubEnergy - dt * 0.72);
  const targetPurr = clamp(phys.rubEnergy, 0, 1);
  phys.purrLevel = lerp(phys.purrLevel, targetPurr, dt * (targetPurr > phys.purrLevel ? 5.2 : 1.7));

  // Impact wince & lift surprise decay
  phys.wince = Math.max(0, phys.wince - dt * 2.4);
  if (phys.dropPhase === 'idle') phys.surprise = Math.max(0, phys.surprise - dt * 3.8);

  // Cute natural blinking
  phys.blinkTimer -= dt;
  if (phys.blinkTimer <= 0) {
    phys.blinkTimer = 2.8 + Math.random() * 3.4;
    phys.blinkVal = 1.0;
  }
  if (phys.blinkVal > 0) {
    phys.blinkVal = Math.max(0, phys.blinkVal - dt * 7.2);
  }

  // Idle look drift gently back toward viewer if no recent pointer
  phys.pointerActiveTimer = Math.max(0, phys.pointerActiveTimer - dt);
  if (phys.pointerActiveTimer <= 0 && !demoState.active) {
    phys.lookTarget.set(
      Math.sin(phys.time * 0.45) * 0.28,
      1.30 + Math.sin(phys.time * 0.7) * 0.08,
      3.4
    );
  }
  phys.lookCurrent.lerp(phys.lookTarget, clamp(dt * 10, 0, 1));

  // Update splash droplets
  for (let i = 0; i < splashDrops.length; i++) {
    const d = splashDrops[i];
    if (d.life <= 0) continue;
    d.life -= dt;
    if (d.life <= 0) {
      d.mesh.visible = false;
      continue;
    }
    d.vy -= 14.5 * dt;
    d.x += d.vx * dt;
    d.y += d.vy * dt;
    d.z += d.vz * dt;
    if (d.y < 0.025) {
      d.y = 0.025;
      d.vy *= -0.25;
      d.vx *= 0.65;
      d.vz *= 0.65;
    }
    const s = d.size * smoothstep(0, 0.22, d.life / d.maxLife);
    d.mesh.position.set(d.x, d.y, d.z);
    d.mesh.scale.set(s * 1.1, s * (d.y <= 0.03 ? 0.55 : 1.15), s * 1.1);
  }
}

// Unified 3D soft-body deformation applied to cat mesh, bubbles, eyes, nose, mouth, whiskers & blush
const _defOut = [0, 0, 0];

function deformPoint(x0, y0, z0, wEarL, wEarR, wCheekL, wCheekR, wTail, wHead, wBase, out) {
  let x = x0;
  let y = y0;
  let z = z0;

  // 1. Part-specific elastic springs
  x += wEarL * phys.earL.x + wEarR * phys.earR.x
     + wCheekL * phys.cheekL.x + wCheekR * phys.cheekR.x
     + wTail * phys.tail.x + wHead * phys.head.x;
  y += wEarL * phys.earL.y + wEarR * phys.earR.y
     + wCheekL * phys.cheekL.y + wCheekR * phys.cheekR.y
     + wTail * phys.tail.y + wHead * phys.head.y;
  z += wEarL * phys.earL.z + wEarR * phys.earR.z
     + wCheekL * phys.cheekL.z + wCheekR * phys.cheekR.z
     + wTail * phys.tail.z + wHead * phys.head.z;

  // 2. Active localized free-grab deformation
  const gMag = Math.abs(phys.grab.x) + Math.abs(phys.grab.y) + Math.abs(phys.grab.z);
  if (gMag > 1e-4) {
    const dx = x0 - phys.grabPos.x;
    const dy = y0 - phys.grabPos.y;
    const dz = z0 - phys.grabPos.z;
    const r2 = phys.grabRadius * phys.grabRadius;
    const gw = Math.exp(-(dx * dx + dy * dy + dz * dz) / r2);
    x += phys.grab.x * gw;
    y += phys.grab.y * gw;
    z += phys.grab.z * gw;
  }

  // 3. Up to 4 simultaneous localized poke wave dents + surrounding elastic bulge
  for (let p = 0; p < 4; p++) {
    const pk = phys.pokes[p];
    if (!pk.active) continue;
    const dx = x0 - pk.cx;
    const dy = y0 - pk.cy;
    const dz = z0 - pk.cz;
    const d2 = dx * dx + dy * dy + dz * dz;
    const r2 = pk.radius * pk.radius;
    if (d2 < r2 * 6.0) {
      const e = Math.exp(-d2 / r2);
      const ring = (d2 / r2) * Math.exp(-d2 / (1.8 * r2));
      const disp = (e - 0.28 * ring) * pk.val;
      x += pk.nx * disp;
      y += pk.ny * disp;
      z += pk.nz * disp;
    }
  }

  // 4. Volume-preserving global squash & stretch + soft-pudding gravity slump + breathing + traveling wave
  const gravitySlump = (1 - phys.firmness) * 0.085 * (1 - clamp(phys.dropY * 2, 0, 1));
  const breath = Math.sin(phys.time * 2.2) * (0.011 + phys.purrLevel * 0.014);
  const purrShiver = phys.purrLevel > 0.02
    ? Math.sin(phys.time * 54.0 + y0 * 4.0) * 0.0042 * phys.purrLevel * wBase
    : 0;
  const ripple = phys.rippleAmp > 0.0005
    ? Math.sin(y0 * 4.8 - phys.ripplePhase) * phys.rippleAmp * wBase
    : 0;

  const q = clamp(phys.squash.p + gravitySlump + breath + ripple, -0.52, 0.68);
  const sy = Math.exp(-q);
  const sxz = Math.exp(q * 0.5);
  const bellyBulge = 1.0 + (sxz - 1.0) * (0.76 + 0.52 * Math.exp(-Math.pow((y0 - 0.54) / 0.66, 2)));

  y *= sy;
  x *= bellyBulge + purrShiver;
  z *= bellyBulge + purrShiver;

  // 5. Height-weighted shear wobble (base stays seated on plate) + rotational twist
  const hy = Math.pow(Math.max(0, y0) / 1.85, 1.22) * wBase;
  const lx = phys.leanX.p;
  const lz = phys.leanZ.p;
  x += lx * hy;
  z += lz * hy;
  y -= 0.14 * (lx * lx + lz * lz) * hy;

  const tw = phys.twistY.p * hy;
  if (Math.abs(tw) > 1e-4) {
    const ct = Math.cos(tw), st = Math.sin(tw);
    const nx = x * ct - z * st;
    const nz = x * st + z * ct;
    x = nx;
    z = nz;
  }

  // 6. Keep bottom cleanly seated on the porcelain plate + vertical drop height
  if (y < 0) y = 0;
  y += phys.dropY;

  out[0] = x;
  out[1] = y;
  out[2] = z;
}

// Fast zero-allocation per-frame mesh deformation & smooth vertex normal recomputation
const _vA = new THREE.Vector3();
const _vB = new THREE.Vector3();
const _vC = new THREE.Vector3();
const _mBasis = new THREE.Matrix4();
const _xAxis = new THREE.Vector3();
const _yAxis = new THREE.Vector3();
const _zAxis = new THREE.Vector3();
const _tmpLook = new THREE.Vector3();

function sampleFeatureFrame(rest, w, posOut, quatOut) {
  const eps = 0.025;
  deformPoint(rest.x, rest.y, rest.z, w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase, _defOut);
  posOut.set(_defOut[0], _defOut[1], _defOut[2]);

  deformPoint(rest.x + eps, rest.y, rest.z, w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase, _defOut);
  _xAxis.set(_defOut[0] - posOut.x, _defOut[1] - posOut.y, _defOut[2] - posOut.z).normalize();

  deformPoint(rest.x, rest.y + eps, rest.z, w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase, _defOut);
  _yAxis.set(_defOut[0] - posOut.x, _defOut[1] - posOut.y, _defOut[2] - posOut.z).normalize();

  _zAxis.crossVectors(_xAxis, _yAxis).normalize();
  _yAxis.crossVectors(_zAxis, _xAxis).normalize();
  _mBasis.makeBasis(_xAxis, _yAxis, _zAxis);
  quatOut.setFromRotationMatrix(_mBasis);
}

function updateDeformedGeometry() {
  const {
    vCount, restPos, posArr, normArr, idxArr, posBuffer, normBuffer,
    wEarL, wEarR, wCheekL, wCheekR, wTail, wHead, wBase
  } = catData;

  for (let i = 0; i < vCount; i++) {
    const i3 = i * 3;
    deformPoint(
      restPos[i3], restPos[i3 + 1], restPos[i3 + 2],
      wEarL[i], wEarR[i], wCheekL[i], wCheekR[i], wTail[i], wHead[i], wBase[i],
      _defOut
    );
    posArr[i3]     = _defOut[0];
    posArr[i3 + 1] = _defOut[1];
    posArr[i3 + 2] = _defOut[2];
  }

  // Recompute smooth vertex normals directly in typed arrays
  normArr.fill(0);
  const triLen = idxArr.length;
  for (let t = 0; t < triLen; t += 3) {
    const ia = idxArr[t] * 3;
    const ib = idxArr[t + 1] * 3;
    const ic = idxArr[t + 2] * 3;

    const ax = posArr[ia], ay = posArr[ia + 1], az = posArr[ia + 2];
    const abx = posArr[ib] - ax, aby = posArr[ib + 1] - ay, abz = posArr[ib + 2] - az;
    const acx = posArr[ic] - ax, acy = posArr[ic + 1] - ay, acz = posArr[ic + 2] - az;

    const nx = aby * acz - abz * acy;
    const ny = abz * acx - abx * acz;
    const nz = abx * acy - aby * acx;

    normArr[ia] += nx; normArr[ia + 1] += ny; normArr[ia + 2] += nz;
    normArr[ib] += nx; normArr[ib + 1] += ny; normArr[ib + 2] += nz;
    normArr[ic] += nx; normArr[ic + 1] += ny; normArr[ic + 2] += nz;
  }

  for (let i = 0; i < vCount; i++) {
    const i3 = i * 3;
    const nx = normArr[i3], ny = normArr[i3 + 1], nz = normArr[i3 + 2];
    const len = Math.hypot(nx, ny, nz);
    if (len > 1e-8) {
      const inv = 1 / len;
      normArr[i3] = nx * inv;
      normArr[i3 + 1] = ny * inv;
      normArr[i3 + 2] = nz * inv;
    } else {
      normArr[i3] = 0; normArr[i3 + 1] = 1; normArr[i3 + 2] = 0;
    }
  }

  posBuffer.needsUpdate = true;
  normBuffer.needsUpdate = true;

  // Update internal shimmering air bubbles in lockstep
  const bSy = Math.exp(-clamp(phys.squash.p, -0.45, 0.55));
  const bSxz = Math.exp(clamp(phys.squash.p, -0.45, 0.55) * 0.5);
  for (let i = 0; i < bubbles.length; i++) {
    const b = bubbles[i];
    const w = b.w;
    deformPoint(b.x0, b.y0, b.z0, w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase, _defOut);
    b.mesh.position.set(_defOut[0], _defOut[1], _defOut[2]);
    const micro = 1 + 0.04 * Math.sin(phys.time * 2.5 + b.phase);
    b.mesh.scale.set(b.r * bSxz * micro, b.r * bSy * micro, b.r * bSxz * micro);
  }

  // Update glossy tracking eyes + happy squint / blink / surprise
  const happySquint = clamp(Math.max(phys.purrLevel * 1.15, phys.wince * 1.1), 0, 1);
  const blinkClose = Math.sin(phys.blinkVal * Math.PI);
  const eyeClose = clamp(Math.max(happySquint, blinkClose), 0, 1);
  const surpriseScale = 1.0 + phys.surprise * 0.16;

  for (let i = 0; i < eyes.length; i++) {
    const e = eyes[i];
    sampleFeatureFrame(e.rest, e.w, e.root.position, e.root.quaternion);
    // Slight inward flush recess along face normal so eye hugs the glossy jelly face
    e.root.translateZ(-0.008);

    // Morph open eye vs happy squint crescent
    const openY = Math.max(0.06, 1.0 - eyeClose * 0.92) * surpriseScale;
    e.openGroup.scale.set(surpriseScale, openY, 1.0);
    e.openGroup.visible = eyeClose < 0.88;

    const arcAmt = smoothstep(0.32, 0.92, happySquint);
    e.squintArc.visible = arcAmt > 0.01;
    e.squintArc.scale.set(
      lerp(0.6, 1.08, arcAmt),
      lerp(0.2, phys.wince > 0.35 ? 0.65 : 1.05, arcAmt),
      1.0
    );
    // Slight cute tilt on wince
    e.squintArc.rotation.z = phys.wince > 0.25 ? e.side * -0.18 * phys.wince : 0;

    // Eye pupil tracking toward finger/pointer in local eye space
    _tmpLook.copy(phys.lookCurrent);
    e.root.worldToLocal(_tmpLook);
    const lenL = _tmpLook.length() || 1;
    const lx = clamp((_tmpLook.x / lenL) * 0.068, -0.030, 0.030);
    const ly = clamp((_tmpLook.y / lenL) * 0.068, -0.026, 0.028);
    e.trackGroup.position.set(lx, ly, 0);
  }

  // Update glossy button nose
  sampleFeatureFrame(noseAnchor.rest, noseAnchor.w, noseMesh.position, noseMesh.quaternion);
  noseMesh.translateZ(0.006);

  // Update deformable ':3' mouth (corners lift happily when purring!)
  const smileLift = phys.purrLevel * 0.024;
  for (let i = 0; i < mouthObj.meta.length; i++) {
    const m = mouthObj.meta[i];
    const w = m.w;
    deformPoint(
      m.x0, m.y0 + smileLift * m.au * m.au, m.z0,
      w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase,
      _defOut
    );
    mouthObj.positions[i * 3]     = _defOut[0];
    mouthObj.positions[i * 3 + 1] = _defOut[1];
    mouthObj.positions[i * 3 + 2] = _defOut[2];
  }
  mouthObj.posAttr.needsUpdate = true;
  mouthObj.geo.computeVertexNormals();

  // Update flexible whiskers
  for (let k = 0; k < whiskers.length; k++) {
    const wh = whiskers[k];
    for (let i = 0; i < wh.meta.length; i++) {
      const m = wh.meta[i];
      const w = m.w;
      deformPoint(
        m.x0, m.y0, m.z0,
        w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase,
        _defOut
      );
      wh.positions[i * 3]     = _defOut[0];
      wh.positions[i * 3 + 1] = _defOut[1];
      wh.positions[i * 3 + 2] = _defOut[2];
    }
    wh.posAttr.needsUpdate = true;
  }

  // Update rosy cheek blush
  blush.mat.opacity = lerp(0.20, 0.72, phys.purrLevel);
  for (let i = 0; i < blush.discs.length; i++) {
    const b = blush.discs[i];
    sampleFeatureFrame(b.rest, b.w, b.mesh.position, b.mesh.quaternion);
    b.mesh.translateZ(0.011);
    const sc = 1.0 + phys.purrLevel * 0.16;
    b.mesh.scale.set(sc, sc, 1);
  }

  // Update shader uniforms (inner soft glow & dynamic plate caustics)
  glowUniforms.uPurr.value = phys.purrLevel;
  glowUniforms.uFirmness.value = phys.firmness;
  glowUniforms.uTime.value = phys.time;

  // Subtle physical material roughness/clearness shift from Soft Pudding -> Firm Gummy
  jellyMat.roughness = lerp(0.068, 0.038, phys.firmness);

  const wobbleEnergy = clamp(
    Math.abs(phys.squash.v) * 0.18 + Math.abs(phys.leanX.v) * 0.2 + phys.rippleAmp * 8.0,
    0, 1.5
  );
  causticUniforms.uTime.value = phys.time;
  causticUniforms.uOffset.value.set(phys.leanX.p, -phys.leanZ.p);
  causticUniforms.uSquash.value = phys.squash.p + (1 - phys.firmness) * 0.08;
  causticUniforms.uDropY.value = phys.dropY;
  causticUniforms.uEnergy.value = wobbleEnergy;
  causticUniforms.uPurr.value = phys.purrLevel;
}

// ============================================================================
// 8. CAMERA ORBIT & RESPONSIVE FRAMING
// ============================================================================
const camState = {
  theta: 0.22,
  phi: 0.34,
  targetTheta: 0.22,
  targetPhi: 0.34,
  dist: 4.85,
  targetY: 0.90
};

function updateCameraProjection() {
  const w = window.innerWidth;
  const h = window.innerHeight;
  const aspect = w / Math.max(1, h);
  camera.aspect = aspect;
  camera.updateProjectionMatrix();
  renderer.setSize(w, h);

  // Pull camera slightly back on narrow portrait phones so the plate, tail & drop all frame cleanly
  if (aspect < 0.85) {
    camState.dist = clamp(4.75 / Math.pow(aspect / 0.85, 0.62), 4.75, 6.9);
    camState.targetY = 0.78;
  } else {
    camState.dist = 4.65;
    camState.targetY = 0.90;
  }
}

function applyCameraTransform(dt) {
  camState.theta = lerp(camState.theta, camState.targetTheta, clamp(dt * 12, 0, 1));
  camState.phi = lerp(camState.phi, camState.targetPhi, clamp(dt * 12, 0, 1));
  const r = camState.dist;
  const cp = Math.cos(camState.phi);
  camera.position.set(
    Math.sin(camState.theta) * cp * r,
    camState.targetY + Math.sin(camState.phi) * r,
    Math.cos(camState.theta) * cp * r
  );
  camera.lookAt(0.06, camState.targetY, 0.0);
}

updateCameraProjection();
applyCameraTransform(1);
window.addEventListener('resize', updateCameraProjection);

// ============================================================================
// 9. UNIFIED TOUCH & MOUSE INTERACTION (POKE, SQUEEZE, PULL, RUB HEAD, ORBIT)
// ============================================================================
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const planeHit = new THREE.Vector3();
const camForward = new THREE.Vector3();
const bary = new THREE.Vector3();

const activePointers = new Map();
let pinchStartDist = 0;

const dragState = {
  active: false,
  pointerId: -1,
  zone: null, // 'earL' | 'earR' | 'cheekL' | 'cheekR' | 'tail' | 'headTop' | 'body' | 'orbit'
  startHit: new THREE.Vector3(),
  lastHit: new THREE.Vector3(),
  restHit: new THREE.Vector3(),
  hitNormal: new THREE.Vector3(0, 0, 1),
  lastClientX: 0,
  lastClientY: 0,
  totalMove: 0,
  holdTime: 0,
  stretchVec: new THREE.Vector3()
};

function clientToNdc(clientX, clientY, out) {
  const rect = renderer.domElement.getBoundingClientRect();
  out.x = ((clientX - rect.left) / rect.width) * 2 - 1;
  out.y = -((clientY - rect.top) / rect.height) * 2 + 1;
}

function updateLookFromNdc(nx, ny) {
  raycaster.setFromCamera({ x: nx, y: ny }, camera);
  // Intersect a gentle virtual plane in front of the cat's face so eyes track finger naturally
  const lookPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -1.85);
  const pt = new THREE.Vector3();
  if (raycaster.ray.intersectPlane(lookPlane, pt)) {
    phys.lookTarget.set(clamp(pt.x, -2.5, 2.5), clamp(pt.y, 0.2, 2.8), clamp(pt.z, 1.2, 4.0));
  }
  phys.pointerActiveTimer = 3.2;
}

// Proximity forgiveness anchors so grabbing ears, tail or cheeks on a phone feels effortless
const GRAB_ANCHORS = [
  { zone: 'earL',   rx:  0.42, ry: 1.84, rz: 0.10, rad: 0.27 },
  { zone: 'earR',   rx: -0.42, ry: 1.84, rz: 0.10, rad: 0.27 },
  { zone: 'tail',   rx:  0.96, ry: 0.34, rz: 0.38, rad: 0.28 },
  { zone: 'cheekL', rx:  0.45, ry: 1.18, rz: 0.34, rad: 0.24 },
  { zone: 'cheekR', rx: -0.45, ry: 1.18, rz: 0.34, rad: 0.24 }
];

function classifyCatHit(hit) {
  const face = hit.face;
  const ia = face.a, ib = face.b, ic = face.c;
  const pos = catData.posArr;
  const rest = catData.restPos;

  _vA.set(pos[ia * 3], pos[ia * 3 + 1], pos[ia * 3 + 2]);
  _vB.set(pos[ib * 3], pos[ib * 3 + 1], pos[ib * 3 + 2]);
  _vC.set(pos[ic * 3], pos[ic * 3 + 1], pos[ic * 3 + 2]);
  THREE.Triangle.getBarycoord(hit.point, _vA, _vB, _vC, bary);

  const rx = rest[ia * 3] * bary.x + rest[ib * 3] * bary.y + rest[ic * 3] * bary.z;
  const ry = rest[ia * 3 + 1] * bary.x + rest[ib * 3 + 1] * bary.y + rest[ic * 3 + 1] * bary.z;
  const rz = rest[ia * 3 + 2] * bary.x + rest[ib * 3 + 2] * bary.y + rest[ic * 3 + 2] * bary.z;

  const wTail = catData.wTail[ia] * bary.x + catData.wTail[ib] * bary.y + catData.wTail[ic] * bary.z;
  const wCheekL = catData.wCheekL[ia] * bary.x + catData.wCheekL[ib] * bary.y + catData.wCheekL[ic] * bary.z;
  const wCheekR = catData.wCheekR[ia] * bary.x + catData.wCheekR[ib] * bary.y + catData.wCheekR[ic] * bary.z;

  let zone = 'body';
  if (ry > 1.54 && rx > 0.14) zone = 'earL';
  else if (ry > 1.54 && rx < -0.14) zone = 'earR';
  else if (wTail > 0.24) zone = 'tail';
  else if (wCheekL > 0.36 && rz > 0.12) zone = 'cheekL';
  else if (wCheekR > 0.36 && rz > 0.12) zone = 'cheekR';
  else if (ry > 1.38 && Math.abs(rx) <= 0.36) zone = 'headTop';

  const normal = hit.face.normal.clone().normalize();
  return { zone, restPt: new THREE.Vector3(rx, ry, rz), worldPt: hit.point.clone(), normal };
}

function pickCatAtNdc(nx, ny) {
  raycaster.setFromCamera({ x: nx, y: ny }, camera);
  const hits = raycaster.intersectObject(catMesh, false);
  if (hits.length > 0) {
    return classifyCatHit(hits[0]);
  }
  // Soft forgiveness fallback for grabbing ears / tail tip with a finger
  let best = null;
  let bestD = 1e9;
  const pt = new THREE.Vector3();
  for (let i = 0; i < GRAB_ANCHORS.length; i++) {
    const a = GRAB_ANCHORS[i];
    const w = computePartWeights(a.rx, a.ry, a.rz);
    deformPoint(a.rx, a.ry, a.rz, w.wEarL, w.wEarR, w.wCheekL, w.wCheekR, w.wTail, w.wHead, w.wBase, _defOut);
    pt.set(_defOut[0], _defOut[1], _defOut[2]);
    const distToRay = raycaster.ray.distanceToPoint(pt);
    if (distToRay < a.rad && distToRay < bestD) {
      bestD = distToRay;
      best = {
        zone: a.zone,
        restPt: new THREE.Vector3(a.rx, a.ry, a.rz),
        worldPt: pt.clone(),
        normal: new THREE.Vector3(0, 0, 1)
      };
    }
  }
  return best;
}

function softLimit3D(v, maxLen) {
  const len = v.length();
  if (len < 1e-5) return v;
  const scaled = maxLen * Math.tanh(len / maxLen);
  return v.multiplyScalar(scaled / len);
}

function beginInteraction(nx, ny, clientX, clientY, pointerId) {
  updateLookFromNdc(nx, ny);
  const picked = pickCatAtNdc(nx, ny);

  dragState.active = true;
  dragState.pointerId = pointerId;
  dragState.lastClientX = clientX;
  dragState.lastClientY = clientY;
  dragState.totalMove = 0;
  dragState.holdTime = 0;
  dragState.stretchVec.set(0, 0, 0);

  if (!picked) {
    dragState.zone = 'orbit';
    renderer.domElement.classList.add('grabbing');
    return;
  }

  dragState.zone = picked.zone;
  dragState.startHit.copy(picked.worldPt);
  dragState.lastHit.copy(picked.worldPt);
  dragState.restHit.copy(picked.restPt);
  dragState.hitNormal.copy(picked.normal);

  camera.getWorldDirection(camForward);
  dragPlane.setFromNormalAndCoplanarPoint(camForward, picked.worldPt);
  renderer.domElement.classList.add('grabbing');

  // Immediate juicy poke feedback on tap/press!
  if (picked.zone === 'headTop') {
    // Gentle soft pet contact on the crown
    addPokeImpulse(picked.restPt.x, picked.restPt.y, picked.restPt.z, picked.normal.x, picked.normal.y, picked.normal.z, 0.13);
    phys.rubEnergy = Math.min(1.15, phys.rubEnergy + 0.18);
    audio.playPoke(0.42, phys.firmness);
  } else {
    const str = picked.zone === 'body' ? 0.28 : 0.18;
    addPokeImpulse(picked.restPt.x, picked.restPt.y, picked.restPt.z, picked.normal.x, picked.normal.y, picked.normal.z, str);
    audio.playPoke(picked.zone === 'body' ? 0.85 : 0.62, phys.firmness);
  }

  // Anchor localized free-grab at contact point
  phys.grabPos.x = picked.restPt.x;
  phys.grabPos.y = picked.restPt.y;
  phys.grabPos.z = picked.restPt.z;
  phys.grabRadius = picked.zone === 'body' ? 0.44 : 0.32;
}

function moveInteraction(nx, ny, clientX, clientY) {
  updateLookFromNdc(nx, ny);
  if (!dragState.active) return;

  const dxPx = clientX - dragState.lastClientX;
  const dyPx = clientY - dragState.lastClientY;
  dragState.lastClientX = clientX;
  dragState.lastClientY = clientY;
  dragState.totalMove += Math.hypot(dxPx, dyPx);

  if (dragState.zone === 'orbit') {
    camState.targetTheta -= dxPx * 0.0085;
    camState.targetPhi = clamp(camState.targetPhi + dyPx * 0.007, 0.14, 1.18);
    return;
  }

  raycaster.setFromCamera({ x: nx, y: ny }, camera);
  if (!raycaster.ray.intersectPlane(dragPlane, planeHit)) return;

  const stepDist = planeHit.distanceTo(dragState.lastHit);
  const delta = planeHit.clone().sub(dragState.startHit);
  dragState.lastHit.copy(planeHit);

  const comp = lerp(1.38, 0.62, phys.firmness);
  const z = dragState.zone;

  if (z === 'earL' || z === 'earR' || z === 'cheekL' || z === 'cheekR' || z === 'tail') {
    const maxStretch = (z === 'cheekL' || z === 'cheekR' ? 0.46 : 0.72) * lerp(1.22, 0.68, phys.firmness);
    const v = softLimit3D(delta.clone().multiplyScalar(0.95 * comp), maxStretch);
    dragState.stretchVec.copy(v);

    const sp = phys[z];
    sp.tx = v.x;
    sp.ty = v.y;
    sp.tz = v.z;

    // Couple tug organically into head & body sway
    const couple = z === 'tail' ? 0.24 : 0.32;
    phys.leanX.t = clamp(v.x * couple, -0.35, 0.35);
    phys.leanZ.t = clamp(v.z * couple, -0.35, 0.35);
    if (z !== 'tail') {
      phys.head.tx = v.x * 0.28;
      phys.head.ty = v.y * 0.22;
      phys.head.tz = v.z * 0.22;
    } else {
      phys.twistY.t = clamp(-v.z * 0.25 + v.x * 0.14, -0.32, 0.32);
    }

    if (stepDist > 0.028) {
      audio.playStretch(clamp(stepDist * 10, 0.2, 0.9), phys.firmness);
    }
  } else if (z === 'headTop') {
    // Rubbing across the head triggers squinting & purring!
    const horizStep = Math.hypot(dxPx, dyPx * 0.55);
    if (horizStep > 1.5 && delta.y > -0.22 && delta.y < 0.26) {
      phys.rubEnergy = Math.min(1.25, phys.rubEnergy + horizStep * 0.0085);
      // Gentle affectionate lean into head rubs
      phys.head.tx = clamp(delta.x * 0.24, -0.14, 0.14);
      phys.head.ty = -0.055 * comp;
      phys.head.tz = clamp(delta.z * 0.15, -0.08, 0.08);
      phys.leanX.t = clamp(delta.x * 0.14, -0.12, 0.12);
      phys.squash.t = 0.06 * comp;
    } else if (delta.y <= -0.22) {
      // Pushing down hard on the head squishes the whole cat!
      phys.squash.t = clamp(-delta.y * 0.58 * comp, 0, 0.48);
      if (stepDist > 0.03) audio.playStretch(0.45, phys.firmness);
    } else if (delta.y >= 0.26) {
      // Pulling straight up stretches the crown playfully
      const v = softLimit3D(delta.clone().multiplyScalar(0.55 * comp), 0.38);
      phys.grab.tx = v.x;
      phys.grab.ty = v.y;
      phys.grab.tz = v.z;
      phys.squash.t = clamp(-v.y * 0.45, -0.26, 0.1);
      if (stepDist > 0.03) audio.playStretch(0.5, phys.firmness);
    }
  } else if (z === 'body') {
    // Pressing down squeezes/squishes the jelly; dragging kneads/pulls it locally
    const downSquish = clamp(-delta.y * 0.62 * comp, -0.22, 0.50);
    phys.squash.t = downSquish;
    phys.leanX.t = clamp(delta.x * 0.36 * comp, -0.35, 0.35);
    phys.leanZ.t = clamp(delta.z * 0.36 * comp, -0.35, 0.35);

    const v = softLimit3D(delta.clone().multiplyScalar(0.55 * comp), 0.36);
    phys.grab.tx = v.x;
    phys.grab.ty = v.y * 0.65;
    phys.grab.tz = v.z;
    dragState.stretchVec.copy(v);

    // If user slides their finger gently over the upper head while pressing, also allow petting/purring!
    if (planeHit.y > 1.36 && Math.abs(planeHit.x) < 0.46 && stepDist > 0.012) {
      phys.rubEnergy = Math.min(1.2, phys.rubEnergy + stepDist * 1.4);
    }
    if (stepDist > 0.032) {
      audio.playStretch(clamp(stepDist * 9, 0.2, 0.85), phys.firmness);
    }
  }
}

function endInteraction() {
  if (!dragState.active) return;
  const z = dragState.zone;
  const stretchAmt = dragState.stretchVec.length();
  const squishAmt = Math.abs(phys.squash.t);

  // Release all active targets back to 0 with snappy recoil
  if (z === 'earL' || z === 'earR' || z === 'cheekL' || z === 'cheekR' || z === 'tail') {
    const sp = phys[z];
    sp.vx -= sp.tx * 5.2;
    sp.vy -= sp.ty * 5.2;
    sp.vz -= sp.tz * 5.2;
    sp.tx = sp.ty = sp.tz = 0;
  }
  phys.head.tx = phys.head.ty = phys.head.tz = 0;
  phys.grab.tx = phys.grab.ty = phys.grab.tz = 0;
  phys.squash.t = 0;
  phys.leanX.t = 0;
  phys.leanZ.t = 0;
  phys.twistY.t = 0;

  if (z !== 'orbit' && (stretchAmt > 0.08 || squishAmt > 0.08)) {
    const power = clamp(Math.max(stretchAmt * 1.7, squishAmt * 1.8), 0.25, 1.0);
    phys.rippleAmp = Math.min(0.09, phys.rippleAmp + 0.045 * power);
    audio.playReleaseBoing(power, phys.firmness);
  }

  dragState.active = false;
  dragState.zone = null;
  dragState.pointerId = -1;
  renderer.domElement.classList.remove('grabbing');
}

// Press-and-hold gentle belly squeeze even without dragging
function updateHoldSqueeze(dt) {
  if (!dragState.active || dragState.zone !== 'body') return;
  dragState.holdTime += dt;
  if (dragState.totalMove < 22 && dragState.holdTime > 0.14) {
    const comp = lerp(1.38, 0.62, phys.firmness);
    const holdAmt = clamp((dragState.holdTime - 0.14) * 0.95, 0, 0.42) * comp;
    phys.squash.t = Math.max(phys.squash.t, holdAmt);
    phys.grab.tx = -dragState.hitNormal.x * holdAmt * 0.45;
    phys.grab.ty = -dragState.hitNormal.y * holdAmt * 0.45;
    phys.grab.tz = -dragState.hitNormal.z * holdAmt * 0.45;
  }
}

// Hide initial hint cleanly on first real touch
const hintPill = document.getElementById('hint-pill');
let hintHidden = false;
function hideHint() {
  if (hintHidden) return;
  hintHidden = true;
  hintPill.classList.add('hidden');
}

const domEl = renderer.domElement;

domEl.addEventListener('pointerdown', (e) => {
  if (!e.isPrimary && activePointers.size >= 2) return;
  audio.unlock();
  hideHint();
  activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });

  try { domEl.setPointerCapture(e.pointerId); } catch (_) {}

  // Two-finger pinch squeeze on touch devices!
  if (activePointers.size === 2) {
    const pts = Array.from(activePointers.values());
    pinchStartDist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
    endInteraction();
    return;
  }

  clientToNdc(e.clientX, e.clientY, ndc);
  beginInteraction(ndc.x, ndc.y, e.clientX, e.clientY, e.pointerId);
});

domEl.addEventListener('pointermove', (e) => {
  if (activePointers.has(e.pointerId)) {
    activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
  }

  // Two-finger pinch squeeze!
  if (activePointers.size === 2) {
    const pts = Array.from(activePointers.values());
    const curDist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
    const ratio = (pinchStartDist - curDist) / Math.max(120, Math.min(window.innerWidth, window.innerHeight) * 0.45);
    const comp = lerp(1.38, 0.62, phys.firmness);
    phys.squash.t = clamp(ratio * 0.85 * comp, -0.32, 0.52);
    audio.playStretch(Math.min(0.8, Math.abs(ratio)), phys.firmness);
    return;
  }

  clientToNdc(e.clientX, e.clientY, ndc);
  if (dragState.active && dragState.pointerId === e.pointerId) {
    moveInteraction(ndc.x, ndc.y, e.clientX, e.clientY);
  } else if (!demoState.active) {
    // Eyes always curiously follow pointer movement!
    updateLookFromNdc(ndc.x, ndc.y);
  }
});

function handlePointerUpOrCancel(e) {
  const wasPinch = activePointers.size >= 2;
  activePointers.delete(e.pointerId);
  try { domEl.releasePointerCapture(e.pointerId); } catch (_) {}

  if (wasPinch && activePointers.size < 2) {
    const sq = Math.abs(phys.squash.t);
    phys.squash.t = 0;
    if (sq > 0.08) audio.playReleaseBoing(clamp(sq * 1.8, 0.3, 1.0), phys.firmness);
  }
  if (dragState.active && dragState.pointerId === e.pointerId) {
    endInteraction();
  }
}

domEl.addEventListener('pointerup', handlePointerUpOrCancel);
domEl.addEventListener('pointercancel', handlePointerUpOrCancel);

// ============================================================================
// 10. UI CONTROLS: DROP BUTTON, FIRMNESS SLIDER, SOUND TOGGLE
// ============================================================================
const dropBtn = document.getElementById('drop-btn');
const sliderEl = document.getElementById('firmness-slider');
const firmnessTag = document.getElementById('firmness-tag');
const muteBtn = document.getElementById('mute-btn');
const iconSoundOn = document.getElementById('icon-sound-on');
const iconSoundOff = document.getElementById('icon-sound-off');

function applyFirmness(val01, fromDemo = false) {
  phys.firmness = clamp(val01, 0, 1);
  if (fromDemo) {
    sliderEl.value = String(Math.round(phys.firmness * 100));
  }
  if (phys.firmness < 0.28) firmnessTag.textContent = 'Soft Pudding';
  else if (phys.firmness < 0.68) firmnessTag.textContent = 'Wobbly Jelly';
  else firmnessTag.textContent = 'Firm Gummy';
}

dropBtn.addEventListener('pointerdown', () => {
  audio.unlock();
  hideHint();
  dropBtn.classList.add('pressed');
  setTimeout(() => dropBtn.classList.remove('pressed'), 160);
  triggerDrop();
});

sliderEl.addEventListener('input', () => {
  audio.unlock();
  hideHint();
  applyFirmness(Number(sliderEl.value) / 100, false);
  // Subtle playful jiggle preview so you immediately feel the new texture!
  phys.squash.v += (Math.random() > 0.5 ? 1 : -1) * 0.65;
});

muteBtn.addEventListener('click', () => {
  audio.unlock();
  audio.setMuted(!audio.muted);
  muteBtn.classList.toggle('muted', audio.muted);
  iconSoundOn.style.display = audio.muted ? 'none' : '';
  iconSoundOff.style.display = audio.muted ? '' : 'none';
  try { localStorage.setItem('jellycat_muted', audio.muted ? '1' : '0'); } catch (_) {}
});

// Safe optional restore of mute setting in sandboxed iframe
try {
  if (localStorage.getItem('jellycat_muted') === '1') {
    audio.setMuted(true);
    muteBtn.classList.add('muted', true);
    iconSoundOn.style.display = 'none';
    iconSoundOff.style.display = '';
  }
} catch (_) {}

applyFirmness(0.40, true);

// ============================================================================
// 11. #demo HANDS-FREE 20-SECOND SHOWCASE LOOP (ANY REAL TOUCH ENDS IT)
// ============================================================================
const demoBadge = document.getElementById('demo-badge');
const demoLabel = document.getElementById('demo-label');
const demoCursor = document.getElementById('demo-cursor');

const DEMO_DURATION = 20.0;
const demoState = {
  active: false,
  t: 0,
  lastActionId: -1,
  grabActive: false
};

const _projV = new THREE.Vector3();
function projectWorldToScreen(x, y, z) {
  _projV.set(x, y, z).project(camera);
  return {
    sx: (_projV.x * 0.5 + 0.5) * window.innerWidth,
    sy: (-_projV.y * 0.5 + 0.5) * window.innerHeight,
    nx: _projV.x,
    ny: _projV.y
  };
}

function setDemoCursor(wx, wy, wz, down, visible = true) {
  if (!visible) {
    demoCursor.style.opacity = '0';
    return;
  }
  const p = projectWorldToScreen(wx, wy, wz);
  demoCursor.style.opacity = '1';
  demoCursor.classList.toggle('down', down);
  demoCursor.style.transform = `translate3d(${p.sx.toFixed(1)}px, ${p.sy.toFixed(1)}px, 0) scale(${down ? 0.84 : 1.0})`;
  phys.lookTarget.set(clamp(wx * 1.4, -2.2, 2.2), clamp(wy, 0.3, 2.5), 2.1);
}

function clearDemoTargets() {
  phys.earL.tx = phys.earL.ty = phys.earL.tz = 0;
  phys.earR.tx = phys.earR.ty = phys.earR.tz = 0;
  phys.cheekL.tx = phys.cheekL.ty = phys.cheekL.tz = 0;
  phys.cheekR.tx = phys.cheekR.ty = phys.cheekR.tz = 0;
  phys.tail.tx = phys.tail.ty = phys.tail.tz = 0;
  phys.head.tx = phys.head.ty = phys.head.tz = 0;
  phys.grab.tx = phys.grab.ty = phys.grab.tz = 0;
  phys.squash.t = 0;
  phys.leanX.t = 0;
  phys.leanZ.t = 0;
  phys.twistY.t = 0;
}

function startDemo() {
  demoState.active = true;
  demoState.t = 0;
  demoState.lastActionId = -1;
  demoBadge.classList.add('active');
  hintPill.classList.add('hidden');
  camState.targetTheta = 0.22;
  camState.targetPhi = 0.34;
}

function stopDemo() {
  if (!demoState.active) return;
  demoState.active = false;
  demoBadge.classList.remove('active');
  demoCursor.style.opacity = '0';
  clearDemoTargets();
}

function checkDemoHash() {
  if (window.location.hash === '#demo' || window.location.href.endsWith('#demo')) {
    startDemo();
  }
}

// Any real user touch/click/key immediately ends #demo cleanly
function onRealUserEvent(e) {
  if (e && e.isTrusted && demoState.active) {
    stopDemo();
  }
}
window.addEventListener('pointerdown', onRealUserEvent, { capture: true, passive: true });
window.addEventListener('touchstart', onRealUserEvent, { capture: true, passive: true });
window.addEventListener('mousedown', onRealUserEvent, { capture: true, passive: true });
window.addEventListener('wheel', onRealUserEvent, { capture: true, passive: true });
window.addEventListener('keydown', onRealUserEvent, { capture: true, passive: true });
window.addEventListener('hashchange', checkDemoHash);

function stepDemo(dt) {
  if (!demoState.active) return;
  const prevT = demoState.t;
  demoState.t = (demoState.t + dt) % DEMO_DURATION;
  const t = demoState.t;
  if (t < prevT) demoState.lastActionId = -1;

  // Subtle slow showcase camera sway
  camState.targetTheta = 0.22 + Math.sin((t / DEMO_DURATION) * Math.PI * 2) * 0.22;
  camState.targetPhi = 0.33 + Math.sin((t / DEMO_DURATION) * Math.PI * 4) * 0.04;

  const fireOnce = (id, fn) => {
    if (demoState.lastActionId < id) {
      demoState.lastActionId = id;
      fn();
    }
  };

  // 0.0 - 2.4s: Poke & Squish Chubby Belly
  if (t < 2.4) {
    demoLabel.textContent = 'Demo: Poke & Squish';
    clearDemoTargets();
    if (t < 0.65) {
      const k = smoothstep(0, 0.55, t);
      setDemoCursor(lerp(-0.9, 0.04, k), lerp(0.95, 0.62, k), 0.68, false, true);
    } else if (t < 1.05) {
      fireOnce(1, () => {
        addPokeImpulse(0.04, 0.62, 0.64, 0, 0, 1, 0.34);
        audio.playPoke(0.85, phys.firmness);
      });
      setDemoCursor(0.04, 0.60, 0.56, true, true);
    } else if (t < 1.95) {
      const sq = Math.sin(smoothstep(1.05, 1.95, t) * Math.PI);
      phys.squash.t = sq * 0.42;
      setDemoCursor(0.0, lerp(0.82, 0.46, sq), 0.60, sq > 0.12, true);
    } else {
      fireOnce(2, () => audio.playReleaseBoing(0.8, phys.firmness));
      setDemoCursor(0.18, 1.15, 0.52, false, true);
    }
  }
  // 2.4 - 5.0s: Pull Ear & Snap Back
  else if (t < 5.0) {
    demoLabel.textContent = 'Demo: Pull Ear';
    clearDemoTargets();
    if (t < 2.8) {
      const k = smoothstep(2.4, 2.8, t);
      setDemoCursor(lerp(0.18, 0.43, k), lerp(1.15, 1.88, k), 0.14, false, true);
    } else if (t < 4.05) {
      const k = smoothstep(2.8, 3.85, t);
      const px = k * 0.48, py = k * 0.38;
      phys.earL.tx = px; phys.earL.ty = py; phys.earL.tz = k * 0.08;
      phys.head.tx = px * 0.32; phys.head.ty = py * 0.20;
      phys.leanX.t = px * 0.28;
      setDemoCursor(0.43 + px, 1.88 + py, 0.18, true, true);
    } else {
      fireOnce(3, () => {
        phys.earL.vx -= 3.2; phys.earL.vy -= 2.6;
        phys.rippleAmp = 0.06;
        audio.playReleaseBoing(0.85, phys.firmness);
      });
      setDemoCursor(0.90, 2.24, 0.22, false, t < 4.55);
    }
  }
  // 5.0 - 7.5s: Pull Puffy Cheek & Snap Back
  else if (t < 7.5) {
    demoLabel.textContent = 'Demo: Pull Cheek';
    clearDemoTargets();
    if (t < 5.4) {
      const k = smoothstep(5.0, 5.4, t);
      setDemoCursor(lerp(0.5, -0.44, k), lerp(1.6, 1.19, k), 0.42, false, true);
    } else if (t < 6.55) {
      const k = smoothstep(5.4, 6.35, t);
      const px = -k * 0.42, py = k * 0.05;
      phys.cheekR.tx = px; phys.cheekR.ty = py; phys.cheekR.tz = k * 0.14;
      phys.head.tx = px * 0.28;
      phys.leanX.t = px * 0.26;
      setDemoCursor(-0.44 + px, 1.19 + py, 0.48, true, true);
    } else {
      fireOnce(4, () => {
        phys.cheekR.vx += 2.8;
        phys.rippleAmp = 0.05;
        audio.playReleaseBoing(0.75, phys.firmness);
      });
      setDemoCursor(-0.86, 1.24, 0.50, false, t < 7.1);
    }
  }
  // 7.5 - 10.2s: Pull Curled Tail & Snap Back
  else if (t < 10.2) {
    demoLabel.textContent = 'Demo: Pull Tail';
    clearDemoTargets();
    if (t < 7.9) {
      const k = smoothstep(7.5, 7.9, t);
      setDemoCursor(lerp(-0.4, 0.94, k), lerp(1.1, 0.38, k), 0.46, false, true);
    } else if (t < 9.2) {
      const k = smoothstep(7.9, 9.0, t);
      const px = k * 0.56, py = k * 0.22, pz = k * 0.18;
      phys.tail.tx = px; phys.tail.ty = py; phys.tail.tz = pz;
      phys.leanX.t = px * 0.22;
      phys.twistY.t = -0.18 * k;
      setDemoCursor(0.94 + px, 0.38 + py, 0.46 + pz, true, true);
    } else {
      fireOnce(5, () => {
        phys.tail.vx -= 3.6; phys.tail.vy -= 1.8;
        phys.rippleAmp = 0.065;
        audio.playReleaseBoing(0.88, phys.firmness);
      });
      setDemoCursor(1.48, 0.60, 0.64, false, t < 9.75);
    }
  }
  // 10.2 - 13.8s: Rub Head -> Squints & Purrs
  else if (t < 13.8) {
    demoLabel.textContent = 'Demo: Head Rub & Purr';
    clearDemoTargets();
    const rubT = t - 10.2;
    const strokeX = Math.sin(rubT * 6.5) * 0.26;
    const strokeY = 1.72 - Math.abs(strokeX) * 0.12;
    phys.rubEnergy = 1.15;
    phys.head.tx = strokeX * 0.30;
    phys.head.ty = -0.06;
    phys.leanX.t = strokeX * 0.15;
    phys.squash.t = 0.07;
    setDemoCursor(strokeX, strokeY, 0.30, true, true);
  }
  // 13.8 - 16.8s: Soft Pudding Drop!
  else if (t < 16.8) {
    demoLabel.textContent = 'Demo: Soft Pudding Drop';
    clearDemoTargets();
    setDemoCursor(0, 1.2, 0.5, false, false);
    if (t < 14.3) {
      const k = smoothstep(13.8, 14.25, t);
      applyFirmness(lerp(0.40, 0.08, k), true);
    } else {
      fireOnce(6, () => {
        applyFirmness(0.08, true);
        dropBtn.classList.add('pressed');
        setTimeout(() => dropBtn.classList.remove('pressed'), 180);
        triggerDrop();
      });
    }
  }
  // 16.8 - 20.0s: Firm Gummy Drop!
  else {
    demoLabel.textContent = 'Demo: Firm Gummy Drop';
    clearDemoTargets();
    setDemoCursor(0, 1.2, 0.5, false, false);
    if (t < 17.45) {
      const k = smoothstep(16.8, 17.4, t);
      applyFirmness(lerp(0.08, 0.92, k), true);
    } else if (t < 19.4) {
      fireOnce(7, () => {
        applyFirmness(0.92, true);
        dropBtn.classList.add('pressed');
        setTimeout(() => dropBtn.classList.remove('pressed'), 180);
        triggerDrop();
      });
    } else {
      const k = smoothstep(19.4, 20.0, t);
      applyFirmness(lerp(0.92, 0.40, k), true);
    }
  }
}

// ============================================================================
// 12. MAIN ANIMATION LOOP (FIXED-SUBSTEP PHYSICS + 60FPS RENDER)
// ============================================================================
checkDemoHash();

// Gentle welcoming jiggle right on load so the cat immediately feels alive and jelly-like
phys.squash.v = 1.45;
phys.earL.vy = -0.8;
phys.earR.vy = -0.8;
phys.tail.vx = 0.7;

let lastTime = performance.now();
function animate(now) {
  requestAnimationFrame(animate);
  const rawDt = Math.min((now - lastTime) / 1000, 0.05);
  lastTime = now;

  stepDemo(rawDt);
  updateHoldSqueeze(rawDt);

  // Fixed substepping (<= 1/120s) guarantees rock-solid spring stability at any refresh rate
  const maxStep = 1 / 120;
  let rem = rawDt;
  while (rem > 0) {
    const dt = Math.min(rem, maxStep);
    stepPhysics(dt);
    rem -= dt;
  }

  audio.updatePurr(phys.purrLevel, rawDt);
  updateDeformedGeometry();
  applyCameraTransform(rawDt);

  renderer.render(scene, camera);
}

requestAnimationFrame(animate);
</script>
</body>
</html>