Skip to content
VibeCodeBench
Back to the app

The code

Build a Cell, Part by Part by Claude Haiku 5.5

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

index.html

broken · auto-checked (Checked by an automated pass. Not hand-played yet.)23.3 KB · 607 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Animal Cell 3D</title>
<style>
  :root { --bg:#0b1020; --panel:rgba(14,22,44,.86); --ink:#eaf2ff; --muted:#9fb3d9; --accent:#5ed0ff; }
  @media (prefers-color-scheme: light) { :root:not([data-theme="dark"]) { --bg:#e9f1ff; --panel:rgba(255,255,255,.9); --ink:#0b1630; --muted:#3b4f78; --accent:#1479c9; } }
  :root[data-theme="dark"] { --bg:#0b1020; --panel:rgba(14,22,44,.86); --ink:#eaf2ff; --muted:#9fb3d9; --accent:#5ed0ff; }
  * { box-sizing: border-box; }
  html, body { margin:0; height:100%; background:var(--bg); color:var(--ink); font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; overflow:hidden; }
  #stage { position:fixed; inset:0; touch-action:none; }
  #top { position:fixed; left:0; right:0; top:0; padding:12px 16px; display:flex; gap:10px; flex-wrap:wrap; align-items:center; justify-content:space-between; pointer-events:none; }
  #top > * { pointer-events:auto; }
  h1 { font-size:18px; margin:0; color:var(--accent); }
  .btns { display:flex; gap:8px; flex-wrap:wrap; align-items:center; }
  button { font:600 16px system-ui, sans-serif; min-height:48px; min-width:48px; padding:0 18px; border-radius:14px; border:0; background:var(--accent); color:#06121f; cursor:pointer; }
  button.alt { background:var(--panel); color:var(--ink); border:2px solid var(--accent); }
  label.sw { display:flex; align-items:center; gap:8px; font:600 16px system-ui; min-height:48px; padding:0 14px; border-radius:14px; background:var(--panel); border:2px solid var(--accent); }
  label.sw input { width:26px; height:26px; accent-color:var(--accent); }
  #bottom { position:fixed; left:0; right:0; bottom:0; padding:12px 16px 18px; background:var(--panel); display:flex; flex-direction:column; gap:10px; }
  #progress { display:flex; align-items:center; gap:10px; font:600 15px system-ui; }
  input[type=range] { flex:1; height:36px; accent-color:var(--accent); }
  #info { position:fixed; left:50%; top:50%; transform:translate(-50%,-50%); width:min(92vw,420px); background:var(--panel); border:2px solid var(--accent); border-radius:18px; padding:18px 20px; display:none; pointer-events:auto; }
  #info h2 { margin:0 0 8px; font-size:20px; color:var(--accent); }
  #info p { margin:0 0 14px; font-size:16px; line-height:1.45; color:var(--ink); }
  #tip { position:fixed; left:16px; right:16px; bottom:150px; text-align:center; font-size:15px; color:var(--muted); pointer-events:none; }
  #lbl { position:fixed; left:0; top:0; padding:4px 8px; border-radius:8px; font:600 13px system-ui; background:var(--panel); color:var(--ink); border:1px solid var(--accent); pointer-events:none; display:none; white-space:nowrap; }
  @media (max-width:600px) { h1 { font-size:16px; } button, label.sw { font-size:15px; } }
</style>
</head>
<body>
<div id="stage"></div>

<div id="top">
  <h1>Animal Cell 3D</h1>
  <div class="btns">
    <label class="sw"><input type="checkbox" id="cut"> Cut open</label>
    <button class="alt" id="rebuild">Rebuild</button>
  </div>
</div>

<div id="tip">Drag to orbit. Pinch or scroll to zoom. Tap a part to read about it.</div>
<div id="lbl"></div>

<div id="info" role="dialog" aria-live="polite">
  <h2 id="iName"></h2>
  <p id="iText"></p>
  <button id="iClose">Close</button>
</div>

<div id="bottom">
  <div id="progress">
    <span id="pLabel">Build</span>
    <input type="range" id="scrub" min="0" max="100" value="100" aria-label="Scrub the build">
    <span id="pVal">100%</span>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function () {
  "use strict";

  // ---------- Storage (safe) ----------
  function safeGet(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } }
  function safeSet(k, v) { try { window.localStorage.setItem(k, v); } catch (e) {} }
  void safeGet; void safeSet;

  // ---------- Parts: name, one plain sentence ----------
  const PARTS = [
    { id: "membrane",  name: "Cell membrane", text: "A thin, flexible skin that lets good things in and keeps others out." },
    { id: "nucleus",   name: "Nucleus", text: "The control center. It holds the DNA, the instructions for the whole cell." },
    { id: "nucleolus", name: "Nucleolus", text: "A dense spot inside the nucleus where ribosome parts are made." },
    { id: "rer",       name: "Rough endoplasmic reticulum", text: "A folded network studded with ribosomes that builds proteins." },
    { id: "ser",       name: "Smooth endoplasmic reticulum", text: "A folded network without ribosomes that makes fats and cleans toxins." },
    { id: "ribosome",  name: "Ribosomes", text: "Tiny machines that read the instructions and build proteins." },
    { id: "golgi",     name: "Golgi apparatus", text: "The packing and shipping center that labels and sends proteins out." },
    { id: "mito",      name: "Mitochondria", text: "The power plants. They turn food into energy the cell can use." },
    { id: "lyso",      name: "Lysosomes", text: "The recycling bins. They break down waste and old parts." },
    { id: "vesicle",   name: "Vesicles", text: "Small bubbles that carry things from one place to another inside the cell." },
    { id: "centriole", name: "Centrioles", text: "A pair of tiny cylinders that help the cell divide into two." },
    { id: "cyto",      name: "Cytoskeleton", text: "A web of protein threads that gives the cell its shape and lets it move." }
  ];

  // ---------- Renderer / scene ----------
  const stage = document.getElementById("stage");
  const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.setSize(window.innerWidth, window.innerHeight);
  stage.appendChild(renderer.domElement);

  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 500);
  camera.position.set(0, 4, 26);

  scene.add(new THREE.AmbientLight(0xffffff, 0.6));
  const sun = new THREE.DirectionalLight(0xffffff, 0.9);
  sun.position.set(10, 14, 12);
  scene.add(sun);

  const root = new THREE.Group();
  scene.add(root);

  // Cell radius
  const R = 10;
  const world = new THREE.Group(); // gets scaled/moved for cut
  root.add(world);

  // ---------- Materials ----------
  function mat(color, opacity, extra) {
    return new THREE.MeshStandardMaterial(Object.assign({
      color: color, transparent: opacity < 1, opacity: opacity, roughness: 0.5, metalness: 0.05
    }, extra || {}));
  }

  // Membrane: see-through shell (double-sided)
  const membraneMat = mat(0x6fd3ff, 0.18, { side: THREE.DoubleSide, depthWrite: false });
  const membrane = new THREE.Mesh(new THREE.SphereGeometry(R, 48, 36), membraneMat);
  world.add(membrane);
  const membraneEdge = new THREE.LineSegments(
    new THREE.EdgesGeometry(new THREE.SphereGeometry(R, 24, 18)),
    new THREE.LineBasicMaterial({ color: 0x9ee8ff, transparent: true, opacity: 0.35 })
  );
  world.add(membraneEdge);

  // Groups for each part (appear during build)
  const partGroups = {};
  const pickables = []; // meshes that can be tapped
  const pulsers = [];   // objects that breathe
  const drifters = [];  // objects that drift

  function addPart(id, build) {
    const g = new THREE.Group();
    g.userData.partId = id;
    build(g);
    g.traverse(o => { if (o.isMesh) { o.userData.partId = id; pickables.push(o); } });
    world.add(g);
    partGroups[id] = g;
    return g;
  }

  function rnd(seed) {
    let s = seed;
    return function () { s = (s * 16807) % 2147483647; return (s - 1) / 2147483646; };
  }

  // Nucleus
  addPart("nucleus", g => {
    const m = new THREE.Mesh(new THREE.SphereGeometry(3.4, 36, 28), mat(0x7b6cff, 0.9));
    m.position.set(-1.2, 0.6, 0);
    g.add(m);
    pulsers.push({ obj: m, base: 1, amp: 0.03, speed: 0.7 });
    // nuclear pores (small rings)
    const ringMat = mat(0xd2c8ff, 1);
    for (let i = 0; i < 10; i++) {
      const a = (i / 10) * Math.PI * 2;
      const pore = new THREE.Mesh(new THREE.TorusGeometry(0.18, 0.05, 8, 16), ringMat);
      pore.position.set(-1.2 + Math.cos(a) * 3.42, 0.6 + Math.sin(a) * 0.9, Math.sin(a * 2) * 0.9);
      pore.lookAt(-1.2, 0.6, 0);
      g.add(pore);
    }
  });

  // Nucleolus (inside nucleus)
  addPart("nucleolus", g => {
    const m = new THREE.Mesh(new THREE.SphereGeometry(1.1, 24, 18), mat(0x3b2fa8, 1));
    m.position.set(-1.6, 1.1, 0.4);
    g.add(m);
    pulsers.push({ obj: m, base: 1, amp: 0.06, speed: 1.4 });
  });

  // Rough ER: sheets with ribosome dots
  addPart("rer", g => {
    const r = rnd(42);
    for (let i = 0; i < 3; i++) {
      const sheet = new THREE.Mesh(new THREE.TorusGeometry(4.6 + i * 0.7, 0.22, 10, 48), mat(0xf29ea0, 0.95));
      sheet.rotation.set(0.4 + i * 0.5, i * 0.7, 0.2 * i);
      sheet.position.set(2.8, -1.5, -0.5);
      g.add(sheet);
    }
    for (let i = 0; i < 40; i++) {
      const d = new THREE.Mesh(new THREE.SphereGeometry(0.12, 8, 6), mat(0xffd27a, 1));
      const a = r() * Math.PI * 2, b = r() * Math.PI * 2;
      d.position.set(2.8 + Math.cos(a) * 5.4, -1.5 + Math.sin(b) * 2.2, -0.5 + Math.sin(a) * 2.2);
      g.add(d);
    }
  });

  // Smooth ER: tubes without dots
  addPart("ser", g => {
    for (let i = 0; i < 3; i++) {
      const t = new THREE.Mesh(new THREE.TorusGeometry(2.6, 0.2, 10, 40), mat(0x8fe3b0, 0.95));
      t.rotation.set(1.1 - i * 0.3, 0.3 * i, 0.5);
      t.position.set(-4.6, -4.2 + i * 0.5, 2.6);
      g.add(t);
    }
  });

  // Ribosomes: small free-floating dots
  addPart("ribosome", g => {
    const r = rnd(7);
    for (let i = 0; i < 46; i++) {
      const m = new THREE.Mesh(new THREE.SphereGeometry(0.22, 8, 6), mat(0xffe08a, 1));
      const a = r() * Math.PI * 2, b = Math.acos(2 * r() - 1), rad = 6 + r() * 2.8;
      m.position.set(Math.sin(b) * Math.cos(a) * rad, Math.cos(b) * rad * 0.8, Math.sin(b) * Math.sin(a) * rad);
      if (m.position.length() > R - 1) m.position.setLength(R - 1.2);
      g.add(m);
      drifters.push({ obj: m, phase: r() * 10, amp: 0.25 });
    }
  });

  // Golgi: stacked flattened discs
  addPart("golgi", g => {
    for (let i = 0; i < 5; i++) {
      const d = new THREE.Mesh(new THREE.CylinderGeometry(1.7 - i * 0.12, 1.5 - i * 0.12, 0.28, 32), mat(0xffb36b, 0.95));
      d.position.set(4.6, 3.4 + i * 0.42, -2.6);
      d.rotation.set(0.3, 0, 0.15);
      g.add(d);
    }
  });

  // Mitochondria: capsules with inner ridges
  addPart("mito", g => {
    const spots = [[-5.2, 3.6, 2.2], [5.5, -3.6, 1.6], [0.8, -5.4, -3.2]];
    spots.forEach((p, i) => {
      const body = new THREE.Mesh(new THREE.CapsuleGeometry ? new THREE.CapsuleGeometry(0.6, 1.6, 6, 16) : new THREE.SphereGeometry(0.9, 16, 12), mat(0xff8f5a, 0.95));
      body.position.set(p[0], p[1], p[2]);
      body.rotation.set(0.5 * i, 0.9, 0.3);
      g.add(body);
      const ridge = new THREE.Mesh(new THREE.TorusGeometry(0.45, 0.06, 6, 18), mat(0xc85a2a, 1));
      ridge.position.copy(body.position);
      ridge.rotation.copy(body.rotation);
      g.add(ridge);
    });
  });

  // Lysosomes: small dark spheres
  addPart("lyso", g => {
    const spots = [[6.2, 0.5, 3.8], [-6.4, -0.8, -2.6], [2.2, 6.2, 2.2]];
    spots.forEach(p => {
      const m = new THREE.Mesh(new THREE.SphereGeometry(0.75, 18, 14), mat(0xb34dd1, 0.95));
      m.position.set(p[0], p[1], p[2]);
      g.add(m);
    });
  });

  // Vesicles: bubbles that drift
  addPart("vesicle", g => {
    const r = rnd(99);
    for (let i = 0; i < 12; i++) {
      const m = new THREE.Mesh(new THREE.SphereGeometry(0.45 + r() * 0.2, 14, 10), mat(0x7ff2e6, 0.55));
      const a = r() * Math.PI * 2;
      m.position.set(Math.cos(a) * (5 + r() * 3), (r() - 0.5) * 6, Math.sin(a) * (4 + r() * 3));
      g.add(m);
      drifters.push({ obj: m, phase: r() * 10, amp: 0.5 });
    }
  });

  // Centrioles: pair of cylinders near the nucleus
  addPart("centriole", g => {
    for (let i = 0; i < 2; i++) {
      const c = new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.28, 2.2, 12), mat(0xffffff, 0.95));
      c.position.set(-6.8 + i * 0.7, 5.2 - i * 0.4, -1.6);
      c.rotation.set(0.3, 0, i * 1.2);
      g.add(c);
    }
  });

  // Cytoskeleton: thin lattice of strands
  addPart("cyto", g => {
    const r = rnd(3);
    const strandMat = mat(0xd6e4ff, 0.55);
    for (let i = 0; i < 22; i++) {
      const a = r() * Math.PI * 2, b = r() * Math.PI;
      const len = 6 + r() * 4;
      const geo = new THREE.CylinderGeometry(0.05, 0.05, len, 6);
      const m = new THREE.Mesh(geo, strandMat);
      m.position.set(Math.sin(b) * Math.cos(a) * 5, Math.cos(b) * 5, Math.sin(b) * Math.sin(a) * 5);
      m.lookAt(0, 0, 0);
      m.rotateX(Math.PI / 2);
      g.add(m);
    }
  });

  // ---------- Build order and visibility ----------
  const ORDER = ["membrane", "nucleus", "nucleolus", "rer", "ser", "ribosome", "golgi", "mito", "lyso", "vesicle", "centriole", "cyto"];
  const totalSteps = ORDER.length;

  function setBuild(progress) { // progress 0..1
    const p = Math.max(0, Math.min(1, progress));
    const steps = p * totalSteps;
    ORDER.forEach((id, i) => {
      const local = Math.max(0, Math.min(1, steps - i));
      const obj = id === "membrane" ? null : partGroups[id];
      if (id === "membrane") {
        membraneMat.opacity = 0.18 * (p > 0 ? 1 : 0.4);
        membrane.scale.setScalar(1);
        membraneEdge.visible = true;
      } else if (obj) {
        obj.visible = local > 0.001;
        const s = 0.3 + 0.7 * local;
        obj.scale.setScalar(s);
        obj.traverse(o => { if (o.isMesh && o.material) { o.material.opacity = (o.material.userData.baseOp ?? o.material.opacity); } });
      }
    });
  }

  // Store base opacity so fades look right
  Object.values(partGroups).forEach(g => g.traverse(o => { if (o.isMesh && o.material) o.material.userData.baseOp = o.material.opacity; }));

  // ---------- Build state ----------
  let progress = 0;      // 0..1
  let target = 1;        // animate toward this
  let autoBuild = true;  // run build on load
  const scrub = document.getElementById("scrub");
  const pVal = document.getElementById("pVal");
  const pLabel = document.getElementById("pLabel");

  function updateUI() {
    const pct = Math.round(progress * 100);
    scrub.value = String(pct);
    pVal.textContent = pct + "%";
    const idx = Math.min(totalSteps - 1, Math.floor(progress * totalSteps));
    const part = PARTS.find(x => x.id === ORDER[idx]);
    pLabel.textContent = progress >= 1 ? "Complete" : "Building: " + (part ? part.name : "");
  }

  scrub.addEventListener("input", () => {
    autoBuild = false;
    target = Number(scrub.value) / 100;
    progress = target;
    setBuild(progress);
    updateUI();
  });

  document.getElementById("rebuild").addEventListener("click", () => {
    closeInfo();
    progress = 0;
    target = 1;
    autoBuild = true;
    t0 = performance.now();
    buildStart = t0;
  });

  // ---------- Cut open ----------
  const cutCheck = document.getElementById("cut");
  const clip = new THREE.Plane(new THREE.Vector3(1, 0, 0), 0);
  const clipping = [];
  let cutAmount = 0; // 0 closed .. 1 open
  let cutTarget = 0;

  cutCheck.addEventListener("change", () => {
    cutTarget = cutCheck.checked ? 1 : 0;
  });

  // Apply clipping to all materials
  function applyClip() {
    renderer.localClippingEnabled = true;
    const planes = cutAmount > 0.01 ? [clip] : [];
    scene.traverse(o => {
      if (o.isMesh && o.material) {
        o.material.clippingPlanes = planes;
        o.material.clipShadows = true;
        o.material.needsUpdate = true;
      }
    });
  }

  // ---------- Camera orbit / zoom / tap ----------
  let yaw = 0.4, pitch = 0.25, dist = 26;
  let orbitTarget = new THREE.Vector3(0, 0, 0);
  let flyTo = null; // { pos, look, t }
  let autoOrbitTimeout = 0;

  function applyCamera() {
    const cp = Math.cos(pitch), sp = Math.sin(pitch);
    camera.position.set(
      orbitTarget.x + dist * cp * Math.sin(yaw),
      orbitTarget.y + dist * sp,
      orbitTarget.z + dist * cp * Math.cos(yaw)
    );
    camera.lookAt(orbitTarget);
  }

  // Pointer handling (mouse + touch unified; no hover needed)
  const pointers = new Map();
  let lastPinch = 0;
  let tapStart = null;
  let dragging = false;

  renderer.domElement.addEventListener("pointerdown", e => {
    renderer.domElement.setPointerCapture(e.pointerId);
    pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    tapStart = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId };
    dragging = false;
    if (pointers.size === 2) lastPinch = pinchDist();
  });

  renderer.domElement.addEventListener("pointermove", e => {
    if (!pointers.has(e.pointerId)) return;
    const prev = pointers.get(e.pointerId);
    pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    if (tapStart && Math.hypot(e.clientX - tapStart.x, e.clientY - tapStart.y) > 10) dragging = true;
    if (pointers.size === 1 && dragging) {
      yaw -= (e.clientX - prev.x) * 0.006;
      pitch = Math.max(-1.2, Math.min(1.2, pitch + (e.clientY - prev.y) * 0.006));
      autoOrbitTimeout = performance.now();
    } else if (pointers.size === 2) {
      const d = pinchDist();
      if (lastPinch > 0) dist = Math.max(8, Math.min(60, dist * (lastPinch / d)));
      lastPinch = d;
      dragging = true;
    }
  });

  function endPointer(e) {
    const wasTap = tapStart && tapStart.id === e.pointerId && !dragging && pointers.size === 1 && (performance.now() - tapStart.t) < 450;
    pointers.delete(e.pointerId);
    if (pointers.size === 0) dragging = false;
    if (wasTap) handleTap(e.clientX, e.clientY);
    if (pointers.size < 2) lastPinch = 0;
    tapStart = null;
  }
  renderer.domElement.addEventListener("pointerup", endPointer);
  renderer.domElement.addEventListener("pointercancel", endPointer);

  function pinchDist() {
    const pts = Array.from(pointers.values());
    if (pts.length < 2) return 0;
    return Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
  }

  renderer.domElement.addEventListener("wheel", e => {
    e.preventDefault();
    dist = Math.max(8, Math.min(60, dist * (1 + e.deltaY * 0.001)));
  }, { passive: false });

  // ---------- Tap: fly to part ----------
  const ray = new THREE.Raycaster();
  const ndc = new THREE.Vector2();
  const lbl = document.getElementById("lbl");
  const info = document.getElementById("info");
  const iName = document.getElementById("iName");
  const iText = document.getElementById("iText");

  function handleTap(x, y) {
    if (demoMode) stopDemo();
    if (!isBuilt()) return; // only tappable once built
    const rect = renderer.domElement.getBoundingClientRect();
    ndc.x = ((x - rect.left) / rect.width) * 2 - 1;
    ndc.y = -((y - rect.top) / rect.height) * 2 + 1;
    ray.setFromCamera(ndc, camera);
    const hits = ray.intersectObjects(pickables, false);
    const hit = hits.find(h => h.object.visible && !(cutAmount > 0.5 && false));
    if (!hit) return;
    const id = hit.object.userData.partId;
    const part = PARTS.find(p => p.id === id);
    if (!part) return;
    const g = partGroups[id];
    if (!g) return;
    const box = new THREE.Box3().setFromObject(g);
    const center = box.getCenter(new THREE.Vector3());
    const local = center.clone();
    flyTo = { from: { pos: camera.position.clone(), look: orbitTarget.clone() }, look: local.clone(), t: 0, part: part };
    showLabel(part.name, x, y);
  }

  function isBuilt() { return progress >= 0.999; }

  function showLabel(name, x, y) {
    lbl.textContent = name;
    lbl.style.display = "block";
    lbl.style.left = Math.max(8, Math.min(window.innerWidth - 220, x + 12)) + "px";
    lbl.style.top = Math.max(8, y - 36) + "px";
  }

  function openInfo(part) {
    iName.textContent = part.name;
    iText.textContent = part.text;
    info.style.display = "block";
  }
  function closeInfo() { info.style.display = "none"; }
  document.getElementById("iClose").addEventListener("click", closeInfo);

  // ---------- Demo mode (#demo): hands-free loop ~20s ----------
  let demoMode = /#demo$/.test(window.location.hash || "");
  let demoStart = 0;
  let demoStep = 0;
  function stopDemo() {
    if (!demoMode) return;
    demoMode = false;
    flyTo = null;
    closeInfo();
    lbl.style.display = "none";
    autoBuild = false;
  }

  // ---------- Animation loop ----------
  const clock = new THREE.Clock();
  let t0 = performance.now();
  let buildStart = t0;
  const BUILD_MS = 9000;

  function demoUpdate(now) {
    const elapsed = (now - demoStart) / 1000;
    if (elapsed > 20) { demoStart = now; demoStep = 0; }
    // Gentle orbit throughout the demo
    yaw += 0.004;
    // Cut open then close at ~8s and ~14s
    cutTarget = (elapsed > 8 && elapsed < 14) ? 1 : 0;
    cutCheck.checked = cutTarget > 0.5;
    // Show a part card around 3s, 10s and 16s
    const stepAt = [3, 10, 16];
    if (demoStep < stepAt.length && elapsed > stepAt[demoStep]) {
      const id = ["nucleus", "mito", "golgi"][demoStep];
      const part = PARTS.find(p => p.id === id);
      const g = partGroups[id];
      if (g) {
        const c = new THREE.Box3().setFromObject(g).getCenter(new THREE.Vector3());
        flyTo = { from: { pos: camera.position.clone(), look: orbitTarget.clone() }, look: c, t: 0, part: part, quiet: true };
      }
      demoStep++;
    }
  }

  function frame(now) {
    const dt = clock.getDelta();
    const time = clock.elapsedTime;

    // Build animation
    if (autoBuild && progress < 1) {
      progress = Math.min(1, (now - buildStart) / BUILD_MS);
      if (progress >= 1) autoBuild = false;
      setBuild(progress);
      updateUI();
    }

    // Demo driver
    if (demoMode) {
      if (!demoStart) { demoStart = now; }
      demoUpdate(now);
    }

    // Cut-open easing
    cutAmount += (cutTarget - cutAmount) * Math.min(1, dt * 6);
    if (Math.abs(cutAmount - cutTarget) < 0.001) cutAmount = cutTarget;
    clip.normal.set(1, 0, 0);
    clip.constant = (1 - cutAmount) * 20; // plane sweeps through the cell
    applyClip();

    // Gentle life: pulse and drift
    pulsers.forEach(p => {
      const s = p.base + Math.sin(time * p.speed) * p.amp;
      p.obj.scale.setScalar(s);
    });
    drifters.forEach(d => {
      d.obj.position.y += Math.sin(time * 0.9 + d.phase) * d.amp * dt * 0.6;
      d.obj.position.x += Math.cos(time * 0.7 + d.phase) * d.amp * dt * 0.4;
    });
    world.rotation.y = Math.sin(time * 0.1) * 0.04;

    // Camera fly
    if (flyTo) {
      flyTo.t = Math.min(1, flyTo.t + dt * 1.6);
      const e = flyTo.t < 0.5 ? 2 * flyTo.t * flyTo.t : 1 - Math.pow(-2 * flyTo.t + 2, 2) / 2;
      orbitTarget.lerpVectors(flyTo.from.look, flyTo.look, e);
      dist = THREE.MathUtils.lerp(dist, 14, e * 0.02);
      if (flyTo.t >= 1) {
        if (!flyTo.quiet && flyTo.part) openInfo(flyTo.part);
        flyTo.done = true;
        flyTo = null;
      }
    }

    applyCamera();
    renderer.render(scene, camera);
    requestAnimationFrame(frame);
  }

  // Start demo immediately if requested; otherwise normal build
  if (demoMode) {
    autoBuild = true;
    buildStart = performance.now();
    cutCheck.checked = false;
  }

  // ---------- Resize ----------
  window.addEventListener("resize", () => {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
  });

  // Ensure any touch ends the demo
  window.addEventListener("touchstart", () => { if (demoMode) stopDemo(); }, { passive: true });

  // Initial UI state
  setBuild(0);
  updateUI();
  applyCamera();
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>