@johnmorrisdotca/chikyu-earth 0.7.0 → 0.9.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.
@@ -0,0 +1,161 @@
1
+ /**
2
+ * One satellite's orbital elements in the "GP" format that CelesTrak and Space-Track both serve as JSON (CCSDS OMM, one object per satellite). Only these fields are read.
3
+ * The package fetches nothing: your page gets the elements (see the satellites guide for the rules of the sources) and passes them in.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { ElementSet } from "@johnmorrisdotca/chikyu-earth/satellites";
8
+ *
9
+ * const iss: ElementSet = {
10
+ * OBJECT_NAME: "ISS (ZARYA)",
11
+ * OBJECT_ID: "1998-067A",
12
+ * EPOCH: "2026-11-02T10:25:21.580320",
13
+ * MEAN_MOTION: 15.49150046,
14
+ * ECCENTRICITY: 0.0007139,
15
+ * INCLINATION: 51.6332,
16
+ * RA_OF_ASC_NODE: 335.9757,
17
+ * ARG_OF_PERICENTER: 339.3739,
18
+ * MEAN_ANOMALY: 20.6961,
19
+ * NORAD_CAT_ID: 25544,
20
+ * BSTAR: 0.00012,
21
+ * MEAN_MOTION_DOT: 0.0001,
22
+ * MEAN_MOTION_DDOT: 0,
23
+ * };
24
+ * console.log(iss.OBJECT_NAME);
25
+ * ```
26
+ */
27
+ export interface ElementSet {
28
+ OBJECT_NAME: string;
29
+ OBJECT_ID?: string;
30
+ /** The moment the elements describe, ISO 8601 in UTC (a trailing `Z` is optional). */
31
+ EPOCH: string;
32
+ /** Revolutions a day. */
33
+ MEAN_MOTION: number;
34
+ ECCENTRICITY: number;
35
+ /** Degrees. */
36
+ INCLINATION: number;
37
+ /** Degrees. */
38
+ RA_OF_ASC_NODE: number;
39
+ /** Degrees. */
40
+ ARG_OF_PERICENTER: number;
41
+ /** Degrees. */
42
+ MEAN_ANOMALY: number;
43
+ NORAD_CAT_ID: number;
44
+ BSTAR: number;
45
+ MEAN_MOTION_DOT: number;
46
+ MEAN_MOTION_DDOT: number;
47
+ EPHEMERIS_TYPE?: number;
48
+ CLASSIFICATION_TYPE?: string;
49
+ ELEMENT_SET_NO?: number;
50
+ REV_AT_EPOCH?: number;
51
+ }
52
+ /**
53
+ * What a page can tell a reader about one satellite at a moment: its name, its number, how old its elements are, how high and how fast it is.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * import type { SatelliteInfo } from "@johnmorrisdotca/chikyu-earth/satellites";
58
+ *
59
+ * const describe = (info: SatelliteInfo): string => `${info.name}: ${info.altitudeKm.toFixed(0)} km up, ${info.speedKmS.toFixed(2)} km/s`;
60
+ * console.log(typeof describe);
61
+ * ```
62
+ */
63
+ export interface SatelliteInfo {
64
+ /** Where it is in its group. */
65
+ index: number;
66
+ name: string;
67
+ /** The NORAD catalogue number. */
68
+ noradId: number;
69
+ /** The international designator (for example `1998-067A`), when the elements carry one. */
70
+ objectId: string | undefined;
71
+ /** The moment of its elements, in milliseconds since the Unix epoch. */
72
+ epochMs: number;
73
+ /** Days between the elements' moment and the moment asked about (negative before it). */
74
+ ageDays: number;
75
+ /** Height above the mean Earth radius (6371 km) at that moment. */
76
+ altitudeKm: number;
77
+ /** Speed against the stars, kilometres a second. */
78
+ speedKmS: number;
79
+ /** One revolution, minutes. */
80
+ periodMinutes: number;
81
+ /** Degrees. */
82
+ inclinationDeg: number;
83
+ }
84
+ /**
85
+ * A satellite chosen from a group: which group and which place in it.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * import type { SatelliteRef } from "@johnmorrisdotca/chikyu-earth/satellites";
90
+ *
91
+ * const first: SatelliteRef = { group: "stations", index: 0 };
92
+ * console.log(first.group);
93
+ * ```
94
+ */
95
+ export interface SatelliteRef {
96
+ group: string;
97
+ index: number;
98
+ }
99
+ /**
100
+ * A satellite the group could not use, and why: its elements did not start SGP4 (bad numbers), or it had decayed at its own epoch.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * import type { RefusedElementSet } from "@johnmorrisdotca/chikyu-earth/satellites";
105
+ *
106
+ * const show = (one: RefusedElementSet): string => `${one.name}: ${one.reason}`;
107
+ * console.log(typeof show);
108
+ * ```
109
+ */
110
+ export interface RefusedElementSet {
111
+ name: string;
112
+ noradId: number;
113
+ reason: string;
114
+ }
115
+ /**
116
+ * A group of satellites, ready to give positions for any moment: what `createSatellites` returns, and what `<chikyu-space>` takes in `setSatellites`.
117
+ * Positions are in Earth radii (6371 km) from the Earth's centre, in the space view's axes (x to the vernal equinox, y north); a satellite whose elements
118
+ * are older than `maxAgeDays` at the moment asked about is not placed (its place stays at the centre and `visible(index)` is false).
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * import type { Satellites } from "@johnmorrisdotca/chikyu-earth/satellites";
123
+ *
124
+ * const first = (group: Satellites): string => group.sets[0]?.OBJECT_NAME ?? "none";
125
+ * console.log(typeof first);
126
+ * ```
127
+ */
128
+ export interface Satellites {
129
+ /** Satellites that started SGP4. */
130
+ readonly count: number;
131
+ /** Their elements, in the order of their places. */
132
+ readonly sets: readonly ElementSet[];
133
+ /** The ones left out, with the reason. */
134
+ readonly refused: readonly RefusedElementSet[];
135
+ /** The oldest an element set may be at the moment shown, in days. */
136
+ readonly maxAgeDays: number;
137
+ /** SGP4 calls made so far, for a page or a test to count. */
138
+ readonly propagations: number;
139
+ /** Milliseconds the last batch of SGP4 took, and the longest so far. */
140
+ readonly timing: {
141
+ lastBatchMs: number;
142
+ maxBatchMs: number;
143
+ };
144
+ /**
145
+ * Fill `out` (3 numbers a satellite) with the positions at `ms`: SGP4 is run for the whole group at two moments `step` apart and the positions between are interpolated, so a
146
+ * steady clock costs one batch a step and every call in between is arithmetic.
147
+ */
148
+ at(ms: number, out: Float32Array): void;
149
+ /** True if satellite `index` was placed by the last `at` (its elements are not too old at that moment). */
150
+ visible(index: number): boolean;
151
+ /** How many of them the last `at` placed. */
152
+ readonly placed: number;
153
+ /** The game time between the two moments SGP4 is run at (1000 to 60000 ms); the space view sets it from the clock's speed. */
154
+ setStep(ms: number): void;
155
+ /** One satellite at exactly `ms` (no interpolation): position in Earth radii and velocity in km/s into `out` (6 numbers). False if its elements are too old or SGP4 gave up. */
156
+ exact(index: number, ms: number, out: Float64Array): boolean;
157
+ /** The path of satellite `index` for one revolution from `ms`, `points` + 1 points in order along it (the last on the first), into a new array of Earth radii. */
158
+ orbit(index: number, ms: number, points: number): Float32Array;
159
+ /** Facts about one satellite at `ms`; undefined if it cannot be placed then. */
160
+ info(index: number, ms: number): SatelliteInfo | undefined;
161
+ }
@@ -0,0 +1,3 @@
1
+ // What the satellites are made of and what the space view asks of them. Types only: nothing here imports satellite.js, so the space element can use them
2
+ // without needing it.
3
+ export {};
@@ -1,8 +1,11 @@
1
1
  import type { GeoPoint } from "../types.ts";
2
2
  import { setThreeLoader } from "../realistic/shared.ts";
3
+ import type { SatelliteInfo, SatelliteRef, Satellites } from "../satellites/types.ts";
4
+ import { type SatelliteStyle } from "./satellite-layer.ts";
5
+ import type { RideLook } from "./ride.ts";
3
6
  import { type ScaleMode } from "./scale.ts";
4
- import { BODY_NAMES, type BodyName, type BodyPainter } from "./scene.ts";
5
- export { BODY_NAMES, type BodyName };
7
+ import { BODY_NAMES, type BodyName, type BodyPainter, type RideTarget } from "./scene.ts";
8
+ export { BODY_NAMES, type BodyName, type RideTarget };
6
9
  /**
7
10
  * Change how the Sun and the planets are drawn (before the first element connects): the space view keeps their places, sizes, light, names and orbits and asks
8
11
  * the painter only for what to draw at each place (see `BodyPainter`). Left alone, they are plain spheres in the right colours.
@@ -61,6 +64,54 @@ export type SpaceState = "loading" | "live" | "unavailable" | "lost" | "idle";
61
64
  * ```
62
65
  */
63
66
  export type SpacePreset = "earth" | "moon" | "sun" | "inner" | "solar-system";
67
+ /**
68
+ * How a ride along is done: `view` `from` (the default) puts the camera at the body looking at the Earth, `follow` keeps it a fixed distance from the body looking at it (`distanceKm`, 3000 by default,
69
+ * for a satellite; a planet or the Moon is kept at the distance the zoom says); `look` `down` (the default) or `horizon` is where a camera at the body points; `smooth` (the default) glides
70
+ * from the old camera to the new one in about a second and a bit, and jumps instead for a reader who asked for reduced motion.
71
+ *
72
+ * @example
73
+ * ```ts no-run
74
+ * import type { RideOptions } from "@johnmorrisdotca/chikyu-earth/space/element";
75
+ *
76
+ * const options: RideOptions = { view: "from", look: "horizon" };
77
+ * console.log(options.look);
78
+ * ```
79
+ */
80
+ export interface RideOptions {
81
+ view?: "from" | "follow";
82
+ look?: RideLook;
83
+ distanceKm?: number;
84
+ smooth?: boolean;
85
+ }
86
+ /**
87
+ * What the camera is riding along with now: the body or satellite, how (`from` or `follow`), where it looks, and the distance kept for a satellite.
88
+ *
89
+ * @example
90
+ * ```ts no-run
91
+ * import type { Riding } from "@johnmorrisdotca/chikyu-earth/space/element";
92
+ *
93
+ * const describe = (ride: Riding | null): string => (ride ? `${ride.view} ${typeof ride.target === "string" ? ride.target : ride.target.group}` : "not riding");
94
+ * console.log(typeof describe);
95
+ * ```
96
+ */
97
+ export interface Riding {
98
+ target: RideTarget;
99
+ view: "from" | "follow";
100
+ look: RideLook;
101
+ distanceKm: number;
102
+ }
103
+ type SatelliteStats = {
104
+ groups: number;
105
+ placed: number;
106
+ tooFast: boolean;
107
+ propagations: number;
108
+ lastBatchMs: number;
109
+ maxBatchMs: number;
110
+ updateMs: number;
111
+ maxUpdateMs: number;
112
+ averageUpdateMs: number;
113
+ updates: number;
114
+ };
64
115
  /**
65
116
  * The `<chikyu-space>` custom element: the Earth, the Moon, the Sun and the planets where they are at a date and time, drawn with three.js through the shared renderer. It takes `center`, `time` (`now` or an ISO date), `speed` (1 is real time, 0 holds, 86400 is a day a second, negative runs backwards), `scale` (`compressed` or `true`), `labels` and `orbits` (`off` hides them); positions are computed in the browser by astronomy-engine, an optional peer dependency. It draws only when something changes, and nothing while it is out of sight.
66
117
  *
@@ -94,15 +145,63 @@ export declare class ChikyuSpace extends HTMLElement {
94
145
  set labels(value: boolean);
95
146
  get orbits(): boolean;
96
147
  set orbits(value: boolean);
97
- /** The shared controls' camera: yaw and tilt turn the view, zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. */
148
+ /**
149
+ * The shared controls' camera: yaw and tilt turn the view, zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. A turn that moves nothing on the screen by half a pixel is kept
150
+ * for the next draw but does not cause one unless `final` is true (the default), so an Auto-turn at the Earth's own rate costs a draw every half minute, not thirty a second.
151
+ *
152
+ * @param view - The controls' yaw and tilt in degrees and zoom.
153
+ * @param final - False for the frames of a turn that is still going on (Auto-turn, a drag); true when it has settled.
154
+ */
98
155
  setView(view: {
99
156
  yaw: number;
100
157
  tilt: number;
101
158
  zoom: number;
102
- }): void;
159
+ }, final?: boolean): void;
103
160
  /** The body the camera looks at: at zoom 1 it fills the view; the yaw and tilt turn the camera round it. */
104
161
  get body(): BodyName;
105
162
  set body(name: BodyName);
163
+ /**
164
+ * Ride along with a body or a satellite. By default the camera sits at it and looks at the Earth, with the way it is going at the top of the picture, at its real place for the moment shown, so the
165
+ * Earth turns and slides beneath as it moves along its orbit (an ISS view goes round about every 90 minutes). The shared controls' yaw and tilt turn the view and tip it towards the horizon, their zoom narrows it.
166
+ * A satellite is `{ group, index }` of a group set with `setSatellites`; it is placed exactly, one SGP4 call a frame, at any speed. Another call switches smoothly; `null` stops. The draw rate follows how
167
+ * fast the picture moves, never more than 30 a second (one a second for a reader who asked for reduced motion), and nothing is drawn out of sight.
168
+ *
169
+ * @param target - A body name (`"Moon"`, `"Mars"`, ...) or a satellite `{ group, index }`, or `null` to stop.
170
+ * @param options - `view`, `look`, `distanceKm`, `smooth` (see `RideOptions`).
171
+ */
172
+ ride(target: RideTarget | null, options?: RideOptions): void;
173
+ /** What the camera is riding along with now, or null. */
174
+ get riding(): Riding | null;
175
+ /**
176
+ * Show a group of satellites (made by `createSatellites`) under a name, or take the group away with `null`. A group is one draw call however many satellites it holds. Giving the name of a group
177
+ * that is already shown replaces it. `style`: `color` and `size` (CSS pixels) of the dots, and `orbits` to draw every orbit (only for a group of 40 or fewer, such as the stations).
178
+ * The groups are placed by SGP4 about once a second and interpolated between, and are hidden while the clock runs faster than `MAX_SATELLITE_SPEED`.
179
+ *
180
+ * @param group - The group's name, for `showSatellites`, `selectSatellite` and the events.
181
+ * @param satellites - The group, or `null` to remove it.
182
+ * @param style - How to draw it.
183
+ */
184
+ setSatellites(group: string, satellites: Satellites | null, style?: Partial<SatelliteStyle>): void;
185
+ /** Show or hide a group without losing it. */
186
+ showSatellites(group: string, on: boolean): void;
187
+ /** The groups now set, with how many satellites each holds and whether it is shown. */
188
+ get satelliteGroups(): {
189
+ name: string;
190
+ count: number;
191
+ visible: boolean;
192
+ }[];
193
+ /** Mark one satellite: a larger ring round it, its orbit drawn, and its name beside it. `null` lets it go. */
194
+ selectSatellite(ref: SatelliteRef | null): void;
195
+ /** The satellite marked by `selectSatellite` or by a press on it, if any. */
196
+ get selectedSatellite(): SatelliteRef | null;
197
+ /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period); undefined if it cannot be placed then. */
198
+ satelliteInfo(ref: SatelliteRef): SatelliteInfo | undefined;
199
+ /** The words shown beside each body, for a page in another language (`{ Mars: "火星" }`). A body left out keeps its English name. */
200
+ get bodyNames(): Partial<Record<BodyName, string>>;
201
+ set bodyNames(value: Partial<Record<BodyName, string>>);
202
+ /** What a screen reader hears after a body's name: "choose to look at it" by default, or the page's own words. */
203
+ get bodyHint(): string;
204
+ set bodyHint(value: string);
106
205
  /** The radius and the distance from the Earth of a body now, for a page's own caption. */
107
206
  bodyInfo(name: BodyName): BodyInfo;
108
207
  /** The zoom that shows a part of the sky: the Earth alone, the Moon's orbit, the Sun, the planets out to Mars, or all of them, at this scale and moment. */
@@ -125,6 +224,17 @@ export declare class ChikyuSpace extends HTMLElement {
125
224
  };
126
225
  time: number;
127
226
  lookups: number;
227
+ satellites: SatelliteStats;
228
+ ride: {
229
+ riding: boolean;
230
+ lost: boolean;
231
+ gliding: boolean;
232
+ };
233
+ /** The camera as the last draw left it: its place in Earth radii from the Earth's centre, and its field of view in degrees. */
234
+ camera: {
235
+ position: [number, number, number];
236
+ fov: number;
237
+ };
128
238
  };
129
239
  }
130
240
  declare global {
@@ -1,7 +1,9 @@
1
1
  import { createGate, frameCap } from "../realistic/gate.js";
2
2
  import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
3
3
  import { MAX_TEXTURE } from "../realistic/tiers.js";
4
+ import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
4
5
  import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt } from "./ephemeris.js";
6
+ import { MAX_ORBIT_GROUP } from "./satellite-layer.js";
5
7
  import { placeAround, placeMoon, placeSun } from "./scale.js";
6
8
  import { BODY_NAMES, createSpaceItem, FIT_DISTANCE, newSpaceModel } from "./scene.js";
7
9
  export { BODY_NAMES };
@@ -29,6 +31,9 @@ export { setThreeLoader };
29
31
  const RAD = Math.PI / 180;
30
32
  /** The Earth's own turn, degrees a second. */
31
33
  const EARTH_RATE = 360 / 86_164.0905;
34
+ /** The quickest a satellite goes round, degrees a second (a low orbit: 88 minutes). */
35
+ const SATELLITE_RATE = 360 / (88 * 60);
36
+ const SATELLITE_COLORS = ["#ffd54f", "#7fd4ff", "#ff8fa3", "#9ef0a8"];
32
37
  const REAL_TIME_TICK_MS = 60_000;
33
38
  const readCentre = (value) => {
34
39
  if (!value)
@@ -72,6 +77,11 @@ export class ChikyuSpace extends HTMLElement {
72
77
  #last = 0;
73
78
  #pool = new Map();
74
79
  #places;
80
+ #chosenLabel;
81
+ #focusBeforeRide = "Earth";
82
+ #lostTold = false;
83
+ #names = {};
84
+ #hint = "choose to look at it";
75
85
  #tiers = {};
76
86
  connectedCallback() {
77
87
  this.#model.centre = readCentre(this.getAttribute("center")) ?? this.#model.centre;
@@ -82,12 +92,13 @@ export class ChikyuSpace extends HTMLElement {
82
92
  this.#model.labels = this.getAttribute("labels") !== "off";
83
93
  this.#model.orbits = this.getAttribute("orbits") !== "off";
84
94
  this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
95
+ this.#model.speed = this.#speed;
85
96
  if (!this.hasAttribute("role"))
86
97
  this.setAttribute("role", "img");
87
98
  if (!this.hasAttribute("aria-label"))
88
99
  this.setAttribute("aria-label", "The Earth, the Moon, the Sun and the planets in their places for the date shown");
89
100
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
90
- root.innerHTML = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}</style><div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
101
+ root.innerHTML = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}.sp-sat{position:absolute;left:0;top:0;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-sat[hidden]{display:none}</style><div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
91
102
  this.#stage = root.getElementById("stage");
92
103
  this.#labelBox = root.getElementById("labels");
93
104
  this.#pool.clear();
@@ -110,6 +121,10 @@ export class ChikyuSpace extends HTMLElement {
110
121
  this.#tiers[layer] = width;
111
122
  },
112
123
  onLabels: (places) => this.#placeLabels(places),
124
+ onSelected: (place) => this.#placeChosen(place),
125
+ onMoving: () => this.#gate?.request(),
126
+ onRideLost: () => this.#rideLost(),
127
+ onSatellitesError: (error) => this.dispatchEvent(new CustomEvent("chikyu-satellites-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
113
128
  ...(painter ? { painter } : {}),
114
129
  });
115
130
  this.#view = taken.renderer.view(this.#stage, item, { still: null });
@@ -178,6 +193,7 @@ export class ChikyuSpace extends HTMLElement {
178
193
  }
179
194
  set speed(value) {
180
195
  this.#speed = Number.isFinite(value) ? value : 1;
196
+ this.#model.speed = this.#speed;
181
197
  this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
182
198
  this.#last = performance.now();
183
199
  this.#schedule();
@@ -207,12 +223,24 @@ export class ChikyuSpace extends HTMLElement {
207
223
  this.#model.orbits = value;
208
224
  this.#gate?.request();
209
225
  }
210
- /** The shared controls' camera: yaw and tilt turn the view, zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. */
211
- setView(view) {
226
+ /**
227
+ * The shared controls' camera: yaw and tilt turn the view, zoom brings the camera in (1 shows the Earth, less shows the sky round it). Pan is not used. A turn that moves nothing on the screen by half a pixel is kept
228
+ * for the next draw but does not cause one unless `final` is true (the default), so an Auto-turn at the Earth's own rate costs a draw every half minute, not thirty a second.
229
+ *
230
+ * @param view - The controls' yaw and tilt in degrees and zoom.
231
+ * @param final - False for the frames of a turn that is still going on (Auto-turn, a drag); true when it has settled.
232
+ */
233
+ setView(view, final = true) {
212
234
  const now = this.#model.view;
213
235
  if (view.yaw === now.yaw && view.tilt === now.tilt && view.zoom === now.zoom)
214
236
  return;
215
237
  this.#model.view = { yaw: view.yaw, tilt: view.tilt, zoom: view.zoom };
238
+ const drawn = this.#model.drawnView;
239
+ if (drawn && !final && view.zoom === drawn.zoom) {
240
+ const turned = Math.max(Math.abs(view.yaw - drawn.yaw), Math.abs(view.tilt - drawn.tilt)) * RAD;
241
+ if (turned * (this.#model.heightPx / 2) < 0.5)
242
+ return;
243
+ }
216
244
  this.#gate?.request();
217
245
  }
218
246
  /** The body the camera looks at: at zoom 1 it fills the view; the yaw and tilt turn the camera round it. */
@@ -225,6 +253,136 @@ export class ChikyuSpace extends HTMLElement {
225
253
  this.#model.focus = name;
226
254
  this.#gate?.request();
227
255
  }
256
+ // --- riding along -------------------------------------------------------------------------------------------------------------------------------
257
+ /**
258
+ * Ride along with a body or a satellite. By default the camera sits at it and looks at the Earth, with the way it is going at the top of the picture, at its real place for the moment shown, so the
259
+ * Earth turns and slides beneath as it moves along its orbit (an ISS view goes round about every 90 minutes). The shared controls' yaw and tilt turn the view and tip it towards the horizon, their zoom narrows it.
260
+ * A satellite is `{ group, index }` of a group set with `setSatellites`; it is placed exactly, one SGP4 call a frame, at any speed. Another call switches smoothly; `null` stops. The draw rate follows how
261
+ * fast the picture moves, never more than 30 a second (one a second for a reader who asked for reduced motion), and nothing is drawn out of sight.
262
+ *
263
+ * @param target - A body name (`"Moon"`, `"Mars"`, ...) or a satellite `{ group, index }`, or `null` to stop.
264
+ * @param options - `view`, `look`, `distanceKm`, `smooth` (see `RideOptions`).
265
+ */
266
+ ride(target, options = {}) {
267
+ const model = this.#model;
268
+ const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
269
+ const wasRiding = model.ride !== null;
270
+ if (target === null) {
271
+ model.ride = null;
272
+ model.focus = this.#focusBeforeRide;
273
+ }
274
+ else {
275
+ if (typeof target === "string" && !BODY_NAMES.includes(target))
276
+ return;
277
+ if (typeof target !== "string" && !model.satellites.groups.get(target.group))
278
+ return;
279
+ if (!wasRiding)
280
+ this.#focusBeforeRide = model.focus;
281
+ const view = typeof target === "string" && target === "Earth" ? "follow" : (options.view ?? "from");
282
+ model.ride = { target: typeof target === "string" ? target : { group: target.group, index: target.index }, view, look: options.look ?? "down", distanceKm: Math.max(100, options.distanceKm ?? 3000) };
283
+ if (typeof target === "string" && view === "follow")
284
+ model.focus = target;
285
+ else if (wasRiding)
286
+ model.focus = this.#focusBeforeRide;
287
+ }
288
+ this.#lostTold = false;
289
+ const pose = model.pose;
290
+ model.transition = (options.smooth ?? true) && !reduced && pose.valid ? { start: performance.now(), duration: 1200, from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov } } : null;
291
+ this.#last = performance.now();
292
+ this.#schedule();
293
+ this.#gate?.request();
294
+ this.dispatchEvent(new CustomEvent("chikyu-ride", { detail: this.riding }));
295
+ }
296
+ /** What the camera is riding along with now, or null. */
297
+ get riding() {
298
+ const ride = this.#model.ride;
299
+ return ride ? { ...ride, target: typeof ride.target === "string" ? ride.target : { ...ride.target } } : null;
300
+ }
301
+ #rideLost() {
302
+ if (this.#lostTold)
303
+ return;
304
+ this.#lostTold = true;
305
+ this.dispatchEvent(new CustomEvent("chikyu-ride-lost", { detail: this.riding }));
306
+ }
307
+ // --- satellites ---------------------------------------------------------------------------------------------------------------------------------
308
+ /**
309
+ * Show a group of satellites (made by `createSatellites`) under a name, or take the group away with `null`. A group is one draw call however many satellites it holds. Giving the name of a group
310
+ * that is already shown replaces it. `style`: `color` and `size` (CSS pixels) of the dots, and `orbits` to draw every orbit (only for a group of 40 or fewer, such as the stations).
311
+ * The groups are placed by SGP4 about once a second and interpolated between, and are hidden while the clock runs faster than `MAX_SATELLITE_SPEED`.
312
+ *
313
+ * @param group - The group's name, for `showSatellites`, `selectSatellite` and the events.
314
+ * @param satellites - The group, or `null` to remove it.
315
+ * @param style - How to draw it.
316
+ */
317
+ setSatellites(group, satellites, style = {}) {
318
+ const groups = this.#model.satellites.groups;
319
+ if (satellites === null) {
320
+ groups.delete(group);
321
+ if (this.#model.satellites.selected?.group === group)
322
+ this.#model.satellites.selected = null;
323
+ }
324
+ else {
325
+ const was = groups.get(group);
326
+ groups.set(group, {
327
+ satellites,
328
+ color: style.color ?? was?.color ?? SATELLITE_COLORS[groups.size % SATELLITE_COLORS.length],
329
+ size: style.size ?? was?.size ?? 3,
330
+ orbits: (style.orbits ?? was?.orbits ?? false) && satellites.count <= MAX_ORBIT_GROUP,
331
+ visible: was?.visible ?? true,
332
+ });
333
+ }
334
+ this.#last = performance.now();
335
+ this.#schedule();
336
+ this.#gate?.request();
337
+ }
338
+ /** Show or hide a group without losing it. */
339
+ showSatellites(group, on) {
340
+ const found = this.#model.satellites.groups.get(group);
341
+ if (!found || found.visible === on)
342
+ return;
343
+ found.visible = on;
344
+ this.#schedule();
345
+ this.#gate?.request();
346
+ }
347
+ /** The groups now set, with how many satellites each holds and whether it is shown. */
348
+ get satelliteGroups() {
349
+ return [...this.#model.satellites.groups].map(([name, group]) => ({ name, count: group.satellites.count, visible: group.visible }));
350
+ }
351
+ /** Mark one satellite: a larger ring round it, its orbit drawn, and its name beside it. `null` lets it go. */
352
+ selectSatellite(ref) {
353
+ const found = ref ? this.#model.satellites.groups.get(ref.group) : undefined;
354
+ this.#model.satellites.selected = ref && found && ref.index >= 0 && ref.index < found.satellites.count ? { group: ref.group, index: ref.index } : null;
355
+ if (this.#chosenLabel)
356
+ this.#chosenLabel.hidden = true;
357
+ this.#gate?.request();
358
+ }
359
+ /** The satellite marked by `selectSatellite` or by a press on it, if any. */
360
+ get selectedSatellite() {
361
+ const chosen = this.#model.satellites.selected;
362
+ return chosen ? { ...chosen } : null;
363
+ }
364
+ /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period); undefined if it cannot be placed then. */
365
+ satelliteInfo(ref) {
366
+ return this.#model.satellites.groups.get(ref.group)?.satellites.info(ref.index, this.#model.time);
367
+ }
368
+ /** The words shown beside each body, for a page in another language (`{ Mars: "火星" }`). A body left out keeps its English name. */
369
+ get bodyNames() {
370
+ return { ...this.#names };
371
+ }
372
+ set bodyNames(value) {
373
+ this.#names = { ...value };
374
+ for (const [name, button] of this.#pool)
375
+ this.#nameLabel(button, name);
376
+ }
377
+ /** What a screen reader hears after a body's name: "choose to look at it" by default, or the page's own words. */
378
+ get bodyHint() {
379
+ return this.#hint;
380
+ }
381
+ set bodyHint(value) {
382
+ this.#hint = value;
383
+ for (const [name, button] of this.#pool)
384
+ this.#nameLabel(button, name);
385
+ }
228
386
  /** The radius and the distance from the Earth of a body now, for a page's own caption. */
229
387
  bodyInfo(name) {
230
388
  const frame = this.#model.drawn?.frame ?? frameAt(this.#model.time);
@@ -259,25 +417,52 @@ export class ChikyuSpace extends HTMLElement {
259
417
  assets: { entries: stats?.assets.entries ?? 0, refs: stats?.assets.refs ?? 0 },
260
418
  time: this.#model.time,
261
419
  lookups: this.#model.lookups,
420
+ satellites: this.#satelliteStats(),
421
+ ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null },
422
+ camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], fov: this.#model.pose.fov },
262
423
  };
263
424
  }
425
+ #satelliteStats() {
426
+ const drawn = this.#model.satellites.drawn;
427
+ let propagations = 0;
428
+ let lastBatchMs = 0;
429
+ let maxBatchMs = 0;
430
+ for (const group of this.#model.satellites.groups.values()) {
431
+ propagations += group.satellites.propagations;
432
+ lastBatchMs = Math.max(lastBatchMs, group.satellites.timing.lastBatchMs);
433
+ maxBatchMs = Math.max(maxBatchMs, group.satellites.timing.maxBatchMs);
434
+ }
435
+ return { groups: this.#model.satellites.groups.size, placed: drawn.placed, tooFast: drawn.tooFast, propagations, lastBatchMs, maxBatchMs, updateMs: drawn.updateMs, maxUpdateMs: drawn.maxUpdateMs, averageUpdateMs: drawn.updates ? drawn.totalMs / drawn.updates : 0, updates: drawn.updates };
436
+ }
264
437
  // --- the game clock ----------------------------------------------------------------------------------------------------------------------------
265
438
  #readSpeed() {
266
439
  const raw = this.getAttribute("speed");
267
440
  const value = raw === null || raw === "" ? 1 : Number(raw);
268
441
  return Number.isFinite(value) ? value : 1;
269
442
  }
270
- /** While time runs, draw as often as it shows: real time once a minute; faster time as often as the Earth's turn moves a pixel (1 to 30 times a second). */
443
+ /** Is anything on show that moves faster than the Earth turns: a group of satellites the clock is slow enough to place? */
444
+ #satellitesMoving() {
445
+ if (Math.abs(this.#speed) > MAX_SATELLITE_SPEED)
446
+ return false;
447
+ for (const group of this.#model.satellites.groups.values())
448
+ if (group.visible && group.satellites.count > 0)
449
+ return true;
450
+ return false;
451
+ }
452
+ /** While time runs, draw as often as it shows: real time once a minute; faster time as often as the Earth's turn moves a pixel (1 to 30 times a second). Satellites go round in 90 minutes and a ride along moves the whole picture, so with either on show real time draws about as often as a pixel moves (once a second at least), and a reader who asked for reduced motion gets one step a second. */
271
453
  #schedule() {
272
454
  clearTimeout(this.#timer);
273
455
  this.#timer = undefined;
274
456
  if (!this.isConnected || this.#speed === 0)
275
457
  return;
276
- const realTime = this.#speed === 1 && this.#mode === "now";
458
+ const satellites = this.#satellitesMoving();
459
+ const riding = this.#model.ride !== null;
277
460
  const radius = this.#model.drawn?.radiusPx ?? 200;
278
- const pixelsPerSecond = EARTH_RATE * RAD * Math.abs(this.#speed) * radius;
279
- const perSecond = Math.min(30, Math.max(1, pixelsPerSecond));
280
- const wait = realTime || this.#speed === 1 ? REAL_TIME_TICK_MS : 1000 / perSecond;
461
+ const pixelsPerSecond = Math.max((satellites ? SATELLITE_RATE : EARTH_RATE) * RAD * Math.abs(this.#speed) * radius, this.#model.rideMotion * Math.abs(this.#speed));
462
+ let perSecond = Math.min(30, Math.max(1, pixelsPerSecond));
463
+ if ((satellites || riding) && matchMedia("(prefers-reduced-motion: reduce)").matches)
464
+ perSecond = 1;
465
+ const wait = !satellites && !riding && this.#speed === 1 ? REAL_TIME_TICK_MS : 1000 / perSecond;
281
466
  this.#timer = setTimeout(this.#tick, wait);
282
467
  }
283
468
  #tick = () => {
@@ -307,8 +492,7 @@ export class ChikyuSpace extends HTMLElement {
307
492
  button.type = "button";
308
493
  button.className = "sp-label";
309
494
  button.dataset["body"] = name;
310
- button.textContent = name;
311
- button.setAttribute("aria-label", `${name}: choose to look at it`);
495
+ this.#nameLabel(button, name);
312
496
  box.append(button);
313
497
  this.#pool.set(name, button);
314
498
  label = button;
@@ -323,6 +507,32 @@ export class ChikyuSpace extends HTMLElement {
323
507
  label.style.transform = `translate(${Math.round(at.x + Math.max(4, Math.min(at.r, 40)))}px,${Math.round(at.y - 8)}px)`;
324
508
  }
325
509
  }
510
+ #placeChosen(place) {
511
+ const box = this.#labelBox;
512
+ if (!box)
513
+ return;
514
+ if (!place) {
515
+ if (this.#chosenLabel)
516
+ this.#chosenLabel.hidden = true;
517
+ return;
518
+ }
519
+ const chosen = this.#model.satellites.selected;
520
+ const name = chosen ? this.satelliteInfo(chosen)?.name : undefined;
521
+ if (!this.#chosenLabel) {
522
+ this.#chosenLabel = box.ownerDocument.createElement("div");
523
+ this.#chosenLabel.className = "sp-sat";
524
+ box.append(this.#chosenLabel);
525
+ }
526
+ if (this.#chosenLabel.textContent !== (name ?? ""))
527
+ this.#chosenLabel.textContent = name ?? "";
528
+ this.#chosenLabel.hidden = !name;
529
+ this.#chosenLabel.style.transform = `translate(${Math.round(place.x + 10)}px,${Math.round(place.y - 8)}px)`;
530
+ }
531
+ #nameLabel(button, name) {
532
+ const text = this.#names[name] ?? name;
533
+ button.textContent = text;
534
+ button.setAttribute("aria-label", `${text}: ${this.#hint}`);
535
+ }
326
536
  // A body is chosen by pressing on it or on its name (and by Tab and Enter on the name); a drag that turns the view is not a choice.
327
537
  #downX = 0;
328
538
  #downY = 0;
@@ -334,11 +544,18 @@ export class ChikyuSpace extends HTMLElement {
334
544
  window.addEventListener("pointerup", this.#up, { capture: true, once: true });
335
545
  };
336
546
  #up = (event) => {
337
- if (Math.hypot(event.clientX - this.#downX, event.clientY - this.#downY) > 6 || !this.#places)
547
+ if (Math.hypot(event.clientX - this.#downX, event.clientY - this.#downY) > 6)
338
548
  return;
339
549
  const rect = this.getBoundingClientRect();
340
550
  const x = event.clientX - rect.left;
341
551
  const y = event.clientY - rect.top;
552
+ const satellite = this.#model.pick?.(x, y, 12);
553
+ if (satellite) {
554
+ this.dispatchEvent(new CustomEvent("chikyu-satellite-click", { detail: { ...satellite, info: this.satelliteInfo(satellite) }, bubbles: true, composed: true }));
555
+ return;
556
+ }
557
+ if (!this.#places)
558
+ return;
342
559
  let best;
343
560
  let bestD = Infinity;
344
561
  for (const name of BODY_NAMES) {