Back to the app
The code
Build a Cell, Part by Part by Claude Opus 5.5
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
index.html
works · auto-checked (Checked by an automated pass. Not hand-played yet.)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Build a Cell</title>
<style>
:root{
--glass:rgba(14,20,50,.74);
--line:rgba(170,190,255,.2);
--text:#eef2ff;
--muted:#aeb8dd;
--accent:#7dd3fc;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden}
body{
background:radial-gradient(ellipse at 50% 38%,#1c2660 0%,#0b1031 52%,#04060f 100%);
color:var(--text);
font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
touch-action:none;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;
}
#stage canvas{position:fixed;inset:0;display:block;outline:none}
#tags{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.tag{position:absolute;left:0;top:0;opacity:0;pointer-events:none;transition:opacity .3s}
.tag.show{opacity:1;pointer-events:auto}
.tag .tg{
position:relative;display:flex;align-items:center;gap:7px;
transform:translate(-50%,calc(-100% - 12px));
padding:7px 12px;border-radius:999px;white-space:nowrap;cursor:pointer;
background:rgba(8,12,36,.8);border:1px solid rgba(255,255,255,.2);
font-size:13px;font-weight:650;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);
transition:font-size .25s,padding .25s,border-color .25s;
}
.tag .tg::after{content:"";position:absolute;left:50%;bottom:-12px;width:2px;height:12px;background:rgba(255,255,255,.55);transform:translateX(-50%)}
.tag .dot{width:10px;height:10px;border-radius:50%;background:var(--c);box-shadow:0 0 10px var(--c);flex:none}
.tag.cur .tg{font-size:16px;padding:9px 15px;border-color:var(--c);box-shadow:0 0 22px rgba(255,255,255,.12)}
#top{
position:fixed;top:0;left:0;right:0;display:flex;flex-wrap:wrap;justify-content:space-between;align-items:flex-start;
gap:10px;padding:max(12px,env(safe-area-inset-top)) 14px 0;pointer-events:none;
}
#top>*{pointer-events:auto}
.brand{display:flex;align-items:center;gap:10px;min-height:48px}
.logo{width:36px;height:36px;border-radius:50%;flex:none;
background:radial-gradient(circle at 42% 45%,#a78bfa 0 22%,transparent 23%),radial-gradient(circle at 50% 50%,rgba(255,159,181,.35) 0 60%,rgba(255,159,181,.9) 62%,transparent 66%);
box-shadow:0 0 18px rgba(255,159,181,.45)}
.brand h1{margin:0;font-size:20px;letter-spacing:.2px}
.brand p{margin:2px 0 0;font-size:12px;color:var(--muted)}
.tools{display:flex;flex-wrap:wrap;gap:8px;justify-content:flex-end;margin-left:auto}
button{
font:inherit;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent;
min-height:48px;padding:0 16px;border-radius:999px;border:1px solid var(--line);
background:var(--glass);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);
display:inline-flex;align-items:center;gap:9px;font-size:15px;font-weight:650;
transition:transform .12s,background .2s,border-color .2s;
}
button:active{transform:scale(.95)}
.switch .track{width:42px;height:26px;border-radius:13px;background:rgba(255,255,255,.2);position:relative;transition:background .25s;flex:none}
.switch .track::after{content:"";position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:#fff;transition:left .25s;box-shadow:0 1px 4px rgba(0,0,0,.4)}
.switch.on{border-color:rgba(244,114,182,.7);background:rgba(244,114,182,.18)}
.switch.on .track{background:#f472b6}
.switch.on .track::after{left:19px}
.chip.on{background:rgba(125,211,252,.2);border-color:rgba(125,211,252,.65)}
#panel{
position:fixed;left:50%;transform:translateX(-50%);bottom:max(12px,env(safe-area-inset-bottom));
width:min(640px,calc(100% - 24px));display:flex;flex-direction:column;gap:10px;pointer-events:none;
}
#card{
--c:#ff9fb5;pointer-events:auto;background:var(--glass);border:1px solid var(--line);border-left:5px solid var(--c);
border-radius:20px;padding:13px 16px 14px;backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
box-shadow:0 12px 40px rgba(0,0,0,.35);
}
.row1{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:22px}
#badge{font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase;color:var(--c)}
#pname{margin:3px 0 4px;font-size:22px;line-height:1.2}
#pline{margin:0;font-size:16px;line-height:1.42}
#pmore{margin:7px 0 0;font-size:14px;line-height:1.42;color:var(--muted)}
#cardBtns{display:flex;gap:8px;margin-top:11px;flex-wrap:wrap}
#closeBtn{width:44px;min-height:44px;padding:0;justify-content:center;font-size:18px;margin:-6px -6px -6px 0}
.primary{background:rgba(125,211,252,.22);border-color:rgba(125,211,252,.6)}
.hidden{display:none!important}
#scrub{
pointer-events:auto;display:flex;align-items:center;gap:12px;background:var(--glass);border:1px solid var(--line);
border-radius:999px;padding:6px 16px 6px 6px;backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
}
#playBtn{width:50px;min-height:50px;padding:0;justify-content:center;flex:none;background:#fde047;color:#1a1a1a;border:none}
.sl{flex:1;position:relative;height:50px;display:flex;align-items:center;min-width:0}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:50px;margin:0;background:transparent;touch-action:none;cursor:pointer}
input[type=range]:focus{outline:none}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:5px;background:linear-gradient(90deg,#7dd3fc var(--fill,0%),rgba(255,255,255,.16) var(--fill,0%))}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;margin-top:-10px;border-radius:50%;background:#fff;border:5px solid #7dd3fc;box-shadow:0 2px 10px rgba(0,0,0,.45)}
input[type=range]::-moz-range-track{height:10px;border-radius:5px;background:rgba(255,255,255,.16)}
input[type=range]::-moz-range-progress{height:10px;border-radius:5px;background:#7dd3fc}
input[type=range]::-moz-range-thumb{width:22px;height:22px;border-radius:50%;background:#fff;border:5px solid #7dd3fc}
#ticks{position:absolute;left:15px;right:15px;top:50%;height:0;pointer-events:none}
.tk{position:absolute;top:-17px;width:7px;height:7px;border-radius:50%;background:var(--c);transform:translateX(-50%);opacity:.3;transition:opacity .3s,transform .3s}
.tk.lit{opacity:1;transform:translateX(-50%) scale(1.25);box-shadow:0 0 6px var(--c)}
#count{font-weight:750;font-variant-numeric:tabular-nums;min-width:46px;text-align:right;font-size:15px;flex:none}
#demoPill{position:fixed;left:50%;transform:translateX(-50%);top:calc(max(12px,env(safe-area-inset-top)) + 62px);
padding:8px 14px;border-radius:999px;background:rgba(253,224,71,.16);border:1px solid rgba(253,224,71,.55);color:#fef3c7;
font-size:13px;font-weight:700;pointer-events:none;white-space:nowrap}
#err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:30px;font-size:18px;line-height:1.5}
@media (max-width:600px){
.brand p{display:none}
.brand h1{font-size:17px}
.logo{width:30px;height:30px}
.tools button{padding:0 13px;font-size:14px}
#pname{font-size:19px}
#pline{font-size:15px}
#pmore{font-size:13.5px}
#card{padding:11px 14px 12px}
#demoPill{top:calc(max(12px,env(safe-area-inset-top)) + 118px)}
}
@media (max-height:540px) and (orientation:landscape){
#panel{left:12px;transform:none;width:min(400px,46%)}
#pmore{display:none}
#pline{font-size:14px}
#pname{font-size:18px}
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="tags"></div>
<header id="top">
<div class="brand"><span class="logo"></span><div><h1>Build a Cell</h1><p>An animal cell, one part at a time</p></div></div>
<div class="tools">
<button id="cutBtn" class="switch" role="switch" aria-checked="false"><span class="track"></span><span>Cut open</span></button>
<button id="labelsBtn" class="chip on" aria-pressed="true">Labels</button>
<button id="rebuildBtn" class="chip"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="M20 11a8 8 0 1 0-2.3 5.7"/><path d="M20 4v7h-7"/></svg>Rebuild</button>
</div>
</header>
<section id="panel">
<div id="card">
<div class="row1"><span id="badge">Starting</span><button id="closeBtn" class="hidden" aria-label="Close">✕</button></div>
<h2 id="pname">Cell membrane</h2>
<p id="pline"></p>
<p id="pmore" class="hidden"></p>
<div id="cardBtns" class="hidden"><button id="homeBtn" class="primary">Show whole cell</button></div>
</div>
<div id="scrub">
<button id="playBtn" aria-label="Play or pause"></button>
<div class="sl"><input id="slider" type="range" min="0" max="11" step="0.01" value="0" aria-label="Build progress"><div id="ticks"></div></div>
<span id="count">0/11</span>
</div>
</section>
<div id="demoPill" class="hidden">Demo · touch anywhere to explore</div>
<div id="err">Sorry, this cell needs WebGL, which this browser could not start.</div>
<script type="importmap">
{"imports":{
"three":"https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/":"https://unpkg.com/three@0.160.0/examples/jsm/"
}}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
const V3 = THREE.Vector3;
const TAU = Math.PI * 2;
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const smooth = x => x * x * (3 - 2 * x);
function easeOutBack(x){ if (x <= 0) return 0; if (x >= 1) return 1; const c1 = 1.4, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); }
let seed = 20261122;
function rand(){ seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }
function randDir(){ const u = rand() * 2 - 1, th = rand() * TAU, s = Math.sqrt(1 - u * u); return new V3(s * Math.cos(th), u, s * Math.sin(th)); }
/* ---------- cell size ---------- */
const RX = 5, RY = 4.2, RZ = 4.6;
const ellF = p => Math.sqrt((p.x / RX) ** 2 + (p.y / RY) ** 2 + (p.z / RZ) ** 2);
function rayEll(P, d, f){
const a = (d.x / RX) ** 2 + (d.y / RY) ** 2 + (d.z / RZ) ** 2;
const b = 2 * (P.x * d.x / (RX * RX) + P.y * d.y / (RY * RY) + P.z * d.z / (RZ * RZ));
const c = (P.x / RX) ** 2 + (P.y / RY) ** 2 + (P.z / RZ) ** 2 - f * f;
return (-b + Math.sqrt(Math.max(0, b * b - 4 * a * c))) / (2 * a);
}
/* ---------- part info ---------- */
const PARTS = [
{ name:'Cell membrane', color:0xff9fb5, fly:'point', dist:5,
line:"The cell's soft, flexible skin that holds everything in and chooses what gets in or out.",
more:'It is made of two thin layers of fatty molecules, a bit like a soap bubble that can heal itself.' },
{ name:'Nucleus', color:0x8b5cf6, fly:'focus', dist:4.6,
line:"The control center that keeps the cell's DNA, the instruction book for building and running the cell.",
more:'Its double wall is dotted with tiny pores that let messages in and out.' },
{ name:'Nucleolus', color:0xe879f9, fly:'focus', dist:2.5,
line:'A dense knot inside the nucleus that builds the pieces used to make ribosomes.',
more:'It has no wall of its own; it is just a very busy crowd of molecules.' },
{ name:'Rough endoplasmic reticulum', short:'Rough ER', color:0x38bdf8, fly:'point', dist:2.8,
line:'Folded sheets covered in ribosomes that build proteins and fold them into the right shape.',
more:'It is called "rough" because the ribosomes stuck to it make it look bumpy.' },
{ name:'Smooth endoplasmic reticulum', short:'Smooth ER', color:0x2dd4bf, fly:'point', dist:2.7,
line:'A web of smooth tubes that makes fats and helps break down poisons.',
more:'Liver cells are packed with it, because they clean harmful chemicals out of your blood.' },
{ name:'Ribosomes', color:0xfde047, fly:'point', dist:1.5,
line:'Tiny machines that read instructions from the DNA and link building blocks together to make proteins.',
more:'One cell can hold millions of them; some float free and some sit on the rough ER.' },
{ name:'Golgi apparatus', short:'Golgi', color:0xfb923c, fly:'focus', dist:3.8,
line:"A stack of flat pouches that sorts, packs and labels proteins, like the cell's post office.",
more:'Finished packages leave from its outer side inside little bubbles called vesicles.' },
{ name:'Mitochondria', color:0xef4444, fly:'object', dist:2.3,
line:'The power plants that turn food and oxygen into energy the cell can use.',
more:'Their inner wall is folded over and over to fit in more energy-making machinery.' },
{ name:'Lysosomes', color:0xa3e635, fly:'object', dist:1.6,
line:'Small bags of digestive juices that break down waste, germs and worn-out parts.',
more:"They are the cell's recycling crew, turning old parts into fresh building blocks." },
{ name:'Vesicles', color:0x7dd3fc, fly:'focus', dist:3.8,
line:'Tiny bubbles that carry materials around the cell and out through the membrane.',
more:'Watch them bud off the Golgi and travel to the edge of the cell.' },
{ name:'Centrioles', color:0xe9d5ff, fly:'focus', dist:2.0,
line:'A pair of tiny tubes that help pull the DNA apart when the cell splits in two.',
more:'Each one is a ring of nine groups of three tubes, set at right angles to its partner.' },
{ name:'Cytoskeleton', color:0x86efac, fly:'point', dist:3.2,
line:'A web of protein ropes and tubes that gives the cell its shape and works like tracks for moving things.',
more:'It is always being taken apart and rebuilt, like scaffolding that can walk.' }
];
const NPARTS = PARTS.length - 1; // 11 build steps
PARTS.forEach(p => { p.css = '#' + p.color.toString(16).padStart(6, '0'); p.a = 0; p.ph = rand() * TAU; p.dph = rand() * TAU; p.pulse = 0.018; p.mode = 'group'; });
/* ---------- renderer ---------- */
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias:true, alpha:true });
} catch (e) {
document.getElementById('err').style.display = 'flex';
throw e;
}
let W = innerWidth, H = innerHeight;
renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));
renderer.setSize(W, H);
renderer.setClearColor(0x000000, 0);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
document.getElementById('stage').appendChild(renderer.domElement);
const scene = new THREE.Scene();
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
pmrem.dispose();
const cutPlane = new THREE.Plane(new V3(0, 0, -1), 6);
renderer.clippingPlanes = [cutPlane];
scene.add(new THREE.HemisphereLight(0xdfe8ff, 0x22113a, 0.45));
const key = new THREE.DirectionalLight(0xffffff, 1.25); key.position.set(6, 9, 8); scene.add(key);
const rim = new THREE.DirectionalLight(0x8fb0ff, 0.7); rim.position.set(-8, -3, -6); scene.add(rim);
const camera = new THREE.PerspectiveCamera(45, W / H, 0.05, 200);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; controls.dampingFactor = 0.08;
controls.rotateSpeed = 0.8; controls.zoomSpeed = 0.9;
controls.minDistance = 0.8; controls.maxDistance = 60;
controls.screenSpacePanning = true;
controls.autoRotate = true; controls.autoRotateSpeed = 0.7;
function stdMat(color, o = {}){
return new THREE.MeshStandardMaterial(Object.assign({ color, roughness:0.45, metalness:0, emissive:color, emissiveIntensity:0.12 }, o));
}
function physMat(color, opacity, o = {}){
return new THREE.MeshPhysicalMaterial(Object.assign({ color, roughness:0.25, metalness:0, clearcoat:0.8, clearcoatRoughness:0.3,
transparent:true, opacity, depthWrite:false, side:THREE.DoubleSide, emissive:color, emissiveIntensity:0.1 }, o));
}
const cell = new THREE.Group(); scene.add(cell);
const pickables = [];
function anchor(parent, x, y, z){ const o = new THREE.Object3D(); o.position.set(x, y, z); parent.add(o); return o; }
function register(i, group, opts = {}){
const p = PARTS[i]; Object.assign(p, opts);
p.group = group; p.basePos = group.position.clone(); p.baseRot = group.rotation.clone(); p.mats = [];
group.traverse(o => {
if (!o.material) return;
o.userData.part = i;
const ms = Array.isArray(o.material) ? o.material : [o.material];
ms.forEach(m => { if (!p.mats.includes(m)) { p.mats.push(m); m.userData.bo = m.opacity; m.userData.be = m.emissiveIntensity || 0; } });
if (o.isMesh && !o.userData.noPick) pickables.push(o);
});
cell.add(group);
}
const tmpV = new V3(), tmpN = new V3();
/* ---------- 0. membrane ---------- */
const memGeo = new THREE.SphereGeometry(1, 96, 64);
const memBase = memGeo.attributes.position.array.slice();
{
const na = memGeo.attributes.normal;
for (let i = 0; i < na.count; i++){
tmpN.set(memBase[i * 3] / RX, memBase[i * 3 + 1] / RY, memBase[i * 3 + 2] / RZ).normalize();
na.setXYZ(i, tmpN.x, tmpN.y, tmpN.z);
}
}
memGeo.boundingSphere = new THREE.Sphere(new V3(), 5.8);
const membrane = new THREE.Group();
const memOuter = new THREE.Mesh(memGeo, physMat(0xff9fb5, 0.24, { clearcoat:1, roughness:0.2, emissiveIntensity:0.09 }));
const memInner = new THREE.Mesh(memGeo, physMat(0xffc8d6, 0.12, { emissiveIntensity:0.05 }));
memInner.scale.setScalar(0.966); memInner.userData.noPick = true;
memOuter.renderOrder = 2; memInner.renderOrder = 1;
membrane.add(memOuter, memInner);
PARTS[0].tag = anchor(membrane, 0, RY + 0.05, 0);
PARTS[0].focus = anchor(membrane, 0, 0, 0);
register(0, membrane, { pulse:0.006 });
function updateMembrane(t){
const a = memGeo.attributes.position.array;
for (let i = 0; i < a.length; i += 3){
const x = memBase[i], y = memBase[i + 1], z = memBase[i + 2];
const d = 1 + 0.028 * Math.sin(2.1 * x + 1.7 * y + t * 0.9) + 0.022 * Math.sin(2.7 * y - 1.9 * z + t * 1.25) + 0.018 * Math.sin(3.3 * z + 2.3 * x - t * 0.75);
a[i] = x * RX * d; a[i + 1] = y * RY * d; a[i + 2] = z * RZ * d;
}
memGeo.attributes.position.needsUpdate = true;
}
/* cytoplasm sparkle (not a part) */
const cytoPts = [];
while (cytoPts.length < 700 * 3){
const p = new V3((rand() * 2 - 1) * RX, (rand() * 2 - 1) * RY, (rand() * 2 - 1) * RZ);
if (ellF(p) < 0.9) cytoPts.push(p.x, p.y, p.z);
}
const cytoGeo = new THREE.BufferGeometry(); cytoGeo.setAttribute('position', new THREE.Float32BufferAttribute(cytoPts, 3));
const cytoMat = new THREE.PointsMaterial({ color:0xc7d6ff, size:0.05, transparent:true, opacity:0.4, depthWrite:false });
const cytoplasm = new THREE.Points(cytoGeo, cytoMat); cell.add(cytoplasm);
/* ---------- 1. nucleus ---------- */
const N = new V3(-0.8, 0.2, -0.2), NR = 1.45;
const nucleus = new THREE.Group(); nucleus.position.copy(N);
nucleus.add(new THREE.Mesh(new THREE.SphereGeometry(NR, 64, 48), physMat(0x8b5cf6, 0.46, { emissiveIntensity:0.16 })));
{
const POR = 80;
const pores = new THREE.InstancedMesh(new THREE.TorusGeometry(0.075, 0.026, 6, 14), stdMat(0x5b21b6, { emissiveIntensity:0.25 }), POR);
const o = new THREE.Object3D();
for (let i = 0; i < POR; i++){
const y = 1 - 2 * (i + 0.5) / POR, r = Math.sqrt(1 - y * y), th = i * 2.39996;
const d = new V3(Math.cos(th) * r, y, Math.sin(th) * r);
o.position.copy(d).multiplyScalar(NR); o.lookAt(d.multiplyScalar(NR * 2)); o.updateMatrix();
pores.setMatrixAt(i, o.matrix);
}
pores.computeBoundingSphere(); nucleus.add(pores);
const chromMat = stdMat(0xc4b5fd, { emissiveIntensity:0.25, roughness:0.6 });
for (let k = 0; k < 8; k++){
const pts = []; const p = randDir().multiplyScalar(rand() * 0.8);
for (let j = 0; j < 9; j++){ pts.push(p.clone()); p.add(randDir().multiplyScalar(0.34)); if (p.length() > 1.15) p.setLength(0.95); }
nucleus.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 70, 0.034, 5), chromMat));
}
}
PARTS[1].tag = anchor(nucleus, -0.55, NR * 0.93, 0.45);
PARTS[1].focus = anchor(nucleus, 0, 0, 0);
register(1, nucleus, { dph:0.7 });
/* ---------- 2. nucleolus ---------- */
const nucleolus = new THREE.Group(); nucleolus.position.copy(N).add(new V3(0.35, 0.3, 0.25));
{
const g = new THREE.SphereGeometry(0.5, 48, 32), pa = g.attributes.position;
for (let i = 0; i < pa.count; i++){
tmpV.fromBufferAttribute(pa, i); tmpN.copy(tmpV).normalize();
const k = 1 + 0.1 * Math.sin(tmpN.x * 9 + 1) * Math.sin(tmpN.y * 8) + 0.07 * Math.sin(tmpN.z * 11 + tmpN.x * 5);
tmpV.copy(tmpN).multiplyScalar(0.5 * k); pa.setXYZ(i, tmpV.x, tmpV.y, tmpV.z);
}
g.computeVertexNormals();
nucleolus.add(new THREE.Mesh(g, stdMat(0xd946ef, { roughness:0.7, emissiveIntensity:0.28 })));
}
PARTS[2].tag = anchor(nucleolus, 0, 0.55, 0);
PARTS[2].focus = anchor(nucleolus, 0, 0, 0);
register(2, nucleolus, { dph:0.7 });
/* ---------- 3. rough ER ---------- */
const rer = new THREE.Group(); rer.position.copy(N);
const rerGeos = [];
{
const rerMat = stdMat(0x38bdf8, { side:THREE.DoubleSide, roughness:0.5, emissiveIntensity:0.15 });
const defs = [[1.85, -1.25, 2.5, 0.55, 2.0], [2.1, -1.1, 2.25, 0.6, 1.9], [2.35, -1.0, 2.0, 0.7, 1.75], [2.6, -0.85, 1.7, 0.8, 1.55]];
defs.forEach(([r, ps, pl, ts, tl], k) => {
const g = new THREE.SphereGeometry(r, 64, 32, ps, pl, ts, tl), pa = g.attributes.position;
for (let i = 0; i < pa.count; i++){
tmpV.fromBufferAttribute(pa, i); const len = tmpV.length(); tmpN.copy(tmpV).normalize();
const w = 1 + 0.045 * Math.sin(tmpN.x * 7 + tmpN.y * 5 + k) + 0.03 * Math.sin(tmpN.z * 9 - tmpN.y * 6 + k * 2);
tmpV.copy(tmpN).multiplyScalar(len * w); pa.setXYZ(i, tmpV.x, tmpV.y, tmpV.z);
}
g.computeVertexNormals();
rer.add(new THREE.Mesh(g, rerMat)); rerGeos.push(g);
});
}
PARTS[3].tag = anchor(rer, -2.25, 1.35, 0.95);
PARTS[3].focus = anchor(rer, -1.9, 0.6, 0.7);
const RER_DPH = 0.7, RER_PH = PARTS[3].ph;
register(3, rer, { dph:RER_DPH });
/* ---------- 4. smooth ER ---------- */
const S = new V3(-1.7, -2.4, 0.9);
const ser = new THREE.Group(); ser.position.copy(S);
{
const serMat = stdMat(0x2dd4bf, { emissiveIntensity:0.18, roughness:0.4 });
const nodes = []; let tries = 0;
while (nodes.length < 15 && tries < 800){
tries++;
const p = new V3((rand() - 0.5) * 2.8, (rand() - 0.5) * 1.6, (rand() - 0.5) * 2.4);
const w = p.clone().add(S);
if (ellF(w) > 0.8 || w.distanceTo(N) < NR + 0.55 || nodes.some(q => q.distanceTo(p) < 0.45)) continue;
nodes.push(p);
}
const edges = new Set();
nodes.forEach((p, i) => {
const order = nodes.map((q, j) => [q.distanceTo(p), j]).filter(x => x[1] !== i).sort((a, b) => a[0] - b[0]);
for (let k = 0; k < 2 && k < order.length; k++){
const j = order[k][1], key = i < j ? i + '-' + j : j + '-' + i;
if (edges.has(key)) continue; edges.add(key);
const q = nodes[j], mid = p.clone().lerp(q, 0.5).add(randDir().multiplyScalar(0.2));
ser.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.QuadraticBezierCurve3(p, mid, q), 18, 0.075, 7), serMat));
}
});
const jGeo = new THREE.SphereGeometry(0.11, 14, 10);
nodes.forEach(p => { const m = new THREE.Mesh(jGeo, serMat); m.position.copy(p); ser.add(m); });
let best = nodes[0]; nodes.forEach(p => { if (p.z + p.y * 0.3 > best.z + best.y * 0.3) best = p; });
PARTS[4].tag = anchor(ser, best.x, best.y + 0.15, best.z);
}
PARTS[4].focus = anchor(ser, 0, 0, 0);
register(4, ser, { dph:RER_DPH });
/* ---------- 5. ribosomes ---------- */
const ribo = new THREE.Group(); ribo.position.copy(N);
{
const ATT = 480, FREE = 170;
const im = new THREE.InstancedMesh(new THREE.SphereGeometry(0.055, 8, 6), stdMat(0xfde047, { emissiveIntensity:0.38, roughness:0.5 }), ATT + FREE);
const m4 = new THREE.Matrix4(); let front = null, frontScore = -1e9, freeTag = null;
for (let i = 0; i < ATT; i++){
const g = rerGeos[Math.floor(rand() * rerGeos.length)], idx = Math.floor(rand() * g.attributes.position.count);
tmpV.fromBufferAttribute(g.attributes.position, idx); tmpN.fromBufferAttribute(g.attributes.normal, idx);
tmpV.addScaledVector(tmpN, rand() < 0.5 ? 0.055 : -0.055);
m4.makeTranslation(tmpV.x, tmpV.y, tmpV.z); im.setMatrixAt(i, m4);
if (g === rerGeos[3] && tmpV.z + tmpV.y * 0.2 > frontScore){ frontScore = tmpV.z + tmpV.y * 0.2; front = tmpV.clone(); }
}
let n = 0;
while (n < FREE){
const w = new V3((rand() * 2 - 1) * RX, (rand() * 2 - 1) * RY, (rand() * 2 - 1) * RZ);
if (ellF(w) > 0.85 || w.distanceTo(N) < NR + 0.3) continue;
const l = w.sub(N); m4.makeTranslation(l.x, l.y, l.z); im.setMatrixAt(ATT + n, m4);
if (!freeTag || l.z > freeTag.z) freeTag = l.clone();
n++;
}
im.computeBoundingSphere(); ribo.add(im);
PARTS[5].tag = anchor(ribo, front.x, front.y + 0.1, front.z);
PARTS[5].focus = anchor(ribo, front.x, front.y, front.z);
}
register(5, ribo, { dph:RER_DPH, ph:RER_PH });
/* ---------- 6. Golgi ---------- */
const G = new V3(2.3, 0.3, 0.3);
const golgi = new THREE.Group(); golgi.position.copy(G);
{
const gStack = new THREE.Group(); gStack.rotation.set(0.2, 0.3, -Math.PI / 2); golgi.add(gStack);
const gMat = stdMat(0xfb923c, { emissiveIntensity:0.2, roughness:0.4 });
const gMat2 = stdMat(0xfdba74, { emissiveIntensity:0.22, roughness:0.4 });
const budGeo = new THREE.SphereGeometry(1, 12, 10);
[0.8, 1.0, 1.12, 1.05, 0.88].forEach((w, k) => {
const g = new THREE.SphereGeometry(1, 48, 18), pa = g.attributes.position;
for (let i = 0; i < pa.count; i++){
const x = pa.getX(i) * w, z = pa.getZ(i) * w * 0.52;
const y = pa.getY(i) * 0.075 + 0.3 * (x * x + 0.5 * z * z) + (k - 2) * 0.23;
pa.setXYZ(i, x, y, z);
}
g.computeVertexNormals();
gStack.add(new THREE.Mesh(g, k % 2 ? gMat2 : gMat));
for (const s of [-1, 1]){
const vx = s * w * (1.04 + rand() * 0.08), vz = (rand() - 0.5) * 0.4 * w;
const b = new THREE.Mesh(budGeo, gMat2);
b.position.set(vx, 0.3 * (vx * vx + 0.5 * vz * vz) + (k - 2) * 0.23, vz); b.scale.setScalar(0.07 + rand() * 0.04);
gStack.add(b);
}
});
}
PARTS[6].tag = anchor(golgi, 0.1, 1.25, 0);
PARTS[6].focus = anchor(golgi, 0.2, 0, 0);
register(6, golgi);
/* ---------- 7. mitochondria ---------- */
const mito = new THREE.Group();
const mitoItems = [];
{
const outerMat = physMat(0xef4444, 0.62, { emissiveIntensity:0.18 });
const crMat = stdMat(0xfda4af, { side:THREE.DoubleSide, emissiveIntensity:0.25, roughness:0.5 });
const capGeo = new THREE.CapsuleGeometry(0.3, 0.85, 8, 18);
const crGeo = new THREE.PlaneGeometry(0.44, 0.95, 1, 80); const pa = crGeo.attributes.position;
for (let i = 0; i < pa.count; i++){ const x = pa.getX(i), y = pa.getY(i); pa.setXYZ(i, 0.17 * Math.sin(y * 22), y, x); }
crGeo.computeVertexNormals();
const POS = [[1.5, 2.3, 1.0], [3.0, -1.9, 0.6], [0.6, -2.6, -1.6], [-0.6, 2.9, -2.0], [1.2, 0.4, -3.0], [-3.0, 1.0, 2.0], [2.0, 1.9, -2.2]];
POS.forEach(([x, y, z]) => {
const it = new THREE.Group(); it.position.set(x, y, z); it.rotation.set(rand() * Math.PI, rand() * Math.PI, rand() * Math.PI);
const outer = new THREE.Mesh(capGeo, outerMat); const cr = new THREE.Mesh(crGeo, crMat);
it.add(cr, outer); mito.add(it);
it.userData = { bp:it.position.clone(), br:it.rotation.clone(), ph:rand() * TAU, wob:0.15, outer };
mitoItems.push(it);
});
}
PARTS[7].tag = anchor(mito, 1.5, 3.0, 1.0);
PARTS[7].focus = anchor(mito, 1.5, 2.3, 1.0);
register(7, mito, { mode:'items', items:mitoItems, drift:0.04 });
/* ---------- 8. lysosomes ---------- */
const lyso = new THREE.Group();
const lysoItems = [];
{
const lMat = physMat(0xa3e635, 0.72, { emissiveIntensity:0.32 });
const grMat = stdMat(0x3f6212, { emissiveIntensity:0.2 });
const grGeo = new THREE.SphereGeometry(0.045, 8, 6), lGeo = new THREE.SphereGeometry(1, 28, 20);
const POS = [[0.4, 1.6, 2.4, 0.27], [3.4, 1.0, -1.3, 0.24], [0.2, -2.5, 2.6, 0.26], [-2.4, -0.9, 2.8, 0.22], [1.8, -0.6, 2.6, 0.25], [-1.8, -1.0, -3.2, 0.28]];
POS.forEach(([x, y, z, r]) => {
const it = new THREE.Group(); it.position.set(x, y, z);
const s = new THREE.Mesh(lGeo, lMat); s.scale.setScalar(r); it.add(s);
for (let k = 0; k < 7; k++){ const g = new THREE.Mesh(grGeo, grMat); g.position.copy(randDir().multiplyScalar(r * 0.55 * rand())); it.add(g); }
lyso.add(it);
it.userData = { bp:it.position.clone(), br:it.rotation.clone(), ph:rand() * TAU, wob:0.3 };
lysoItems.push(it);
});
}
PARTS[8].tag = anchor(lyso, 0.4, 1.95, 2.4);
PARTS[8].focus = anchor(lyso, 0.4, 1.6, 2.4);
register(8, lyso, { mode:'items', items:lysoItems, drift:0.04 });
/* ---------- 9. vesicles ---------- */
const ves = new THREE.Group(); ves.position.copy(G);
const vesList = [];
{
const vMat = physMat(0x7dd3fc, 0.78, { emissiveIntensity:0.28 });
const vGeo = new THREE.SphereGeometry(1, 18, 14);
for (let k = 0; k < 20; k++){
let a, b;
if (k < 15){
a = new V3(1.0 + rand() * 0.3, (rand() - 0.5) * 1.4, (rand() - 0.5) * 0.8);
const P = a.clone().add(G);
const d = new V3(0.8 + rand() * 0.5, (rand() - 0.5) * 1.8, (rand() - 0.5) * 1.8).normalize();
b = P.addScaledVector(d, rayEll(P, d, 0.9)).sub(G);
} else {
a = new V3(-1.55 + rand() * 0.25, (rand() - 0.5) * 1.0, (rand() - 0.5) * 1.0);
b = new V3(-0.7, (rand() - 0.5) * 0.8, (rand() - 0.5) * 0.6);
}
const c = a.clone().lerp(b, 0.5).add(randDir().multiplyScalar(0.6));
const m = new THREE.Mesh(vGeo, vMat); ves.add(m);
vesList.push({ m, a, b, c, r:0.1 + rand() * 0.07, sp:0.09 + rand() * 0.1, ph:rand() });
}
}
PARTS[9].tag = anchor(ves, 1.7, 1.0, 0.4);
PARTS[9].focus = anchor(ves, 1.5, 0.2, 0.3);
register(9, ves, { mode:'vesicles', drift:0.03 });
function updateVesicles(t){
const A = PARTS[9].a, n = vesList.length;
vesList.forEach((v, k) => {
const u = (t * v.sp + v.ph) % 1, w = 1 - u;
v.m.position.set(w * w * v.a.x + 2 * w * u * v.c.x + u * u * v.b.x, w * w * v.a.y + 2 * w * u * v.c.y + u * u * v.b.y, w * w * v.a.z + 2 * w * u * v.c.z + u * u * v.b.z);
const ak = clamp((A - 0.5 * k / n) * 2);
v.m.scale.setScalar(Math.max(1e-4, v.r * Math.pow(Math.sin(Math.PI * u), 0.35) * easeOutBack(ak)));
});
}
/* ---------- 10. centrioles ---------- */
const C = new V3(0.9, -1.7, 1.4);
const cen = new THREE.Group(); cen.position.copy(C);
{
const rodGeo = new THREE.CylinderGeometry(0.022, 0.022, 0.5, 6);
const cMat = stdMat(0xe9d5ff, { emissiveIntensity:0.32, roughness:0.35 });
const make = () => {
const im = new THREE.InstancedMesh(rodGeo, cMat, 27), o = new THREE.Object3D(); let n = 0;
for (let i = 0; i < 9; i++){ const a = i / 9 * TAU; for (let j = 0; j < 3; j++){ const r = 0.12 + j * 0.042, aa = a + j * 0.17; o.position.set(Math.cos(aa) * r, 0, Math.sin(aa) * r); o.updateMatrix(); im.setMatrixAt(n++, o.matrix); } }
im.computeBoundingSphere(); return im;
};
const c1 = make(); c1.position.set(-0.2, 0, 0);
const c2 = make(); c2.rotation.x = Math.PI / 2; c2.position.set(0.22, 0.05, 0.12);
const cloud = new THREE.Mesh(new THREE.SphereGeometry(0.68, 28, 20), physMat(0xc4b5fd, 0.1, { emissiveIntensity:0.15 }));
cen.add(c1, c2, cloud);
}
PARTS[10].tag = anchor(cen, 0, 0.62, 0);
PARTS[10].focus = anchor(cen, 0, 0, 0);
register(10, cen, { spin:0.25, drift:0.04 });
/* ---------- 11. cytoskeleton ---------- */
const cyto = new THREE.Group(); cyto.position.copy(C);
{
const mtMat = stdMat(0x86efac, { emissiveIntensity:0.35, roughness:0.5 });
let best = null, bestScore = -1e9;
for (let k = 0; k < 34; k++){
const d = randDir(); const end = C.clone().addScaledVector(d, rayEll(C, d, 0.9));
const mid = C.clone().lerp(end, 0.5).add(randDir().multiplyScalar(0.55));
const toN = mid.clone().sub(N); if (toN.length() < NR + 0.6) mid.copy(N).add(toN.setLength(NR + 0.6));
const pts = [new V3(0, 0, 0), mid.sub(C), end.clone().sub(C)];
cyto.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 40, 0.024, 4), mtMat));
const sc = end.z + end.y * 0.4; if (sc > bestScore){ bestScore = sc; best = pts; }
}
PARTS[11].tag = anchor(cyto, best[2].x * 0.92, best[2].y * 0.92 + 0.1, best[2].z * 0.92);
PARTS[11].focus = anchor(cyto, best[1].x, best[1].y, best[1].z);
const ap = [];
for (let k = 0; k < 240; k++){ const d = randDir(), f = 0.84 + rand() * 0.06; ap.push(new V3(d.x * RX * f, d.y * RY * f, d.z * RZ * f)); }
const seg = [];
ap.forEach((p, i) => {
const order = ap.map((q, j) => [q.distanceTo(p), j]).filter(x => x[1] !== i).sort((a, b) => a[0] - b[0]);
for (let k = 0; k < 2; k++){ const q = ap[order[k][1]]; seg.push(p.x - C.x, p.y - C.y, p.z - C.z, q.x - C.x, q.y - C.y, q.z - C.z); }
});
const lg = new THREE.BufferGeometry(); lg.setAttribute('position', new THREE.Float32BufferAttribute(seg, 3));
cyto.add(new THREE.LineSegments(lg, new THREE.LineBasicMaterial({ color:0x6ee7b7, transparent:true, opacity:0.5, depthWrite:false })));
}
register(11, cyto, { drift:0.02, pulse:0.008 });
/* ---------- state ---------- */
const isDemo = location.hash === '#demo';
let demo = isDemo ? { t:0, next:0 } : null;
let time = 0, memT = 0, buildT = 0, playing = true, holdT = 1.6, doneT = 0;
let selected = null, labelsOn = true, cutOn = false, cutAmt = 0, curPart = 0;
let sliderDragging = false, fly = null;
const cutDir = new V3(0, 0, 1);
const appearOf = i => clamp((buildT - (i - 1)) / 0.55);
const isComplete = () => buildT >= NPARTS && doneT > 1.8 && !sliderDragging;
/* ---------- camera helpers ---------- */
function homeDist(){
const vf = THREE.MathUtils.degToRad(camera.fov) / 2, hf = Math.atan(Math.tan(vf) * camera.aspect);
return Math.max(5.0 / Math.tan(vf) * 1.12, 5.5 / Math.tan(hf));
}
function resize(){
W = innerWidth; H = innerHeight;
renderer.setSize(W, H);
camera.aspect = W / H;
const sh = W / H < 0.9 ? 0.13 : 0.05;
camera.setViewOffset(W, H, 0, H * sh, W, H);
camera.updateProjectionMatrix();
}
addEventListener('resize', resize);
resize();
function flyTo(target, pos, dur = 1.3){
fly = { t:0, dur, p0:camera.position.clone(), p1:pos.clone(), t0:controls.target.clone(), t1:target.clone() };
controls.autoRotate = false;
}
function flyHome(dur = 1.4){
const dir = camera.position.clone().sub(controls.target).normalize();
if (cutOn) dir.addScaledVector(cutDir, 1.4);
dir.y = clamp(dir.y, -0.35, 0.45); dir.normalize();
flyTo(new V3(0, 0, 0), dir.multiplyScalar(homeDist()), dur);
}
camera.position.set(0, 3, homeDist() * 1.7);
controls.target.set(0, 0, 0);
camera.lookAt(0, 0, 0);
flyTo(new V3(0, 0, 0), new V3(0, 0.22, 1).normalize().multiplyScalar(homeDist()), 2.4);
controls.autoRotate = true;
controls.addEventListener('start', () => { controls.autoRotate = false; fly = null; });
function selectPart(i, hit){
const p = PARTS[i]; selected = i; lastKey = '';
const focus = new V3();
if (hit && p.fly === 'point') focus.copy(hit.point);
else if (hit && p.fly === 'object'){
const o = hit.object; if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere();
focus.copy(o.geometry.boundingSphere.center).applyMatrix4(o.matrixWorld);
} else p.focus.getWorldPosition(focus);
const dir = camera.position.clone().sub(controls.target).normalize();
if (cutOn) dir.addScaledVector(cutDir, 1.6).normalize();
flyTo(focus, focus.clone().addScaledVector(dir, p.dist), 1.3);
}
function closeInfo(){ selected = null; lastKey = ''; }
function setCut(on){
cutOn = on;
if (on && cutAmt < 0.05){
cutDir.copy(camera.position).sub(controls.target).normalize();
cutPlane.normal.copy(cutDir).negate();
}
cutBtn.classList.toggle('on', on); cutBtn.setAttribute('aria-checked', on ? 'true' : 'false');
}
function rebuild(){
buildT = 0; doneT = 0; playing = true; holdT = demo ? 0.3 : 1.0;
closeInfo(); setCut(false); flyHome(); controls.autoRotate = true;
}
/* ---------- picking ---------- */
const raycaster = new THREE.Raycaster(), ndc = new THREE.Vector2();
function doPick(x, y){
ndc.set(x / W * 2 - 1, -(y / H) * 2 + 1);
raycaster.setFromCamera(ndc, camera);
const hits = raycaster.intersectObjects(pickables, false).filter(h => {
const p = PARTS[h.object.userData.part];
return p.a > 0.5 && cutPlane.distanceToPoint(h.point) >= -0.02;
});
if (!hits.length) return;
const h = hits.find(h => h.object.userData.part !== 0) || hits[0];
selectPart(h.object.userData.part, h);
}
const cv = renderer.domElement, downs = new Set(); let tapCand = null;
cv.addEventListener('pointerdown', e => {
downs.add(e.pointerId);
tapCand = downs.size === 1 ? { x:e.clientX, y:e.clientY, t:performance.now(), id:e.pointerId } : null;
});
cv.addEventListener('pointerup', e => {
downs.delete(e.pointerId);
if (tapCand && tapCand.id === e.pointerId && Math.hypot(e.clientX - tapCand.x, e.clientY - tapCand.y) < 10 && performance.now() - tapCand.t < 450) doPick(e.clientX, e.clientY);
tapCand = null;
});
cv.addEventListener('pointercancel', e => { downs.delete(e.pointerId); tapCand = null; });
cv.addEventListener('pointermove', e => { if (tapCand && Math.hypot(e.clientX - tapCand.x, e.clientY - tapCand.y) > 10) tapCand = null; });
document.addEventListener('gesturestart', e => e.preventDefault());
/* ---------- UI ---------- */
const $ = id => document.getElementById(id);
const cutBtn = $('cutBtn'), labelsBtn = $('labelsBtn'), slider = $('slider'), playBtn = $('playBtn');
const card = $('card'), badge = $('badge'), pname = $('pname'), pline = $('pline'), pmore = $('pmore');
const closeBtn = $('closeBtn'), cardBtns = $('cardBtns'), countEl = $('count');
const PLAY = '<svg width="22" height="22" viewBox="0 0 24 24"><path d="M7 4.5v15l13-7.5z" fill="currentColor"/></svg>';
const PAUSE = '<svg width="22" height="22" viewBox="0 0 24 24"><rect x="6" y="4.5" width="4.4" height="15" rx="1.3" fill="currentColor"/><rect x="13.6" y="4.5" width="4.4" height="15" rx="1.3" fill="currentColor"/></svg>';
cutBtn.addEventListener('click', () => setCut(!cutOn));
labelsBtn.addEventListener('click', () => { labelsOn = !labelsOn; labelsBtn.classList.toggle('on', labelsOn); labelsBtn.setAttribute('aria-pressed', String(labelsOn)); });
$('rebuildBtn').addEventListener('click', rebuild);
closeBtn.addEventListener('click', closeInfo);
$('homeBtn').addEventListener('click', () => { closeInfo(); flyHome(); });
playBtn.addEventListener('click', () => {
if (playing) { playing = false; return; }
if (buildT >= NPARTS) { buildT = 0; closeInfo(); }
playing = true; holdT = 0;
});
const endDrag = () => { sliderDragging = false; };
slider.addEventListener('pointerdown', () => { sliderDragging = true; playing = false; });
slider.addEventListener('pointerup', endDrag);
slider.addEventListener('pointercancel', endDrag);
slider.addEventListener('change', endDrag);
slider.addEventListener('input', () => { buildT = parseFloat(slider.value); playing = false; });
const ticksEl = $('ticks'), ticks = [];
for (let i = 1; i <= NPARTS; i++){
const t = document.createElement('span'); t.className = 'tk'; t.style.left = ((i - 0.5) / NPARTS * 100) + '%'; t.style.setProperty('--c', PARTS[i].css);
ticksEl.appendChild(t); ticks.push(t);
}
const tagsEl = $('tags');
PARTS.forEach((p, i) => {
const el = document.createElement('div'); el.className = 'tag'; el.style.setProperty('--c', p.css);
el.innerHTML = '<div class="tg"><span class="dot"></span>' + (p.short || p.name) + '</div>';
el.addEventListener('click', e => { e.stopPropagation(); if (p.a > 0.5) selectPart(i); });
tagsEl.appendChild(el); p.el = el;
});
let lastKey = '', lastPlay = null;
function updatePanel(){
const complete = isComplete();
const k = selected !== null ? 'i' + selected : complete ? 'done' : 'b' + curPart;
if (k === lastKey) return; lastKey = k;
let c, b, n, l, m = '', info = false;
if (selected !== null){
const p = PARTS[selected]; c = p.css; b = 'What it does'; n = p.name; l = p.line; m = p.more; info = true;
} else if (complete){
c = '#fde047'; b = 'Complete!'; n = 'Your animal cell is alive';
l = 'Drag to spin it, pinch to zoom, and tap any part to fly to it and read what it does.';
m = 'Flip the Cut open switch to slice it in half and look inside.';
} else if (curPart === 0){
const p = PARTS[0]; c = p.css; b = 'Starting'; n = p.name;
l = 'Here is an empty cell: just its see-through skin. ' + p.line.replace("The cell's", 'It is the');
} else {
const p = PARTS[curPart]; c = p.css; b = 'Part ' + curPart + ' of ' + NPARTS; n = p.name; l = p.line;
}
card.style.setProperty('--c', c);
badge.textContent = b; pname.textContent = n; pline.textContent = l; pmore.textContent = m;
pmore.classList.toggle('hidden', !m);
closeBtn.classList.toggle('hidden', !info);
cardBtns.classList.toggle('hidden', !info);
}
function updateUI(){
if (!sliderDragging) slider.value = buildT.toFixed(2);
slider.style.setProperty('--fill', (buildT / NPARTS * 100).toFixed(2) + '%');
countEl.textContent = curPart + '/' + NPARTS;
if (lastPlay !== playing){ lastPlay = playing; playBtn.innerHTML = playing ? PAUSE : PLAY; }
for (let i = 0; i < NPARTS; i++) ticks[i].classList.toggle('lit', PARTS[i + 1].a > 0.5);
updatePanel();
}
const tv = new V3();
function updateTags(){
const complete = isComplete();
PARTS.forEach((p, i) => {
let show = false, cur = false;
if (p.a > 0.55){
if (selected !== null) { show = i === selected || (labelsOn && complete); cur = i === selected; }
else if (!complete) { show = i === curPart; cur = show; }
else show = labelsOn;
}
if (show){
p.tag.getWorldPosition(tv);
if (cutPlane.distanceToPoint(tv) < 0) show = false;
else { tv.project(camera); if (tv.z > 1 || Math.abs(tv.x) > 1.05 || Math.abs(tv.y) > 1.05) show = false; }
}
if (show) p.el.style.transform = 'translate(' + ((tv.x * 0.5 + 0.5) * W).toFixed(1) + 'px,' + ((-tv.y * 0.5 + 0.5) * H).toFixed(1) + 'px)';
p.el.classList.toggle('show', show);
p.el.classList.toggle('cur', cur);
});
}
/* ---------- part animation ---------- */
function updateParts(t){
for (let i = 0; i < PARTS.length; i++){
const p = PARTS[i], g = p.group;
const a = i === 0 ? clamp(memT / 1.6) : appearOf(i);
p.a = a;
g.visible = a > 0.001;
if (!g.visible) continue;
const amp = p.drift ?? 0.06;
g.position.set(p.basePos.x + Math.sin(t * 0.45 + p.dph) * amp, p.basePos.y + Math.sin(t * 0.37 + p.dph * 1.7) * amp, p.basePos.z + Math.sin(t * 0.41 + p.dph * 0.6) * amp * 0.8);
g.rotation.set(p.baseRot.x + Math.sin(t * 0.3 + p.dph) * 0.025, p.baseRot.y + Math.sin(t * 0.23 + p.dph * 1.3) * 0.03 + t * (p.spin || 0), p.baseRot.z);
const pulse = 1 + p.pulse * Math.sin(t * 1.5 + p.ph);
if (p.mode === 'items'){
g.scale.setScalar(pulse);
const n = p.items.length;
p.items.forEach((it, k) => {
const ak = clamp((a - 0.5 * k / n) * 2), u = it.userData;
it.visible = ak > 0.001;
it.scale.setScalar(Math.max(1e-4, easeOutBack(ak)));
it.position.set(u.bp.x, u.bp.y + Math.sin(t * 0.8 + u.ph) * 0.07, u.bp.z);
it.rotation.set(u.br.x + Math.sin(t * 0.5 + u.ph) * u.wob, u.br.y, u.br.z + Math.sin(t * 0.42 + u.ph * 1.3) * u.wob);
});
} else if (p.mode === 'vesicles') g.scale.setScalar(1);
else g.scale.setScalar(Math.max(1e-4, easeOutBack(a)) * pulse);
const glow = Math.sin(clamp(a) * Math.PI) * 0.9 + (selected === i ? 0.25 + 0.2 * Math.sin(t * 4) : 0);
for (const m of p.mats){
if (m.emissiveIntensity !== undefined) m.emissiveIntensity = m.userData.be + glow;
if (m.transparent) m.opacity = m.userData.bo * clamp(a * 1.5);
}
}
}
/* ---------- demo (#demo) ---------- */
const DEMO = [
[0, () => { rebuild(); }],
[9.9, () => setCut(true)],
[11.0, () => {
let pick = null, bestD = 1e9, maxD = -1e9, fallback = null;
mitoItems.forEach(it => {
it.getWorldPosition(tmpV); const d = cutPlane.distanceToPoint(tmpV);
if (d > 0.45 && d < bestD){ bestD = d; pick = it; }
if (d > maxD){ maxD = d; fallback = it; }
});
const it = pick || fallback, o = it.userData.outer;
selectPart(7, { object:o, point:o.getWorldPosition(new V3()) });
}],
[13.9, () => selectPart(1)],
[16.6, () => { closeInfo(); setCut(false); flyHome(1.0); controls.autoRotate = true; }]
];
function demoTick(dt){
demo.t += dt;
if (demo.t >= 20.5){ demo.t = 0; demo.next = 0; }
while (demo.next < DEMO.length && demo.t >= DEMO[demo.next][0]){ DEMO[demo.next][1](); demo.next++; }
if (demo.t > 17.4 && demo.t < 19.8){ playing = false; buildT = NPARTS - 8 * Math.sin(Math.PI * (demo.t - 17.4) / 2.4); }
else if (demo.t >= 19.8) buildT = NPARTS;
}
function endDemo(){
if (!demo) return;
demo = null; $('demoPill').classList.add('hidden');
}
if (demo) $('demoPill').classList.remove('hidden');
['pointerdown', 'touchstart', 'wheel', 'keydown'].forEach(ev => addEventListener(ev, e => { if (demo && e.isTrusted) endDemo(); }, { capture:true, passive:true }));
/* ---------- loop ---------- */
const clock = new THREE.Clock();
function frame(){
const dt = Math.min(clock.getDelta(), 0.05);
time += dt; memT += dt;
if (demo) demoTick(dt);
const rate = demo ? NPARTS / 9 : 1 / 2.4;
if (playing && !sliderDragging){
if (holdT > 0) holdT -= dt;
else { buildT = Math.min(NPARTS, buildT + dt * rate); if (buildT >= NPARTS) playing = false; }
}
if (buildT >= NPARTS) doneT += dt; else doneT = 0;
curPart = 0; for (let i = 1; i <= NPARTS; i++) if (appearOf(i) > 0) curPart = i;
cutAmt += ((cutOn ? 1 : 0) - cutAmt) * Math.min(1, dt * 2.4);
cutPlane.constant = 6 * (1 - smooth(clamp(cutAmt)));
updateMembrane(time);
updateParts(time);
updateVesicles(time);
if (selected !== null && PARTS[selected].a < 0.3) closeInfo();
cytoplasm.rotation.y = time * 0.02; cytoplasm.rotation.x = Math.sin(time * 0.1) * 0.05;
cytoMat.opacity = 0.4 * clamp(memT / 1.6);
if (fly){
fly.t += dt / fly.dur;
const e = smooth(clamp(fly.t));
camera.position.lerpVectors(fly.p0, fly.p1, e);
controls.target.lerpVectors(fly.t0, fly.t1, e);
camera.lookAt(controls.target);
if (fly.t >= 1){ fly = null; controls.update(); }
} else controls.update();
renderer.render(scene, camera);
updateTags();
updateUI();
}
renderer.setAnimationLoop(frame);
</script>
</body>
</html>
