Back to the app
The code
Build a Cell, Part by Part by Claude Fable 5.2
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>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{height:100%;margin:0;overflow:hidden;overscroll-behavior:none}
body{background:radial-gradient(ellipse at 50% 40%,#12354a 0%,#0a1c2e 55%,#050b16 100%);color:#eaf6ff;
font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-user-select:none;user-select:none}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none;cursor:grab}
#top{position:fixed;top:0;left:0;right:0;display:flex;align-items:center;justify-content:space-between;gap:8px;
padding:calc(10px + env(safe-area-inset-top)) 14px 8px;pointer-events:none}
#top h1{margin:0;font-size:18px;font-weight:800;letter-spacing:.2px;text-shadow:0 2px 8px #000a}
#top h1 small{display:block;font-size:12px;font-weight:500;opacity:.75}
.pill{background:#0c2233cc;border:1px solid #6fd7e655;border-radius:999px;padding:6px 12px;font-size:14px;font-weight:700;white-space:nowrap}
#demoBadge{display:none;background:#ffcf4a;color:#2a1c00;border-color:#ffcf4a;margin-right:6px}
#labels{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.chip{position:absolute;left:0;top:0;height:34px;padding:0 12px 0 9px;border-radius:999px;border:1px solid #ffffff44;
background:#081826d9;color:#fff;font:600 13px/1 inherit;font-family:inherit;display:flex;align-items:center;gap:7px;white-space:nowrap;
opacity:0;pointer-events:none;transition:opacity .35s;cursor:pointer;will-change:transform}
.chip.on{opacity:1;pointer-events:auto}
.chip.sel{background:#fff;color:#06202e;border-color:#fff}
.chip i{width:12px;height:12px;border-radius:50%;display:block;flex:none;box-shadow:0 0 8px currentColor}
#panel{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(10px + env(safe-area-inset-bottom));
width:min(560px,calc(100% - 20px));display:flex;flex-direction:column;gap:8px}
#card,#ctl{background:#0a1e2ee6;border:1px solid #6fd7e640;border-radius:18px;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
#card{padding:12px 14px;min-height:112px;position:relative}
#cstep{font-size:12px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:#8fe6f2}
#cname{display:flex;align-items:center;gap:9px;font-size:21px;font-weight:800;margin:3px 0 4px}
#cdot{width:16px;height:16px;border-radius:50%;flex:none}
#cone{margin:0;font-size:16px;line-height:1.35}
#cmore{margin:6px 0 0;font-size:14.5px;line-height:1.4;color:#c4dcea;display:none}
#cback{display:none;margin-top:10px}
#ctl{padding:10px 12px;display:flex;flex-direction:column;gap:8px}
.row{display:flex;align-items:center;gap:10px}
button.big{min-height:48px;padding:0 18px;border-radius:14px;border:1px solid #7fe3ea66;background:#134058;color:#fff;
font:700 16px/1 inherit;font-family:inherit;cursor:pointer;display:flex;align-items:center;gap:8px}
button.big:active{transform:scale(.96);background:#1b5a7a}
#rebuild{background:#1f8a70;border-color:#6ff0c8}
#cut{flex:1;justify-content:space-between}
#cut .tr{width:54px;height:30px;border-radius:999px;background:#062030;border:1px solid #7fe3ea66;position:relative;flex:none;transition:background .25s}
#cut .tr::after{content:"";position:absolute;top:3px;left:3px;width:22px;height:22px;border-radius:50%;background:#cfeeff;transition:transform .25s}
#cut[aria-checked="true"] .tr{background:#ffb347}
#cut[aria-checked="true"] .tr::after{transform:translateX(24px);background:#fff}
.row label{font-size:14px;font-weight:700;flex:none;width:44px}
#scrub{-webkit-appearance:none;appearance:none;flex:1;height:44px;background:transparent;margin:0;touch-action:none;cursor:pointer}
#scrub::-webkit-slider-runnable-track{height:10px;border-radius:9px;background:linear-gradient(90deg,#7fe3ea,#a37bf0,#ff7b54,#d8f04a)}
#scrub::-moz-range-track{height:10px;border-radius:9px;background:linear-gradient(90deg,#7fe3ea,#a37bf0,#ff7b54,#d8f04a)}
#scrub::-webkit-slider-thumb{-webkit-appearance:none;width:32px;height:32px;margin-top:-11px;border-radius:50%;background:#fff;border:4px solid #1f8a70;box-shadow:0 2px 8px #0009}
#scrub::-moz-range-thumb{width:26px;height:26px;border-radius:50%;background:#fff;border:4px solid #1f8a70}
#fail{position:fixed;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:30px;font-size:17px;background:#06121e}
@media (orientation:landscape) and (max-height:540px){
#panel{left:calc(10px + env(safe-area-inset-left));transform:none;width:300px;bottom:8px;gap:6px}
#card{min-height:0;padding:9px 12px}#cname{font-size:18px}#cone{font-size:14.5px}#cmore{font-size:13px}
#ctl{padding:7px 10px;gap:4px}button.big{min-height:44px;padding:0 12px;font-size:15px}
#top h1 small{display:none}
}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="labels"></div>
<div id="top">
<h1>Build a Cell<small>Watch an animal cell come alive</small></h1>
<div style="display:flex;align-items:center"><span class="pill" id="demoBadge">DEMO</span><span class="pill" id="prog">1 / 12</span></div>
</div>
<div id="panel">
<div id="card">
<div id="cstep"></div>
<div id="cname"><i id="cdot"></i><span id="cn"></span></div>
<p id="cone"></p>
<p id="cmore"></p>
<button class="big" id="cback" type="button">↩ Whole cell</button>
</div>
<div id="ctl">
<div class="row">
<button class="big" id="rebuild" type="button">↻ Rebuild</button>
<button class="big" id="cut" type="button" role="switch" aria-checked="false"><span>Cut open</span><span class="tr"></span></button>
</div>
<div class="row"><label for="scrub">Build</label><input id="scrub" type="range" min="0" max="12" step="0.01" value="0" aria-label="Scrub through the build"></div>
</div>
</div>
<div id="fail">This page needs WebGL and the three.js library to draw the cell.<br>Please check your connection and reload.</div>
<script>setTimeout(function(){if(!window.__cellOK)document.getElementById('fail').style.display='flex'},9000);</script>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js';
const PARTS=[
{n:'Cell membrane',c:'#7fe3ea',d:0,one:'A thin, stretchy skin that holds the cell together and chooses what gets in and out.',more:'It works like a doorman: food and oxygen are let in, waste is shown out, and troublemakers are kept outside.'},
{n:'Nucleus',c:'#a37bf0',d:7.5,one:'The control room, where the cell keeps its DNA, the instruction book for building you.',more:'Tiny holes called pores let copies of the instructions travel out to the rest of the cell.'},
{n:'Nucleolus',c:'#e05fb4',d:4.2,one:'A dense blob inside the nucleus that builds the pieces of ribosomes.',more:'Think of it as a factory that makes factories: its pieces leave the nucleus and click together into ribosomes.'},
{n:'Rough ER',c:'#5b86ff',d:7,one:'Folded sheets wrapped around the nucleus where ribosomes park to make proteins.',more:'ER is short for endoplasmic reticulum. New proteins slide inside the sheets, get folded into shape and are sent on to the Golgi. The ribosomes stuck to it make it look rough.'},
{n:'Smooth ER',c:'#3fd6a6',d:5.5,one:'A tangle of smooth tubes that makes fats and helps clear out poisons.',more:'It has no ribosomes, so it looks smooth. It also stores calcium, which muscles need to squeeze.'},
{n:'Ribosomes',c:'#ffd08a',d:3.4,one:'Tiny machines that read the instructions and snap proteins together piece by piece.',more:'Some float free and some sit on the rough ER. One cell can have millions of them.'},
{n:'Golgi apparatus',c:'#f6b53c',d:5.5,one:'The post office of the cell: it packs proteins, labels them and ships them out.',more:'Proteins arrive from the ER, move through the stack of flat bags, and leave in little bubbles with an address tag.'},
{n:'Mitochondria',c:'#ff7b54',d:3.8,one:'Power stations that turn food and oxygen into energy the cell can use.',more:'The wiggly folds inside give them more room to make energy. Busy cells, like muscle, have thousands.'},
{n:'Lysosomes',c:'#5fd06f',d:3.4,one:'Recycling bins full of enzymes that break down worn-out parts and germs.',more:'They swallow rubbish, dissolve it, and hand the useful bits back to the cell to use again.'},
{n:'Vesicles',c:'#a8dcff',d:3.4,one:'Little bubbles that carry cargo from one part of the cell to another.',more:'They pinch off from the Golgi, ride along the cytoskeleton, and can merge with the membrane to drop cargo outside.'},
{n:'Centrioles',c:'#d8f04a',d:3.2,one:'A pair of tiny barrels that help organise the cell when it splits in two.',more:'Each barrel is made of nine sets of tubes. Together they anchor the fibres that pull the copied DNA apart.'},
{n:'Cytoskeleton',c:'#cfeeff',d:7,one:'A web of fibres that gives the cell its shape and works as tracks for moving things around.',more:'It is like bones and railways in one: it can be taken apart and rebuilt in seconds so the cell can move.'}
];
const N=PARTS.length, $=id=>document.getElementById(id);
const canvas=$('c'),labelsEl=$('labels'),panel=$('panel'),slider=$('scrub'),cutBtn=$('cut');
const clamp=(v,a,b)=>Math.min(b,Math.max(a,v));
let seed=90210;const R=()=>{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};
let renderer;
try{renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:true});}catch(e){$('fail').style.display='flex';throw e;}
window.__cellOK=true;
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
renderer.localClippingEnabled=true;
const scene=new THREE.Scene();
const camera=new THREE.PerspectiveCamera(42,1,0.1,300);
scene.add(camera);
scene.add(new THREE.HemisphereLight(0xd6f3ff,0x1a2c44,1.15));
const keyL=new THREE.DirectionalLight(0xffffff,1.7);keyL.position.set(-3,4,5);camera.add(keyL);
scene.add(new THREE.PointLight(0x66ffe0,0.55,0,0));
const RX=5.6,RY=4.5,RZ=4.9,NUC=new THREE.Vector3(-1,0.3,0);
const cutPlane=new THREE.Plane(new THREE.Vector3(0,0,-1),9);
const cell=new THREE.Group();scene.add(cell);
const mats=PARTS.map(()=>[]),anchors=[],foc=[],floaters=[],pick=[];
const std=(col,o)=>{const m=new THREE.MeshStandardMaterial(Object.assign({color:col,roughness:.5,metalness:0,emissive:col,emissiveIntensity:.14},o||{}));m.userData.e0=m.emissiveIntensity;return m};
const ghost=new THREE.MeshBasicMaterial({transparent:true,opacity:0,depthWrite:false});
function reg(part,mesh,doPick){mesh.userData.part=part;const m=mesh.material;if(m&&m.emissive&&mats[part].indexOf(m)<0)mats[part].push(m);if(doPick!==false)pick.push(mesh);return mesh}
function floater(part,obj,o){o=o||{};floaters.push({part,obj,base:obj.position.clone(),rot:obj.rotation.clone(),ph:R()*6.283,amp:o.amp==null?.09:o.amp,ra:o.ra==null?.08:o.ra,s0:o.s||1,pulse:o.pulse==null?.03:o.pulse,cutHide:!!o.cutHide});
if(o.cutHide)obj.traverse(m=>{m.userData.cutHide=true});cell.add(obj);return obj}
function anchor(part,parent,x,y,z){const a=new THREE.Object3D();a.position.set(x||0,y||0,z||0);parent.add(a);anchors[part]=a;if(!foc[part])foc[part]=a;return a}
function randIn(f,minN){for(;;){const x=R()*2-1,y=R()*2-1,z=R()*2-1;if(x*x+y*y+z*z>1)continue;const v=new THREE.Vector3(x*RX*f,y*RY*f,z*RZ*f);if(v.distanceTo(NUC)>minN)return v}}
/* ---------- 0 membrane ---------- */
const memMat=new THREE.ShaderMaterial({transparent:true,depthWrite:false,side:THREE.DoubleSide,
uniforms:{uT:{value:0},uCut:{value:9},uGlow:{value:0}},
vertexShader:`uniform float uT;varying vec3 vN;varying vec3 vV;varying vec3 vW;varying vec3 vO;
void main(){vec3 p=position;float w=sin(p.x*5.+uT*.9)*sin(p.y*6.+uT*.7)*sin(p.z*5.5-uT*.8);p+=normal*w*.022;vO=p;
vec4 wp=modelMatrix*vec4(p,1.);vW=wp.xyz;vec4 mv=viewMatrix*wp;vV=-mv.xyz;vN=normalMatrix*normal;gl_Position=projectionMatrix*mv;}`,
fragmentShader:`uniform float uT;uniform float uCut;uniform float uGlow;varying vec3 vN;varying vec3 vV;varying vec3 vW;varying vec3 vO;
void main(){if(vW.z>uCut)discard;vec3 n=normalize(vN);float fr=pow(1.-abs(dot(normalize(vV),n)),2.2);
float sp=sin(vO.x*18.+uT*.6)*sin(vO.y*18.-uT*.5)*sin(vO.z*18.+uT*.4);
vec3 col=mix(vec3(.22,.72,.86),vec3(.78,1.,.96),fr);
float a=.055+.6*fr+.05*sp*fr+uGlow*(.08+.25*fr);gl_FragColor=vec4(col,clamp(a,0.,1.));}`});
const mem=new THREE.Mesh(new THREE.SphereGeometry(1,72,48),memMat);mem.scale.set(RX,RY,RZ);mem.renderOrder=10;mem.userData.part=0;cell.add(mem);pick.push(mem);
const glow=new THREE.Mesh(new THREE.SphereGeometry(1,32,24),new THREE.MeshBasicMaterial({color:0x2bd4c4,transparent:true,opacity:.07,side:THREE.BackSide,depthWrite:false,clippingPlanes:[cutPlane]}));
glow.scale.set(RX*.985,RY*.985,RZ*.985);glow.renderOrder=9;cell.add(glow);
anchor(0,cell,0,RY*.97,0);
const rimPts=[];for(let i=0;i<48;i++){const a=i/48*6.283;rimPts.push(new THREE.Vector3(Math.cos(a)*RX,Math.sin(a)*RY,0))}
const rimMat=new THREE.MeshBasicMaterial({color:0xc4fbff,transparent:true,opacity:0});
const rim=new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(rimPts,true),160,.07,6,true),rimMat);rim.visible=false;cell.add(rim);
/* ---------- 1 nucleus ---------- */
const nuc=new THREE.Group();nuc.position.copy(NUC);
nuc.add(reg(1,new THREE.Mesh(new THREE.SphereGeometry(1.5,48,36),std(0x8f63e0,{transparent:true,opacity:.6,side:THREE.DoubleSide,depthWrite:false,clippingPlanes:[cutPlane],roughness:.35}))));
{const pores=new THREE.InstancedMesh(new THREE.SphereGeometry(.075,8,6),std(0x4b2c95,{clippingPlanes:[cutPlane]}),70),M=new THREE.Matrix4();
for(let i=0;i<70;i++){const d=new THREE.Vector3(R()-.5,R()-.5,R()-.5).normalize().multiplyScalar(1.49);M.makeTranslation(d.x,d.y,d.z);pores.setMatrixAt(i,M)}
reg(1,pores,false);nuc.add(pores)}
floater(1,nuc,{amp:.05,ra:.03,pulse:.02});anchor(1,nuc,0,1.5,0);foc[1]=nuc;
/* ---------- 2 nucleolus ---------- */
{const g=new THREE.SphereGeometry(.56,28,20),P=g.attributes.position,v=new THREE.Vector3();
for(let i=0;i<P.count;i++){v.fromBufferAttribute(P,i);v.multiplyScalar(1+.09*Math.sin(v.x*9)*Math.sin(v.y*9+1)*Math.sin(v.z*9+2));P.setXYZ(i,v.x,v.y,v.z)}
g.computeVertexNormals();const m=reg(2,new THREE.Mesh(g,std(0xe05fb4,{roughness:.7,emissiveIntensity:.25})));
m.position.copy(NUC).add(new THREE.Vector3(.15,-.1,0));floater(2,m,{amp:.035,ra:.3,pulse:.05});anchor(2,m)}
/* ---------- 3 rough ER (+ ribosome studs, part 5) ---------- */
const rer=new THREE.Group();rer.position.copy(NUC);
const studPts=[];
{const rerMat=std(0x4f7dff,{side:THREE.DoubleSide,clippingPlanes:[cutPlane],roughness:.6}),v=new THREE.Vector3();
[[1.85,2.6,3.4],[2.15,3.6,3.6],[2.45,4.4,2.8]].forEach((s,k)=>{
const g=new THREE.SphereGeometry(s[0],56,20,s[1],s[2],.75,1.65),P=g.attributes.position;
for(let i=0;i<P.count;i++){v.fromBufferAttribute(P,i);v.multiplyScalar(1+.045*Math.sin(v.y*7+k*2)*Math.cos(Math.atan2(v.z,v.x)*9+k));P.setXYZ(i,v.x,v.y,v.z);
if(R()<.22)studPts.push(v.clone().multiplyScalar(R()<.5?1.03:.97))}
g.computeVertexNormals();rer.add(reg(3,new THREE.Mesh(g,rerMat)))})}
floater(3,rer,{amp:.05,ra:.03,pulse:.02});anchor(3,rer,1.7,.67,-.25);
const riboGeo=new THREE.SphereGeometry(.06,7,5),riboMat=std(0xffd08a,{clippingPlanes:[cutPlane],emissiveIntensity:.3});
const studs=new THREE.InstancedMesh(riboGeo,riboMat,studPts.length);
{const M=new THREE.Matrix4();studPts.forEach((p,i)=>{M.makeTranslation(p.x,p.y,p.z);studs.setMatrixAt(i,M)})}
reg(5,studs,false);rer.add(studs);
/* ---------- 4 smooth ER ---------- */
{const ser=new THREE.Group();ser.position.set(2.3,2,-.6);const serMat=std(0x3fd6a6,{roughness:.4});
for(let k=0;k<6;k++){const pts=[];for(let j=0;j<6;j++)pts.push(new THREE.Vector3((R()-.5)*1.9,(R()-.5)*1.7,(R()-.5)*1.3));
const closed=k%2===0;ser.add(reg(4,new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts,closed),56,.1,8,closed),serMat)))}
floater(4,ser,{amp:.08,ra:.06});anchor(4,ser)}
/* ---------- 5 free ribosomes ---------- */
{const ribo=new THREE.Group(),n=240,im=new THREE.InstancedMesh(riboGeo,riboMat,n),M=new THREE.Matrix4(),C=new THREE.Vector3(-2.9,-2.4,-.3);
for(let i=0;i<n;i++){let p;if(i<10){const a=i*.9;p=new THREE.Vector3(C.x+Math.cos(a)*.22+(i-5)*.05,C.y+Math.sin(a)*.22,C.z+(i-5)*.07)}else p=randIn(.86,2.75);
M.makeTranslation(p.x,p.y,p.z);im.setMatrixAt(i,M)}
reg(5,im,false);ribo.add(im);
const px=reg(5,new THREE.Mesh(new THREE.SphereGeometry(.5,10,8),ghost));px.position.copy(C);ribo.add(px);
floater(5,ribo,{amp:.05,ra:.03,pulse:.01});anchor(5,ribo,C.x,C.y,C.z)}
/* ---------- 6 Golgi ---------- */
{const gol=new THREE.Group();gol.position.set(2.9,-1,-.3);gol.rotation.set(.2,.3,.1);
for(let k=0;k<5;k++){const Rk=.7+k*.2,m=reg(6,new THREE.Mesh(new THREE.TorusGeometry(Rk,.085,10,44,2),std(new THREE.Color().setHSL(.115-.012*k,.9,.6-.03*k))));
m.rotation.z=-1;m.scale.z=5.5;m.position.x=-1.1;gol.add(m)}
const bm=std(0xffd27a);
for(let i=0;i<7;i++){const Rk=.7+(i%5)*.2,a=(i%2?1:-1)*(1.12+R()*.15),b=reg(6,new THREE.Mesh(new THREE.SphereGeometry(.1+R()*.05,12,10),bm));
b.position.set(Rk*Math.cos(a)-1.1+(i>4?.5:0),Rk*Math.sin(a),(R()-.5)*.7);gol.add(b)}
floater(6,gol,{amp:.07,ra:.05});anchor(6,gol,.35,0,0)}
/* ---------- 7 mitochondria ---------- */
{const outG=new THREE.CapsuleGeometry(.3,.75,6,18),outM=std(0xff7b54,{transparent:true,opacity:.55,depthWrite:false,roughness:.35}),inM=std(0xd63a2f,{emissiveIntensity:.3}),zz=[];
for(let j=0;j<9;j++)zz.push(new THREE.Vector3(j%2?.17:-.17,-.44+j*.11,0));
const inG=new THREE.TubeGeometry(new THREE.CatmullRomCurve3(zz),40,.05,6,false);
[[4,.5,-.7],[-4.1,-.9,-.4],[.4,3,-1.6],[-2.6,2.6,1.6],[1.6,-1.2,2.6],[-.6,-2.6,-2.6],[3,.6,2.2]].forEach((p,i)=>{
const g=new THREE.Group();g.position.set(p[0],p[1],p[2]);g.rotation.set(R()*3,R()*3,i===1?.1:R()*3);
g.add(reg(7,new THREE.Mesh(inG,inM),false),reg(7,new THREE.Mesh(outG,outM)));
floater(7,g,{amp:.12,ra:.22,cutHide:p[2]>.5});if(i===0)anchor(7,g)})}
/* ---------- 8 lysosomes ---------- */
{const lm=std(0x5fd06f,{roughness:.6}),dm=std(0x2f8f45);
[[-3.7,1.6,-.9],[1.4,-2.9,-1.3],[1.2,.2,-3.2],[-1.8,-2.9,1.6],[2.2,2.4,2],[-2.4,1.2,-3],[.6,-.6,3.4]].forEach((p,i)=>{
const g=new THREE.Group();g.position.set(p[0],p[1],p[2]);g.add(reg(8,new THREE.Mesh(new THREE.SphereGeometry(.3,20,16),lm)));
for(let k=0;k<5;k++){const s=reg(8,new THREE.Mesh(new THREE.SphereGeometry(.07,8,6),dm),false),d=new THREE.Vector3(R()-.5,R()-.5,R()-.5).normalize().multiplyScalar(.27);s.position.copy(d);g.add(s)}
floater(8,g,{amp:.14,ra:.6,pulse:.05,cutHide:p[2]>.5});if(i===0)anchor(8,g)})}
/* ---------- 9 vesicles ---------- */
{const vm=std(0xa8dcff,{transparent:true,opacity:.8,roughness:.15,emissiveIntensity:.25});
for(let i=0;i<13;i++){let p;if(i===0)p=new THREE.Vector3(4,-1.9,-.5);else if(i<6)p=new THREE.Vector3(2.9+.8+R()*.8,-1+(R()-.5)*2,-.3+(R()-.5)*1.4);else p=randIn(.8,2.9);
const m=reg(9,new THREE.Mesh(new THREE.SphereGeometry(.14+R()*.08,16,12),vm));m.position.copy(p);
floater(9,m,{amp:.26,ra:.2,pulse:.07,cutHide:p.z>.4});if(i===0)anchor(9,m)}}
/* ---------- 10 centrioles ---------- */
const C0=new THREE.Vector3(.75,-2.65,-.2);
{const cen=new THREE.Group();cen.position.set(.5,-2.6,-.2);cen.rotation.set(.3,.4,.2);const cM=std(0xd8f04a,{emissiveIntensity:.25}),rod=new THREE.CylinderGeometry(.04,.04,.62,6);
for(let b=0;b<2;b++){const barrel=new THREE.Group();for(let i=0;i<9;i++){const a=i/9*6.283,m=reg(10,new THREE.Mesh(rod,cM),false);m.position.set(Math.cos(a)*.16,0,Math.sin(a)*.16);barrel.add(m)}
if(b){barrel.rotation.z=Math.PI/2;barrel.position.set(.5,-.1,0)}cen.add(barrel)}
const px=reg(10,new THREE.Mesh(new THREE.SphereGeometry(.55,10,8),ghost));px.position.set(.25,0,0);cen.add(px);
floater(10,cen,{amp:.05,ra:.1,s:1.25});anchor(10,cen,.25,0,0)}
/* ---------- 11 cytoskeleton ---------- */
{const cyto=new THREE.Group();cyto.position.copy(C0);
const mtM=std(0xbfeaff,{transparent:true,opacity:.8,clippingPlanes:[cutPlane],roughness:.7,emissiveIntensity:.3}),acM=std(0xff9fd0,{transparent:true,opacity:.75,clippingPlanes:[cutPlane],emissiveIntensity:.3});
const surf=(d,f)=>{d.normalize();return new THREE.Vector3(d.x*RX*f,d.y*RY*f,d.z*RZ*f)};
for(let i=0;i<18;i++){const d=i?new THREE.Vector3(R()*2-1,R()*2-1,R()*2-1):new THREE.Vector3(-.75,.5,-.25);if(d.lengthSq()<.05)d.set(1,.2,0);
const e=surf(d,.95),mid=C0.clone().lerp(e,.5).add(new THREE.Vector3(R()-.5,R()-.5,R()-.5).multiplyScalar(.9));
if(mid.distanceTo(NUC)<2.7){const o=mid.clone().sub(NUC);if(o.lengthSq()<.01)o.set(0,-1,0);mid.copy(NUC).add(o.setLength(4.6))}
const cv=new THREE.QuadraticBezierCurve3(C0.clone(),mid,e),g=new THREE.TubeGeometry(cv,28,.028,5,false);g.translate(-C0.x,-C0.y,-C0.z);
cyto.add(reg(11,new THREE.Mesh(g,mtM),false));
if(i===0){const a=cv.getPoint(.6).sub(C0);anchor(11,cyto,a.x,a.y,a.z)}}
for(let i=0;i<20;i++){const d=new THREE.Vector3(R()*2-1,R()*2-1,R()*2-1);if(d.lengthSq()<.05)d.set(0,1,0);d.normalize();
const d2=d.clone().add(new THREE.Vector3(R()-.5,R()-.5,R()-.5).multiplyScalar(.9)),g=new THREE.TubeGeometry(new THREE.LineCurve3(surf(d,.9),surf(d2,.9)),1,.02,5,false);
g.translate(-C0.x,-C0.y,-C0.z);cyto.add(reg(11,new THREE.Mesh(g,acM),false))}
floater(11,cyto,{amp:.02,ra:.008,pulse:.004})}
/* ---------- drifting dust outside ---------- */
let dust;{const g=new THREE.BufferGeometry(),a=[];for(let i=0;i<170;i++){const v=new THREE.Vector3(R()-.5,R()-.5,R()-.5).normalize().multiplyScalar(13+R()*24);a.push(v.x,v.y,v.z)}
g.setAttribute('position',new THREE.Float32BufferAttribute(a,3));dust=new THREE.Points(g,new THREE.PointsMaterial({color:0x7fd6e6,size:.17,transparent:true,opacity:.4,depthWrite:false}));scene.add(dust)}
/* ---------- state ---------- */
const NORMAL=1/3.4;
let p=0,building=true,speed=NORMAL,complete=false,cur=0,sel=-1,cutOn=false,cutAmt=0,cutZ=9,T=0,last=performance.now(),lastAct=-99,sliding=false;
let W=1,H=1,home=24,cardKey='';
const ea=new Array(N).fill(0);
const cam={th:.5,ph:1.25,r:30,t:new THREE.Vector3()},goal={th:.5,ph:1.25,r:30,t:new THREE.Vector3()};
const tmp=new THREE.Vector3(),ndc=new THREE.Vector2(),ray=new THREE.Raycaster();
const back=x=>{const c1=1.70158,c3=c1+1;return 1+c3*Math.pow(x-1,3)+c1*Math.pow(x-1,2)};
const smooth=x=>x*x*(3-2*x);
const wrap=a=>{a=(a+Math.PI)%(2*Math.PI);if(a<0)a+=2*Math.PI;return a-Math.PI};
const chips=PARTS.map((P,i)=>{const b=document.createElement('button');b.type='button';b.className='chip';
const dot=document.createElement('i');dot.style.background=P.c;dot.style.color=P.c;b.appendChild(dot);b.appendChild(document.createTextNode(P.n));
b.addEventListener('click',()=>{selectPart(i)});labelsEl.appendChild(b);return{el:b,w:0,on:false,sel:false}});
function selectPart(i){
if(i>0&&ea[i]<.5)return;sel=i;
if(i===0){goal.r=home;return}
const v=foc[i].getWorldPosition(tmp),d=v.clone().add(new THREE.Vector3(0,0,cutOn?5:2.5)).normalize();
goal.th=cam.th+wrap(Math.atan2(d.x,d.z)-cam.th);goal.ph=clamp(Math.acos(clamp(d.y,-1,1)),.55,2.55);goal.r=PARTS[i].d;
}
function unselect(){sel=-1;goal.r=home}
function setCut(on){cutOn=on;cutBtn.setAttribute('aria-checked',on?'true':'false');
if(on&&Math.cos(goal.th)<.4)goal.th=Math.round(goal.th/6.2832)*6.2832+.5}
function rebuild(){p=0;building=true;sel=-1;goal.r=home;setCut(false);slider.value=0}
function refreshCard(){
const key=sel+'|'+cur+'|'+complete;if(key===cardKey)return;cardKey=key;
const showSel=sel>=0,i=showSel?sel:cur;
if(!showSel&&complete){$('cstep').textContent='All 12 parts are in';$('cn').textContent='Your cell is alive!';$('cdot').style.background='#fff';
$('cone').textContent='Drag to spin it, pinch to zoom, and tap any part to fly to it and read what it does.'}
else{$('cstep').textContent=showSel?'What it does':'Adding part '+(i+1)+' of 12';$('cn').textContent=PARTS[i].n;$('cdot').style.background=PARTS[i].c;$('cone').textContent=PARTS[i].one}
$('cmore').textContent=showSel?PARTS[i].more:'';$('cmore').style.display=showSel?'block':'none';$('cback').style.display=showSel?'flex':'none';
$('prog').textContent=complete?'12 / 12':(cur+1)+' / 12';
}
function updateLabels(){
const placed=[];
for(let i=0;i<N;i++){const c=chips[i];let show=ea[i]>.6&&(complete||i===cur||i===sel),x=0,y=0;
if(show){anchors[i].getWorldPosition(tmp).project(camera);if(tmp.z>1||tmp.z<-1)show=false;else{x=(tmp.x*.5+.5)*W;y=(-tmp.y*.5+.5)*H-28}}
if(!show){if(c.on){c.el.classList.remove('on');c.on=false}continue}
if(!c.w)c.w=c.el.offsetWidth||90;
x=clamp(x,c.w/2+6,W-c.w/2-6);y=clamp(y,62,H-30);
for(let k=0;k<4;k++)for(const q of placed){if(Math.abs(x-q.x)<(c.w+q.w)/2+4&&Math.abs(y-q.y)<37)y=q.y+(y>=q.y?37:-37)}
placed.push({x,y,w:c.w});
c.el.style.transform='translate('+(x-c.w/2).toFixed(1)+'px,'+(y-17).toFixed(1)+'px)';
if(!c.on){c.el.classList.add('on');c.on=true}
const s=i===sel;if(s!==c.sel){c.el.classList.toggle('sel',s);c.sel=s}
}
}
function pickAt(x,y){
ndc.set(x/W*2-1,-(y/H)*2+1);ray.setFromCamera(ndc,camera);
const hits=ray.intersectObjects(pick,false);let memHit=false;
for(const h of hits){const o=h.object,i=o.userData.part;
if(i===0){memHit=true;continue}
if(ea[i]<.5)continue;
if(cutAmt>.5){if(o.userData.cutHide)continue;if((i===1||i===3)&&h.point.z>cutZ+.02)continue}
selectPart(i);return}
if(memHit)selectPart(0);else unselect();
}
/* ---------- input ---------- */
let demo=/#demo$/.test(String(location.href)),dT=0,dI=-1;
function endDemo(){if(!demo)return;demo=false;$('demoBadge').style.display='none';speed=NORMAL;if(p<12)building=true}
function userAct(){lastAct=T;endDemo()}
['pointerdown','touchstart','wheel','keydown'].forEach(ev=>window.addEventListener(ev,userAct,{capture:true,passive:true}));
const pts=new Map();let downX=0,downY=0,downT=0,moved=false,pinch0=1,r0=1;
const pinchDist=()=>{const a=[...pts.values()];return Math.hypot(a[0].x-a[1].x,a[0].y-a[1].y)||1};
canvas.addEventListener('pointerdown',e=>{try{canvas.setPointerCapture(e.pointerId)}catch(_){}
pts.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(pts.size===1){downX=e.clientX;downY=e.clientY;downT=performance.now();moved=false}
else{moved=true;if(pts.size===2){pinch0=pinchDist();r0=goal.r}}});
canvas.addEventListener('pointermove',e=>{const q=pts.get(e.pointerId);if(!q)return;lastAct=T;
const dx=e.clientX-q.x,dy=e.clientY-q.y;q.x=e.clientX;q.y=e.clientY;
if(pts.size===1){if(Math.hypot(e.clientX-downX,e.clientY-downY)>9)moved=true;
if(moved){goal.th-=dx*.0065;goal.ph=clamp(goal.ph-dy*.0065,.25,Math.PI-.25)}}
else if(pts.size===2){goal.r=clamp(r0*pinch0/pinchDist(),2.2,home*1.5)}});
function pUp(e){if(!pts.has(e.pointerId))return;const one=pts.size===1;pts.delete(e.pointerId);
if(one&&!moved&&e.type==='pointerup'&&performance.now()-downT<600)pickAt(e.clientX,e.clientY);
if(pts.size===1)moved=true}
canvas.addEventListener('pointerup',pUp);canvas.addEventListener('pointercancel',pUp);
canvas.addEventListener('wheel',e=>{e.preventDefault();goal.r=clamp(goal.r*Math.exp(e.deltaY*.0012),2.2,home*1.5)},{passive:false});
canvas.addEventListener('contextmenu',e=>e.preventDefault());
$('rebuild').addEventListener('click',rebuild);
cutBtn.addEventListener('click',()=>setCut(!cutOn));
$('cback').addEventListener('click',unselect);
slider.addEventListener('pointerdown',()=>{sliding=true});
slider.addEventListener('input',()=>{sliding=true;building=false;p=parseFloat(slider.value)||0});
['pointerup','pointercancel','change','blur'].forEach(ev=>slider.addEventListener(ev,()=>{sliding=false}));
function resize(){
W=window.innerWidth||1;H=window.innerHeight||1;renderer.setSize(W,H,false);
const pr=panel.getBoundingClientRect(),side=pr.width<W*.6,top=56;let ox=0,oy=0,fw=1,fh=1;
if(side){ox=-pr.right/2;fw=(W-pr.right)/W;oy=-top/2;fh=(H-top)/H}
else{oy=(pr.height+14-top)/2;fh=(H-pr.height-14-top)/H}
camera.setViewOffset(W,H,ox,oy,W,H);
const tv=Math.tan(camera.fov*Math.PI/360);
home=Math.max(5/(tv*Math.max(.3,fh)),6.1/(tv*(W/H)*Math.max(.3,fw)))*1.04;
if(sel<=0)goal.r=home;
chips.forEach(c=>{c.w=0});
}
window.addEventListener('resize',resize);window.addEventListener('orientationchange',()=>setTimeout(resize,250));
/* ---------- demo script (about 20 s loop) ---------- */
const demoEvents=[[8.4,()=>selectPart(7)],[10.9,unselect],[11.3,()=>setCut(true)],[13.3,()=>selectPart(2)],[15.6,unselect],[18.9,()=>setCut(false)]];
function runDemo(dt){
dT+=dt;if(dI<0||dT>=20){dT=0;dI=0;rebuild();speed=12/8}
while(dI<demoEvents.length&&dT>=demoEvents[dI][0]){demoEvents[dI][1]();dI++}
if(dT>16&&dT<18.7){building=false;p=12-7*Math.sin(Math.PI*(dT-16)/2.7);slider.value=p}
else if(dT>=18.7&&p<12&&!building){p=12;slider.value=12}
lastAct=-99;
}
/* ---------- main loop ---------- */
function frame(now){
requestAnimationFrame(frame);
const dt=Math.min(.05,Math.max(0,(now-last)/1000));last=now;T+=dt;
if(demo)runDemo(dt);
if(building){p=Math.min(12,p+dt*speed);if(p>=12)building=false;if(!sliding)slider.value=p}
complete=p>=12;cur=Math.min(N-1,Math.floor(p));
ea[0]=1;for(let i=1;i<N;i++)ea[i]=back(clamp((p-i)/.6,0,1));
if(sel>0&&ea[sel]<.5)unselect();
cutAmt+=((cutOn?1:0)-cutAmt)*(1-Math.exp(-dt*3.2));
const ce=smooth(clamp(cutAmt,0,1));cutZ=5.3*(1-ce);cutPlane.constant=cutZ;
memMat.uniforms.uCut.value=cutZ;memMat.uniforms.uT.value=T;memMat.uniforms.uGlow.value=sel===0?.55+.45*Math.sin(T*4):0;
const rs=Math.sqrt(Math.max(0,1-(cutZ/RZ)*(cutZ/RZ)));rim.visible=ce>.02&&rs>.01;rim.scale.set(rs||.001,rs||.001,1);rim.position.z=cutZ;rimMat.opacity=ce;
const breathe=1+.012*Math.sin(T*.9);cell.scale.setScalar(breathe);
for(const f of floaters){
let s=ea[f.part]*(1+f.pulse*Math.sin(T*1.7+f.ph));if(f.cutHide)s*=1-ce;
const o=f.obj;o.visible=s>.002;if(!o.visible)continue;
o.position.set(f.base.x+f.amp*Math.sin(T*.5+f.ph),f.base.y+f.amp*Math.sin(T*.43+f.ph*1.7),f.base.z+f.amp*Math.cos(T*.37+f.ph*2.3));
o.rotation.set(f.rot.x+f.ra*Math.sin(T*.31+f.ph),f.rot.y+f.ra*Math.sin(T*.27+f.ph*1.3),f.rot.z+f.ra*Math.cos(T*.23+f.ph));
o.scale.setScalar(s*f.s0);
}
studs.visible=ea[5]>.002;studs.scale.setScalar(Math.max(.001,ea[5]));
for(let i=1;i<N;i++){const add=i===sel?.4+.3*Math.sin(T*5):(i===cur&&!complete?.18:0);for(const m of mats[i])m.emissiveIntensity=m.userData.e0+add}
dust.rotation.y=T*.012;dust.rotation.x=T*.005;
if(sel>0)foc[sel].getWorldPosition(goal.t);else goal.t.set(0,0,0);
if(pts.size===0&&sel<0&&T-lastAct>2.5)goal.th+=dt*(cutOn?.2*Math.cos(T*.45):.1);
const k=1-Math.exp(-dt*4.5);
cam.th+=(goal.th-cam.th)*k;cam.ph+=(goal.ph-cam.ph)*k;cam.r+=(goal.r-cam.r)*k;cam.t.lerp(goal.t,k);
const sp=Math.sin(cam.ph);
camera.position.set(cam.t.x+cam.r*sp*Math.sin(cam.th),cam.t.y+cam.r*Math.cos(cam.ph),cam.t.z+cam.r*sp*Math.cos(cam.th));
camera.lookAt(cam.t);
renderer.render(scene,camera);
updateLabels();refreshCard();
}
resize();cam.r=goal.r=home*1.15;goal.r=home;
if(demo)$('demoBadge').style.display='inline-block';
refreshCard();
requestAnimationFrame(t=>{last=t;frame(t)});
</script>
</body>
</html>
