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 Living Cell</title>
<style>
:root{--glass:rgba(12,20,46,.74);--line:rgba(160,200,255,.24);--ink:#eef5ff;--muted:#a9b8d8;--accent:#ffd84d}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;color:var(--ink);font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
body{background:#060a1c radial-gradient(ellipse at 50% 42%,#1d2d62 0%,#0b1331 55%,#04071a 100%)}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
#labels{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.lab{position:absolute;left:0;top:0;display:flex;align-items:center;gap:6px;padding:6px 11px;border-radius:999px;background:rgba(8,14,38,.8);border:1px solid var(--line);font-size:13px;font-weight:700;white-space:nowrap;cursor:pointer;opacity:0;pointer-events:none;transition:opacity .35s}
.lab i{width:10px;height:10px;border-radius:50%;flex:none}
.lab::after{content:"";position:absolute;left:50%;bottom:-7px;width:2px;height:7px;margin-left:-1px;background:rgba(200,225,255,.6)}
#card{position:fixed;left:0;right:0;margin:0 auto;top:max(12px,env(safe-area-inset-top));width:min(560px,calc(100% - 24px));padding:13px 16px 14px;border-radius:18px;background:var(--glass);border:1px solid var(--line);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);box-shadow:0 10px 40px rgba(0,0,0,.35)}
#step{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--accent);font-weight:800}
#card h1{margin:4px 0;font-size:22px;display:flex;align-items:center;gap:10px;line-height:1.15}
#dot{width:15px;height:15px;border-radius:50%;flex:none;box-shadow:0 0 14px currentColor}
#text{margin:0;font-size:16px;line-height:1.42;color:#d9e5ff}
#back{margin-top:11px;display:none;width:100%}
.pop{animation:pop .45s ease}
@keyframes pop{from{opacity:.2;transform:translateY(6px)}to{opacity:1;transform:none}}
#panel{position:fixed;left:0;right:0;margin:0 auto;bottom:max(12px,env(safe-area-inset-bottom));width:min(560px,calc(100% - 24px));padding:10px 14px 14px;border-radius:20px;background:var(--glass);border:1px solid var(--line);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);display:flex;flex-direction:column;gap:8px;box-shadow:0 10px 40px rgba(0,0,0,.35)}
#hint{font-size:13px;color:var(--muted);text-align:center;min-height:18px}
.row{display:flex;align-items:center;gap:10px}
.sm{font-size:13px;font-weight:700;color:var(--muted);min-width:34px;text-align:center}
.btn{flex:1;min-height:52px;padding:0 10px;border-radius:14px;border:1px solid var(--line);background:rgba(255,255,255,.08);color:var(--ink);font-family:inherit;font-size:16px;font-weight:700;cursor:pointer;touch-action:manipulation;white-space:nowrap}
.btn:active{transform:scale(.97);background:rgba(255,255,255,.18)}
.sw{flex:1.45;display:flex;align-items:center;justify-content:center;gap:9px}
.knob{width:44px;height:26px;border-radius:13px;background:rgba(255,255,255,.22);position:relative;transition:background .25s;flex:none}
.knob::after{content:"";position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:#fff;transition:left .25s}
.sw[aria-checked=true]{border-color:#ff7d9b}
.sw[aria-checked=true] .knob{background:#ff5f86}
.sw[aria-checked=true] .knob::after{left:21px}
input[type=range]{flex:1;-webkit-appearance:none;appearance:none;height:44px;margin:0;background:transparent;touch-action:none}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:5px;background:linear-gradient(90deg,var(--accent) 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 var(--accent);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:var(--accent)}
input[type=range]::-moz-range-thumb{width:22px;height:22px;border-radius:50%;background:#fff;border:5px solid var(--accent)}
@media (max-width:420px){#card h1{font-size:19px}#text{font-size:15px}.btn{font-size:15px;padding:0 6px}.lab{font-size:12px;padding:5px 9px}.knob{width:38px}.sw[aria-checked=true] .knob::after{left:15px}}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="labels"></div>
<div id="card" aria-live="polite"><div id="step">Loading</div><h1><i id="dot"></i><span id="name">Animal cell</span></h1><p id="text">Getting the microscope ready…</p><button id="back" class="btn">← Back to the whole cell</button></div>
<div id="panel">
<div id="hint"></div>
<div class="row"><span class="sm">Build</span><input id="slider" type="range" min="0" max="1100" step="1" value="0" aria-label="Scrub through the build"><span id="count" class="sm">0/11</span></div>
<div class="row"><button id="rebuild" class="btn">⟳ Rebuild</button><button id="play" class="btn">❚❚ Pause</button><button id="cut" class="btn sw" role="switch" aria-checked="false"><span class="knob"></span>Cut open</button></div>
</div>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"}}</script>
<script type="module">
import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
const $=id=>document.getElementById(id);
const V=(x=0,y=0,z=0)=>new THREE.Vector3(x,y,z);
const clamp=(x,a,b)=>x<a?a:x>b?b:x;
const smooth=x=>x*x*(3-2*x);
const inOut=x=>x<.5?4*x*x*x:1-Math.pow(-2*x+2,3)/2;
const backOut=x=>x<=0?0:x>=1?1:1+2.70158*Math.pow(x-1,3)+1.70158*Math.pow(x-1,2);
let seed=20271;
const rnd=()=>{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)*rnd();
const rdir=()=>{const u=rr(-1,1),a=rr(0,6.2832),s=Math.sqrt(1-u*u);return V(s*Math.cos(a),u,s*Math.sin(a))};
const m4=new THREE.Matrix4(),tmp=V(),Y=V(0,1,0),Z=V(0,0,1),ONE=V(1,1,1);
/* ---------- words for a curious 12-year-old ---------- */
const INFO=[
['Nucleus','Nucleus','#9b7bff',"The control center: it keeps the cell's DNA, its instruction book.","The nucleus stores DNA, the instructions for building and running the whole cell. It decides which instructions get used, and tiny pores in its double wall let messages in and out."],
['Nucleolus','Nucleolus','#ff5fa8',"A dense spot inside the nucleus that builds ribosomes.","The nucleolus is a little factory inside the nucleus. It puts together the pieces of ribosomes, then sends them out through the nuclear pores so they can start making proteins."],
['Rough endoplasmic reticulum','Rough ER','#4aa8ff',"Folded sheets dotted with ribosomes that make proteins to ship out.","The rough ER is a maze of flat, folded sheets wrapped around the nucleus. Ribosomes stuck all over it make it look bumpy. Proteins built here get folded into shape and packed up for delivery."],
['Smooth endoplasmic reticulum','Smooth ER','#3fe0b0',"Tubes with no ribosomes that make fats and clean up poisons.","The smooth ER is a tangle of tubes with no ribosomes on them. It makes fats (lipids) for new membranes, stores calcium, and helps break down harmful chemicals."],
['Ribosomes','Ribosomes','#7d8bff',"Tiny machines that read instructions and build proteins.","Ribosomes are so small that millions fit in one cell. Each one reads a message copied from the DNA and snaps building blocks called amino acids together, one by one, to make a protein."],
['Golgi apparatus','Golgi','#ffa94d',"The post office: it finishes, packs and ships proteins.","The Golgi apparatus is a stack of flat pouches. Proteins arrive from the ER, get finished and tagged with an address, then leave inside little bubbles called vesicles."],
['Mitochondria','Mitochondria','#ff7a59',"Power plants that turn food into energy the cell can use.","Mitochondria use oxygen to burn sugar and make ATP, tiny packets of energy that power almost everything the cell does. Their folded inner walls give them extra room to work."],
['Lysosomes','Lysosomes','#a6e34a',"Clean-up crews filled with juices that digest waste.","Lysosomes are little sacs full of digestive enzymes. They break down worn-out parts, food and invading germs so the pieces can be recycled."],
['Vesicles','Vesicles','#ff9bd8',"Tiny bubbles that carry cargo around the cell.","Vesicles are the cell's delivery trucks. These bubbles carry proteins from the ER to the Golgi and from the Golgi to the membrane, where they can pop open and send things outside."],
['Centrioles','Centrioles','#ffd84d',"Two tiny barrels that help the cell split in two.","Centrioles come as a pair set at right angles, each made of nine bundles of tiny tubes. When the cell divides, they organize the fibers that pull the copied DNA apart."],
['Cytoskeleton','Cytoskeleton','#9ff3ff',"A web of fibers that gives the cell its shape and roads to travel on.","The cytoskeleton is made of protein fibers that work like bones, muscles and highways all at once. They hold the cell's shape, help it move, and act as tracks for moving cargo."]
];
const MEMP={i:-1,name:'Cell membrane',label:'Membrane',color:'#8fdcff',items:[],
short:"Every cell starts with a membrane: a thin, see-through skin that controls what goes in and out.",
more:"The cell membrane is a thin, oily skin that wraps the whole cell. It lets food and water in, keeps harmful things out, and is dotted with proteins that work like doors."};
/* ---------- renderer, camera, lights ---------- */
let renderer;
try{renderer=new THREE.WebGLRenderer({canvas:$('c'),antialias:true,alpha:true})}
catch(e){$('step').textContent='Oops';$('text').textContent='This device could not start 3D graphics (WebGL).';throw e}
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
renderer.localClippingEnabled=true;
renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.15;
const scene=new THREE.Scene();
const camera=new THREE.PerspectiveCamera(45,1,.05,150);
const controls=new OrbitControls(camera,renderer.domElement);
Object.assign(controls,{enableDamping:true,dampingFactor:.08,minDistance:.5,maxDistance:45,rotateSpeed:.8,autoRotate:true,autoRotateSpeed:.8});
scene.add(new THREE.HemisphereLight(0xd6ecff,0x2b1a4a,1.25));
const L1=new THREE.DirectionalLight(0xffffff,2.2);L1.position.set(5,7,8);scene.add(L1);
const L2=new THREE.DirectionalLight(0x8fb0ff,1);L2.position.set(-6,-3,-6);scene.add(L2);
const cutPlane=new THREE.Plane(V(0,0,-1),50),CLIP=[cutPlane],cutDir=V(0,0,1);
let cutOn=false,cutAmt=0;
/* ---------- membrane, membrane proteins, cytoplasm ---------- */
const MR=3;
const wob=(x,y,z,t)=>1+.022*Math.sin(x*3.1+t*.9)*Math.sin(y*2.7+t*.7)+.014*Math.sin(z*4.3-t*1.1)+.008*Math.sin(t*1.3);
const memGeo=new THREE.SphereGeometry(MR,80,56),memBase=memGeo.attributes.position.array.slice();
memGeo.boundingSphere=new THREE.Sphere(V(),MR*1.2);
const memMat=new THREE.MeshPhysicalMaterial({color:0x8fdcff,emissive:0x2f6fc0,emissiveIntensity:.18,roughness:.18,clearcoat:1,clearcoatRoughness:.25,transparent:true,opacity:0,depthWrite:false,side:THREE.DoubleSide,clippingPlanes:CLIP});
const membrane=new THREE.Mesh(memGeo,memMat);membrane.userData={part:-1,shell:true};scene.add(membrane);
MEMP.group=membrane;MEMP.focus=membrane;
const pick=[membrane];
const PN=120,prot=new THREE.InstancedMesh(new THREE.CapsuleGeometry(.045,.09,3,8),new THREE.MeshStandardMaterial({color:0x7fe3ff,emissive:0x2a8fd0,emissiveIntensity:.35,roughness:.4,clippingPlanes:CLIP}),PN);
const protD=[],protQ=[];for(let k=0;k<PN;k++){const d=rdir();protD.push(d);protQ.push(new THREE.Quaternion().setFromUnitVectors(Y,d))}
scene.add(prot);
const CN=700,cArr=new Float32Array(CN*3);
for(let k=0;k<CN;k++){const v=rdir().multiplyScalar(Math.cbrt(rnd())*2.85);cArr[k*3]=v.x;cArr[k*3+1]=v.y;cArr[k*3+2]=v.z}
const cGeo=new THREE.BufferGeometry();cGeo.setAttribute('position',new THREE.BufferAttribute(cArr,3));
const cyto=new THREE.Points(cGeo,new THREE.PointsMaterial({color:0xbfe8ff,size:.03,transparent:true,opacity:.5,depthWrite:false,clippingPlanes:CLIP}));scene.add(cyto);
const ring=new THREE.Mesh(new THREE.TorusGeometry(1,.012,8,180),new THREE.MeshBasicMaterial({color:0xaef0ff,transparent:true,opacity:0,depthWrite:false}));ring.visible=false;scene.add(ring);
/* ---------- part-building helpers ---------- */
const parts=[];let cur=null;
function M(color,o={}){const m=new THREE.MeshStandardMaterial(Object.assign({color,emissive:color,emissiveIntensity:.14,roughness:.42,metalness:0,side:THREE.DoubleSide,clippingPlanes:CLIP},o));if(m.opacity<1){m.transparent=true;m.depthWrite=false}m.userData.e0=m.emissiveIntensity;m.userData.o0=m.opacity;cur.mats.push(m);return m}
function part(i,pos){const [name,label,color,short,more]=INFO[i];const g=new THREE.Group();if(pos)g.position.copy(pos);scene.add(g);const anchor=new THREE.Object3D();g.add(anchor);
cur={i,name,label,color,short,more,group:g,anchor,focus:g,items:[],inst:[],mats:[],dist:2,amp:.035,ph:rnd()*6.28,a:0};parts.push(cur);return cur}
function reg(o){o.traverse(c=>{if(c.isMesh&&c.userData.part===undefined){c.userData.part=cur.i;pick.push(c)}})}
function item(o,bob=.03,pul=.04){cur.group.add(o);reg(o);Object.assign(o.userData,{p0:o.position.clone(),s0:o.scale.clone(),ph:rnd()*6.28,bob,pul});cur.items.push(o);return o}
function grow(o){item(o,0,0);o.userData.grow=o.geometry.index.count;return o}
function inst(geo,mat,list,delay,parent=cur.group){const im=new THREE.InstancedMesh(geo,mat,list.length);list.forEach((mt,k)=>im.setMatrixAt(k,mt));if(im.computeBoundingSphere)im.computeBoundingSphere();parent.add(im);reg(im);cur.inst.push([im,list.length,delay]);return im}
function tube(pts,seg,r,rs,mat){return new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts),seg,r,rs),mat)}
function bump(g,amt,f){const pa=g.attributes.position,v=V();for(let j=0;j<pa.count;j++){v.fromBufferAttribute(pa,j);v.multiplyScalar(1+amt*Math.sin(v.x*f)*Math.sin(v.y*f*1.1+1)*Math.sin(v.z*f*.9+2));pa.setXYZ(j,v.x,v.y,v.z)}g.computeVertexNormals();return g}
const at=(P,x,y,z)=>{const o=new THREE.Object3D();o.position.set(x,y,z);P.group.add(o);return o};
const N=V(.3,.15,-.1),G=V(-1.05,-1.35,1.0),S=V(1.6,-1.2,-.4),C=V(1.0,1.2,.85),R0=V(1.75,.45,1.45);
const occ=[[N,1.12],[G,.85],[S,.78],[C,.42],[R0,.35]];
for(const f of [-1,0,1])for(const th of [.6,1.1,1.6])occ.push([N.clone().add(V(-Math.cos(f)*Math.sin(th),Math.cos(th),Math.sin(f)*Math.sin(th)).multiplyScalar(1.58)),.5]);
function spot(rmax,cl){for(let n=0;n<600;n++){const v=rdir().multiplyScalar(rr(.5,rmax));if(occ.every(([c,r])=>v.distanceTo(c)>r+cl)){occ.push([v,cl]);return v}}return rdir().multiplyScalar(rmax)}
let P;
/* 0 nucleus */
P=part(0,N);P.dist=3.4;P.ph=1;P.anchor.position.set(0,1.1,0);
{const sh=new THREE.Mesh(new THREE.SphereGeometry(1,56,40),M(0x8a6cff,{opacity:.5,roughness:.3}));sh.userData.shell=true;item(sh,0,.012);
const ms=[];for(let k=0;k<90;k++){const d=rdir();ms.push(new THREE.Matrix4().compose(d,new THREE.Quaternion().setFromUnitVectors(Z,d),ONE))}
inst(new THREE.TorusGeometry(.05,.017,6,14),M(0xe2d6ff,{emissiveIntensity:.3}),ms,.5);
const cm=M(0xc77dff,{emissiveIntensity:.3});
for(let k=0;k<6;k++){const pts=[];const v=rdir().multiplyScalar(rr(.2,.6));for(let s=0;s<8;s++){pts.push(v.clone());v.add(rdir().multiplyScalar(.25));if(v.length()>.8)v.setLength(.65)}grow(tube(pts,70,.022,5,cm))}}
/* 1 nucleolus */
P=part(1,N.clone().add(V(.22,.2,.22)));P.dist=1.9;P.ph=1;P.anchor.position.set(0,.42,0);
{const m=new THREE.Mesh(bump(new THREE.IcosahedronGeometry(1,3),.1,6),M(0xff4f9a,{roughness:.6,emissiveIntensity:.25}));m.scale.setScalar(.34);item(m,0,.03)}
/* 2 rough ER */
P=part(2,N);P.dist=2.6;P.ph=1;P.point=true;P.anchor.position.set(-1.5,1.15,0);P.focus=P.anchor;
{const mat=M(0x4aa8ff,{roughness:.5}),dots=[],v=V(),d=V();
for(let k=0;k<4;k++){const r=1.25+k*.21,g=new THREE.SphereGeometry(r,60,30,-1.25,2.5,.4+k*.04,1.35-k*.04),pa=g.attributes.position;
for(let j=0;j<pa.count;j++){v.fromBufferAttribute(pa,j);d.copy(v).normalize();v.copy(d).multiplyScalar(r+.07*Math.sin(d.x*13+k)*Math.sin(d.y*11-k*2)+.04*Math.sin(d.z*17+k));pa.setXYZ(j,v.x,v.y,v.z);
if(rnd()<.09)dots.push(new THREE.Matrix4().makeTranslation(v.x+d.x*.035,v.y+d.y*.035,v.z+d.z*.035))}
g.computeVertexNormals();item(new THREE.Mesh(g,mat),0,.01)}
for(let k=dots.length-1;k>0;k--){const j=Math.floor(rnd()*(k+1));[dots[k],dots[j]]=[dots[j],dots[k]]}
inst(new THREE.IcosahedronGeometry(.03,0),M(0x3352e0,{emissiveIntensity:.35}),dots,.35)}
/* 3 smooth ER */
P=part(3,S);P.dist=2.1;P.point=true;P.anchor.position.set(0,.72,0);
{const mat=M(0x3fe0b0,{roughness:.35});for(let k=0;k<8;k++){const pts=[],v=rdir().multiplyScalar(rr(0,.35)),dir=rdir();for(let s=0;s<6;s++){pts.push(v.clone());dir.add(rdir().multiplyScalar(.9)).normalize();v.addScaledVector(dir,.26);if(v.length()>.65)v.multiplyScalar(.75)}grow(tube(pts,48,.05,8,mat))}}
/* 4 ribosomes */
P=part(4);P.dist=1;P.amp=.015;P.anchor.position.copy(R0).add(V(0,.32,0));P.focus=at(P,R0.x,R0.y,R0.z);
{const rb=[];for(let k=0;k<14;k++)rb.push(R0.clone().add(V(Math.cos(k*.5)*.2,k*.035-.24,Math.sin(k*.5)*.2)));
while(rb.length<260){const v=rdir().multiplyScalar(Math.cbrt(rnd())*2.75);if(v.distanceTo(N)>1.15&&v.length()>.4)rb.push(v)}
P.rib=rb;P.ribIm=inst(new THREE.IcosahedronGeometry(.042,1),M(0x7d8bff,{emissiveIntensity:.4}),rb.map(v=>new THREE.Matrix4().makeTranslation(v.x,v.y,v.z)),0)}
/* 5 Golgi apparatus */
P=part(5,G);P.dist=2;P.group.quaternion.setFromUnitVectors(Y,N.clone().sub(G).normalize());P.anchor.position.set(0,.55,0);
{const cols=[0xff8a3d,0xff9a44,0xffab4e,0xffbd58,0xffcf66];
for(let k=0;k<5;k++){const w=.72-k*.07,g=new THREE.SphereGeometry(1,40,12),pa=g.attributes.position;for(let j=0;j<pa.count;j++){const x=pa.getX(j)*w,z=pa.getZ(j)*w*.6;pa.setXYZ(j,x,pa.getY(j)*.05-.55*x*x-.3*z*z,z)}g.computeVertexNormals();const m=new THREE.Mesh(g,M(cols[k],{roughness:.38}));m.position.y=k*.15-.3;item(m,.012,.02)}
const vm=M(0xffc46b,{emissiveIntensity:.3}),vg=new THREE.SphereGeometry(.055,14,10);
for(let k=0;k<6;k++){const w=.72-(k%5)*.07,sg=k%2?1:-1,m=new THREE.Mesh(vg,vm);m.position.set(sg*(w+.07),(k%5)*.15-.3-.55*w*w,rr(-.15,.15));item(m,.03,.05)}}
/* 6 mitochondria */
P=part(6);P.dist=1.5;P.amp=.02;
{const om=M(0xff7a59,{opacity:.55,roughness:.3}),im=M(0xffd2a6,{emissiveIntensity:.25}),cg=new THREE.CapsuleGeometry(.17,.5,8,18),rg=new THREE.PlaneGeometry(.26,.62,1,60),pa=rg.attributes.position;
for(let j=0;j<pa.count;j++)pa.setZ(j,.075*Math.sin(pa.getY(j)*34));rg.computeVertexNormals();
for(let k=0;k<7;k++){const g=new THREE.Group(),o=new THREE.Mesh(cg,om);o.userData.shell=true;g.add(o,new THREE.Mesh(rg,im));g.position.copy(spot(2.25,.5));g.quaternion.setFromUnitVectors(Y,rdir());g.scale.setScalar(rr(.85,1.15));item(g,.05,.03);if(!k){P.focus=g;P.anchor.position.copy(g.position).add(V(0,.42,0))}}}
/* 7 lysosomes */
P=part(7);P.dist=1.1;P.amp=.02;
{const mat=M(0xa6e34a,{roughness:.55,emissiveIntensity:.22}),g=bump(new THREE.IcosahedronGeometry(1,3),.07,8);
for(let k=0;k<7;k++){const m=new THREE.Mesh(g,mat);m.position.copy(spot(2.5,.24));m.scale.setScalar(rr(.13,.2));item(m,.05,.05);if(!k){P.focus=m;P.anchor.position.copy(m.position).add(V(0,.3,0))}}}
/* 8 vesicles (they travel!) */
P=part(8);P.dist=1.2;P.amp=0;
{const mat=M(0xff9bd8,{opacity:.7,roughness:.2,emissiveIntensity:.3}),g=new THREE.SphereGeometry(1,20,14),out=G.clone().normalize(),erP=N.clone().add(G.clone().sub(N).normalize().multiplyScalar(1.35));
for(let k=0;k<16;k++){const m=new THREE.Mesh(g,mat);m.scale.setScalar(rr(.07,.11));item(m,0,.05);const toEr=k%4===0;
m.userData.trav={a:toEr?erP.clone().add(rdir().multiplyScalar(.25)):G.clone().add(rdir().multiplyScalar(.3)),b:toEr?G.clone().add(rdir().multiplyScalar(.2)):out.clone().add(rdir().multiplyScalar(.85)).normalize().multiplyScalar(2.8),sp:rr(.05,.1)*(toEr?1.6:1),ph:rnd()}}
P.anchor.position.copy(G).add(out.clone().multiplyScalar(.8));P.focus=P.anchor}
/* 9 centrioles */
P=part(9,C);P.dist=1.2;P.anchor.position.set(0,.38,0);
{const mat=M(0xffd84d,{emissiveIntensity:.3,roughness:.35}),cy=new THREE.CylinderGeometry(.015,.015,.4,6);
for(let b=0;b<2;b++){const g=new THREE.Group(),ms=[];for(let j=0;j<9;j++)for(let s=0;s<3;s++){const an=j/9*6.2832+s*.14,r=.1+s*.024;ms.push(new THREE.Matrix4().makeTranslation(Math.cos(an)*r,0,Math.sin(an)*r))}
inst(cy,mat,ms,0,g);if(b){g.rotation.z=Math.PI/2;g.position.set(.24,.18,0)}item(g,.01,.02)}}
/* 10 cytoskeleton */
P=part(10);P.dist=2.2;P.amp=.006;P.point=true;
{const mt=M(0x9ff3ff,{opacity:.65,emissiveIntensity:.5}),ac=M(0xff9fd0,{opacity:.6,emissiveIntensity:.4});
for(let k=0;k<26;k++){const end=rdir().multiplyScalar(2.9),pts=[];for(let s=0;s<=6;s++){const v=C.clone().lerp(end,s/6);if(s&&s<6)v.add(rdir().multiplyScalar(.12));if(v.distanceTo(N)<1.2)v.sub(N).setLength(1.2).add(N);pts.push(v)}grow(tube(pts,64,.016,5,mt));if(!k){P.anchor.position.copy(pts[4]);P.focus=P.anchor}}
for(let k=0;k<18;k++){const a=rdir(),b=a.clone().add(rdir().multiplyScalar(.7)).normalize(),pts=[];for(let s=0;s<=5;s++)pts.push(a.clone().lerp(b,s/5).normalize().multiplyScalar(2.78+.05*Math.sin(s*2+k)));grow(tube(pts,40,.011,4,ac))}}
parts.forEach(q=>{q.base=q.group.position.clone();q.group.visible=false});
/* ---------- floating labels ---------- */
const labWrap=$('labels');
parts.forEach(q=>{const d=document.createElement('div');d.className='lab';d.innerHTML='<i style="background:'+q.color+'"></i>'+q.label;d.addEventListener('click',()=>{if(p>=11)select(q,null)});labWrap.appendChild(d);q.el=d;q.lv=false});
/* ---------- state ---------- */
let p=0,playing=true,hold=1.6,SPT=2.3,doneT=0,sel=null,fly=null,scrub=null,autoSpin=true,msg='',msgT=0;
const ray=new THREE.Raycaster(),ndc=new THREE.Vector2();
const homeDist=()=>4.3/Math.tan(THREE.MathUtils.degToRad(camera.fov/2))/Math.min(1,camera.aspect)+.4;
function flyTo(target,dist,spin){const dir=camera.position.clone().sub(controls.target);if(dir.lengthSq()<1e-6)dir.set(0,.25,1);dir.normalize();
fly={t:0,dur:1.4,p0:camera.position.clone(),q0:controls.target.clone(),p1:target.clone().addScaledVector(dir,dist),q1:target.clone(),spin};controls.autoRotate=false}
function goHome(){sel=null;flyTo(V(),homeDist(),autoSpin)}
function select(P,hit){sel=P;const wp=V();
if(hit&&P.point)wp.copy(hit.point);
else if(hit&&P.i===4&&hit.instanceId!==undefined){hit.object.getMatrixAt(hit.instanceId,m4);wp.setFromMatrixPosition(m4).applyMatrix4(hit.object.matrixWorld)}
else if(hit&&P.i>=0){let o=hit.object;while(o.parent&&o.parent!==P.group)o=o.parent;(o.isInstancedMesh||o.parent!==P.group?P.focus:o).getWorldPosition(wp)}
else{P.focus.getWorldPosition(wp);
if(cutAmt>0&&wp.dot(cutDir)>-.05&&P.items.length>1){let best=null,bd=1e9;for(const o of P.items){o.getWorldPosition(tmp);const d=tmp.dot(cutDir);if(d<bd){bd=d;best=o}}best.getWorldPosition(wp)}}
flyTo(wp,P.i<0?homeDist()*.8:P.dist,false)}
function shown(o){for(;o;o=o.parent)if(!o.visible)return false;return true}
function choose(hits){let sh=null;for(const h of hits){if(h.object.userData.shell){if(sh&&sh.object===h.object)return sh;if(!sh||sh.object===membrane)sh=h;continue}return h}return sh}
function say(t){msg=t;msgT=3}
function tap(x,y){
if(p<11){say('Almost there! Let the cell finish building, or slide to the end.');return}
ndc.set(x/innerWidth*2-1,-(y/innerHeight)*2+1);ray.setFromCamera(ndc,camera);
const c=cutPlane.constant,hits=ray.intersectObjects(pick,false).filter(h=>shown(h.object)&&!(cutAmt>0&&h.point.dot(cutDir)>c+.02));
const h=choose(hits);if(!h){if(sel)goHome();return}
const i=h.object.userData.part;select(i<0?MEMP:parts[i],h)}
/* ---------- input ---------- */
const cv=renderer.domElement;let down=null,ptrs=0;
cv.addEventListener('pointerdown',e=>{ptrs++;down=ptrs>1?null:{x:e.clientX,y:e.clientY,t:performance.now()}});
const up=e=>{ptrs=Math.max(0,ptrs-1);if(down&&e.type==='pointerup'&&Math.hypot(e.clientX-down.x,e.clientY-down.y)<9&&performance.now()-down.t<600)tap(e.clientX,e.clientY);down=null};
cv.addEventListener('pointerup',up);cv.addEventListener('pointercancel',up);
controls.addEventListener('start',()=>{fly=null;autoSpin=false;controls.autoRotate=false});
function rebuild(){p=0;hold=1.2;playing=true;doneT=0;scrub=null;autoSpin=true;goHome()}
$('rebuild').addEventListener('click',rebuild);
$('play').addEventListener('click',()=>{if(p>=11){rebuild();return}playing=!playing;hold=0;scrub=null});
$('cut').addEventListener('click',()=>setCut(!cutOn));
$('back').addEventListener('click',goHome);
const slider=$('slider');
slider.addEventListener('input',()=>{p=slider.value/100;playing=false;hold=0;scrub=null;if(sel)goHome()});
function setCut(on){if(on&&cutAmt<=0){cutDir.copy(camera.position).normalize();if(cutDir.lengthSq()<.5)cutDir.set(0,0,1)}cutOn=on;$('cut').setAttribute('aria-checked',String(on))}
/* ---------- #demo: hands-free 20 s loop ---------- */
let demo=/#demo$/.test(location.href)?{t:0,i:0}:null;
const DEMO=[
[0,()=>{sel=null;setCut(false);p=0;hold=.4;playing=true;doneT=0;scrub=null;SPT=.75;autoSpin=true;goHome()}],
[9.3,()=>setCut(true)],
[10.9,()=>select(parts[6],null)],
[13.5,()=>select(parts[0],null)],
[16,()=>{goHome();setCut(false)}],
[17.2,()=>{scrub={a:p,b:5,t:0,d:1.8}}]];
function endDemo(){if(!demo)return;demo=null;SPT=2.3;scrub=null}
for(const ev of ['pointerdown','touchstart','wheel','keydown'])addEventListener(ev,e=>{if(e.isTrusted)endDemo()},{capture:true,passive:true});
/* ---------- UI text ---------- */
let cardKey='';const ui={};
function setText(id,v){if(ui[id]!==v){ui[id]=v;$(id).textContent=v}}
function setCard(key,step,name,color,text,back){if(key===cardKey)return;cardKey=key;$('step').textContent=step;$('name').textContent=name;const d=$('dot');d.style.background=color;d.style.color=color;$('text').textContent=text;$('back').style.display=back?'block':'none';const c=$('card');c.classList.remove('pop');void c.offsetWidth;c.classList.add('pop')}
function cardState(){
if(sel){setCard('s'+sel.i,sel.i<0?'The outer skin':'Part '+(sel.i+1)+' of 11 · what it does',sel.name,sel.color,sel.more,true);return}
if(p<=.001){setCard('m','Start · an empty cell',MEMP.name,MEMP.color,MEMP.short,false);return}
if(p>=11&&doneT>2.6){setCard('done','Complete · 11 of 11','Your cell is alive!','#ffd84d','Drag to spin it, pinch to zoom, and tap any part to fly in and see what it does.',false);return}
const i=Math.min(10,Math.ceil(p)-1),q=parts[i];setCard('b'+i,'Part '+(i+1)+' of 11',q.name,q.color,q.short,false)}
function hintState(){let h;
if(demo)h='Demo playing · touch anywhere to take over';else if(msgT>0)h=msg;
else if(sel)h='Drag to look around · tap another part';
else if(p>=11)h='Drag to spin · Pinch to zoom · Tap any part';
else h=playing?'Building… drag the slider to scrub through':'Paused · press Play or drag the slider';
setText('hint',h);
setText('play',p>=11?'▶ Replay':playing?'❚❚ Pause':'▶ Play');
setText('count',Math.floor(p+1e-6)+'/11')}
/* ---------- animation loop ---------- */
const clock=new THREE.Clock();let t=0;
function frame(){
requestAnimationFrame(frame);
const dt=Math.min(clock.getDelta(),.05);t+=dt;
if(demo){demo.t+=dt;while(demo.i<DEMO.length&&demo.t>=DEMO[demo.i][0])DEMO[demo.i++][1]();if(demo.t>=20){demo.t=0;demo.i=0}}
if(scrub){scrub.t+=dt;const k=inOut(Math.min(1,scrub.t/scrub.d));p=scrub.a+(scrub.b-scrub.a)*k;playing=false;if(k>=1)scrub=null}
else if(playing){if(hold>0)hold-=dt;else{p=Math.min(11,p+dt/SPT);if(p>=11)playing=false}}
doneT=p>=11?doneT+dt:0;if(msgT>0)msgT-=dt;
if(sel&&sel.i>=0&&p<sel.i+1)goHome();
/* membrane breathes */
memMat.opacity=.22*Math.min(1,t/1.2);
memMat.emissiveIntensity=.16+.05*Math.sin(t*1.2)+(sel===MEMP?.3+.2*Math.sin(t*5):0);
const ma=memGeo.attributes.position.array;
for(let k=0;k<ma.length;k+=3){const x=memBase[k],y=memBase[k+1],z=memBase[k+2],w=wob(x/MR,y/MR,z/MR,t);ma[k]=x*w;ma[k+1]=y*w;ma[k+2]=z*w}
memGeo.attributes.position.needsUpdate=true;
for(let k=0;k<PN;k++){const d=protD[k];m4.compose(tmp.copy(d).multiplyScalar(MR*wob(d.x,d.y,d.z,t)),protQ[k],ONE);prot.setMatrixAt(k,m4)}
prot.instanceMatrix.needsUpdate=true;
cyto.rotation.y=t*.025;cyto.rotation.x=Math.sin(t*.1)*.1;
/* parts appear, drift and pulse */
for(const q of parts){const a=clamp(p-q.i,0,1);q.a=a;q.group.visible=a>0;if(!a)continue;
const b=q.base,ph=q.ph,A=q.amp;q.group.position.set(b.x+Math.sin(t*.5+ph)*A,b.y+Math.sin(t*.63+ph*1.7)*A,b.z+Math.sin(t*.41+ph*2.3)*A);
const n=q.items.length;
for(let j=0;j<n;j++){const o=q.items[j],u=o.userData,l=clamp((a-.45*j/n)/.55,0,1);o.visible=l>0;if(!o.visible)continue;
if(u.grow){o.geometry.setDrawRange(0,Math.floor(u.grow*smooth(l)/3)*3);continue}
const s=Math.max(1e-3,backOut(l)*(1+u.pul*Math.sin(t*1.7+u.ph)));
if(u.trav){const v=u.trav,f=(t*v.sp+v.ph)%1;o.position.lerpVectors(v.a,v.b,f);o.position.y+=Math.sin(f*Math.PI)*.15;o.scale.copy(u.s0).multiplyScalar(Math.max(1e-3,s*Math.pow(Math.sin(f*Math.PI),.5)));continue}
o.scale.copy(u.s0).multiplyScalar(s);
if(u.bob)o.position.set(u.p0.x+Math.sin(t*.8+u.ph)*u.bob,u.p0.y+Math.sin(t*.67+u.ph*1.3)*u.bob,u.p0.z+Math.sin(t*.53+u.ph*.7)*u.bob)}
for(const [im,c,dl] of q.inst)im.count=Math.floor(c*clamp((a-dl)/(1-dl),0,1));
if(q.rib){const im=q.ribIm;for(let k=0;k<im.count;k++){const v=q.rib[k];m4.makeTranslation(v.x+Math.sin(t*.9+k)*.02,v.y+Math.sin(t*.7+k*1.7)*.02,v.z+Math.sin(t*.8+k*2.3)*.02);im.setMatrixAt(k,m4)}im.instanceMatrix.needsUpdate=true}
const hi=sel===q?.4+.3*Math.sin(t*5):0,fl=a<1?(1-a)*1.1:0;
for(const m of q.mats){m.emissiveIntensity=m.userData.e0+hi+fl;if(m.userData.o0<1)m.opacity=m.userData.o0*Math.min(1,a*2.5)}}
/* cut open */
cutAmt=clamp(cutAmt+(cutOn?dt:-dt)/.9,0,1);const ca=smooth(cutAmt);
if(ca>0){cutPlane.normal.copy(cutDir).negate();cutPlane.constant=MR*1.12*(1-ca)}else{cutPlane.normal.set(0,0,-1);cutPlane.constant=50}
ring.visible=ca>0;
if(ca>0){const c=cutPlane.constant,r=Math.sqrt(Math.max(0,MR*MR*1.04-c*c));ring.position.copy(cutDir).multiplyScalar(c);ring.quaternion.setFromUnitVectors(Z,cutDir);ring.scale.set(Math.max(r,1e-3),Math.max(r,1e-3),1);ring.material.opacity=.85*Math.min(1,ca*4)}
/* camera flights */
if(fly){fly.t+=dt;const k=inOut(Math.min(1,fly.t/fly.dur));camera.position.lerpVectors(fly.p0,fly.p1,k);controls.target.lerpVectors(fly.q0,fly.q1,k);if(k>=1){controls.autoRotate=fly.spin;fly=null}}
controls.update();
/* labels follow their parts */
scene.updateMatrixWorld();
const W=innerWidth,H=innerHeight,c=cutPlane.constant;
for(const q of parts){let vis=!sel&&!fly&&q.a>=.8,x=0,y=0;
if(vis){q.anchor.getWorldPosition(tmp);if(cutAmt>0&&tmp.dot(cutDir)>c+.05)vis=false;else{tmp.project(camera);if(tmp.z>1||Math.abs(tmp.x)>1.05||Math.abs(tmp.y)>1.05)vis=false;x=(tmp.x+1)/2*W;y=(1-tmp.y)/2*H}}
if(vis)q.el.style.transform='translate('+x.toFixed(1)+'px,'+y.toFixed(1)+'px) translate(-50%,-120%)';
if(vis!==q.lv){q.lv=vis;q.el.style.opacity=vis?1:0;q.el.style.pointerEvents=vis?'auto':'none'}}
cardState();hintState();
slider.value=Math.round(p*100);slider.style.setProperty('--fill',(p/11*100).toFixed(1)+'%');
renderer.render(scene,camera)}
function resize(){renderer.setSize(innerWidth,innerHeight);camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix()}
addEventListener('resize',resize);resize();
camera.position.set(0,.28,1).normalize().multiplyScalar(homeDist());
frame();
</script>
</body>
</html>
