astraeus 0.1.0 → 0.2.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 (77) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +39 -6
  3. package/package.json +9 -6
  4. package/src/api/AstraeusScene.d.ts +27 -0
  5. package/src/api/AstraeusScene.js +38 -0
  6. package/src/api/activity.d.ts +50 -0
  7. package/src/api/activity.js +62 -0
  8. package/src/api/bodies.d.ts +24 -0
  9. package/src/api/bodies.js +24 -0
  10. package/src/api/errors.d.ts +1 -1
  11. package/src/api/group.d.ts +83 -0
  12. package/src/api/group.js +121 -0
  13. package/src/api/index.d.ts +5 -1
  14. package/src/api/index.js +2 -1
  15. package/src/api/mount.d.ts +10 -1
  16. package/src/api/mount.js +12 -3
  17. package/src/api/prepared.d.ts +10 -0
  18. package/src/api/prepared.js +5 -0
  19. package/src/api/scene.d.ts +121 -8
  20. package/src/api/scene.js +464 -57
  21. package/src/api/story.d.ts +63 -0
  22. package/src/api/story.js +52 -0
  23. package/src/api/sunOrbit.d.ts +14 -0
  24. package/src/api/sunOrbit.js +61 -0
  25. package/src/api/switches.d.ts +14 -0
  26. package/src/api/switches.js +19 -0
  27. package/src/api/time.d.ts +4 -0
  28. package/src/api/time.js +8 -0
  29. package/src/app/App.js +35 -17
  30. package/src/app/AstraeusScene.d.ts +1 -1
  31. package/src/app/DebugOverlay.d.ts +3 -52
  32. package/src/app/DebugOverlay.js +2 -29
  33. package/src/app/PanelLoadBoundary.d.ts +18 -0
  34. package/src/app/PanelLoadBoundary.js +17 -0
  35. package/src/app/debugReadout.d.ts +53 -0
  36. package/src/app/debugReadout.js +30 -0
  37. package/src/app/developerPanels.d.ts +6 -0
  38. package/src/app/developerPanels.js +11 -0
  39. package/src/app/displaySwitches.d.ts +54 -0
  40. package/src/app/displaySwitches.js +48 -0
  41. package/src/app/experienceDefinition.d.ts +5 -1
  42. package/src/app/listSwitch.d.ts +16 -0
  43. package/src/{experiences/showers/showerChoice.js → app/listSwitch.js} +1 -9
  44. package/src/app/metricReadouts.d.ts +1 -1
  45. package/src/app/metricReadouts.js +1 -1
  46. package/src/app/openClock.d.ts +7 -0
  47. package/src/app/openClock.js +14 -0
  48. package/src/app/sceneContentsHooks.d.ts +3 -3
  49. package/src/app/sceneDebug.d.ts +1 -1
  50. package/src/app/sceneDebug.js +1 -1
  51. package/src/app/skyModel.js +2 -0
  52. package/src/app/trackedMetrics.d.ts +53 -0
  53. package/src/{experiences/apollo11/spacecraftMetrics.js → app/trackedMetrics.js} +40 -56
  54. package/src/assets/licence.d.ts +1 -0
  55. package/src/core/bodies/index.d.ts +3 -0
  56. package/src/core/bodies/index.js +3 -1
  57. package/src/core/planetSeries.d.ts +2 -0
  58. package/src/core/planetSeries.js +4 -0
  59. package/src/core/provenance.d.ts +2 -1
  60. package/src/core/scalePolicy.d.ts +3 -0
  61. package/src/core/scalePolicy.js +2 -0
  62. package/src/core/state.d.ts +1 -0
  63. package/src/shell/AstraeusShell.d.ts +4 -1
  64. package/src/shell/AstraeusShell.js +7 -3
  65. package/src/shell/DisplaySwitches.d.ts +16 -0
  66. package/src/shell/DisplaySwitches.js +31 -0
  67. package/src/shell/TimelineBar.css +4 -0
  68. package/src/shell/TopBar.css +20 -0
  69. package/src/shell/TopBar.d.ts +4 -1
  70. package/src/shell/TopBar.js +3 -2
  71. package/src/shell/experience.d.ts +2 -0
  72. package/src/shell/phone.css +3 -0
  73. package/src/shell/topBarIcons.d.ts +1 -0
  74. package/src/shell/topBarIcons.js +1 -0
  75. package/src/synthetic/syntheticDefinition.js +3 -3
  76. package/src/experiences/apollo11/spacecraftMetrics.d.ts +0 -34
  77. package/src/experiences/showers/showerChoice.d.ts +0 -25
package/src/api/scene.js CHANGED
@@ -1,16 +1,25 @@
1
- import { createEvents } from "../core/events.js";
2
1
  import { createProvenance } from "../core/provenance.js";
3
2
  import { SampledTrajectory } from "../core/sampledTrajectory.js";
4
3
  import { readableScale, trueScale } from "../core/scalePolicy.js";
5
- import { loadPlanetSeries } from "../core/planetSeries.js";
6
- import { catalogue } from "../assets/catalogue.js";
4
+ import { loadPlanetSeries, planetSeriesLoaded } from "../core/planetSeries.js";
5
+ import { catalogue as builtInCatalogue, extendCatalogue, rootBodyId } from "../assets/catalogue.js";
6
+ import { buildElementsBody, ElementsBodyError, parseElementsBodyRecord } from "../core/elementsBody.js";
7
7
  import { createComposition, SIDEREAL_MONTH_MS } from "../assets/compositions.js";
8
8
  import { IO_PERIOD_DAYS } from "../core/bodies/io.js";
9
9
  import { bodyMetrics } from "../app/bodyMetrics.js";
10
10
  import { needsPlanetSeries } from "../app/planetNeeds.js";
11
+ import { catalogueItem } from "../app/catalogueItem.js";
12
+ import { createReadoutMetrics } from "../app/trackedMetrics.js";
13
+ import { circlesTheSun, sunOrbitIdOf, sunOrbitLayer } from "./sunOrbit.js";
11
14
  import { readyMade } from "./bodies.js";
12
15
  import { installData } from "./data.js";
16
+ import { planActivity, rateMetricOf } from "./activity.js";
17
+ import { buildGroupLayer, planGroup } from "./group.js";
13
18
  import { SceneError } from "./errors.js";
19
+ import { toUtcMs } from "./time.js";
20
+ import { switchesOf } from "./switches.js";
21
+ import { eventsOf, panelsOf, timelineOf } from "./story.js";
22
+ export { toUtcMs } from "./time.js";
14
23
  /** The orbits the engine can draw: the parent the line is measured from, and the span one lap covers. */
15
24
  const ORBITS = {
16
25
  moon: { parent: "earth", path: { spanMs: SIDEREAL_MONTH_MS } },
@@ -20,70 +29,178 @@ const DEFAULT_COLOR = "#ffd27a";
20
29
  const DAY_MS = 86_400_000;
21
30
  const PROVIDER_PATH_SAMPLES = 128;
22
31
  const SCALES = [trueScale, readableScale];
23
- /** Converts a moment to Unix milliseconds, or throws a `bad-time` SceneError naming it. */
24
- export function toUtcMs(time, what = "time") {
25
- const ms = time instanceof Date ? time.getTime() : typeof time === "number" ? time : Date.parse(time);
26
- if (!Number.isFinite(ms))
27
- throw new SceneError("bad-time", `${what} "${String(time)}" is not a valid moment; use an ISO text such as "1969-07-20T20:17:40Z", a Date or Unix milliseconds`);
28
- return ms;
29
- }
30
32
  /** The scene's camera: what it opens on. */
31
33
  export class SceneCamera {
32
34
  #target;
35
+ #following = false;
33
36
  #view = {};
37
+ #reach;
34
38
  #has;
35
39
  constructor(has) {
36
40
  this.#has = has;
37
41
  }
38
42
  /** Opens framed on a body or trajectory already added to the scene and already following it (the viewer's Follow button shows as pressed). */
39
43
  follow(id, view = {}) {
44
+ return this.#open("follow", id, view, true);
45
+ }
46
+ /** Opens framed on a body or trajectory already added to the scene, looking at it but not following it (the viewer's Focus button shows as pressed). The last of `follow` and `lookAt` wins. */
47
+ lookAt(id, view = {}) {
48
+ return this.#open("lookAt", id, view, false);
49
+ }
50
+ #open(call, id, view, following) {
40
51
  if (!this.#has(id))
41
- throw new SceneError("unknown-body", `camera.follow("${id}"): no body or trajectory with that id has been added to the scene`);
52
+ throw new SceneError("unknown-body", `camera.${call}("${id}"): no body or trajectory with that id has been added to the scene`);
53
+ if (view.up !== undefined && view.up !== "equatorial" && view.up !== "ecliptic")
54
+ throw new SceneError("bad-camera", `camera.${call}("${id}"): up "${String(view.up)}" must be "equatorial" or "ecliptic"`);
42
55
  this.#target = id;
56
+ this.#following = following;
43
57
  this.#view = view;
44
58
  return this;
45
59
  }
60
+ /**
61
+ * 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`.
62
+ * Labels reach as far: a body's label stays shown at any distance the camera can take. Without this call the camera frames the scene as before.
63
+ */
64
+ setReach(distance) {
65
+ if (!(typeof distance === "number" && Number.isFinite(distance) && distance > 0))
66
+ throw new SceneError("bad-camera", `camera.setReach: distance must be a finite number above 0, got ${String(distance)}`);
67
+ this.#reach = distance;
68
+ return this;
69
+ }
70
+ /** The farthest zoom-out set with `setReach`, if any. */
71
+ get reach() { return this.#reach; }
46
72
  get target() { return this.#target; }
73
+ /** Whether the opening view follows its target (`follow`) rather than only looking at it (`lookAt`). */
74
+ get following() { return this.#following; }
47
75
  get view() { return this.#view; }
48
76
  }
49
- /** A scene built with imperative calls. `mount(element, scene)` draws it; `toDefinition()` is what the app is given. */
77
+ /**
78
+ * A scene built with imperative calls. `mount(element, scene)` draws it; `toDefinition()` is what the app is given. Every method returns the scene, so calls chain.
79
+ * @example
80
+ * const scene = new Scene()
81
+ * .addBody(earth)
82
+ * .addBody(moon, { orbit: true })
83
+ * .setTime("2026-01-01T00:00:00Z");
84
+ * scene.camera.follow("moon", { distance: 60 });
85
+ */
50
86
  export class Scene {
87
+ /** The camera: `scene.camera.follow(id)` opens framed on a body or trajectory. */
51
88
  camera;
52
89
  #bodies = new Map();
53
90
  #tracked = new Map();
91
+ #groups = new Map();
92
+ #activities = new Map();
54
93
  #orbits = new Set();
94
+ #own = new Map();
95
+ #shape = new Map();
96
+ #catalogue = builtInCatalogue;
97
+ #notes = new Map();
98
+ #looks = new Map();
55
99
  #timeUtcMs;
56
100
  #scale = trueScale;
101
+ #scaleOnly = false;
102
+ #events = [];
103
+ #eventProvenance;
104
+ #panels;
105
+ #timeline;
106
+ #switches;
57
107
  constructor() {
58
- this.camera = new SceneCamera((id) => this.#bodies.has(id) || this.#tracked.has(id));
108
+ this.camera = new SceneCamera((id) => this.#taken(id));
59
109
  }
60
110
  /** Adds a catalogued body: a ready-made one (`earth`, `moon`, ...) or its id. The first body added is the scene's centre. `{ orbit: true }` also draws its orbit line. */
61
111
  addBody(body, options = {}) {
62
112
  const id = typeof body === "string" ? body : body.id;
63
- if (options.orbit === true && ORBITS[id] === undefined)
64
- throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the engine draws the orbit line of ${Object.keys(ORBITS).join(" and ")} only`);
65
- if (!catalogue.has(id))
66
- throw new SceneError("unknown-body", `addBody("${id}"): not a catalogued body (known: ${catalogue.ids().join(", ")})`);
67
- if (this.#bodies.has(id) || this.#tracked.has(id))
68
- throw new SceneError("duplicate-id", `addBody("${id}"): already in the scene`);
113
+ this.#register("addBody", id, typeof body === "string" ? readyMade(id) ?? { id, label: this.#catalogue.has(id) ? this.#catalogue.get(id).definition.label : id } : body, options);
114
+ return this;
115
+ }
116
+ /**
117
+ * Adds your own body that circles the Sun, from its published orbit elements and where they came from: a record with the id, label, elements at an epoch, the source
118
+ * (name, URL, solution, access date), a stated accuracy and optionally a radius and marker. Drawn as a marker on unperturbed two-body motion about the Sun; the provenance
119
+ * and the stated limits show on its info card. The options are `addBody`'s (`{ orbit: true }` draws its whole orbit from periapsis). A bad record throws `bad-element`
120
+ * naming the field; a repeated id throws `duplicate-id`.
121
+ * @example
122
+ * scene.addBody(sun).addBodyFromElements(record, { orbit: true, showLabel: false });
123
+ */
124
+ addBodyFromElements(record, options = {}) {
125
+ const parsed = parseRecord(record);
126
+ if (this.#taken(parsed.id) || this.#catalogue.has(parsed.id))
127
+ throw new SceneError("duplicate-id", `addBodyFromElements("${parsed.id}"): that id is already in the scene or the catalogue`);
128
+ const root = builtInCatalogue.get(rootBodyId()).definition;
129
+ const before = this.#catalogue;
130
+ this.#catalogue = extendCatalogue(before, [parsed]);
131
+ try {
132
+ this.#register("addBodyFromElements", parsed.id, { id: parsed.id, label: parsed.label }, options);
133
+ }
134
+ catch (error) {
135
+ this.#catalogue = before;
136
+ throw error;
137
+ }
138
+ this.#own.set(parsed.id, buildElementsBody(parsed, { id: root.id, gmKm3S2: root.gmKm3S2 }).sampling);
139
+ return this;
140
+ }
141
+ #register(call, id, ref, options) {
142
+ if (options.orbit === true && ORBITS[id] === undefined && !(circlesTheSun(this.#catalogue, id)))
143
+ 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`);
144
+ if (!this.#catalogue.has(id))
145
+ throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${this.#catalogue.ids().join(", ")})`);
146
+ if (this.#taken(id))
147
+ throw new SceneError("duplicate-id", `${call}("${id}"): already in the scene`);
148
+ checkBodyLook(id, options);
69
149
  if (options.orbit === true)
70
150
  this.#orbits.add(id);
71
- this.#bodies.set(id, typeof body === "string" ? readyMade(id) ?? { id, label: catalogue.get(id).definition.label } : body);
72
- return this;
151
+ if (options.color !== undefined || options.knownLimitations !== undefined)
152
+ this.#looks.set(id, { ...(options.color === undefined ? {} : { color: options.color }), ...(options.knownLimitations === undefined ? {} : { knownLimitations: options.knownLimitations }) });
153
+ if (options.enlarge !== undefined || options.showLabel !== undefined)
154
+ this.#shape.set(id, { ...(options.enlarge === undefined ? {} : { enlarge: options.enlarge }), ...(options.showLabel === undefined ? {} : { showLabel: options.showLabel }) });
155
+ if (options.description !== undefined)
156
+ this.#notes.set(id, options.description);
157
+ this.#bodies.set(id, ref);
73
158
  }
74
159
  /** Adds a path to follow and draw, from sampled states or a provider with `stateAt(time)`. */
75
160
  addTrajectory(input) {
76
161
  const id = input.id;
77
162
  if (typeof id !== "string" || id === "")
78
163
  throw new SceneError("bad-trajectory", "addTrajectory: the trajectory needs a non-empty id");
79
- if (this.#bodies.has(id) || this.#tracked.has(id))
164
+ if (this.#taken(id))
80
165
  throw new SceneError("duplicate-id", `addTrajectory("${id}"): that id is already in the scene`);
81
166
  const center = input.center ?? "earth";
82
- if (!catalogue.has(center))
167
+ if (!builtInCatalogue.has(center))
83
168
  throw new SceneError("unknown-body", `addTrajectory("${id}"): centre "${center}" is not a catalogued body`);
84
169
  const provenance = input.provenance ?? createProvenance({ sourceType: "illustrative", sources: ["Supplied by the caller"], accuracy: "As supplied; the engine makes no claim.", notes: "Positions were passed to addTrajectory." });
85
170
  const common = { id, label: input.label ?? id, color: input.color ?? DEFAULT_COLOR, anchorTimesUtcMs: [], provenance };
86
- this.#tracked.set(id, { center, body: "samples" in input ? sampledBody(common, input, center) : providerBody(common, input) });
171
+ const readouts = readoutsOf(id, input.readouts);
172
+ const body = "samples" in input ? sampledBody(common, input, center) : providerBody(common, input);
173
+ this.#tracked.set(id, { center, body: withAnchors(body, input.anchors), readouts, ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
174
+ return this;
175
+ }
176
+ /** Whether a body, path or group already has this id. */
177
+ #taken(id) {
178
+ return this.#bodies.has(id) || this.#tracked.has(id) || this.#groups.has(id);
179
+ }
180
+ /**
181
+ * Adds a group of listed orbits drawn as one set of dots (one colour and dot size, one menu item and info card), with an optional clump near a body.
182
+ * The orbits circle the scene's centre unless `center` names another body. A repeated id throws `duplicate-id`; an empty list, a bad orbit, colour, clump or centre throws `bad-group`.
183
+ * @example
184
+ * scene.addGroup({ id: "ring", orbits: [{ id: "a", semiMajorAxisKm: 90_000, eccentricity: 0.1, inclinationDeg: 5, raanDeg: 40, argumentOfPeriapsisDeg: 70 }], color: "#9de3a8" });
185
+ */
186
+ addGroup(input) {
187
+ const plan = planGroup(input, this.#catalogue);
188
+ if (this.#taken(plan.id))
189
+ throw new SceneError("duplicate-id", `addGroup("${plan.id}"): that id is already in the scene`);
190
+ this.#groups.set(plan.id, plan);
191
+ return this;
192
+ }
193
+ /**
194
+ * Adds a period of activity to the timeline: a rate curve the timeline glows by, its peak mark, and where each stretch comes from. A group's `{ kind: "rate" }` readout shows its live rate
195
+ * (unavailable outside the period) against the peak. Without `setTimeline`, the timeline spans the activities. A repeated id, or a bad curve, peak, source or moment, throws `bad-activity`.
196
+ * @example
197
+ * scene.addActivity({ id: "burst", label: "Burst", unit: "per hour", start: "2026-08-01", end: "2026-08-20", peak: "2026-08-12", samples: [{ time: "2026-08-01", value: 2 }, { time: "2026-08-12", value: 100 }, { time: "2026-08-20", value: 5 }] });
198
+ */
199
+ addActivity(input) {
200
+ const plan = planActivity(input);
201
+ if (this.#activities.has(plan.window.id))
202
+ throw new SceneError("bad-activity", `addActivity("${plan.window.id}"): an activity with that id is already in the scene`);
203
+ this.#activities.set(plan.window.id, plan);
87
204
  return this;
88
205
  }
89
206
  /** Sets the moment the scene opens at. */
@@ -91,13 +208,164 @@ export class Scene {
91
208
  this.#timeUtcMs = toUtcMs(time, "setTime");
92
209
  return this;
93
210
  }
94
- /** Chooses the opening scale: `trueScale` or `readableScale`; the viewer can switch to the other. */
95
- setScale(scale) {
211
+ /** Chooses the opening scale: `trueScale` or `readableScale`; the viewer can switch to the other (in a Sun-centred scene with an enlarged body, to the \"solar-system\" scale instead of the readable one), unless `{ only: true }` offers this scale alone. */
212
+ setScale(scale, options = {}) {
96
213
  if (!SCALES.some((known) => known.id === scale?.id))
97
214
  throw new SceneError("bad-scale", `setScale: "${String(scale?.id)}" is not a scale; use trueScale or readableScale`);
98
215
  this.#scale = scale;
216
+ this.#scaleOnly = options.only === true;
217
+ return this;
218
+ }
219
+ /** Adds timed events to the timeline, each with an id, a label and a moment; `provenance` says where the times come from and is shown with every event. May be called more than once. */
220
+ addEvents(events, options = {}) {
221
+ this.#events = eventsOf(events, this.#events);
222
+ if (options.provenance !== undefined)
223
+ this.#eventProvenance = options.provenance;
224
+ return this;
225
+ }
226
+ /** Adds story panels that open as playback reaches them. Their times may name events (`addEvents`) and path anchors, and `object` a body or path; these are checked when the scene is built (`mount`), and a mistake throws `bad-panels` naming the panel and field. */
227
+ addStoryPanels(panels) {
228
+ this.#panels = panels;
229
+ return this;
230
+ }
231
+ /** 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`), 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. */
232
+ setTimeline(timeline) {
233
+ this.#timeline = timelineOf(timeline);
99
234
  return this;
100
235
  }
236
+ /**
237
+ * Places the display switches: for each of `orbitLines` (orbit ring, trailing arc and moon orbits), `labels` (body and anchor labels) and `milkyWay` (the sky picture), `place` is
238
+ * `"top-bar"` (a button in the bar), `"panel"` (a row in one switch panel opened from the bar) or `"developer"` (only in the Developer drawer, where every switch stays), and `on` is
239
+ * whether it starts on (default on). A switch the scene has nothing for (orbit lines with no orbit drawn) shows nowhere. May be called more than once; later calls replace the same switch.
240
+ * A bad switch name, place or `on` throws `bad-switch`.
241
+ * @example
242
+ * scene.setSwitches({ orbitLines: { place: "top-bar" }, labels: { place: "panel", on: false }, milkyWay: { place: "developer", on: false } });
243
+ */
244
+ setSwitches(switches) {
245
+ this.#switches = switchesOf(switches, this.#switches);
246
+ return this;
247
+ }
248
+ /** The state of a trajectory added with `addTrajectory` at a moment, about its centre body (position in km, velocity in km/s): for figures a story quotes, such as a peak speed. Throws `unknown-body` for any other id and `bad-time` for a moment outside the path. */
249
+ stateOf(id, time) {
250
+ const entry = this.#tracked.get(id);
251
+ if (entry === undefined)
252
+ throw new SceneError("unknown-body", `stateOf("${id}"): no trajectory with that id has been added to the scene`);
253
+ const timeUtcMs = toUtcMs(time, `stateOf("${id}") time`);
254
+ const { startUtcMs, endUtcMs } = entry.body.trajectory.bounds;
255
+ if (timeUtcMs < startUtcMs || timeUtcMs > endUtcMs)
256
+ throw new SceneError("bad-time", `stateOf("${id}"): ${new Date(timeUtcMs).toISOString()} is outside the path (${new Date(startUtcMs).toISOString()} to ${new Date(endUtcMs).toISOString()})`);
257
+ return entry.body.trajectory.stateAt(timeUtcMs, entry.center);
258
+ }
259
+ /** The story panels, resolved against this scene's events, anchors, objects and timeline span. */
260
+ #storyPanels(window) {
261
+ if (this.#panels === undefined)
262
+ return undefined;
263
+ const anchors = new Map();
264
+ for (const { body } of this.#tracked.values())
265
+ body.anchorLabels?.forEach((label, index) => { if (!anchors.has(label))
266
+ anchors.set(label, body.anchorTimesUtcMs[index]); });
267
+ return panelsOf(this.#panels, { events: this.#events, anchors, objectIds: [...this.#bodies.keys(), ...this.#tracked.keys(), ...this.#groups.keys()], window });
268
+ }
269
+ /** Checks the groups against the finished scene: each circles its centre (default the scene's first body), which and whose clump body the scene must hold. */
270
+ #checkGroups(ids) {
271
+ for (const plan of this.#groups.values()) {
272
+ const center = plan.input.center ?? ids[0];
273
+ const clump = plan.input.clump;
274
+ if (!ids.includes(center))
275
+ throw new SceneError("bad-group", `addGroup("${plan.id}"): the orbits circle "${center}", which has not been added to the scene`);
276
+ if (clump !== undefined && !ids.includes(clump.near))
277
+ throw new SceneError("bad-group", `addGroup("${plan.id}"): clump.near "${clump.near}" has not been added to the scene`);
278
+ if (clump !== undefined && clump.near === center)
279
+ throw new SceneError("bad-group", `addGroup("${plan.id}"): the clump cannot be near the body the orbits circle ("${center}")`);
280
+ }
281
+ }
282
+ /** The draw layers of the groups chosen by `which` (a clump near a planet reads its position, so needs the planet series). */
283
+ #groupLayers(ids, window, openUtcMs, which) {
284
+ return [...this.#groups.values()].filter(which).map((plan) => buildGroupLayer(plan, this.#catalogue, plan.input.center ?? ids[0], openUtcMs, window));
285
+ }
286
+ /** The Sun-orbit lines that can be drawn now: all of them when the planet series are loaded, else none (they are drawn in `prepare`). */
287
+ #earlySunPaths(orbitIds, openUtcMs) {
288
+ return planetSeriesLoaded() ? orbitIds.map((id) => this.#sunPath(id, openUtcMs)) : [];
289
+ }
290
+ /** Whether a Sun-centred scene enlarges a body, which the viewer's solar-system scale draws. */
291
+ #enlargedInSun(sunCentred) {
292
+ return sunCentred && [...this.#shape.values()].some((shape) => shape.enlarge !== undefined);
293
+ }
294
+ /** The activity windows, when any were added. */
295
+ #windowsEntry() {
296
+ return this.#activities.size === 0 ? {} : { windows: [...this.#activities.values()].map((activity) => activity.window) };
297
+ }
298
+ /** The bars of a group's info card at a moment. */
299
+ #groupMetrics(id, timeUtcMs) {
300
+ return (this.#groups.get(id)?.input.readouts ?? []).map((spec) => rateMetricOf(id, this.#activities.get(spec.activity ?? this.#firstActivity()), timeUtcMs));
301
+ }
302
+ #firstActivity() {
303
+ return this.#activities.keys().next().value;
304
+ }
305
+ /** A group's rate readout names an activity the scene holds. */
306
+ #checkGroupReadouts() {
307
+ for (const { id, input } of this.#groups.values()) {
308
+ for (const spec of input.readouts ?? []) {
309
+ const named = spec.activity ?? (this.#activities.size > 0 ? this.#firstActivity() : undefined);
310
+ if (named === undefined || !this.#activities.has(named))
311
+ throw new SceneError("bad-readout", `addGroup("${id}"): readout rate ${named === undefined ? "needs an activity (addActivity)" : `names activity "${named}", which has not been added to the scene`}`);
312
+ }
313
+ }
314
+ }
315
+ /** Throws `missing-data` naming the bodies whose data package was not passed. */
316
+ #checkData(data) {
317
+ const missing = this.missingData(data);
318
+ if (missing.length === 0)
319
+ return;
320
+ const names = [...this.#bodies.values()].filter((body) => body.requires !== undefined && missing.includes(body.requires)).map((body) => body.id);
321
+ throw new SceneError("missing-data", `${names.join(", ")} needs the ${missing.join(", ")} package: install it and pass it as mount(element, scene, { data: [...] })`);
322
+ }
323
+ /** The engine's own orbit loops (the Moon's and Io's) the scene asked for. */
324
+ #moonPaths() {
325
+ return [...this.#orbits].filter((id) => ORBITS[id] !== undefined).map((id) => {
326
+ const orbit = ORBITS[id];
327
+ if (!this.#bodies.has(orbit.parent))
328
+ throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about ${orbit.parent}, which has not been added to the scene`);
329
+ return { body: id, ...orbit.path };
330
+ });
331
+ }
332
+ /** Whether the scene is centred on the Sun; such a scene cannot hold a tracked path. */
333
+ #checkSunCentred(ids) {
334
+ const sunCentred = ids[0] === rootBodyId(this.#catalogue);
335
+ if (sunCentred && this.#tracked.size > 0)
336
+ throw new SceneError("bad-trajectory", `addTrajectory("${[...this.#tracked.keys()][0]}"): a scene centred on the Sun cannot hold a tracked path yet; centre the scene on Earth or another body`);
337
+ return sunCentred;
338
+ }
339
+ /** The shell item of a body: from the catalogue, with the scene's own words, look and label setting. A Sun-centred scene sets no label reach. */
340
+ #bodyObject(body, ids, sunCentred) {
341
+ const own = { labelPriority: 100 - ids.indexOf(body.id), ...(sunCentred ? {} : { labelMaxDistance: Math.max(500, this.camera.reach ?? 0) }), ...(this.#shape.get(body.id)?.showLabel === undefined ? {} : { showLabel: this.#shape.get(body.id).showLabel }), ...(this.#notes.has(body.id) ? { description: this.#notes.get(body.id) } : {}), ...this.#looks.get(body.id) };
342
+ return { ...catalogueItem(body.id, own, this.#catalogue), label: body.label };
343
+ }
344
+ /** The bodies that asked for a Sun-orbit line, checked: the Sun must be in the scene and the line's id free. */
345
+ #sunOrbitIds(ids) {
346
+ return [...this.#orbits].filter((id) => ORBITS[id] === undefined).map((id) => {
347
+ if (!ids.includes(rootBodyId(this.#catalogue)))
348
+ throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about the Sun, which has not been added to the scene`);
349
+ if (this.#taken(sunOrbitIdOf(id)))
350
+ throw new SceneError("duplicate-id", `addBody("${id}", { orbit: true }): the orbit line's id "${sunOrbitIdOf(id)}" is already in the scene`);
351
+ return id;
352
+ });
353
+ }
354
+ /** 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. */
355
+ #sunPath(id, openUtcMs) {
356
+ const layer = sunOrbitLayer(this.#catalogue, id, openUtcMs, this.#looks.get(id)?.color ?? "", this.#own.get(id));
357
+ if (layer === undefined)
358
+ 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`);
359
+ return layer;
360
+ }
361
+ /** A readout names a body the scene must hold, so it can be measured against. */
362
+ #checkReadouts(entry, ids) {
363
+ for (const spec of entry.readouts) {
364
+ const named = readoutBody(spec);
365
+ if (named !== undefined && !ids.includes(named))
366
+ throw new SceneError("bad-readout", `addTrajectory("${entry.body.id}"): readout ${spec.kind} names "${named}", which has not been added to the scene`);
367
+ }
368
+ }
101
369
  /** The data packages the added bodies need that `data` does not provide. */
102
370
  missingData(data = []) {
103
371
  const have = new Set(data.flatMap((source) => source.provides));
@@ -108,57 +376,137 @@ export class Scene {
108
376
  toDefinition(data = []) {
109
377
  if (this.#bodies.size === 0)
110
378
  throw new SceneError("empty-scene", "the scene has no bodies; call addBody before mount");
111
- const missing = this.missingData(data);
112
- if (missing.length > 0) {
113
- const names = [...this.#bodies.values()].filter((body) => body.requires !== undefined && missing.includes(body.requires)).map((body) => body.id);
114
- throw new SceneError("missing-data", `${names.join(", ")} needs the ${missing.join(", ")} package: install it and pass it as mount(element, scene, { data: [...] })`);
115
- }
379
+ this.#checkData(data);
380
+ this.#checkGroupReadouts();
116
381
  const ids = [...this.#bodies.keys()];
117
- const paths = [...this.#orbits].map((id) => {
118
- const orbit = ORBITS[id];
119
- if (!this.#bodies.has(orbit.parent))
120
- throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about ${orbit.parent}, which has not been added to the scene`);
121
- return { body: id, ...orbit.path };
122
- });
382
+ const paths = this.#moonPaths();
383
+ const sunCentred = this.#checkSunCentred(ids);
384
+ for (const entry of this.#tracked.values())
385
+ this.#checkReadouts(entry, ids);
123
386
  const tracked = [...this.#tracked.values()].map((entry) => entry.body);
124
- const window = windowOf(tracked, this.#timeUtcMs);
125
- const startUtcMs = this.#timeUtcMs ?? window.startUtcMs;
387
+ const timeline = this.#timeline;
388
+ const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
389
+ const sunOrbitIds = this.#sunOrbitIds(ids);
390
+ // 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.
391
+ const sunPaths = this.#earlySunPaths(sunOrbitIds, startUtcMs);
126
392
  const target = this.camera.target;
127
393
  const view = this.camera.view;
394
+ const storyPanels = this.#storyPanels(window);
395
+ this.#checkGroups(ids);
396
+ // 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).
397
+ const seriesIn = planetSeriesLoaded();
398
+ const late = (plan) => !seriesIn && plan.input.clump !== undefined;
399
+ const layers = [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))];
400
+ const labelled = [...this.#bodies.values(), ...tracked, ...[...this.#groups.values()]].map(({ id, label }) => ({ id, label }));
128
401
  const definition = {
129
402
  experience: {
130
403
  objects: [
131
- ...[...this.#bodies.values()].map((body) => ({ id: body.id, label: body.label, labelPriority: 100 - ids.indexOf(body.id), labelMaxDistance: 500 })),
132
- ...tracked.map((body) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, labelMaxDistance: 4, provenance: body.provenance })),
133
- ],
134
- cameraPresets: [
135
- { id: "overview", label: "Overview", request: { kind: "overview" } },
136
- ...(target === undefined ? [] : [{ id: "focus-target", label: "Focus", request: { kind: "focus", target } }, { id: "follow-target", label: "Follow", request: { kind: "follow", target } }]),
404
+ ...[...this.#bodies.values()].map((body) => this.#bodyObject(body, ids, sunCentred)),
405
+ ...[...this.#tracked.values()].map(({ body, description, knownLimitations }) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, labelMaxDistance: 4, provenance: body.provenance, ...(description === undefined ? {} : { description }), ...(knownLimitations === undefined ? {} : { knownLimitations }) })),
137
406
  ],
138
- ...(target === undefined ? {} : { startCameraPresetId: "follow-target" }),
139
- events: createEvents([]),
407
+ cameraPresets: cameraPresetsOf(labelled),
408
+ ...(target === undefined ? {} : { startCameraPresetId: `${this.camera.following ? "follow" : "focus"}-${target}` }),
409
+ events: this.#events,
410
+ ...(this.#eventProvenance === undefined ? {} : { eventProvenance: this.#eventProvenance }),
411
+ ...(storyPanels === undefined ? {} : { storyPanels }),
412
+ ...(timeline?.none === true ? { hideTimeline: true } : {}),
140
413
  window,
141
- rates: [60, 3_600, DAY_MS / 1000],
414
+ ...this.#windowsEntry(),
415
+ rates: timeline?.rates ?? [60, 3_600, DAY_MS / 1000],
142
416
  },
143
- clock: { startUtcMs, rate: 60 },
144
- sceneLayers: ["tracked-bodies"],
145
- composition: createComposition(catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
146
- scaleChoices: [this.#scale.id, ...SCALES.filter((scale) => scale.id !== this.#scale.id).map((scale) => scale.id)],
417
+ clock: clockOf(timeline, startUtcMs),
418
+ ...groupLayersEntry(layers, this.#groups.size > 0, sunOrbitIds.length > 0),
419
+ ...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
420
+ ...(this.#own.size === 0 ? {} : { catalogue: this.#catalogue }),
421
+ ...visualOverridesEntry(this.#shape),
422
+ composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
423
+ scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
424
+ ...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
425
+ ...viewEntries(timeline, this.camera),
147
426
  ...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
148
427
  trackedBodies: tracked,
149
428
  createMetrics: ({ resolver }) => {
150
429
  const catalogued = bodyMetrics(resolver, ids, ["distance"]);
151
- return (objectId, timeUtcMs) => (this.#tracked.has(objectId) ? [] : catalogued(objectId, timeUtcMs));
430
+ const readouts = createReadoutMetrics([...this.#tracked.values()].map(({ body, readouts: specs }) => ({ body, readouts: specs })), resolver);
431
+ return (objectId, timeUtcMs) => (this.#groups.has(objectId) ? this.#groupMetrics(objectId, timeUtcMs) : this.#tracked.has(objectId) ? readouts(objectId, timeUtcMs) : catalogued(objectId, timeUtcMs));
152
432
  },
153
433
  prepare: async () => {
154
- if (needsPlanetSeries(definition))
434
+ if (needsPlanetSeries(definition) || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
155
435
  await loadPlanetSeries();
436
+ if (this.#groups.size > layers.length)
437
+ layers.push(...this.#groupLayers(ids, window, startUtcMs, late));
438
+ if (sunPaths.length < sunOrbitIds.length)
439
+ sunPaths.push(...sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs)));
156
440
  await installData(data, ids, window);
157
441
  },
158
442
  };
159
443
  return definition;
160
444
  }
161
445
  }
446
+ /** The playback and camera settings the scene asked for: looping, the farthest zoom-out and the ecliptic up. */
447
+ function viewEntries(timeline, camera) {
448
+ const { reach, view, target } = camera;
449
+ return {
450
+ ...(timeline?.loop === true ? { loop: true } : {}),
451
+ ...(reach === undefined ? {} : { camera: { maxFocusDistance: reach, far: reach * 2.5 } }),
452
+ ...(view.up === undefined || target === undefined ? {} : { viewUp: view.up }),
453
+ };
454
+ }
455
+ /** The scene's layers: the points layer and the groups only when a group was added. */
456
+ function groupLayersEntry(layers, hasGroups, sunCentred) {
457
+ const sceneLayers = ["tracked-bodies", ...(hasGroups ? ["points"] : []), ...(sunCentred ? ["sun-centred"] : [])];
458
+ return hasGroups ? { sceneLayers, groups: layers } : { sceneLayers };
459
+ }
460
+ /** The enlargements the scene asked for, as the engine's per-body overrides. */
461
+ function visualOverridesEntry(shape) {
462
+ const overrides = {};
463
+ for (const [id, { enlarge }] of shape)
464
+ if (enlarge !== undefined)
465
+ overrides[id] = { exaggeration: enlarge };
466
+ return Object.keys(overrides).length === 0 ? {} : { visualOverrides: overrides };
467
+ }
468
+ /** Parses an elements record, naming the field a mistake is in. */
469
+ function parseRecord(record) {
470
+ try {
471
+ return parseElementsBodyRecord(record, "addBodyFromElements");
472
+ }
473
+ catch (error) {
474
+ if (error instanceof ElementsBodyError)
475
+ throw new SceneError("bad-element", error.message);
476
+ throw error;
477
+ }
478
+ }
479
+ /** The camera menu is automatic: Overview, and Focus and Follow for every body and path. */
480
+ function cameraPresetsOf(objects) {
481
+ return [
482
+ { id: "overview", label: "Overview", request: { kind: "overview" } },
483
+ ...objects.flatMap(({ id, label }) => [
484
+ { id: `focus-${id}`, label: `Focus ${label}`, request: { kind: "focus", target: id } },
485
+ { id: `follow-${id}`, label: `Follow ${label}`, request: { kind: "follow", target: id } },
486
+ ]),
487
+ ];
488
+ }
489
+ /** The timeline span and the moment the clock opens at; a moment outside a span the caller set is a `bad-timeline`. */
490
+ function spanOf(timeline, timeUtcMs, tracked) {
491
+ const setTime = (timeline?.none === true ? timeline.atUtcMs : undefined) ?? timeUtcMs;
492
+ const window = timeline?.window ?? windowOf(tracked, setTime);
493
+ if (timeline?.window !== undefined && setTime !== undefined && (setTime < window.startUtcMs || setTime > window.endUtcMs)) {
494
+ throw new SceneError("bad-timeline", `setTime ${new Date(setTime).toISOString()} is outside the timeline (${new Date(window.startUtcMs).toISOString()} to ${new Date(window.endUtcMs).toISOString()})`);
495
+ }
496
+ return { window, startUtcMs: setTime ?? window.startUtcMs };
497
+ }
498
+ /** The clock's opening: 60 times real time unless set; with no timeline and no rate, frozen. */
499
+ function clockOf(timeline, startUtcMs) {
500
+ return { startUtcMs, rate: timeline?.rate ?? 60, ...(timeline?.none === true && timeline.rate === undefined ? { playing: false } : {}) };
501
+ }
502
+ /**
503
+ * The scale choices offered: the opening one first, then the other unless the caller offered one alone. A Sun-centred scene with an enlarged body (`addBody(x, { enlarge })`)
504
+ * offers the viewer's "solar-system" scale (true distances, the named bodies enlarged) in place of the readable scale it would offer second, since the readable scale does not enlarge.
505
+ */
506
+ function scaleChoicesOf(scale, only, enlarged) {
507
+ const second = SCALES.filter((other) => other.id !== scale.id).map((other) => (enlarged && other.id === readableScale.id ? "solar-system" : other.id));
508
+ return only ? [scale.id] : [scale.id, ...second];
509
+ }
162
510
  function sampledBody(common, input, center) {
163
511
  const samples = input.samples.map((sample, index) => ({ ...sample, timeUtcMs: toUtcMs(sample.time, `addTrajectory("${common.id}") sample ${index} time`) }));
164
512
  try {
@@ -181,14 +529,73 @@ function providerBody(common, input) {
181
529
  const step = (bounds.endUtcMs - bounds.startUtcMs) / (PROVIDER_PATH_SAMPLES - 1);
182
530
  return { ...common, trajectory, pathTimesUtcMs: Array.from({ length: PROVIDER_PATH_SAMPLES }, (_, index) => bounds.startUtcMs + index * step) };
183
531
  }
184
- /** The timeline span: the trajectories' union, else a month about the chosen time (or about now). */
532
+ /** The timeline span: the union of the trajectories' and activities' spans, else a month about the chosen time (or about now). */
185
533
  function windowOf(tracked, timeUtcMs) {
186
534
  if (tracked.length > 0) {
187
- const start = Math.min(...tracked.map((body) => body.trajectory.bounds.startUtcMs));
188
- const end = Math.max(...tracked.map((body) => body.trajectory.bounds.endUtcMs));
535
+ const start = Math.min(...tracked.map((bounds) => bounds.startUtcMs));
536
+ const end = Math.max(...tracked.map((bounds) => bounds.endUtcMs));
189
537
  if (timeUtcMs === undefined || (timeUtcMs >= start && timeUtcMs <= end))
190
538
  return { startUtcMs: start, endUtcMs: end };
191
539
  }
192
540
  const centre = timeUtcMs ?? Date.now();
193
541
  return { startUtcMs: centre - 15 * DAY_MS, endUtcMs: centre + 15 * DAY_MS };
194
542
  }
543
+ /** Checks the colour and known limits given to `addBody`. */
544
+ function checkBodyLook(id, options) {
545
+ if (options.enlarge !== undefined && !(typeof options.enlarge === "number" && Number.isFinite(options.enlarge) && options.enlarge >= 1))
546
+ throw new SceneError("bad-body", `addBody("${id}"): enlarge ${String(options.enlarge)} must be a number of at least 1`);
547
+ if (options.showLabel !== undefined && typeof options.showLabel !== "boolean")
548
+ throw new SceneError("bad-body", `addBody("${id}"): showLabel must be true or false`);
549
+ if (options.color !== undefined && !(typeof options.color === "string" && /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(options.color)))
550
+ throw new SceneError("bad-body", `addBody("${id}"): color "${String(options.color)}" is not a hex colour such as "#9fd8ff"`);
551
+ const limits = options.knownLimitations;
552
+ if (limits !== undefined && !(Array.isArray(limits) && limits.every((line) => typeof line === "string" && line !== "")))
553
+ throw new SceneError("bad-body", `addBody("${id}"): knownLimitations must be a list of non-empty texts`);
554
+ }
555
+ const READOUT_KINDS = ["range", "speed", "distance", "altitude"];
556
+ /** The body a readout names, if any. */
557
+ function readoutBody(spec) {
558
+ return spec.kind === "range" ? spec.marker : spec.kind === "distance" ? spec.to : spec.kind === "altitude" ? spec.above : undefined;
559
+ }
560
+ /** Checks each readout's kind and the catalogued body it names; whether the scene holds that body is checked when the definition is built. */
561
+ function readoutsOf(id, readouts = []) {
562
+ if (!Array.isArray(readouts))
563
+ throw new SceneError("bad-readout", `addTrajectory("${id}"): readouts must be a list`);
564
+ for (const spec of readouts) {
565
+ if (!READOUT_KINDS.includes(spec?.kind))
566
+ throw new SceneError("bad-readout", `addTrajectory("${id}"): readout kind "${String(spec?.kind)}" is not one of ${READOUT_KINDS.join(", ")}`);
567
+ const named = readoutBody(spec);
568
+ if (spec.kind !== "range" && spec.kind !== "speed" && named === undefined)
569
+ throw new SceneError("bad-readout", `addTrajectory("${id}"): readout ${spec.kind} needs ${spec.kind === "distance" ? "`to`" : "`above`"}, the body to measure against`);
570
+ if (named !== undefined && !builtInCatalogue.has(named))
571
+ throw new SceneError("bad-readout", `addTrajectory("${id}"): readout ${spec.kind} names "${named}", which is not a catalogued body`);
572
+ }
573
+ return readouts;
574
+ }
575
+ /** The body with its anchors: sorted by time, each labelled with its id. Every anchor needs a distinct id and a moment inside the path. */
576
+ function withAnchors(body, anchors = []) {
577
+ if (!Array.isArray(anchors))
578
+ throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): anchors must be a list`);
579
+ const { startUtcMs, endUtcMs } = body.trajectory.bounds;
580
+ const seen = new Set();
581
+ const placed = anchors.map((anchor) => {
582
+ if (typeof anchor?.id !== "string" || anchor.id === "")
583
+ throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): every anchor needs a non-empty id`);
584
+ if (seen.has(anchor.id))
585
+ throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): anchor "${anchor.id}" appears twice`);
586
+ seen.add(anchor.id);
587
+ const timeUtcMs = anchorTime(body.id, anchor);
588
+ if (timeUtcMs < startUtcMs || timeUtcMs > endUtcMs)
589
+ throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): anchor "${anchor.id}" is outside the path (${new Date(startUtcMs).toISOString()} to ${new Date(endUtcMs).toISOString()})`);
590
+ return { id: anchor.id, timeUtcMs };
591
+ }).sort((a, b) => a.timeUtcMs - b.timeUtcMs);
592
+ return placed.length === 0 ? body : { ...body, anchorTimesUtcMs: placed.map((anchor) => anchor.timeUtcMs), anchorLabels: placed.map((anchor) => anchor.id) };
593
+ }
594
+ function anchorTime(path, anchor) {
595
+ try {
596
+ return toUtcMs(anchor.time);
597
+ }
598
+ catch {
599
+ throw new SceneError("bad-anchor", `addTrajectory("${path}"): anchor "${anchor.id}" has a time "${String(anchor.time)}" that is not a valid moment`);
600
+ }
601
+ }