My son is in 6th grade, and lately he has a lot of exams across different subjects. To help him prepare, we take pictures of the pages from his study book and turn them into a cheat sheet with AI’s help.
A cheat sheet is still a wall of text, so I wanted to try something more visual: seeing the material instead of only reading it. I opened Claude Code and wrote:
Look at ~/Downloads/cheat-sheet.pdf, create HTML WebGL so that my son can easily learn graphically, it should be animated, and all content should be captured, add navigation keys for different scenes so he can set his pace
The result was a single HTML file with an animated 3D scene for each chapter. It links textual answers to visual models, which makes the material click. He moves at his own pace with the arrow keys, and a quiz mode hides the answer until he presses Space.
Since he said he found it easier to study this way, I turned it into a skill, which you can find below. It even plays generated lo-fi study music in the background.
animated-study-page skill
Save these files under ~/.claude/skills/ with the same folder structure.
animated-study-page/SKILL.md
---
name: animated-study-page
description: Turn study material (a PDF cheat sheet, textbook chapter, Q&A list, notes) into a single self-contained animated WebGL (Three.js) HTML learning page for a child/student — one 3D scene per topic, every question and answer captured verbatim, keyboard navigation so the learner sets the pace, quiz mode, and auto-play. Use when the user asks to make learning material "graphical", "animated", "interactive", "3D", or "easy for my kid to learn", or asks for a visual study page from a document, in any language.
---
# Animated study page
Output: ONE `.html` file. A 3D stage sits on the left and a question card on the right; on a phone they stack. The answer lines and the 3D parts light up together.
The full UI and engine are already written: `references/template.html`. It's about 330 lines, tested, and includes a tiny demo scene. **Copy it, then replace only the CONFIG + CONTENT block and the scene builders.** Don't rewrite the engine.
## Workflow (move fast — the user wants a result, not a plan)
1. **Extract all the content.** Read the whole source (`pdftotext -layout` or the pdf skill). Count the items. Keep the wording **verbatim** and in the original language, and keep any review/summary section. Dropping nothing is the main acceptance criterion; check the final count against the source.
2. **Plan chapters and scenes.** Chapter 0 is the intro card (`title:true`), then the topic chapters, then a review chapter last (steps with `rv:0..`). Use one 3D scene per chapter. Scenes are built lazily and reused for every step in that chapter, and `mode` switches the animation for each question.
3. **Copy the template** to the target path. Then fill in:
- `<html lang>`, `<title>`, and the font subset (e.g. `&subset=cyrillic`).
- Every visible string in the HTML: header, hint, cover, nav titles, help table. Also `UI` (labels and counters), `STORE` (a unique localStorage key) and `CHAPTERS` (name, key digit, colour).
- `STEPS` with every item.
- One `buildX(S)` per scene, plus the `BUILD` and `CAMDEF` maps.
4. **Test:** `scripts/check.sh page.html <outdir> start q1 q5 c1 c2 … review1`. Cover every chapter plus the complex questions. Fix every FAIL, then **open the PNGs and look at them**.
5. **Deliver.** Publish as an Artifact, or give the file path. Say what was verified and what wasn't.
Don't stop for questions. Default to the source's language and to the learner age the material implies.
## Step data (documented again at the top of the template)
```js
{ch:1, sc:'cells', n:2, q:'Question verbatim?',
a:[ 'plain line', // "Term – def" auto-bolds Term
['clickable line', ['nucleus','nucL']], // cycles; lights parts + label ids
{flow:[['Mouth',['m']],['Stomach',['s']]]} ], // A → B → C chain (processes, pathways)
mode:'divide', // read by the scene's S.update to choose the animation
focus:['membrane'], // always lit for this step
labels:['memL'], // always-visible labels
cycle:[['a'],['b']], per:3.5, // auto-cycle groups when no line is an array
cam:[tx,ty,tz,dist,yawDeg,pitchDeg]} // optional; else CAMDEF[sc]
```
Split multi-part answers into array lines so that each part lights up its own 3D piece. That synchronisation is what makes the page teach.
## Scene API (`S` given to every builder)
- `S.add(part, obj, hlColor?, parent?)` adds the object and registers its MeshStandardMaterials under `part`. Lit parts glow and pulse; when something is lit, everything else dims. Use `M(color)` materials.
- `S.regMat(part, mat)` registers a material created outside `S.add`. Without it the base colour is unset and highlighting breaks.
- `S.lab(id, text, anchorObj | [x,y,z], 'r'|'l'|'u'|'d', 'big'?)` adds a DOM label that tracks a 3D point. A label is shown when its id is in the active parts or in `labels`.
- `S.flow(curve, n, color, size, speed)` adds particles that move along a curve. Toggle them with `f.on` and reverse them with `f.rev`. Use it for blood, food, air, signals, electricity and water cycles.
- `S.update = ctx => {}` runs every frame. `ctx` provides:
- `mode`
- `st`: seconds since the step started
- `T`: global time, frozen while paused
- `dt`
- `step`
- `ci`: the cycle index. Assign it to make the animation drive which line is lit.
- `p`: progress from 0 to 1 within the cycle.
- Helpers:
- Basic shapes: `ball(r,mat,pos,scale)`, `mesh(geo,mat,pos,scale,rot)`, `limb(a,b,r,mat)` (a capsule between two points).
- Tubes: `tube(pts,r,mat)` and `fatTube(pts,radiusFn,mat)` (a tube whose radius varies along its length).
- Shapes: `lathe([[r,y]..],mat)` makes vases, teeth and bottles, `bean(sx,sy,sz,side)` makes kidney-like shapes, and `curve(pts,closed)`.
- Utilities: `holo(color,opacity)` (fresnel see-through ghost shader, good for a body or shell giving context), `anchor`, `seeded(seed)` rng, `lerp`, and `smooth`.
## Making good scenes
- Make them stylised and readable rather than realistic. Build them from primitives with saturated colours on a dark ground, using roughly 5–15 named parts per scene.
- Put context in a translucent `holo` shell, e.g. a body, a cell membrane or the Earth, with the subject inside it in solid colour.
- Animate the idea, not decoration:
- things that move (a heartbeat, a walk cycle, an orbit, a lever)
- things that flow (`S.flow`)
- things that change (scale, colour, visibility over `ctx.p`)
- For a "compare X vs Y" question, show both side by side. For a sequence, use a `flow` line.
- Show props only in the modes that use them (`obj.visible = c.mode==='x'`). Hide timed props until the animation reaches them.
- The review chapter can be a carousel of mini versions of the earlier scenes (rotate a ring to `step.rv`).
## Keep from the template (already implemented)
- **Keys use `e.code`**, so they work on non-Latin keyboard layouts:
- →/Space/Enter: next (in quiz mode the first press reveals the answer)
- ←: previous; ↑/↓: chapter; 1–9/0: jump to a chapter
- Home/End: first/last step
- Q: quiz; A: auto (15 s); P: pause; R: reset view; M: music; H/?: help; Esc: close help
- Buttons for every key, chapter chips, per-chapter dots, a progress bar and a "Question N of M" counter, computed from the highest `n`.
- Drag rotates and the wheel zooms. The camera eases between steps.
- Hash routes `#start`, `#qN`, `#cN` and `#reviewN`, plus localStorage resume.
- Relaxing study music (♪ button / M), on by default. It's generative lo-fi made with Web Audio: chords, bass, a random gentle melody, a soft beat and vinyl crackle. Nothing is downloaded and there's no YouTube embed (an embed needs a click, can show ads, and breaks when the video is removed). Browsers block sound until a click or key press, so it starts on the first interaction. Turning it off is remembered.
- Three.js r149 UMD from jsDelivr.
## Gotchas
- Keep chapter count ≤ 11 (intro + 9 + review) so the digit keys map 1:1. Otherwise, group chapters.
animated-study-page/references/template.html
<!doctype html>
<html lang="en"><!-- TODO: source language code -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="claude:viewport-fit-sides" content="cover">
<title>Study 3D</title><!-- TODO: 2-4 word title -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<!-- TODO: add &subset=cyrillic / greek / etc. if the source language needs it -->
<link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@600;800&family=Nunito:wght@500;700;800;900&display=swap" rel="stylesheet">
<style>
/* Retheme by editing the tokens on :root. --ch is set per chapter at runtime. */
:root{color-scheme:dark;--bg:#1a0f22;--bg2:#2b1638;--ink:#fff6f0;--soft:#d9c6e6;--muted:#a58fb8;--card:#24132f;--line:#4a2d5c;--hl:#ffd23f;--mint:#5ce1c6;--coral:#ff5d6c;--ch:#ff7a59}
*{box-sizing:border-box;min-width:0}
html,body{height:100%;margin:0}
body{background:var(--bg);color:var(--ink);font:17px/1.5 Nunito,system-ui,sans-serif;overflow:hidden;display:grid;grid-template-rows:auto 1fr auto}
button{font:inherit;color:inherit}
header{display:flex;align-items:center;gap:14px;padding:10px max(2vw,16px,env(safe-area-inset-left,0px));padding-top:calc(10px + env(safe-area-inset-top,0px));border-bottom:1px solid var(--line);background:var(--bg)}
header h1{font:800 16px/1.1 Unbounded,sans-serif;margin:0;white-space:nowrap;letter-spacing:-.01em}
#chips{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;flex:1}
#chips::-webkit-scrollbar{display:none}
.chip{flex:none;border:1px solid var(--line);background:transparent;border-radius:999px;padding:5px 12px;font-size:14px;font-weight:800;white-space:nowrap;cursor:pointer;color:var(--soft)}
.chip kbd{font:700 11px Nunito;opacity:.7;margin-right:5px;border:1px solid currentColor;border-radius:4px;padding:0 4px}
.chip.on{background:var(--c);border-color:var(--c);color:#1a0f22}
.chip:hover{border-color:var(--c)}
main{display:grid;grid-template-columns:minmax(0,1fr) clamp(340px,34vw,500px);min-height:0}
#stage{position:relative;min-height:0;overflow:hidden;background:radial-gradient(ellipse at 50% 45%,#3a1d4a 0%,#21112b 55%,#140a1a 100%);cursor:grab;touch-action:none}
#stage:active{cursor:grabbing}
#stage canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
#labels{position:absolute;inset:0;pointer-events:none;overflow:hidden}
.lab{position:absolute;left:0;top:0;opacity:0;transition:opacity .35s}
.lab.on{opacity:1}
.lab b{position:absolute;width:10px;height:10px;margin:-5px 0 0 -5px;border-radius:50%;background:var(--hl);box-shadow:0 0 0 3px rgba(255,210,63,.3)}
.lab span{position:absolute;top:0;white-space:nowrap;background:rgba(20,10,26,.88);border:1.5px solid var(--hl);color:#fff;font-weight:800;font-size:15px;padding:3px 10px;border-radius:10px;transform:translateY(-50%)}
.lab.r span{left:14px}.lab.l span{right:14px}
.lab.u span{left:0;transform:translate(-50%,calc(-100% - 12px))}
.lab.d span{left:0;transform:translate(-50%,12px)}
.lab.big b{display:none}
.lab.big span{font:800 clamp(20px,2.6vw,34px)/1.1 Unbounded,sans-serif;padding:8px 16px;border-radius:14px;border-width:2px;left:0;transform:translate(-50%,-50%)}
#hint{position:absolute;left:12px;bottom:10px;font-size:13px;color:var(--muted);pointer-events:none}
#paused{position:absolute;right:12px;top:10px;font-weight:900;color:var(--hl);font-size:14px}
aside{border-left:1px solid var(--line);background:var(--card);display:flex;flex-direction:column;min-height:0}
#card{flex:1;overflow-y:auto;padding:22px 24px 18px}
#tag{display:inline-flex;gap:8px;align-items:center;font-weight:900;font-size:14px;color:#1a0f22;background:var(--ch);border-radius:8px;padding:3px 10px}
#count{color:var(--muted);font-weight:800;font-size:14px;margin:12px 0 4px}
#bar{height:6px;background:var(--line);border-radius:3px;overflow:hidden}
#bar i{display:block;height:100%;background:var(--ch);transition:width .4s}
#q{font:800 clamp(21px,1.9vw,27px)/1.22 Nunito,sans-serif;margin:16px 0 14px;letter-spacing:-.01em}
#q.title{font:800 clamp(26px,2.6vw,38px)/1.1 Unbounded,sans-serif}
#ans{position:relative}
#ans .ln{padding:8px 12px;border-radius:12px;margin:0 0 6px;border:1.5px solid transparent;transition:background .3s,border-color .3s;color:var(--soft)}
#ans .ln b{color:var(--ink)}
#ans .ln.on{background:rgba(255,210,63,.12);border-color:var(--hl);color:var(--ink)}
#ans.plain .ln{color:var(--ink)}
.flow{display:flex;flex-wrap:wrap;gap:6px 4px;align-items:center;padding:4px 0}
.flow .it{padding:6px 11px;border-radius:10px;border:1.5px solid var(--line);font-weight:800;font-size:16px;transition:all .3s;color:var(--soft)}
.flow .it.on{background:var(--hl);border-color:var(--hl);color:#1a0f22;transform:scale(1.06)}
.flow .ar{color:var(--muted);font-weight:900}
#cover{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:var(--card);border:2px dashed var(--line);border-radius:14px;cursor:pointer;font-weight:900;color:var(--hl);min-height:90px}
#ans.hide #cover{display:flex}
#ans.hide{min-height:110px}
#dots{display:flex;flex-wrap:wrap;gap:6px;margin-top:18px}
#dots button{width:30px;height:30px;border-radius:8px;border:1px solid var(--line);background:transparent;font-size:12px;font-weight:800;cursor:pointer;color:var(--muted)}
#dots button.on{background:var(--ch);color:#1a0f22;border-color:var(--ch)}
#dots button.seen{color:var(--ink)}
nav{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:center;padding:10px max(2vw,16px,env(safe-area-inset-left,0px));padding-bottom:calc(10px + env(safe-area-inset-bottom,0px));border-top:1px solid var(--line);background:var(--bg)}
nav button{min-height:44px;min-width:44px;border-radius:12px;border:1.5px solid var(--line);background:var(--bg2);font-weight:900;font-size:16px;padding:0 14px;cursor:pointer;display:inline-flex;gap:7px;align-items:center}
nav button:hover{border-color:var(--mint)}
nav button.on{background:var(--mint);color:#1a0f22;border-color:var(--mint)}
nav button.main{background:var(--hl);color:#1a0f22;border-color:var(--hl);padding:0 22px}
nav kbd{font:800 11px Nunito;border:1px solid currentColor;border-radius:4px;padding:0 4px;opacity:.75}
#help{position:fixed;inset:0;background:rgba(10,5,14,.82);display:flex;align-items:center;justify-content:center;z-index:9;padding:20px}
#help[hidden]{display:none}
#help .box{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:24px 28px;max-width:560px;width:100%;max-height:90vh;overflow:auto}
#help h2{font:800 22px Unbounded,sans-serif;margin:0 0 14px}
#help table{width:100%;border-collapse:collapse}
#help td{padding:6px 4px;border-bottom:1px solid var(--line);vertical-align:top}
#help td:first-child{white-space:nowrap;font-weight:900;color:var(--hl);padding-right:14px}
@media (max-width:800px){
body{overflow:auto;display:block}
header h1{display:none}
main{display:flex;flex-direction:column}
#stage{height:50svh;flex:none}
aside{border-left:0;border-top:1px solid var(--line)}
#card{padding:16px max(5vw,16px)}
nav{position:sticky;bottom:0}
nav .opt{display:none}
.lab span{font-size:13px}
}
@media (prefers-reduced-motion:reduce){.lab,.flow .it,#bar i{transition:none}}
</style>
</head>
<body>
<!-- All visible strings below are TODO: translate into the source language. -->
<header>
<h1>Subject 6</h1>
<div id="chips"></div>
</header>
<main>
<div id="stage"><div id="labels"></div><div id="hint">Drag to rotate · wheel to zoom</div><div id="paused" hidden>⏸ PAUSED</div></div>
<aside>
<div id="card">
<span id="tag"></span>
<div id="count"></div>
<div id="bar"><i></i></div>
<h2 id="q"></h2>
<div id="ans"><div id="lines"></div><div id="cover">Think… then press Space for the answer</div></div>
<div id="dots"></div>
</div>
</aside>
</main>
<nav>
<button id="bPrevC" class="opt" title="Previous chapter">▲ <kbd>↑</kbd></button>
<button id="bPrev" title="Previous">◀ Back <kbd>←</kbd></button>
<button id="bNext" class="main" title="Next">Next ▶ <kbd>→</kbd></button>
<button id="bNextC" class="opt" title="Next chapter">▼ <kbd>↓</kbd></button>
<button id="bQuiz" title="Quiz: answer hidden">Quiz <kbd>Q</kbd></button>
<button id="bAuto" class="opt" title="Auto advance">Auto <kbd>A</kbd></button>
<button id="bPause" class="opt" title="Pause animation">⏸ <kbd>P</kbd></button>
<button id="bMusic" title="Relaxing study music">♪ <kbd>M</kbd></button>
<button id="bHelp" title="Help">? <kbd>H</kbd></button>
</nav>
<div id="help" hidden><div class="box">
<h2>Keys</h2>
<table>
<tr><td>→ or Space</td><td>Next question (in quiz mode, first reveals the answer)</td></tr>
<tr><td>←</td><td>Previous question</td></tr>
<tr><td>↓ / ↑</td><td>Next / previous chapter</td></tr>
<tr><td>1 – 9</td><td>Jump to chapter 1–9</td></tr>
<tr><td>0</td><td>Review (last chapter)</td></tr>
<tr><td>Home / End</td><td>First / last</td></tr>
<tr><td>Q</td><td>Quiz mode: answer hidden until you press Space</td></tr>
<tr><td>A</td><td>Auto advance (every 15 seconds)</td></tr>
<tr><td>P</td><td>Pause / resume animation</td></tr>
<tr><td>R</td><td>Reset the 3D view</td></tr>
<tr><td>M</td><td>Relaxing study music (on / off)</td></tr>
<tr><td>Mouse</td><td>Drag to rotate, wheel to zoom. Click an answer line to see it on the model.</td></tr>
<tr><td>H / Esc</td><td>Open / close help</td></tr>
</table>
</div></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.149.0/build/three.min.js"></script>
<script>
{
/* =====================================================================
CONFIG + CONTENT (replace everything in this block)
Answer line forms:
"plain text" -> static line ("Term – def" bolds Term)
["text", ["partA","labelId"]] -> cycles/clickable, lights those parts+labels
{flow:[["A",[parts]],["B",[parts]]]} -> A → B → C chain, each item cycles
Step fields: ch, sc (scene key), n (question number), rv (review index, 0-based),
title:true (intro card), q, a[], mode (read by scene update), focus[] (always lit),
labels[] (always shown), cycle[[parts]..] + per (auto-cycle when no array lines),
cam:[tx,ty,tz,dist,yawDeg,pitchDeg]
===================================================================== */
const UI={welcome:'Welcome',q:'Question',qOf:(n,t)=>`Question ${n} of ${t}`,rOf:(n,t)=>`Review ${n} of ${t}`};
const STORE='study3d-idx'; // TODO: unique localStorage key per page
const CHAPTERS=[ // index 0 = intro, last = review; key shown on the chip
{name:'Start',key:'Home',c:'#5ce1c6'},
{name:'Demo chapter',key:'1',c:'#ff7a59'},
{name:'Review',key:'0',c:'#5ce1c6'}
];
const DEMO='demo';
const STEPS=[
{ch:0,sc:DEMO,title:true,q:'Subject – Grade 6',a:['N questions and answers','Press → (or Space) to start. Press H for all keys.'],mode:'intro'},
{ch:1,sc:DEMO,n:1,q:'What are the parts of the demo model?',a:[['Core – the centre',['core']],['Ring – goes around',['ring']],['Moon – orbits',['moon','moonL']]],mode:'orbit'},
{ch:1,sc:DEMO,n:2,q:'How does something travel along a path?',a:[{flow:[['Start',['core']],['Path',['ring']],['End',['moon']]]}],mode:'flow',cam:[0,0,0,7,30,25]},
{ch:2,sc:DEMO,rv:0,q:'Review',a:['Core – centre; ring – around; moon – orbits.'],focus:['core','ring','moon']},
];
/* ---------- helpers ---------- */
const V3=(x,y,z)=>new THREE.Vector3(x,y,z);
const toV=p=>p.isVector3?p.clone():V3(p[0],p[1],p[2]);
const curve=(pts,closed=false)=>new THREE.CatmullRomCurve3(pts.map(toV),closed,'catmullrom',0.5);
const M=(c,o={})=>new THREE.MeshStandardMaterial(Object.assign({color:c,roughness:.5,metalness:.05},o));
const GLOW=(c)=>new THREE.MeshBasicMaterial({color:c});
const SPH=new THREE.SphereGeometry(1,32,24);
function mesh(geo,mat,pos,scl,rot){const m=new THREE.Mesh(geo,mat);if(pos)m.position.set(pos[0],pos[1],pos[2]);if(scl)(typeof scl==='number'?m.scale.setScalar(scl):m.scale.set(scl[0],scl[1],scl[2]));if(rot)m.rotation.set(rot[0],rot[1],rot[2]);return m}
function ball(r,mat,pos,s){const m=mesh(SPH,mat,pos);m.scale.set(r*(s?s[0]:1),r*(s?s[1]:1),r*(s?s[2]:1));return m}
function tube(pts,r,mat,seg=64,closed=false){const c=curve(pts,closed);const m=new THREE.Mesh(new THREE.TubeGeometry(c,seg,r,10,closed),mat);m.userData.curve=c;return m}
function limb(a,b,r,mat){a=toV(a);b=toV(b);const d=b.clone().sub(a),len=d.length();const m=new THREE.Mesh(new THREE.CapsuleGeometry(r,Math.max(.001,len),6,14),mat);m.position.copy(a).add(b).multiplyScalar(.5);m.quaternion.setFromUnitVectors(V3(0,1,0),d.normalize());return m}
function fatTube(pts,rf,mat,seg=90,rs=18){const c=curve(pts);const g=new THREE.TubeGeometry(c,seg,1,rs,false);const p=g.attributes.position,v=new THREE.Vector3();for(let i=0;i<=seg;i++){const ctr=c.getPointAt(i/seg),r=rf(i/seg);for(let j=0;j<=rs;j++){const k=i*(rs+1)+j;v.fromBufferAttribute(p,k).sub(ctr).multiplyScalar(r).add(ctr);p.setXYZ(k,v.x,v.y,v.z)}}g.computeVertexNormals();const m=new THREE.Mesh(g,mat);m.userData.curve=c;return m}
function bean(sx,sy,sz,side){const g=new THREE.SphereGeometry(1,36,26);const p=g.attributes.position;for(let i=0;i<p.count;i++){let x=p.getX(i),y=p.getY(i),z=p.getZ(i);const m=Math.max(0,-x*side);x+=side*m*m*0.7*(1-y*y);p.setXYZ(i,x*sx,y*sy,z*sz)}g.computeVertexNormals();return g}
function lathe(pr,mat,seg=40,ps=0,pl=Math.PI*2){return new THREE.Mesh(new THREE.LatheGeometry(pr.map(([r,y])=>new THREE.Vector2(r,y)),seg,ps,pl),mat)}
function seeded(s){return()=>(s=s*16807%2147483647)/2147483647}
function lerp(a,b,t){return a+(b-a)*t}
function smooth(t){t=Math.max(0,Math.min(1,t));return t*t*(3-2*t)}
function holo(c=0x9fd8ff,o=.55){return new THREE.ShaderMaterial({uniforms:{c:{value:new THREE.Color(c)},o:{value:o}},vertexShader:'varying vec3 n;varying vec3 v;void main(){vec4 mv=modelViewMatrix*vec4(position,1.);n=normalize(normalMatrix*normal);v=normalize(-mv.xyz);gl_Position=projectionMatrix*mv;}',fragmentShader:'uniform vec3 c;uniform float o;varying vec3 n;varying vec3 v;void main(){float f=pow(1.-abs(dot(normalize(n),normalize(v))),2.4);gl_FragColor=vec4(c,o*(0.05+0.95*f));}',transparent:true,depthWrite:false,blending:THREE.AdditiveBlending})}
/* ---------- scene object: parts (highlight), labels, particle flows ---------- */
const labelsEl=document.getElementById('labels');
function newScene(key){
const S={key,g:new THREE.Group(),mats:[],labels:{},flows:[],anims:[]};
S.reg=(name,obj,hl)=>{if(!name)return obj;obj.traverse(o=>{if(!o.isMesh)return;(Array.isArray(o.material)?o.material:[o.material]).forEach(m=>{if(!m.isMeshStandardMaterial)return;const u=m.userData;if(!u.parts){u.parts=[];u.base=m.color.clone();u.gl=0;u.dm=0;S.mats.push(m)}if(!u.parts.includes(name))u.parts.push(name);if(hl)u.hl=new THREE.Color(hl)})});return obj};
S.regMat=(name,m)=>{if(!name)return;const u=m.userData;if(!u.parts){u.parts=[];u.base=m.color.clone();u.gl=0;u.dm=0;S.mats.push(m)}if(!u.parts.includes(name))u.parts.push(name)};
S.add=(name,obj,hl,parent)=>{(parent||S.g).add(obj);return S.reg(name,obj,hl)};
S.lab=(id,text,anchor,side='r',cls='')=>{let a=anchor;if(Array.isArray(anchor)){a=new THREE.Object3D();a.position.set(anchor[0],anchor[1],anchor[2]);S.g.add(a)}const el=document.createElement('div');el.className='lab '+side+' '+cls;el.innerHTML='<b></b><span></span>';el.lastChild.textContent=text;el.hidden=true;labelsEl.appendChild(el);const L={el,a,set:t=>{if(L.t!==t){L.t=t;el.lastChild.textContent=t}},t:text};S.labels[id]=L;return L};
S.flow=(c,n,color,size=.045,speed=.08,parent)=>{const f={c,ms:[],off:[],speed,on:true,rev:false,mat:GLOW(color)};const g=new THREE.SphereGeometry(size,10,8);for(let i=0;i<n;i++){const s=new THREE.Mesh(g,f.mat);(parent||S.g).add(s);f.ms.push(s);f.off.push(i/n)}S.flows.push(f);return f};
return S;
}
function anchor(parent,pos){const a=new THREE.Object3D();a.position.set(pos[0],pos[1],pos[2]);parent.add(a);return a}
/* ---------- scenes: one builder per scene key ----------
S.add(part,obj,hlColor?) registers materials for highlight/dim;
S.regMat(part,mat) for materials added outside S.add;
S.lab(id,text,anchorObj|[x,y,z],'r'|'l'|'u'|'d', 'big'?) DOM label;
S.flow(curve,n,color,size,speed) particles along a curve (f.on, f.rev);
S.update=ctx=>{...} per frame: ctx.mode, ctx.st (s since step start), ctx.T (global, stops on pause),
ctx.dt, ctx.step, ctx.ci (current cycle index – may be overridden), ctx.p (0..1 within cycle) */
function buildDemo(S){
const core=S.add('core',ball(1,M(0xffb347),[0,0,0]));
S.lab('core','Core',[0,1.1,0],'u');
const ring=S.add('ring',new THREE.Mesh(new THREE.TorusGeometry(2.4,.06,12,90),M(0x5ce1c6)));ring.rotation.x=Math.PI/2;
const piv=new THREE.Group();S.g.add(piv);
const moon=S.add('moon',ball(.32,M(0xb197fc),[2.4,0,0]),null,piv);
S.lab('moonL','Moon',anchor(moon,[0,1.4,0]),'r');
const path=curve([[2.4,0,0],[0,0,2.4],[-2.4,0,0],[0,0,-2.4]],true);
const f=S.flow(path,24,0xffd23f,.05,.12);
S.update=c=>{piv.rotation.y=c.T*.6;core.rotation.y=c.T*.3;f.on=c.mode==='flow';
if(c.mode==='intro')S.g.rotation.y=c.T*.2;else S.g.rotation.y=0};
}
const BUILD={[DEMO]:buildDemo};
const CAMDEF={[DEMO]:[0,0,0,8,0,18]}; // default camera per scene
/* =====================================================================
ENGINE
===================================================================== */
const stage=document.getElementById('stage');
const renderer=new THREE.WebGLRenderer({antialias:true,alpha:true});renderer.setPixelRatio(Math.min(2,devicePixelRatio));stage.prepend(renderer.domElement);
const scene=new THREE.Scene();const camera=new THREE.PerspectiveCamera(40,1,.05,200);
scene.add(new THREE.HemisphereLight(0xfff0f5,0x2a1533,.95));const dl=new THREE.DirectionalLight(0xffffff,.85);dl.position.set(4,8,6);scene.add(dl);const rl=new THREE.DirectionalLight(0x7fd8ff,.5);rl.position.set(-6,2,-6);scene.add(rl);
const scenes={};
const NQ=Math.max(0,...STEPS.map(s=>s.n||0)),NR=STEPS.filter(s=>s.rv!=null).length,LASTCH=CHAPTERS.length-1;
function getScene(k){if(!scenes[k]){const S=newScene(k);BUILD[k](S);scene.add(S.g);scenes[k]=S}return scenes[k]}
const HL=new THREE.Color(0xffd23f);
let idx=0,cur=null,st=0,T=0,paused=false,quiz=false,revealed=true,auto=false,autoT=0;
const cam={t:V3(0,0,0),d:13,y:0,p:5},camGoal={t:V3(),d:13,y:0,p:5},user={y:0,p:0,z:1};
let cycle=[];
function resize(){const r=stage.getBoundingClientRect();renderer.setSize(r.width,r.height,false);camera.aspect=r.width/Math.max(1,r.height);camera.updateProjectionMatrix()}
new ResizeObserver(resize).observe(stage);
const $=id=>document.getElementById(id);
const chipsEl=$('chips');
chipsEl.innerHTML=CHAPTERS.map((c,i)=>`<button class="chip" data-i="${i}" style="--c:${c.c}"><kbd>${c.key}</kbd>${c.name}</button>`).join('');
chipsEl.addEventListener('click',e=>{const b=e.target.closest('.chip');if(b)goChapter(+b.dataset.i)});
const seen=new Set();
function fmt(t){const i=t.indexOf(' – ');if(i>0&&i<40){const b=document.createElement('span');b.innerHTML='<b></b>';b.firstChild.textContent=t.slice(0,i);b.append(' – '+t.slice(i+3));return b}const s=document.createElement('span');s.textContent=t;return s}
function render(){
const s=STEPS[idx],ch=CHAPTERS[s.ch];document.documentElement.style.setProperty('--ch',ch.c);
$('tag').textContent=s.ch===0?UI.welcome:(s.ch===LASTCH&&s.rv!=null?'★ '+ch.name:s.ch+'. '+ch.name);
$('count').textContent=s.n?UI.qOf(s.n,NQ):(s.rv!=null?UI.rOf(s.rv+1,NR):'');
$('bar').firstChild.style.width=(s.n?s.n/NQ*100:(s.rv!=null?100:0))+'%';
const q=$('q');q.textContent=s.q;q.className=s.title?'title':'';
const L=$('lines');L.innerHTML='';cycle=[];
s.a.forEach(line=>{
if(line.flow){const d=document.createElement('div');d.className='flow';line.flow.forEach(([t,p],k)=>{if(k){const a=document.createElement('span');a.className='ar';a.textContent='→';d.appendChild(a)}const it=document.createElement('span');it.className='it';it.textContent=t;d.appendChild(it);cycle.push({parts:p,el:it});it.onclick=()=>pin(cycle.length&&cycle.findIndex(c=>c.el===it))});L.appendChild(d);return}
const d=document.createElement('div');d.className='ln';const txt=Array.isArray(line)?line[0]:line;d.appendChild(fmt(txt));L.appendChild(d);
if(Array.isArray(line)){const k=cycle.length;cycle.push({parts:line[1],el:d});d.style.cursor='pointer';d.onclick=()=>pin(k)}
});
if(!cycle.length&&s.cycle)cycle=s.cycle.map(p=>({parts:p,el:null}));
$('ans').className=(quiz&&!revealed&&!s.title?'hide':'')+(cycle.some(c=>c.el)?'':' plain');
// dots
const same=STEPS.map((x,i)=>[x,i]).filter(([x])=>x.ch===s.ch);
$('dots').innerHTML=same.length>1?same.map(([x,i])=>`<button data-i="${i}" class="${i===idx?'on':''} ${seen.has(i)?'seen':''}" title="${x.n?UI.q+' '+x.n:''}">${x.n||(x.rv!=null?x.rv+1:'•')}</button>`).join(''):'';
[...chipsEl.children].forEach((c,i)=>c.classList.toggle('on',i===s.ch));chipsEl.children[s.ch].scrollIntoView({block:'nearest',inline:'nearest'});
}
$('dots').addEventListener('click',e=>{const b=e.target.closest('button');if(b)go(+b.dataset.i)});
let pinned=-1;function pin(k){pinned=pinned===k?-1:k}
function go(i){
i=Math.max(0,Math.min(STEPS.length-1,i));const prevSc=cur&&cur.key;idx=i;seen.add(i);st=0;pinned=-1;revealed=!quiz;autoT=0;
const s=STEPS[i];const S=getScene(s.sc);
if(cur!==S){Object.values(scenes).forEach(x=>{x.g.visible=x===S;Object.values(x.labels).forEach(l=>{l.el.hidden=x!==S})});cur=S}
const c=s.cam||CAMDEF[s.sc];camGoal.t.set(c[0],c[1],c[2]);camGoal.d=c[3];camGoal.y=c[4]*Math.PI/180;camGoal.p=c[5]*Math.PI/180;user.y=0;user.p=0;user.z=1;
if(prevSc!==s.sc){cam.t.copy(camGoal.t);cam.d=camGoal.d*1.6;cam.y=camGoal.y-.6;cam.p=camGoal.p}
render();
try{history.replaceState(null,'',s.ch===0?'#start':(s.n?'#q'+s.n:'#review'+(s.rv+1)))}catch(e){}
try{localStorage.setItem(STORE,i)}catch(e){}
}
function next(){const s=STEPS[idx];if(quiz&&!revealed&&!s.title){revealed=true;render();return}go(idx+1)}
function prev(){go(idx-1)}
function goChapter(ch){const i=STEPS.findIndex(s=>s.ch===ch);if(i>=0)go(i)}
function chapterStep(d){const ch=Math.max(0,Math.min(LASTCH,STEPS[idx].ch+d));goChapter(ch)}
function toggleQuiz(){quiz=!quiz;revealed=!quiz;$('bQuiz').classList.toggle('on',quiz);render()}
function togglePause(){paused=!paused;$('paused').hidden=!paused;$('bPause').classList.toggle('on',paused)}
function toggleAuto(){auto=!auto;autoT=0;$('bAuto').classList.toggle('on',auto)}
function help(v){$('help').hidden=v===undefined?!$('help').hidden:!v}
$('bNext').onclick=next;$('bPrev').onclick=prev;$('bNextC').onclick=()=>chapterStep(1);$('bPrevC').onclick=()=>chapterStep(-1);$('bQuiz').onclick=toggleQuiz;$('bPause').onclick=togglePause;$('bAuto').onclick=toggleAuto;$('bHelp').onclick=()=>help();$('help').onclick=()=>help(false);$('cover').onclick=()=>{revealed=true;render()};
/* ---------- study music: generative lo-fi (Web Audio, no downloads) ---------- */
const Music=(()=>{let ac,master,on=false,timer=null,next=0,step=0;const MKEY=STORE+'-music';
const CH=[[48,55,59,64],[45,52,55,60],[41,48,52,57],[43,50,55,62]]; // Cmaj7 · Am7 · Fmaj7 · G6
const SC=[60,62,64,67,69,72,74,76,79],BEAT=60/68,fq=m=>440*Math.pow(2,(m-69)/12);
function init(){ac=new (window.AudioContext||window.webkitAudioContext)();master=ac.createGain();master.gain.value=0;
const lp=ac.createBiquadFilter();lp.type='lowpass';lp.frequency.value=1700;
const rev=ac.createConvolver(),len=ac.sampleRate*2.5,b=ac.createBuffer(2,len,ac.sampleRate);for(let c=0;c<2;c++){const d=b.getChannelData(c);for(let i=0;i<len;i++)d[i]=(Math.random()*2-1)*Math.pow(1-i/len,3)}rev.buffer=b;
const wet=ac.createGain();wet.gain.value=.35;master.connect(lp);lp.connect(ac.destination);lp.connect(rev);rev.connect(wet);wet.connect(ac.destination);
const nb=ac.createBuffer(1,ac.sampleRate*3,ac.sampleRate),nd=nb.getChannelData(0);for(let i=0;i<nd.length;i++)nd[i]=(Math.random()<.0006?(Math.random()*2-1)*.5:0)+(Math.random()*2-1)*.01;
const ns=ac.createBufferSource();ns.buffer=nb;ns.loop=true;const nf=ac.createBiquadFilter();nf.type='highpass';nf.frequency.value=1500;ns.connect(nf);nf.connect(master);ns.start()}
function note(m,t,dur,vol,type,att){const g=ac.createGain();g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(vol,t+att);g.gain.exponentialRampToValueAtTime(.0001,t+dur);g.connect(master);
[0,7].forEach(dt=>{const o=ac.createOscillator();o.type=type;o.frequency.value=fq(m);o.detune.value=dt;o.connect(g);o.start(t);o.stop(t+dur+.05)})}
function kick(t){const o=ac.createOscillator(),g=ac.createGain();o.frequency.setValueAtTime(110,t);o.frequency.exponentialRampToValueAtTime(40,t+.18);g.gain.setValueAtTime(.22,t);g.gain.exponentialRampToValueAtTime(.001,t+.3);o.connect(g);g.connect(master);o.start(t);o.stop(t+.32)}
function hat(t){const s=ac.createBufferSource(),bf=ac.createBuffer(1,ac.sampleRate*.05,ac.sampleRate),d=bf.getChannelData(0);for(let i=0;i<d.length;i++)d[i]=Math.random()*2-1;s.buffer=bf;const f=ac.createBiquadFilter();f.type='highpass';f.frequency.value=7000;const g=ac.createGain();g.gain.setValueAtTime(.025,t);g.gain.exponentialRampToValueAtTime(.001,t+.05);s.connect(f);f.connect(g);g.connect(master);s.start(t)}
function sched(){while(next<ac.currentTime+1.3){const ch=CH[Math.floor(step/8)%4],e=step%8,t=next+(e%2?BEAT*.09:0);
if(e===0){ch.forEach(m=>note(m,t,BEAT*4.3,.03,'triangle',.5));note(ch[0]-12,t,BEAT*3.6,.07,'sine',.02)}
if(e===4)note(ch[0]-12,t,BEAT*1.8,.05,'sine',.02);
if(Math.random()<.4){const p=SC.filter(m=>ch.some(c=>(m-c)%12===0)||Math.random()<.3);note(p[Math.floor(Math.random()*p.length)],t,BEAT*1.8,.028,'sine',.015)}
if(e===0||e===5)kick(t);if(e===2||e===6)hat(t);next+=BEAT/2;step++}}
function set(v){on=v;$('bMusic').classList.toggle('on',on);try{localStorage.setItem(MKEY,on?'1':'0')}catch(e){}
if(on){if(!ac)init();ac.resume();next=ac.currentTime+.1;master.gain.cancelScheduledValues(ac.currentTime);master.gain.linearRampToValueAtTime(.8,ac.currentTime+2);if(!timer)timer=setInterval(sched,200)}
else if(ac){master.gain.cancelScheduledValues(ac.currentTime);master.gain.setValueAtTime(master.gain.value,ac.currentTime);master.gain.linearRampToValueAtTime(0,ac.currentTime+.8);clearInterval(timer);timer=null}}
// browsers allow sound only after a click/key: if it was on last time, resume on the first interaction
let want=true;try{want=localStorage.getItem(MKEY)!=='0'}catch(e){} // on by default unless turned off before
if(want){$('bMusic').classList.add('on');const arm=e=>{if(e.code==='KeyM'||e.target.closest?.('#bMusic'))return;removeEventListener('keydown',arm);removeEventListener('pointerdown',arm);if(!on)set(true)};addEventListener('keydown',arm);addEventListener('pointerdown',arm)}
return{toggle:()=>set(!on)}})();
$('bMusic').onclick=()=>Music.toggle();
addEventListener('keydown',e=>{
if(e.metaKey||e.ctrlKey||e.altKey)return;const k=e.code;
if(!$('help').hidden&&(k==='Escape'||k==='KeyH'||k==='Slash')){help(false);e.preventDefault();return}
const map={ArrowRight:next,Space:next,Enter:next,PageDown:next,ArrowLeft:prev,Backspace:prev,PageUp:prev,ArrowDown:()=>chapterStep(1),ArrowUp:()=>chapterStep(-1),Home:()=>go(0),End:()=>go(STEPS.length-1),KeyQ:toggleQuiz,KeyP:togglePause,KeyA:toggleAuto,KeyM:()=>Music.toggle(),KeyH:()=>help(),Slash:()=>help(),Escape:()=>help(false),KeyR:()=>{user.y=0;user.p=0;user.z=1}};
if(/^Digit\d$/.test(k)||/^Numpad\d$/.test(k)){const d=+k.slice(-1);goChapter(d===0?LASTCH:d);e.preventDefault();return}
if(map[k]){map[k]();e.preventDefault()}
});
// drag rotate / zoom
let drag=null;
stage.addEventListener('pointerdown',e=>{drag={x:e.clientX,y:e.clientY};stage.setPointerCapture(e.pointerId)});
stage.addEventListener('pointermove',e=>{if(!drag)return;user.y-=(e.clientX-drag.x)*.008;user.p=Math.max(-1.2,Math.min(1.2,user.p+(e.clientY-drag.y)*.006));drag={x:e.clientX,y:e.clientY}});
addEventListener('pointerup',()=>drag=null);
stage.addEventListener('wheel',e=>{e.preventDefault();user.z=Math.max(.35,Math.min(2.5,user.z*(1+e.deltaY*.001)))},{passive:false});
addEventListener('hashchange',route);
function route(){const h=location.hash.slice(1);let m;if(h==='start')return go(0);if(m=h.match(/^q(\d+)$/)){const i=STEPS.findIndex(s=>s.n===+m[1]);if(i>=0)return go(i)}if(m=h.match(/^review(\d)$/)){const i=STEPS.findIndex(s=>s.rv===+m[1]-1);if(i>=0)return go(i)}if(m=h.match(/^c(\d+)$/))return goChapter(+m[1]);return false}
const clock=new THREE.Clock();const wp=V3();
function frame(){
requestAnimationFrame(frame);
const dt=Math.min(.05,clock.getDelta());st+=dt;if(!paused)T+=dt;
const s=STEPS[idx],S=cur;
if(auto&&$('help').hidden){autoT+=dt;if(quiz&&!revealed&&autoT>7){revealed=true;render()}if(autoT>15){autoT=0;if(idx<STEPS.length-1)next();else toggleAuto()}}
const per=s.per||3.2;const n=cycle.length;
const ctx={mode:s.mode||'',st:paused?st*0:st,T,dt:paused?0:dt,step:s,ci:n?Math.floor(st/per)%n:0,p:(st%per)/per,active:new Set()};
if(pinned>=0)ctx.ci=pinned;
// active set preliminary (for update that needs it)
const build=()=>{const a=new Set(s.focus||[]);if(n&&cycle[ctx.ci])cycle[ctx.ci].parts.forEach(p=>a.add(p));(s.labels||[]).forEach(()=>{});return a};
ctx.active=build();
S.update&&S.update(ctx);
if(pinned>=0)ctx.ci=pinned;
const act=build();
// card line highlight
cycle.forEach((c,i)=>c.el&&c.el.classList.toggle('on',i===ctx.ci&&n>0));
// materials
const any=act.size>0,k=1-Math.exp(-dt*6),pulse=.32+.2*Math.sin(st*5);
S.mats.forEach(m=>{const u=m.userData;const on=u.parts.some(p=>act.has(p));u.gl+=((on?1:0)-u.gl)*k;u.dm+=((any&&!on?1:0)-u.dm)*k;m.color.copy(u.base).multiplyScalar(1-.62*u.dm);m.emissive.copy(u.hl||HL).multiplyScalar(u.gl*pulse)});
// flows
S.flows.forEach(f=>{const vis=f.on&&f.ms[0].parent&&isVis(f.ms[0].parent);f.ms.forEach((m,i)=>{m.visible=vis;if(!vis)return;let u=(f.off[i]+T*f.speed)%1;if(f.rev)u=1-u;m.position.copy(f.c.getPointAt(u))})});
// camera
const kc=1-Math.exp(-dt*2.6);cam.t.lerp(camGoal.t,kc);cam.d+=(camGoal.d*user.z-cam.d)*kc;cam.y+=(camGoal.y+user.y-cam.y)*kc;cam.p+=(camGoal.p+user.p-cam.p)*kc;
const sway=paused?0:Math.sin(T*.25)*.06;const yy=cam.y+sway,pp=Math.max(-1.45,Math.min(1.45,cam.p));
camera.position.set(cam.t.x+cam.d*Math.sin(yy)*Math.cos(pp),cam.t.y+cam.d*Math.sin(pp),cam.t.z+cam.d*Math.cos(yy)*Math.cos(pp));camera.lookAt(cam.t);
renderer.render(scene,camera);
// labels
const r=renderer.domElement,Wd=r.clientWidth,Ht=r.clientHeight;const show=new Set([...act,...(s.labels||[])]);
for(const id in S.labels){const L=S.labels[id];const want=show.has(id)&&isVis(L.a);L.el.hidden=false;if(want){L.a.getWorldPosition(wp);wp.project(camera);if(wp.z>1){L.el.classList.remove('on');continue}L.el.style.transform=`translate(${(wp.x+1)/2*Wd}px,${(1-wp.y)/2*Ht}px)`}L.el.classList.toggle('on',want)}
}
function isVis(o){while(o){if(!o.visible)return false;o=o.parent}return true}
// boot
function start(data){
const i=data&&typeof data.idx==='number'?data.idx:null;
if(i!=null)go(i);else if(route()===false||!location.hash){let saved=0;try{saved=+localStorage.getItem(STORE)||0}catch(e){}go(location.hash?idx:saved)}
if(data&&data.quiz)toggleQuiz();
resize();frame();
}
window.claude?.hot?.snapshot?.(()=>({idx,quiz}));
window.claude?.hot?.ready?window.claude.hot.ready(start):start(window.claude?.hot?.data??{});
}
</script>
</body>
</html>
animated-study-page/scripts/check.sh
#!/bin/bash
# Usage: check.sh page.html outdir hash1 hash2 ... (e.g. start q1 q7 c3 review1)
# Renders each hash in headless Chrome, reports JS errors, saves screenshots to outdir.
set -u
PAGE=$(cd "$(dirname "$1")" && pwd)/$(basename "$1"); OUT=$2; shift 2; mkdir -p "$OUT"
C="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; [ -x "$C" ] || C=$(command -v google-chrome || command -v chromium)
T="$OUT/_t.html"
sed 's#<script src="https://cdn#<script>window.onerror=(m,s,l)=>{document.title="ERR "+m+" @"+l}</script><script src="https://cdn#' "$PAGE" > "$T"
F=(--headless=new --use-angle=swiftshader --enable-unsafe-swiftshader --window-size=1400,900 --virtual-time-budget=4000)
for h in "$@"; do
t=$("$C" "${F[@]}" --dump-dom "file://$T#$h" 2>/dev/null | grep -o '<title>[^<]*' | sed 's/<title>//')
case "$t" in ERR*) echo "FAIL #$h: $t";; *) echo "ok #$h";; esac
"$C" "${F[@]}" --screenshot="$OUT/$h.png" "file://$T#$h" >/dev/null 2>&1
done
echo "screenshots: $OUT"
Then I also tried it myself for one of my psychology study subjects. I found it easier to study this way, too!

Publishing it was super easy via Spacefast:
publish it to Spacefast
Reading an answer while watching it happen on a 3D model helps it stick. Hopefully it makes studying a bit more fun 🙂