@beeson-group/tycho 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/viewer.ts ADDED
@@ -0,0 +1,864 @@
1
+ /**
2
+ * three.js scene for one trajectory in one frame, with a 2D axes overlay.
3
+ *
4
+ * Drawing is a pure function of a true anomaly: `showAt(fRel)` draws the state
5
+ * at that epoch and nothing depends on wall-clock time, which is what makes
6
+ * deterministic recording possible. The one exception is cosmetic: the family
7
+ * highlight eases and ripples between members over a short transition.
8
+ *
9
+ * Smoothness follows the reference matplotlib tool: the stored samples are a
10
+ * dense, arclength-adaptive track. The trail is cut from that track at the
11
+ * current epoch rather than joined up from a playback grid, so it lies on the
12
+ * orbit instead of chording across it, and the spacecraft is interpolated
13
+ * between the two samples that bracket the epoch.
14
+ *
15
+ * Colour: the current member's trail and full orbit take that member's colour
16
+ * in the frame's colormap. The spacecraft leaves a comet-style trail: a
17
+ * tapered ribbon sized in screen pixels, bright and wide at the craft, thinning
18
+ * and fading over a fixed stretch of orbit behind it, with a soft additive
19
+ * glow underneath. The other members are drawn with per-vertex alpha: a kernel
20
+ * over parameter distance brightens the neighbours of the current member over
21
+ * their whole orbits, on top of a sparse context set, relaxing fast in and
22
+ * slower out when the member changes.
23
+ */
24
+
25
+ import * as THREE from 'three';
26
+ import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
27
+ import { colormap, colormapCss } from './colormaps';
28
+ import {
29
+ FRAMES,
30
+ type ER3BPSystem,
31
+ type FrameId,
32
+ bodyPosition,
33
+ bodyTrail,
34
+ segmentIndex,
35
+ transformTrajectory,
36
+ } from './frames';
37
+
38
+ /** Okabe-Ito on black, as in the reference animation. */
39
+ export interface Palette {
40
+ background: string;
41
+ craft: string;
42
+ primary: string;
43
+ secondary: string;
44
+ grid: string;
45
+ axis: string;
46
+ text: string;
47
+ }
48
+
49
+ export const DARK: Palette = {
50
+ background: '#000000',
51
+ craft: '#F0E442',
52
+ primary: '#56B4E9',
53
+ secondary: '#A8A8A8',
54
+ grid: '#1e1e1e',
55
+ axis: '#555555',
56
+ text: '#cfcfcf',
57
+ };
58
+
59
+ /** A whole family branch: n members, m samples each, rotating-pulsating x,y and relative true anomaly. */
60
+ export interface FamilyTracks {
61
+ count: number;
62
+ samples: number;
63
+ positions: Float32Array; // n*m*2
64
+ anomalies: Float32Array; // n*m
65
+ params: Float64Array; // n
66
+ mu: number;
67
+ f0: number;
68
+ }
69
+
70
+ export type FamilyMode = 'hidden' | 'neighbours' | 'family';
71
+
72
+ /** Highlight kernel width as a fraction of the family's parameter range. */
73
+ const NEIGHBOUR_SIGMA = 0.05;
74
+ /** Alpha of the nearest neighbours' trail; the current member itself is drawn separately. */
75
+ const NEIGHBOUR_PEAK = 0.55;
76
+ /** About this many members are drawn as the family's context in 'family' mode. */
77
+ const SPARSE_COUNT = 40;
78
+ const SPARSE_ALPHA = 0.4;
79
+ /** Spacecraft trail: length as a fraction of the period, core and glow widths in CSS pixels at the craft. */
80
+ const TRAIL_FRACTION = 0.3;
81
+ /** Nose: the ribbon grows from a point at the craft to full width over this fraction of the trail. */
82
+ const TRAIL_NOSE = 0.07;
83
+ const TRAIL_CORE_PX = 6;
84
+ const TRAIL_GLOW_PX = 22;
85
+ /** Time constants of the alpha relaxation: fast in, slower out, so the trail fades behind. */
86
+ const RISE_MS = 60;
87
+ const DECAY_MS = 320;
88
+
89
+ function discTexture(): THREE.Texture {
90
+ const c = document.createElement('canvas');
91
+ c.width = c.height = 64;
92
+ const g = c.getContext('2d')!;
93
+ g.fillStyle = '#fff';
94
+ g.beginPath();
95
+ g.arc(32, 32, 28, 0, Math.PI * 2);
96
+ g.fill();
97
+ const t = new THREE.CanvasTexture(c);
98
+ t.needsUpdate = true;
99
+ return t;
100
+ }
101
+
102
+ function points(color: string, size: number, tex: THREE.Texture, count: number): THREE.Points {
103
+ const geom = new THREE.BufferGeometry();
104
+ geom.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * count), 3));
105
+ const mat = new THREE.PointsMaterial({
106
+ color,
107
+ size,
108
+ map: tex,
109
+ transparent: true,
110
+ alphaTest: 0.5,
111
+ sizeAttenuation: false,
112
+ depthTest: false,
113
+ });
114
+ return new THREE.Points(geom, mat);
115
+ }
116
+
117
+ function line(color: string, opacity: number, count: number): THREE.Line {
118
+ const geom = new THREE.BufferGeometry();
119
+ geom.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * count), 3));
120
+ // always in the transparent pass so renderOrder decides stacking (opaque objects would draw first)
121
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity, depthTest: false });
122
+ return new THREE.Line(geom, mat);
123
+ }
124
+
125
+ function niceStep(range: number, target = 6): number {
126
+ const raw = range / target;
127
+ const mag = Math.pow(10, Math.floor(Math.log10(raw)));
128
+ const r = raw / mag;
129
+ const step = r < 1.5 ? 1 : r < 3.5 ? 2 : r < 7.5 ? 5 : 10;
130
+ return step * mag;
131
+ }
132
+
133
+ export class OrbitViewer {
134
+ readonly host: HTMLElement;
135
+ readonly canvas: HTMLCanvasElement;
136
+ readonly overlay: HTMLCanvasElement;
137
+ readonly renderer: THREE.WebGLRenderer;
138
+ readonly scene = new THREE.Scene();
139
+ readonly camera: THREE.OrthographicCamera;
140
+ readonly controls: OrbitControls;
141
+ palette: Palette = DARK;
142
+
143
+ frame: FrameId = 'rotating_pulsating';
144
+ showGhost = true;
145
+ /** draw the frame name at the top of the overlay (off when a panel header shows it) */
146
+ showTitle = false;
147
+ private threeD = false;
148
+
149
+ private sys: ER3BPSystem = { mu: 0.5, e: 0, f0: 0 };
150
+ private xy: Float32Array = new Float32Array(0);
151
+ private fRel: ArrayLike<number> = new Float32Array(0);
152
+ private xyz: Float32Array = new Float32Array(0);
153
+ private fNow = 0;
154
+
155
+ // family ghosts
156
+ private tracks: FamilyTracks | null = null;
157
+ private familyMode: FamilyMode = 'hidden';
158
+ private paramRange: [number, number] | null = null;
159
+ private alphaNow = new Float32Array(0); // per member, as drawn
160
+ private alphaFrom = new Float32Array(0); // per member, at the start of the transition
161
+ private alphaTo = new Float32Array(0); // per member, target
162
+ private baseAlpha = new Float32Array(0); // per member, constant context level
163
+ private written = new Float32Array(0); // per member, constant alpha last written, or -1 for per-vertex
164
+ private fadeLast = 0;
165
+ private fadeRaf = 0;
166
+
167
+ private orbit: THREE.Line; // crisp centre line of the trail
168
+ private trailCore: THREE.Mesh; // tapered ribbon in the member colour
169
+ private trailGlow: THREE.Mesh; // wider additive halo under it
170
+ private trailPts: Float32Array = new Float32Array(0); // x,y per trail point, craft first
171
+ private trailT: Float32Array = new Float32Array(0); // 0 at the craft, 1 at the trail's end
172
+ private trailCount = 0;
173
+ private memberRgb = [1, 1, 1];
174
+ private ghost: THREE.Line; // the current member's complete orbit
175
+ private family: THREE.LineSegments; // other members, coloured by parameter with per-vertex alpha
176
+ private craft: THREE.Points;
177
+ private primary: THREE.Points;
178
+ private secondary: THREE.Points;
179
+ private primaryTrail: THREE.Line;
180
+ private secondaryTrail: THREE.Line;
181
+ private grid: THREE.GridHelper;
182
+ private ro: ResizeObserver;
183
+ private userMoved = false;
184
+
185
+ constructor(host: HTMLElement, frame: FrameId = 'rotating_pulsating') {
186
+ this.host = host;
187
+ this.frame = frame;
188
+ this.canvas = document.createElement('canvas');
189
+ this.overlay = document.createElement('canvas');
190
+ for (const c of [this.canvas, this.overlay]) {
191
+ c.style.position = 'absolute';
192
+ c.style.inset = '0';
193
+ c.style.width = '100%';
194
+ c.style.height = '100%';
195
+ }
196
+ this.overlay.style.pointerEvents = 'none';
197
+ host.style.position = 'relative';
198
+ host.appendChild(this.canvas);
199
+ host.appendChild(this.overlay);
200
+
201
+ this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true, preserveDrawingBuffer: true });
202
+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
203
+ this.renderer.setClearColor(new THREE.Color(this.palette.background), 1);
204
+
205
+ this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, -100, 100);
206
+ this.camera.position.set(0, 0, 10);
207
+ this.camera.up.set(0, 1, 0);
208
+
209
+ this.controls = new OrbitControls(this.camera, this.canvas);
210
+ this.controls.enableDamping = false;
211
+ this.controls.screenSpacePanning = true;
212
+ this.controls.zoomToCursor = true;
213
+ this.controls.addEventListener('change', () => {
214
+ this.userMoved = true;
215
+ this.render();
216
+ });
217
+
218
+ const tex = discTexture();
219
+ // a 4-component colour attribute gives per-vertex alpha in three.js
220
+ this.family = new THREE.LineSegments(
221
+ new THREE.BufferGeometry(),
222
+ new THREE.LineBasicMaterial({ vertexColors: true, transparent: true, opacity: 1, depthTest: false }),
223
+ );
224
+ this.family.visible = false;
225
+ this.ghost = line('#d0d0d0', 0.8, 2); // the current member's complete orbit, recoloured per member
226
+ this.orbit = line('#ffffff', 1, 2); // the trail's centre line, recoloured per member
227
+ const ribbon = (blending: THREE.Blending) =>
228
+ new THREE.Mesh(
229
+ new THREE.BufferGeometry(),
230
+ new THREE.MeshBasicMaterial({ vertexColors: true, transparent: true, depthTest: false, depthWrite: false, blending, side: THREE.DoubleSide }),
231
+ );
232
+ this.trailGlow = ribbon(THREE.AdditiveBlending);
233
+ this.trailCore = ribbon(THREE.NormalBlending);
234
+ this.primaryTrail = line(this.palette.primary, 0.3, 2);
235
+ this.secondaryTrail = line(this.palette.secondary, 0.3, 2);
236
+ this.craft = points(this.palette.craft, 9, tex, 1);
237
+ this.primary = points(this.palette.primary, 8, tex, 1);
238
+ this.secondary = points(this.palette.secondary, 6, tex, 1);
239
+ this.grid = new THREE.GridHelper(4, 16, this.palette.axis, this.palette.grid);
240
+ this.grid.rotation.x = Math.PI / 2;
241
+ this.grid.visible = false;
242
+ const stack: THREE.Object3D[] = [
243
+ this.grid,
244
+ this.family,
245
+ this.primaryTrail,
246
+ this.secondaryTrail,
247
+ this.ghost,
248
+ this.trailGlow,
249
+ this.trailCore,
250
+ this.orbit,
251
+ this.primary,
252
+ this.secondary,
253
+ this.craft,
254
+ ];
255
+ stack.forEach((o, i) => (o.renderOrder = i));
256
+ this.scene.add(...stack);
257
+ this.setThreeD(false);
258
+
259
+ this.ro = new ResizeObserver(() => this.resize());
260
+ this.ro.observe(host);
261
+ this.resize();
262
+ }
263
+
264
+ dispose(): void {
265
+ cancelAnimationFrame(this.fadeRaf);
266
+ this.ro.disconnect();
267
+ this.controls.dispose();
268
+ this.renderer.dispose();
269
+ }
270
+
271
+ get system(): ER3BPSystem {
272
+ return this.sys;
273
+ }
274
+
275
+ get epoch(): number {
276
+ return this.fNow;
277
+ }
278
+
279
+ /** Colour of the current member in this frame's colormap. */
280
+ private memberColor(): string {
281
+ const r = this.paramRange;
282
+ const u = r && r[1] > r[0] ? (this.sys.e - r[0]) / (r[1] - r[0]) : 0.5;
283
+ return colormapCss(this.spec().cmap, u);
284
+ }
285
+
286
+ /**
287
+ * Loads the current member: M (x, y) rotating-pulsating pairs and M relative
288
+ * true anomalies (increasing). The camera is left alone unless `refit`.
289
+ */
290
+ setTrajectory(xy: Float32Array, fRel: ArrayLike<number>, sys: ER3BPSystem, refit = false): void {
291
+ const changed = sys.e !== this.sys.e;
292
+ this.xy = xy;
293
+ this.fRel = fRel;
294
+ this.sys = sys;
295
+ const m = fRel.length;
296
+ if (this.xyz.length !== 3 * m) {
297
+ this.xyz = new Float32Array(3 * m);
298
+ for (const l of [this.ghost, this.primaryTrail, this.secondaryTrail]) {
299
+ l.geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * m), 3));
300
+ }
301
+ // one extra vertex for the interpolated spacecraft position
302
+ this.orbit.geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * (m + 1)), 3));
303
+ const P = m + 3; // samples, the craft, and two nose points
304
+ this.trailPts = new Float32Array(2 * P);
305
+ this.trailT = new Float32Array(P);
306
+ const index: number[] = [];
307
+ for (let i = 0; i < P - 1; i++) index.push(2 * i, 2 * i + 1, 2 * i + 2, 2 * i + 1, 2 * i + 3, 2 * i + 2);
308
+ for (const r of [this.trailCore, this.trailGlow]) {
309
+ r.geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(6 * P), 3));
310
+ r.geometry.setAttribute('color', new THREE.BufferAttribute(new Float32Array(8 * P), 4));
311
+ r.geometry.setIndex(index);
312
+ r.frustumCulled = false;
313
+ }
314
+ }
315
+ this.recompute();
316
+ if (changed) this.focusFamily(false);
317
+ if (refit) this.fit();
318
+ }
319
+
320
+ /** Family ghosts: all members of `tracks`, drawn according to `mode`. */
321
+ setFamily(tracks: FamilyTracks | null, mode: FamilyMode): void {
322
+ const rebuild = tracks !== this.tracks;
323
+ this.tracks = tracks;
324
+ this.familyMode = tracks ? mode : 'hidden';
325
+ if (rebuild) this.rebuildFamily();
326
+ this.family.visible = this.familyMode !== 'hidden' && !!tracks;
327
+ this.focusFamily(true);
328
+ this.recolour();
329
+ this.render();
330
+ }
331
+
332
+ setFrame(frame: FrameId): void {
333
+ if (frame === this.frame) return;
334
+ this.frame = frame;
335
+ this.recompute();
336
+ this.rebuildFamily();
337
+ this.fit();
338
+ }
339
+
340
+ setThreeD(on: boolean): void {
341
+ this.threeD = on;
342
+ this.controls.enableRotate = on;
343
+ this.controls.mouseButtons = on
344
+ ? { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN }
345
+ : { LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };
346
+ this.controls.touches = on
347
+ ? { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN }
348
+ : { ONE: THREE.TOUCH.PAN, TWO: THREE.TOUCH.DOLLY_PAN };
349
+ this.grid.visible = on;
350
+ this.overlay.style.display = on ? 'none' : '';
351
+ if (!on) this.fit();
352
+ else this.render();
353
+ }
354
+
355
+ private spec() {
356
+ return FRAMES.find((f) => f.id === this.frame)!;
357
+ }
358
+
359
+ /** Rebuilds the family geometry (positions and RGB) for the current frame; alpha comes from the highlight. */
360
+ private rebuildFamily(): void {
361
+ const t = this.tracks;
362
+ if (!t) {
363
+ this.paramRange = null;
364
+ this.family.visible = false;
365
+ return;
366
+ }
367
+ const n = t.count;
368
+ const m = t.samples;
369
+ let pmin = Infinity;
370
+ let pmax = -Infinity;
371
+ for (let i = 0; i < n; i++) {
372
+ pmin = Math.min(pmin, t.params[i]);
373
+ pmax = Math.max(pmax, t.params[i]);
374
+ }
375
+ this.paramRange = [pmin, pmax];
376
+ if (this.alphaNow.length !== n) {
377
+ this.alphaNow = new Float32Array(n);
378
+ this.alphaFrom = new Float32Array(n);
379
+ this.alphaTo = new Float32Array(n);
380
+ this.baseAlpha = new Float32Array(n);
381
+ this.written = new Float32Array(n);
382
+ }
383
+ this.written.fill(-2); // force a full write after the geometry is rebuilt
384
+ const segs = n * (m - 1);
385
+ const pos = new Float32Array(segs * 6);
386
+ const col = new Float32Array(segs * 8);
387
+ const tmp = new Float32Array(3 * m);
388
+ const rgb = [0, 0, 0];
389
+ const cmap = this.spec().cmap;
390
+ let o = 0;
391
+ let c = 0;
392
+ for (let i = 0; i < n; i++) {
393
+ const xy = t.positions.subarray(i * m * 2, (i + 1) * m * 2);
394
+ const f = t.anomalies.subarray(i * m, (i + 1) * m);
395
+ transformTrajectory(xy, f, { mu: t.mu, e: t.params[i], f0: t.f0 }, this.frame, tmp);
396
+ const u = pmax > pmin ? (t.params[i] - pmin) / (pmax - pmin) : 0.5;
397
+ colormap(cmap, u, rgb);
398
+ const a = 0;
399
+ for (let k = 0; k < m - 1; k++) {
400
+ pos[o] = tmp[3 * k];
401
+ pos[o + 1] = tmp[3 * k + 1];
402
+ pos[o + 2] = 0;
403
+ pos[o + 3] = tmp[3 * k + 3];
404
+ pos[o + 4] = tmp[3 * k + 4];
405
+ pos[o + 5] = 0;
406
+ o += 6;
407
+ col[c] = col[c + 4] = rgb[0];
408
+ col[c + 1] = col[c + 5] = rgb[1];
409
+ col[c + 2] = col[c + 6] = rgb[2];
410
+ col[c + 3] = col[c + 7] = a;
411
+ c += 8;
412
+ }
413
+ }
414
+ const g = this.family.geometry;
415
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
416
+ g.setAttribute('color', new THREE.BufferAttribute(col, 4));
417
+ g.computeBoundingSphere();
418
+ this.family.visible = this.familyMode !== 'hidden';
419
+ }
420
+
421
+ /**
422
+ * Target alphas for the current member's neighbourhood: a Gaussian band over
423
+ * parameter distance on top of the sparse context set, then either applied at
424
+ * once or reached by asymmetric relaxation (fast in, slower out).
425
+ */
426
+ private focusFamily(immediate = false): void {
427
+ const t = this.tracks;
428
+ const r = this.paramRange;
429
+ if (!t || !r) return;
430
+ const n = t.count;
431
+ const range = Math.max(1e-9, r[1] - r[0]);
432
+ const sigma = NEIGHBOUR_SIGMA * range;
433
+ const stride = Math.max(1, Math.round(n / SPARSE_COUNT));
434
+ let current = -1;
435
+ for (let i = 0; i < n; i++) if (t.params[i] === this.sys.e) current = i;
436
+ for (let i = 0; i < n; i++) {
437
+ const sparse = this.familyMode === 'family' && (i % stride === 0 || i === n - 1);
438
+ const d = (t.params[i] - this.sys.e) / sigma;
439
+ this.baseAlpha[i] = sparse && i !== current ? SPARSE_ALPHA : 0;
440
+ this.alphaTo[i] = i === current ? 0 : NEIGHBOUR_PEAK * Math.exp(-d * d);
441
+ }
442
+ if (this.familyMode === 'hidden') {
443
+ this.alphaTo.fill(0);
444
+ this.baseAlpha.fill(0);
445
+ }
446
+ cancelAnimationFrame(this.fadeRaf);
447
+ if (immediate || this.familyMode === 'hidden') {
448
+ this.alphaNow.set(this.alphaTo);
449
+ this.writeAlpha();
450
+ return;
451
+ }
452
+ this.fadeLast = performance.now();
453
+ const step = (now: number) => {
454
+ const dt = Math.max(0, now - this.fadeLast);
455
+ this.fadeLast = now;
456
+ const up = 1 - Math.exp(-dt / RISE_MS);
457
+ const down = 1 - Math.exp(-dt / DECAY_MS);
458
+ let maxDiff = 0;
459
+ for (let i = 0; i < n; i++) {
460
+ const a = this.alphaNow[i];
461
+ const b = this.alphaTo[i];
462
+ const next = a + (b - a) * (b > a ? up : down);
463
+ this.alphaNow[i] = next;
464
+ maxDiff = Math.max(maxDiff, Math.abs(b - next));
465
+ }
466
+ if (maxDiff < 0.004) this.alphaNow.set(this.alphaTo);
467
+ this.writeAlpha();
468
+ this.render();
469
+ if (maxDiff >= 0.004) this.fadeRaf = requestAnimationFrame(step);
470
+ };
471
+ this.fadeRaf = requestAnimationFrame(step);
472
+ }
473
+
474
+ /** Writes per-member alphas (context level or neighbourhood weight, whichever is larger) into the colour attribute. */
475
+ private writeAlpha(): void {
476
+ const t = this.tracks;
477
+ const attr = this.family.geometry.getAttribute('color') as THREE.BufferAttribute | undefined;
478
+ if (!t || !attr) return;
479
+ const col = attr.array as Float32Array;
480
+ const per = (t.samples - 1) * 8;
481
+ let dirty = false;
482
+ for (let i = 0; i < t.count; i++) {
483
+ const a = Math.max(this.baseAlpha[i], this.alphaNow[i]);
484
+ if (this.written[i] === a) continue;
485
+ const start = i * per;
486
+ for (let c = start + 3; c < start + per; c += 4) col[c] = a;
487
+ this.written[i] = a;
488
+ dirty = true;
489
+ }
490
+ if (dirty) attr.needsUpdate = true;
491
+ }
492
+
493
+ /** Recolours the current member's trail and complete orbit with its colormap colour. */
494
+ private recolour(): void {
495
+ const css = this.memberColor();
496
+ (this.orbit.material as THREE.LineBasicMaterial).color.set(css);
497
+ (this.ghost.material as THREE.LineBasicMaterial).color.set(css);
498
+ const r = this.paramRange;
499
+ const u = r && r[1] > r[0] ? (this.sys.e - r[0]) / (r[1] - r[0]) : 0.5;
500
+ colormap(this.spec().cmap, u, this.memberRgb);
501
+ }
502
+
503
+ /** Recomputes the transformed member track and body trails for the current frame. */
504
+ private recompute(): void {
505
+ const m = this.fRel.length;
506
+ if (!m) return;
507
+ transformTrajectory(this.xy, this.fRel, this.sys, this.frame, this.xyz);
508
+ (this.ghost.geometry.getAttribute('position') as THREE.BufferAttribute).set(this.xyz).needsUpdate = true;
509
+ this.ghost.geometry.setDrawRange(0, m);
510
+ this.recolour();
511
+ const pt = this.primaryTrail.geometry.getAttribute('position') as THREE.BufferAttribute;
512
+ const st = this.secondaryTrail.geometry.getAttribute('position') as THREE.BufferAttribute;
513
+ bodyTrail('primary', this.fRel, this.sys, this.frame, pt.array as Float32Array);
514
+ bodyTrail('secondary', this.fRel, this.sys, this.frame, st.array as Float32Array);
515
+ pt.needsUpdate = st.needsUpdate = true;
516
+ this.primaryTrail.geometry.setDrawRange(0, m);
517
+ this.secondaryTrail.geometry.setDrawRange(0, m);
518
+ for (const l of [this.ghost, this.primaryTrail, this.secondaryTrail]) l.geometry.computeBoundingSphere();
519
+ this.showAt(this.fNow);
520
+ }
521
+
522
+ /**
523
+ * Draws the epoch `fRel` (relative true anomaly): the trail cut from the stored
524
+ * track up to the bracketing sample plus an interpolated end point, the craft
525
+ * interpolated on the same segment, and the bodies at the exact epoch.
526
+ */
527
+ showAt(fRel: number): void {
528
+ const m = this.fRel.length;
529
+ if (!m) return;
530
+ const f = this.fRel;
531
+ const fr = Math.max(f[0], Math.min(f[m - 1], fRel));
532
+ this.fNow = fr;
533
+ const k = segmentIndex(f, fr);
534
+ const span = f[k + 1] - f[k];
535
+ const u = span > 0 ? (fr - f[k]) / span : 0;
536
+ const x = this.xyz[3 * k] + (this.xyz[3 * k + 3] - this.xyz[3 * k]) * u;
537
+ const y = this.xyz[3 * k + 1] + (this.xyz[3 * k + 4] - this.xyz[3 * k + 1]) * u;
538
+
539
+ // trail points, craft first, walking back along the orbit (wrapping, since it is periodic)
540
+ const period = f[m - 1] - f[0];
541
+ const L = TRAIL_FRACTION * period;
542
+ const pts = this.trailPts;
543
+ const tt = this.trailT;
544
+ let n = 0;
545
+ pts[0] = x;
546
+ pts[1] = y;
547
+ tt[0] = 0;
548
+ n = 1;
549
+ let idx = k;
550
+ let wrapped = false;
551
+ while (n < m) {
552
+ const behind = (wrapped ? fr + period : fr) - f[idx];
553
+ if (behind >= L) {
554
+ // end the trail exactly at length L by interpolating toward this sample
555
+ const prev = tt[n - 1] * L;
556
+ const w = (L - prev) / Math.max(1e-12, behind - prev);
557
+ pts[2 * n] = pts[2 * n - 2] + (this.xyz[3 * idx] - pts[2 * n - 2]) * w;
558
+ pts[2 * n + 1] = pts[2 * n - 1] + (this.xyz[3 * idx + 1] - pts[2 * n - 1]) * w;
559
+ tt[n] = 1;
560
+ n++;
561
+ break;
562
+ }
563
+ pts[2 * n] = this.xyz[3 * idx];
564
+ pts[2 * n + 1] = this.xyz[3 * idx + 1];
565
+ tt[n] = behind / L;
566
+ n++;
567
+ if (idx === 0) {
568
+ if (wrapped) break;
569
+ wrapped = true;
570
+ idx = m - 2;
571
+ } else idx--;
572
+ }
573
+ // shape the nose: two extra points on the first segment so the taper from the craft is smooth
574
+ if (n >= 2 && tt[1] > TRAIL_NOSE) {
575
+ for (let i = n - 1; i >= 1; i--) {
576
+ pts[2 * (i + 2)] = pts[2 * i];
577
+ pts[2 * (i + 2) + 1] = pts[2 * i + 1];
578
+ tt[i + 2] = tt[i];
579
+ }
580
+ const seg = tt[3];
581
+ for (let j = 1; j <= 2; j++) {
582
+ const t = (TRAIL_NOSE * j) / 2;
583
+ const w = t / seg;
584
+ pts[2 * j] = pts[0] + (pts[6] - pts[0]) * w;
585
+ pts[2 * j + 1] = pts[1] + (pts[7] - pts[1]) * w;
586
+ tt[j] = t;
587
+ }
588
+ n += 2;
589
+ }
590
+ this.trailCount = n;
591
+ const line = this.orbit.geometry.getAttribute('position') as THREE.BufferAttribute;
592
+ const larr = line.array as Float32Array;
593
+ for (let i = 0; i < n; i++) {
594
+ larr[3 * i] = pts[2 * i];
595
+ larr[3 * i + 1] = pts[2 * i + 1];
596
+ larr[3 * i + 2] = 0;
597
+ }
598
+ line.needsUpdate = true;
599
+ this.orbit.geometry.setDrawRange(0, n);
600
+ this.ghost.visible = this.showGhost;
601
+
602
+ const set = (p: THREE.Points, px: number, py: number) => {
603
+ const a = p.geometry.getAttribute('position') as THREE.BufferAttribute;
604
+ a.setXYZ(0, px, py, 0);
605
+ a.needsUpdate = true;
606
+ };
607
+ set(this.craft, x, y);
608
+ const fAbs = this.sys.f0 + fr;
609
+ const tmp = new Float32Array(2);
610
+ bodyPosition('primary', this.sys, this.frame, fAbs, tmp);
611
+ set(this.primary, tmp[0], tmp[1]);
612
+ bodyPosition('secondary', this.sys, this.frame, fAbs, tmp);
613
+ set(this.secondary, tmp[0], tmp[1]);
614
+ this.render();
615
+ }
616
+
617
+ /** Fits the camera to the member's orbit plus body trails, resetting any user pan or zoom. */
618
+ fit(): void {
619
+ const m = this.fRel.length;
620
+ if (!m) return;
621
+ const box = new THREE.Box3();
622
+ for (const l of [this.ghost, this.primaryTrail, this.secondaryTrail]) {
623
+ l.geometry.computeBoundingBox();
624
+ if (l.geometry.boundingBox) box.union(l.geometry.boundingBox);
625
+ }
626
+ const size = new THREE.Vector3();
627
+ const centre = new THREE.Vector3();
628
+ box.getSize(size);
629
+ box.getCenter(centre);
630
+ const w = Math.max(size.x, 1e-6) * 1.15;
631
+ const h = Math.max(size.y, 1e-6) * 1.15;
632
+ const aspect = this.aspect();
633
+ this.camera.zoom = Math.min((2 * aspect) / w, 2 / h);
634
+ this.camera.position.set(centre.x, centre.y, 10);
635
+ this.camera.up.set(0, 1, 0);
636
+ this.controls.target.set(centre.x, centre.y, 0);
637
+ this.camera.updateProjectionMatrix();
638
+ this.controls.update();
639
+ this.userMoved = false;
640
+ this.render();
641
+ }
642
+
643
+ private aspect(): number {
644
+ const r = this.host.getBoundingClientRect();
645
+ return Math.max(r.width, 1) / Math.max(r.height, 1);
646
+ }
647
+
648
+ resize(): void {
649
+ const r = this.host.getBoundingClientRect();
650
+ const w = Math.max(1, Math.floor(r.width));
651
+ const h = Math.max(1, Math.floor(r.height));
652
+ this.renderer.setSize(w, h, false);
653
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
654
+ this.overlay.width = Math.floor(w * dpr);
655
+ this.overlay.height = Math.floor(h * dpr);
656
+ const aspect = w / h;
657
+ this.camera.left = -aspect;
658
+ this.camera.right = aspect;
659
+ this.camera.top = 1;
660
+ this.camera.bottom = -1;
661
+ this.camera.updateProjectionMatrix();
662
+ if (!this.userMoved) this.fit();
663
+ else this.render();
664
+ }
665
+
666
+ /** World rectangle visible through the axis-aligned orthographic camera. */
667
+ private visibleRect(): { x0: number; x1: number; y0: number; y1: number } {
668
+ const hw = (this.camera.right - this.camera.left) / (2 * this.camera.zoom);
669
+ const hh = (this.camera.top - this.camera.bottom) / (2 * this.camera.zoom);
670
+ const cx = this.camera.position.x;
671
+ const cy = this.camera.position.y;
672
+ return { x0: cx - hw, x1: cx + hw, y0: cy - hh, y1: cy + hh };
673
+ }
674
+
675
+ /** World units per CSS pixel through the orthographic camera. */
676
+ private pixelSize(): number {
677
+ const w = Math.max(1, this.host.getBoundingClientRect().width);
678
+ return (this.camera.right - this.camera.left) / (this.camera.zoom * w);
679
+ }
680
+
681
+ /** Lays the trail ribbons out from the trail points at the current zoom: width and alpha taper along the trail. */
682
+ private layoutRibbon(): void {
683
+ const n = this.trailCount;
684
+ const px = this.pixelSize();
685
+ const [r, g, b] = this.memberRgb;
686
+ for (const [mesh, widthPx, alphaScale] of [
687
+ [this.trailCore, TRAIL_CORE_PX, 1],
688
+ [this.trailGlow, TRAIL_GLOW_PX, 0.32],
689
+ ] as [THREE.Mesh, number, number][]) {
690
+ const pos = mesh.geometry.getAttribute('position') as THREE.BufferAttribute | undefined;
691
+ const col = mesh.geometry.getAttribute('color') as THREE.BufferAttribute | undefined;
692
+ if (!pos || !col || n < 2) {
693
+ mesh.visible = false;
694
+ continue;
695
+ }
696
+ mesh.visible = true;
697
+ const P = pos.array as Float32Array;
698
+ const C = col.array as Float32Array;
699
+ const pts = this.trailPts;
700
+ for (let i = 0; i < n; i++) {
701
+ const i0 = Math.max(0, i - 1);
702
+ const i1 = Math.min(n - 1, i + 1);
703
+ let tx = pts[2 * i1] - pts[2 * i0];
704
+ let ty = pts[2 * i1 + 1] - pts[2 * i0 + 1];
705
+ const len = Math.hypot(tx, ty) || 1;
706
+ tx /= len;
707
+ ty /= len;
708
+ const t = this.trailT[i];
709
+ const nose = t < TRAIL_NOSE ? 1 - Math.pow(1 - t / TRAIL_NOSE, 2) : 1; // pointed at the craft
710
+ const taper = Math.pow(1 - t, 0.8) * nose;
711
+ const half = 0.5 * widthPx * px * taper;
712
+ const nx = -ty * half;
713
+ const ny = tx * half;
714
+ const x = pts[2 * i];
715
+ const y = pts[2 * i + 1];
716
+ P[6 * i] = x + nx;
717
+ P[6 * i + 1] = y + ny;
718
+ P[6 * i + 2] = 0;
719
+ P[6 * i + 3] = x - nx;
720
+ P[6 * i + 4] = y - ny;
721
+ P[6 * i + 5] = 0;
722
+ const a = alphaScale * Math.pow(1 - t, 1.6);
723
+ C[8 * i] = C[8 * i + 4] = r;
724
+ C[8 * i + 1] = C[8 * i + 5] = g;
725
+ C[8 * i + 2] = C[8 * i + 6] = b;
726
+ C[8 * i + 3] = C[8 * i + 7] = a;
727
+ }
728
+ pos.needsUpdate = col.needsUpdate = true;
729
+ mesh.geometry.setDrawRange(0, (n - 1) * 6);
730
+ }
731
+ }
732
+
733
+ render(): void {
734
+ this.layoutRibbon();
735
+ this.renderer.render(this.scene, this.camera);
736
+ if (!this.threeD) this.drawOverlay();
737
+ }
738
+
739
+ /** Grid, ticks, axis titles, frame name and colourbar, in CSS pixels on the overlay canvas. */
740
+ private drawOverlay(): void {
741
+ const g = this.overlay.getContext('2d');
742
+ if (!g) return;
743
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
744
+ const W = this.overlay.width / dpr;
745
+ const H = this.overlay.height / dpr;
746
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
747
+ g.clearRect(0, 0, W, H);
748
+ const { x0, x1, y0, y1 } = this.visibleRect();
749
+ const sx = (x: number) => ((x - x0) / (x1 - x0)) * W;
750
+ const sy = (y: number) => H - ((y - y0) / (y1 - y0)) * H;
751
+ const font = '12px "Helvetica Neue", Arial, sans-serif';
752
+ g.font = font;
753
+ g.lineWidth = 1;
754
+
755
+ const stepX = niceStep(x1 - x0, Math.max(3, W / 110));
756
+ const stepY = niceStep(y1 - y0, Math.max(3, H / 70));
757
+ const decimals = (s: number) => Math.max(0, -Math.floor(Math.log10(s)));
758
+ const dx = decimals(stepX);
759
+ const dy = decimals(stepY);
760
+
761
+ g.strokeStyle = this.palette.grid;
762
+ g.fillStyle = this.palette.text;
763
+ g.textAlign = 'center';
764
+ g.textBaseline = 'top';
765
+ for (let x = Math.ceil(x0 / stepX) * stepX; x <= x1; x += stepX) {
766
+ const px = Math.round(sx(x)) + 0.5;
767
+ g.beginPath();
768
+ g.moveTo(px, 0);
769
+ g.lineTo(px, H);
770
+ g.stroke();
771
+ if (px > 56) g.fillText((Math.abs(x) < 1e-12 ? 0 : x).toFixed(dx), px, H - 30);
772
+ }
773
+ g.textAlign = 'right';
774
+ g.textBaseline = 'middle';
775
+ for (let y = Math.ceil(y0 / stepY) * stepY; y <= y1; y += stepY) {
776
+ const py = Math.round(sy(y)) + 0.5;
777
+ g.beginPath();
778
+ g.moveTo(0, py);
779
+ g.lineTo(W, py);
780
+ g.stroke();
781
+ if (py < H - 40 && py > 22) g.fillText((Math.abs(y) < 1e-12 ? 0 : y).toFixed(dy), 44, py);
782
+ }
783
+ g.strokeStyle = this.palette.axis;
784
+ if (x0 < 0 && x1 > 0) {
785
+ const px = Math.round(sx(0)) + 0.5;
786
+ g.beginPath();
787
+ g.moveTo(px, 0);
788
+ g.lineTo(px, H);
789
+ g.stroke();
790
+ }
791
+ if (y0 < 0 && y1 > 0) {
792
+ const py = Math.round(sy(0)) + 0.5;
793
+ g.beginPath();
794
+ g.moveTo(0, py);
795
+ g.lineTo(W, py);
796
+ g.stroke();
797
+ }
798
+ const spec = this.spec();
799
+ const halo = (text: string, x: number, y: number) => {
800
+ g.strokeStyle = this.palette.background;
801
+ g.lineWidth = 4;
802
+ g.lineJoin = 'round';
803
+ g.strokeText(text, x, y);
804
+ g.fillStyle = this.palette.text;
805
+ g.fillText(text, x, y);
806
+ g.lineWidth = 1;
807
+ };
808
+ g.font = '13px "Helvetica Neue", Arial, sans-serif';
809
+ g.textAlign = 'center';
810
+ g.textBaseline = 'top';
811
+ if (this.showTitle) halo(spec.label, W / 2, 8);
812
+ g.textBaseline = 'bottom';
813
+ halo(spec.axes[0], W / 2, H - 6);
814
+ g.save();
815
+ g.translate(14, H / 2);
816
+ g.rotate(-Math.PI / 2);
817
+ g.textBaseline = 'middle';
818
+ halo(spec.axes[1], 0, 0);
819
+ g.restore();
820
+
821
+ // colourbar for the family, with the highlighted band and a marker at the current member
822
+ if (this.paramRange && this.tracks) {
823
+ const [lo, hi] = this.paramRange;
824
+ const bw = 8;
825
+ const bh = Math.min(H * 0.5, 220);
826
+ const bx = W - 46;
827
+ const by = (H - bh) / 2;
828
+ const grad = g.createLinearGradient(0, by + bh, 0, by);
829
+ for (let i = 0; i <= 10; i++) grad.addColorStop(i / 10, colormapCss(spec.cmap, i / 10));
830
+ g.fillStyle = grad;
831
+ g.fillRect(bx, by, bw, bh);
832
+ g.strokeStyle = this.palette.axis;
833
+ g.strokeRect(bx + 0.5, by + 0.5, bw, bh);
834
+ g.fillStyle = this.palette.text;
835
+ g.font = font;
836
+ g.textAlign = 'left';
837
+ g.textBaseline = 'middle';
838
+ const ticks = 4;
839
+ for (let i = 0; i <= ticks; i++) {
840
+ const v = lo + ((hi - lo) * i) / ticks;
841
+ const py = by + bh - (bh * i) / ticks;
842
+ g.fillText(v.toFixed(2), bx + bw + 5, py);
843
+ }
844
+ g.textAlign = 'center';
845
+ g.textBaseline = 'bottom';
846
+ g.fillText('e', bx + bw / 2, by - 4);
847
+ if (hi > lo) {
848
+ const py = by + bh - (bh * (this.sys.e - lo)) / (hi - lo);
849
+ if (this.familyMode !== 'hidden') {
850
+ const half = bh * NEIGHBOUR_SIGMA * 1.5;
851
+ g.fillStyle = 'rgba(255,255,255,0.18)';
852
+ g.fillRect(bx - 3, py - half, bw + 6, 2 * half);
853
+ }
854
+ g.fillStyle = this.palette.text;
855
+ g.beginPath();
856
+ g.moveTo(bx - 2, py);
857
+ g.lineTo(bx - 8, py - 4);
858
+ g.lineTo(bx - 8, py + 4);
859
+ g.closePath();
860
+ g.fill();
861
+ }
862
+ }
863
+ }
864
+ }