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 3D</title>
<style>
:root{--ui:rgba(12,20,46,.80);--line:rgba(160,210,255,.22);--txt:#eaf4ff;--mut:#a9bedf;--accent:#5fd4ff}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;color:var(--txt);font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;touch-action:none;user-select:none;-webkit-user-select:none}
body{background:radial-gradient(ellipse at 50% 38%,#173064 0%,#0b1636 48%,#050816 100%)}
#c{position:fixed;inset:0;width:100%;height:100%;display:block}
#labels{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.lab{position:absolute;left:0;top:0;pointer-events:auto;border:1px solid rgba(255,255,255,.22);background:rgba(8,16,38,.74);color:#fff;font:600 12px/1 system-ui,sans-serif;padding:8px 11px 8px 8px;border-radius:999px;display:none;align-items:center;gap:6px;white-space:nowrap;cursor:pointer;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}
.lab i,#cardDot{display:inline-block;width:10px;height:10px;border-radius:50%;flex:none;box-shadow:0 0 8px currentColor}
.lab.now{border-color:#fff;box-shadow:0 0 14px rgba(140,220,255,.7);font-size:13px}
.lab.sel{border-color:#ffe066;box-shadow:0 0 14px rgba(255,224,102,.7)}
#top{position:fixed;top:calc(10px + env(safe-area-inset-top));left:12px;right:12px;display:flex;justify-content:space-between;align-items:center;pointer-events:none;gap:8px}
.brand b{display:block;font-size:19px;letter-spacing:.3px}
.brand span{font-size:12px;color:var(--mut)}
#chip{background:var(--ui);border:1px solid var(--line);border-radius:999px;padding:8px 13px;font-size:13px;font-weight:700;white-space:nowrap}
#demoBadge{position:fixed;top:calc(62px + env(safe-area-inset-top));left:50%;transform:translateX(-50%);background:#ffe066;color:#1a1400;font-weight:800;font-size:12px;padding:6px 12px;border-radius:999px;pointer-events:none}
#hint{position:fixed;left:50%;top:calc(64px + env(safe-area-inset-top));transform:translateX(-50%);background:rgba(95,212,255,.18);border:1px solid rgba(95,212,255,.5);padding:9px 14px;border-radius:999px;font-size:13px;font-weight:600;opacity:0;transition:opacity .6s;pointer-events:none;white-space:nowrap}
#hint.show{opacity:1}
#panel{position:fixed;left:0;right:0;bottom:0;padding:0 10px calc(10px + env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:8px;max-width:660px;margin:0 auto;pointer-events:none}
#card,#controls{pointer-events:auto;background:var(--ui);border:1px solid var(--line);border-radius:18px;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}
#card{padding:11px 14px 12px}
#card.pop{animation:pop .45s ease}
@keyframes pop{0%{transform:translateY(6px) scale(.98);opacity:.4}100%{transform:none;opacity:1}}
#cardTag{font-size:11px;letter-spacing:.8px;text-transform:uppercase;color:var(--mut);font-weight:700;margin-bottom:3px}
#cardTitle{display:flex;align-items:center;gap:8px;font-size:18px;font-weight:800}
#cardLine{margin:5px 0 0;font-size:15px;line-height:1.35}
#cardMore{margin:7px 0 0;font-size:14px;line-height:1.4;color:#cfe0f7;display:none}
#cardMore b{color:#ffe066}
#controls{padding:10px 10px 10px}
.row{display:flex;align-items:center;gap:10px;padding:0 4px 8px}
.lbl{font-size:13px;font-weight:700;color:var(--mut);min-width:38px}
input[type=range]{flex:1;-webkit-appearance:none;appearance:none;height:34px;background:transparent;touch-action:none;margin:0}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#3fb6e8,#8b6cff,#ff6f4a)}
input[type=range]::-moz-range-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#3fb6e8,#8b6cff,#ff6f4a)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;border-radius:50%;background:#fff;border:3px solid #5fd4ff;margin-top:-10px;box-shadow:0 2px 8px rgba(0,0,0,.5)}
input[type=range]::-moz-range-thumb{width:26px;height:26px;border-radius:50%;background:#fff;border:3px solid #5fd4ff}
.btns{display:grid;grid-template-columns:repeat(4,1fr);gap:7px}
.btn{min-height:50px;border-radius:14px;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.08);color:#fff;font:700 14px/1.15 system-ui,sans-serif;padding:6px 6px;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:7px;text-align:center}
.btn:active{transform:scale(.96);background:rgba(255,255,255,.16)}
#rebuild{background:linear-gradient(180deg,#2aa7da,#1b77b5);border-color:transparent}
.sw .knob{width:34px;height:20px;border-radius:12px;background:rgba(255,255,255,.25);position:relative;flex:none;transition:background .25s}
.sw .knob::after{content:"";position:absolute;left:2px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .25s}
.sw[aria-checked=true]{background:rgba(255,111,74,.22);border-color:#ff8a66}
.sw[aria-checked=true] .knob{background:#ff6f4a}
.sw[aria-checked=true] .knob::after{transform:translateX(14px)}
#err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:30px;font-size:16px}
@media (max-width:430px){
.btn{font-size:12.5px;min-height:52px;flex-direction:column;gap:4px}
.sw .knob{width:30px;height:18px}.sw .knob::after{width:14px;height:14px}.sw[aria-checked=true] .knob::after{transform:translateX(12px)}
#cardLine{font-size:14px}#cardMore{font-size:13px}#cardTitle{font-size:17px}
.brand b{font-size:17px}
}
</style>
<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>
</head>
<body>
<canvas id="c" aria-label="Interactive 3D animal cell"></canvas>
<div id="labels"></div>
<div id="top">
<div class="brand"><b>Build-a-Cell</b><span>a living 3D animal cell</span></div>
<div id="chip">Starting…</div>
</div>
<div id="demoBadge" hidden>DEMO · touch to take over</div>
<div id="hint">Drag to spin · Pinch to zoom · Tap a part</div>
<div id="panel">
<div id="card">
<div id="cardTag"></div>
<div id="cardTitle"><span id="cardDot"></span><span id="cardName"></span></div>
<p id="cardLine"></p>
<p id="cardMore"></p>
</div>
<div id="controls">
<div class="row"><span class="lbl">Build</span><input id="scrub" type="range" min="0" max="11" step="0.01" value="0" aria-label="Scrub through the build"></div>
<div class="btns">
<button id="rebuild" class="btn">↻ Rebuild</button>
<button id="cut" class="btn sw" role="switch" aria-checked="false"><span class="knob"></span><span>Cut open</span></button>
<button id="labelsBtn" class="btn">Labels: on</button>
<button id="home" class="btn">Whole cell</button>
</div>
</div>
</div>
<div id="err">Sorry, this device could not start 3D graphics (WebGL).</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const $ = id => document.getElementById(id);
/* ---------- data ---------- */
const MEMBRANE = {name:'Cell membrane', color:'#7fd6ff', line:"A thin, see-through skin that holds the cell together and decides what gets in and out."};
const PARTS = [
{name:'Nucleus', color:'#8b6cff', focus:3.6,
line:"The control center that keeps the cell's DNA, its instruction book.",
more:"Think of it as the cell's library and head office. It stores DNA, makes copies of the instructions the cell needs, and sends them out through tiny holes called <b>nuclear pores</b>."},
{name:'Nucleolus', color:'#ff4f9a', focus:1.9,
line:"A dense ball inside the nucleus that builds the parts of ribosomes.",
more:"It has no skin of its own. It's a busy spot inside the nucleus where ribosome pieces are put together before they head out into the cell to make proteins."},
{name:'Rough ER', color:'#3fb6e8', focus:2.8,
line:"Folded sheets dotted with ribosomes, where many proteins are made and folded.",
more:"ER stands for endoplasmic reticulum. Ribosomes stuck to it make it look bumpy, or <b>rough</b>. Proteins made here get folded into the right shape and then sent on to the Golgi."},
{name:'Smooth ER', color:'#6fe0a0', focus:2.3,
line:"A web of tubes with no ribosomes that makes fats and cleans up harmful chemicals.",
more:"Smooth ER builds the fats (lipids) used for membranes, stores calcium and helps break down poisons. Your liver cells are packed with it!"},
{name:'Ribosomes', color:'#ffe066', focus:1.0,
line:"Tiny machines that read instructions and snap building blocks together into proteins.",
more:"They are so small you need an electron microscope to see them. Some float freely, others sit on the rough ER. They follow RNA instructions to link <b>amino acids</b> into proteins."},
{name:'Golgi apparatus', color:'#ffa03c', focus:2.3,
line:"A stack of flat pouches that packs, labels and ships proteins, like a post office.",
more:"Proteins arrive from the ER, get finishing touches such as sugar 'address labels', and are sorted into vesicles that carry them where they are needed, even outside the cell."},
{name:'Mitochondria', color:'#ff6f4a', focus:1.4,
line:"Power plants that turn food and oxygen into energy the cell can use.",
more:"They burn sugar with oxygen to make <b>ATP</b>, the cell's energy coins. The folds inside give them more working space. They even have their own little loop of DNA!"},
{name:'Lysosomes', color:'#b6f23c', focus:1.1,
line:"Recycling bags full of enzymes that break down waste and worn-out parts.",
more:"Their strong enzymes digest old cell parts, germs and food bits. Their skin keeps those enzymes locked up so they don't digest the rest of the cell."},
{name:'Vesicles', color:'#9ff0ff', focus:0.9,
line:"Little bubbles that carry things around the cell and out to its edge.",
more:"Vesicles pinch off from the ER and Golgi, ride along the cytoskeleton, and can merge with the cell membrane to dump their cargo outside. Watch them travel!"},
{name:'Centrioles', color:'#f7a8ff', focus:1.3,
line:"A pair of tiny tube bundles that help the cell split its chromosomes when it divides.",
more:"Each centriole is a ring of nine groups of three tiny tubes. The pair sits at right angles and organizes the strands that pull copied chromosomes apart when one cell becomes two."},
{name:'Cytoskeleton', color:'#d8ecff', focus:2.8,
line:"A web of protein strands that gives the cell its shape and works like roads.",
more:"It's made of <b>microtubules</b> (thicker, white here) and thinner filaments (pink). It acts like a skeleton and a road system at once: motor proteins walk along it carrying cargo."}
];
const NP = PARTS.length;
/* ---------- renderer / scene ---------- */
let renderer;
try{
renderer = new THREE.WebGLRenderer({canvas:$('c'), antialias:true, alpha:true});
}catch(e){ $('err').style.display='flex'; throw e; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1, 2));
renderer.setClearColor(0x000000, 0);
renderer.localClippingEnabled = true;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, 1, 0.05, 200);
camera.position.set(2.4, 2.8, 12);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; controls.dampingFactor = 0.08;
controls.enablePan = false; controls.minDistance = 0.4; controls.maxDistance = 45;
controls.rotateSpeed = 0.8; controls.autoRotate = true; controls.autoRotateSpeed = 0.7;
controls.touches = {ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_ROTATE};
scene.add(new THREE.HemisphereLight(0xbfe4ff, 0x2a1f50, 1.1));
scene.add(new THREE.AmbientLight(0xffffff, 0.35));
const sun = new THREE.DirectionalLight(0xffffff, 1.8); sun.position.set(5, 7, 8); scene.add(sun);
const rim = new THREE.DirectionalLight(0x88aaff, 0.8); rim.position.set(-6, -3, -5); scene.add(rim);
const inner = new THREE.PointLight(0x9fdcff, 5, 0, 2); scene.add(inner);
const root = new THREE.Group(); scene.add(root);
/* ---------- helpers ---------- */
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; }
const rr = (a,b) => a + (b-a)*rand();
const V = (x,y,z) => new THREE.Vector3(x,y,z);
function randDir(){ const u = rr(-1,1), th = rr(0, Math.PI*2), s = Math.sqrt(1-u*u); return V(s*Math.cos(th), u, s*Math.sin(th)); }
const sph = (phi, th) => V(-Math.cos(phi)*Math.sin(th), Math.cos(th), Math.sin(phi)*Math.sin(th));
const clamp = (x,a,b) => Math.max(a, Math.min(b, x));
const easeOutBack = t => { const c1 = 1.70158, c3 = c1+1; return 1 + c3*Math.pow(t-1,3) + c1*Math.pow(t-1,2); };
const easeInOut = t => t<.5 ? 4*t*t*t : 1 - Math.pow(-2*t+2,3)/2;
const smooth = t => t*t*(3-2*t);
const clipPlane = new THREE.Plane(V(0,0,-1), 6);
const CLIP = [clipPlane];
const cutDir = V(0,0,1);
let clipC = 6, clipTarget = 6, cutOn = false;
function stdMat(color, o = {}){
const op = o.opacity ?? 1;
return new THREE.MeshStandardMaterial({
color, roughness: o.rough ?? 0.5, metalness: 0,
emissive: new THREE.Color(o.emissive ?? color), emissiveIntensity: o.emi ?? 0.15,
transparent: op < 1, opacity: op, side: o.side ?? THREE.FrontSide,
clippingPlanes: CLIP, map: o.map || null, depthWrite: o.depthWrite ?? true
});
}
const parts = PARTS.map((p,i) => ({...p, idx:i, pieces:[], mats:[], appear:0, anchorObj:root, anchorLocal:V(0,0,0)}));
function regMat(part, m){ part.mats.push({m, base:m.opacity, emi:m.emissiveIntensity, baseT:m.transparent}); return m; }
function addPiece(part, obj, o = {}){
obj.traverse(c => { c.userData.part = part.idx; });
const pc = {obj, part, pos:obj.position.clone(), quat:obj.quaternion.clone(), scl:obj.scale.clone(),
order:o.order ?? rand(), amp:o.amp ?? 0.03, ph:rand()*6.283, sp:0.35 + rand()*0.5,
pulse:o.pulse ?? 0.03, rot:o.rot ?? 0, grow:o.grow || 0, inst:o.inst || null, path:o.path || null, period:o.period || 6, last:NaN};
if (!pc.inst && !pc.grow) obj.scale.setScalar(0);
if (pc.grow){ obj.geometry.setDrawRange(0, 0); }
part.pieces.push(pc);
return pc;
}
/* key positions */
const N = V(0.25, 0.15, -0.15); // nucleus
const G = V(-1.75, 0.85, 0.35); // golgi
const S = V(-0.45, -1.75, -0.2); // smooth ER
const C = V(1.45, -1.5, 0.9); // centrosome
const occ = [{p:N, r:1.05}, {p:G, r:0.8}, {p:S, r:0.85}, {p:C, r:0.45}];
for (const ph of [Math.PI-0.7, Math.PI, Math.PI+0.7]) for (const th of [0.9, 1.57, 2.2]) occ.push({p:N.clone().add(sph(ph,th).multiplyScalar(1.48)), r:0.5});
function place(r, maxR = 2.6){
for (let k = 0; k < 600; k++){
const p = randDir().multiplyScalar(Math.cbrt(rand()) * (maxR - r));
if (occ.every(o => o.p.distanceTo(p) > o.r + r)){ occ.push({p, r}); return p; }
}
const p = randDir().multiplyScalar(2.3); occ.push({p, r}); return p;
}
function canvasTex(w, h, draw){ const c = document.createElement('canvas'); c.width = w; c.height = h; draw(c.getContext('2d'), w, h); const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t; }
/* ---------- membrane ---------- */
const R = 3;
const memGeo = new THREE.SphereGeometry(R, 96, 64);
const memBase = memGeo.attributes.position.array.slice();
function memMat(side){
return new THREE.MeshPhysicalMaterial({color:0x7fd6ff, roughness:0.2, metalness:0, clearcoat:1, clearcoatRoughness:0.25,
transparent:true, opacity:0.13, side, depthWrite:false, emissive:0x0b3a58, emissiveIntensity:0.7, clippingPlanes:CLIP});
}
const memBackM = memMat(THREE.BackSide), memFrontM = memMat(THREE.FrontSide);
const memBack = new THREE.Mesh(memGeo, memBackM); memBack.renderOrder = -10;
const memFront = new THREE.Mesh(memGeo, memFrontM); memFront.renderOrder = 10;
const fresM = new THREE.ShaderMaterial({
uniforms:{uColor:{value:new THREE.Color(0x8fe3ff)}, uOpacity:{value:0}},
vertexShader:`#include <clipping_planes_pars_vertex>
varying vec3 vN; varying vec3 vV;
void main(){
#include <begin_vertex>
vec4 mvPosition = modelViewMatrix * vec4(transformed, 1.0);
vN = normalize(normalMatrix * normal); vV = normalize(-mvPosition.xyz);
gl_Position = projectionMatrix * mvPosition;
#include <clipping_planes_vertex>
}`,
fragmentShader:`#include <clipping_planes_pars_fragment>
uniform vec3 uColor; uniform float uOpacity;
varying vec3 vN; varying vec3 vV;
void main(){
#include <clipping_planes_fragment>
float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.6);
gl_FragColor = vec4(uColor * f * uOpacity, 1.0);
}`,
transparent:true, depthWrite:false, blending:THREE.AdditiveBlending, clipping:true, clippingPlanes:CLIP
});
const memRim = new THREE.Mesh(memGeo, fresM); memRim.renderOrder = 11;
root.add(memBack, memFront, memRim);
const cutRing = new THREE.Mesh(new THREE.TorusGeometry(1, 0.028, 8, 160), new THREE.MeshBasicMaterial({color:0xaeefff, transparent:true, opacity:0, depthWrite:false}));
cutRing.renderOrder = 12; scene.add(cutRing);
/* cytoplasm particles */
const dotTex = canvasTex(64, 64, (g,w,h) => { const gr = g.createRadialGradient(32,32,0,32,32,32); gr.addColorStop(0,'rgba(255,255,255,1)'); gr.addColorStop(.4,'rgba(255,255,255,.5)'); gr.addColorStop(1,'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0,0,w,h); });
const PC = 700;
const cytoGeo = new THREE.BufferGeometry();
const cytoBase = new Float32Array(PC*3);
for (let i = 0; i < PC; i++){ const p = randDir().multiplyScalar(Math.cbrt(rand())*2.8); cytoBase.set([p.x,p.y,p.z], i*3); }
cytoGeo.setAttribute('position', new THREE.BufferAttribute(cytoBase.slice(), 3));
const cytoM = new THREE.PointsMaterial({color:0xbfe9ff, size:0.06, map:dotTex, transparent:true, opacity:0, depthWrite:false, blending:THREE.AdditiveBlending, clippingPlanes:CLIP});
const cyto = new THREE.Points(cytoGeo, cytoM); root.add(cyto);
/* ---------- 0 nucleus ---------- */
{
const part = parts[0];
const shellM = regMat(part, new THREE.MeshPhysicalMaterial({color:0x8b6cff, roughness:0.25, metalness:0, clearcoat:1,
transparent:true, opacity:0.5, side:THREE.DoubleSide, depthWrite:false, emissive:0x3b2390, emissiveIntensity:0.55, clippingPlanes:CLIP}));
const shell = new THREE.Mesh(new THREE.SphereGeometry(1, 64, 48), shellM);
shell.position.copy(N);
const poreM = regMat(part, stdMat(0xe2d6ff, {emi:0.5}));
const pores = new THREE.InstancedMesh(new THREE.TorusGeometry(0.045, 0.015, 6, 12), poreM, 80);
const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), one = V(1,1,1);
for (let i = 0; i < 80; i++){ const d = randDir(); q.setFromUnitVectors(V(0,0,1), d); m4.compose(d.clone().multiplyScalar(1.0), q, one); pores.setMatrixAt(i, m4); }
shell.add(pores);
const chrM = regMat(part, stdMat(0xc98bff, {opacity:0.9, emi:0.4}));
for (let k = 0; k < 7; k++){
const pts = []; let p = randDir().multiplyScalar(rr(0, 0.55));
for (let j = 0; j < 9; j++){ pts.push(p.clone()); p.add(randDir().multiplyScalar(0.24)); if (p.length() > 0.8) p.multiplyScalar(0.7); }
shell.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 70, 0.022, 5), chrM));
}
root.add(shell);
addPiece(part, shell, {order:0, amp:0.025, pulse:0.02});
part.anchorObj = shell; part.anchorLocal = V(0, 1.0, 0);
}
/* ---------- 1 nucleolus ---------- */
{
const part = parts[1];
const g = new THREE.IcosahedronGeometry(0.33, 4);
const pa = g.attributes.position, v = V(0,0,0);
for (let i = 0; i < pa.count; i++){ v.fromBufferAttribute(pa, i); const f = 1 + 0.07*Math.sin(v.x*18)*Math.sin(v.y*16+1)*Math.sin(v.z*17+2) + 0.04*Math.sin(v.x*9+v.y*7); v.multiplyScalar(f); pa.setXYZ(i, v.x, v.y, v.z); }
g.computeVertexNormals();
const mesh = new THREE.Mesh(g, regMat(part, stdMat(0xff4f9a, {rough:0.7, emi:0.3})));
mesh.position.copy(N).add(V(0.22, 0.18, 0.12));
root.add(mesh);
addPiece(part, mesh, {order:0, amp:0.02, pulse:0.04, rot:0.3});
part.anchorObj = mesh; part.anchorLocal = V(0, 0.33, 0);
}
/* ---------- 2 rough ER ---------- */
const sheets = [];
{
const part = parts[2];
const grp = new THREE.Group(); grp.position.copy(N); root.add(grp);
const m = regMat(part, stdMat(0x3fb6e8, {opacity:0.82, side:THREE.DoubleSide, emi:0.22, rough:0.4}));
const specs = [[1.28, Math.PI-1.05, 2.1, 0.55, 1.5], [1.46, Math.PI-0.95, 1.9, 0.62, 1.4], [1.64, Math.PI-0.85, 1.7, 0.7, 1.3]];
specs.forEach((s, k) => {
const g = new THREE.SphereGeometry(s[0], 72, 24, s[1], s[2], s[3], s[4]);
const pa = g.attributes.position, v = V(0,0,0);
for (let i = 0; i < pa.count; i++){
v.fromBufferAttribute(pa, i); const n = v.clone().normalize();
const a = Math.atan2(v.z, v.x), e = Math.acos(clamp(n.y, -1, 1));
const w = 0.045*Math.sin(a*10 + 1.3) + 0.03*Math.sin(e*14 + 2.1) + 0.02*Math.sin((a+e)*7);
v.addScaledVector(n, w); pa.setXYZ(i, v.x, v.y, v.z);
}
g.computeVertexNormals();
const mesh = new THREE.Mesh(g, m); grp.add(mesh); sheets.push(mesh);
addPiece(part, mesh, {order:k/3, amp:0.012, pulse:0.012});
});
part.anchorObj = sheets[2]; part.anchorLocal = sph(Math.PI+0.35, 0.85).multiplyScalar(1.66);
}
/* ---------- 3 smooth ER ---------- */
{
const part = parts[3];
const m = regMat(part, stdMat(0x6fe0a0, {emi:0.25, rough:0.45}));
let first = null;
for (let k = 0; k < 10; k++){
const pts = []; const p = S.clone().add(randDir().multiplyScalar(rr(0, 0.5)));
for (let j = 0; j < 7; j++){ pts.push(p.clone()); p.add(randDir().multiplyScalar(0.28)); if (p.distanceTo(S) > 0.8) p.lerp(S, 0.45); }
const curve = new THREE.CatmullRomCurve3(pts);
if (!first) first = curve.getPoint(0.5);
const g = new THREE.TubeGeometry(curve, 64, 0.05, 8, false);
const mesh = new THREE.Mesh(g, m); root.add(mesh);
addPiece(part, mesh, {grow:g.index.count, order:k/10, amp:0.015, pulse:0});
}
part.anchorLocal = first;
}
/* ---------- 4 ribosomes ---------- */
{
const part = parts[4];
const geo = new THREE.IcosahedronGeometry(0.032, 1);
const m = regMat(part, stdMat(0xffe066, {emi:0.35, rough:0.5}));
sheets.forEach(sh => {
const pa = sh.geometry.attributes.position, na = sh.geometry.attributes.normal, list = [];
for (let i = 0; i < 110; i++){
const j = Math.floor(rand()*pa.count);
const p = V(pa.getX(j), pa.getY(j), pa.getZ(j)); const n = V(na.getX(j), na.getY(j), na.getZ(j));
p.addScaledVector(n, 0.04 * (rand() < 0.5 ? 1 : -1)); list.push(p);
}
const inst = new THREE.InstancedMesh(geo, m, list.length); sh.add(inst);
addPiece(part, inst, {inst:list, amp:0, pulse:0});
});
const free = [];
while (free.length < 150){ const p = randDir().multiplyScalar(Math.cbrt(rand())*2.75); if (p.distanceTo(N) > 1.15) free.push(p); }
const fi = new THREE.InstancedMesh(geo, m, free.length); root.add(fi);
addPiece(part, fi, {inst:free, amp:0.03, pulse:0});
part.anchorObj = sheets[2]; part.anchorLocal = sph(Math.PI-0.5, 1.75).multiplyScalar(1.72);
}
/* ---------- 5 golgi ---------- */
const gDir = G.clone().sub(N).normalize();
{
const part = parts[5];
const grp = new THREE.Group(); grp.position.copy(G); grp.quaternion.setFromUnitVectors(V(0,1,0), gDir); root.add(grp);
const m = regMat(part, stdMat(0xffa03c, {side:THREE.DoubleSide, emi:0.28, rough:0.4, opacity:0.93}));
for (let k = 0; k < 5; k++){
const r = 1.1 + k*0.11, th = 0.46 - k*0.035;
const g = new THREE.SphereGeometry(r, 44, 6, 0, Math.PI*2, 0, th); g.translate(0, -1.1, 0);
const mesh = new THREE.Mesh(g, m);
const rimR = r*Math.sin(th);
const rimT = new THREE.Mesh(new THREE.TorusGeometry(rimR, 0.032, 6, 48), m);
rimT.rotation.x = Math.PI/2; rimT.position.y = r*Math.cos(th) - 1.1; mesh.add(rimT);
mesh.scale.set(1.35, 1, 0.9);
grp.add(mesh);
addPiece(part, mesh, {order:k/5, amp:0.01, pulse:0.02});
}
const bm = regMat(part, stdMat(0xffc07a, {emi:0.35}));
for (let k = 0; k < 9; k++){
const a = rr(0, Math.PI*2);
const b = new THREE.Mesh(new THREE.SphereGeometry(rr(0.045, 0.065), 14, 10), bm);
b.position.set(Math.cos(a)*0.72, rr(-0.15, 0.4), Math.sin(a)*0.5); grp.add(b);
addPiece(part, b, {order:0.6 + rand()*0.4, amp:0.03, pulse:0.06});
}
part.anchorObj = grp; part.anchorLocal = V(0, 0.55, 0);
}
/* ---------- 6 mitochondria ---------- */
{
const part = parts[6];
const tex = canvasTex(256, 256, (g,w,h) => {
g.fillStyle = '#ff8d4d'; g.fillRect(0,0,w,h);
g.lineCap = 'round';
for (let y = 14; y < h; y += 24){
g.strokeStyle = '#b5401c'; g.lineWidth = 8; g.beginPath();
for (let x = 0; x <= w; x += 8){ const yy = y + Math.sin(x*0.07 + y)*6; x ? g.lineTo(x, yy) : g.moveTo(x, yy); } g.stroke();
g.strokeStyle = 'rgba(255,225,180,.7)'; g.lineWidth = 2; g.beginPath();
for (let x = 0; x <= w; x += 8){ const yy = y + 6 + Math.sin(x*0.07 + y)*6; x ? g.lineTo(x, yy) : g.moveTo(x, yy); } g.stroke();
}
});
const m = regMat(part, stdMat(0xffffff, {map:tex, emissive:0xff6a30, emi:0.18, rough:0.55}));
const om = regMat(part, stdMat(0xffb27a, {opacity:0.3, emi:0.3, depthWrite:false}));
const geo = new THREE.CapsuleGeometry(0.15, 0.42, 8, 20);
for (let k = 0; k < 7; k++){
const mesh = new THREE.Mesh(geo, m);
mesh.position.copy(place(0.4)); mesh.quaternion.setFromUnitVectors(V(0,1,0), randDir());
const outer = new THREE.Mesh(geo, om); outer.scale.setScalar(1.18); mesh.add(outer);
root.add(mesh);
addPiece(part, mesh, {order:k/7, amp:0.04, rot:0.25, pulse:0.03});
if (k === 0){ part.anchorObj = mesh; part.anchorLocal = V(0, 0.4, 0); }
}
}
/* ---------- 7 lysosomes ---------- */
{
const part = parts[7];
const g = new THREE.IcosahedronGeometry(0.13, 3);
const pa = g.attributes.position, v = V(0,0,0);
for (let i = 0; i < pa.count; i++){ v.fromBufferAttribute(pa, i); v.multiplyScalar(1 + 0.06*Math.sin(v.x*60)*Math.sin(v.y*55)*Math.sin(v.z*50)); pa.setXYZ(i, v.x, v.y, v.z); }
g.computeVertexNormals();
const m = regMat(part, stdMat(0xb6f23c, {emi:0.35, rough:0.6}));
const dm = regMat(part, stdMat(0x3d7a10, {emi:0.2}));
for (let k = 0; k < 6; k++){
const mesh = new THREE.Mesh(g, m); mesh.position.copy(place(0.17));
for (let j = 0; j < 5; j++){ const d = new THREE.Mesh(new THREE.SphereGeometry(0.025, 8, 6), dm); d.position.copy(randDir().multiplyScalar(0.125)); mesh.add(d); }
root.add(mesh);
addPiece(part, mesh, {order:k/6, amp:0.05, pulse:0.05, rot:0.5});
if (k === 0){ part.anchorObj = mesh; part.anchorLocal = V(0, 0.15, 0); }
}
}
/* ---------- 8 vesicles ---------- */
{
const part = parts[8];
const m = regMat(part, stdMat(0x9ff0ff, {opacity:0.7, emi:0.45, rough:0.2}));
const geo = new THREE.SphereGeometry(1, 18, 12);
for (let k = 0; k < 10; k++){
const r = rr(0.05, 0.085);
const mesh = new THREE.Mesh(geo, m); mesh.scale.setScalar(r);
if (k < 4) mesh.position.copy(G).add(gDir.clone().multiplyScalar(0.3)).add(randDir().multiplyScalar(rr(0.6, 0.85)));
else mesh.position.copy(place(r + 0.03));
root.add(mesh);
addPiece(part, mesh, {order:k/10, amp:0.06, pulse:0.06});
if (k === 4){ part.anchorObj = mesh; part.anchorLocal = V(0, 1.2, 0); }
}
for (let k = 0; k < 7; k++){
let a, b;
if (k < 4){
a = G.clone().add(gDir.clone().multiplyScalar(0.5)).add(randDir().multiplyScalar(0.15));
b = G.clone().normalize().add(randDir().multiplyScalar(0.7)).normalize().multiplyScalar(2.85);
} else {
a = N.clone().add(gDir.clone().multiplyScalar(1.15)).add(randDir().multiplyScalar(0.2));
b = G.clone().sub(gDir.clone().multiplyScalar(0.25)).add(randDir().multiplyScalar(0.15));
}
const mid = a.clone().lerp(b, 0.5).add(randDir().multiplyScalar(0.3)); if (mid.length() > 2.7) mid.setLength(2.7);
const path = new THREE.CatmullRomCurve3([a, mid, b]);
const mesh = new THREE.Mesh(geo, m); mesh.scale.setScalar(rr(0.055, 0.075)); mesh.position.copy(a);
root.add(mesh);
addPiece(part, mesh, {order:0.5 + rand()*0.5, amp:0, pulse:0.05, path, period:rr(5, 8)});
}
}
/* ---------- 9 centrioles ---------- */
{
const part = parts[9];
const grp = new THREE.Group(); grp.position.copy(C); grp.quaternion.setFromUnitVectors(V(0,1,0), randDir()); root.add(grp);
const m = regMat(part, stdMat(0xf7a8ff, {emi:0.35, rough:0.4}));
const tube = new THREE.CylinderGeometry(0.021, 0.021, 0.34, 8);
function centriole(){
const g = new THREE.Group();
for (let j = 0; j < 9; j++){
const a = j*Math.PI*2/9;
for (let t = 0; t < 3; t++){
const rad = 0.095 + t*0.03, aa = a + t*0.2;
const c = new THREE.Mesh(tube, m); c.position.set(Math.cos(aa)*rad, 0, Math.sin(aa)*rad); g.add(c);
}
}
return g;
}
const c1 = centriole(), c2 = centriole();
c2.rotation.x = Math.PI/2; c2.position.set(0, 0.24, 0.2);
grp.add(c1, c2);
addPiece(part, c1, {order:0, amp:0.01, pulse:0.02, rot:0.08});
addPiece(part, c2, {order:0.5, amp:0.01, pulse:0.02, rot:0.08});
const haze = new THREE.Mesh(new THREE.SphereGeometry(0.42, 24, 16), regMat(part, stdMat(0xf7a8ff, {opacity:0.1, emi:0.7, depthWrite:false})));
haze.position.set(0, 0.12, 0.08); grp.add(haze);
addPiece(part, haze, {order:0.3, amp:0.01, pulse:0.08});
part.anchorObj = grp; part.anchorLocal = V(0, 0.45, 0);
}
/* ---------- 10 cytoskeleton ---------- */
{
const part = parts[10];
const mtM = regMat(part, stdMat(0xe4f1ff, {opacity:0.6, emi:0.55, depthWrite:false}));
const afM = regMat(part, stdMat(0xff8fc7, {opacity:0.55, emi:0.55, depthWrite:false}));
const toN = N.clone().sub(C).normalize();
let made = 0, firstPt = null;
for (let k = 0; k < 400 && made < 20; k++){
const end = randDir().multiplyScalar(2.85);
const d = end.clone().sub(C).normalize(); if (d.dot(toN) > 0.3) continue;
const mid = C.clone().lerp(end, 0.5).add(randDir().multiplyScalar(0.4));
if (mid.distanceTo(N) < 1.4) mid.copy(N).add(mid.clone().sub(N).setLength(1.4));
if (mid.length() > 2.75) mid.setLength(2.75);
const curve = new THREE.CatmullRomCurve3([C.clone(), mid, end]);
if (!firstPt) firstPt = curve.getPoint(0.65);
const g = new THREE.TubeGeometry(curve, 48, 0.014, 5, false);
const mesh = new THREE.Mesh(g, mtM); root.add(mesh);
addPiece(part, mesh, {grow:g.index.count, order:made/20*0.6, amp:0, pulse:0});
made++;
}
for (let k = 0; k < 26; k++){
const d0 = randDir(); const axis = V(0,0,0).crossVectors(d0, randDir()).normalize();
const len = rr(0.5, 1.1), rad = rr(2.5, 2.85), pts = [];
for (let j = 0; j < 6; j++) pts.push(d0.clone().applyAxisAngle(axis, len*j/5).multiplyScalar(rad + Math.sin(j*1.3 + k)*0.06));
const g = new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 40, 0.009, 4, false);
const mesh = new THREE.Mesh(g, afM); root.add(mesh);
addPiece(part, mesh, {grow:g.index.count, order:0.3 + rand()*0.7, amp:0, pulse:0});
}
part.anchorLocal = firstPt;
}
/* ---------- labels ---------- */
const labelsEl = $('labels');
let labelsOn = true;
parts.forEach(p => {
const b = document.createElement('button');
b.className = 'lab'; b.innerHTML = `<i style="background:${p.color};color:${p.color}"></i>${p.name}`;
b.addEventListener('click', ev => { ev.stopPropagation(); selectPart(p.idx); });
labelsEl.appendChild(b); p.labEl = b;
});
/* ---------- state ---------- */
let demo = location.hash === '#demo';
const RATE_NORMAL = 1/1.7, RATE_DEMO = 1/0.85;
let buildRate = demo ? RATE_DEMO : RATE_NORMAL;
let progress = -1, playing = true, selected = null, fly = null, completedOnce = false;
let T = 0;
/* layout: keep the cell centered in the free area above the panel */
let viewS = 0, viewSTarget = 0;
function measure(){
const h = innerHeight, panelH = $('panel').offsetHeight, topH = $('top').offsetHeight + 16;
viewSTarget = (panelH - topH) / 2;
return {w:innerWidth, h, panelH, topH};
}
function homeDist(){
const {w, h, panelH, topH} = measure();
const fullH = h + 2*Math.max(0, viewSTarget);
const f = (fullH/2) / Math.tan(THREE.MathUtils.degToRad(camera.fov/2));
const availH = Math.max(110, (h - panelH - topH)/2 - 6), availW = Math.max(110, w/2 - 10);
return 3.3 * f / Math.min(availH, availW) * 1.05;
}
function applyView(){
const w = innerWidth, h = innerHeight, s = Math.max(0, viewS);
camera.aspect = w / (h + 2*s);
camera.setViewOffset(w, h + 2*s, 0, 2*s, w, h);
camera.updateProjectionMatrix();
}
function onResize(){ renderer.setSize(innerWidth, innerHeight, false); measure(); }
addEventListener('resize', onResize);
onResize(); viewS = viewSTarget; applyView();
camera.position.setLength(homeDist());
try { new ResizeObserver(() => measure()).observe($('panel')); } catch(e){}
/* ---------- camera flights ---------- */
function flyTo(target, dist, dir){
dir = (dir || camera.position.clone().sub(controls.target)).clone().normalize();
fly = {t:0, dur:1.3, p0:camera.position.clone(), t0:controls.target.clone(), t1:target.clone(), p1:target.clone().add(dir.multiplyScalar(dist))};
}
function goHome(){
selected = null;
const dir = camera.position.clone().sub(controls.target); if (dir.lengthSq() < 1e-6) dir.set(0.2, 0.25, 1);
flyTo(V(0,0,0), homeDist(), dir);
controls.autoRotate = true;
}
controls.addEventListener('start', () => { fly = null; controls.autoRotate = false; });
function anchorWorld(p, out){ return p.anchorObj.localToWorld(out.copy(p.anchorLocal)); }
function selectPart(idx, point){
const p = parts[idx];
if (p.appear < 0.5) return;
selected = idx;
const tgt = point ? point.clone() : anchorWorld(p, V(0,0,0));
flyTo(tgt, p.focus, cutOn ? cutDir.clone() : null);
controls.autoRotate = false;
}
function selectVisiblePiece(idx){
const p = parts[idx];
for (const pc of p.pieces){ const w = pc.obj.getWorldPosition(V(0,0,0)); if (cutDir.dot(w) < clipC - 0.2){ selectPart(idx, w); return; } }
selectPart(idx);
}
/* ---------- cut / rebuild / labels ---------- */
const cutBtn = $('cut');
function setCut(on){
cutOn = on;
if (on){
if (clipC > 3.2){ cutDir.copy(camera.position); if (cutDir.lengthSq() < 1e-4) cutDir.set(0,0,1); cutDir.normalize(); clipC = Math.min(clipC, 4); }
clipTarget = 0;
} else clipTarget = 6;
cutBtn.setAttribute('aria-checked', on ? 'true' : 'false');
}
cutBtn.addEventListener('click', () => setCut(!cutOn));
function rebuild(){
progress = -1; playing = true; selected = null; completedOnce = false;
goHome();
}
$('rebuild').addEventListener('click', rebuild);
$('home').addEventListener('click', goHome);
$('labelsBtn').addEventListener('click', () => { labelsOn = !labelsOn; $('labelsBtn').textContent = 'Labels: ' + (labelsOn ? 'on' : 'off'); });
const scrub = $('scrub');
scrub.addEventListener('input', () => {
progress = clamp(parseFloat(scrub.value), 0, NP); playing = false;
if (selected != null && progress < selected + 0.6) selected = null;
});
/* ---------- tapping parts ---------- */
const raycaster = new THREE.Raycaster();
const pointers = new Set(); let down = null, multi = false;
const cv = renderer.domElement;
cv.addEventListener('pointerdown', e => {
pointers.add(e.pointerId);
if (pointers.size > 1) multi = true;
if (pointers.size === 1){ multi = false; down = {x:e.clientX, y:e.clientY, t:performance.now()}; }
});
function endPointer(e, isUp){
pointers.delete(e.pointerId);
if (isUp && down && !multi && pointers.size === 0){
const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y);
if (moved < 10 && performance.now() - down.t < 650) pick(e.clientX, e.clientY);
}
if (pointers.size === 0) down = null;
}
cv.addEventListener('pointerup', e => endPointer(e, true));
cv.addEventListener('pointercancel', e => endPointer(e, false));
const _m4 = new THREE.Matrix4();
function pick(x, y){
const rect = cv.getBoundingClientRect();
const ndc = new THREE.Vector2(((x - rect.left)/rect.width)*2 - 1, -((y - rect.top)/rect.height)*2 + 1);
raycaster.setFromCamera(ndc, camera);
const objs = [];
parts.forEach(p => { if (p.appear > 0.6) p.pieces.forEach(pc => objs.push(pc.obj)); });
const hits = raycaster.intersectObjects(objs, true).filter(h => {
if (h.object.userData.part == null) return false;
if (cutDir.dot(h.point) > clipC + 0.01) return false;
return parts[h.object.userData.part].appear > 0.6;
});
if (!hits.length) return;
let h = hits[0];
if (h.object.userData.part === 0){ const inner = hits.find(x => x.object.userData.part === 1); if (inner) h = inner; }
const idx = h.object.userData.part;
let point;
if (h.object.isInstancedMesh && h.instanceId != null){
h.object.getMatrixAt(h.instanceId, _m4); point = V(0,0,0).setFromMatrixPosition(_m4); h.object.localToWorld(point);
} else {
const g = h.object.geometry; if (!g.boundingSphere) g.computeBoundingSphere();
const ws = g.boundingSphere.radius * h.object.matrixWorld.getMaxScaleOnAxis();
point = ws < 0.6 ? g.boundingSphere.center.clone().applyMatrix4(h.object.matrixWorld) : h.point.clone();
}
if (idx === 0) point = parts[0].pieces[0].obj.getWorldPosition(V(0,0,0));
selectPart(idx, point);
}
/* ---------- demo mode ---------- */
let demoT = 0, demoStep = 0;
const DEMO = [
[0, () => { setCut(false); rebuild(); }],
[10.8, () => setCut(true)],
[12.6, () => selectPart(0)],
[15.2, () => selectVisiblePiece(6)],
[17.8, () => { setCut(false); goHome(); }]
];
const DEMO_LEN = 21;
function demoTick(dt){
demoT += dt;
while (demoStep < DEMO.length && demoT >= DEMO[demoStep][0]){ DEMO[demoStep][1](); demoStep++; }
if (demoT >= DEMO_LEN){ demoT = 0; demoStep = 0; }
}
function startDemo(){ demo = true; demoT = 0; demoStep = 0; buildRate = RATE_DEMO; $('demoBadge').hidden = false; }
function endDemo(){ if (!demo) return; demo = false; buildRate = RATE_NORMAL; $('demoBadge').hidden = true; }
if (demo) startDemo();
addEventListener('pointerdown', e => { if (e.isTrusted) endDemo(); }, true);
addEventListener('touchstart', e => { if (e.isTrusted) endDemo(); }, {capture:true, passive:true});
addEventListener('wheel', e => { if (e.isTrusted) endDemo(); }, {capture:true, passive:true});
addEventListener('hashchange', () => { if (location.hash === '#demo') startDemo(); });
/* ---------- card ---------- */
const card = $('card');
let cardKey = '', chipKey = '';
function setCard(tag, name, color, line, more){
$('cardTag').textContent = tag; $('cardName').textContent = name;
$('cardDot').style.background = color; $('cardDot').style.color = color;
$('cardLine').textContent = line;
const mEl = $('cardMore'); if (more){ mEl.innerHTML = '<b>What it does:</b> ' + more; mEl.style.display = 'block'; } else mEl.style.display = 'none';
card.classList.remove('pop'); void card.offsetWidth; card.classList.add('pop');
}
function updateCard(){
let key;
if (selected != null) key = 's' + selected;
else if (progress < 0) key = 'm';
else if (progress >= NP) key = 'd';
else key = 'p' + Math.floor(progress);
if (key !== cardKey){
cardKey = key;
if (key === 'm') setCard('Step 0 · the empty cell', MEMBRANE.name, MEMBRANE.color, MEMBRANE.line);
else if (key === 'd') setCard('All 11 parts added', 'Your cell is complete!', '#ffe066', 'Drag to spin it, pinch to zoom, and tap any part to fly to it and see what it does.');
else if (key[0] === 'p'){ const p = parts[+key.slice(1)]; setCard(`Adding part ${p.idx+1} of ${NP}`, p.name, p.color, p.line); }
else { const p = parts[selected]; setCard(`Part ${p.idx+1} of ${NP} · tap "Whole cell" to zoom out`, p.name, p.color, p.line, p.more); }
}
const ck = progress >= NP ? 'done' : progress < 0 ? 'start' : String(Math.floor(progress) + 1) + (playing ? '' : 'p');
if (ck !== chipKey){
chipKey = ck;
$('chip').textContent = progress >= NP ? 'Complete ✓' : progress < 0 ? 'Empty cell' : `Part ${Math.floor(progress)+1} / ${NP}` + (playing ? '' : ' · paused');
}
}
function onComplete(){
if (completedOnce) return; completedOnce = true;
if (!demo){ const h = $('hint'); h.classList.add('show'); setTimeout(() => h.classList.remove('show'), 4500); }
}
/* ---------- animation ---------- */
const _v = V(0,0,0), _q = new THREE.Quaternion(), _e = new THREE.Euler(), _s = V(1,1,1), _q0 = new THREE.Quaternion(), _mm = new THREE.Matrix4();
function updatePieces(){
for (const p of parts){
const local = clamp(progress - p.idx, 0, 1);
p.appear = local;
const a = smooth(clamp(local*1.6, 0, 1));
const building = local > 0 && local < 1 && playing;
let hl = 0;
if (selected === p.idx) hl = 0.35 + 0.3*Math.sin(T*4);
if (building) hl += (1 - local)*0.8;
for (const mt of p.mats){
const m = mt.m;
m.opacity = mt.base * a;
const wantT = mt.baseT || a < 0.999;
if (m.transparent !== wantT){ m.transparent = wantT; m.needsUpdate = true; }
m.emissiveIntensity = mt.emi + hl;
m.visible = a > 0.001;
}
for (const pc of p.pieces){
const t = clamp((local - pc.order*0.45) / 0.55, 0, 1);
const o = pc.obj;
if (pc.inst){
if (pc.last !== local){
pc.last = local; const L = pc.inst, n = L.length;
for (let i = 0; i < n; i++){
const ti = clamp((local - (i/n)*0.6) / 0.4, 0, 1), s = easeOutBack(ti);
_mm.compose(L[i], _q0, _s.set(s, s, s)); o.setMatrixAt(i, _mm);
}
o.instanceMatrix.needsUpdate = true; o.boundingSphere = null;
}
o.visible = local > 0;
if (pc.amp){ o.position.set(pc.pos.x + Math.sin(T*pc.sp + pc.ph)*pc.amp, pc.pos.y + Math.sin(T*pc.sp*1.3 + pc.ph*2)*pc.amp, pc.pos.z + Math.sin(T*pc.sp*0.8 + pc.ph*3)*pc.amp); }
continue;
}
if (pc.grow){
const n = Math.floor(pc.grow * (1 - Math.pow(1 - t, 2)) / 3) * 3;
o.geometry.setDrawRange(0, n); o.visible = n > 0;
continue;
}
let s = easeOutBack(t);
if (pc.path){
const f = ((T / pc.period) + pc.ph) % 1;
pc.path.getPoint(f, o.position);
s *= Math.min(1, Math.sin(f*Math.PI)*4);
} else {
o.position.set(pc.pos.x + Math.sin(T*pc.sp + pc.ph)*pc.amp, pc.pos.y + Math.sin(T*pc.sp*1.3 + pc.ph*2)*pc.amp, pc.pos.z + Math.sin(T*pc.sp*0.8 + pc.ph*3)*pc.amp);
}
const pulse = 1 + pc.pulse*Math.sin(T*1.6 + pc.ph);
o.scale.copy(pc.scl).multiplyScalar(Math.max(0, s*pulse));
o.visible = s > 0.002;
if (pc.rot){
o.quaternion.copy(pc.quat);
_e.set(Math.sin(T*0.5 + pc.ph)*pc.rot, Math.sin(T*0.4 + pc.ph*2)*pc.rot, Math.sin(T*0.3 + pc.ph)*pc.rot*0.5);
o.quaternion.multiply(_q.setFromEuler(_e));
}
}
}
}
function updateMembrane(){
const pa = memGeo.attributes.position, arr = pa.array;
for (let i = 0; i < arr.length; i += 3){
const x = memBase[i], y = memBase[i+1], z = memBase[i+2];
const w = 0.022*Math.sin(x*0.6 + T*0.9)*Math.sin(y*0.5 + T*0.7 + 1) + 0.014*Math.sin(z*0.8 + T*1.1 + 2) + 0.008*Math.sin((x+y)*1.4 + T*1.7);
const f = 1 + w;
arr[i] = x*f; arr[i+1] = y*f; arr[i+2] = z*f;
}
pa.needsUpdate = true;
memGeo.computeVertexNormals();
memGeo.boundingSphere = null;
const intro = Math.min(1, T/1.2);
const br = 1 + 0.12*Math.sin(T*1.3);
memFrontM.opacity = 0.13*intro*br; memBackM.opacity = 0.12*intro*br;
fresM.uniforms.uOpacity.value = 0.95*intro;
}
function updateCyto(){
const arr = cytoGeo.attributes.position.array;
for (let i = 0; i < arr.length; i += 3){
arr[i] = cytoBase[i] + Math.sin(T*0.5 + i)*0.05;
arr[i+1] = cytoBase[i+1] + Math.sin(T*0.43 + i*1.7)*0.05;
arr[i+2] = cytoBase[i+2] + Math.sin(T*0.37 + i*2.3)*0.05;
}
cytoGeo.attributes.position.needsUpdate = true;
cytoM.opacity = 0.45 * clamp(progress/NP, 0, 1) + 0.05*Math.min(1, T);
}
const _lv = V(0,0,0);
function updateLabels(){
const w = innerWidth, h = innerHeight;
const cur = playing && progress >= 0 && progress < NP ? Math.floor(progress) : -1;
for (const p of parts){
const el = p.labEl;
let show = (labelsOn || p.idx === cur || p.idx === selected) && p.appear > 0.7;
if (show){
anchorWorld(p, _lv);
if (cutDir.dot(_lv) > clipC + 0.02) show = false;
else {
_lv.project(camera);
if (_lv.z > 1 || _lv.z < -1 || Math.abs(_lv.x) > 1.1 || Math.abs(_lv.y) > 1.1) show = false;
else {
const x = (_lv.x + 1)/2*w, y = (1 - _lv.y)/2*h;
el.style.transform = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px) translate(-50%,-120%)`;
}
}
}
el.style.display = show ? 'flex' : 'none';
el.classList.toggle('now', p.idx === cur);
el.classList.toggle('sel', p.idx === selected);
}
}
let last = performance.now();
function frame(now){
const dt = Math.min(0.05, (now - last)/1000); last = now; T += dt;
if (demo) demoTick(dt);
if (playing){
progress += dt*buildRate;
if (progress >= NP){ progress = NP; playing = false; onComplete(); }
scrub.value = Math.max(0, progress);
}
updatePieces(); updateMembrane(); updateCyto();
clipC += (clipTarget - clipC) * (1 - Math.exp(-dt*2.4));
clipPlane.normal.copy(cutDir).negate(); clipPlane.constant = clipC;
const ringR = clipC < R ? Math.sqrt(R*R - clipC*clipC) * 1.01 : 0;
cutRing.visible = ringR > 0.01 && clipC < 5;
if (cutRing.visible){
cutRing.scale.setScalar(ringR); cutRing.position.copy(cutDir).multiplyScalar(clipC);
cutRing.quaternion.setFromUnitVectors(V(0,0,1), cutDir);
cutRing.material.opacity = 0.75 * clamp(1 - clipC/R, 0, 1) + 0.15;
}
viewS += (viewSTarget - viewS) * (1 - Math.exp(-dt*6)); applyView();
if (fly){
fly.t += dt; const k = easeInOut(Math.min(1, fly.t/fly.dur));
controls.target.lerpVectors(fly.t0, fly.t1, k);
camera.position.lerpVectors(fly.p0, fly.p1, k);
if (fly.t >= fly.dur) fly = null;
}
controls.update();
updateLabels(); updateCard();
renderer.render(scene, camera);
requestAnimationFrame(frame);
}
updateCard();
requestAnimationFrame(frame);
</script>
</body>
</html>
