astraeus 0.8.1 → 0.9.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 (131) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +104 -31
  3. package/package.json +1 -1
  4. package/src/api/AstraeusScene.d.ts +1 -1
  5. package/src/api/AstraeusScene.js +4 -1
  6. package/src/api/AstraeusScene.node.js +4 -1
  7. package/src/api/assembleScene.d.ts +2 -0
  8. package/src/api/assembleScene.js +28 -6
  9. package/src/api/cameraRequest.d.ts +15 -0
  10. package/src/api/cameraRequest.js +89 -0
  11. package/src/api/errors.d.ts +9 -1
  12. package/src/api/index.d.ts +6 -3
  13. package/src/api/look.d.ts +49 -0
  14. package/src/api/lookInput.d.ts +1 -1
  15. package/src/api/lookInput.js +6 -1
  16. package/src/api/planBodies.d.ts +2 -1
  17. package/src/api/planBodies.js +6 -1
  18. package/src/api/planCamera.d.ts +35 -7
  19. package/src/api/planCamera.js +94 -11
  20. package/src/api/planPaths.d.ts +2 -0
  21. package/src/api/planPaths.js +14 -9
  22. package/src/api/planSkyFigures.d.ts +22 -0
  23. package/src/api/planSkyFigures.js +145 -0
  24. package/src/api/planStory.d.ts +2 -2
  25. package/src/api/planStory.js +14 -9
  26. package/src/api/planViews.js +1 -1
  27. package/src/api/providerPathTimes.d.ts +10 -0
  28. package/src/api/providerPathTimes.js +109 -0
  29. package/src/api/scene.d.ts +23 -4
  30. package/src/api/scene.js +23 -5
  31. package/src/api/sceneReads.d.ts +21 -2
  32. package/src/api/shownDuring.d.ts +12 -0
  33. package/src/api/shownDuring.js +30 -0
  34. package/src/api/skyFigureInput.d.ts +45 -0
  35. package/src/api/skyFigureInput.js +1 -0
  36. package/src/api/skyTraceInput.d.ts +33 -0
  37. package/src/api/skyTraceInput.js +45 -0
  38. package/src/api/story.d.ts +13 -4
  39. package/src/api/story.js +45 -2
  40. package/src/api/viewerCamera.d.ts +4 -3
  41. package/src/api/viewerCamera.js +10 -32
  42. package/src/api/viewerHandle.d.ts +27 -4
  43. package/src/api/viewerHandle.js +6 -0
  44. package/src/api/viewerLink.d.ts +49 -4
  45. package/src/api/viewerLink.js +25 -0
  46. package/src/api/viewerPanels.d.ts +26 -0
  47. package/src/api/viewerPanels.js +42 -0
  48. package/src/api/viewerSelection.d.ts +1 -1
  49. package/src/api/viewerSelection.js +3 -3
  50. package/src/app/App.js +129 -30
  51. package/src/app/App.node.js +129 -30
  52. package/src/app/AstraeusScene.d.ts +20 -5
  53. package/src/app/AstraeusScene.js +3 -3
  54. package/src/app/CameraController.d.ts +19 -1
  55. package/src/app/CameraController.js +38 -11
  56. package/src/app/DeveloperSettings.d.ts +11 -3
  57. package/src/app/DeveloperSettings.js +13 -3
  58. package/src/app/SceneLabels.d.ts +20 -2
  59. package/src/app/SceneLabels.js +46 -6
  60. package/src/app/SkyFiguresView.d.ts +56 -0
  61. package/src/app/SkyFiguresView.js +242 -0
  62. package/src/app/StoryMarkers.d.ts +2 -2
  63. package/src/app/StoryMarkers.js +2 -2
  64. package/src/app/displaySwitches.d.ts +13 -3
  65. package/src/app/displaySwitches.js +17 -3
  66. package/src/app/experienceDefinition.d.ts +9 -3
  67. package/src/app/experienceDefinition.js +4 -2
  68. package/src/app/labelStyle.d.ts +17 -0
  69. package/src/app/labelStyle.js +13 -0
  70. package/src/app/liveLook.js +8 -0
  71. package/src/app/look.d.ts +9 -5
  72. package/src/app/look.js +11 -0
  73. package/src/app/lookOut.d.ts +32 -0
  74. package/src/app/lookOut.js +50 -0
  75. package/src/app/sceneCamera.d.ts +5 -3
  76. package/src/app/sceneCamera.js +66 -3
  77. package/src/app/sceneContentsHooks.d.ts +2 -1
  78. package/src/app/sceneContentsHooks.js +3 -2
  79. package/src/app/sceneFrame.d.ts +22 -4
  80. package/src/app/sceneFrame.js +67 -22
  81. package/src/app/sceneFraming.d.ts +7 -0
  82. package/src/app/sceneFraming.js +12 -0
  83. package/src/app/sceneHooks.d.ts +2 -0
  84. package/src/app/sceneHooks.js +4 -1
  85. package/src/app/scenePicking.d.ts +20 -0
  86. package/src/app/scenePicking.js +49 -0
  87. package/src/app/scenePointer.d.ts +3 -1
  88. package/src/app/scenePointer.js +3 -2
  89. package/src/app/skyFigures.d.ts +73 -0
  90. package/src/app/skyFigures.js +50 -0
  91. package/src/app/style.css +2 -1
  92. package/src/app/viewHiding.d.ts +10 -1
  93. package/src/app/viewHiding.js +30 -1
  94. package/src/app/viewLink.d.ts +8 -8
  95. package/src/app/viewLink.js +24 -4
  96. package/src/app/viewerPort.d.ts +30 -3
  97. package/src/assets/sky.d.ts +13 -4
  98. package/src/assets/sky.js +33 -8
  99. package/src/assets/stars/hyg-v42-naked-eye.json +1 -1
  100. package/src/core/bodies/moonSystem.js +1 -15
  101. package/src/core/lookValues.d.ts +9 -0
  102. package/src/core/lookValues.js +24 -0
  103. package/src/core/pacing.d.ts +38 -6
  104. package/src/core/pacing.js +141 -21
  105. package/src/core/readBytes.d.ts +1 -0
  106. package/src/core/readBytes.js +15 -0
  107. package/src/core/skyTrace.d.ts +49 -0
  108. package/src/core/skyTrace.js +39 -0
  109. package/src/core/startView.d.ts +39 -0
  110. package/src/core/startView.js +56 -0
  111. package/src/core/storyPanels.d.ts +51 -3
  112. package/src/core/storyPanels.js +52 -12
  113. package/src/shell/AstraeusShell.d.ts +17 -6
  114. package/src/shell/AstraeusShell.js +100 -26
  115. package/src/shell/AstraeusShell.node.js +100 -26
  116. package/src/shell/ObjectControls.js +11 -8
  117. package/src/shell/StoryPanelView.d.ts +12 -3
  118. package/src/shell/StoryPanelView.js +2 -2
  119. package/src/shell/experience.d.ts +31 -0
  120. package/src/shell/experience.js +4 -1
  121. package/src/shell/infoModel.js +9 -1
  122. package/src/shell/objectModel.d.ts +9 -4
  123. package/src/shell/objectModel.js +16 -5
  124. package/src/shell/phone.css +1 -1
  125. package/src/shell/storyPanels.d.ts +1 -1
  126. package/src/shell/storyPanels.js +1 -1
  127. package/src/shell/style.css +9 -1
  128. package/src/shell/topBarIcons.d.ts +1 -0
  129. package/src/shell/topBarIcons.js +1 -0
  130. package/src/shell/useStoryPanels.d.ts +9 -6
  131. package/src/shell/useStoryPanels.js +10 -6
@@ -1,8 +1,12 @@
1
1
  import { SceneError } from "./errors.js";
2
2
  import { frozenCopy } from "./frozenCopy.js";
3
- import { validateStartView } from "../core/startView.js";
3
+ import { eqjUnitVector, SKY_OPENING_FOV_DEG, validateCameraView } from "../core/startView.js";
4
+ import { hiddenByView, viewById } from "../app/viewHiding.js";
5
+ import { cameraRequestOf, checkToward } from "./cameraRequest.js";
4
6
  import { farthestSunDistanceKm } from "./sunOrbit.js";
5
7
  import { planetSeriesLoaded } from "../core/planetSeries.js";
8
+ /** Each camera's opening look-out toward an id, kept out of the public class: the request the viewer runs on its first frame, as it runs a `setCamera` one. */
9
+ const towardIds = new WeakMap();
6
10
  /** The scene's camera: what it opens on. */
7
11
  export class SceneCamera {
8
12
  #target;
@@ -12,6 +16,7 @@ export class SceneCamera {
12
16
  #far;
13
17
  #pose;
14
18
  #followIds;
19
+ #lookOutIds = Object.freeze([]);
15
20
  #fit;
16
21
  #has;
17
22
  #circlesSun;
@@ -37,24 +42,57 @@ export class SceneCamera {
37
42
  throw new SceneError("bad-camera", `camera.${call}("${id}"): up "${String(view.up)}" must be "equatorial" or "ecliptic"`);
38
43
  this.#target = id;
39
44
  this.#pose = undefined;
45
+ towardIds.delete(this);
40
46
  this.#following = following;
41
47
  this.#view = frozenCopy(view);
42
48
  return this;
43
49
  }
44
50
  /**
45
- * Opens at a pose with no camera button pressed (neither Focus nor Follow shows as pressed, and choosing another body moves the camera as it does without a start). The pose is what `ViewerHandle.camera` reads:
46
- * `{ focus, azimuthDeg, elevationDeg, distance }`, distance in Earth radii. `focus` must be a body or trajectory already added (else `unknown-body`); a bad angle or distance throws `bad-camera`.
47
- * The last of `follow`, `focus` and `setStartView` wins. Default: none.
51
+ * Opens standing inside a body (at its centre) and looking out, with no camera button pressed. `body` must be a body or trajectory already added (else `unknown-body`).
52
+ * `look` is checked by the rule `setCamera`'s look-out uses: `direction` is a star-map position (`{ raDeg, decDeg }`, J2000 degrees; default 0, 0) or the id of an object or sky figure to turn toward
53
+ * (a figure may be added later); `fovDeg` is the vertical field of view, 5 to 100 degrees (default 60). A malformed look throws `bad-camera`; an id the opening view cannot turn toward throws `bad-camera` when the scene is built.
54
+ * The viewer turns toward an id on its first frame as `setCamera` does; until then `pose` and `ViewerHandle.camera` are undefined. The last of `follow`, `focus`, `lookOut` and `setStartView` wins.
55
+ * @example
56
+ * scene.camera.lookOut("earth", { direction: { raDeg: 83.6, decDeg: 22 }, fovDeg: 40 });
57
+ * scene.camera.lookOut("earth", { direction: "Leo", fovDeg: 80 });
58
+ */
59
+ lookOut(body, look = {}) {
60
+ this.#editable();
61
+ const id = typeof body === "string" ? body : body?.id;
62
+ if (typeof look !== "object" || look === null || Array.isArray(look) || "lookOut" in look)
63
+ throw new SceneError("bad-camera", `camera.lookOut: the look must be { direction?, fovDeg? }, got ${JSON.stringify(look)}`);
64
+ const request = cameraRequestOf({ ...look, lookOut: id }, "camera.lookOut", undefined);
65
+ if (typeof request.direction !== "string") {
66
+ // Already checked: the nested or flat position, else right ascension 0, declination 0.
67
+ const record = look;
68
+ const { raDeg, decDeg } = (record.direction ?? ("raDeg" in record ? record : { raDeg: 0, decDeg: 0 }));
69
+ return this.#start({ lookOut: id, raDeg, decDeg, fovDeg: request.fovDeg ?? SKY_OPENING_FOV_DEG }, "camera.lookOut");
70
+ }
71
+ if (!this.#has(request.body))
72
+ throw new SceneError("unknown-body", `camera.lookOut: "${request.body}" has not been added to the scene`);
73
+ this.#reset();
74
+ towardIds.set(this, request);
75
+ return this;
76
+ }
77
+ /**
78
+ * Opens at a pose with no camera button pressed (neither Focus nor Follow shows as pressed, and choosing another body moves the camera as it does without a start). The pose is what `ViewerHandle.camera` reads, either kind:
79
+ * an orbit pose `{ focus, azimuthDeg, elevationDeg, distance }` (distance in Earth radii), or a sky pose `{ lookOut, raDeg, decDeg, fovDeg }` (standing inside a body, looking out).
80
+ * `focus` or `lookOut` must be a body or trajectory already added (else `unknown-body`); a bad angle, distance or field of view throws `bad-camera`.
81
+ * The last of `follow`, `focus`, `lookOut` and `setStartView` wins. Default: none.
48
82
  * @example
49
83
  * scene.camera.setStartView({ focus: "earth", azimuthDeg: 20, elevationDeg: 30, distance: 40 });
50
84
  */
51
85
  setStartView(pose) {
86
+ return this.#start(pose, "camera.setStartView");
87
+ }
88
+ #start(pose, call) {
52
89
  this.#editable();
53
- const focus = pose?.focus;
54
- if (typeof focus === "string" && !this.#has(focus))
55
- throw new SceneError("unknown-body", `camera.setStartView: "${focus}" has not been added to the scene`);
90
+ const record = pose;
91
+ const named = record?.lookOut ?? record?.focus;
92
+ if (typeof named === "string" && !this.#has(named))
93
+ throw new SceneError("unknown-body", `${call}: "${named}" has not been added to the scene`);
56
94
  try {
57
- this.#pose = validateStartView(pose, "camera.setStartView pose");
95
+ this.#pose = validateCameraView(pose, `${call} pose`);
58
96
  }
59
97
  catch (error) {
60
98
  if (error instanceof RangeError)
@@ -64,8 +102,16 @@ export class SceneCamera {
64
102
  this.#target = undefined;
65
103
  this.#following = false;
66
104
  this.#view = {};
105
+ towardIds.delete(this);
67
106
  return this;
68
107
  }
108
+ /** Clears every opening call before a look-out toward an id. */
109
+ #reset() {
110
+ this.#target = undefined;
111
+ this.#pose = undefined;
112
+ this.#following = false;
113
+ this.#view = {};
114
+ }
69
115
  /**
70
116
  * Chooses the objects whose Follow button the camera menu offers, by body, id, path or group already added to the scene (else `unknown-body`); the others offer Focus only. An empty list offers Follow on none.
71
117
  * Default: every body, path and group. A scene whose opening view follows an object (`follow`) must list it, else the scene throws `bad-camera` when it is built.
@@ -83,6 +129,23 @@ export class SceneCamera {
83
129
  this.#followIds = Object.freeze([...new Set(named)]);
84
130
  return this;
85
131
  }
132
+ /**
133
+ * Chooses the bodies whose "Look out from" entry the camera menu offers, by body, id or path already added to the scene (else `unknown-body`); the entry stands inside the body and looks out, and any other camera entry leaves it.
134
+ * Default: none. An empty list offers none. The opening view is separate: `lookOut` opens looking out whether or not the body is listed.
135
+ * @example
136
+ * scene.camera.setLookOutChoices(["earth", "mars"]);
137
+ */
138
+ setLookOutChoices(ids) {
139
+ this.#editable();
140
+ if (!Array.isArray(ids))
141
+ throw new SceneError("bad-camera", "camera.setLookOutChoices: give a list of bodies or ids");
142
+ const named = ids.map((item) => (typeof item === "string" ? item : item?.id));
143
+ for (const id of named)
144
+ if (typeof id !== "string" || !this.#has(id))
145
+ throw new SceneError("unknown-body", `camera.setLookOutChoices("${String(id)}"): no body or trajectory with that id has been added to the scene`);
146
+ this.#lookOutIds = Object.freeze([...new Set(named)]);
147
+ return this;
148
+ }
86
149
  /**
87
150
  * Sets how far the viewer can zoom out from what they look at, in Earth radii (the scene's scaled unit); a finite number above 0, else `bad-camera`.
88
151
  * Also sets the camera's far plane (where drawing stops) to 2.5 times `distance`, so what lies out to the reach is still drawn; `farEarthRadii` (a finite number at least `distance`, in Earth radii) sets the far plane itself instead.
@@ -128,15 +191,31 @@ export class SceneCamera {
128
191
  get reachEarthRadii() { return this.#reach; }
129
192
  /** The far plane set with `setReach`'s `farEarthRadii`, if any. */
130
193
  get farEarthRadii() { return this.#far; }
131
- /** The pose `setStartView` set, if it is the last opening call. */
194
+ /** The pose `setStartView` or `lookOut` set, if it is the last opening call (undefined after a `lookOut` toward an id). */
132
195
  get pose() { return this.#pose; }
133
196
  /** The objects offering Follow (`setFollowChoices`); undefined: every one. */
134
197
  get followChoices() { return this.#followIds; }
198
+ /** The bodies offering "Look out from" (`setLookOutChoices`); none by default. */
199
+ get lookOutChoices() { return this.#lookOutIds; }
135
200
  get target() { return this.#target; }
136
201
  /** Whether the opening view follows its target (`follow`) rather than only looking at it (`focus`). */
137
202
  get following() { return this.#following; }
138
203
  get view() { return this.#view; }
139
204
  }
205
+ /**
206
+ * Refuses an opening look-out toward an id `setCamera` would refuse on the opening view (`checkToward`, the same check and wording): the direction must name an object the opening view shows or a sky figure.
207
+ * Called when the scene is built, after every figure is in.
208
+ */
209
+ export function checkOpeningLook(camera, definition, groupIds, figureIds) {
210
+ const toward = towardIds.get(camera);
211
+ if (toward === undefined)
212
+ return;
213
+ const views = definition.views;
214
+ const hidden = hiddenByView(views, viewById(views, views?.start ?? ""), definition.experience).objects;
215
+ const shown = [...definition.experience.objects.map(({ id }) => id), ...groupIds].filter((id) => !hidden.has(id));
216
+ if (typeof toward.direction === "string")
217
+ checkToward(toward.direction, "camera.lookOut", shown, [...figureIds], "the opening view");
218
+ }
140
219
  /** 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. */
141
220
  export function fitFarthestKm(camera, catalogue, own, openUtcMs) {
142
221
  const id = camera.fitted;
@@ -155,6 +234,9 @@ export function startPresetEntry(camera) {
155
234
  }
156
235
  /** The `startView` entry of the definition: the opening framing of the camera's target (absent when none was asked for). */
157
236
  export function startViewEntry(camera) {
237
+ const toward = towardIds.get(camera);
238
+ if (toward !== undefined)
239
+ return { startView: toward };
158
240
  if (camera.pose !== undefined)
159
241
  return { startView: { ...camera.pose } };
160
242
  const target = camera.target;
@@ -172,13 +254,14 @@ export function viewEntries(timeline, camera, farthestKm, cover) {
172
254
  ...(view.up === undefined || target === undefined ? {} : { viewUp: view.up }),
173
255
  };
174
256
  }
175
- /** The camera menu: Overview, Focus for every body and path, and Follow for every one unless `setFollowChoices` named fewer. */
176
- export function cameraPresetsOf(objects, followChoices) {
257
+ /** The camera menu: Overview, Focus for every body and path, Follow for every one unless `setFollowChoices` named fewer, and "Look out from" for the bodies `setLookOutChoices` listed (the look is toward right ascension 0, declination 0 until the visitor turns). */
258
+ export function cameraPresetsOf(objects, followChoices, lookOutChoices = []) {
177
259
  return [
178
260
  { id: "overview", label: "Overview", request: { kind: "overview" } },
179
261
  ...objects.flatMap(({ id, label }) => [
180
262
  { id: `focus-${id}`, label: `Focus ${label}`, request: { kind: "focus", target: id } },
181
263
  ...(followChoices === undefined || followChoices.includes(id) ? [{ id: `follow-${id}`, label: `Follow ${label}`, request: { kind: "follow", target: id } }] : []),
264
+ ...(lookOutChoices.includes(id) ? [{ id: `lookout-${id}`, label: `Look out from ${label}`, request: { kind: "lookOut", body: id, direction: eqjUnitVector(0, 0) } }] : []),
182
265
  ]),
183
266
  ];
184
267
  }
@@ -3,6 +3,7 @@ import type { WindowProvenanceSpan } from "../core/timeWindow.js";
3
3
  import { type BodyCatalogue } from "../assets/catalogue.js";
4
4
  import { type TrackedBody } from "../app/mission.js";
5
5
  import { SceneError } from "./errors.js";
6
+ import type { ShownSpan } from "../shell/experience.js";
6
7
  import type { ReadoutInput, TrajectoryInput } from "./scene.js";
7
8
  import { type ScenePathRead } from "./sceneReads.js";
8
9
  export interface Tracked {
@@ -13,6 +14,7 @@ export interface Tracked {
13
14
  readonly description?: string;
14
15
  readonly knownLimitations?: readonly string[];
15
16
  readonly provenanceSpans?: readonly WindowProvenanceSpan[];
17
+ readonly shownDuring?: ShownSpan;
16
18
  readonly readouts: readonly ReadoutInput[];
17
19
  }
18
20
  /** The paths in the order added, as the public list states them. */
@@ -1,20 +1,21 @@
1
1
  import { createProvenance } from "../core/provenance.js";
2
2
  import { SampledTrajectory } from "../core/sampledTrajectory.js";
3
- import { createState } from "../core/state.js";
3
+ import { assertUtcUnixMs, createState } from "../core/state.js";
4
4
  import { createOrbTwoBodyAdapter } from "../core/twoBodyAdapter.js";
5
5
  import { createStateResolver } from "../core/stateResolver.js";
6
6
  import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
7
7
  import { planetSeriesLoaded } from "../core/planetSeries.js";
8
8
  import { catalogue as builtInCatalogue } from "../assets/catalogue.js";
9
9
  import { lineBodies } from "../app/mission.js";
10
+ import { providerPathTimes } from "./providerPathTimes.js";
10
11
  import { planLineStretches, planPathProvenance } from "./pathProvenance.js";
11
12
  import { influenceStretches, sphereOfInfluenceKm } from "./sphereOfInfluence.js";
12
13
  import { SceneError } from "./errors.js";
13
14
  import { rejectRenamed } from "./renamedInputs.js";
14
15
  import { toUtcMs } from "./time.js";
16
+ import { planShownDuring } from "./shownDuring.js";
15
17
  import { frozenList } from "./sceneReads.js";
16
18
  const DEFAULT_COLOR = "#ffd27a";
17
- const PROVIDER_PATH_SAMPLES = 128;
18
19
  /** Samples along a path when its farthest distance is read for the default zoom-out. */
19
20
  const PATH_COVER_SAMPLES = 400;
20
21
  /** The paths in the order added, as the public list states them. */
@@ -37,13 +38,14 @@ export function buildTracked(input, center, labelReaches) {
37
38
  if (input.plane !== undefined && input.plane !== "EQJ" && input.plane !== "ecliptic-j2000")
38
39
  throw new SceneError("bad-trajectory", `addTrajectory("${id}"): plane "${String(input.plane)}" must be "EQJ" or "ecliptic-j2000"`);
39
40
  const toEqj = input.plane === "ecliptic-j2000" ? createOrbTwoBodyAdapter().eclipticJ2000ToEqjMatrix() : null;
40
- const body = "samples" in input ? sampledBody(common, input, center, toEqj) : providerBody(common, input, toEqj);
41
+ const body = "samples" in input ? sampledBody(common, input, center, toEqj) : providerBody(common, input, center, toEqj);
41
42
  const span = { startUtcMs: body.trajectory.bounds.startUtcMs, endUtcMs: body.trajectory.bounds.endUtcMs };
42
43
  const provenanceSpans = input.provenanceSpans === undefined ? undefined : planPathProvenance(id, input.provenanceSpans, span);
44
+ const shownDuring = planShownDuring("addTrajectory", id, "bad-trajectory", input.shownDuring);
43
45
  checkLineFixedToType(id, input.lineFixedTo);
44
46
  const auto = input.lineFixedTo === "auto";
45
47
  const lineFixedTo = typeof input.lineFixedTo === "object" ? planLineStretches(id, input.lineFixedTo, span) : auto ? undefined : input.lineFixedTo;
46
- return { center, ...(auto ? { auto: true } : {}), body: withAnchors(lineFixedTo === undefined ? body : { ...body, lineFixedTo }, input.anchors), readouts, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) };
48
+ return { center, ...(auto ? { auto: true } : {}), body: withAnchors(lineFixedTo === undefined ? body : { ...body, lineFixedTo }, input.anchors), readouts, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(shownDuring === undefined ? {} : { shownDuring }), ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) };
47
49
  }
48
50
  /** Rotates a vector by a row-major 3x3 matrix; a missing matrix leaves it as it is. Input that is not three numbers passes through for the State checks to refuse. */
49
51
  function rotated(matrix, v) {
@@ -71,16 +73,19 @@ function checkLineFixedToType(id, value) {
71
73
  if (value !== undefined && typeof value !== "string" && typeof value !== "object")
72
74
  throw new SceneError("bad-trajectory", `addTrajectory("${id}"): lineFixedTo ${String(value)} must be a body id, "auto" or a list of stretches`);
73
75
  }
74
- function providerBody(common, input, toEqj) {
76
+ function providerBody(common, input, center, toEqj) {
75
77
  if (typeof input.provider?.stateAt !== "function")
76
78
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): provider needs a stateAt(time) function`);
77
79
  const bounds = { startUtcMs: toUtcMs(input.bounds?.start, `addTrajectory("${common.id}") bounds.start`), endUtcMs: toUtcMs(input.bounds?.end, `addTrajectory("${common.id}") bounds.end`) };
78
80
  if (bounds.endUtcMs <= bounds.startUtcMs)
79
81
  throw new SceneError("bad-trajectory", `addTrajectory("${common.id}"): bounds must end after they start`);
80
- const trajectory = { body: common.id, bounds, stateAt: (timeUtcMs, center) => rotatedState(toEqj, input.provider.stateAt(timeUtcMs, center)) };
81
- // Whole milliseconds, because the state resolver refuses a fractional time (the line is placed against another body at these times).
82
- const step = (bounds.endUtcMs - bounds.startUtcMs) / (PROVIDER_PATH_SAMPLES - 1);
83
- return { ...common, trajectory, pathTimesUtcMs: Array.from({ length: PROVIDER_PATH_SAMPLES }, (_, index) => Math.round(bounds.startUtcMs + index * step)) };
82
+ const trajectory = { body: common.id, bounds, stateAt: (timeUtcMs, center) => {
83
+ // Every call reaches the host here (`stateOf`, line planning, reach, sampling): a provider only ever sees whole milliseconds (I-177).
84
+ assertUtcUnixMs(timeUtcMs);
85
+ return rotatedState(toEqj, input.provider.stateAt(timeUtcMs, center));
86
+ } };
87
+ // Whole milliseconds, because the state resolver refuses a fractional time (the line is placed against another body at these times). The 128 even moments gain more where the path bends or the body moves fast, as seen from `center`.
88
+ return { ...common, trajectory, pathTimesUtcMs: providerPathTimes(bounds.startUtcMs, bounds.endUtcMs, (t) => trajectory.stateAt(t, center).positionKm) };
84
89
  }
85
90
  /** A provider's State with its position and velocity rotated into EQJ; unchanged for EQJ input. */
86
91
  function rotatedState(matrix, state) {
@@ -0,0 +1,22 @@
1
+ import { type StarById } from "../assets/sky.js";
2
+ import { type SkyFigureLayer } from "../app/skyFigures.js";
3
+ import type { SkyFigureCard } from "../shell/experience.js";
4
+ import type { SkyFigureInput } from "./skyFigureInput.js";
5
+ import { type SceneSkyFigureRead } from "./sceneReads.js";
6
+ /** What a `Scene` has planned for sky figures, in the order added. */
7
+ export declare class SkyFigurePlan {
8
+ private readonly taken;
9
+ readonly figures: Map<string, SkyFigureInput>;
10
+ constructor(taken: (id: string) => boolean);
11
+ /** Checks every figure (shape, then ids against the scene and each other) and adds them all, or none. */
12
+ add(figures: readonly SkyFigureInput[]): void;
13
+ has(id: string): boolean;
14
+ /** The figures in the order added: id, label, kind, and the card words as given (`listed` true unless said false). */
15
+ reads(): readonly SceneSkyFigureRead[];
16
+ /** What the viewer's info card and object menu read for each figure (no star list needed). */
17
+ cards(): readonly SkyFigureCard[];
18
+ /** Whether any end names a catalogue star, so the star list is needed to place it. */
19
+ get needsStars(): boolean;
20
+ /** The drawable figures. `stars` finds a star by its Hipparcos number; a number it does not hold throws `unknown-star`. Called when the scene is built (the star list loads asynchronously, so not at the `addSkyFigures` call). */
21
+ layers(stars: ReadonlyMap<number, StarById>): readonly SkyFigureLayer[];
22
+ }
@@ -0,0 +1,145 @@
1
+ import { isCssColour, isFontFamily, LABEL_SIZE_LIMITS } from "../core/lookValues.js";
2
+ import { eqjUnit } from "../assets/sky.js";
3
+ import { meanDirection } from "../app/skyFigures.js";
4
+ import { createProvenance } from "../core/provenance.js";
5
+ import { SceneError } from "./errors.js";
6
+ import { frozenCopy } from "./frozenCopy.js";
7
+ import { frozenList } from "./sceneReads.js";
8
+ const bad = (id, message) => new SceneError("bad-sky-figure", `addSkyFigures("${String(id)}"): ${message}`);
9
+ const isText = (value) => typeof value === "string" && value !== "";
10
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
11
+ const isPosition = (value) => typeof value === "object" && value !== null && isNumber(value.raDeg) && isNumber(value.decDeg) && Math.abs(value.decDeg) <= 90;
12
+ const isStar = (value) => typeof value === "object" && value !== null && Number.isInteger(value.star) && value.star > 0;
13
+ function checkEnd(id, end, where) {
14
+ if (!isStar(end) && !isPosition(end))
15
+ throw bad(id, `${where} must be { star: <Hipparcos number> } or { raDeg, decDeg } with a declination within ±90, got ${JSON.stringify(end)}`);
16
+ }
17
+ /** Checks the card fields (description, facts, sources, provenance) and the menu flag, as `addBody` and `addTrajectory` check theirs. */
18
+ function checkCard(id, figure) {
19
+ if (figure.description !== undefined && !isText(figure.description))
20
+ throw bad(id, `description must be a non-empty text, got ${JSON.stringify(figure.description)}`);
21
+ const { facts, sources } = figure;
22
+ if (facts !== undefined && !(Array.isArray(facts) && facts.every((fact) => isText(fact?.label) && isText(fact?.value))))
23
+ throw bad(id, "facts must be a list of { label, value } with both texts non-empty");
24
+ if (sources !== undefined && !(Array.isArray(sources) && sources.every(isText)))
25
+ throw bad(id, "sources must be a list of non-empty texts");
26
+ if (figure.listed !== undefined && typeof figure.listed !== "boolean")
27
+ throw bad(id, `listed must be true or false, got ${JSON.stringify(figure.listed)}`);
28
+ if (figure.provenance !== undefined) {
29
+ try {
30
+ createProvenance(figure.provenance);
31
+ }
32
+ catch (error) {
33
+ throw bad(id, `provenance is malformed (${error instanceof Error ? error.message : String(error)})`);
34
+ }
35
+ }
36
+ }
37
+ /** The provenance a figure's card shows: the one given (default: illustrative, supplied by the caller, as for a path) with `sources` added after its own. */
38
+ function provenanceOf(figure) {
39
+ const own = figure.provenance ?? createProvenance({ sourceType: "illustrative", sources: ["Supplied by the caller"], accuracy: "As supplied; the engine makes no claim.", notes: "The figure's lines were passed to addSkyFigures." });
40
+ return createProvenance({ ...own, sources: [...own.sources, ...(figure.sources ?? [])] });
41
+ }
42
+ /** Checks a figure's own colours, label font and label size. */
43
+ function checkLooks(id, figure) {
44
+ if (figure.color !== undefined && !isCssColour(figure.color))
45
+ throw bad(id, `color must be a CSS colour such as "#8fb4ff", got ${JSON.stringify(figure.color)}`);
46
+ if (figure.labelColor !== undefined && !isCssColour(figure.labelColor))
47
+ throw bad(id, `labelColor must be a CSS colour such as "#cfe0ff", got ${JSON.stringify(figure.labelColor)}`);
48
+ if (figure.labelFont !== undefined && !isFontFamily(figure.labelFont))
49
+ throw bad(id, `labelFont must be a non-empty CSS font-family text, got ${JSON.stringify(figure.labelFont)}`);
50
+ if (figure.labelSizePx !== undefined && !(isNumber(figure.labelSizePx) && figure.labelSizePx >= LABEL_SIZE_LIMITS.min && figure.labelSizePx <= LABEL_SIZE_LIMITS.max))
51
+ throw bad(id, `labelSizePx must be a number from ${LABEL_SIZE_LIMITS.min} to ${LABEL_SIZE_LIMITS.max}, got ${JSON.stringify(figure.labelSizePx)}`);
52
+ }
53
+ /** Checks one figure's shape; throws `bad-sky-figure` naming the field. */
54
+ function checkShape(figure) {
55
+ if (typeof figure !== "object" || figure === null)
56
+ throw bad(figure, "give a { id, label, segments } or { id, label, kind: \"boundary\", points } object");
57
+ const { id, kind = "figure" } = figure;
58
+ if (!isText(id))
59
+ throw bad(id, "id must be a non-empty text");
60
+ if (!isText(figure.label))
61
+ throw bad(id, "label must be a non-empty text");
62
+ if (kind !== "figure" && kind !== "boundary")
63
+ throw bad(id, `kind must be "figure" or "boundary", got ${JSON.stringify(kind)}`);
64
+ if (kind === "figure") {
65
+ if (figure.points !== undefined)
66
+ throw bad(id, "a figure has segments, not points (use kind: \"boundary\" for points)");
67
+ if (!Array.isArray(figure.segments) || figure.segments.length === 0)
68
+ throw bad(id, "a figure needs segments: a non-empty list of [end, end] pairs");
69
+ figure.segments.forEach((pair, index) => {
70
+ if (!Array.isArray(pair) || pair.length !== 2)
71
+ throw bad(id, `segments[${index}] must be a pair [end, end]`);
72
+ checkEnd(id, pair[0], `segments[${index}][0]`);
73
+ checkEnd(id, pair[1], `segments[${index}][1]`);
74
+ });
75
+ }
76
+ else {
77
+ if (figure.segments !== undefined)
78
+ throw bad(id, "a boundary has points, not segments");
79
+ if (!Array.isArray(figure.points) || figure.points.length < 3)
80
+ throw bad(id, "a boundary needs points: a closed loop of at least three { raDeg, decDeg }");
81
+ figure.points.forEach((point, index) => { if (!isPosition(point))
82
+ throw bad(id, `points[${index}] must be { raDeg, decDeg } with a declination within ±90, got ${JSON.stringify(point)}`); });
83
+ }
84
+ if (figure.labelAt !== undefined && !isPosition(figure.labelAt))
85
+ throw bad(id, `labelAt must be { raDeg, decDeg } with a declination within ±90, got ${JSON.stringify(figure.labelAt)}`);
86
+ if (figure.shown !== undefined && figure.shown !== "always" && figure.shown !== "whenTraced")
87
+ throw bad(id, `shown must be "always" or "whenTraced", got ${JSON.stringify(figure.shown)}`);
88
+ checkLooks(id, figure);
89
+ checkCard(id, figure);
90
+ }
91
+ const endsOf = (figure) => (figure.segments ?? []).flat();
92
+ /** What a `Scene` has planned for sky figures, in the order added. */
93
+ export class SkyFigurePlan {
94
+ taken;
95
+ figures = new Map();
96
+ constructor(taken) {
97
+ this.taken = taken;
98
+ }
99
+ /** Checks every figure (shape, then ids against the scene and each other) and adds them all, or none. */
100
+ add(figures) {
101
+ if (!Array.isArray(figures) || figures.length === 0)
102
+ throw bad("", "give a non-empty list of figures");
103
+ const copies = figures.map((figure) => { checkShape(figure); return frozenCopy(figure); });
104
+ const seen = new Set();
105
+ for (const { id } of copies) {
106
+ if (this.figures.has(id) || seen.has(id) || this.taken(id))
107
+ throw new SceneError("duplicate-id", `addSkyFigures("${id}"): that id is already in the scene`);
108
+ seen.add(id);
109
+ }
110
+ for (const copy of copies)
111
+ this.figures.set(copy.id, copy);
112
+ }
113
+ has(id) { return this.figures.has(id); }
114
+ /** The figures in the order added: id, label, kind, and the card words as given (`listed` true unless said false). */
115
+ reads() {
116
+ return frozenList([...this.figures.values()].map((figure) => ({ id: figure.id, label: figure.label, kind: figure.kind ?? "figure", listed: figure.listed !== false, provenance: provenanceOf(figure), ...(figure.description === undefined ? {} : { description: figure.description }), ...(figure.facts === undefined ? {} : { facts: figure.facts }) })));
117
+ }
118
+ /** What the viewer's info card and object menu read for each figure (no star list needed). */
119
+ cards() {
120
+ return [...this.figures.values()].map((figure) => ({ id: figure.id, label: figure.label, listed: figure.listed !== false, provenance: provenanceOf(figure), ...(figure.description === undefined ? {} : { description: figure.description }), ...(figure.facts === undefined ? {} : { facts: figure.facts }) }));
121
+ }
122
+ /** Whether any end names a catalogue star, so the star list is needed to place it. */
123
+ get needsStars() { return [...this.figures.values()].some((figure) => endsOf(figure).some((end) => "star" in end)); }
124
+ /** The drawable figures. `stars` finds a star by its Hipparcos number; a number it does not hold throws `unknown-star`. Called when the scene is built (the star list loads asynchronously, so not at the `addSkyFigures` call). */
125
+ layers(stars) {
126
+ const direction = (id, end) => {
127
+ if ("star" in end) {
128
+ const found = stars.get(end.star);
129
+ if (found === undefined)
130
+ throw new SceneError("unknown-star", `addSkyFigures("${id}"): star ${end.star} is not in the star list (Hipparcos numbers of stars of magnitude 6.5 or brighter)`);
131
+ return found.direction;
132
+ }
133
+ return eqjUnit(end.raDeg, end.decDeg);
134
+ };
135
+ return [...this.figures.values()].map((figure) => {
136
+ const kind = figure.kind ?? "figure";
137
+ const segments = kind === "figure"
138
+ ? figure.segments.map(([from, to]) => [direction(figure.id, from), direction(figure.id, to)])
139
+ : figure.points.map((point, index) => [eqjUnit(point.raDeg, point.decDeg), eqjUnit(figure.points[(index + 1) % figure.points.length].raDeg, figure.points[(index + 1) % figure.points.length].decDeg)]);
140
+ const labelAt = figure.labelAt === undefined ? meanDirection(segments.flatMap(([from, to]) => [from, to])) : eqjUnit(figure.labelAt.raDeg, figure.labelAt.decDeg);
141
+ const own = ["color", "labelColor", "labelFont", "labelSizePx"].filter((key) => figure[key] !== undefined);
142
+ return { id: figure.id, label: figure.label, kind, segments, labelAt, ...(figure.shown === "whenTraced" ? { whenTraced: true } : {}), ...Object.fromEntries(own.map((key) => [key, figure[key]])) };
143
+ });
144
+ }
145
+ }
@@ -16,11 +16,11 @@ export declare class StoryPlan {
16
16
  /** The events name only objects the scene holds. */
17
17
  checkObjects(ids: ReadonlySet<string>): void;
18
18
  /** The story panels, resolved against this scene's events, the anchors of its paths, its objects and timeline span. */
19
- panels(window: TimeBounds, tracked: Iterable<Tracked>, objectIds: readonly string[]): StoryPanelSet | undefined;
19
+ panels(window: TimeBounds, tracked: Iterable<Tracked>, objectIds: readonly string[], figureIds: readonly string[]): StoryPanelSet | undefined;
20
20
  /** The events sorted by time, each with its own provenance, else the batch's. */
21
21
  eventReads(): readonly SceneEventRead[];
22
22
  /** The story panels as the public list states them (resolved as `panels` resolves them); empty when none were added. */
23
- panelReads(window: TimeBounds, tracked: Iterable<Tracked>, objectIds: readonly string[]): readonly ScenePanelRead[];
23
+ panelReads(window: TimeBounds, tracked: Iterable<Tracked>, objectIds: readonly string[], figureIds: readonly string[]): readonly ScenePanelRead[];
24
24
  /** The event provenance entries of the experience: the batch's, and each event's own. */
25
25
  provenanceEntries(): Pick<ExperienceConfig, "eventProvenance" | "eventProvenanceById">;
26
26
  }
@@ -31,14 +31,14 @@ export class StoryPlan {
31
31
  checkEventObjects(this.events, ids);
32
32
  }
33
33
  /** The story panels, resolved against this scene's events, the anchors of its paths, its objects and timeline span. */
34
- panels(window, tracked, objectIds) {
34
+ panels(window, tracked, objectIds, figureIds) {
35
35
  if (this.#panels === undefined)
36
36
  return undefined;
37
37
  const anchors = new Map();
38
38
  for (const { body } of tracked)
39
39
  body.anchorLabels?.forEach((label, index) => { if (!anchors.has(label))
40
40
  anchors.set(label, body.anchorTimesUtcMs[index]); });
41
- return panelsOf(this.#panels, this.#playback, { events: this.events, anchors, objectIds, window });
41
+ return panelsOf(this.#panels, this.#playback, { events: this.events, anchors, objectIds, figureIds, window });
42
42
  }
43
43
  /** The events sorted by time, each with its own provenance, else the batch's. */
44
44
  eventReads() {
@@ -48,13 +48,18 @@ export class StoryPlan {
48
48
  }));
49
49
  }
50
50
  /** The story panels as the public list states them (resolved as `panels` resolves them); empty when none were added. */
51
- panelReads(window, tracked, objectIds) {
52
- const set = this.panels(window, tracked, objectIds);
53
- return frozenList((set?.panels ?? []).map(({ id, timeUtcMs, title, body, details, provenance, objectId }) => ({
54
- id, timeUtcMs, title, provenance,
55
- body: Object.freeze([...body]), details: Object.freeze([...details]),
56
- ...(objectId === undefined ? {} : { object: objectId }),
57
- })));
51
+ panelReads(window, tracked, objectIds, figureIds) {
52
+ const set = this.panels(window, tracked, objectIds, figureIds);
53
+ const listed = [...(set?.panels ?? []), ...(set?.steps ?? [])];
54
+ return frozenList(listed.map((panel) => {
55
+ const { id, title, body, details, provenance, objectId } = panel;
56
+ return {
57
+ id, title, provenance,
58
+ ..."timeUtcMs" in panel ? { timeUtcMs: panel.timeUtcMs } : {},
59
+ body: Object.freeze([...body]), details: Object.freeze([...details]),
60
+ ...(objectId === undefined ? {} : { object: objectId }),
61
+ };
62
+ }));
58
63
  }
59
64
  /** The event provenance entries of the experience: the batch's, and each event's own. */
60
65
  provenanceEntries() {
@@ -30,6 +30,6 @@ export class ViewPlan {
30
30
  viewsEntry(scene, storyPanels) {
31
31
  if (this.#views === undefined)
32
32
  return {};
33
- return { views: resolveViews(this.#views, { objects: scene.objects, events: scene.events, panels: storyPanels?.panels.map(({ id }) => id) ?? [] }) };
33
+ return { views: resolveViews(this.#views, { objects: scene.objects, events: scene.events, panels: [...(storyPanels?.panels ?? []), ...(storyPanels?.steps ?? [])].map(({ id }) => id) }) };
34
34
  }
35
35
  }
@@ -0,0 +1,10 @@
1
+ /** The moments a provider path's line is drawn at: 128 even ones plus extra ones where the line bends or the body moves fast, as seen from the path's centre (O-070). */
2
+ /** Even moments every path starts from. */
3
+ export declare const PROVIDER_SEED_SAMPLES = 128;
4
+ /** Most moments a provider path is drawn at. */
5
+ export declare const PROVIDER_MAX_SAMPLES = 4096;
6
+ /**
7
+ * Strictly increasing whole-millisecond moments from `startUtcMs` to `endUtcMs`: the 128 even ones (the first and last are the bounds), then midpoints of the intervals that bend
8
+ * or speed up most, until none is over the limits or there are 4,096. `positionAt` gives the body's position about the path's centre; if it throws or gives no position, the even moments stand alone.
9
+ */
10
+ export declare function providerPathTimes(startUtcMs: number, endUtcMs: number, positionAt: (timeUtcMs: number) => ArrayLike<number>): number[];
@@ -0,0 +1,109 @@
1
+ /** The moments a provider path's line is drawn at: 128 even ones plus extra ones where the line bends or the body moves fast, as seen from the path's centre (O-070). */
2
+ /** Even moments every path starts from. */
3
+ export const PROVIDER_SEED_SAMPLES = 128;
4
+ /** Most moments a provider path is drawn at. */
5
+ export const PROVIDER_MAX_SAMPLES = 4096;
6
+ /** An interval is split while the body sweeps more than this angle about the centre between its ends. */
7
+ const MAX_SWEEP_RAD = (3 * Math.PI) / 180;
8
+ /** An interval is split while its true midpoint lies farther than this fraction of its distance from the centre from the chord's midpoint (the body speeding up or slowing down shows here too). */
9
+ const MAX_CHORD_ERROR = 0.0025;
10
+ /** The position as three finite numbers, or null when the provider gave something else. */
11
+ const read = (positionAt, timeUtcMs) => {
12
+ const p = positionAt(timeUtcMs);
13
+ return p?.length === 3 && Number.isFinite(p[0]) && Number.isFinite(p[1]) && Number.isFinite(p[2]) ? [p[0], p[1], p[2]] : null;
14
+ };
15
+ /** The interval's score. */
16
+ function scored(a, b, pa, pb, positionAt) {
17
+ const mid = Math.floor((a + b) / 2);
18
+ const pm = read(positionAt, mid);
19
+ if (pm === null)
20
+ return { a, b, pa, pb, mid, pm: pa, score: 0 };
21
+ const w = (mid - a) / (b - a);
22
+ const na = Math.hypot(...pa);
23
+ const nb = Math.hypot(...pb);
24
+ const dot = pa[0] * pb[0] + pa[1] * pb[1] + pa[2] * pb[2];
25
+ const sweep = Math.acos(Math.max(-1, Math.min(1, dot / (na * nb))));
26
+ const chord = Math.hypot(pm[0] - (pa[0] + w * (pb[0] - pa[0])), pm[1] - (pa[1] + w * (pb[1] - pa[1])), pm[2] - (pa[2] + w * (pb[2] - pa[2])));
27
+ const reach = Math.max(Math.hypot(...pm), Math.min(na, nb));
28
+ const score = Math.max(sweep / MAX_SWEEP_RAD, chord / (MAX_CHORD_ERROR * reach));
29
+ return { a, b, pa, pb, mid, pm, score: Number.isFinite(score) ? score : 0 };
30
+ }
31
+ /** Max-heap on score; ties go to the earlier interval, so the result is the same every time. */
32
+ class Worst {
33
+ #items = [];
34
+ get size() {
35
+ return this.#items.length;
36
+ }
37
+ #before(i, j) {
38
+ const x = this.#items[i];
39
+ const y = this.#items[j];
40
+ return x.score > y.score || (x.score === y.score && x.a < y.a);
41
+ }
42
+ #swap(i, j) {
43
+ [this.#items[i], this.#items[j]] = [this.#items[j], this.#items[i]];
44
+ }
45
+ push(item) {
46
+ this.#items.push(item);
47
+ for (let i = this.#items.length - 1; i > 0;) {
48
+ const parent = (i - 1) >> 1;
49
+ if (!this.#before(i, parent))
50
+ break;
51
+ this.#swap(i, parent);
52
+ i = parent;
53
+ }
54
+ }
55
+ pop() {
56
+ const top = this.#items[0];
57
+ const last = this.#items.pop();
58
+ if (this.#items.length > 0) {
59
+ this.#items[0] = last;
60
+ for (let i = 0;;) {
61
+ let best = i;
62
+ for (const child of [2 * i + 1, 2 * i + 2])
63
+ if (child < this.#items.length && this.#before(child, best))
64
+ best = child;
65
+ if (best === i)
66
+ break;
67
+ this.#swap(i, best);
68
+ i = best;
69
+ }
70
+ }
71
+ return top;
72
+ }
73
+ }
74
+ /**
75
+ * Strictly increasing whole-millisecond moments from `startUtcMs` to `endUtcMs`: the 128 even ones (the first and last are the bounds), then midpoints of the intervals that bend
76
+ * or speed up most, until none is over the limits or there are 4,096. `positionAt` gives the body's position about the path's centre; if it throws or gives no position, the even moments stand alone.
77
+ */
78
+ export function providerPathTimes(startUtcMs, endUtcMs, positionAt) {
79
+ const step = (endUtcMs - startUtcMs) / (PROVIDER_SEED_SAMPLES - 1);
80
+ const seeds = [...new Set(Array.from({ length: PROVIDER_SEED_SAMPLES }, (_, index) => Math.round(startUtcMs + index * step)))];
81
+ try {
82
+ return refined(seeds, positionAt);
83
+ }
84
+ catch {
85
+ return seeds; // a provider that cannot answer yet (its data is not loaded) keeps the even moments
86
+ }
87
+ }
88
+ function refined(seeds, positionAt) {
89
+ const found = seeds.map((t) => read(positionAt, t));
90
+ const positions = found.filter((p) => p !== null);
91
+ if (positions.length < seeds.length)
92
+ return [...seeds]; // a position the provider does not give: the fault is named when the line is drawn
93
+ const heap = new Worst();
94
+ for (let i = 1; i < seeds.length; i += 1)
95
+ if (seeds[i] - seeds[i - 1] >= 2)
96
+ heap.push(scored(seeds[i - 1], seeds[i], positions[i - 1], positions[i], positionAt));
97
+ const times = new Set(seeds);
98
+ while (heap.size > 0 && times.size < PROVIDER_MAX_SAMPLES) {
99
+ const worst = heap.pop();
100
+ if (worst.score <= 1)
101
+ break;
102
+ times.add(worst.mid);
103
+ for (const [a, b, pa, pb] of [[worst.a, worst.mid, worst.pa, worst.pm], [worst.mid, worst.b, worst.pm, worst.pb]]) {
104
+ if (b - a >= 2)
105
+ heap.push(scored(a, b, pa, pb, positionAt));
106
+ }
107
+ }
108
+ return [...times].sort((x, y) => x - y);
109
+ }