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