astraeus 0.4.0 → 0.5.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +64 -10
  3. package/data/ephemerides/planets/planets.json +1 -1
  4. package/package.json +1 -1
  5. package/src/api/AstraeusScene.d.ts +9 -1
  6. package/src/api/AstraeusScene.js +26 -4
  7. package/src/api/AstraeusScene.node.js +26 -4
  8. package/src/api/data.js +11 -1
  9. package/src/api/errors.d.ts +1 -1
  10. package/src/api/index.d.ts +2 -1
  11. package/src/api/mount.d.ts +16 -0
  12. package/src/api/mount.js +13 -1
  13. package/src/api/mount.node.js +13 -1
  14. package/src/api/pathProvenance.d.ts +10 -0
  15. package/src/api/pathProvenance.js +34 -0
  16. package/src/api/scene.d.ts +7 -1
  17. package/src/api/scene.js +103 -14
  18. package/src/api/story.d.ts +41 -1
  19. package/src/api/story.js +63 -1
  20. package/src/api/sunOrbit.d.ts +3 -3
  21. package/src/api/sunOrbit.js +92 -24
  22. package/src/api/viewerLink.d.ts +40 -0
  23. package/src/api/viewerLink.js +86 -0
  24. package/src/app/App.d.ts +4 -1
  25. package/src/app/App.js +42 -6
  26. package/src/app/App.node.js +42 -6
  27. package/src/app/AstraeusScene.d.ts +7 -0
  28. package/src/app/BodySetView.js +3 -2
  29. package/src/app/KeplerPoints.d.ts +1 -1
  30. package/src/app/KeplerPoints.js +3 -2
  31. package/src/app/PointsView.js +3 -2
  32. package/src/app/TrackedBodyView.js +3 -2
  33. package/src/app/bodyDraw.js +3 -2
  34. package/src/app/dotMaterial.d.ts +11 -0
  35. package/src/app/dotMaterial.js +38 -0
  36. package/src/app/experienceDefinition.d.ts +12 -0
  37. package/src/app/mission.d.ts +1 -1
  38. package/src/app/mission.js +1 -1
  39. package/src/app/openClock.d.ts +1 -1
  40. package/src/app/openClock.js +3 -0
  41. package/src/app/sceneContentsHooks.js +2 -1
  42. package/src/app/sceneFrame.d.ts +2 -2
  43. package/src/app/sceneFrame.js +6 -1
  44. package/src/app/sceneFraming.d.ts +1 -1
  45. package/src/app/sceneFraming.js +9 -3
  46. package/src/app/viewerPort.d.ts +33 -0
  47. package/src/app/viewerPort.js +1 -0
  48. package/src/core/bodies/io.js +1 -1
  49. package/src/core/bodies/jupiterMoons.d.ts +1 -1
  50. package/src/core/bodies/jupiterMoons.js +6 -6
  51. package/src/core/bodies/moonSystem.d.ts +15 -1
  52. package/src/core/bodies/moonSystem.js +58 -7
  53. package/src/core/bodies/outerPlanets.js +1 -1
  54. package/src/core/bodies/planetMoons.js +10 -10
  55. package/src/core/chebyshevEphemeris.d.ts +7 -1
  56. package/src/core/chebyshevEphemeris.js +24 -7
  57. package/src/core/clock.d.ts +8 -0
  58. package/src/core/clock.js +14 -0
  59. package/src/core/pacing.d.ts +24 -0
  60. package/src/core/pacing.js +35 -0
  61. package/src/core/planetModels.d.ts +4 -1
  62. package/src/core/planetModels.js +6 -1
  63. package/src/core/planetSeries.d.ts +3 -0
  64. package/src/core/planetSeries.js +8 -1
  65. package/src/core/timeWindow.d.ts +2 -0
  66. package/src/core/timeWindow.js +4 -3
  67. package/src/shell/AstraeusShell.d.ts +6 -2
  68. package/src/shell/AstraeusShell.js +3 -3
  69. package/src/shell/AstraeusShell.node.js +3 -3
  70. package/src/shell/TimelineBar.d.ts +4 -2
  71. package/src/shell/TimelineBar.js +15 -6
  72. package/src/shell/TimelineBar.node.js +15 -6
  73. package/src/shell/experience.d.ts +3 -1
  74. package/src/shell/infoModel.js +5 -4
  75. package/src/shell/timelineModel.d.ts +2 -3
  76. package/src/shell/timelineModel.js +3 -11
  77. package/src/synthetic/syntheticJourneyScene.d.ts +9 -0
  78. package/src/synthetic/syntheticJourneyScene.js +75 -0
package/src/api/scene.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { createProvenance } from "../core/provenance.js";
2
+ import { planPathProvenance } from "./pathProvenance.js";
2
3
  import { SampledTrajectory } from "../core/sampledTrajectory.js";
3
4
  import { readableScale, solarSystemScale, trueScale } from "../core/scalePolicy.js";
4
5
  import { createState } from "../core/state.js";
5
6
  import { createOrbTwoBodyAdapter } from "../core/twoBodyAdapter.js";
6
7
  import { createStateResolver } from "../core/stateResolver.js";
7
8
  import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
8
- import { loadPlanetSeries, planetSeriesLoaded } from "../core/planetSeries.js";
9
+ import { isPlanetId, loadPlanetSeries, planetSeriesLoaded, planetSeriesSpan } from "../core/planetSeries.js";
9
10
  import { catalogue as builtInCatalogue, extendCatalogue, rootBodyId } from "../assets/catalogue.js";
10
11
  import { buildElementsBody, ElementsBodyError, parseElementsBodyRecord } from "../core/elementsBody.js";
11
12
  import { createComposition, SIDEREAL_MONTH_MS } from "../assets/compositions.js";
@@ -22,7 +23,8 @@ import { buildGroupLayer, planGroup } from "./group.js";
22
23
  import { SceneError } from "./errors.js";
23
24
  import { toUtcMs } from "./time.js";
24
25
  import { switchesOf } from "./switches.js";
25
- import { eventProvenanceOf, eventsOf, panelsOf, timelineOf } from "./story.js";
26
+ import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
27
+ import { eventProvenanceOf, eventsOf, pacingFor, panelsOf, timelineOf } from "./story.js";
26
28
  export { toUtcMs } from "./time.js";
27
29
  /** The orbits the engine can draw: the span one lap covers (the parent the line is measured from is the body's catalogue parent). */
28
30
  const ORBITS = {
@@ -33,6 +35,8 @@ const DEFAULT_COLOR = "#ffd27a";
33
35
  const DAY_MS = 86_400_000;
34
36
  const PROVIDER_PATH_SAMPLES = 128;
35
37
  const SCALES = [trueScale, readableScale, solarSystemScale];
38
+ /** Samples along a path when its farthest distance is read for the default zoom-out. */
39
+ const PATH_COVER_SAMPLES = 400;
36
40
  /** The scene's camera: what it opens on. */
37
41
  export class SceneCamera {
38
42
  #target;
@@ -176,7 +180,7 @@ export class Scene {
176
180
  }
177
181
  #register(call, id, ref, options) {
178
182
  if (options.orbit === true && ORBITS[id] === undefined && !(circlesTheSun(this.#catalogue, id)))
179
- throw new SceneError("no-orbit", `${call}("${id}", { orbit: true }): the engine draws the orbit line of ${Object.keys(ORBITS).join(" and ")} and of any body that circles the Sun`);
183
+ throw new SceneError("no-orbit", `${call}("${id}", { orbit: true }): the engine draws the orbit line of ${Object.keys(ORBITS).join(" and ")} and of any body that circles the Sun (every planet: its own source over a full turn where the source covers one, else the two-body ellipse osculating at the opening time)`);
180
184
  if (!this.#catalogue.has(id))
181
185
  throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${this.#catalogue.ids().join(", ")})`);
182
186
  if (this.#taken(id))
@@ -230,7 +234,8 @@ export class Scene {
230
234
  throw new SceneError("bad-trajectory", `addTrajectory("${id}"): plane "${String(input.plane)}" must be "EQJ" or "ecliptic-j2000"`);
231
235
  const toEqj = input.plane === "ecliptic-j2000" ? createOrbTwoBodyAdapter().eclipticJ2000ToEqjMatrix() : null;
232
236
  const body = "samples" in input ? sampledBody(common, input, center, toEqj) : providerBody(common, input, toEqj);
233
- this.#tracked.set(id, { center, body: withAnchors(body, input.anchors), readouts, ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
237
+ const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs });
238
+ this.#tracked.set(id, { center, body: withAnchors(body, input.anchors), readouts, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
234
239
  }
235
240
  /** Whether a body, path or group already has this id. */
236
241
  #taken(id) {
@@ -295,7 +300,7 @@ export class Scene {
295
300
  this.#panels = panels;
296
301
  return this;
297
302
  }
298
- /** Sets the timeline: its span (`start`, `end`), the speeds offered (`rates`), the speed it opens at (`rate`) and whether playback wraps from the end to the start (`loop`; ignored with `{ none: true }`, which has no span to wrap, and when `setTimeline` is not called), or `{ none: true }` for no timeline bar, with time frozen at `at` or running at `rate`. Without this call the span follows the paths and the speeds are 1 minute, 1 hour and 1 day per second. */
303
+ /** Sets the timeline: its span (`start`, `end`), the speeds offered (`rates`), the speed it opens at (`rate`), `pacing` (playback that slows for encounters and speeds up for cruise: spans `{ from, to, rate }` and event rules `{ near: { type, within }, rate }`, easing between speeds; a speed the visitor or host picks wins until `setRate("auto")`; see `PacingInput`) and whether playback wraps from the end to the start (`loop`; ignored with `{ none: true }`, which has no span to wrap, and when `setTimeline` is not called), or `{ none: true }` for no timeline bar, with time frozen at `at` or running at `rate`. Without this call the span follows the paths and the speeds are 1 minute, 1 hour and 1 day per second. */
299
304
  setTimeline(timeline) {
300
305
  this.#timeline = timelineOf(timeline);
301
306
  return this;
@@ -422,6 +427,54 @@ export class Scene {
422
427
  }
423
428
  }
424
429
  }
430
+ /** The `out-of-span` error naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded); undefined otherwise. */
431
+ #planetSpanError(ids, window) {
432
+ const planets = ids.filter(isPlanetId);
433
+ if (planets.length === 0 || !planetSeriesLoaded())
434
+ return undefined;
435
+ const span = planetSeriesSpan();
436
+ if (window.startUtcMs >= span.startUtcMs && window.endUtcMs <= span.endUtcMs)
437
+ return undefined;
438
+ const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
439
+ return new SceneError("out-of-span", `${planets.join(", ")} is outside the years the built-in planet series covers: it covers ${iso(span.startUtcMs)} to ${iso(span.endUtcMs)}, but the scene runs ${iso(window.startUtcMs)} to ${iso(window.endUtcMs)}; set the timeline inside that span`);
440
+ }
441
+ /** Throws `out-of-span` naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded). */
442
+ #checkPlanetSpan(ids, window) {
443
+ const error = this.#planetSpanError(ids, window);
444
+ if (error !== undefined)
445
+ throw error;
446
+ }
447
+ /**
448
+ * The one choke point for planet-series reads during setup (orbit lines, the fit distance, clump groups): checks the span first, and turns a
449
+ * `TimeScaleOutOfRangeError` from the read into the named `out-of-span` error when the window is outside the series, so no setup read can leak the raw one.
450
+ */
451
+ #planetRead(ids, window, read) {
452
+ this.#checkPlanetSpan(ids, window);
453
+ try {
454
+ return read();
455
+ }
456
+ catch (error) {
457
+ if (error instanceof TimeScaleOutOfRangeError)
458
+ throw this.#planetSpanError(ids, window) ?? error;
459
+ throw error;
460
+ }
461
+ }
462
+ /**
463
+ * A setup read in `toDefinition`: an `out-of-span` failure is recorded in `fault` and the read gives `fallback`, so `toDefinition` (and so `mount`) never throws it;
464
+ * `prepare` rejects with the recorded error, which is how it always arrives (once, as `ready` rejecting).
465
+ */
466
+ #deferredRead(ids, window, fault, fallback, read) {
467
+ try {
468
+ return this.#planetRead(ids, window, read);
469
+ }
470
+ catch (error) {
471
+ if (error instanceof SceneError && error.code === "out-of-span") {
472
+ fault.error ??= error;
473
+ return fallback;
474
+ }
475
+ throw error;
476
+ }
477
+ }
425
478
  /** Throws `missing-data` naming the bodies whose data package was not passed. */
426
479
  #checkData(data) {
427
480
  const missing = this.missingData(data);
@@ -473,19 +526,40 @@ export class Scene {
473
526
  return id;
474
527
  });
475
528
  }
529
+ /**
530
+ * The distance the default zoom-out must cover for the scene's paths about the scene centre (I-114): a path reaching past the planets must fit whole whichever point of it the camera looks at,
531
+ * so twice its farthest distance from the centre (no two points of a path are farther apart than that). Sampled over each path's span; undefined when no path is about the centre.
532
+ */
533
+ #pathCover(sunCentred, centre) {
534
+ if (!sunCentred)
535
+ return undefined;
536
+ const about = [...this.#tracked.values()].filter((entry) => entry.center === centre);
537
+ if (about.length === 0)
538
+ return undefined;
539
+ return () => 2 * Math.max(...about.map(({ body }) => {
540
+ const { startUtcMs, endUtcMs } = body.trajectory.bounds;
541
+ let farthest = 0;
542
+ for (let k = 0; k < PATH_COVER_SAMPLES; k += 1)
543
+ farthest = Math.max(farthest, Math.hypot(...body.trajectory.stateAt(Math.round(startUtcMs + ((endUtcMs - startUtcMs) * k) / (PATH_COVER_SAMPLES - 1)), centre).positionKm));
544
+ return farthest;
545
+ }));
546
+ }
476
547
  /** The fitted body's farthest Sun distance, read once when the viewer first needs it (a planet's reads the planet series, loaded by then); undefined when no orbit is fitted. */
477
548
  #fitFarthestKm(openUtcMs) {
478
549
  const id = this.camera.fitted;
479
550
  if (id === undefined)
480
551
  return undefined;
481
552
  let km;
482
- return () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
553
+ const read = () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
554
+ if (planetSeriesLoaded())
555
+ read();
556
+ return { read, settle: () => void read() };
483
557
  }
484
558
  /** One Sun-orbit line: one full turn from the opening time (an own body from its periapsis). Reads planet positions, so the planet series must be loaded. */
485
559
  #sunPath(id, openUtcMs) {
486
560
  const layer = sunOrbitLayer(this.#catalogue, id, openUtcMs, this.#looks.get(id)?.color ?? "", this.#own.get(id));
487
561
  if (layer === undefined)
488
- throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): "${id}" completes no turn within a dozen years and the catalogue does not know its period; add it with addBodyFromElements to draw its whole orbit`);
562
+ throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): "${id}" completes no turn within thirty years and its position and the Sun's gravity do not give a bound ellipse; add it with addBodyFromElements to draw its whole orbit`);
489
563
  return layer;
490
564
  }
491
565
  /** A readout, or the body the line is fixed to, names a body the scene must hold. */
@@ -521,8 +595,11 @@ export class Scene {
521
595
  const timeline = this.#timeline;
522
596
  const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
523
597
  const sunOrbitIds = this.#sunOrbitIds(ids);
598
+ // The farthest distance is worked out in setup, once: now when the planet series are in, else in `prepare` once they are; never in the frame loop.
599
+ const fault = {};
600
+ const fit = this.#deferredRead(ids, window, fault, undefined, () => this.#fitFarthestKm(startUtcMs));
524
601
  // The lines read planet positions; when the planet series are not loaded yet (a consumer's mount), they are drawn in `prepare`, once the series are in. The viewer draws only after `prepare` resolves.
525
- const sunPaths = this.#earlySunPaths(sunOrbitIds, startUtcMs);
602
+ const sunPaths = this.#deferredRead(ids, window, fault, [], () => this.#earlySunPaths(sunOrbitIds, startUtcMs));
526
603
  const target = this.camera.target;
527
604
  const view = this.camera.view;
528
605
  const storyPanels = this.#storyPanels(window);
@@ -530,14 +607,14 @@ export class Scene {
530
607
  // A clump near a body reads its position; with the planet series not loaded yet, those groups are built in `prepare` (the viewer draws only after it resolves).
531
608
  const seriesIn = planetSeriesLoaded();
532
609
  const late = (plan) => !seriesIn && plan.input.clump !== undefined;
533
- const layers = [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))];
610
+ const layers = this.#deferredRead(ids, window, fault, [], () => [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))]);
534
611
  const labelled = [...this.#bodies.values(), ...tracked, ...[...this.#groups.values()]].map(({ id, label }) => ({ id, label }));
535
612
  const catalogue = this.#catalogue;
536
613
  const definition = {
537
614
  experience: {
538
615
  objects: [
539
616
  ...[...this.#bodies.values()].map((body) => this.#bodyObject(body, ids, sunCentred)),
540
- ...[...this.#tracked.values()].map(({ body, description, knownLimitations }) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, ...this.#labelReach(body.id, sunCentred), provenance: body.provenance, ...(description === undefined ? {} : { description }), ...(knownLimitations === undefined ? {} : { knownLimitations }) })),
617
+ ...[...this.#tracked.values()].map(({ body, description, knownLimitations, provenanceSpans }) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, ...this.#labelReach(body.id, sunCentred), provenance: body.provenance, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(description === undefined ? {} : { description }), ...(knownLimitations === undefined ? {} : { knownLimitations }) })),
541
618
  ],
542
619
  cameraPresets: cameraPresetsOf(labelled),
543
620
  ...(target === undefined ? {} : { startCameraPresetId: `${this.camera.following ? "follow" : "focus"}-${target}` }),
@@ -550,6 +627,7 @@ export class Scene {
550
627
  rates: timeline?.rates ?? [60, 3_600, DAY_MS / 1000],
551
628
  },
552
629
  clock: clockOf(timeline, startUtcMs),
630
+ ...pacingEntry(timeline, this.#events),
553
631
  ...groupLayersEntry(layers, this.#groups.size > 0, sunOrbitIds.length > 0),
554
632
  ...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
555
633
  ...(this.#own.size === 0 ? {} : { catalogue: this.#catalogue }),
@@ -557,7 +635,7 @@ export class Scene {
557
635
  composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
558
636
  scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
559
637
  ...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
560
- ...viewEntries(timeline, this.camera, this.#fitFarthestKm(startUtcMs)),
638
+ ...viewEntries(timeline, this.camera, fit?.read, this.#pathCover(sunCentred, ids[0])),
561
639
  ...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
562
640
  trackedBodies: tracked,
563
641
  createMetrics: ({ resolver }) => {
@@ -566,12 +644,17 @@ export class Scene {
566
644
  return (objectId, timeUtcMs) => (this.#groups.has(objectId) ? this.#groupMetrics(objectId, timeUtcMs) : this.#tracked.has(objectId) ? readouts(objectId, timeUtcMs) : catalogued(objectId, timeUtcMs));
567
645
  },
568
646
  prepare: async () => {
647
+ if (fault.error !== undefined)
648
+ throw fault.error;
569
649
  if (needsPlanetSeries(definition) || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
570
650
  await loadPlanetSeries();
651
+ this.#checkPlanetSpan(ids, window);
571
652
  if (this.#groups.size > layers.length)
572
- layers.push(...this.#groupLayers(ids, window, startUtcMs, late));
653
+ layers.push(...this.#planetRead(ids, window, () => this.#groupLayers(ids, window, startUtcMs, late)));
573
654
  if (sunPaths.length < sunOrbitIds.length)
574
- sunPaths.push(...sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs)));
655
+ sunPaths.push(...this.#planetRead(ids, window, () => sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs))));
656
+ if (fit !== undefined)
657
+ this.#planetRead(ids, window, () => fit.settle());
575
658
  await installData(data, ids, window);
576
659
  },
577
660
  };
@@ -579,12 +662,13 @@ export class Scene {
579
662
  }
580
663
  }
581
664
  /** The playback and camera settings the scene asked for: looping, the farthest zoom-out and the ecliptic up. */
582
- function viewEntries(timeline, camera, farthestKm) {
665
+ function viewEntries(timeline, camera, farthestKm, cover) {
583
666
  const { reach, view, target } = camera;
584
667
  return {
585
668
  ...(timeline?.loop === true ? { loop: true } : {}),
586
669
  ...(reach === undefined ? {} : { camera: { maxFocusDistance: reach, far: reach * 2.5 } }),
587
670
  ...(farthestKm === undefined ? {} : { camera: { fitOrbit: { farthestKm } } }),
671
+ ...(reach !== undefined || farthestKm !== undefined || cover === undefined ? {} : { camera: { cover: { farthestKm: cover } } }),
588
672
  ...(view.up === undefined || target === undefined ? {} : { viewUp: view.up }),
589
673
  };
590
674
  }
@@ -633,6 +717,11 @@ function spanOf(timeline, timeUtcMs, tracked) {
633
717
  }
634
718
  return { window, startUtcMs: setTime ?? now ?? window.startUtcMs };
635
719
  }
720
+ /** The pacing the timeline asked for, laid over the scene's events; a rule naming an event type with no events throws `bad-timeline`. */
721
+ function pacingEntry(timeline, events) {
722
+ const pacing = timeline === undefined ? undefined : pacingFor(timeline, events, timeline.rate ?? 60);
723
+ return pacing === undefined ? {} : { pacing };
724
+ }
636
725
  /** The clock's opening: 60 times real time unless set; with no timeline and no rate, frozen. */
637
726
  function clockOf(timeline, startUtcMs) {
638
727
  return { startUtcMs, rate: timeline?.rate ?? 60, ...(timeline?.none === true && timeline.rate === undefined ? { playing: false } : {}) };
@@ -1,4 +1,5 @@
1
1
  import { type TimelineEvent } from "../core/events.js";
2
+ import type { Pacing } from "../core/pacing.js";
2
3
  import { type Provenance } from "../core/provenance.js";
3
4
  import type { TimeBounds } from "../core/trajectory.js";
4
5
  import { type PanelLookup, type StoryPanelSet } from "../shell/storyPanels.js";
@@ -27,7 +28,8 @@ export type TimelineInput = {
27
28
  readonly start: TimeInput;
28
29
  readonly end: TimeInput;
29
30
  readonly rates?: readonly number[];
30
- readonly rate?: number; /** True: while playing, reaching the end wraps to the start and plays on. The viewer can still seek and pause. Default false. Not available with `none: true`, where it is ignored. */
31
+ readonly rate?: number; /** Playback that slows for encounters and speeds up for cruise: see `PacingInput`. */
32
+ readonly pacing?: readonly PacingInput[]; /** True: while playing, reaching the end wraps to the start and plays on. The viewer can still seek and pause. Default false. Not available with `none: true`, where it is ignored. */
31
33
  readonly loop?: boolean;
32
34
  readonly none?: undefined;
33
35
  } | {
@@ -35,6 +37,37 @@ export type TimelineInput = {
35
37
  readonly at?: TimeInput;
36
38
  readonly rate?: number;
37
39
  };
40
+ /**
41
+ * One piece of a timeline's pacing. A span `{ from, to, rate }` plays at `rate` between two moments; an event rule `{ near: { type, within }, rate }` plays at `rate`
42
+ * within `within` seconds (simulated) of every event of that `type` (see `addEvents`). Outside every piece playback runs at the timeline's `rate`. Between a piece and
43
+ * what surrounds it the speed eases over `ramp` simulated seconds (default: `within` for an event rule, a tenth of the span for a span). `rate` here is any positive number;
44
+ * it need not be one of the offered `rates`. Spans may not overlap (touching is fine); where an event rule meets a span or another rule, the slowest speed wins, whichever contains the other and in whatever order they are listed.
45
+ */
46
+ export type PacingInput = {
47
+ readonly from: TimeInput;
48
+ readonly to: TimeInput;
49
+ readonly rate: number;
50
+ readonly ramp?: number;
51
+ } | {
52
+ readonly near: {
53
+ readonly type: string;
54
+ readonly within: number;
55
+ };
56
+ readonly rate: number;
57
+ readonly ramp?: number;
58
+ };
59
+ /** A checked pacing piece: moments as Unix milliseconds, seconds as milliseconds. */
60
+ export type PacingPiece = {
61
+ readonly fromUtcMs: number;
62
+ readonly toUtcMs: number;
63
+ readonly rate: number;
64
+ readonly rampMs: number;
65
+ } | {
66
+ readonly type: string;
67
+ readonly withinMs: number;
68
+ readonly rate: number;
69
+ readonly rampMs: number;
70
+ };
38
71
  /** What `setTimeline` was given, checked and converted. */
39
72
  export interface TimelineSetting {
40
73
  readonly window?: TimeBounds;
@@ -42,6 +75,8 @@ export interface TimelineSetting {
42
75
  readonly rate?: number;
43
76
  /** Playback wraps from the end of the span to its start. */
44
77
  readonly loop?: boolean;
78
+ /** The checked pacing pieces (absent: none). */
79
+ readonly pacing?: readonly PacingPiece[];
45
80
  /** No timeline bar. */
46
81
  readonly none: boolean;
47
82
  /** For no timeline: the moment time is frozen at, or runs on from. */
@@ -67,3 +102,8 @@ export declare function eventsOf(inputs: readonly EventInput[], known: readonly
67
102
  export declare function timelineOf(input: TimelineInput): TimelineSetting;
68
103
  /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
69
104
  export declare function panelsOf(raw: StoryPanelsInput, lookup: PanelLookup): StoryPanelSet;
105
+ /**
106
+ * The pacing the viewer runs, laid over the events: spans, then one zone per event of each rule's type. `pacedRate` lays the zones fastest first, so the slowest applicable piece wins wherever they meet, whatever contains what.
107
+ * A rule whose type has no event throws `bad-timeline` naming the piece (a mistyped type would otherwise slow nothing, silently).
108
+ */
109
+ export declare function pacingFor(setting: TimelineSetting, events: readonly TimelineEvent[], baseRate: number): Pacing | undefined;
package/src/api/story.js CHANGED
@@ -48,7 +48,8 @@ export function timelineOf(input) {
48
48
  const rates = input.rates;
49
49
  if (rates !== undefined && (!Array.isArray(rates) || rates.length === 0 || !rates.every((rate) => Number.isFinite(rate) && rate > 0)))
50
50
  throw bad("rates must be a non-empty list of positive numbers");
51
- return { none: false, window, ...(rates === undefined ? {} : { rates }), ...(input.rate === undefined ? {} : { rate: input.rate }), ...(input.loop === true ? { loop: true } : {}) };
51
+ const pacing = pacingOf(input.pacing, bad);
52
+ return { none: false, window, ...(rates === undefined ? {} : { rates }), ...(pacing === undefined ? {} : { pacing }), ...(input.rate === undefined ? {} : { rate: input.rate }), ...(input.loop === true ? { loop: true } : {}) };
52
53
  }
53
54
  /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
54
55
  export function panelsOf(raw, lookup) {
@@ -61,3 +62,64 @@ export function panelsOf(raw, lookup) {
61
62
  throw error;
62
63
  }
63
64
  }
65
+ /** Checks `pacing`: each piece names the field that is wrong (`pacing[2].rate`); spans must not overlap. */
66
+ function pacingOf(input, bad) {
67
+ if (input === undefined)
68
+ return undefined;
69
+ if (!Array.isArray(input))
70
+ throw bad("pacing must be a list of { from, to, rate } and { near: { type, within }, rate }");
71
+ const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
72
+ const pieces = input.map((raw, index) => {
73
+ const at = `pacing[${index}]`;
74
+ if (typeof raw !== "object" || raw === null)
75
+ throw bad(`${at} must be an object`);
76
+ const piece = raw;
77
+ if (!positive(piece.rate))
78
+ throw bad(`${at}.rate must be a positive number, got ${String(piece.rate)}`);
79
+ if (piece.ramp !== undefined && !(typeof piece.ramp === "number" && Number.isFinite(piece.ramp) && piece.ramp >= 0))
80
+ throw bad(`${at}.ramp must be zero or more seconds, got ${String(piece.ramp)}`);
81
+ if (piece.near !== undefined) {
82
+ const { type, within } = piece.near;
83
+ if (typeof type !== "string" || type === "")
84
+ throw bad(`${at}.near.type must be a non-empty event type`);
85
+ if (!positive(within))
86
+ throw bad(`${at}.near.within must be a positive number of seconds, got ${String(within)}`);
87
+ return { type, withinMs: within * 1000, rate: piece.rate, rampMs: (piece.ramp ?? within) * 1000 };
88
+ }
89
+ if (piece.from === undefined || piece.to === undefined)
90
+ throw bad(`${at} needs { from, to, rate } or { near: { type, within }, rate }`);
91
+ const fromUtcMs = toUtcMs(piece.from, `setTimeline ${at}.from`);
92
+ const toUtcMsValue = toUtcMs(piece.to, `setTimeline ${at}.to`);
93
+ if (toUtcMsValue <= fromUtcMs)
94
+ throw bad(`${at}.to must be after ${at}.from`);
95
+ return { fromUtcMs, toUtcMs: toUtcMsValue, rate: piece.rate, rampMs: piece.ramp === undefined ? (toUtcMsValue - fromUtcMs) / 10 : piece.ramp * 1000 };
96
+ });
97
+ const spans = pieces.flatMap((piece, index) => ("fromUtcMs" in piece ? [{ piece, index }] : [])).sort((a, b) => a.piece.fromUtcMs - b.piece.fromUtcMs);
98
+ for (let i = 1; i < spans.length; i += 1) {
99
+ if (spans[i].piece.fromUtcMs < spans[i - 1].piece.toUtcMs)
100
+ throw bad(`pacing[${spans[i].index}] overlaps pacing[${spans[i - 1].index}]; spans may touch but not overlap`);
101
+ }
102
+ return pieces.length === 0 ? undefined : pieces;
103
+ }
104
+ /**
105
+ * The pacing the viewer runs, laid over the events: spans, then one zone per event of each rule's type. `pacedRate` lays the zones fastest first, so the slowest applicable piece wins wherever they meet, whatever contains what.
106
+ * A rule whose type has no event throws `bad-timeline` naming the piece (a mistyped type would otherwise slow nothing, silently).
107
+ */
108
+ export function pacingFor(setting, events, baseRate) {
109
+ if (setting.pacing === undefined)
110
+ return undefined;
111
+ const spans = [];
112
+ const near = [];
113
+ setting.pacing.forEach((piece, index) => {
114
+ if ("fromUtcMs" in piece) {
115
+ spans.push({ fromUtcMs: piece.fromUtcMs, toUtcMs: piece.toUtcMs, rate: piece.rate, rampMs: piece.rampMs });
116
+ return;
117
+ }
118
+ const matching = events.filter((event) => event.type === piece.type);
119
+ if (matching.length === 0)
120
+ throw new SceneError("bad-timeline", `setTimeline: pacing[${index}].near.type "${piece.type}" matches no event; give the events that type with addEvents`);
121
+ for (const event of matching)
122
+ near.push({ fromUtcMs: event.timeUtcMs - piece.withinMs, toUtcMs: event.timeUtcMs + piece.withinMs, rate: piece.rate, rampMs: piece.rampMs });
123
+ });
124
+ return { baseRate, zones: [...spans, ...near] };
125
+ }
@@ -13,8 +13,8 @@ export declare function circlesTheSun(catalogue: BodyCatalogue, id: BodyId): boo
13
13
  */
14
14
  export declare function sunOrbitLayer(catalogue: BodyCatalogue, id: BodyId, startUtcMs: number, color: string, given?: EccentricSampling): PathLayer | undefined;
15
15
  /**
16
- * The farthest a body that circles the Sun gets from it, in km: a(1+e) when the period and eccentricity are known (published elements or the
17
- * catalogue's comet sampling; a from Kepler's third law about the Sun), else the largest Sun distance over one full turn of its own state source.
18
- * A planet's source reads the planet series, so those must be loaded. Throws `no-orbit` for a body that completes no turn in the search.
16
+ * The farthest a body that circles the Sun gets from it, in km, by the same rule as its orbit line: a(1+e) when the period and eccentricity are known
17
+ * (published elements, the catalogue's comet sampling) or when the line is the osculating ellipse; else the largest Sun distance over one full turn of
18
+ * its own state source. A planet's source reads the planet series, so those must be loaded. Throws `no-orbit` for a body drawn by neither form.
19
19
  */
20
20
  export declare function farthestSunDistanceKm(catalogue: BodyCatalogue, id: BodyId, startUtcMs: number, given?: EccentricSampling): number;
@@ -1,12 +1,15 @@
1
1
  import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
2
2
  import { BUILT_IN_SAMPLING, EARTH_EPHEMERIS } from "../core/bodies/index.js";
3
+ import { fillKeplerRangeKm, keplerElementsFromStates } from "../core/keplerElements.js";
4
+ import { createState, EQJ } from "../core/state.js";
5
+ import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
3
6
  import { createEarthSunTrajectory, fullTurnSpanMs } from "../core/sunCentredSources.js";
4
7
  import { rootBodyId } from "../assets/catalogue.js";
5
8
  import { SceneError } from "./errors.js";
6
9
  const DAY_MS = 86_400_000;
7
- /** The turn search walks in two-day steps; the longest orbit among the planets is a dozen years. */
10
+ /** The turn search walks in two-day steps; a full turn is looked for up to about thirty years (Saturn's). */
8
11
  const TURN_STEP_MS = 2 * DAY_MS;
9
- const TURN_MAX_STEPS = 3_000;
12
+ const TURN_MAX_STEPS = 6_000;
10
13
  const TURN_SAMPLES = 361;
11
14
  /** The id of a body's Sun-orbit line. */
12
15
  export const sunOrbitIdOf = (id) => `${id}-orbit`;
@@ -18,19 +21,86 @@ function trajectoryOf(catalogue, id) {
18
21
  const adapter = createOrbAstronomyAdapter();
19
22
  return id === "earth" ? createEarthSunTrajectory(adapter) : catalogue.get(id).source.create(adapter);
20
23
  }
24
+ const VELOCITY_STEP_MS = DAY_MS / 2;
25
+ /** The body's velocity from its position source (which models none): a central difference, or a one-sided one at the end of the source's years. */
26
+ function velocityKmS(source, timeUtcMs, center) {
27
+ const at = (t) => {
28
+ try {
29
+ return source.stateAt(t, center).positionKm;
30
+ }
31
+ catch (error) {
32
+ if (error instanceof RangeError)
33
+ return undefined;
34
+ throw error;
35
+ }
36
+ };
37
+ const [before, after] = [at(timeUtcMs - VELOCITY_STEP_MS), at(timeUtcMs + VELOCITY_STEP_MS)];
38
+ const here = source.stateAt(timeUtcMs, center).positionKm;
39
+ const [from, to, seconds] = before !== undefined && after !== undefined ? [before, after, VELOCITY_STEP_MS / 500] : after !== undefined ? [here, after, VELOCITY_STEP_MS / 1000] : before !== undefined ? [before, here, VELOCITY_STEP_MS / 1000] : [here, here, 1];
40
+ return [0, 1, 2].map((axis) => (to[axis] - from[axis]) / seconds);
41
+ }
42
+ /** The two-body ellipse osculating at `startUtcMs`, as a source, the span of one turn from periapsis and its sampling; undefined when the body is not bound or no Sun GM is known. */
43
+ function osculatingOrbit(catalogue, id, source, startUtcMs) {
44
+ const root = rootBodyId(catalogue);
45
+ const mu = catalogue.get(root).definition.gmKm3S2;
46
+ if (mu === undefined)
47
+ return undefined;
48
+ const position = source.stateAt(startUtcMs, root).positionKm;
49
+ const velocity = velocityKmS(source, startUtcMs, root);
50
+ if (![...position, ...velocity].every(Number.isFinite))
51
+ return undefined;
52
+ const elements = keplerElementsFromStates(Float64Array.from([position[0], position[1], position[2], ...velocity]), 1, mu, startUtcMs);
53
+ const a = elements.semiMajorAxisKm[0];
54
+ const e = elements.eccentricity[0];
55
+ if (!(a > 0) || !(e >= 0 && e < 1) || !Number.isFinite(elements.meanMotionRadS[0]))
56
+ return undefined;
57
+ const periodMs = Math.round((2 * Math.PI * 1000) / elements.meanMotionRadS[0]);
58
+ const periapsisUtcMs = Math.round(startUtcMs - (elements.meanAnomalyRad[0] * 1000) / elements.meanMotionRadS[0]);
59
+ return { source: ellipseSource(id, elements), span: { startUtcMs: periapsisUtcMs, endUtcMs: periapsisUtcMs + periodMs }, sampling: { eccentricity: e, periodMs, periapsisUtcMs }, osculating: true, farthestKm: a * (1 + e) };
60
+ }
61
+ function ellipseSource(id, elements) {
62
+ return Object.freeze({
63
+ body: id,
64
+ stateAt(timeUtcMs) {
65
+ const out = new Float64Array(3);
66
+ fillKeplerRangeKm(elements, timeUtcMs, out, 0, 1);
67
+ return createState({ body: id, center: "sun", timeUtcMs, frame: EQJ, positionKm: out, orientation: null }, () => false);
68
+ },
69
+ });
70
+ }
71
+ /**
72
+ * How a body that circles the Sun is drawn, one rule for every body and never by name: with published elements (`given`, or the catalogue's comet
73
+ * sampling) from periapsis for one period; else one full turn of its own source when the source covers a whole turn from `startUtcMs`; else (a source
74
+ * that ends first, such as the planet series for Uranus and Neptune) the two-body ellipse osculating at `startUtcMs`. Undefined when none can be drawn.
75
+ */
76
+ function drawnOrbit(catalogue, id, startUtcMs, given) {
77
+ const source = trajectoryOf(catalogue, id);
78
+ const sampling = given ?? BUILT_IN_SAMPLING[id];
79
+ if (sampling !== undefined) {
80
+ const gm = catalogue.get(rootBodyId(catalogue)).definition.gmKm3S2;
81
+ const semiMajorKm = Math.cbrt(gm * (sampling.periodMs / 1000 / (2 * Math.PI)) ** 2);
82
+ return { source, span: { startUtcMs: sampling.periapsisUtcMs, endUtcMs: sampling.periapsisUtcMs + Math.round(sampling.periodMs) }, sampling, osculating: false, farthestKm: semiMajorKm * (1 + sampling.eccentricity) };
83
+ }
84
+ const span = turnSpan(source, startUtcMs);
85
+ if (span !== undefined)
86
+ return { source, span, sampling: undefined, osculating: false, farthestKm: undefined };
87
+ return osculatingOrbit(catalogue, id, source, startUtcMs);
88
+ }
21
89
  /**
22
90
  * The orbit line of a body that circles the Sun: one full turn from `startUtcMs`, from the body's own state source. A body given published elements
23
91
  * (`sampling`) is drawn from its periapsis for one period with samples spaced by eccentric anomaly, so a sharp orbit is smooth. Returns undefined when
24
92
  * the body completes no turn within the search (a comet's century-long orbit given without elements).
25
93
  */
26
94
  export function sunOrbitLayer(catalogue, id, startUtcMs, color, given) {
27
- const sampling = given ?? BUILT_IN_SAMPLING[id];
28
- const { definition, visual } = catalogue.get(id);
29
- const source = trajectoryOf(catalogue, id);
30
- const span = sampling === undefined ? turnSpan(source, startUtcMs) : { startUtcMs: sampling.periapsisUtcMs, endUtcMs: sampling.periapsisUtcMs + Math.round(sampling.periodMs) };
31
- if (span === undefined)
95
+ const drawn = drawnOrbit(catalogue, id, startUtcMs, given);
96
+ if (drawn === undefined)
32
97
  return undefined;
98
+ const { definition, visual } = catalogue.get(id);
99
+ const { source, span, sampling, osculating } = drawn;
33
100
  const provenance = id === "earth" ? EARTH_EPHEMERIS.provenance : definition.accuracy.position;
101
+ const limitation = osculating
102
+ ? `${definition.label}'s source does not cover a whole turn from the scene's opening time, so this is the two-body ellipse osculating at that time (position and velocity from the source, the Sun's gravity alone): perturbations over a turn are not drawn, and the line leaves the source's own positions as the years pass from the opening time. Samples are spaced by eccentric anomaly and joined by straight segments.`
103
+ : sampling === undefined ? "A turn's samples joined by straight segments." : "One full turn of unperturbed two-body motion from periapsis; samples are spaced by eccentric anomaly and joined by straight segments.";
34
104
  return {
35
105
  kind: "orbit",
36
106
  color: color || visual.material.color,
@@ -44,9 +114,11 @@ export function sunOrbitLayer(catalogue, id, startUtcMs, color, given) {
44
114
  color: color || visual.material.color,
45
115
  labelPriority: 50,
46
116
  showLabel: false,
47
- description: `${definition.label}'s path round the Sun for one full turn, drawn from the same position source that places ${definition.label}.`,
117
+ description: osculating
118
+ ? `${definition.label}'s path round the Sun for one turn, drawn as the two-body ellipse osculating at the scene's opening time.`
119
+ : `${definition.label}'s path round the Sun for one full turn, drawn from the same position source that places ${definition.label}.`,
48
120
  provenance,
49
- knownLimitations: [sampling === undefined ? "A turn's samples joined by straight segments." : "One full turn of unperturbed two-body motion from periapsis; samples are spaced by eccentric anomaly and joined by straight segments."],
121
+ knownLimitations: [limitation],
50
122
  },
51
123
  };
52
124
  }
@@ -55,30 +127,26 @@ function turnSpan(source, startUtcMs) {
55
127
  return { startUtcMs, endUtcMs: startUtcMs + fullTurnSpanMs(source, startUtcMs, TURN_STEP_MS, TURN_MAX_STEPS) };
56
128
  }
57
129
  catch (error) {
58
- if (error instanceof RangeError && /no full turn/.test(error.message))
130
+ // No full turn in the search, or the source's years end first (the planet series): the source does not cover a whole turn.
131
+ if (error instanceof TimeScaleOutOfRangeError || (error instanceof RangeError && /no full turn|do not cover/.test(error.message)))
59
132
  return undefined;
60
133
  throw error;
61
134
  }
62
135
  }
63
136
  /**
64
- * The farthest a body that circles the Sun gets from it, in km: a(1+e) when the period and eccentricity are known (published elements or the
65
- * catalogue's comet sampling; a from Kepler's third law about the Sun), else the largest Sun distance over one full turn of its own state source.
66
- * A planet's source reads the planet series, so those must be loaded. Throws `no-orbit` for a body that completes no turn in the search.
137
+ * The farthest a body that circles the Sun gets from it, in km, by the same rule as its orbit line: a(1+e) when the period and eccentricity are known
138
+ * (published elements, the catalogue's comet sampling) or when the line is the osculating ellipse; else the largest Sun distance over one full turn of
139
+ * its own state source. A planet's source reads the planet series, so those must be loaded. Throws `no-orbit` for a body drawn by neither form.
67
140
  */
68
141
  export function farthestSunDistanceKm(catalogue, id, startUtcMs, given) {
69
- const sampling = given ?? BUILT_IN_SAMPLING[id];
70
- if (sampling !== undefined) {
71
- const gm = catalogue.get(rootBodyId(catalogue)).definition.gmKm3S2;
72
- const semiMajorKm = Math.cbrt(gm * (sampling.periodMs / 1000 / (2 * Math.PI)) ** 2);
73
- return semiMajorKm * (1 + sampling.eccentricity);
74
- }
75
- const source = trajectoryOf(catalogue, id);
76
- const span = turnSpan(source, startUtcMs);
77
- if (span === undefined)
78
- throw new SceneError("no-orbit", `camera.fitOrbit("${id}"): "${id}" completes no turn within a dozen years and the catalogue does not know its period; add it with addBodyFromElements`);
142
+ const drawn = drawnOrbit(catalogue, id, startUtcMs, given);
143
+ if (drawn === undefined)
144
+ throw new SceneError("no-orbit", `camera.fitOrbit("${id}"): "${id}" completes no turn within thirty years and its position and the Sun's gravity do not give a bound ellipse; add it with addBodyFromElements`);
145
+ if (drawn.farthestKm !== undefined)
146
+ return drawn.farthestKm;
79
147
  let farthest = 0;
80
148
  for (let k = 0; k < TURN_SAMPLES; k += 1) {
81
- const [x, y, z] = source.stateAt(Math.round(span.startUtcMs + ((span.endUtcMs - span.startUtcMs) * k) / (TURN_SAMPLES - 1)), rootBodyId(catalogue)).positionKm;
149
+ const [x, y, z] = drawn.source.stateAt(Math.round(drawn.span.startUtcMs + ((drawn.span.endUtcMs - drawn.span.startUtcMs) * k) / (TURN_SAMPLES - 1)), rootBodyId(catalogue)).positionKm;
82
150
  farthest = Math.max(farthest, Math.hypot(x, y, z));
83
151
  }
84
152
  return farthest;
@@ -0,0 +1,40 @@
1
+ import type { ViewerChangeCause, ViewerControl, ViewerPort, ViewerState } from "../app/viewerPort.js";
2
+ import { type TimeInput } from "./time.js";
3
+ /** What a host is told when the viewer's time, speed or playing state changes. */
4
+ export interface ViewerChange {
5
+ /** The viewer's time, Unix milliseconds UTC. */
6
+ readonly time: number;
7
+ /** Simulated seconds per real second. */
8
+ readonly rate: number;
9
+ readonly playing: boolean;
10
+ /** `playback`: the clock ran on; `visitor`: someone used the timeline; `host`: the host page called `setTime` or `setRate`. */
11
+ readonly cause: ViewerChangeCause;
12
+ }
13
+ /** Where the playback rate comes from. `scene` is the rate the scene opened at; `chosen` is one a visitor or the host picked, which stays until it is released. */
14
+ export type RateSource = "scene" | "chosen";
15
+ /**
16
+ * Joins a host page to a mounted viewer's one clock: reads, sets and change callbacks. Created by `mount` and `AstraeusScene`; the viewer attaches
17
+ * its clock controls when it opens and detaches when it closes.
18
+ */
19
+ export declare class ViewerLink implements ViewerPort {
20
+ #private;
21
+ attach(control: ViewerControl): void;
22
+ detach(): void;
23
+ /** Stops all callbacks for good (the host unmounted). */
24
+ close(): void;
25
+ get rateSource(): RateSource;
26
+ /** The viewer's time (Unix milliseconds UTC), or undefined before it is drawn or after it is gone. */
27
+ get time(): number | undefined;
28
+ get rate(): number | undefined;
29
+ get playing(): boolean | undefined;
30
+ setTime(time: TimeInput): void;
31
+ /**
32
+ * Only a speed the timeline offers is taken, so the speed picker always shows what is running; any other number throws `bad-timeline`.
33
+ * `"auto"` hands the rate back to the scene's pacing (`setTimeline({ pacing })`) and throws `bad-timeline` when the scene has none. The in-between speeds pacing
34
+ * runs at are never set through here; they arrive in `onChange` and `rate`.
35
+ */
36
+ setRate(rate: number | "auto"): void;
37
+ /** Calls `listener` whenever the time, speed or playing state changes; returns the function that stops it. */
38
+ onChange(listener: (change: ViewerChange) => void): () => void;
39
+ publish(state: ViewerState, cause: ViewerChangeCause): void;
40
+ }