Skip to content
VibeCodeBench
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.)32.1 KB · 409 lines · loads unpkg.com/[email protected]/build/three.module.js, unpkg.com/[email protected]/examples/jsm/
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Build a Living Cell</title>
<style>
:root{--glass:rgba(12,20,44,.76);--line:rgba(255,255,255,.16);--ink:#eef4ff;--mut:#a9b8d8;--acc:#38bdf8}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;background:radial-gradient(120% 90% at 50% 35%,#16244d 0%,#0a1230 45%,#050816 100%);color:var(--ink);font-family:ui-rounded,"Segoe UI",system-ui,-apple-system,Roboto,sans-serif;user-select:none;-webkit-user-select:none}
#app{position:fixed;inset:0}
canvas{display:block;width:100%;height:100%;touch-action:none}
#labels{position:absolute;inset:0;pointer-events:none;overflow:hidden}
.tag{position:absolute;left:0;top:0;display:flex;align-items:center;gap:5px;padding:6px 10px 6px 8px;border-radius:999px;border:1px solid var(--line);background:rgba(8,14,34,.74);color:#fff;font-family:inherit;font-size:12px;font-weight:600;white-space:nowrap;transition:opacity .3s;cursor:pointer}
.tag::after{content:"";position:absolute;left:50%;bottom:-8px;width:2px;height:8px;margin-left:-1px;background:rgba(255,255,255,.55)}
.tag i{width:8px;height:8px;border-radius:50%;flex:none}
.tag.new{font-size:14px;background:rgba(30,60,120,.9);box-shadow:0 0 16px rgba(120,200,255,.6)}
.tag.sel{border-color:#fff;background:rgba(40,70,140,.92)}
#top{position:absolute;top:0;left:0;right:0;display:flex;justify-content:space-between;align-items:flex-start;padding:calc(10px + env(safe-area-inset-top)) 14px 8px;pointer-events:none}
#top h1{margin:0;font-size:19px;letter-spacing:.3px;text-shadow:0 2px 8px #000}
#top h1 small{display:block;font-size:12px;font-weight:500;color:var(--mut)}
#count{background:var(--glass);border:1px solid var(--line);border-radius:999px;padding:8px 12px;font-weight:700;font-size:14px;white-space:nowrap}
#demo{position:absolute;left:50%;top:calc(58px + env(safe-area-inset-top));transform:translateX(-50%);background:#f472b6;color:#200a18;font-weight:800;font-size:13px;padding:7px 14px;border-radius:999px;pointer-events:none;white-space:nowrap}
#hint{position:absolute;left:50%;top:calc(58px + env(safe-area-inset-top));transform:translateX(-50%);background:var(--glass);border:1px solid var(--line);font-size:14px;font-weight:600;padding:9px 14px;border-radius:999px;pointer-events:none;opacity:0;transition:opacity .6s;white-space:nowrap}
#hint.show{opacity:1}
#panel{position:absolute;left:50%;transform:translateX(-50%);bottom:calc(8px + env(safe-area-inset-bottom));width:min(720px,calc(100% - 16px));background:var(--glass);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border:1px solid var(--line);border-radius:20px;padding:12px;display:flex;flex-direction:column;gap:8px}
#card{min-height:76px}
#card.pop{animation:pop .45s ease}
@keyframes pop{from{opacity:.2;transform:translateY(6px)}to{opacity:1;transform:none}}
.ch{display:flex;align-items:center;gap:8px}
#dot{width:14px;height:14px;border-radius:50%;flex:none;box-shadow:0 0 10px currentColor}
#cname{font-size:18px}
#cstep{margin-left:auto;font-size:12px;color:var(--mut);white-space:nowrap}
#ctext{margin:5px 0 0;font-size:15px;line-height:1.35}
#cfact{margin:4px 0 0;font-size:13px;color:#fde68a;line-height:1.3}
#cfact:empty{display:none}
#chips{position:relative;display:flex;gap:6px;overflow-x:auto;touch-action:pan-x;scrollbar-width:none;padding-bottom:1px}
#chips::-webkit-scrollbar{display:none}
.chip{flex:none;min-height:44px;display:flex;align-items:center;gap:6px;padding:0 12px;border-radius:14px;border:1px solid var(--line);background:rgba(255,255,255,.06);color:var(--ink);font-family:inherit;font-size:14px;font-weight:600;cursor:pointer;transition:opacity .3s}
.chip i{width:10px;height:10px;border-radius:50%}
.chip.off{opacity:.3}
.chip.sel{border-color:#fff;background:rgba(255,255,255,.18)}
.row{display:flex;align-items:center;gap:10px}
.b{min-height:52px;border-radius:14px;border:1px solid var(--line);background:rgba(255,255,255,.08);color:var(--ink);font-family:inherit;font-weight:700;font-size:13px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;padding:4px 4px;cursor:pointer;position:relative;text-align:center}
.b:active{transform:scale(.96)}
.b .ic{font-size:19px;line-height:1}
#play{width:52px;flex:none}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}
.sw input{position:absolute;opacity:0;pointer-events:none}
.sw .tr{width:42px;height:22px;border-radius:11px;background:rgba(255,255,255,.24);position:relative;transition:.25s}
.sw .tr::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:.25s}
.sw input:checked+.tr{background:#f472b6}
.sw input:checked+.tr::after{transform:translateX(20px)}
#rebuild{background:linear-gradient(180deg,#38bdf8,#0284c7);border-color:transparent;color:#fff}
.b.on{background:rgba(56,189,248,.22);border-color:var(--acc)}
input[type=range]{-webkit-appearance:none;appearance:none;flex:1;min-width:0;height:48px;background:transparent;margin:0;--p:0%}
input[type=range]::-webkit-slider-runnable-track{height:8px;border-radius:4px;background:linear-gradient(90deg,var(--acc) var(--p),rgba(255,255,255,.2) var(--p))}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:30px;height:30px;border-radius:50%;background:#fff;margin-top:-11px;border:4px solid var(--acc)}
input[type=range]::-moz-range-track{height:8px;border-radius:4px;background:rgba(255,255,255,.2)}
input[type=range]::-moz-range-progress{height:8px;border-radius:4px;background:var(--acc)}
input[type=range]::-moz-range-thumb{width:24px;height:24px;border-radius:50%;background:#fff;border:4px solid var(--acc)}
#err{position:absolute;inset:0;display:none;align-items:center;justify-content:center;padding:30px;text-align:center;font-size:18px}
</style>
<script type="importmap">
{"imports":{"three":"https://unpkg.com/[email protected]/build/three.module.js","three/addons/":"https://unpkg.com/[email protected]/examples/jsm/"}}
</script>
</head>
<body>
<div id="app">
  <div id="labels"></div>
  <header id="top">
    <h1>Build a Living Cell<small>A 3D animal cell, part by part</small></h1>
    <div id="count">0 / 11 parts</div>
  </header>
  <div id="demo" hidden>Demo &middot; tap anywhere to explore</div>
  <div id="hint">Drag to spin &middot; pinch to zoom &middot; tap a part</div>
  <section id="panel">
    <div id="card"><div class="ch"><span id="dot"></span><b id="cname">An empty cell</b><span id="cstep"></span></div><p id="ctext"></p><p id="cfact"></p></div>
    <div id="chips"></div>
    <div class="row">
      <button class="b" id="play" aria-label="Play or pause the build"></button>
      <input type="range" id="scrub" min="0" max="1100" step="1" value="0" aria-label="Scrub through the build">
    </div>
    <div class="grid">
      <label class="b sw"><input type="checkbox" id="cut"><span class="tr"></span><span>Cut open</span></label>
      <button class="b" id="rebuild"><span class="ic">&#8635;</span>Rebuild</button>
      <button class="b" id="home"><span class="ic">&#9678;</span>Whole cell</button>
      <button class="b on" id="lbl"><span class="ic">&#127991;&#65039;</span>Labels</button>
    </div>
  </section>
  <div id="err">Sorry, this device could not start 3D graphics.</div>
</div>
<script type="module">
import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';

const $=id=>document.getElementById(id);
let S=20261122;
function rnd(){S|=0;S=S+0x6D2B79F5|0;let t=Math.imul(S^S>>>15,1|S);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 V=(x=0,y=0,z=0)=>new THREE.Vector3(x,y,z);
const randDir=()=>{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 clamp=(x,a=0,b=1)=>Math.min(b,Math.max(a,x));
const easeBack=x=>{if(x<=0)return 0;if(x>=1)return 1;const c1=1.70158,c3=c1+1;return 1+c3*Math.pow(x-1,3)+c1*Math.pow(x-1,2)};
const easeIO=x=>x<.5?4*x*x*x:1-Math.pow(-2*x+2,3)/2;

let renderer;
try{renderer=new THREE.WebGLRenderer({antialias:true,alpha:true})}catch(e){$('err').style.display='flex';$('panel').style.display='none';throw e}
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));
$('app').prepend(renderer.domElement);
const scene=new THREE.Scene();
const camera=new THREE.PerspectiveCamera(45,1,.05,300);
scene.add(camera);
const controls=new OrbitControls(camera,renderer.domElement);
Object.assign(controls,{enableDamping:true,dampingFactor:.08,enablePan:false,minDistance:.6,maxDistance:60,rotateSpeed:.7,autoRotate:true,autoRotateSpeed:.6});
controls.touches={ONE:THREE.TOUCH.ROTATE,TWO:THREE.TOUCH.DOLLY_PAN};
const plane=new THREE.Plane(V(0,0,-1),9);
renderer.clippingPlanes=[plane];

scene.add(new THREE.HemisphereLight(0xcfe8ff,0x3a2450,1.2));
const dl=new THREE.DirectionalLight(0xffffff,1.7);dl.position.set(5,8,6);scene.add(dl);
const cl=new THREE.DirectionalLight(0xffffff,.7);cl.position.set(0,0,1);camera.add(cl);

const R=5,C=V(-.5,.3,0),NR=1.45,N=11;
const gDir=V(.93,-.3,.2).normalize(),G=C.clone().addScaledVector(gDir,3.95);
const sDir=V(-.6,-.5,-.6).normalize(),S0=C.clone().addScaledVector(sDir,3.4);
const cDir=V(-.3,-.85,.45).normalize(),CP=C.clone().addScaledVector(cDir,3.35);
const DS=THREE.DoubleSide,dm=new THREE.Object3D(),tA=V(),tB=V();

const cell=new THREE.Group();scene.add(cell);
const parts=[];
function part(name,color,text,fact,dist,pulse=.025){const g=new THREE.Group();cell.add(g);const p={i:parts.length,name,color,hex:'#'+color.toString(16).padStart(6,'0'),text,fact,dist,pulse,g,pieces:[],mats:[],anchor:V(),focus:null,labPc:null,multi:false,rev:0,flash:0};parts.push(p);return p}
function piece(p,o,opt={}){(opt.parent||p.g).add(o);const pc=Object.assign({o,bp:o.position.clone(),bs:o.scale.clone(),br:o.rotation.clone(),ph:rr(0,6.28),amp:.035,mode:'scale',spin:0,pick:false},opt);o.traverse(c=>c.userData.pc=pc);p.pieces.push(pc);return pc}
function M(color,o={}){const m=new THREE.MeshStandardMaterial(Object.assign({color,roughness:.45,metalness:0,emissive:color,emissiveIntensity:.16},o));if(m.opacity<1){m.transparent=true;m.depthWrite=false}m.userData.ei=m.emissiveIntensity;return m}
function bump(g,a,f){const p=g.attributes.position,v=V();for(let i=0;i<p.count;i++){v.fromBufferAttribute(p,i);v.multiplyScalar(1+a*Math.sin(v.x*f*2.1+1)*Math.sin(v.y*f*1.7+2)*Math.sin(v.z*f*2.3));p.setXYZ(i,v.x,v.y,v.z)}g.computeVertexNormals()}

/* 0 membrane */
const memMat=new THREE.ShaderMaterial({
uniforms:{uTime:{value:0},uColor:{value:new THREE.Color(0x9bd7ff)},uOp:{value:1}},
vertexShader:`#include <clipping_planes_pars_vertex>
uniform float uTime;varying vec3 vN;varying vec3 vV;
void main(){vec3 p=position;float w=sin(p.x*1.1+uTime*.9)*.07+sin(p.y*1.4+uTime*.7)*.07+sin(p.z*1.2+uTime*1.1)*.06;p+=normal*w;
vec4 mvPosition=modelViewMatrix*vec4(p,1.);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 uOp;varying vec3 vN;varying vec3 vV;
void main(){
#include <clipping_planes_fragment>
float f=pow(1.-abs(dot(normalize(vN),normalize(vV))),2.4);gl_FragColor=vec4(uColor*(.6+f*.8),clamp((.05+f*.75)*uOp,0.,1.));}`,
transparent:true,depthWrite:false,side:DS,clipping:true});
const P0=part('Cell membrane',0x8fd3ff,"The cell membrane is a thin, bendy skin that controls what goes in and out of the cell.","It is made of two layers of fatty molecules, like a super-thin sandwich.",4.2);
const mem=new THREE.Mesh(new THREE.SphereGeometry(R,96,64),memMat);mem.renderOrder=10;
piece(P0,mem,{mode:'mem',amp:0});P0.anchor.set(3.3,3.4,1.2);

/* 1 nucleus */
const P1=part('Nucleus',0x8b5cf6,"The nucleus is the control center: it keeps the DNA, the instruction book for the whole cell.","If you stretched out the DNA from just one of your cells, it would be about 2 meters long!",5.2,.02);
const env=new THREE.Mesh(new THREE.SphereGeometry(NR,48,32),M(0x8b5cf6,{opacity:.42,side:DS,roughness:.25}));env.position.copy(C);
const pores=new THREE.InstancedMesh(new THREE.TorusGeometry(.07,.022,6,12),M(0xddd6fe),80);
for(let i=0;i<80;i++){const d=randDir();dm.position.copy(d).multiplyScalar(NR);dm.lookAt(d.clone().multiplyScalar(3));dm.updateMatrix();pores.setMatrixAt(i,dm.matrix)}
env.add(pores);
const chromM=M(0xe9d5ff,{emissiveIntensity:.35});
for(let k=0;k<7;k++){const pts=[];let q=randDir().multiplyScalar(rr(.2,.8));for(let j=0;j<9;j++){pts.push(q.clone());q.add(randDir().multiplyScalar(.32));if(q.length()>1.1)q.setLength(1)}env.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts),60,.03,5),chromM))}
piece(P1,env,{amp:.02,pick:true});P1.anchor.copy(C).add(V(0,NR,0));P1.focus=C.clone();

/* 2 nucleolus */
const P2=part('Nucleolus',0xe879f9,"The nucleolus is a dense spot inside the nucleus that starts building ribosomes.","It has no skin of its own. It is just a busy crowd of molecules.",2.6,.04);
const ng=new THREE.SphereGeometry(.48,40,28);bump(ng,.07,6);
const nuc=new THREE.Mesh(ng,M(0xd946ef,{roughness:.6,emissiveIntensity:.3}));nuc.position.copy(C).add(V(.35,.3,-.25));
piece(P2,nuc,{amp:.03,pick:true});P2.anchor.copy(nuc.position);

/* 3 rough ER */
const P3=part('Rough ER',0x3b82f6,"The rough ER is a folded sheet dotted with ribosomes, where many proteins are made.","ER is short for endoplasmic reticulum, a fancy name meaning \"little net inside\".",5,.02);
const rerM=M(0x3b82f6,{opacity:.74,side:DS,roughness:.3}),dotM=M(0xff7a6b,{emissiveIntensity:.3}),dotG=new THREE.SphereGeometry(.04,6,4);
[[1.85,2.2,3.4,.55,2.05],[2.15,4.0,3.2,.45,2.25],[2.45,1.6,2.8,.6,1.95],[2.75,3.6,3.4,.5,2.1]].forEach(([r,ps,pl,ts,tl],k)=>{
 const g=new THREE.SphereGeometry(r,72,30,ps,pl,ts,tl),p=g.attributes.position,uv=g.attributes.uv,v=V();
 for(let i=0;i<p.count;i++){v.fromBufferAttribute(p,i);const w=.09*Math.sin(uv.getX(i)*pl*5+k)+.05*Math.sin(uv.getY(i)*tl*9);v.multiplyScalar(1+w/r);p.setXYZ(i,v.x,v.y,v.z)}
 g.computeVertexNormals();
 const m=new THREE.Mesh(g,rerM);m.position.copy(C);
 const dots=new THREE.InstancedMesh(dotG,dotM,90);
 for(let j=0;j<90;j++){v.fromBufferAttribute(p,Math.floor(rnd()*p.count));v.multiplyScalar(1+(rnd()<.5?.025:-.025));dm.position.copy(v);dm.updateMatrix();dots.setMatrixAt(j,dm.matrix)}
 m.add(dots);piece(P3,m,{amp:.015});
});
P3.anchor.copy(C).add(V(1,1.25,-1));

/* 4 smooth ER */
const P4=part('Smooth ER',0x2dd4bf,"The smooth ER is a tangle of tubes that makes fats and helps break down harmful chemicals.","Your liver cells are packed with smooth ER to help clean your blood.",4,.02);
const serM=M(0x2dd4bf,{roughness:.35,emissiveIntensity:.22}),serPts=[];
for(let k=0;k<8;k++){
 let q=k<2?C.clone().addScaledVector(V(sDir.x+rr(-.3,.3),sDir.y+rr(-.3,.3),sDir.z+rr(-.3,.3)).normalize(),2.6):serPts[Math.floor(rnd()*serPts.length)].clone();
 const pts=[q.clone()],dir=sDir.clone().add(randDir().multiplyScalar(.9)).normalize();
 for(let j=0;j<6;j++){q.addScaledVector(dir.add(randDir().multiplyScalar(.5)).normalize(),.5);if(q.length()>4.4)q.setLength(4.3);if(q.distanceTo(C)<2.5)q.sub(C).setLength(2.6).add(C);pts.push(q.clone())}
 serPts.push(...pts.slice(1));
 piece(P4,new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts),70,.075,6),serM),{mode:'grow',amp:.02});
}
P4.anchor.copy(serPts[3]);

/* 5 ribosomes */
const P5=part('Ribosomes',0xff7a6b,"Ribosomes are tiny machines that read instructions and snap proteins together.","One cell can have millions of ribosomes working at the same time.",2.4,0);
const RN=320,ribo=new THREE.InstancedMesh(new THREE.SphereGeometry(.055,8,6),M(0xff7a6b,{emissiveIntensity:.35}),RN);
for(let i=0;i<RN;i++){let p;do{p=randDir().multiplyScalar(Math.cbrt(rnd())*4.5)}while(p.distanceTo(C)<NR+.35);if(P5.anchor.lengthSq()===0&&p.length()>3.4&&p.z>0)P5.anchor.copy(p);dm.position.copy(p);dm.scale.setScalar(rr(.8,1.3));dm.updateMatrix();ribo.setMatrixAt(i,dm.matrix)}
dm.scale.setScalar(1);
piece(P5,ribo,{mode:'inst',n:RN,amp:0});

/* 6 golgi */
const P6=part('Golgi apparatus',0xf59e0b,"The Golgi apparatus is the cell's post office: it sorts, packs and ships proteins.","It is named after Camillo Golgi, the Italian scientist who spotted it in 1898.",3.6,.03);
const golgi=new THREE.Group();golgi.position.copy(G);golgi.quaternion.setFromUnitVectors(V(0,1,0),gDir);P6.g.add(golgi);
const gm=[0xfbbf24,0xf59e0b,0xf59e0b,0xea9a0a,0xd97706].map(c=>M(c,{roughness:.4,side:DS}));
const GA=[.72,.92,1.08,1,.84];
GA.forEach((a,i)=>{const g=new THREE.SphereGeometry(1,40,14),p=g.attributes.position;for(let j=0;j<p.count;j++){const x=p.getX(j)*a,z=p.getZ(j)*a*.62;p.setXYZ(j,x,p.getY(j)*.075+.3*(x*x+z*z),z)}g.computeVertexNormals();const m=new THREE.Mesh(g,gm[i]);m.position.y=(i-2)*.21;piece(P6,m,{parent:golgi,amp:.02,pick:true})});
for(let k=0;k<9;k++){const i=3+(k%2),a=GA[i]+.12,an=rr(0,6.28),x=Math.cos(an)*a,z=Math.sin(an)*a*.62;const s=new THREE.Mesh(new THREE.SphereGeometry(rr(.07,.11),12,8),gm[1]);s.position.set(x,(i-2)*.21+.3*(x*x+z*z)+.05,z);piece(P6,s,{parent:golgi,amp:.04,pick:true})}
P6.anchor.copy(G);

/* 7 mitochondria */
const occ=[{p:C,r:2.95},{p:G,r:1.25},{p:S0,r:1.1},{p:CP,r:.6}];
function place(r,a,b){let p;for(let t=0;t<600;t++){p=randDir().multiplyScalar(rr(a,b));if(occ.every(o=>p.distanceTo(o.p)>o.r+r))break}occ.push({p,r});return p}
const P7=part('Mitochondria',0xfb923c,"Mitochondria are power plants that turn food and oxygen into energy the cell can use.","Mitochondria have their own tiny DNA, separate from the nucleus.",2.6,.03);
const mOut=M(0xfb923c,{opacity:.78,side:DS,roughness:.35}),mIn=M(0xfde68a,{emissiveIntensity:.3});
const capG=new THREE.CapsuleGeometry(.3,.85,8,20),crG=new THREE.CylinderGeometry(.21,.21,.03,20);
for(let k=0;k<7;k++){const p=place(.62,2.6,4.25),g=new THREE.Group();g.add(new THREE.Mesh(capG,mOut));
 for(let j=0;j<5;j++){const c=new THREE.Mesh(crG,mIn);c.position.set(j%2?.07:-.07,-.5+j*.25,0);c.rotation.z=j%2?.1:-.1;g.add(c)}
 g.position.copy(p);g.quaternion.setFromUnitVectors(V(0,1,0),p.clone().normalize().cross(randDir()).normalize());g.rotateY(rr(0,6.28));
 piece(P7,g,{amp:.07,spin:.25,pick:true})}
P7.multi=true;P7.labPc=P7.pieces[0];

/* 8 lysosomes */
const P8=part('Lysosomes',0xa3e635,"Lysosomes are little recycling bags full of enzymes that break down old parts and germs.","Inside, they are acidic, which helps their enzymes chop things up.",1.9,.05);
const lOut=M(0xa3e635,{opacity:.82,roughness:.3}),lIn=M(0x4d7c0f,{emissiveIntensity:.2});
for(let k=0;k<7;k++){const r=rr(.24,.34),p=place(r+.05,2.2,4.4),g=new THREE.Group();g.add(new THREE.Mesh(new THREE.SphereGeometry(r,24,16),lOut));for(let j=0;j<4;j++){const d=new THREE.Mesh(new THREE.SphereGeometry(r*.22,8,6),lIn);d.position.copy(randDir().multiplyScalar(r*.45));g.add(d)}g.position.copy(p);piece(P8,g,{amp:.09,pick:true})}
P8.multi=true;P8.labPc=P8.pieces[0];

/* 9 vesicles */
const P9=part('Vesicles',0x7dd3fc,"Vesicles are tiny bubbles that carry materials around the cell and out through the membrane.","Nerve cells use vesicles to send chemical messages to each other.",1.6,.04);
const vM=M(0x7dd3fc,{opacity:.72,roughness:.15,emissiveIntensity:.3}),gOut=G.clone().addScaledVector(gDir,.7);
for(let k=0;k<16;k++){const s=new THREE.Mesh(new THREE.SphereGeometry(rr(.11,.18),16,12),vM);const a=gOut.clone().add(randDir().multiplyScalar(.35));let d;do{d=gDir.clone().add(randDir().multiplyScalar(1.2)).normalize()}while(d.dot(gDir)<.3);const e=d.multiplyScalar(4.75),m=a.clone().lerp(e,.5).add(randDir().multiplyScalar(.8));s.position.copy(a);piece(P9,s,{mode:'ves',a,m,e,sp:rr(.035,.06),pick:true,amp:0})}
P9.multi=true;P9.labPc=P9.pieces[0];

/* 10 centrioles */
const P10=part('Centrioles',0xfde047,"Centrioles are two tiny bundles of tubes that help pull DNA copies apart when a cell divides.","Each centriole is a ring of 9 groups of three tiny tubes.",2.1,.03);
const cM=M(0xfde047,{emissiveIntensity:.3}),rodG=new THREE.CylinderGeometry(.022,.022,.6,6);
function centriole(){const im=new THREE.InstancedMesh(rodG,cM,27);let n=0;dm.rotation.set(0,0,0);for(let i=0;i<9;i++)for(let k=0;k<3;k++){const a=i*Math.PI*2/9+k*.13,r=.11+k*.034;dm.position.set(Math.cos(a)*r,0,Math.sin(a)*r);dm.updateMatrix();im.setMatrixAt(n++,dm.matrix)}return im}
const c1=new THREE.Group();c1.add(centriole());c1.position.copy(CP);
const c2=new THREE.Group();c2.add(centriole());c2.position.copy(CP).add(V(.32,.18,.1));c2.rotation.set(Math.PI/2,0,.3);
const halo=new THREE.Mesh(new THREE.SphereGeometry(.62,24,16),M(0xfde047,{opacity:.1,roughness:1}));halo.position.copy(CP).add(V(.16,.09,.05));
piece(P10,c1,{amp:.03,spin:.2,pick:true});piece(P10,c2,{amp:.03,spin:.2,pick:true});piece(P10,halo,{amp:.02,pick:true});
P10.anchor.copy(CP);

/* 11 cytoskeleton */
const P11=part('Cytoskeleton',0xa5b4fc,"The cytoskeleton is a web of protein threads that holds the cell's shape and works like roads.","Motor proteins walk along these threads carrying cargo, like trucks on a highway.",6,0);
const mtM=M(0xa5b4fc,{opacity:.75,emissiveIntensity:.45}),acM=M(0xf0abfc,{opacity:.55,emissiveIntensity:.4});
const push=q=>{if(q.distanceTo(C)<NR+.35)q.sub(C).setLength(NR+.45).add(C);return q};
for(let k=0;k<24;k++){const e=randDir().multiplyScalar(4.8),pts=[CP.clone()];for(let j=1;j<4;j++)pts.push(push(CP.clone().lerp(e,j/4).add(randDir().multiplyScalar(.45))));pts.push(e);const cv=new THREE.CatmullRomCurve3(pts);if(!k)P11.anchor.copy(cv.getPoint(.6));piece(P11,new THREE.Mesh(new THREE.TubeGeometry(cv,48,.026,4),mtM),{mode:'grow',amp:.03})}
for(let k=0;k<26;k++){const a=randDir(),b=a.clone().add(randDir().multiplyScalar(1.1)).normalize(),pts=[];for(let j=0;j<6;j++)pts.push(a.clone().lerp(b,j/5).normalize().multiplyScalar(4.72+rr(-.08,.05)));piece(P11,new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts),40,.016,4),acM),{mode:'grow',amp:.03})}

/* cytoplasm sparkles */
const pg=new THREE.BufferGeometry(),pa=new Float32Array(1500);
for(let i=0;i<500;i++){const p=randDir().multiplyScalar(Math.cbrt(rnd())*4.7);pa[i*3]=p.x;pa[i*3+1]=p.y;pa[i*3+2]=p.z}
pg.setAttribute('position',new THREE.BufferAttribute(pa,3));
const dust=new THREE.Points(pg,new THREE.PointsMaterial({color:0xbfe3ff,size:.04,transparent:true,opacity:.45,depthWrite:false}));cell.add(dust);

const pickables=[];
parts.forEach(P=>{const s=new Set();P.g.traverse(o=>{if(o.isMesh){o.userData.part=P.i;pickables.push(o);s.add(o.material)}});P.mats=[...s]});

/* UI */
const labEls=[],chipEls=[];
parts.forEach(P=>{
 const b=document.createElement('button');b.className='tag';b.innerHTML=`<i style="background:${P.hex}"></i>${P.name}`;b.addEventListener('click',()=>selectPart(P.i));$('labels').appendChild(b);labEls.push(b);
 const c=document.createElement('button');c.className='chip off';c.innerHTML=`<i style="background:${P.hex}"></i>${P.name}`;c.addEventListener('click',()=>selectPart(P.i));$('chips').appendChild(c);chipEls.push(c);
});
const ICON_PLAY='<svg viewBox="0 0 24 24" width="22" height="22"><path d="M7 5l12 7-12 7z" fill="currentColor"/></svg>';
const ICON_PAUSE='<svg viewBox="0 0 24 24" width="22" height="22"><path d="M6 5h4v14H6zM14 5h4v14h-4z" fill="currentColor"/></svg>';

let buildT=-.8,playing=true,sel=null,fly=null,cutOn=false,showLabels=true,scrubbing=false,cardKey='',lastCount=-1,hintTimer=0;
let demo=location.hash==='#demo',dT=0,dIdx=0,dScrub=false;
if(demo)$('demo').hidden=false;
function setPlay(){$('play').innerHTML=playing?ICON_PAUSE:ICON_PLAY}
setPlay();

function anchorOf(P){return P.labPc?P.labPc.o.getWorldPosition(tA):tA.copy(P.anchor)}
function targetOf(P){
 if(P.multi){let best=null,bd=1e9;for(const pc of P.pieces){if(!pc.o.visible)continue;const w=pc.o.getWorldPosition(V());if(plane.distanceToPoint(w)<0)continue;const d=w.distanceTo(camera.position);if(d<bd){bd=d;best=w}}if(best)return best}
 return (P.focus||P.anchor).clone();
}
function flyTo(tg,dist,outward){
 let dir=outward?tg.clone().normalize():camera.position.clone().sub(controls.target).normalize();
 if(dir.lengthSq()<.5)dir.set(0,0,1);
 if(cutOn){const no=plane.normal.clone().negate();if(dir.dot(no)<.35)dir.addScaledVector(no,1.2).normalize()}
 fly={t:0,d:1.5,p0:camera.position.clone(),t0:controls.target.clone(),t1:tg.clone(),p1:tg.clone().addScaledVector(dir,dist)};
}
function selectPart(i,point){
 const P=parts[i];if(!P||P.rev<.5)return;
 sel=i;flyTo(point||targetOf(P),P.dist,i===0);controls.autoRotate=false;
 const c=chipEls[i],ch=$('chips');ch.scrollTo({left:c.offsetLeft-ch.clientWidth/2+c.offsetWidth/2,behavior:'smooth'});
}
function goHome(){sel=null;flyTo(V(),fitDist(),false);controls.autoRotate=true}
function rebuild(){buildT=-.6;playing=true;sel=null;setPlay();goHome()}
function setCut(on){
 cutOn=on;$('cut').checked=on;
 if(on){const n=camera.position.clone();if(n.lengthSq()<.01)n.set(0,0,1);plane.normal.copy(n.normalize()).negate();if(plane.constant>6)plane.constant=6.5}
}
function showHint(){$('hint').classList.add('show');clearTimeout(hintTimer);hintTimer=setTimeout(()=>$('hint').classList.remove('show'),5000)}

$('play').addEventListener('click',()=>{if(playing)playing=false;else{if(buildT>=N)buildT=-.3;playing=true;sel=null}setPlay()});
$('rebuild').addEventListener('click',rebuild);
$('home').addEventListener('click',goHome);
$('lbl').addEventListener('click',()=>{showLabels=!showLabels;$('lbl').classList.toggle('on',showLabels)});
$('cut').addEventListener('change',e=>setCut(e.target.checked));
const scrub=$('scrub');
scrub.addEventListener('pointerdown',()=>{scrubbing=true});
window.addEventListener('pointerup',()=>{scrubbing=false});
window.addEventListener('pointercancel',()=>{scrubbing=false});
scrub.addEventListener('input',()=>{buildT=scrub.value/100;playing=false;setPlay()});

/* demo ends on any real touch */
function endDemo(){demo=false;dScrub=false;$('demo').hidden=true}
window.addEventListener('pointerdown',e=>{if(demo&&e.isTrusted)endDemo()},true);
const dSteps=[[0,rebuild],[8.7,()=>selectPart(7)],[11.2,()=>selectPart(6)],[13.4,()=>setCut(true)],[14.6,()=>selectPart(1)],[17,goHome],[18,()=>{dScrub=true;playing=false;setPlay()}],[19.6,()=>{dScrub=false;setCut(false)}]];
function demoStep(dt){dT+=dt;while(dIdx<dSteps.length&&dT>=dSteps[dIdx][0]){dSteps[dIdx][1]();dIdx++}if(dScrub)buildT=Math.max(5,buildT-dt*5);if(dT>=21){dT=0;dIdx=0}}

/* picking */
const ray=new THREE.Raycaster(),ndc=new THREE.Vector2();
function shown(o){for(;o;o=o.parent)if(!o.visible)return false;return true}
function pick(x,y){
 const W=innerWidth,H=innerHeight;ndc.set(x/W*2-1,-(y/H)*2+1);ray.setFromCamera(ndc,camera);
 let mh=null;
 for(const h of ray.intersectObjects(pickables,false)){const pi=h.object.userData.part;if(parts[pi].rev<.5||!shown(h.object)||plane.distanceToPoint(h.point)<0)continue;if(pi===0){mh=mh||h;continue}const pc=h.object.userData.pc;return{pi,point:pc&&pc.pick?pc.o.getWorldPosition(V()):h.point.clone()}}
 let best=null,bd=34*34;
 for(const P of parts){if(P.i===0||P.rev<.5)continue;for(const pc of P.pieces){if(!pc.pick||!pc.o.visible)continue;const w=pc.o.getWorldPosition(V());if(plane.distanceToPoint(w)<0)continue;tB.copy(w).project(camera);if(tB.z>1)continue;const dx=(tB.x+1)/2*W-x,dy=(1-tB.y)/2*H-y,d=dx*dx+dy*dy;if(d<bd){bd=d;best={pi:P.i,point:w}}}}
 return best||(mh&&{pi:0,point:mh.point.clone()});
}
const cvs=renderer.domElement,downs=new Set();let tap=null;
cvs.addEventListener('pointerdown',e=>{downs.add(e.pointerId);tap=downs.size===1?{x:e.clientX,y:e.clientY,t:performance.now()}:null;fly=null;controls.autoRotate=false});
cvs.addEventListener('pointerup',e=>{downs.delete(e.pointerId);if(tap&&downs.size===0){const dx=e.clientX-tap.x,dy=e.clientY-tap.y;if(dx*dx+dy*dy<144&&performance.now()-tap.t<600){const r=pick(e.clientX,e.clientY);if(r)selectPart(r.pi,r.point)}}if(!downs.size)tap=null});
cvs.addEventListener('pointercancel',e=>{downs.delete(e.pointerId);tap=null});

/* layout */
function fitDist(){const w=innerWidth,h=innerHeight,ph=$('panel').offsetHeight+12,th=$('top').offsetHeight,t=Math.tan(camera.fov*Math.PI/360);return 5.5/Math.sin(Math.atan(Math.min(t*Math.max(.3,(h-ph-th)/h),t*w/h)))}
function resize(){const w=innerWidth,h=innerHeight;renderer.setSize(w,h,false);camera.aspect=w/h;const ph=$('panel').offsetHeight+12,th=$('top').offsetHeight;camera.setViewOffset(w,h,0,(ph-th)/2,w,h);camera.updateProjectionMatrix();controls.maxDistance=Math.max(30,fitDist()*1.8)}
window.addEventListener('resize',resize);
resize();
camera.position.copy(V(.35,.35,1).normalize().multiplyScalar(fitDist()));

/* card */
function updCard(){
 let k;if(sel!=null)k='s'+sel;else if(buildT<0)k='e';else if(buildT<N)k='b'+Math.floor(buildT);else k='d';
 if(k===cardKey)return;cardKey=k;
 let P=parts[0],name,text,fact='',step,col;
 if(k[0]==='s'){P=parts[sel];name=P.name;text=P.text;fact='Did you know? '+P.fact;step=sel?'Part '+sel+' of '+N:'Outer skin'}
 else if(k==='e'){name='An empty cell';text='This see-through bubble is the cell membrane. Watch the parts arrive one at a time!';step='0 of '+N}
 else if(k[0]==='b'){const i=Math.floor(buildT)+1;P=parts[i];name=P.name;text=P.text;step='Part '+i+' of '+N}
 else{name='Your cell is complete!';text='Drag to spin it, pinch to zoom, and tap any part to fly to it and see what it does.';step=N+' of '+N;col='#ffffff'}
 $('dot').style.background=col||P.hex;$('dot').style.color=col||P.hex;
 $('cname').textContent=name;$('ctext').textContent=text;$('cfact').textContent=fact;$('cstep').textContent=step;
 const cd=$('card');cd.classList.remove('pop');void cd.offsetWidth;cd.classList.add('pop');
}

/* loop */
const clock=new THREE.Clock();
function loop(){
 requestAnimationFrame(loop);
 const dt=Math.min(clock.getDelta(),.05),t=clock.elapsedTime;
 if(demo)demoStep(dt);
 if(playing){buildT+=dt*(demo?1.45:1/1.8);if(buildT>=N){buildT=N;playing=false;setPlay();showHint()}}
 if(!scrubbing){const v=Math.round(clamp(buildT,0,N)*100);if(+scrub.value!==v)scrub.value=v}
 scrub.style.setProperty('--p',(scrub.value/(N*100)*100)+'%');
 plane.constant+=((cutOn?0:9)-plane.constant)*Math.min(1,dt*2.2);
 memMat.uniforms.uTime.value=t;
 dust.rotation.y=t*.02;dust.rotation.x=Math.sin(t*.1)*.1;
 if(sel!=null&&parts[sel].rev<.5)sel=null;
 let built=0;
 for(const P of parts){
  const rv=P.i===0?1:clamp(buildT-(P.i-1));
  if(rv>0&&P.rev<=0&&P.i)P.flash=1;
  P.rev=rv;if(P.i&&rv>=.5)built++;
  P.g.visible=rv>0;
  P.flash*=Math.exp(-dt*1.6);
  const hl=(sel===P.i?.35+.25*Math.sin(t*4):0)+P.flash*.8;
  for(const m of P.mats){if(m.isShaderMaterial)m.uniforms.uOp.value=1+hl*.8;else m.emissiveIntensity=m.userData.ei+hl}
  if(!P.g.visible)continue;
  const n=P.pieces.length;
  P.pieces.forEach((pc,k)=>{
   const st=n>1?k/n*.55:0,lp=clamp((rv-st)/(n>1?.45:1)),o=pc.o,ph=pc.ph,pul=1+Math.sin(t*1.7+ph)*P.pulse;
   if(pc.mode==='mem'){o.scale.setScalar(1+Math.sin(t*.8)*.008);return}
   if(pc.mode==='inst'){o.count=Math.floor(pc.n*lp);o.visible=o.count>0;o.rotation.set(Math.sin(t*.13)*.03,Math.sin(t*.1)*.04,0);return}
   if(pc.mode==='ves'){const f=(t*pc.sp+ph/6.283)%1,u=1-f;o.position.set(0,0,0).addScaledVector(pc.a,u*u).addScaledVector(pc.m,2*u*f).addScaledVector(pc.e,f*f);const e=easeBack(lp)*clamp(Math.min(f,1-f)*8)*pul;o.scale.setScalar(Math.max(e,1e-4));o.visible=e>.01;return}
   o.position.set(pc.bp.x+Math.sin(t*.5+ph)*pc.amp,pc.bp.y+Math.sin(t*.43+ph*1.3)*pc.amp,pc.bp.z+Math.cos(t*.37+ph)*pc.amp);
   if(pc.spin)o.rotation.set(pc.br.x+Math.sin(t*.3+ph)*pc.spin,pc.br.y+Math.sin(t*.23+ph)*pc.spin,pc.br.z);
   if(pc.mode==='grow'){const g=o.geometry;g.setDrawRange(0,Math.floor(g.index.count*lp/6)*6);o.visible=lp>0;return}
   const e=easeBack(lp);o.visible=e>.001;o.scale.copy(pc.bs).multiplyScalar(Math.max(e,1e-4)*pul);
  });
 }
 if(built!==lastCount){lastCount=built;$('count').textContent=built+' / '+N+' parts'}
 if(fly){fly.t+=dt;const k=easeIO(clamp(fly.t/fly.d));controls.target.lerpVectors(fly.t0,fly.t1,k);camera.position.lerpVectors(fly.p0,fly.p1,k);if(fly.t>=fly.d)fly=null}
 controls.update();
 const W=innerWidth,H=innerHeight;
 parts.forEach((P,i)=>{
  const el=labEls[i];let show=showLabels&&P.rev>.6;
  if(show){const w=anchorOf(P);if(plane.distanceToPoint(w)<0)show=false;else{tB.copy(w).project(camera);if(tB.z>1||Math.abs(tB.x)>1.1||Math.abs(tB.y)>1.1)show=false;else el.style.transform=`translate(${((tB.x+1)/2*W).toFixed(1)}px,${((1-tB.y)/2*H).toFixed(1)}px) translate(-50%,calc(-100% - 8px))`}}
  el.style.opacity=show?1:0;el.style.pointerEvents=show?'auto':'none';
  el.classList.toggle('new',P.flash>.15);el.classList.toggle('sel',sel===i);
  chipEls[i].classList.toggle('off',P.rev<.5);chipEls[i].classList.toggle('sel',sel===i);
 });
 updCard();
 renderer.render(scene,camera);
}
loop();
</script>
</body>
</html>