astraeus 0.4.0 → 0.5.1

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 (104) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +65 -11
  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 +122 -26
  18. package/src/api/story.d.ts +45 -1
  19. package/src/api/story.js +73 -2
  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/AstraeusScene.js +3 -1
  29. package/src/app/BodySetView.js +3 -2
  30. package/src/app/KeplerPoints.d.ts +1 -1
  31. package/src/app/KeplerPoints.js +3 -2
  32. package/src/app/LayeredRender.js +1 -0
  33. package/src/app/OrbitSetView.js +5 -0
  34. package/src/app/PointsView.js +3 -2
  35. package/src/app/SceneLabels.d.ts +8 -0
  36. package/src/app/SceneLabels.js +15 -1
  37. package/src/app/SkyView.js +2 -0
  38. package/src/app/TrackedBodyView.js +3 -2
  39. package/src/app/bodyDraw.js +3 -2
  40. package/src/app/dotMaterial.d.ts +11 -0
  41. package/src/app/dotMaterial.js +38 -0
  42. package/src/app/experienceDefinition.d.ts +12 -0
  43. package/src/app/mission.d.ts +1 -1
  44. package/src/app/mission.js +1 -1
  45. package/src/app/openClock.d.ts +1 -1
  46. package/src/app/openClock.js +3 -0
  47. package/src/app/sceneContentsHooks.js +2 -1
  48. package/src/app/sceneFrame.d.ts +2 -2
  49. package/src/app/sceneFrame.js +6 -1
  50. package/src/app/sceneFraming.d.ts +1 -1
  51. package/src/app/sceneFraming.js +9 -3
  52. package/src/app/viewerPort.d.ts +33 -0
  53. package/src/app/viewerPort.js +1 -0
  54. package/src/assets/bodies/jupiter.js +2 -0
  55. package/src/assets/bodies/outerPlanetCatalogues.d.ts +1 -5
  56. package/src/assets/bodies/outerPlanetCatalogues.js +2 -6
  57. package/src/assets/bodies/outerPlanetRings.d.ts +5 -0
  58. package/src/assets/bodies/outerPlanetRings.js +6 -0
  59. package/src/assets/bodies/planetSystemMaps.js +6 -3
  60. package/src/assets/compositions.js +2 -1
  61. package/src/assets/visual.d.ts +1 -1
  62. package/src/core/bodies/io.js +2 -1
  63. package/src/core/bodies/jupiterMoons.d.ts +1 -1
  64. package/src/core/bodies/jupiterMoons.js +7 -6
  65. package/src/core/bodies/moon.d.ts +2 -0
  66. package/src/core/bodies/moon.js +4 -0
  67. package/src/core/bodies/moonSystem.d.ts +17 -1
  68. package/src/core/bodies/moonSystem.js +59 -7
  69. package/src/core/bodies/outerPlanetData.d.ts +0 -3
  70. package/src/core/bodies/outerPlanetData.js +1 -7
  71. package/src/core/bodies/outerPlanetRingData.d.ts +3 -0
  72. package/src/core/bodies/outerPlanetRingData.js +10 -0
  73. package/src/core/bodies/outerPlanets.js +1 -1
  74. package/src/core/bodies/planetMoons.js +12 -11
  75. package/src/core/body.d.ts +4 -0
  76. package/src/core/chebyshevEphemeris.d.ts +7 -1
  77. package/src/core/chebyshevEphemeris.js +24 -7
  78. package/src/core/clock.d.ts +8 -0
  79. package/src/core/clock.js +14 -0
  80. package/src/core/events.d.ts +2 -0
  81. package/src/core/pacing.d.ts +24 -0
  82. package/src/core/pacing.js +35 -0
  83. package/src/core/planetModels.d.ts +4 -1
  84. package/src/core/planetModels.js +6 -1
  85. package/src/core/planetSeries.d.ts +3 -0
  86. package/src/core/planetSeries.js +8 -1
  87. package/src/core/satelliteMeanElements.d.ts +2 -8
  88. package/src/core/satelliteMeanElements.js +2 -15
  89. package/src/core/siderealPeriod.d.ts +27 -0
  90. package/src/core/siderealPeriod.js +18 -0
  91. package/src/core/timeWindow.d.ts +2 -0
  92. package/src/core/timeWindow.js +4 -3
  93. package/src/shell/AstraeusShell.d.ts +6 -2
  94. package/src/shell/AstraeusShell.js +9 -5
  95. package/src/shell/AstraeusShell.node.js +9 -5
  96. package/src/shell/TimelineBar.d.ts +4 -2
  97. package/src/shell/TimelineBar.js +15 -6
  98. package/src/shell/TimelineBar.node.js +15 -6
  99. package/src/shell/experience.d.ts +3 -1
  100. package/src/shell/infoModel.js +5 -4
  101. package/src/shell/timelineModel.d.ts +2 -3
  102. package/src/shell/timelineModel.js +3 -11
  103. package/src/synthetic/syntheticJourneyScene.d.ts +9 -0
  104. package/src/synthetic/syntheticJourneyScene.js +76 -0
package/src/api/scene.js CHANGED
@@ -1,15 +1,15 @@
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
- import { createComposition, SIDEREAL_MONTH_MS } from "../assets/compositions.js";
12
- import { IO_PERIOD_DAYS } from "../core/bodies/io.js";
12
+ import { createComposition } from "../assets/compositions.js";
13
13
  import { bodyMetrics } from "../app/bodyMetrics.js";
14
14
  import { needsPlanetSeries } from "../app/planetNeeds.js";
15
15
  import { catalogueItem } from "../app/catalogueItem.js";
@@ -22,17 +22,27 @@ import { buildGroupLayer, planGroup } from "./group.js";
22
22
  import { SceneError } from "./errors.js";
23
23
  import { toUtcMs } from "./time.js";
24
24
  import { switchesOf } from "./switches.js";
25
- import { eventProvenanceOf, eventsOf, panelsOf, timelineOf } from "./story.js";
25
+ import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
26
+ import { checkEventObjects, eventProvenanceOf, eventsOf, pacingFor, panelsOf, timelineOf } from "./story.js";
26
27
  export { toUtcMs } from "./time.js";
27
- /** 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
- const ORBITS = {
29
- moon: { path: { spanMs: SIDEREAL_MONTH_MS } },
30
- io: { path: { spanMs: IO_PERIOD_DAYS * 86_400_000, look: { endFadeOn: false } } },
31
- };
28
+ /**
29
+ * The orbit line of a catalogued moon, by one rule: one lap of the period its catalogue definition carries (`orbitPeriodDays`, read once from the record or mean
30
+ * elements), drawn about its parent. Undefined where the definition gives no period. A moon closes its loop (Io's look) unless its definition says its line fades (the Moon's, as before).
31
+ */
32
+ function moonOrbitPath(catalogue, id) {
33
+ if (!catalogue.has(id))
34
+ return undefined;
35
+ const { orbitPeriodDays, orbitLineFades, parentId } = catalogue.get(id).definition;
36
+ if (orbitPeriodDays === undefined || parentId === undefined)
37
+ return undefined;
38
+ return { spanMs: orbitPeriodDays * 86_400_000, ...(orbitLineFades === true ? {} : { look: { endFadeOn: false } }) };
39
+ }
32
40
  const DEFAULT_COLOR = "#ffd27a";
33
41
  const DAY_MS = 86_400_000;
34
42
  const PROVIDER_PATH_SAMPLES = 128;
35
43
  const SCALES = [trueScale, readableScale, solarSystemScale];
44
+ /** Samples along a path when its farthest distance is read for the default zoom-out. */
45
+ const PATH_COVER_SAMPLES = 400;
36
46
  /** The scene's camera: what it opens on. */
37
47
  export class SceneCamera {
38
48
  #target;
@@ -175,8 +185,8 @@ export class Scene {
175
185
  return this;
176
186
  }
177
187
  #register(call, id, ref, options) {
178
- 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`);
188
+ if (options.orbit === true && moonOrbitPath(this.#catalogue, id) === undefined && !(circlesTheSun(this.#catalogue, id)))
189
+ throw new SceneError("no-orbit", `${call}("${id}", { orbit: true }): the engine draws the orbit line of any catalogued moon whose data give a period about its planet 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
190
  if (!this.#catalogue.has(id))
181
191
  throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${this.#catalogue.ids().join(", ")})`);
182
192
  if (this.#taken(id))
@@ -230,7 +240,8 @@ export class Scene {
230
240
  throw new SceneError("bad-trajectory", `addTrajectory("${id}"): plane "${String(input.plane)}" must be "EQJ" or "ecliptic-j2000"`);
231
241
  const toEqj = input.plane === "ecliptic-j2000" ? createOrbTwoBodyAdapter().eclipticJ2000ToEqjMatrix() : null;
232
242
  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 }) });
243
+ const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs });
244
+ 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
245
  }
235
246
  /** Whether a body, path or group already has this id. */
236
247
  #taken(id) {
@@ -295,7 +306,7 @@ export class Scene {
295
306
  this.#panels = panels;
296
307
  return this;
297
308
  }
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. */
309
+ /** 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
310
  setTimeline(timeline) {
300
311
  this.#timeline = timelineOf(timeline);
301
312
  return this;
@@ -422,6 +433,54 @@ export class Scene {
422
433
  }
423
434
  }
424
435
  }
436
+ /** 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. */
437
+ #planetSpanError(ids, window) {
438
+ const planets = ids.filter(isPlanetId);
439
+ if (planets.length === 0 || !planetSeriesLoaded())
440
+ return undefined;
441
+ const span = planetSeriesSpan();
442
+ if (window.startUtcMs >= span.startUtcMs && window.endUtcMs <= span.endUtcMs)
443
+ return undefined;
444
+ const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
445
+ 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`);
446
+ }
447
+ /** Throws `out-of-span` naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded). */
448
+ #checkPlanetSpan(ids, window) {
449
+ const error = this.#planetSpanError(ids, window);
450
+ if (error !== undefined)
451
+ throw error;
452
+ }
453
+ /**
454
+ * The one choke point for planet-series reads during setup (orbit lines, the fit distance, clump groups): checks the span first, and turns a
455
+ * `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.
456
+ */
457
+ #planetRead(ids, window, read) {
458
+ this.#checkPlanetSpan(ids, window);
459
+ try {
460
+ return read();
461
+ }
462
+ catch (error) {
463
+ if (error instanceof TimeScaleOutOfRangeError)
464
+ throw this.#planetSpanError(ids, window) ?? error;
465
+ throw error;
466
+ }
467
+ }
468
+ /**
469
+ * 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;
470
+ * `prepare` rejects with the recorded error, which is how it always arrives (once, as `ready` rejecting).
471
+ */
472
+ #deferredRead(ids, window, fault, fallback, read) {
473
+ try {
474
+ return this.#planetRead(ids, window, read);
475
+ }
476
+ catch (error) {
477
+ if (error instanceof SceneError && error.code === "out-of-span") {
478
+ fault.error ??= error;
479
+ return fallback;
480
+ }
481
+ throw error;
482
+ }
483
+ }
425
484
  /** Throws `missing-data` naming the bodies whose data package was not passed. */
426
485
  #checkData(data) {
427
486
  const missing = this.missingData(data);
@@ -432,12 +491,12 @@ export class Scene {
432
491
  }
433
492
  /** The engine's own orbit loops (the Moon's and Io's) the scene asked for. */
434
493
  #moonPaths() {
435
- return [...this.#orbits].filter((id) => ORBITS[id] !== undefined).map((id) => {
436
- const orbit = ORBITS[id];
494
+ return [...this.#orbits].filter((id) => moonOrbitPath(this.#catalogue, id) !== undefined).map((id) => {
495
+ const orbit = moonOrbitPath(this.#catalogue, id);
437
496
  const parent = this.#catalogue.get(id).definition.parentId;
438
497
  if (parent === undefined || !this.#bodies.has(parent))
439
498
  throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about ${parent}, which has not been added to the scene`);
440
- return { body: id, ...orbit.path };
499
+ return { body: id, ...orbit };
441
500
  });
442
501
  }
443
502
  /** Whether the scene is centred on the Sun. */
@@ -465,7 +524,7 @@ export class Scene {
465
524
  }
466
525
  /** The bodies that asked for a Sun-orbit line, checked: the Sun must be in the scene and the line's id free. */
467
526
  #sunOrbitIds(ids) {
468
- return [...this.#orbits].filter((id) => ORBITS[id] === undefined).map((id) => {
527
+ return [...this.#orbits].filter((id) => moonOrbitPath(this.#catalogue, id) === undefined).map((id) => {
469
528
  if (!ids.includes(rootBodyId(this.#catalogue)))
470
529
  throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about the Sun, which has not been added to the scene`);
471
530
  if (this.#taken(sunOrbitIdOf(id)))
@@ -473,19 +532,40 @@ export class Scene {
473
532
  return id;
474
533
  });
475
534
  }
535
+ /**
536
+ * 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,
537
+ * 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.
538
+ */
539
+ #pathCover(sunCentred, centre) {
540
+ if (!sunCentred)
541
+ return undefined;
542
+ const about = [...this.#tracked.values()].filter((entry) => entry.center === centre);
543
+ if (about.length === 0)
544
+ return undefined;
545
+ return () => 2 * Math.max(...about.map(({ body }) => {
546
+ const { startUtcMs, endUtcMs } = body.trajectory.bounds;
547
+ let farthest = 0;
548
+ for (let k = 0; k < PATH_COVER_SAMPLES; k += 1)
549
+ farthest = Math.max(farthest, Math.hypot(...body.trajectory.stateAt(Math.round(startUtcMs + ((endUtcMs - startUtcMs) * k) / (PATH_COVER_SAMPLES - 1)), centre).positionKm));
550
+ return farthest;
551
+ }));
552
+ }
476
553
  /** 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
554
  #fitFarthestKm(openUtcMs) {
478
555
  const id = this.camera.fitted;
479
556
  if (id === undefined)
480
557
  return undefined;
481
558
  let km;
482
- return () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
559
+ const read = () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
560
+ if (planetSeriesLoaded())
561
+ read();
562
+ return { read, settle: () => void read() };
483
563
  }
484
564
  /** 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
565
  #sunPath(id, openUtcMs) {
486
566
  const layer = sunOrbitLayer(this.#catalogue, id, openUtcMs, this.#looks.get(id)?.color ?? "", this.#own.get(id));
487
567
  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`);
568
+ 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
569
  return layer;
490
570
  }
491
571
  /** A readout, or the body the line is fixed to, names a body the scene must hold. */
@@ -521,8 +601,11 @@ export class Scene {
521
601
  const timeline = this.#timeline;
522
602
  const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
523
603
  const sunOrbitIds = this.#sunOrbitIds(ids);
604
+ // 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.
605
+ const fault = {};
606
+ const fit = this.#deferredRead(ids, window, fault, undefined, () => this.#fitFarthestKm(startUtcMs));
524
607
  // 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);
608
+ const sunPaths = this.#deferredRead(ids, window, fault, [], () => this.#earlySunPaths(sunOrbitIds, startUtcMs));
526
609
  const target = this.camera.target;
527
610
  const view = this.camera.view;
528
611
  const storyPanels = this.#storyPanels(window);
@@ -530,14 +613,15 @@ export class Scene {
530
613
  // 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
614
  const seriesIn = planetSeriesLoaded();
532
615
  const late = (plan) => !seriesIn && plan.input.clump !== undefined;
533
- const layers = [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))];
616
+ const layers = this.#deferredRead(ids, window, fault, [], () => [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))]);
534
617
  const labelled = [...this.#bodies.values(), ...tracked, ...[...this.#groups.values()]].map(({ id, label }) => ({ id, label }));
535
618
  const catalogue = this.#catalogue;
619
+ checkEventObjects(this.#events, new Set(labelled.map(({ id }) => id)));
536
620
  const definition = {
537
621
  experience: {
538
622
  objects: [
539
623
  ...[...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 }) })),
624
+ ...[...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
625
  ],
542
626
  cameraPresets: cameraPresetsOf(labelled),
543
627
  ...(target === undefined ? {} : { startCameraPresetId: `${this.camera.following ? "follow" : "focus"}-${target}` }),
@@ -550,6 +634,7 @@ export class Scene {
550
634
  rates: timeline?.rates ?? [60, 3_600, DAY_MS / 1000],
551
635
  },
552
636
  clock: clockOf(timeline, startUtcMs),
637
+ ...pacingEntry(timeline, this.#events),
553
638
  ...groupLayersEntry(layers, this.#groups.size > 0, sunOrbitIds.length > 0),
554
639
  ...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
555
640
  ...(this.#own.size === 0 ? {} : { catalogue: this.#catalogue }),
@@ -557,7 +642,7 @@ export class Scene {
557
642
  composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
558
643
  scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
559
644
  ...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
560
- ...viewEntries(timeline, this.camera, this.#fitFarthestKm(startUtcMs)),
645
+ ...viewEntries(timeline, this.camera, fit?.read, this.#pathCover(sunCentred, ids[0])),
561
646
  ...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
562
647
  trackedBodies: tracked,
563
648
  createMetrics: ({ resolver }) => {
@@ -566,12 +651,17 @@ export class Scene {
566
651
  return (objectId, timeUtcMs) => (this.#groups.has(objectId) ? this.#groupMetrics(objectId, timeUtcMs) : this.#tracked.has(objectId) ? readouts(objectId, timeUtcMs) : catalogued(objectId, timeUtcMs));
567
652
  },
568
653
  prepare: async () => {
654
+ if (fault.error !== undefined)
655
+ throw fault.error;
569
656
  if (needsPlanetSeries(definition) || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
570
657
  await loadPlanetSeries();
658
+ this.#checkPlanetSpan(ids, window);
571
659
  if (this.#groups.size > layers.length)
572
- layers.push(...this.#groupLayers(ids, window, startUtcMs, late));
660
+ layers.push(...this.#planetRead(ids, window, () => this.#groupLayers(ids, window, startUtcMs, late)));
573
661
  if (sunPaths.length < sunOrbitIds.length)
574
- sunPaths.push(...sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs)));
662
+ sunPaths.push(...this.#planetRead(ids, window, () => sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs))));
663
+ if (fit !== undefined)
664
+ this.#planetRead(ids, window, () => fit.settle());
575
665
  await installData(data, ids, window);
576
666
  },
577
667
  };
@@ -579,12 +669,13 @@ export class Scene {
579
669
  }
580
670
  }
581
671
  /** The playback and camera settings the scene asked for: looping, the farthest zoom-out and the ecliptic up. */
582
- function viewEntries(timeline, camera, farthestKm) {
672
+ function viewEntries(timeline, camera, farthestKm, cover) {
583
673
  const { reach, view, target } = camera;
584
674
  return {
585
675
  ...(timeline?.loop === true ? { loop: true } : {}),
586
676
  ...(reach === undefined ? {} : { camera: { maxFocusDistance: reach, far: reach * 2.5 } }),
587
677
  ...(farthestKm === undefined ? {} : { camera: { fitOrbit: { farthestKm } } }),
678
+ ...(reach !== undefined || farthestKm !== undefined || cover === undefined ? {} : { camera: { cover: { farthestKm: cover } } }),
588
679
  ...(view.up === undefined || target === undefined ? {} : { viewUp: view.up }),
589
680
  };
590
681
  }
@@ -633,6 +724,11 @@ function spanOf(timeline, timeUtcMs, tracked) {
633
724
  }
634
725
  return { window, startUtcMs: setTime ?? now ?? window.startUtcMs };
635
726
  }
727
+ /** The pacing the timeline asked for, laid over the scene's events; a rule naming an event type with no events throws `bad-timeline`. */
728
+ function pacingEntry(timeline, events) {
729
+ const pacing = timeline === undefined ? undefined : pacingFor(timeline, events, timeline.rate ?? 60);
730
+ return pacing === undefined ? {} : { pacing };
731
+ }
636
732
  /** The clock's opening: 60 times real time unless set; with no timeline and no rate, frozen. */
637
733
  function clockOf(timeline, startUtcMs) {
638
734
  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";
@@ -12,6 +13,8 @@ export interface EventInput {
12
13
  readonly type?: string;
13
14
  /** Where this event's time comes from. Shown with the event; an event without one shows the `provenance` of `addEvents`. Malformed: `addEvents` throws "bad-event" naming the event. */
14
15
  readonly provenance?: Provenance;
16
+ /** The body or trajectory (its id) this event is about. Go to this event seeks to its time and frames the object as `camera.lookAt` does. Not in the scene when the scene is built (`mount`): "bad-event" naming the event and the id. Without one, Go to only seeks. */
17
+ readonly object?: string;
15
18
  }
16
19
  /** Options of `addEvents`. */
17
20
  export interface AddEventsOptions {
@@ -27,7 +30,8 @@ export type TimelineInput = {
27
30
  readonly start: TimeInput;
28
31
  readonly end: TimeInput;
29
32
  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. */
33
+ readonly rate?: number; /** Playback that slows for encounters and speeds up for cruise: see `PacingInput`. */
34
+ 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
35
  readonly loop?: boolean;
32
36
  readonly none?: undefined;
33
37
  } | {
@@ -35,6 +39,37 @@ export type TimelineInput = {
35
39
  readonly at?: TimeInput;
36
40
  readonly rate?: number;
37
41
  };
42
+ /**
43
+ * 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`
44
+ * 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
45
+ * 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;
46
+ * 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.
47
+ */
48
+ export type PacingInput = {
49
+ readonly from: TimeInput;
50
+ readonly to: TimeInput;
51
+ readonly rate: number;
52
+ readonly ramp?: number;
53
+ } | {
54
+ readonly near: {
55
+ readonly type: string;
56
+ readonly within: number;
57
+ };
58
+ readonly rate: number;
59
+ readonly ramp?: number;
60
+ };
61
+ /** A checked pacing piece: moments as Unix milliseconds, seconds as milliseconds. */
62
+ export type PacingPiece = {
63
+ readonly fromUtcMs: number;
64
+ readonly toUtcMs: number;
65
+ readonly rate: number;
66
+ readonly rampMs: number;
67
+ } | {
68
+ readonly type: string;
69
+ readonly withinMs: number;
70
+ readonly rate: number;
71
+ readonly rampMs: number;
72
+ };
38
73
  /** What `setTimeline` was given, checked and converted. */
39
74
  export interface TimelineSetting {
40
75
  readonly window?: TimeBounds;
@@ -42,6 +77,8 @@ export interface TimelineSetting {
42
77
  readonly rate?: number;
43
78
  /** Playback wraps from the end of the span to its start. */
44
79
  readonly loop?: boolean;
80
+ /** The checked pacing pieces (absent: none). */
81
+ readonly pacing?: readonly PacingPiece[];
45
82
  /** No timeline bar. */
46
83
  readonly none: boolean;
47
84
  /** For no timeline: the moment time is frozen at, or runs on from. */
@@ -59,6 +96,8 @@ export interface StoryPanelsInput {
59
96
  readonly autoOpen?: boolean;
60
97
  readonly panels: readonly unknown[];
61
98
  }
99
+ /** Throws "bad-event" naming the first event whose `object` is not among the scene's `objectIds`. */
100
+ export declare function checkEventObjects(events: readonly TimelineEvent[], objectIds: ReadonlySet<string>): void;
62
101
  /** Checks a provenance given to `addEvents` (for the whole batch, or for the event `eventId`) and returns it frozen; throws "bad-event" when malformed. */
63
102
  export declare function eventProvenanceOf(value: unknown, eventId?: string): Provenance;
64
103
  /** The events merged with `inputs`, sorted by time; each needs a distinct non-empty id and label and a valid moment. */
@@ -67,3 +106,8 @@ export declare function eventsOf(inputs: readonly EventInput[], known: readonly
67
106
  export declare function timelineOf(input: TimelineInput): TimelineSetting;
68
107
  /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
69
108
  export declare function panelsOf(raw: StoryPanelsInput, lookup: PanelLookup): StoryPanelSet;
109
+ /**
110
+ * 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.
111
+ * A rule whose type has no event throws `bad-timeline` naming the piece (a mistyped type would otherwise slow nothing, silently).
112
+ */
113
+ export declare function pacingFor(setting: TimelineSetting, events: readonly TimelineEvent[], baseRate: number): Pacing | undefined;
package/src/api/story.js CHANGED
@@ -3,6 +3,13 @@ import { createProvenance } from "../core/provenance.js";
3
3
  import { parseStoryPanels, StoryPanelError } from "../shell/storyPanels.js";
4
4
  import { SceneError } from "./errors.js";
5
5
  import { toUtcMs } from "./time.js";
6
+ /** Throws "bad-event" naming the first event whose `object` is not among the scene's `objectIds`. */
7
+ export function checkEventObjects(events, objectIds) {
8
+ for (const event of events) {
9
+ if (event.object !== undefined && !objectIds.has(event.object))
10
+ throw new SceneError("bad-event", `addEvents: event "${event.id}" object "${event.object}" is not a body or trajectory in the scene`);
11
+ }
12
+ }
6
13
  /** Checks a provenance given to `addEvents` (for the whole batch, or for the event `eventId`) and returns it frozen; throws "bad-event" when malformed. */
7
14
  export function eventProvenanceOf(value, eventId) {
8
15
  const where = eventId === undefined ? "addEvents: provenance" : `addEvents: event "${eventId}" provenance`;
@@ -27,7 +34,9 @@ export function eventsOf(inputs, known) {
27
34
  throw new SceneError("bad-event", `addEvents: event "${input.id}" appears twice`);
28
35
  ids.add(input.id);
29
36
  const timeUtcMs = toUtcMs(input.time, `addEvents: event "${input.id}" time`);
30
- return { id: input.id, label: input.label, timeUtcMs, ...(input.type === undefined ? {} : { type: input.type }) };
37
+ if (input.object !== undefined && (typeof input.object !== "string" || input.object === ""))
38
+ throw new SceneError("bad-event", `addEvents: event "${input.id}" object must be a non-empty id`);
39
+ return { id: input.id, label: input.label, timeUtcMs, ...(input.type === undefined ? {} : { type: input.type }), ...(input.object === undefined ? {} : { object: input.object }) };
31
40
  });
32
41
  return createEvents([...known, ...added].sort((a, b) => a.timeUtcMs - b.timeUtcMs));
33
42
  }
@@ -48,7 +57,8 @@ export function timelineOf(input) {
48
57
  const rates = input.rates;
49
58
  if (rates !== undefined && (!Array.isArray(rates) || rates.length === 0 || !rates.every((rate) => Number.isFinite(rate) && rate > 0)))
50
59
  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 } : {}) };
60
+ const pacing = pacingOf(input.pacing, bad);
61
+ return { none: false, window, ...(rates === undefined ? {} : { rates }), ...(pacing === undefined ? {} : { pacing }), ...(input.rate === undefined ? {} : { rate: input.rate }), ...(input.loop === true ? { loop: true } : {}) };
52
62
  }
53
63
  /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
54
64
  export function panelsOf(raw, lookup) {
@@ -61,3 +71,64 @@ export function panelsOf(raw, lookup) {
61
71
  throw error;
62
72
  }
63
73
  }
74
+ /** Checks `pacing`: each piece names the field that is wrong (`pacing[2].rate`); spans must not overlap. */
75
+ function pacingOf(input, bad) {
76
+ if (input === undefined)
77
+ return undefined;
78
+ if (!Array.isArray(input))
79
+ throw bad("pacing must be a list of { from, to, rate } and { near: { type, within }, rate }");
80
+ const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
81
+ const pieces = input.map((raw, index) => {
82
+ const at = `pacing[${index}]`;
83
+ if (typeof raw !== "object" || raw === null)
84
+ throw bad(`${at} must be an object`);
85
+ const piece = raw;
86
+ if (!positive(piece.rate))
87
+ throw bad(`${at}.rate must be a positive number, got ${String(piece.rate)}`);
88
+ if (piece.ramp !== undefined && !(typeof piece.ramp === "number" && Number.isFinite(piece.ramp) && piece.ramp >= 0))
89
+ throw bad(`${at}.ramp must be zero or more seconds, got ${String(piece.ramp)}`);
90
+ if (piece.near !== undefined) {
91
+ const { type, within } = piece.near;
92
+ if (typeof type !== "string" || type === "")
93
+ throw bad(`${at}.near.type must be a non-empty event type`);
94
+ if (!positive(within))
95
+ throw bad(`${at}.near.within must be a positive number of seconds, got ${String(within)}`);
96
+ return { type, withinMs: within * 1000, rate: piece.rate, rampMs: (piece.ramp ?? within) * 1000 };
97
+ }
98
+ if (piece.from === undefined || piece.to === undefined)
99
+ throw bad(`${at} needs { from, to, rate } or { near: { type, within }, rate }`);
100
+ const fromUtcMs = toUtcMs(piece.from, `setTimeline ${at}.from`);
101
+ const toUtcMsValue = toUtcMs(piece.to, `setTimeline ${at}.to`);
102
+ if (toUtcMsValue <= fromUtcMs)
103
+ throw bad(`${at}.to must be after ${at}.from`);
104
+ return { fromUtcMs, toUtcMs: toUtcMsValue, rate: piece.rate, rampMs: piece.ramp === undefined ? (toUtcMsValue - fromUtcMs) / 10 : piece.ramp * 1000 };
105
+ });
106
+ const spans = pieces.flatMap((piece, index) => ("fromUtcMs" in piece ? [{ piece, index }] : [])).sort((a, b) => a.piece.fromUtcMs - b.piece.fromUtcMs);
107
+ for (let i = 1; i < spans.length; i += 1) {
108
+ if (spans[i].piece.fromUtcMs < spans[i - 1].piece.toUtcMs)
109
+ throw bad(`pacing[${spans[i].index}] overlaps pacing[${spans[i - 1].index}]; spans may touch but not overlap`);
110
+ }
111
+ return pieces.length === 0 ? undefined : pieces;
112
+ }
113
+ /**
114
+ * 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.
115
+ * A rule whose type has no event throws `bad-timeline` naming the piece (a mistyped type would otherwise slow nothing, silently).
116
+ */
117
+ export function pacingFor(setting, events, baseRate) {
118
+ if (setting.pacing === undefined)
119
+ return undefined;
120
+ const spans = [];
121
+ const near = [];
122
+ setting.pacing.forEach((piece, index) => {
123
+ if ("fromUtcMs" in piece) {
124
+ spans.push({ fromUtcMs: piece.fromUtcMs, toUtcMs: piece.toUtcMs, rate: piece.rate, rampMs: piece.rampMs });
125
+ return;
126
+ }
127
+ const matching = events.filter((event) => event.type === piece.type);
128
+ if (matching.length === 0)
129
+ throw new SceneError("bad-timeline", `setTimeline: pacing[${index}].near.type "${piece.type}" matches no event; give the events that type with addEvents`);
130
+ for (const event of matching)
131
+ near.push({ fromUtcMs: event.timeUtcMs - piece.withinMs, toUtcMs: event.timeUtcMs + piece.withinMs, rate: piece.rate, rampMs: piece.rampMs });
132
+ });
133
+ return { baseRate, zones: [...spans, ...near] };
134
+ }
@@ -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;