astraeus 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +76 -7
- package/package.json +10 -6
- package/src/api/AstraeusScene.d.ts +27 -0
- package/src/api/AstraeusScene.js +38 -0
- package/src/api/AstraeusScene.node.js +37 -0
- package/src/api/activity.d.ts +50 -0
- package/src/api/activity.js +62 -0
- package/src/api/bodies.d.ts +24 -0
- package/src/api/bodies.js +24 -0
- package/src/api/errors.d.ts +1 -1
- package/src/api/group.d.ts +89 -0
- package/src/api/group.js +121 -0
- package/src/api/index.d.ts +6 -1
- package/src/api/index.js +3 -1
- package/src/api/index.node.js +8 -0
- package/src/api/mount.d.ts +10 -1
- package/src/api/mount.js +15 -4
- package/src/api/mount.node.js +36 -0
- package/src/api/prepared.d.ts +10 -0
- package/src/api/prepared.js +5 -0
- package/src/api/scene.d.ts +148 -9
- package/src/api/scene.js +563 -59
- package/src/api/story.d.ts +69 -0
- package/src/api/story.js +63 -0
- package/src/api/sunOrbit.d.ts +20 -0
- package/src/api/sunOrbit.js +85 -0
- package/src/api/switches.d.ts +14 -0
- package/src/api/switches.js +19 -0
- package/src/api/time.d.ts +4 -0
- package/src/api/time.js +8 -0
- package/src/app/App.d.ts +6 -2
- package/src/app/App.js +43 -21
- package/src/app/App.node.js +401 -0
- package/src/app/AstraeusScene.d.ts +1 -1
- package/src/app/DebugOverlay.d.ts +3 -52
- package/src/app/DebugOverlay.js +2 -29
- package/src/app/PanelLoadBoundary.d.ts +19 -0
- package/src/app/PanelLoadBoundary.js +17 -0
- package/src/app/SkyView.d.ts +3 -3
- package/src/app/SkyView.js +19 -10
- package/src/app/debugReadout.d.ts +53 -0
- package/src/app/debugReadout.js +30 -0
- package/src/app/developerPanels.d.ts +6 -0
- package/src/app/developerPanels.js +11 -0
- package/src/app/displaySwitches.d.ts +54 -0
- package/src/app/displaySwitches.js +48 -0
- package/src/app/experienceDefinition.d.ts +13 -1
- package/src/app/listSwitch.d.ts +16 -0
- package/src/{experiences/showers/showerChoice.js → app/listSwitch.js} +1 -9
- package/src/app/metricReadouts.d.ts +1 -1
- package/src/app/metricReadouts.js +1 -1
- package/src/app/openClock.d.ts +7 -0
- package/src/app/openClock.js +14 -0
- package/src/app/sceneContentsHooks.d.ts +3 -3
- package/src/app/sceneContentsHooks.js +2 -2
- package/src/app/sceneDebug.d.ts +1 -1
- package/src/app/sceneDebug.js +1 -1
- package/src/app/sceneFrame.js +4 -3
- package/src/app/sceneFraming.d.ts +13 -0
- package/src/app/sceneFraming.js +22 -0
- package/src/app/skyModel.js +3 -1
- package/src/app/trackedMetrics.d.ts +53 -0
- package/src/{experiences/apollo11/spacecraftMetrics.js → app/trackedMetrics.js} +40 -56
- package/src/assets/licence.d.ts +1 -0
- package/src/assets/pictures.d.ts +1 -1
- package/src/assets/sky.d.ts +4 -4
- package/src/assets/sky.js +12 -13
- package/src/core/bodies/index.d.ts +3 -0
- package/src/core/bodies/index.js +3 -1
- package/src/core/bodies/io.js +1 -1
- package/src/core/bodies/jupiterData.js +2 -2
- package/src/core/bodies/jupiterMoons.js +8 -12
- package/src/core/bodies/moon.d.ts +8 -0
- package/src/core/bodies/moon.js +28 -5
- package/src/core/bodies/outerPlanetData.js +7 -7
- package/src/core/bodies/planetMoons.js +18 -27
- package/src/core/bodies/swiftTuttle.js +2 -0
- package/src/core/elementsBody.d.ts +2 -0
- package/src/core/elementsBody.js +3 -0
- package/src/core/moonTrajectory.js +3 -5
- package/src/core/planetModels.js +1 -1
- package/src/core/planetSeries.d.ts +2 -0
- package/src/core/planetSeries.js +4 -0
- package/src/core/provenance.d.ts +7 -2
- package/src/core/provenance.js +3 -1
- package/src/core/scalePolicy.d.ts +3 -0
- package/src/core/scalePolicy.js +2 -0
- package/src/core/state.d.ts +1 -0
- package/src/shell/AstraeusShell.d.ts +4 -1
- package/src/shell/AstraeusShell.js +12 -6
- package/src/shell/AstraeusShell.node.js +225 -0
- package/src/shell/DisplaySwitches.d.ts +16 -0
- package/src/shell/DisplaySwitches.js +31 -0
- package/src/shell/StoryPanelView.js +3 -1
- package/src/shell/TimelineBar.css +4 -0
- package/src/shell/TimelineBar.node.js +75 -0
- package/src/shell/TopBar.css +20 -0
- package/src/shell/TopBar.d.ts +4 -1
- package/src/shell/TopBar.js +3 -2
- package/src/shell/TopBar.node.js +14 -0
- package/src/shell/experience.d.ts +4 -0
- package/src/shell/infoModel.js +3 -1
- package/src/shell/phone.css +4 -1
- package/src/shell/topBarIcons.d.ts +1 -0
- package/src/shell/topBarIcons.js +1 -0
- package/src/shell/useDrawers.js +1 -1
- package/src/shell/useZoomThrough.d.ts +7 -0
- package/src/shell/useZoomThrough.js +51 -0
- package/src/synthetic/syntheticDefinition.js +3 -3
- package/src/experiences/apollo11/spacecraftMetrics.d.ts +0 -34
- package/src/experiences/showers/showerChoice.d.ts +0 -25
package/src/api/scene.js
CHANGED
|
@@ -1,16 +1,27 @@
|
|
|
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 {
|
|
6
|
-
import {
|
|
4
|
+
import { createStateResolver } from "../core/stateResolver.js";
|
|
5
|
+
import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
|
|
6
|
+
import { loadPlanetSeries, planetSeriesLoaded } from "../core/planetSeries.js";
|
|
7
|
+
import { catalogue as builtInCatalogue, extendCatalogue, rootBodyId } from "../assets/catalogue.js";
|
|
8
|
+
import { buildElementsBody, ElementsBodyError, parseElementsBodyRecord } from "../core/elementsBody.js";
|
|
7
9
|
import { createComposition, SIDEREAL_MONTH_MS } from "../assets/compositions.js";
|
|
8
10
|
import { IO_PERIOD_DAYS } from "../core/bodies/io.js";
|
|
9
11
|
import { bodyMetrics } from "../app/bodyMetrics.js";
|
|
10
12
|
import { needsPlanetSeries } from "../app/planetNeeds.js";
|
|
13
|
+
import { catalogueItem } from "../app/catalogueItem.js";
|
|
14
|
+
import { createReadoutMetrics } from "../app/trackedMetrics.js";
|
|
15
|
+
import { circlesTheSun, farthestSunDistanceKm, sunOrbitIdOf, sunOrbitLayer } from "./sunOrbit.js";
|
|
11
16
|
import { readyMade } from "./bodies.js";
|
|
12
17
|
import { installData } from "./data.js";
|
|
18
|
+
import { planActivity, rateMetricOf } from "./activity.js";
|
|
19
|
+
import { buildGroupLayer, planGroup } from "./group.js";
|
|
13
20
|
import { SceneError } from "./errors.js";
|
|
21
|
+
import { toUtcMs } from "./time.js";
|
|
22
|
+
import { switchesOf } from "./switches.js";
|
|
23
|
+
import { eventProvenanceOf, eventsOf, panelsOf, timelineOf } from "./story.js";
|
|
24
|
+
export { toUtcMs } from "./time.js";
|
|
14
25
|
/** The orbits the engine can draw: the parent the line is measured from, and the span one lap covers. */
|
|
15
26
|
const ORBITS = {
|
|
16
27
|
moon: { parent: "earth", path: { spanMs: SIDEREAL_MONTH_MS } },
|
|
@@ -20,70 +31,207 @@ const DEFAULT_COLOR = "#ffd27a";
|
|
|
20
31
|
const DAY_MS = 86_400_000;
|
|
21
32
|
const PROVIDER_PATH_SAMPLES = 128;
|
|
22
33
|
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
34
|
/** The scene's camera: what it opens on. */
|
|
31
35
|
export class SceneCamera {
|
|
32
36
|
#target;
|
|
37
|
+
#following = false;
|
|
33
38
|
#view = {};
|
|
39
|
+
#reach;
|
|
40
|
+
#fit;
|
|
34
41
|
#has;
|
|
35
|
-
|
|
42
|
+
#circlesSun;
|
|
43
|
+
constructor(has, circlesSun) {
|
|
36
44
|
this.#has = has;
|
|
45
|
+
this.#circlesSun = circlesSun;
|
|
37
46
|
}
|
|
38
47
|
/** 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
48
|
follow(id, view = {}) {
|
|
49
|
+
return this.#open("follow", id, view, true);
|
|
50
|
+
}
|
|
51
|
+
/** 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. */
|
|
52
|
+
lookAt(id, view = {}) {
|
|
53
|
+
return this.#open("lookAt", id, view, false);
|
|
54
|
+
}
|
|
55
|
+
#open(call, id, view, following) {
|
|
40
56
|
if (!this.#has(id))
|
|
41
|
-
throw new SceneError("unknown-body", `camera
|
|
57
|
+
throw new SceneError("unknown-body", `camera.${call}("${id}"): no body or trajectory with that id has been added to the scene`);
|
|
58
|
+
if (view.up !== undefined && view.up !== "equatorial" && view.up !== "ecliptic")
|
|
59
|
+
throw new SceneError("bad-camera", `camera.${call}("${id}"): up "${String(view.up)}" must be "equatorial" or "ecliptic"`);
|
|
42
60
|
this.#target = id;
|
|
61
|
+
this.#following = following;
|
|
43
62
|
this.#view = view;
|
|
44
63
|
return this;
|
|
45
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* 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`.
|
|
67
|
+
* 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.
|
|
68
|
+
* 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.
|
|
69
|
+
* `setReach` and `fitOrbit` set the same limit, so the later call wins and replaces the earlier one.
|
|
70
|
+
*/
|
|
71
|
+
setReach(distance) {
|
|
72
|
+
if (!(typeof distance === "number" && Number.isFinite(distance) && distance > 0))
|
|
73
|
+
throw new SceneError("bad-camera", `camera.setReach: distance must be a finite number above 0, got ${String(distance)}`);
|
|
74
|
+
this.#reach = distance;
|
|
75
|
+
this.#fit = undefined;
|
|
76
|
+
return this;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Sets the farthest zoom-out so the whole orbit of a body circling the Sun (a planet, a built-in comet or one from `addBodyFromElements`, already added to the scene) fits the canvas
|
|
80
|
+
* from any view direction: the orbit's farthest Sun distance divided by the sine of the narrower half field of view of the canvas (vertical 45 degrees, or horizontal from the
|
|
81
|
+
* canvas's width over height), with 10 percent to spare. The viewer fits again whenever the canvas changes shape, such as a phone turning or a window resizing; the far plane follows
|
|
82
|
+
* as for `setReach`. The opening view does not move. Any other body throws `bad-camera` naming it; an id not in the scene throws `unknown-body`. `setReach` and `fitOrbit` set the
|
|
83
|
+
* same limit, so the later call wins and replaces the earlier one.
|
|
84
|
+
* @example
|
|
85
|
+
* scene.camera.fitOrbit("c-2025-a1");
|
|
86
|
+
*/
|
|
87
|
+
fitOrbit(body) {
|
|
88
|
+
const id = typeof body === "string" ? body : body.id;
|
|
89
|
+
if (!this.#has(id))
|
|
90
|
+
throw new SceneError("unknown-body", `camera.fitOrbit("${id}"): no body or trajectory with that id has been added to the scene`);
|
|
91
|
+
if (!this.#circlesSun(id))
|
|
92
|
+
throw new SceneError("bad-camera", `camera.fitOrbit("${id}"): "${id}" is not a body that circles the Sun (a planet, a comet or one added with addBodyFromElements)`);
|
|
93
|
+
this.#fit = id;
|
|
94
|
+
this.#reach = undefined;
|
|
95
|
+
return this;
|
|
96
|
+
}
|
|
97
|
+
/** The body `fitOrbit` fits the zoom-out to, if any. */
|
|
98
|
+
get fitted() { return this.#fit; }
|
|
99
|
+
/** The farthest zoom-out set with `setReach`, if any. */
|
|
100
|
+
get reach() { return this.#reach; }
|
|
46
101
|
get target() { return this.#target; }
|
|
102
|
+
/** Whether the opening view follows its target (`follow`) rather than only looking at it (`lookAt`). */
|
|
103
|
+
get following() { return this.#following; }
|
|
47
104
|
get view() { return this.#view; }
|
|
48
105
|
}
|
|
49
|
-
/**
|
|
106
|
+
/**
|
|
107
|
+
* 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.
|
|
108
|
+
* @example
|
|
109
|
+
* const scene = new Scene()
|
|
110
|
+
* .addBody(earth)
|
|
111
|
+
* .addBody(moon, { orbit: true })
|
|
112
|
+
* .setTime("2026-01-01T00:00:00Z");
|
|
113
|
+
* scene.camera.follow("moon", { distance: 60 });
|
|
114
|
+
*/
|
|
50
115
|
export class Scene {
|
|
116
|
+
/** The camera: `scene.camera.follow(id)` opens framed on a body or trajectory. */
|
|
51
117
|
camera;
|
|
52
118
|
#bodies = new Map();
|
|
53
119
|
#tracked = new Map();
|
|
120
|
+
#groups = new Map();
|
|
121
|
+
#activities = new Map();
|
|
54
122
|
#orbits = new Set();
|
|
123
|
+
#own = new Map();
|
|
124
|
+
#shape = new Map();
|
|
125
|
+
#catalogue = builtInCatalogue;
|
|
126
|
+
#notes = new Map();
|
|
127
|
+
#looks = new Map();
|
|
128
|
+
#sources = new Map();
|
|
55
129
|
#timeUtcMs;
|
|
56
130
|
#scale = trueScale;
|
|
131
|
+
#scaleOnly = false;
|
|
132
|
+
#events = [];
|
|
133
|
+
#eventProvenance;
|
|
134
|
+
#eventOwnProvenance = new Map();
|
|
135
|
+
#panels;
|
|
136
|
+
#timeline;
|
|
137
|
+
#switches;
|
|
57
138
|
constructor() {
|
|
58
|
-
this.camera = new SceneCamera((id) => this.#
|
|
139
|
+
this.camera = new SceneCamera((id) => this.#taken(id), (id) => this.#bodies.has(id) && circlesTheSun(this.#catalogue, id));
|
|
59
140
|
}
|
|
60
141
|
/** 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
142
|
addBody(body, options = {}) {
|
|
62
143
|
const id = typeof body === "string" ? body : body.id;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
144
|
+
this.#register("addBody", id, typeof body === "string" ? readyMade(id) ?? { id, label: this.#catalogue.has(id) ? this.#catalogue.get(id).definition.label : id } : body, options);
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* 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
|
|
149
|
+
* (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
|
|
150
|
+
* 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`
|
|
151
|
+
* naming the field; a repeated id throws `duplicate-id`.
|
|
152
|
+
* @example
|
|
153
|
+
* scene.addBody(sun).addBodyFromElements(record, { orbit: true, showLabel: false });
|
|
154
|
+
*/
|
|
155
|
+
addBodyFromElements(record, options = {}) {
|
|
156
|
+
const parsed = parseRecord(record);
|
|
157
|
+
if (this.#taken(parsed.id) || this.#catalogue.has(parsed.id))
|
|
158
|
+
throw new SceneError("duplicate-id", `addBodyFromElements("${parsed.id}"): that id is already in the scene or the catalogue`);
|
|
159
|
+
const root = builtInCatalogue.get(rootBodyId()).definition;
|
|
160
|
+
const before = this.#catalogue;
|
|
161
|
+
this.#catalogue = extendCatalogue(before, [parsed]);
|
|
162
|
+
try {
|
|
163
|
+
this.#register("addBodyFromElements", parsed.id, { id: parsed.id, label: parsed.label }, options);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
this.#catalogue = before;
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
this.#own.set(parsed.id, buildElementsBody(parsed, { id: root.id, gmKm3S2: root.gmKm3S2 }).sampling);
|
|
170
|
+
return this;
|
|
171
|
+
}
|
|
172
|
+
#register(call, id, ref, options) {
|
|
173
|
+
if (options.orbit === true && ORBITS[id] === undefined && !(circlesTheSun(this.#catalogue, id)))
|
|
174
|
+
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`);
|
|
175
|
+
if (!this.#catalogue.has(id))
|
|
176
|
+
throw new SceneError("unknown-body", `${call}("${id}"): not a catalogued body (known: ${this.#catalogue.ids().join(", ")})`);
|
|
177
|
+
if (this.#taken(id))
|
|
178
|
+
throw new SceneError("duplicate-id", `${call}("${id}"): already in the scene`);
|
|
179
|
+
checkBodyLook(id, options);
|
|
69
180
|
if (options.orbit === true)
|
|
70
181
|
this.#orbits.add(id);
|
|
71
|
-
|
|
72
|
-
|
|
182
|
+
if (options.color !== undefined || options.knownLimitations !== undefined)
|
|
183
|
+
this.#looks.set(id, { ...(options.color === undefined ? {} : { color: options.color }), ...(options.knownLimitations === undefined ? {} : { knownLimitations: options.knownLimitations }) });
|
|
184
|
+
if (options.enlarge !== undefined || options.showLabel !== undefined)
|
|
185
|
+
this.#shape.set(id, { ...(options.enlarge === undefined ? {} : { enlarge: options.enlarge }), ...(options.showLabel === undefined ? {} : { showLabel: options.showLabel }) });
|
|
186
|
+
if (options.description !== undefined)
|
|
187
|
+
this.#notes.set(id, options.description);
|
|
188
|
+
this.#bodies.set(id, ref);
|
|
73
189
|
}
|
|
74
190
|
/** Adds a path to follow and draw, from sampled states or a provider with `stateAt(time)`. */
|
|
75
191
|
addTrajectory(input) {
|
|
76
192
|
const id = input.id;
|
|
77
193
|
if (typeof id !== "string" || id === "")
|
|
78
194
|
throw new SceneError("bad-trajectory", "addTrajectory: the trajectory needs a non-empty id");
|
|
79
|
-
if (this.#
|
|
195
|
+
if (this.#taken(id))
|
|
80
196
|
throw new SceneError("duplicate-id", `addTrajectory("${id}"): that id is already in the scene`);
|
|
81
197
|
const center = input.center ?? "earth";
|
|
82
|
-
if (!
|
|
198
|
+
if (!builtInCatalogue.has(center))
|
|
83
199
|
throw new SceneError("unknown-body", `addTrajectory("${id}"): centre "${center}" is not a catalogued body`);
|
|
84
200
|
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
201
|
const common = { id, label: input.label ?? id, color: input.color ?? DEFAULT_COLOR, anchorTimesUtcMs: [], provenance };
|
|
86
|
-
|
|
202
|
+
const readouts = readoutsOf(id, input.readouts);
|
|
203
|
+
const body = "samples" in input ? sampledBody(common, input, center) : providerBody(common, input);
|
|
204
|
+
this.#tracked.set(id, { center, body: withAnchors(body, input.anchors), readouts, ...(input.description === undefined ? {} : { description: input.description }), ...(input.knownLimitations === undefined ? {} : { knownLimitations: input.knownLimitations }) });
|
|
205
|
+
return this;
|
|
206
|
+
}
|
|
207
|
+
/** Whether a body, path or group already has this id. */
|
|
208
|
+
#taken(id) {
|
|
209
|
+
return this.#bodies.has(id) || this.#tracked.has(id) || this.#groups.has(id);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* 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.
|
|
213
|
+
* 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 or clump throws `bad-group`. A `center` that is not a catalogued body throws `unknown-body`; a catalogued one the finished scene does not hold throws `bad-group` from `toDefinition`.
|
|
214
|
+
* @example
|
|
215
|
+
* scene.addGroup({ id: "ring", orbits: [{ id: "a", semiMajorAxisKm: 90_000, eccentricity: 0.1, inclinationDeg: 5, raanDeg: 40, argumentOfPeriapsisDeg: 70 }], color: "#9de3a8" });
|
|
216
|
+
*/
|
|
217
|
+
addGroup(input) {
|
|
218
|
+
const plan = planGroup(input, this.#catalogue);
|
|
219
|
+
if (this.#taken(plan.id))
|
|
220
|
+
throw new SceneError("duplicate-id", `addGroup("${plan.id}"): that id is already in the scene`);
|
|
221
|
+
this.#groups.set(plan.id, plan);
|
|
222
|
+
return this;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* 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
|
|
226
|
+
* (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`.
|
|
227
|
+
* @example
|
|
228
|
+
* 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 }] });
|
|
229
|
+
*/
|
|
230
|
+
addActivity(input) {
|
|
231
|
+
const plan = planActivity(input);
|
|
232
|
+
if (this.#activities.has(plan.window.id))
|
|
233
|
+
throw new SceneError("bad-activity", `addActivity("${plan.window.id}"): an activity with that id is already in the scene`);
|
|
234
|
+
this.#activities.set(plan.window.id, plan);
|
|
87
235
|
return this;
|
|
88
236
|
}
|
|
89
237
|
/** Sets the moment the scene opens at. */
|
|
@@ -91,13 +239,226 @@ export class Scene {
|
|
|
91
239
|
this.#timeUtcMs = toUtcMs(time, "setTime");
|
|
92
240
|
return this;
|
|
93
241
|
}
|
|
94
|
-
/** Chooses the opening scale: `trueScale` or `readableScale`; the viewer can switch to the other. */
|
|
95
|
-
setScale(scale) {
|
|
242
|
+
/** 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. */
|
|
243
|
+
setScale(scale, options = {}) {
|
|
96
244
|
if (!SCALES.some((known) => known.id === scale?.id))
|
|
97
245
|
throw new SceneError("bad-scale", `setScale: "${String(scale?.id)}" is not a scale; use trueScale or readableScale`);
|
|
98
246
|
this.#scale = scale;
|
|
247
|
+
this.#scaleOnly = options.only === true;
|
|
248
|
+
return this;
|
|
249
|
+
}
|
|
250
|
+
/** 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 that has none of its own (`EventInput.provenance`). May be called more than once. Malformed provenance throws "bad-event". */
|
|
251
|
+
addEvents(events, options = {}) {
|
|
252
|
+
const merged = eventsOf(events, this.#events);
|
|
253
|
+
const own = events.flatMap((event) => event.provenance === undefined ? [] : [[event.id, eventProvenanceOf(event.provenance, event.id)]]);
|
|
254
|
+
const batch = options.provenance === undefined ? undefined : eventProvenanceOf(options.provenance);
|
|
255
|
+
this.#events = merged;
|
|
256
|
+
for (const [id, provenance] of own)
|
|
257
|
+
this.#eventOwnProvenance.set(id, provenance);
|
|
258
|
+
if (batch !== undefined)
|
|
259
|
+
this.#eventProvenance = batch;
|
|
99
260
|
return this;
|
|
100
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Adds story panels that open as playback reaches them. A panel opens only when forward playback crosses its time, so one at the opening instant never opens by itself
|
|
264
|
+
* (a panel with an `object` still has its marker on that object). `at.utc` may be any instant inside the timeline, in any year. 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.
|
|
265
|
+
*/
|
|
266
|
+
addStoryPanels(panels) {
|
|
267
|
+
this.#panels = panels;
|
|
268
|
+
return this;
|
|
269
|
+
}
|
|
270
|
+
/** Sets the timeline: its span (`start`, `end`), the speeds offered (`rates`), the speed it opens at (`rate`) and whether playback wraps from the end to the start (`loop`; ignored with `{ none: true }`, which has no span to wrap, and when `setTimeline` is not called), or `{ none: true }` for no timeline bar, with time frozen at `at` or running at `rate`. Without this call the span follows the paths and the speeds are 1 minute, 1 hour and 1 day per second. */
|
|
271
|
+
setTimeline(timeline) {
|
|
272
|
+
this.#timeline = timelineOf(timeline);
|
|
273
|
+
return this;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* 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
|
|
277
|
+
* `"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
|
|
278
|
+
* 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.
|
|
279
|
+
* A bad switch name, place or `on` throws `bad-switch`.
|
|
280
|
+
* @example
|
|
281
|
+
* scene.setSwitches({ orbitLines: { place: "top-bar" }, labels: { place: "panel", on: false }, milkyWay: { place: "developer", on: false } });
|
|
282
|
+
*/
|
|
283
|
+
setSwitches(switches) {
|
|
284
|
+
this.#switches = switchesOf(switches, this.#switches);
|
|
285
|
+
return this;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* The state of a body in the scene at a moment (position in km always; velocity in km/s only where the body's source provides it), the same State the viewer draws: for a path added with `addTrajectory`, about its centre body;
|
|
289
|
+
* for a ready-made body or one from `addBodyFromElements`, about its parent (a planet about the Sun, a moon about its planet). Figures a story quotes, such as a distance from the Sun, come from here. `velocityKmS` is set only for a path whose
|
|
290
|
+
* samples or provider carry velocities and for a moon from fitted data (Io); planets, Earth, the Sun, the built-in comet and elements bodies give position only, so check it before use. An id the scene does not hold throws `unknown-body`. Ready-made and elements bodies answer at any date (they have no data cut-off); only a moment outside an
|
|
291
|
+
* `addTrajectory` path throws `bad-time`. A planet before the planet series have loaded (they load at mount) throws `missing-data`.
|
|
292
|
+
* @example
|
|
293
|
+
* const sunDistanceKm = Math.hypot(...scene.stateOf("earth", "2026-08-12T00:00:00Z").positionKm);
|
|
294
|
+
*/
|
|
295
|
+
stateOf(id, time) {
|
|
296
|
+
const entry = this.#tracked.get(id);
|
|
297
|
+
if (entry === undefined && !this.#bodies.has(id))
|
|
298
|
+
throw new SceneError("unknown-body", `stateOf("${id}"): no body or trajectory with that id has been added to the scene`);
|
|
299
|
+
const timeUtcMs = toUtcMs(time, `stateOf("${id}") time`);
|
|
300
|
+
const trajectory = entry?.body.trajectory ?? this.#catalogueSource(id);
|
|
301
|
+
const bounds = trajectory?.bounds;
|
|
302
|
+
if (bounds !== undefined && (timeUtcMs < bounds.startUtcMs || timeUtcMs > bounds.endUtcMs))
|
|
303
|
+
throw new SceneError("bad-time", `stateOf("${id}"): ${new Date(timeUtcMs).toISOString()} is outside the ${entry === undefined ? "body's data" : "path"} (${new Date(bounds.startUtcMs).toISOString()} to ${new Date(bounds.endUtcMs).toISOString()})`);
|
|
304
|
+
if (trajectory === undefined)
|
|
305
|
+
return this.#sunState(id, timeUtcMs);
|
|
306
|
+
try {
|
|
307
|
+
return trajectory.stateAt(timeUtcMs, entry?.center ?? this.#catalogue.get(id).definition.parentId);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
if (entry === undefined && error instanceof Error && error.message.startsWith("the planet series are not loaded"))
|
|
311
|
+
throw new SceneError("missing-data", `stateOf("${id}"): ${error.message}`);
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/** The Provenance of a body's position, as its info card shows it: for a ready-made or elements body the catalogue's position record, for a path the one passed to `addTrajectory`. Carries `accuracyClass` and `maxErrorFraction` where a comparison with an independent ephemeris exists. An id the scene does not hold throws `unknown-body`. */
|
|
316
|
+
provenanceOf(id) {
|
|
317
|
+
const entry = this.#tracked.get(id);
|
|
318
|
+
if (entry !== undefined)
|
|
319
|
+
return entry.body.provenance; // addTrajectory always sets one
|
|
320
|
+
if (!this.#bodies.has(id))
|
|
321
|
+
throw new SceneError("unknown-body", `provenanceOf("${id}"): no body or trajectory with that id has been added to the scene`);
|
|
322
|
+
return this.#catalogue.get(id).definition.accuracy.position;
|
|
323
|
+
}
|
|
324
|
+
/** A catalogued body's state source, the one the viewer draws from, made once per scene; none for the root (the Sun). */
|
|
325
|
+
#catalogueSource(id) {
|
|
326
|
+
const binding = this.#catalogue.sources().find((source) => source.body === id);
|
|
327
|
+
if (binding === undefined)
|
|
328
|
+
return undefined;
|
|
329
|
+
const made = this.#sources.get(id) ?? binding.create(createOrbAstronomyAdapter());
|
|
330
|
+
this.#sources.set(id, made);
|
|
331
|
+
return made;
|
|
332
|
+
}
|
|
333
|
+
/** The root body is at the origin of itself and at rest. */
|
|
334
|
+
#sunState(id, timeUtcMs) {
|
|
335
|
+
return createStateResolver(this.#catalogue.definitions(), this.#catalogue.sources(), createOrbAstronomyAdapter()).stateOf(id, timeUtcMs, id);
|
|
336
|
+
}
|
|
337
|
+
/** The story panels, resolved against this scene's events, anchors, objects and timeline span. */
|
|
338
|
+
#storyPanels(window) {
|
|
339
|
+
if (this.#panels === undefined)
|
|
340
|
+
return undefined;
|
|
341
|
+
const anchors = new Map();
|
|
342
|
+
for (const { body } of this.#tracked.values())
|
|
343
|
+
body.anchorLabels?.forEach((label, index) => { if (!anchors.has(label))
|
|
344
|
+
anchors.set(label, body.anchorTimesUtcMs[index]); });
|
|
345
|
+
return panelsOf(this.#panels, { events: this.#events, anchors, objectIds: [...this.#bodies.keys(), ...this.#tracked.keys(), ...this.#groups.keys()], window });
|
|
346
|
+
}
|
|
347
|
+
/** 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. */
|
|
348
|
+
#checkGroups(ids) {
|
|
349
|
+
for (const plan of this.#groups.values()) {
|
|
350
|
+
const center = plan.input.center ?? ids[0];
|
|
351
|
+
const clump = plan.input.clump;
|
|
352
|
+
if (!ids.includes(center))
|
|
353
|
+
throw new SceneError("bad-group", `addGroup("${plan.id}"): the orbits circle "${center}", which has not been added to the scene`);
|
|
354
|
+
if (clump !== undefined && !ids.includes(clump.near))
|
|
355
|
+
throw new SceneError("bad-group", `addGroup("${plan.id}"): clump.near "${clump.near}" has not been added to the scene`);
|
|
356
|
+
if (clump !== undefined && clump.near === center)
|
|
357
|
+
throw new SceneError("bad-group", `addGroup("${plan.id}"): the clump cannot be near the body the orbits circle ("${center}")`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/** The draw layers of the groups chosen by `which` (a clump near a planet reads its position, so needs the planet series). */
|
|
361
|
+
#groupLayers(ids, window, openUtcMs, which) {
|
|
362
|
+
return [...this.#groups.values()].filter(which).map((plan) => buildGroupLayer(plan, this.#catalogue, plan.input.center ?? ids[0], openUtcMs, window));
|
|
363
|
+
}
|
|
364
|
+
/** 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`). */
|
|
365
|
+
#earlySunPaths(orbitIds, openUtcMs) {
|
|
366
|
+
return planetSeriesLoaded() ? orbitIds.map((id) => this.#sunPath(id, openUtcMs)) : [];
|
|
367
|
+
}
|
|
368
|
+
/** Whether a Sun-centred scene enlarges a body, which the viewer's solar-system scale draws. */
|
|
369
|
+
#enlargedInSun(sunCentred) {
|
|
370
|
+
return sunCentred && [...this.#shape.values()].some((shape) => shape.enlarge !== undefined);
|
|
371
|
+
}
|
|
372
|
+
/** The activity windows, when any were added. */
|
|
373
|
+
#windowsEntry() {
|
|
374
|
+
return this.#activities.size === 0 ? {} : { windows: [...this.#activities.values()].map((activity) => activity.window) };
|
|
375
|
+
}
|
|
376
|
+
/** The bars of a group's info card at a moment. */
|
|
377
|
+
#groupMetrics(id, timeUtcMs) {
|
|
378
|
+
return (this.#groups.get(id)?.input.readouts ?? []).map((spec) => rateMetricOf(id, this.#activities.get(spec.activity ?? this.#firstActivity()), timeUtcMs));
|
|
379
|
+
}
|
|
380
|
+
#firstActivity() {
|
|
381
|
+
return this.#activities.keys().next().value;
|
|
382
|
+
}
|
|
383
|
+
/** A group's rate readout names an activity the scene holds. */
|
|
384
|
+
#checkGroupReadouts() {
|
|
385
|
+
for (const { id, input } of this.#groups.values()) {
|
|
386
|
+
for (const spec of input.readouts ?? []) {
|
|
387
|
+
const named = spec.activity ?? (this.#activities.size > 0 ? this.#firstActivity() : undefined);
|
|
388
|
+
if (named === undefined || !this.#activities.has(named))
|
|
389
|
+
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`}`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/** Throws `missing-data` naming the bodies whose data package was not passed. */
|
|
394
|
+
#checkData(data) {
|
|
395
|
+
const missing = this.missingData(data);
|
|
396
|
+
if (missing.length === 0)
|
|
397
|
+
return;
|
|
398
|
+
const names = [...this.#bodies.values()].filter((body) => body.requires !== undefined && missing.includes(body.requires)).map((body) => body.id);
|
|
399
|
+
throw new SceneError("missing-data", `${names.join(", ")} needs the ${missing.join(", ")} package: install it and pass it as mount(element, scene, { data: [...] })`);
|
|
400
|
+
}
|
|
401
|
+
/** The engine's own orbit loops (the Moon's and Io's) the scene asked for. */
|
|
402
|
+
#moonPaths() {
|
|
403
|
+
return [...this.#orbits].filter((id) => ORBITS[id] !== undefined).map((id) => {
|
|
404
|
+
const orbit = ORBITS[id];
|
|
405
|
+
if (!this.#bodies.has(orbit.parent))
|
|
406
|
+
throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about ${orbit.parent}, which has not been added to the scene`);
|
|
407
|
+
return { body: id, ...orbit.path };
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
/** Whether the scene is centred on the Sun; such a scene cannot hold a tracked path. */
|
|
411
|
+
#checkSunCentred(ids) {
|
|
412
|
+
const sunCentred = ids[0] === rootBodyId(this.#catalogue);
|
|
413
|
+
if (sunCentred && this.#tracked.size > 0)
|
|
414
|
+
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`);
|
|
415
|
+
return sunCentred;
|
|
416
|
+
}
|
|
417
|
+
/** The shell item of a body: from the catalogue, with the scene's own words, look and label setting. A Sun-centred scene, or one that fits the zoom-out to an orbit (`fitOrbit`, whose limit changes with the canvas), sets no label limit, so labels stay shown at any distance. */
|
|
418
|
+
#bodyObject(body, ids, sunCentred) {
|
|
419
|
+
const own = { labelPriority: 100 - ids.indexOf(body.id), ...(sunCentred || this.camera.fitted !== undefined ? {} : { 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) };
|
|
420
|
+
return { ...catalogueItem(body.id, own, this.#catalogue), label: body.label };
|
|
421
|
+
}
|
|
422
|
+
/** The event provenance entries of the experience: the batch's, and each event's own. */
|
|
423
|
+
#eventProvenanceEntries() {
|
|
424
|
+
return {
|
|
425
|
+
...(this.#eventProvenance === undefined ? {} : { eventProvenance: this.#eventProvenance }),
|
|
426
|
+
...(this.#eventOwnProvenance.size === 0 ? {} : { eventProvenanceById: Object.fromEntries(this.#eventOwnProvenance) }),
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
/** The bodies that asked for a Sun-orbit line, checked: the Sun must be in the scene and the line's id free. */
|
|
430
|
+
#sunOrbitIds(ids) {
|
|
431
|
+
return [...this.#orbits].filter((id) => ORBITS[id] === undefined).map((id) => {
|
|
432
|
+
if (!ids.includes(rootBodyId(this.#catalogue)))
|
|
433
|
+
throw new SceneError("no-orbit", `addBody("${id}", { orbit: true }): the orbit is drawn about the Sun, which has not been added to the scene`);
|
|
434
|
+
if (this.#taken(sunOrbitIdOf(id)))
|
|
435
|
+
throw new SceneError("duplicate-id", `addBody("${id}", { orbit: true }): the orbit line's id "${sunOrbitIdOf(id)}" is already in the scene`);
|
|
436
|
+
return id;
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
/** 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. */
|
|
440
|
+
#fitFarthestKm(openUtcMs) {
|
|
441
|
+
const id = this.camera.fitted;
|
|
442
|
+
if (id === undefined)
|
|
443
|
+
return undefined;
|
|
444
|
+
let km;
|
|
445
|
+
return () => (km ??= farthestSunDistanceKm(this.#catalogue, id, openUtcMs, this.#own.get(id)));
|
|
446
|
+
}
|
|
447
|
+
/** 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. */
|
|
448
|
+
#sunPath(id, openUtcMs) {
|
|
449
|
+
const layer = sunOrbitLayer(this.#catalogue, id, openUtcMs, this.#looks.get(id)?.color ?? "", this.#own.get(id));
|
|
450
|
+
if (layer === undefined)
|
|
451
|
+
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`);
|
|
452
|
+
return layer;
|
|
453
|
+
}
|
|
454
|
+
/** A readout names a body the scene must hold, so it can be measured against. */
|
|
455
|
+
#checkReadouts(entry, ids) {
|
|
456
|
+
for (const spec of entry.readouts) {
|
|
457
|
+
const named = readoutBody(spec);
|
|
458
|
+
if (named !== undefined && !ids.includes(named))
|
|
459
|
+
throw new SceneError("bad-readout", `addTrajectory("${entry.body.id}"): readout ${spec.kind} names "${named}", which has not been added to the scene`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
101
462
|
/** The data packages the added bodies need that `data` does not provide. */
|
|
102
463
|
missingData(data = []) {
|
|
103
464
|
const have = new Set(data.flatMap((source) => source.provides));
|
|
@@ -108,57 +469,141 @@ export class Scene {
|
|
|
108
469
|
toDefinition(data = []) {
|
|
109
470
|
if (this.#bodies.size === 0)
|
|
110
471
|
throw new SceneError("empty-scene", "the scene has no bodies; call addBody before mount");
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
}
|
|
472
|
+
this.#checkData(data);
|
|
473
|
+
this.#checkGroupReadouts();
|
|
116
474
|
const ids = [...this.#bodies.keys()];
|
|
117
|
-
const paths =
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
return { body: id, ...orbit.path };
|
|
122
|
-
});
|
|
475
|
+
const paths = this.#moonPaths();
|
|
476
|
+
const sunCentred = this.#checkSunCentred(ids);
|
|
477
|
+
for (const entry of this.#tracked.values())
|
|
478
|
+
this.#checkReadouts(entry, ids);
|
|
123
479
|
const tracked = [...this.#tracked.values()].map((entry) => entry.body);
|
|
124
|
-
const
|
|
125
|
-
const startUtcMs = this.#timeUtcMs
|
|
480
|
+
const timeline = this.#timeline;
|
|
481
|
+
const { window, startUtcMs } = spanOf(timeline, this.#timeUtcMs, [...tracked.map((body) => body.trajectory.bounds), ...[...this.#activities.values()].map((activity) => activity.window)]);
|
|
482
|
+
const sunOrbitIds = this.#sunOrbitIds(ids);
|
|
483
|
+
// 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.
|
|
484
|
+
const sunPaths = this.#earlySunPaths(sunOrbitIds, startUtcMs);
|
|
126
485
|
const target = this.camera.target;
|
|
127
486
|
const view = this.camera.view;
|
|
487
|
+
const storyPanels = this.#storyPanels(window);
|
|
488
|
+
this.#checkGroups(ids);
|
|
489
|
+
// 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).
|
|
490
|
+
const seriesIn = planetSeriesLoaded();
|
|
491
|
+
const late = (plan) => !seriesIn && plan.input.clump !== undefined;
|
|
492
|
+
const layers = [...this.#groupLayers(ids, window, startUtcMs, (plan) => !late(plan))];
|
|
493
|
+
const labelled = [...this.#bodies.values(), ...tracked, ...[...this.#groups.values()]].map(({ id, label }) => ({ id, label }));
|
|
494
|
+
const catalogue = this.#catalogue;
|
|
128
495
|
const definition = {
|
|
129
496
|
experience: {
|
|
130
497
|
objects: [
|
|
131
|
-
...[...this.#bodies.values()].map((body) => (
|
|
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 } }]),
|
|
498
|
+
...[...this.#bodies.values()].map((body) => this.#bodyObject(body, ids, sunCentred)),
|
|
499
|
+
...[...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
500
|
],
|
|
138
|
-
|
|
139
|
-
|
|
501
|
+
cameraPresets: cameraPresetsOf(labelled),
|
|
502
|
+
...(target === undefined ? {} : { startCameraPresetId: `${this.camera.following ? "follow" : "focus"}-${target}` }),
|
|
503
|
+
events: this.#events,
|
|
504
|
+
...this.#eventProvenanceEntries(),
|
|
505
|
+
...(storyPanels === undefined ? {} : { storyPanels }),
|
|
506
|
+
...(timeline?.none === true ? { hideTimeline: true } : {}),
|
|
140
507
|
window,
|
|
141
|
-
|
|
508
|
+
...this.#windowsEntry(),
|
|
509
|
+
rates: timeline?.rates ?? [60, 3_600, DAY_MS / 1000],
|
|
142
510
|
},
|
|
143
|
-
clock:
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
511
|
+
clock: clockOf(timeline, startUtcMs),
|
|
512
|
+
...groupLayersEntry(layers, this.#groups.size > 0, sunOrbitIds.length > 0),
|
|
513
|
+
...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
|
|
514
|
+
...(this.#own.size === 0 ? {} : { catalogue: this.#catalogue }),
|
|
515
|
+
...visualOverridesEntry(this.#shape),
|
|
516
|
+
composition: createComposition(this.#catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
|
|
517
|
+
scaleChoices: scaleChoicesOf(this.#scale, this.#scaleOnly, this.#enlargedInSun(sunCentred)),
|
|
518
|
+
...(this.#switches === undefined ? {} : { displaySwitches: this.#switches }),
|
|
519
|
+
...viewEntries(timeline, this.camera, this.#fitFarthestKm(startUtcMs)),
|
|
147
520
|
...(target === undefined ? {} : { startView: { focus: target, azimuthDeg: view.azimuthDeg ?? 0, elevationDeg: view.elevationDeg ?? 30, distance: view.distance ?? 40 } }),
|
|
148
521
|
trackedBodies: tracked,
|
|
149
522
|
createMetrics: ({ resolver }) => {
|
|
150
|
-
const catalogued = bodyMetrics(resolver, ids, ["distance"]);
|
|
151
|
-
|
|
523
|
+
const catalogued = bodyMetrics(resolver, ids, ["distance"], catalogue);
|
|
524
|
+
const readouts = createReadoutMetrics([...this.#tracked.values()].map(({ body, readouts: specs }) => ({ body, readouts: specs })), resolver);
|
|
525
|
+
return (objectId, timeUtcMs) => (this.#groups.has(objectId) ? this.#groupMetrics(objectId, timeUtcMs) : this.#tracked.has(objectId) ? readouts(objectId, timeUtcMs) : catalogued(objectId, timeUtcMs));
|
|
152
526
|
},
|
|
153
527
|
prepare: async () => {
|
|
154
|
-
if (needsPlanetSeries(definition))
|
|
528
|
+
if (needsPlanetSeries(definition) || sunPaths.length < sunOrbitIds.length || this.#groups.size > layers.length)
|
|
155
529
|
await loadPlanetSeries();
|
|
530
|
+
if (this.#groups.size > layers.length)
|
|
531
|
+
layers.push(...this.#groupLayers(ids, window, startUtcMs, late));
|
|
532
|
+
if (sunPaths.length < sunOrbitIds.length)
|
|
533
|
+
sunPaths.push(...sunOrbitIds.map((id) => this.#sunPath(id, startUtcMs)));
|
|
156
534
|
await installData(data, ids, window);
|
|
157
535
|
},
|
|
158
536
|
};
|
|
159
537
|
return definition;
|
|
160
538
|
}
|
|
161
539
|
}
|
|
540
|
+
/** The playback and camera settings the scene asked for: looping, the farthest zoom-out and the ecliptic up. */
|
|
541
|
+
function viewEntries(timeline, camera, farthestKm) {
|
|
542
|
+
const { reach, view, target } = camera;
|
|
543
|
+
return {
|
|
544
|
+
...(timeline?.loop === true ? { loop: true } : {}),
|
|
545
|
+
...(reach === undefined ? {} : { camera: { maxFocusDistance: reach, far: reach * 2.5 } }),
|
|
546
|
+
...(farthestKm === undefined ? {} : { camera: { fitOrbit: { farthestKm } } }),
|
|
547
|
+
...(view.up === undefined || target === undefined ? {} : { viewUp: view.up }),
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
/** The scene's layers: the points layer and the groups only when a group was added. */
|
|
551
|
+
function groupLayersEntry(layers, hasGroups, sunCentred) {
|
|
552
|
+
const sceneLayers = ["tracked-bodies", ...(hasGroups ? ["points"] : []), ...(sunCentred ? ["sun-centred"] : [])];
|
|
553
|
+
return hasGroups ? { sceneLayers, groups: layers } : { sceneLayers };
|
|
554
|
+
}
|
|
555
|
+
/** The enlargements the scene asked for, as the engine's per-body overrides. */
|
|
556
|
+
function visualOverridesEntry(shape) {
|
|
557
|
+
const overrides = {};
|
|
558
|
+
for (const [id, { enlarge }] of shape)
|
|
559
|
+
if (enlarge !== undefined)
|
|
560
|
+
overrides[id] = { exaggeration: enlarge };
|
|
561
|
+
return Object.keys(overrides).length === 0 ? {} : { visualOverrides: overrides };
|
|
562
|
+
}
|
|
563
|
+
/** Parses an elements record, naming the field a mistake is in. */
|
|
564
|
+
function parseRecord(record) {
|
|
565
|
+
try {
|
|
566
|
+
return parseElementsBodyRecord(record, "addBodyFromElements");
|
|
567
|
+
}
|
|
568
|
+
catch (error) {
|
|
569
|
+
if (error instanceof ElementsBodyError)
|
|
570
|
+
throw new SceneError("bad-element", error.message);
|
|
571
|
+
throw error;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/** The camera menu is automatic: Overview, and Focus and Follow for every body and path. */
|
|
575
|
+
function cameraPresetsOf(objects) {
|
|
576
|
+
return [
|
|
577
|
+
{ id: "overview", label: "Overview", request: { kind: "overview" } },
|
|
578
|
+
...objects.flatMap(({ id, label }) => [
|
|
579
|
+
{ id: `focus-${id}`, label: `Focus ${label}`, request: { kind: "focus", target: id } },
|
|
580
|
+
{ id: `follow-${id}`, label: `Follow ${label}`, request: { kind: "follow", target: id } },
|
|
581
|
+
]),
|
|
582
|
+
];
|
|
583
|
+
}
|
|
584
|
+
/** The timeline span and the moment the clock opens at; a moment outside a span the caller set is a `bad-timeline`. */
|
|
585
|
+
function spanOf(timeline, timeUtcMs, tracked) {
|
|
586
|
+
const setTime = (timeline?.none === true ? timeline.atUtcMs : undefined) ?? timeUtcMs;
|
|
587
|
+
// With nothing setting a span or a moment, the month window is centred on now and the clock opens at now (not at the window's start).
|
|
588
|
+
const now = setTime === undefined && timeline?.window === undefined && tracked.length === 0 ? Date.now() : undefined;
|
|
589
|
+
const window = timeline?.window ?? windowOf(tracked, setTime ?? now);
|
|
590
|
+
if (timeline?.window !== undefined && setTime !== undefined && (setTime < window.startUtcMs || setTime > window.endUtcMs)) {
|
|
591
|
+
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()})`);
|
|
592
|
+
}
|
|
593
|
+
return { window, startUtcMs: setTime ?? now ?? window.startUtcMs };
|
|
594
|
+
}
|
|
595
|
+
/** The clock's opening: 60 times real time unless set; with no timeline and no rate, frozen. */
|
|
596
|
+
function clockOf(timeline, startUtcMs) {
|
|
597
|
+
return { startUtcMs, rate: timeline?.rate ?? 60, ...(timeline?.none === true && timeline.rate === undefined ? { playing: false } : {}) };
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* 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 })`)
|
|
601
|
+
* 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.
|
|
602
|
+
*/
|
|
603
|
+
function scaleChoicesOf(scale, only, enlarged) {
|
|
604
|
+
const second = SCALES.filter((other) => other.id !== scale.id).map((other) => (enlarged && other.id === readableScale.id ? "solar-system" : other.id));
|
|
605
|
+
return only ? [scale.id] : [scale.id, ...second];
|
|
606
|
+
}
|
|
162
607
|
function sampledBody(common, input, center) {
|
|
163
608
|
const samples = input.samples.map((sample, index) => ({ ...sample, timeUtcMs: toUtcMs(sample.time, `addTrajectory("${common.id}") sample ${index} time`) }));
|
|
164
609
|
try {
|
|
@@ -181,14 +626,73 @@ function providerBody(common, input) {
|
|
|
181
626
|
const step = (bounds.endUtcMs - bounds.startUtcMs) / (PROVIDER_PATH_SAMPLES - 1);
|
|
182
627
|
return { ...common, trajectory, pathTimesUtcMs: Array.from({ length: PROVIDER_PATH_SAMPLES }, (_, index) => bounds.startUtcMs + index * step) };
|
|
183
628
|
}
|
|
184
|
-
/** The timeline span: the trajectories'
|
|
629
|
+
/** The timeline span: the union of the trajectories' and activities' spans, else a month about the chosen time (or about now). */
|
|
185
630
|
function windowOf(tracked, timeUtcMs) {
|
|
186
631
|
if (tracked.length > 0) {
|
|
187
|
-
const start = Math.min(...tracked.map((
|
|
188
|
-
const end = Math.max(...tracked.map((
|
|
632
|
+
const start = Math.min(...tracked.map((bounds) => bounds.startUtcMs));
|
|
633
|
+
const end = Math.max(...tracked.map((bounds) => bounds.endUtcMs));
|
|
189
634
|
if (timeUtcMs === undefined || (timeUtcMs >= start && timeUtcMs <= end))
|
|
190
635
|
return { startUtcMs: start, endUtcMs: end };
|
|
191
636
|
}
|
|
192
637
|
const centre = timeUtcMs ?? Date.now();
|
|
193
638
|
return { startUtcMs: centre - 15 * DAY_MS, endUtcMs: centre + 15 * DAY_MS };
|
|
194
639
|
}
|
|
640
|
+
/** Checks the colour and known limits given to `addBody`. */
|
|
641
|
+
function checkBodyLook(id, options) {
|
|
642
|
+
if (options.enlarge !== undefined && !(typeof options.enlarge === "number" && Number.isFinite(options.enlarge) && options.enlarge >= 1))
|
|
643
|
+
throw new SceneError("bad-body", `addBody("${id}"): enlarge ${String(options.enlarge)} must be a number of at least 1`);
|
|
644
|
+
if (options.showLabel !== undefined && typeof options.showLabel !== "boolean")
|
|
645
|
+
throw new SceneError("bad-body", `addBody("${id}"): showLabel must be true or false`);
|
|
646
|
+
if (options.color !== undefined && !(typeof options.color === "string" && /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(options.color)))
|
|
647
|
+
throw new SceneError("bad-body", `addBody("${id}"): color "${String(options.color)}" is not a hex colour such as "#9fd8ff"`);
|
|
648
|
+
const limits = options.knownLimitations;
|
|
649
|
+
if (limits !== undefined && !(Array.isArray(limits) && limits.every((line) => typeof line === "string" && line !== "")))
|
|
650
|
+
throw new SceneError("bad-body", `addBody("${id}"): knownLimitations must be a list of non-empty texts`);
|
|
651
|
+
}
|
|
652
|
+
const READOUT_KINDS = ["range", "speed", "distance", "altitude"];
|
|
653
|
+
/** The body a readout names, if any. */
|
|
654
|
+
function readoutBody(spec) {
|
|
655
|
+
return spec.kind === "range" ? spec.marker : spec.kind === "distance" ? spec.to : spec.kind === "altitude" ? spec.above : undefined;
|
|
656
|
+
}
|
|
657
|
+
/** Checks each readout's kind and the catalogued body it names; whether the scene holds that body is checked when the definition is built. */
|
|
658
|
+
function readoutsOf(id, readouts = []) {
|
|
659
|
+
if (!Array.isArray(readouts))
|
|
660
|
+
throw new SceneError("bad-readout", `addTrajectory("${id}"): readouts must be a list`);
|
|
661
|
+
for (const spec of readouts) {
|
|
662
|
+
if (!READOUT_KINDS.includes(spec?.kind))
|
|
663
|
+
throw new SceneError("bad-readout", `addTrajectory("${id}"): readout kind "${String(spec?.kind)}" is not one of ${READOUT_KINDS.join(", ")}`);
|
|
664
|
+
const named = readoutBody(spec);
|
|
665
|
+
if (spec.kind !== "range" && spec.kind !== "speed" && named === undefined)
|
|
666
|
+
throw new SceneError("bad-readout", `addTrajectory("${id}"): readout ${spec.kind} needs ${spec.kind === "distance" ? "`to`" : "`above`"}, the body to measure against`);
|
|
667
|
+
if (named !== undefined && !builtInCatalogue.has(named))
|
|
668
|
+
throw new SceneError("bad-readout", `addTrajectory("${id}"): readout ${spec.kind} names "${named}", which is not a catalogued body`);
|
|
669
|
+
}
|
|
670
|
+
return readouts;
|
|
671
|
+
}
|
|
672
|
+
/** 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. */
|
|
673
|
+
function withAnchors(body, anchors = []) {
|
|
674
|
+
if (!Array.isArray(anchors))
|
|
675
|
+
throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): anchors must be a list`);
|
|
676
|
+
const { startUtcMs, endUtcMs } = body.trajectory.bounds;
|
|
677
|
+
const seen = new Set();
|
|
678
|
+
const placed = anchors.map((anchor) => {
|
|
679
|
+
if (typeof anchor?.id !== "string" || anchor.id === "")
|
|
680
|
+
throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): every anchor needs a non-empty id`);
|
|
681
|
+
if (seen.has(anchor.id))
|
|
682
|
+
throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): anchor "${anchor.id}" appears twice`);
|
|
683
|
+
seen.add(anchor.id);
|
|
684
|
+
const timeUtcMs = anchorTime(body.id, anchor);
|
|
685
|
+
if (timeUtcMs < startUtcMs || timeUtcMs > endUtcMs)
|
|
686
|
+
throw new SceneError("bad-anchor", `addTrajectory("${body.id}"): anchor "${anchor.id}" is outside the path (${new Date(startUtcMs).toISOString()} to ${new Date(endUtcMs).toISOString()})`);
|
|
687
|
+
return { id: anchor.id, timeUtcMs };
|
|
688
|
+
}).sort((a, b) => a.timeUtcMs - b.timeUtcMs);
|
|
689
|
+
return placed.length === 0 ? body : { ...body, anchorTimesUtcMs: placed.map((anchor) => anchor.timeUtcMs), anchorLabels: placed.map((anchor) => anchor.id) };
|
|
690
|
+
}
|
|
691
|
+
function anchorTime(path, anchor) {
|
|
692
|
+
try {
|
|
693
|
+
return toUtcMs(anchor.time);
|
|
694
|
+
}
|
|
695
|
+
catch {
|
|
696
|
+
throw new SceneError("bad-anchor", `addTrajectory("${path}"): anchor "${anchor.id}" has a time "${String(anchor.time)}" that is not a valid moment`);
|
|
697
|
+
}
|
|
698
|
+
}
|