/ proof-of-concept / toy-instruments
Sign in
proof-of-concept / toy-instruments
toy-instruments / src / ui / scene3d.ts
642 lines · 28.5 KBBlameHistoryRaw
1import * as THREE from 'three';
2import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
3import type { BeadSystem, Excitation } from '../sim/types';
4import { css, fmtNum } from './plot';
5import { timelineBar, type Timeline } from './timeline';
7// 3D view of a bead-spring system. "Setup" shows the geometry at rest with
8// supports, pins, excitation and pickup marked; "Replay" animates saved
9// displacement frames (exaggerated) on the shared timeline.
11export interface SceneSpec {
12 sys: BeadSystem;
13 exc: Excitation;
14 excKind: 'pluck' | 'strike' | 'hammer' | 'mallet' | 'stick' | 'force' | 'press';
15 pickup: Float64Array; // 3n weights
16 pickupLabel: string;
17 hoop?: { radius: number }; // round rim in the x-z plane, centred on the origin (instead of walls)
18 post?: { y: number }; // centre support: a stand rod from (0, y, 0) down to the floor
19 note?: string; // extra legend text
20 mic?: { dir: [number, number, number]; label: string; from: [number, number, number] }; // direction to a far-field microphone
23export interface ReplaySpec extends SceneSpec {
24 frames: Float32Array; // nFrames x 3n, matches the timeline
25 malletPos?: Float32Array; // mallet position (3 per frame)
28type Mode = 'setup' | 'replay';
30export interface SceneOptions {
31 // just the model and its legend: no setup/replay tabs, view buttons, exaggeration
32 // input, timeline bar or help note (the embedded widget has its own controls)
33 simple?: boolean;
34 // displacement exaggeration for replays (default: automatic, so the largest motion is
35 // visible). When set, the setup view draws the initial shape (pluck, press) at the same
36 // scale, so different amplitudes look different; otherwise it is scaled to a fixed size.
37 exaggeration?: number;
39type View = 'persp' | 'front' | 'top' | 'end';
41const GLYPH = 0.12; // length of the largest excitation glyph, in units of the model size
43export class BeadScene {
44 private renderer: THREE.WebGLRenderer | null = null;
45 private scene = new THREE.Scene();
46 private camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
47 private controls: OrbitControls | null = null;
48 private model = new THREE.Group();
49 private wrap: HTMLDivElement;
50 private legend: HTMLDivElement;
51 private note: HTMLParagraphElement;
52 private bar: HTMLElement;
53 private exagRow: HTMLElement;
54 private exagInput: HTMLInputElement;
55 private tabs: HTMLElement;
57 private mode: Mode = 'setup';
58 private view: View = 'persp';
59 private fitted = false;
60 private setupSpec: SceneSpec | null = null;
61 private replaySpec: ReplaySpec | null = null;
62 private exaggeration = 1;
63 private autoExaggeration = 1;
65 // geometry of the current build, in normalized scene units
66 private scale = 1;
67 private center = new THREE.Vector3();
68 private beads: THREE.InstancedMesh | null = null;
69 private pins: THREE.InstancedMesh | null = null;
70 private springs: THREE.LineSegments | null = null;
71 private slideRings: { mesh: THREE.Mesh; bead: number }[] = [];
72 private hammerArrows: THREE.Group | null = null;
73 private pickupArrow: { arrow: THREE.ArrowHelper; bead: number } | null = null;
74 private mallet: { group: THREE.Group; contact: THREE.Vector3; dir: THREE.Vector3 } | null = null;
75 private spec: SceneSpec | null = null;
76 private frames: Float32Array | null = null;
78 constructor(
79 root: HTMLElement,
80 private tl: Timeline,
81 private opts: SceneOptions = {},
82 ) {
83 root.innerHTML = `
84 <div class="card-head">
85 <div class="seg" data-r="tabs"><button data-v="setup" class="on">Setup</button><button data-v="replay" disabled>Replay</button></div>
86 <div class="seg" data-r="views"><button data-v="persp" class="on">3D</button><button data-v="front">Front x–y</button><button data-v="top">Top x–z</button><button data-v="end">End y–z</button></div>
87 </div>
88 <div class="scene-wrap" data-r="wrap"></div>
89 <div class="legend scene-legend" data-r="legend"></div>
90 <div class="viewer-bar" data-r="exag" hidden>
91 <label class="inline">exaggeration × <input type="number" min="1" step="any" data-r="exag-in" style="width:110px"></label>
92 <button class="btn-small" data-r="exag-auto">Auto</button>
93 </div>
94 <div data-r="bar" hidden></div>
95 <p class="note" data-r="note"></p>`;
96 const q = <T extends HTMLElement>(r: string) => root.querySelector(`[data-r="${r}"]`) as T;
97 this.wrap = q('wrap');
98 this.legend = q('legend');
99 this.note = q('note');
100 this.tabs = q('tabs');
101 this.exagRow = q('exag');
102 this.exagInput = q('exag-in');
103 this.bar = timelineBar(tl);
104 this.bar.hidden = true;
105 q('bar').replaceWith(this.bar);
106 if (opts.simple) {
107 (root.querySelector('.card-head') as HTMLElement).hidden = true;
108 this.note.hidden = true;
109 }
111 this.tabs.addEventListener('click', (e) => {
112 const b = (e.target as HTMLElement).closest('button');
113 if (b && !b.disabled) this.setMode(b.dataset.v as Mode);
114 });
115 q('views').addEventListener('click', (e) => {
116 const b = (e.target as HTMLElement).closest('button');
117 if (!b) return;
118 q('views').querySelectorAll('button').forEach((x) => x.classList.toggle('on', x === b));
119 this.setView(b.dataset.v as View);
120 });
121 this.exagInput.addEventListener('change', () => {
122 const v = Number(this.exagInput.value);
123 if (v > 0) {
124 this.exaggeration = v;
125 this.update();
126 }
127 });
128 q('exag-auto').addEventListener('click', () => {
129 this.exaggeration = this.autoExaggeration;
130 this.exagInput.value = fmtNum(this.exaggeration);
131 this.update();
132 });
134 try {
135 this.renderer = new THREE.WebGLRenderer({ antialias: true });
136 this.renderer.setPixelRatio(window.devicePixelRatio || 1);
137 this.wrap.append(this.renderer.domElement);
138 this.controls = new OrbitControls(this.camera, this.renderer.domElement);
139 this.controls.addEventListener('change', () => this.render());
140 } catch {
141 this.wrap.innerHTML = '<p class="note">WebGL is not available in this browser, so the 3D view is off.</p>';
142 }
143 this.scene.add(new THREE.AmbientLight(0xffffff, 1.6));
144 const sun = new THREE.DirectionalLight(0xffffff, 2.2);
145 sun.position.set(0.4, 1, 0.8);
146 this.scene.add(sun);
147 this.scene.add(this.model);
148 this.setView('persp');
150 tl.onChange(() => {
151 if (this.mode === 'replay') this.update();
152 });
153 new ResizeObserver(() => this.resize()).observe(this.wrap);
154 window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => this.rebuild());
155 }
157 // set the replay's displacement exaggeration (kept for later replays)
158 setExaggeration(x: number) {
159 this.opts.exaggeration = this.exaggeration = x;
160 this.exagInput.value = fmtNum(x);
161 if (this.mode === 'setup') this.rebuild(); // the initial shape is drawn at this scale
162 else this.update();
163 }
165 // redraw with the current colors (after a theme change the view cannot see by itself)
166 restyle() {
167 this.rebuild();
168 }
170 showSetup(spec: SceneSpec) {
171 this.setupSpec = spec;
172 if (this.mode === 'setup') this.rebuild();
173 else this.setMode('setup');
174 }
176 // keep = true: more frames of the replay already shown (a partial result
177 // growing); keeps the mode and any exaggeration the user set
178 showReplay(spec: ReplaySpec, keep = false) {
179 this.replaySpec = spec;
180 let tmax = 0;
181 for (let i = 0; i < spec.frames.length; i++) if (i % 3 !== 0) tmax = Math.max(tmax, Math.abs(spec.frames[i]));
182 const size = modelSize(spec.sys);
183 const wasAuto = this.exaggeration === this.autoExaggeration;
184 this.autoExaggeration = tmax > 0 ? Math.max(1, (GLYPH * size) / tmax) : 1;
185 if (this.opts.exaggeration) this.exaggeration = this.opts.exaggeration;
186 else if (!keep || wasAuto) this.exaggeration = this.autoExaggeration;
187 this.exagInput.value = fmtNum(this.exaggeration);
188 if (keep) {
189 if (this.mode === 'replay') {
190 this.frames = spec.frames;
191 this.update();
192 }
193 return;
194 }
195 (this.tabs.querySelector('[data-v="replay"]') as HTMLButtonElement).disabled = false;
196 this.setMode('replay');
197 }
199 private setMode(m: Mode) {
200 this.mode = m;
201 this.tabs.querySelectorAll<HTMLButtonElement>('button').forEach((b) => b.classList.toggle('on', b.dataset.v === m));
202 this.bar.hidden = this.exagRow.hidden = m !== 'replay' || !!this.opts.simple;
203 if (m === 'setup') this.tl.pause();
204 this.rebuild();
205 }
207 private setView(v: View) {
208 this.view = v;
209 const dirs: Record<View, [number, number, number]> = {
210 persp: [-0.45, 0.42, 1.05],
211 front: [0, 0, 1],
212 top: [0, 1, 0.0001],
213 end: [1, 0, 0],
214 };
215 // back off far enough that the model (about 1.4 wide with its supports) fits horizontally
216 const half = Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2));
217 const fit = 0.75 / (half * this.camera.aspect) + 0.3;
218 const dist = Math.max(this.view === 'persp' ? 1.2 : 1.45, fit);
219 this.camera.position.set(...dirs[v]).setLength(dist);
220 this.camera.up.set(0, 1, 0);
221 if (v === 'top') this.camera.up.set(0, 0, -1);
222 this.controls?.target.set(0, 0, 0);
223 this.camera.lookAt(0, 0, 0);
224 this.controls?.update();
225 this.render();
226 }
228 private resize() {
229 if (!this.renderer) return;
230 const w = this.wrap.clientWidth;
231 const h = this.wrap.clientHeight;
232 if (w === 0 || h === 0) return;
233 this.renderer.setSize(w, h);
234 const narrowBefore = this.camera.aspect < 1;
235 this.camera.aspect = w / h;
236 this.camera.updateProjectionMatrix();
237 // refit when the view turns portrait or landscape (phone rotation, first layout)
238 if (narrowBefore !== this.camera.aspect < 1 || !this.fitted) {
239 this.fitted = true;
240 this.setView(this.view);
241 } else this.render();
242 }
244 private render() {
245 this.renderer?.render(this.scene, this.camera);
246 }
248 // node position (beads and anchors), normalized
249 private nodePos(sys: BeadSystem, node: number, out: THREE.Vector3): THREE.Vector3 {
250 if (node < sys.n) out.set(sys.rest[3 * node], sys.rest[3 * node + 1], sys.rest[3 * node + 2]);
251 else out.set(...sys.anchors[node - sys.n].pos);
252 return out.sub(this.center).multiplyScalar(this.scale);
253 }
255 private rebuild() {
256 const spec = this.mode === 'replay' ? this.replaySpec : this.setupSpec;
257 disposeGroup(this.model);
258 this.beads = this.pins = this.springs = this.hammerArrows = null;
259 this.slideRings = [];
260 this.pickupArrow = null;
261 this.mallet = null;
262 this.spec = spec;
263 this.frames = this.mode === 'replay' && this.replaySpec ? this.replaySpec.frames : null;
264 if (!spec) return this.render();
265 if (this.renderer) this.renderer.setClearColor(new THREE.Color(css('--surface-1', this.wrap)));
266 const { sys, exc, pickup } = spec;
267 const n = sys.n;
269 // normalize: longest extent of beads and anchors -> 1, centered
270 const box = new THREE.Box3();
271 const v = new THREE.Vector3();
272 for (let i = 0; i < n; i++) box.expandByPoint(v.set(sys.rest[3 * i], sys.rest[3 * i + 1], sys.rest[3 * i + 2]));
273 for (const a of sys.anchors) box.expandByPoint(v.set(...a.pos));
274 box.getCenter(this.center);
275 const size = box.getSize(new THREE.Vector3());
276 this.scale = 1 / Math.max(size.x, size.y, size.z, 1e-12);
278 // bead size from nearest-neighbour spacing
279 let minLen = Infinity;
280 const p = new THREE.Vector3();
281 const q = new THREE.Vector3();
282 for (let s = 0; s < sys.si.length; s++) minLen = Math.min(minLen, this.nodePos(sys, sys.si[s], p).distanceTo(this.nodePos(sys, sys.sj[s], q)));
283 if (!Number.isFinite(minLen)) minLen = 0.05;
284 const r = Math.min(0.32 * minLen, 0.022);
286 const cBead = new THREE.Color(css('--series-1', this.wrap));
287 const cExc = new THREE.Color(css('--series-2', this.wrap));
288 const cPick = new THREE.Color(css('--series-3', this.wrap));
289 const cInk = new THREE.Color(css('--text-primary', this.wrap));
290 const cMuted = new THREE.Color(css('--text-muted', this.wrap));
292 // grid floor for depth cues
293 const grid = new THREE.GridHelper(1.4, 14, cMuted, cMuted);
294 (grid.material as THREE.Material).transparent = true;
295 (grid.material as THREE.Material).opacity = 0.25;
296 grid.position.y = -0.22;
297 this.model.add(grid);
298 this.model.add(axisTriad(new THREE.Vector3(-0.58, -0.22, -0.3), 0.08, cInk));
300 // beads (pinned beads are drawn as cubes instead)
301 const pickBead = (i: number) => pickup[3 * i] !== 0 || pickup[3 * i + 1] !== 0 || pickup[3 * i + 2] !== 0;
302 const free: number[] = [];
303 const pinned: number[] = [];
304 for (let i = 0; i < n; i++) (sys.pinned[i] ? pinned : free).push(i);
305 const beadMat = new THREE.MeshStandardMaterial({ roughness: 0.55, metalness: 0.1 });
306 this.beads = new THREE.InstancedMesh(new THREE.SphereGeometry(r, 20, 14), beadMat, Math.max(1, n));
307 this.beads.count = n;
308 // a pickup over every bead is named in the legend rather than painting the whole model
309 let nPick = 0;
310 for (let i = 0; i < n; i++) if (pickBead(i)) nPick++;
311 for (let i = 0; i < n; i++) this.beads.setColorAt(i, pickBead(i) && nPick < n ? cPick : cBead);
312 this.model.add(this.beads);
313 if (pinned.length) {
314 this.pins = new THREE.InstancedMesh(new THREE.BoxGeometry(2.4 * r, 2.4 * r, 2.4 * r), new THREE.MeshStandardMaterial({ color: cInk, roughness: 0.6 }), pinned.length);
315 this.model.add(this.pins);
316 }
317 (this.beads.userData as { free: number[]; pinned: number[] }) = { free, pinned };
319 // springs
320 const sg = new THREE.BufferGeometry();
321 sg.setAttribute('position', new THREE.BufferAttribute(new Float32Array(sys.si.length * 6), 3));
322 this.springs = new THREE.LineSegments(sg, new THREE.LineBasicMaterial({ color: cMuted }));
323 this.model.add(this.springs);
325 // supports
326 const wallSize = 0.16;
327 if (spec.hoop) {
328 const hoop = new THREE.Mesh(
329 new THREE.TorusGeometry(spec.hoop.radius * this.scale, 0.012, 10, 96),
330 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.7 }),
331 );
332 hoop.rotation.x = Math.PI / 2;
333 hoop.position.set(-this.center.x * this.scale, -this.center.y * this.scale, -this.center.z * this.scale);
334 this.model.add(hoop);
335 }
336 if (spec.post) {
337 const o = new THREE.Vector3(-this.center.x, spec.post.y - this.center.y, -this.center.z).multiplyScalar(this.scale);
338 const rodLen = o.y + 0.22;
339 const rod = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, rodLen + 0.04, 10), new THREE.MeshStandardMaterial({ color: cMuted }));
340 rod.position.copy(o).add(new THREE.Vector3(0, 0.02 - rodLen / 2, 0));
341 this.model.add(rod);
342 }
343 if (spec.mic) {
344 const o = new THREE.Vector3(...spec.mic.from).sub(this.center).multiplyScalar(this.scale);
345 this.model.add(new THREE.ArrowHelper(new THREE.Vector3(...spec.mic.dir).normalize(), o, 0.42, new THREE.Color(css('--series-3', this.wrap)), 0.05, 0.025));
346 }
347 if (!spec.hoop) sys.anchors.forEach((a) => {
348 const at = this.nodePos(sys, sys.n + sys.anchors.indexOf(a), new THREE.Vector3());
349 const side = at.x < 0 ? -1 : 1;
350 if (a.slideBead < 0) {
351 const wall = new THREE.Mesh(
352 new THREE.BoxGeometry(0.02, wallSize, wallSize),
353 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.8 }),
354 );
355 wall.position.copy(at).add(new THREE.Vector3(side * 0.01, 0, 0));
356 this.model.add(wall);
357 } else {
358 const plane = new THREE.Mesh(
359 new THREE.PlaneGeometry(wallSize, wallSize),
360 new THREE.MeshBasicMaterial({ color: cMuted, transparent: true, opacity: 0.18, side: THREE.DoubleSide, depthWrite: false }),
361 );
362 plane.rotation.y = Math.PI / 2;
363 plane.position.copy(at);
364 this.model.add(plane);
365 const edges = new THREE.LineSegments(new THREE.EdgesGeometry(plane.geometry), new THREE.LineBasicMaterial({ color: cMuted }));
366 edges.rotation.y = Math.PI / 2;
367 edges.position.copy(at);
368 this.model.add(edges);
369 const ring = new THREE.Mesh(new THREE.TorusGeometry(1.3 * r, 0.35 * r, 8, 24), new THREE.MeshStandardMaterial({ color: cInk }));
370 ring.rotation.y = Math.PI / 2;
371 ring.position.copy(at);
372 this.model.add(ring);
373 this.slideRings.push({ mesh: ring, bead: a.slideBead });
374 }
375 });
377 // excitation glyphs
378 const legend: string[] = [];
379 const sw = (c: THREE.Color, shape = 'dot') => `<i class="glyph ${shape}" style="--c:#${c.getHexString()}"></i>`;
380 legend.push(`<span>${sw(cBead)}bead</span>`);
381 if (pinned.length) legend.push(`<span>${sw(cInk, 'square')}${spec.post ? 'bead held at the hub' : 'pinned bead'}</span>`);
382 if (spec.hoop) legend.push(`<span>${sw(cMuted, 'ring')}clamped rim</span>`);
384 else if (sys.anchors.some((a) => a.slideBead < 0)) legend.push(`<span>${sw(cMuted, 'square')}clamped end (wall)</span>`);
385 if (sys.anchors.some((a) => a.slideBead >= 0)) legend.push(`<span>${sw(cInk, 'ring')}sliding end (ring on a frictionless plane)</span>`);
386 const size0 = modelSize(sys);
387 const dirs = (field: Float64Array) => {
388 let m = 0;
389 for (let i = 0; i < n; i++) m = Math.max(m, Math.hypot(field[3 * i], field[3 * i + 1], field[3 * i + 2]));
390 return m;
391 };
392 if (this.mode === 'setup' && spec.excKind === 'pluck') {
393 const m = dirs(exc.u0);
394 if (m > 0) {
395 const E = this.opts.exaggeration ?? (GLYPH * size0) / m;
396 const pts: THREE.Vector3[] = [];
397 const left = sys.anchors.find((a) => a.pos[0] < sys.rest[0]);
398 const right = sys.anchors.find((a) => a.pos[0] > sys.rest[3 * (n - 1)]);
399 if (left) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(left), new THREE.Vector3()));
400 for (let i = 0; i < n; i++) {
401 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
402 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
403 }
404 if (right) pts.push(this.nodePos(sys, n + sys.anchors.indexOf(right), new THREE.Vector3()));
405 const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineDashedMaterial({ color: cExc, dashSize: 0.015, gapSize: 0.01 }));
406 line.computeLineDistances();
407 this.model.add(line);
408 let peak = 0;
409 for (let i = 1; i < n; i++) if (Math.hypot(exc.u0[3 * i + 1], exc.u0[3 * i + 2]) > Math.hypot(exc.u0[3 * peak + 1], exc.u0[3 * peak + 2])) peak = i;
410 const from = this.nodePos(sys, peak, new THREE.Vector3());
411 const to = pts[peak + (left ? 1 : 0)];
412 const len = from.distanceTo(to);
413 if (len > 0) this.model.add(new THREE.ArrowHelper(to.clone().sub(from).normalize(), from, len, cExc, 0.25 * len, 0.12 * len));
414 legend.push(`<span>${sw(cExc, 'dash')}pluck: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm peak)</span>`);
415 }
416 }
417 if (spec.excKind === 'strike' && this.mode === 'setup') {
418 const m = dirs(exc.v0);
419 if (m > 0) this.model.add(this.arrows(sys, exc.v0, m, cExc, false));
420 legend.push(`<span>${sw(cExc, 'arrow')}strike: initial velocity (${fmtNum(m)} m/s peak)</span>`);
421 }
422 if (this.mode === 'setup' && spec.excKind === 'press') {
423 const m = dirs(exc.u0);
424 if (m > 0) {
425 const E = this.opts.exaggeration ?? (0.5 * GLYPH * size0) / m;
426 const pts: THREE.Vector3[] = [];
427 for (let i = 0; i < n; i++) {
428 if (Math.hypot(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]) < 0.02 * m) continue;
429 const w = new THREE.Vector3(exc.u0[3 * i], exc.u0[3 * i + 1], exc.u0[3 * i + 2]).multiplyScalar(E * this.scale);
430 pts.push(this.nodePos(sys, i, new THREE.Vector3()).add(w));
431 }
432 const dots = new THREE.Points(new THREE.BufferGeometry().setFromPoints(pts), new THREE.PointsMaterial({ color: cExc, size: 1.2 * r }));
433 this.model.add(dots);
434 legend.push(`<span>${sw(cExc)}press: initial shape, drawn ×${fmtNum(E)} (${fmtNum(m * 1000)} mm deep)</span>`);
435 }
436 }
437 if (exc.mallet) {
438 const ml = exc.mallet;
439 const dir = new THREE.Vector3(...ml.vel0).normalize(); // the stick travels along its own axis
440 const contact = new THREE.Vector3();
441 for (let i = 0; i < n; i++) if (ml.weights[i] > 0) contact.addScaledVector(this.nodePos(sys, i, new THREE.Vector3()), ml.weights[i]);
442 const head = Math.max(1.6 * r, 0.025);
443 const group = new THREE.Group();
444 const felt = new THREE.Mesh(new THREE.SphereGeometry(head, 24, 16), new THREE.MeshStandardMaterial({ color: cExc, roughness: 0.9 }));
445 felt.position.copy(dir).multiplyScalar(-head);
446 const stick = new THREE.Mesh(
447 new THREE.CylinderGeometry(0.15 * head, 0.15 * head, 0.3, 10),
448 new THREE.MeshStandardMaterial({ color: cMuted, roughness: 0.6 }),
449 );
450 stick.position.copy(dir).multiplyScalar(-(2 * head + 0.15));
451 stick.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);
452 group.add(felt, stick);
453 this.model.add(group);
454 this.mallet = { group, contact, dir };
455 const speed = Math.hypot(...ml.vel0);
456 const what = spec.excKind === 'stick' ? 'stick' : 'mallet';
457 legend.push(
458 `<span>${sw(cExc)}${what}: ${fmtNum(ml.mass * 1000)} g at ${fmtNum(speed)} m/s, contact F = K δ^${fmtNum(ml.p)}${this.mode === 'replay' ? ' (motion exaggerated like the beads)' : ''}</span>`,
459 );
460 }
461 if ((spec.excKind === 'hammer' || spec.excKind === 'force') && exc.force) {
462 const m = dirs(exc.force.shape);
463 if (m > 0) {
464 this.hammerArrows = this.arrows(sys, exc.force.shape, m, cExc, true);
465 this.model.add(this.hammerArrows);
466 }
467 legend.push(
468 `<span>${sw(cExc, 'arrow')}${spec.excKind === 'hammer' ? 'hammer' : 'force'}: force pulse, ${fmtNum(exc.force.F0)} N peak over ${fmtNum(exc.force.tau * 1000)} ms${this.mode === 'replay' ? ' (shown while it acts)' : ''}</span>`,
469 );
470 }
472 // pickup
473 const pk: number[] = [];
474 for (let i = 0; i < n; i++) if (pickBead(i)) pk.push(i);
475 if (pk.length === 1) {
476 const i = pk[0];
477 const d = new THREE.Vector3(pickup[3 * i], pickup[3 * i + 1], pickup[3 * i + 2]).normalize();
478 const len = Math.max(0.05, 6 * r);
479 const arrow = new THREE.ArrowHelper(d, this.nodePos(sys, i, new THREE.Vector3()), len, cPick, 0.3 * len, 0.18 * len);
480 this.model.add(arrow);
481 this.pickupArrow = { arrow, bead: i };
482 }
483 legend.push(spec.mic ? `<span>${sw(cPick, 'arrow')}${spec.mic.label}</span>` : `<span>${sw(cPick)}pickup: ${spec.pickupLabel}</span>`);
484 if (spec.note) legend.push(`<span>${spec.note}</span>`);
485 this.legend.innerHTML = legend.join('');
486 this.update();
487 }
489 // arrows proportional to a per-bead vector field; `into` = arrow ends at the bead (a push)
490 private arrows(sys: BeadSystem, field: Float64Array, max: number, color: THREE.Color, into: boolean): THREE.Group {
491 const g = new THREE.Group();
492 for (let i = 0; i < sys.n; i++) {
493 const d = new THREE.Vector3(field[3 * i], field[3 * i + 1], field[3 * i + 2]);
494 const mag = d.length();
495 if (mag < 0.05 * max) continue;
496 const len = GLYPH * (mag / max);
497 d.normalize();
498 const at = this.nodePos(sys, i, new THREE.Vector3());
499 const origin = into ? at.clone().addScaledVector(d, -len) : at;
500 const arrow = new THREE.ArrowHelper(d, origin, len, color, Math.min(0.03, 0.3 * len), Math.min(0.016, 0.18 * len));
501 arrow.userData = { bead: i, dir: d.clone(), len };
502 g.add(arrow);
503 }
504 return g;
505 }
507 // position everything for the current frame (or rest, in setup)
508 private update() {
509 const spec = this.spec;
510 if (!spec || !this.beads) return this.render();
511 const { sys } = spec;
512 const n = sys.n;
513 const frames = this.frames;
514 const off = frames ? this.tl.frame * 3 * n : 0;
515 const E = this.exaggeration * this.scale;
516 const P = new Array<THREE.Vector3>(n + sys.anchors.length);
517 for (let i = 0; i < n; i++) {
518 const p = this.nodePos(sys, i, new THREE.Vector3());
519 if (frames) p.add(new THREE.Vector3(frames[off + 3 * i], frames[off + 3 * i + 1], frames[off + 3 * i + 2]).multiplyScalar(E));
520 P[i] = p;
521 }
522 sys.anchors.forEach((a, k) => {
523 const p = this.nodePos(sys, n + k, new THREE.Vector3());
524 if (a.slideBead >= 0) {
525 p.y = P[a.slideBead].y;
526 p.z = P[a.slideBead].z;
527 }
528 P[n + k] = p;
529 });
530 const m = new THREE.Matrix4();
531 const { pinned } = this.beads.userData as { free: number[]; pinned: number[] };
532 for (let i = 0; i < n; i++) {
533 // hide pinned beads' spheres (cubes stand in)
534 m.makeScale(sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1, sys.pinned[i] ? 0 : 1).setPosition(P[i]);
535 this.beads.setMatrixAt(i, m);
536 }
537 this.beads.instanceMatrix.needsUpdate = true;
538 if (this.beads.instanceColor) this.beads.instanceColor.needsUpdate = true;
539 if (this.pins) {
540 pinned.forEach((i, k) => this.pins!.setMatrixAt(k, m.makeTranslation(P[i].x, P[i].y, P[i].z)));
541 this.pins.instanceMatrix.needsUpdate = true;
542 }
543 if (this.springs) {
544 const arr = (this.springs.geometry.getAttribute('position') as THREE.BufferAttribute).array as Float32Array;
545 for (let s = 0; s < sys.si.length; s++) {
546 const a = P[sys.si[s]];
547 const b = P[sys.sj[s]];
548 arr.set([a.x, a.y, a.z, b.x, b.y, b.z], 6 * s);
549 }
550 this.springs.geometry.getAttribute('position').needsUpdate = true;
551 this.springs.geometry.computeBoundingSphere();
552 }
553 for (const { mesh, bead } of this.slideRings) {
554 mesh.position.y = P[bead].y;
555 mesh.position.z = P[bead].z;
556 }
557 if (this.pickupArrow) this.pickupArrow.arrow.position.copy(P[this.pickupArrow.bead]);
558 if (this.mallet) {
559 const mp = this.mode === 'replay' ? this.replaySpec?.malletPos : undefined;
560 const g = this.mallet.group.position.copy(this.mallet.contact);
561 // in setup it hovers back along its path; in replay it follows the run
562 if (mp) g.add(new THREE.Vector3(mp[3 * this.tl.frame], mp[3 * this.tl.frame + 1], mp[3 * this.tl.frame + 2]).multiplyScalar(E));
563 else g.addScaledVector(this.mallet.dir, -0.6 * GLYPH);
564 }
565 if (this.hammerArrows && spec.exc.force) {
566 const f = spec.exc.force;
567 const t = frames ? this.tl.times[this.tl.frame] : f.tau / 2;
568 const s = t >= 0 && t <= f.tau ? 0.5 * (1 - Math.cos((2 * Math.PI * t) / f.tau)) : 0;
569 this.hammerArrows.visible = s > 0.02;
570 for (const c of this.hammerArrows.children) {
571 const { bead, dir, len } = c.userData as { bead: number; dir: THREE.Vector3; len: number };
572 const l = Math.max(1e-4, len * (frames ? s : 1));
573 const arrow = c as THREE.ArrowHelper;
574 arrow.position.copy(P[bead]).addScaledVector(dir, -l);
575 arrow.setLength(l, Math.min(0.03, 0.3 * l), Math.min(0.016, 0.18 * l));
576 }
577 }
578 if (this.mode === 'replay' && frames) {
579 this.note.textContent =
580 `Displacements drawn ×${fmtNum(this.exaggeration)} (all three components, so longitudinal motion is exaggerated too). ` +
581 `Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.`;
582 } else {
583 this.note.textContent = 'Beads at rest. Drag to rotate; pinch or scroll to zoom; two-finger or right-drag to pan.';
584 }
585 this.render();
586 }
589function modelSize(sys: BeadSystem): number {
590 let lo = Infinity;
591 let hi = -Infinity;
592 for (let i = 0; i < sys.n; i++) {
593 lo = Math.min(lo, sys.rest[3 * i]);
594 hi = Math.max(hi, sys.rest[3 * i]);
595 }
596 for (const a of sys.anchors) {
597 lo = Math.min(lo, a.pos[0]);
598 hi = Math.max(hi, a.pos[0]);
599 }
600 return Math.max(hi - lo, 1e-12);
603function textSprite(text: string, color: THREE.Color): THREE.Sprite {
604 const c = document.createElement('canvas');
605 c.width = c.height = 64;
606 const ctx = c.getContext('2d')!;
607 ctx.fillStyle = `#${color.getHexString()}`;
608 ctx.font = '600 44px system-ui, sans-serif';
609 ctx.textAlign = 'center';
610 ctx.textBaseline = 'middle';
611 ctx.fillText(text, 32, 34);
612 const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), depthTest: false }));
613 s.scale.set(0.04, 0.04, 1);
614 return s;
617function axisTriad(at: THREE.Vector3, len: number, ink: THREE.Color): THREE.Group {
618 const g = new THREE.Group();
619 const axes: [string, THREE.Vector3][] = [
620 ['x', new THREE.Vector3(1, 0, 0)],
621 ['y', new THREE.Vector3(0, 1, 0)],
622 ['z', new THREE.Vector3(0, 0, 1)],
623 ];
624 for (const [name, d] of axes) {
625 g.add(new THREE.ArrowHelper(d, at, len, ink, 0.2 * len, 0.1 * len));
626 const label = textSprite(name, ink);
627 label.position.copy(at).addScaledVector(d, len * 1.3);
628 g.add(label);
629 }
630 return g;
633function disposeGroup(g: THREE.Group) {
634 g.traverse((o) => {
635 const m = o as THREE.Mesh;
636 m.geometry?.dispose();
637 const mat = m.material as THREE.Material | THREE.Material[] | undefined;
638 if (Array.isArray(mat)) mat.forEach((x) => x.dispose());
639 else mat?.dispose();
640 });
641 g.clear();
↑↓ move↵openescclose