import {takeBrainFocus} from './brain-focus.js?v=brain-circuit-47'; import * as THREE from './vendor/three.module.js'; import {$,api,state,card,escape} from './common.js'; let meshPromise; export const brainMesh=()=>meshPromise??=fetch('/static/brain-model.json').then(r=>{if(!r.ok)throw Error('Brain geometry is unavailable.');return r.json()}); const palette={frontal:'#d6ae68',parietal:'#ad96cf',temporal:'#80b3ce',occipital:'#70b79d'}; const location={cortex:[-45,-20,45],frontal:[-42,40,20],parietal:[-40,-35,55],occipital:[-28,-84,17],temporal:[-55,-15,-5],motor:[-39,-10,55],sensory:[-42,-25,55],association:[-46,-42,32],broca:[-48,20,12],wernicke:[-50,-40,6],angular:[-42,-54,36],hippocampus:[-25,-27,-10],amygdala:[-23,3,-12],limbic:[-23,-17,-12],thalamus:[-9,-14,8],basal:[-19,1,12],callosum:[0,-9,29],cerebellum:[-23,-62,-30],brainstem:[0,-36,-44],medulla:[0,-41,-61],ras:[0,-37,-38],pons:[0,-32,-39],hypothalamus:[0,-3,-8],pituitary:[0,8,-28],pineal:[0,-30,9],chiasm:[0,12,-19],ventricles:[-7,-12,20]}; function point(p){return new THREE.Vector3(p[0]/90,(p[2]-8)/90,-(p[1]+20)/90)} export async function brainScene(canvas,{onSelect=()=>{},simple=false}={}){ const model=await brainMesh();if(!canvas.isConnected)return {destroy(){},mode(){},select(){},reset(){},labels(){}}; const renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:false});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setClearColor('#132a29');renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.15; const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(37,1,.1,100);camera.position.set(0,.15,4.8);camera.lookAt(0,0,0); scene.add(new THREE.HemisphereLight('#fff5dc','#345b5c',2.5));const lamp=new THREE.DirectionalLight('#fff4de',3.5);lamp.position.set(-3,4,5);scene.add(lamp);const rim=new THREE.DirectionalLight('#86b4d5',2);rim.position.set(4,1,-3);scene.add(rim); const brain=new THREE.Group();scene.add(brain);brain.rotation.set(.05,1.35,0); const pickable=[],hemispheres=[],deep=[],materials=[],geometries=[],sprites=[];let alive=true,mode='outside',selected='frontal',showLabels=false,raf,drag=null,autoorbit=false,cortexOpacity=1,spread=.8,isolated=false,route=null,routeDot=null; function material(color,opts={}){const m=new THREE.MeshStandardMaterial({color,roughness:.66,metalness:.05,...opts});materials.push(m);return m} function addMesh(id,geometry,color,isDeep=true){geometries.push(geometry);const mesh=new THREE.Mesh(geometry,material(color));mesh.userData={id,deep:isDeep};brain.add(mesh);pickable.push(mesh);if(isDeep)deep.push(mesh);return mesh} for(let side=0;side<2;side++){ const start=side*model.hemisphere_count,end=start+model.hemisphere_count,positions=new Float32Array(model.hemisphere_count*3),colors=new Float32Array(positions.length); for(let i=start;if[0]>=start&&f[0]f.map(v=>v-start)),g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(positions,3));g.setAttribute('color',new THREE.BufferAttribute(colors,3));g.setIndex(indices);g.computeVertexNormals();geometries.push(g); const normals=g.getAttribute('normal'),sum=new Float32Array(positions.length),counts=new Uint16Array(model.hemisphere_count),shade=new Float32Array(model.hemisphere_count);for(let j=0;j.9&&!['cerebellum','brainstem','pons','medulla'].includes(mesh.userData.id)?.12:1} for(const mesh of hemispheres){mesh.visible=mode!=='half'||mesh.userData.start===0;mesh.position.x=mode==='split'?(mesh.userData.start?spread:-spread):0;mesh.material.opacity=(mode==='inside'?.11:isolated?.2:1)*cortexOpacity;mesh.material.depthWrite=mesh.material.opacity>.9;const colors=mesh.geometry.getAttribute('color');for(let i=0;ip.id===id)?.view==='inner'&&!['cerebellum','brainstem','medulla','pons','ras'].includes(id))mode='inside';recolor();if(notify)onSelect(id)} const down=e=>{canvas.setPointerCapture(e.pointerId);drag={x:e.clientX,y:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:false}}; const move=e=>{if(!drag)return;const dx=e.clientX-drag.lastX,dy=e.clientY-drag.lastY;brain.rotation.y+=dx*.007;brain.rotation.x=Math.max(-1.3,Math.min(1.3,brain.rotation.x+dy*.007));drag.moved ||=Math.hypot(e.clientX-drag.x,e.clientY-drag.y)>5;drag.lastX=e.clientX;drag.lastY=e.clientY}; const up=e=>{if(drag&&!drag.moved){const r=canvas.getBoundingClientRect();pointer.set((e.clientX-r.left)/r.width*2-1,-(e.clientY-r.top)/r.height*2+1);raycaster.setFromCamera(pointer,camera);const objects=pickable.filter(o=>o.visible&&(mode!=='inside'||o.userData.deep));const hit=raycaster.intersectObjects(objects,false)[0];if(hit){let id=hit.object.userData.id;if(id==='cortex'&&hit.face)id=model.regions[hit.object.userData.start+hit.face.a];select(id)}}drag=null}; const wheel=e=>{e.preventDefault();camera.position.z=Math.max(3,Math.min(8,camera.position.z+e.deltaY*.003))};canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointermove',move);canvas.addEventListener('pointerup',up);canvas.addEventListener('pointercancel',()=>drag=null);canvas.addEventListener('wheel',wheel,{passive:false}); function reset(){brain.rotation.set(.05,1.35,0);camera.position.z=4.8;mode='outside';selected='frontal';cortexOpacity=1;isolated=false;autoorbit=false;recolor();onSelect(selected)} const key=e=>{if(e.key==='ArrowLeft')brain.rotation.y-=.15;else if(e.key==='ArrowRight')brain.rotation.y+=.15;else if(e.key==='ArrowUp')brain.rotation.x-=.1;else if(e.key==='ArrowDown')brain.rotation.x+=.1;else if(e.key==='+'||e.key==='=')camera.position.z=Math.max(3,camera.position.z-.3);else if(e.key==='-')camera.position.z=Math.min(8,camera.position.z+.3);else return;e.preventDefault()};canvas.addEventListener('keydown',key); function setRoute(ids,animate=true){if(route){brain.remove(route.group);route.group.children.forEach(o=>{o.geometry?.dispose();o.material?.dispose()})}route=null;routeDot=null;if(!ids?.length)return;const curve=new THREE.CatmullRomCurve3(ids.map(id=>point(location[id]))),group=new THREE.Group();const wire=new THREE.Mesh(new THREE.TubeGeometry(curve,80,.009,8,false),new THREE.MeshBasicMaterial({color:'#f2ca78',transparent:true,opacity:.7,depthTest:false}));group.add(wire);routeDot=new THREE.Mesh(new THREE.SphereGeometry(.035,16,12),new THREE.MeshBasicMaterial({color:'#fff4b5',depthTest:false}));group.add(routeDot);brain.add(group);routeDot.visible=animate;route={curve,group,animate};} let lastW=0,lastH=0,lastTime=performance.now();function render(t=performance.now()){const dt=Math.min(.05,(t-lastTime)/1000);lastTime=t;if(autoorbit&&!drag)brain.rotation.y+=dt*.28;if(route&&routeDot&&route.animate)routeDot.position.copy(route.curve.getPoint((t/3500)%1));if(!alive)return;const r=canvas.getBoundingClientRect();if(r.width!==lastW||r.height!==lastH){lastW=r.width;lastH=r.height;renderer.setSize(r.width,r.height,false);camera.aspect=r.width/r.height;camera.updateProjectionMatrix()}renderer.render(scene,camera);raf=requestAnimationFrame(render)}recolor();render(); return {getMode(){return mode},opacity(v){cortexOpacity=v;recolor()},spread(v){spread=v;recolor()},isolate(v){isolated=v;recolor()},orbit(v){autoorbit=v},route:setRoute,viewpoint(v){const poses={left:[.05,1.57,0],right:[.05,-1.57,0],front:[0,Math.PI,0],back:[0,0,0],top:[Math.PI/2,0,0]};brain.rotation.set(...poses[v]);},zoom(v){camera.position.z=Math.max(3,Math.min(8,camera.position.z+v))},select,mode(v){mode=v;if(v==='split')brain.rotation.set(.08,.1,0);if(v==='half')brain.rotation.set(.05,-1.4,0);recolor()},labels(v){showLabels=v;recolor()},reset,rotate(){brain.rotation.y+=.18},destroy(){setRoute(null);alive=false;cancelAnimationFrame(raf);canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointermove',move);canvas.removeEventListener('pointerup',up);canvas.removeEventListener('wheel',wheel);canvas.removeEventListener('keydown',key);for(const g of geometries)g.dispose();for(const m of materials)m.dispose();for(const s of sprites){s.material.map.dispose();s.material.dispose()}renderer.dispose()}}; } const routes={ vision:{name:'See → decide → move',ids:['thalamus','occipital','association','frontal','motor'],notes:['Sensory information is relayed and processed.','Visual areas analyze the input.','Information is combined with context.','Goals and plans influence the response.','Motor systems help produce an action.']}, memory:{name:'See → form a memory',ids:['occipital','association','hippocampus','frontal'],notes:['A visual event is processed.','Features are linked with meaning and context.','The hippocampus helps form new explicit memories.','Goal-directed use and retrieval involve wider systems.']}, movement:{name:'Plan → select → coordinate',ids:['frontal','basal','motor','cerebellum','brainstem'],notes:['A goal shapes a movement plan.','Action-selection circuits contribute.','Motor cortex contributes to voluntary movement.','The cerebellum contributes to timing and coordination.','Brainstem pathways connect brain and body.']} }; export async function explorer(root){ root.innerHTML=card('A brain you can turn, open, and investigate.',`

Use the views to get your bearings, open the hemispheres to see deeper structures, or follow an illustrated route. Click a colored region or choose one of the 27 parts below.

DRAG TO TURN · SCROLL TO ZOOM · CLICK TO IDENTIFYANATOMICAL CORTEX · SCHEMATIC INTERNAL STRUCTURES
FOLLOW A SIGNAL · ILLUSTRATED

How might the parts work together?

The moving dot illustrates connections between teaching landmarks. It is not recorded activity or a complete neural pathway.

FIND A PART

Can you identify it from its role?

Start a challenge, then click a structure or choose its name from the list.

${state.anatomy.map(p=>``).join('')}

The folded cortex is the standard fsaverage5 anatomical surface. Sulcal shading follows the mesh curvature. Lobe boundaries, functional locations, internal shapes, and routes are schematic teaching guides. A region can support several functions, and broad systems overlap with individual parts.

`,'27 PARTS · GUIDED ROUTES · LOCATION CHALLENGES'); const $=s=>root.querySelector(s),canvas=$('#brain-3d'),detail=$('#brain-3d-detail');let alive=true,challenge=null,routeId=null,routeStep=0; function syncMode(){root.querySelectorAll('[data-brain-mode]').forEach(b=>b.classList.toggle('selected',b.dataset.brainMode===view.getMode()))} function describe(id){if(!alive)return;syncMode();const p=state.anatomy.find(p=>p.id===id);if(!p)return;detail.innerHTML=`PART ${p.number} OF 27 · ${p.view==='inner'?'DEEPER STRUCTURE / SYSTEM':'CORTICAL REGION'}

${escape(p.name)}

In a human brain: ${escape(p.biology)}

In this lab’s software analogy: ${escape(p.analogy)}

The highlighted location is a teaching landmark. Complex functions involve wider networks.

`;root.querySelectorAll('[data-brain-part]').forEach(b=>b.classList.toggle('selected',b.dataset.brainPart===id));if(challenge){if(id===challenge.id){$('#brain-quiz-feedback').textContent='You found it: '+p.name+'. '+p.biology;challenge=null;$('#brain-quiz-reveal').disabled=true}else $('#brain-quiz-feedback').textContent=p.name+' has a different role. Read its explanation and try another structure.'}} const view=await brainScene(canvas,{onSelect:describe});if(!canvas.isConnected)return()=>view.destroy();describe('frontal'); root.querySelectorAll('[data-brain-mode]').forEach(b=>b.onclick=()=>{view.mode(b.dataset.brainMode);syncMode()});root.querySelectorAll('[data-brain-part]').forEach(b=>b.onclick=()=>view.select(b.dataset.brainPart)); $('#brain-home').onclick=()=>{view.reset();$('#brain-opacity').value=100;$('#brain-opacity-value').textContent='100%';$('#brain-isolate').checked=$('#brain-orbit').checked=false;$('#brain-viewpoint').value='left';view.route(null);routeId=null;$('#brain-route-next').disabled=true}; $('#brain-labels').onchange=e=>view.labels(e.target.checked);$('#brain-orbit').onchange=e=>view.orbit(e.target.checked);$('#brain-isolate').onchange=e=>view.isolate(e.target.checked);$('#brain-viewpoint').onchange=e=>view.viewpoint(e.target.value);$('#brain-opacity').oninput=e=>{$('#brain-opacity-value').textContent=e.target.value+'%';view.opacity(Number(e.target.value)/100)};$('#brain-spread').oninput=e=>{$('#brain-spread-value').textContent=e.target.value;view.spread(Number(e.target.value));view.mode('split');syncMode()};$('#brain-zoom-in').onclick=()=>view.zoom(-.35);$('#brain-zoom-out').onclick=()=>view.zoom(.35); function routeShow(){const r=routes[routeId];view.route(r.ids);view.mode('inside');view.select(r.ids[routeStep]);$('#brain-route-note').textContent=`Step ${routeStep+1} / ${r.ids.length}: ${state.anatomy.find(p=>p.id===r.ids[routeStep]).name}. ${r.notes[routeStep]} This route is an illustration.`;$('#brain-route-next').textContent=routeStep===r.ids.length-1?'Start route again':'Next step';$('#brain-route-next').disabled=false} $('#brain-route-start').onclick=()=>{challenge=null;routeId=$('#brain-route').value;routeStep=0;routeShow()};$('#brain-route-next').onclick=()=>{if(!routeId)return;routeStep=(routeStep+1)%routes[routeId].ids.length;routeShow()};$('#brain-route-clear').onclick=()=>{view.route(null);routeId=null;$('#brain-route-next').disabled=true;$('#brain-route-note').textContent='Route cleared. The dots represent an illustrated route, not recorded brain activity.'}; $('#brain-quiz-start').onclick=()=>{view.route(null);routeId=null;$('#brain-route-next').disabled=true;const choices=state.anatomy.filter(p=>['frontal','occipital','parietal','temporal','hippocampus','amygdala','thalamus','callosum','cerebellum','pons','hypothalamus','ventricles'].includes(p.id));challenge=choices[Math.floor(Math.random()*choices.length)];$('#brain-quiz-question').textContent='Find the structure with this role: '+challenge.biology;$('#brain-quiz-feedback').textContent='Select a region on the model or a name below. You can open the brain and rotate it.';$('#brain-quiz-reveal').disabled=false;$('#brain-labels').checked=false;view.labels(false)}; $('#brain-quiz-reveal').onclick=()=>{if(!challenge)return;const id=challenge.id;challenge=null;view.select(id);$('#brain-quiz-feedback').textContent='Answer: '+state.anatomy.find(p=>p.id===id).name+'. Try a new challenge when ready.';$('#brain-quiz-reveal').disabled=true};$('#brain-part-search').oninput=e=>{const q=e.target.value.toLowerCase();for(const p of state.anatomy)root.querySelector(`[data-brain-part="${p.id}"]`).hidden=!(p.name+' '+p.biology).toLowerCase().includes(q)}; const requestedPart=takeBrainFocus();if(requestedPart&&location[requestedPart]){view.mode('inside');view.select(requestedPart);syncMode();} return()=>{alive=false;view.destroy()}; }