@johnmorrisdotca/chikyu-earth 0.36.0 → 0.37.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.
@@ -1,12 +1,20 @@
1
1
  // SGP4 for a group of satellites, kept cheap: the whole group is run at two moments a step apart and every position in between is an interpolation, so the cost is one batch a step
2
2
  // (about once a second), never one a frame. satellite.js (MIT) does the SGP4 itself; this file never touches the screen and imports on a server.
3
3
  import { json2satrec, sgp4 } from "satellite.js";
4
+ import { CLASS_COLOURS } from "../catalogue/kinds.js";
5
+ import { classOfElements } from "../catalogue/orbit.js";
4
6
  import { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS } from "./limits.js";
7
+ import { ownerCountry } from "./owners.js";
5
8
  /** The Earth's mean radius in kilometres: the unit of every position here (the same as the space view's). */
6
9
  const EARTH_RADIUS_KM = 6371;
7
10
  const DAY_MS = 86_400_000;
8
11
  const MIN_STEP_MS = 1000;
9
12
  const MAX_STEP_MS = 60_000;
13
+ /**
14
+ * From this eccentricity up, a satellite is not turned about its orbit's axis at the mean motion above the interpolation limit, because it does not go round at a steady rate or stay at one height
15
+ * (a Molniya orbit is 10 times quicker at its lowest point than its mean): its place and its streak are SGP4 itself, two calls a frame, for the few that are this eccentric.
16
+ */
17
+ export const ECCENTRIC_FROM = 0.02;
10
18
  const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text : `${text}Z`);
11
19
  /**
12
20
  * Make a group of satellites from their element sets. Each starts SGP4 once here; one that does not (bad numbers, decayed at its own epoch) is listed in `refused` and left out.
@@ -73,6 +81,32 @@ export function createSatellites(sets, options = {}) {
73
81
  }
74
82
  }
75
83
  const n = recs.length;
84
+ const normal = new Float32Array(n * 3);
85
+ const rate = new Float64Array(n);
86
+ const classColour = new Float32Array(n * 3);
87
+ const eccentric = [];
88
+ let newestEpochMs = 0;
89
+ for (let i = 0; i < n; i += 1) {
90
+ const set = usable[i];
91
+ const epoch = epochs[i];
92
+ if (epoch > newestEpochMs)
93
+ newestEpochMs = epoch;
94
+ const iRad = (set.INCLINATION * Math.PI) / 180;
95
+ const oRad = (set.RA_OF_ASC_NODE * Math.PI) / 180;
96
+ const si = Math.sin(iRad);
97
+ const ci = Math.cos(iRad);
98
+ normal[i * 3] = Math.sin(oRad) * si;
99
+ normal[i * 3 + 1] = ci;
100
+ normal[i * 3 + 2] = Math.cos(oRad) * si;
101
+ rate[i] = (set.MEAN_MOTION * 2 * Math.PI) / DAY_MS;
102
+ if (set.ECCENTRICITY >= ECCENTRIC_FROM)
103
+ eccentric.push(i);
104
+ const kind = classOfElements(set.MEAN_MOTION, set.ECCENTRICITY) ?? "other";
105
+ const hex = Number.parseInt(CLASS_COLOURS[kind].slice(1), 16);
106
+ classColour[i * 3] = ((hex >> 16) & 255) / 255;
107
+ classColour[i * 3 + 1] = ((hex >> 8) & 255) / 255;
108
+ classColour[i * 3 + 2] = (hex & 255) / 255;
109
+ }
76
110
  let a = new Float32Array(n * 3);
77
111
  let b = new Float32Array(n * 3);
78
112
  let okA = new Uint8Array(n);
@@ -87,6 +121,23 @@ export function createSatellites(sets, options = {}) {
87
121
  let propagations = 0;
88
122
  let placed = 0;
89
123
  const timing = { lastBatchMs: 0, maxBatchMs: 0 };
124
+ const pinned = new Float32Array(n * 3);
125
+ const pinOk = new Uint8Array(n);
126
+ let pinMs = Number.NaN;
127
+ /** Turn `x,y,z` about the unit axis `nx,ny,nz` by `ang` radians, into `out` at `at` (no allocation: it runs for every satellite on every frame). */
128
+ const turn = (x, y, z, nx, ny, nz, ang, out, at) => {
129
+ const c = Math.cos(ang);
130
+ const s = Math.sin(ang);
131
+ const dot = nx * x + ny * y + nz * z;
132
+ const k = 1 - c;
133
+ out[at] = x * c + (ny * z - nz * y) * s + nx * dot * k;
134
+ out[at + 1] = y * c + (nz * x - nx * z) * s + ny * dot * k;
135
+ out[at + 2] = z * c + (nx * y - ny * x) * s + nz * dot * k;
136
+ };
137
+ const place = new Float64Array(6);
138
+ const isEccentric = new Uint8Array(n);
139
+ for (const i of eccentric)
140
+ isEccentric[i] = 1;
90
141
  /** SGP4 for the whole group at one moment, into `buffer` in the space view's axes (TEME x, z, -y: x to the vernal equinox, y north). */
91
142
  const sample = (buffer, ok, ms) => {
92
143
  const started = performance.now();
@@ -142,9 +193,83 @@ export function createSatellites(sets, options = {}) {
142
193
  return propagations;
143
194
  },
144
195
  timing,
196
+ newestEpochMs,
197
+ classColour,
145
198
  get placed() {
146
199
  return placed;
147
200
  },
201
+ pin(ms) {
202
+ if (n === 0)
203
+ return;
204
+ sample(pinned, pinOk, ms);
205
+ pinMs = ms;
206
+ },
207
+ arc(ms, spanMs, positions, segments) {
208
+ if (n === 0)
209
+ return 0;
210
+ if (!Number.isFinite(pinMs)) {
211
+ sample(pinned, pinOk, ms);
212
+ pinMs = ms;
213
+ }
214
+ const span = spanMs;
215
+ let count = 0;
216
+ for (let i = 0; i < n; i += 1) {
217
+ const k = i * 3;
218
+ const dim = Math.abs(ms - epochs[i]) > dimAfterMs ? 1 : 0;
219
+ if (dim !== dimmed[i]) {
220
+ dimmed[i] = dim;
221
+ dimVersion += 1;
222
+ }
223
+ const w = k * 2;
224
+ if (isEccentric[i] === 1) {
225
+ if (!exactAt(i, ms, place)) {
226
+ positions.fill(0, k, k + 3);
227
+ segments.fill(0, w, w + 6);
228
+ shown[i] = 0;
229
+ continue;
230
+ }
231
+ positions[k] = place[0];
232
+ positions[k + 1] = place[1];
233
+ positions[k + 2] = place[2];
234
+ segments[w + 3] = place[0];
235
+ segments[w + 4] = place[1];
236
+ segments[w + 5] = place[2];
237
+ if (exactAt(i, ms - span, place)) {
238
+ segments[w] = place[0];
239
+ segments[w + 1] = place[1];
240
+ segments[w + 2] = place[2];
241
+ }
242
+ else {
243
+ segments[w] = positions[k];
244
+ segments[w + 1] = positions[k + 1];
245
+ segments[w + 2] = positions[k + 2];
246
+ }
247
+ shown[i] = 1;
248
+ count += 1;
249
+ continue;
250
+ }
251
+ if (pinOk[i] !== 1) {
252
+ positions.fill(0, k, k + 3);
253
+ segments.fill(0, w, w + 6);
254
+ shown[i] = 0;
255
+ continue;
256
+ }
257
+ const nx = normal[k];
258
+ const ny = normal[k + 1];
259
+ const nz = normal[k + 2];
260
+ const sweep = Math.max(-Math.PI, Math.min(Math.PI, rate[i] * span));
261
+ const along = rate[i] * (ms - pinMs);
262
+ turn(pinned[k], pinned[k + 1], pinned[k + 2], nx, ny, nz, along, positions, k);
263
+ turn(pinned[k], pinned[k + 1], pinned[k + 2], nx, ny, nz, along - sweep, segments, w);
264
+ segments[w + 3] = positions[k];
265
+ segments[w + 4] = positions[k + 1];
266
+ segments[w + 5] = positions[k + 2];
267
+ shown[i] = 1;
268
+ count += 1;
269
+ }
270
+ placed = count;
271
+ return count;
272
+ },
148
273
  setStep(ms) {
149
274
  const next = Math.min(MAX_STEP_MS, Math.max(MIN_STEP_MS, Math.round(ms)));
150
275
  if (next !== stepMs) {
@@ -235,6 +360,9 @@ export function createSatellites(sets, options = {}) {
235
360
  periodMinutes: 1440 / set.MEAN_MOTION,
236
361
  inclinationDeg: set.INCLINATION,
237
362
  };
363
+ const country = ownerCountry(set.COUNTRY_CODE ?? set.OWNER);
364
+ if (country)
365
+ info.ownerCountry = country;
238
366
  return info;
239
367
  },
240
368
  };
@@ -48,6 +48,10 @@ export interface ElementSet {
48
48
  CLASSIFICATION_TYPE?: string;
49
49
  ELEMENT_SET_NO?: number;
50
50
  REV_AT_EPOCH?: number;
51
+ /** The owner's code, as one catalogue writes it (`US`, `PRC`, `ESA`), when the source carries it. */
52
+ COUNTRY_CODE?: string;
53
+ /** The owner's code, as the other catalogue writes it (the same codes), when the source carries it. */
54
+ OWNER?: string;
51
55
  }
52
56
  /**
53
57
  * 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.
@@ -80,6 +84,8 @@ export interface SatelliteInfo {
80
84
  periodMinutes: number;
81
85
  /** Degrees. */
82
86
  inclinationDeg: number;
87
+ /** The owner's country as an ISO 3166-1 alpha-2 code (`ownerCountry`), when the elements carry an owner code (`COUNTRY_CODE` or `OWNER`) and the owner is one country; absent for an organisation, several countries, an ambiguous owner or an unknown code. */
88
+ ownerCountry?: string;
83
89
  }
84
90
  /**
85
91
  * A satellite chosen from a group: which group and which place in it.
@@ -154,10 +160,22 @@ export interface Satellites {
154
160
  at(ms: number, out: Float32Array): void;
155
161
  /** True if satellite `index` was placed by the last `at` (its elements are not too old at that moment). */
156
162
  visible(index: number): boolean;
157
- /** How many of them the last `at` placed. */
163
+ /** How many of them the last `at` or `arc` placed. */
158
164
  readonly placed: number;
165
+ /** The newest element epoch in the group, in milliseconds since the Unix epoch, or 0 when it is empty. The date of the data. */
166
+ readonly newestEpochMs: number;
167
+ /** Red, green and blue, from 0 to 1, of each satellite's orbit class, 3 numbers a satellite. It does not change. */
168
+ readonly classColour: Float32Array;
159
169
  /** 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. */
160
170
  setStep(ms: number): void;
171
+ /** Place every satellite with SGP4 at `ms` and keep that place. `arc` turns it along the orbit until the next `pin`. One batch, no interpolation. */
172
+ pin(ms: number): void;
173
+ /**
174
+ * The place of each satellite at `ms` into `positions` (3 numbers each) and the stretch of orbit it travels over `spanMs` of game time into `segments` (6 numbers each: where it was `spanMs` earlier, then where it is).
175
+ * The place is the last `pin`, turned about the orbit's axis by the mean motion, so a fast clock does not run SGP4 for every satellite on every frame. A `spanMs` that would turn it more than half a revolution is cut there. An orbit with an eccentricity of 0.02 or more is placed by SGP4 itself instead (two calls a frame), because a turn at the mean motion would put it off its path.
176
+ * Returns how many were written.
177
+ */
178
+ arc(ms: number, spanMs: number, positions: Float32Array, segments: Float32Array): number;
161
179
  /** 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. */
162
180
  exact(index: number, ms: number, out: Float64Array): boolean;
163
181
  /** 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. */
@@ -14,7 +14,7 @@ import type { LightMode } from "../realistic/earth.ts";
14
14
  import type { SatelliteInfo, SatelliteRef, Satellites } from "../satellites/types.ts";
15
15
  import { type PlanetName } from "./ephemeris.ts";
16
16
  import { type SatelliteStyle } from "./satellite-layer.ts";
17
- import { type RideLook } from "./ride.ts";
17
+ import { type RideFace, type RideLook } from "./ride.ts";
18
18
  import { type ScaleMode } from "./scale.ts";
19
19
  import { BODY_NAMES, type CameraMode, type BodyName, type BodyPainter, type RideTarget, type SatellitePainter } from "./scene.ts";
20
20
  export { BODY_NAMES, type BodyName, type CameraMode, type RideTarget };
@@ -93,7 +93,7 @@ export type SpacePreset = "earth" | "moon" | "sun" | "inner" | "solar-system" |
93
93
  /**
94
94
  * 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,
95
95
  * for a satellite; a planet or the Moon is kept at the distance the zoom says); `above` (a satellite only; a body is followed) puts it on the line from the Earth's centre through the satellite, `distanceKm` (divided by the zoom) above it, looking straight down at it with the way it is going at the top
96
- * of the picture, the satellite held in the middle while the Earth turns beneath (a drag turns the picture about the satellite and tips the camera back or ahead of it); `look` `down` (the default) or `horizon` is where a camera at the body points; `smooth` (the default) glides
96
+ * of the picture, the satellite held in the middle while the Earth turns beneath (a drag turns the picture about the satellite and tips the camera back or ahead of it); `look` `down` (the default) or `horizon` is where a camera at the body points; `face` opens looking one way (see `face`); `smooth` (the default) glides
97
97
  * 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.
98
98
  *
99
99
  * @example
@@ -107,11 +107,13 @@ export type SpacePreset = "earth" | "moon" | "sun" | "inner" | "solar-system" |
107
107
  export interface RideOptions {
108
108
  view?: "from" | "follow" | "above";
109
109
  look?: RideLook;
110
+ /** Face this way as the ride opens (`face`). */
111
+ face?: RideFace;
110
112
  distanceKm?: number;
111
113
  smooth?: boolean;
112
114
  }
113
115
  /**
114
- * 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.
116
+ * What the camera is riding along with now: the body or satellite, how (`from`, `follow` or `above`), where it looks, the facing it looks round from (`null` when none was chosen), and the distance kept for a satellite.
115
117
  *
116
118
  * @example
117
119
  * ```ts no-run
@@ -125,12 +127,16 @@ export interface Riding {
125
127
  target: RideTarget;
126
128
  view: "from" | "follow" | "above";
127
129
  look: RideLook;
130
+ face: RideFace | null;
128
131
  distanceKm: number;
129
132
  }
130
133
  type SatelliteStats = {
131
134
  groups: number;
132
135
  placed: number;
136
+ segments: number;
133
137
  tooFast: boolean;
138
+ dotScale: number;
139
+ epochMs: number;
134
140
  propagations: number;
135
141
  lastBatchMs: number;
136
142
  maxBatchMs: number;
@@ -358,6 +364,19 @@ export declare class ChikyuSpace extends HTMLElement {
358
364
  * @param options - `view`, `look`, `distanceKm`, `smooth` (see `RideOptions`).
359
365
  */
360
366
  ride(target: RideTarget | null, options?: RideOptions): void;
367
+ /**
368
+ * Face one way while riding: `ahead` along the way it goes, `behind`, `left` or `right` (as seen facing ahead), `down` straight at the Earth, `up` straight away from it.
369
+ * In the `above` view, `down` looks straight down at the satellite and the Earth below it. The camera glides there in half a second (at once for a reader who asked for reduced motion) and keeps the zoom.
370
+ * The facing stays pressed until the view is turned or tipped. `chikyu-ride-face` is sent with `{ face }` (`null` when it is let go). Keys, while the element is focused: W ahead, S behind, A left, D right, R up, F down. The arrow keys stay with the view controls.
371
+ *
372
+ * @param face - The way to face.
373
+ * Following a body (a planet, the Moon) there is no way to face: it returns `false`. Held keys do not repeat, and keys typed in a field or in editable text are left to it.
374
+ *
375
+ * @returns Whether the camera faces that way now (`true` too when it already did, and nothing moves).
376
+ */
377
+ face(face: RideFace): boolean;
378
+ /** The facing (`face`), while the view has not been turned or tipped from it; `null` otherwise. */
379
+ get facing(): RideFace | null;
361
380
  /**
362
381
  * The satellites the page has a model for (`setSatellitePainter`) in the groups now set, each with its name in the page's language: the large satellites that can be followed as a model. Empty with no painter.
363
382
  */
@@ -379,10 +398,15 @@ export declare class ChikyuSpace extends HTMLElement {
379
398
  } | null;
380
399
  /** What the camera is riding along with now, or null. */
381
400
  get riding(): Riding | null;
401
+ /**
402
+ * Colour each satellite by its orbit class (low, medium, geostationary, highly elliptical, other). Off by default, so a group keeps the colour it was given. The attribute is `satellite-tint="orbit"`.
403
+ */
404
+ get satelliteTint(): "off" | "orbit";
405
+ set satelliteTint(value: "off" | "orbit");
382
406
  /**
383
407
  * 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
384
408
  * 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).
385
- * 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`.
409
+ * The groups are placed by SGP4 about once a second and interpolated between. Above `MAX_SATELLITE_SPEED` each satellite is a short streak along its orbit instead of being hidden.
386
410
  *
387
411
  * @param group - The group's name, for `showSatellites`, `selectSatellite` and the events.
388
412
  * @param satellites - The group, or `null` to remove it.
@@ -427,7 +451,7 @@ export declare class ChikyuSpace extends HTMLElement {
427
451
  visible: boolean;
428
452
  heightKm: number;
429
453
  } | null;
430
- /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period); undefined if it cannot be placed then. */
454
+ /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period, and `ownerCountry` when the owner is one country); undefined if it cannot be placed then. */
431
455
  satelliteInfo(ref: SatelliteRef): SatelliteInfo | undefined;
432
456
  /** The words shown beside each body, for a page in another language (`{ Mars: "火星" }`). A body left out keeps its English name. */
433
457
  get bodyNames(): Partial<Record<BodyName, string>>;
@@ -462,6 +486,7 @@ export declare class ChikyuSpace extends HTMLElement {
462
486
  riding: boolean;
463
487
  lost: boolean;
464
488
  gliding: boolean;
489
+ facing: RideFace | null;
465
490
  };
466
491
  /** The camera as the last draw left it: its place in Earth radii from the Earth's centre, the way it is turned (a unit quaternion, x y z w) and its field of view in degrees. */
467
492
  camera: {
@@ -20,10 +20,9 @@ import { IMMERSIVE_STYLE, immersiveWheel } from "../realistic/immersive.js";
20
20
  import { readMeteorStrength } from "../meteors/strength.js";
21
21
  import { METEOR_NOTE_STYLE, prefersLessMotion, setMeteorNote } from "../meteors/note.js";
22
22
  import { MAX_TEXTURE } from "../realistic/tiers.js";
23
- import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
24
23
  import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt } from "./ephemeris.js";
25
24
  import { MAX_ORBIT_GROUP } from "./satellite-layer.js";
26
- import { rideTiltLimits, rideTurnDegrees } from "./ride.js";
25
+ import { RIDE_FACES, rideTiltLimits, rideTurnDegrees } from "./ride.js";
27
26
  import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
28
27
  import { BODY_NAMES, createSpaceItem, DEFAULT_EARTH_SIZE, newSpaceModel } from "./scene.js";
29
28
  export { BODY_NAMES };
@@ -65,6 +64,7 @@ export function setSatellitePainter(next) {
65
64
  /** Mean radii in kilometres (IAU), for what a click tells. */
66
65
  const RADIUS_KM = { Sun: 695_700, Mercury: 2439.7, Venus: 6051.8, Earth: 6371, Moon: 1737.4, Mars: 3389.5, Jupiter: 69_911, Saturn: 58_232, Uranus: 25_362, Neptune: 24_622, Pluto: 1188.3 };
67
66
  export { setThreeLoader };
67
+ const FACE_KEYS = { w: "ahead", s: "behind", a: "left", d: "right", r: "up", f: "down" };
68
68
  /** A `light` attribute: `lit` or `boost`, else the true sun. */
69
69
  const readLight = (value) => (value === "lit" || value === "boost" ? value : "sun");
70
70
  const RAD = Math.PI / 180;
@@ -139,7 +139,7 @@ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:h
139
139
  * ```
140
140
  */
141
141
  export class ChikyuSpace extends HTMLElement {
142
- static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "bodies-credit"];
142
+ static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "bodies-credit", "satellite-tint"];
143
143
  #model = newSpaceModel();
144
144
  #mode = "now";
145
145
  #speed = 1;
@@ -184,16 +184,22 @@ export class ChikyuSpace extends HTMLElement {
184
184
  #tiers = {};
185
185
  #hands;
186
186
  #ridden = {};
187
+ #toldFacing = null;
187
188
  #placeLayer;
188
189
  #placeList = [];
189
190
  /** Counts the turns to a place, so a new one stops the one before. */
190
191
  #placeGlide = 0;
191
192
  #nameBoxes = new Map();
193
+ /** A font that arrives after the names were measured: the boxes are read again on the next layout. The satellites' marks are not touched, or the page would be told again about each one already in view. */
194
+ #onFonts = () => {
195
+ this.#nameBoxes.clear();
196
+ };
192
197
  /** The controller behind the element's own hands (`set`, `fit`, `state`), while it is in a page. */
193
198
  get controller() {
194
199
  return this.#hands?.controller;
195
200
  }
196
201
  connectedCallback() {
202
+ document.fonts?.addEventListener?.("loadingdone", this.#onFonts);
197
203
  this.#model.centre = readCentre(this.getAttribute("center")) ?? this.#model.centre;
198
204
  this.#mode = readTime(this.getAttribute("time"));
199
205
  this.#model.time = this.#mode === "now" ? Date.now() : this.#mode;
@@ -314,16 +320,24 @@ export class ChikyuSpace extends HTMLElement {
314
320
  this.addEventListener("pointerdown", this.#down);
315
321
  // before the shared hands (which hear it after this): a plain wheel in an immersive view zooms
316
322
  this.addEventListener("wheel", this.#wheel, { capture: true, passive: false });
323
+ this.addEventListener("keydown", this.#faceKey);
324
+ if (!this.hasAttribute("tabindex"))
325
+ this.tabIndex = 0;
317
326
  this.#hands = carryControls(this, { initial: this.#model.view, limits: LIMITS, onChange: (state, info) => this.setView(state, info.final) });
318
327
  this.#labelBox.addEventListener("click", this.#labelClick);
319
328
  this.#labelBox.addEventListener("focusin", this.#labelFocus);
320
329
  }
321
330
  disconnectedCallback() {
331
+ document.fonts?.removeEventListener?.("loadingdone", this.#onFonts);
332
+ this.#marks = [];
333
+ this.#markSeen.clear();
334
+ this.#nameBoxes.clear();
322
335
  this.#hands?.unbind();
323
336
  this.#hands = undefined;
324
337
  this.#zoomRange(false);
325
338
  this.removeEventListener("pointerdown", this.#down);
326
339
  this.removeEventListener("wheel", this.#wheel, { capture: true });
340
+ this.removeEventListener("keydown", this.#faceKey);
327
341
  window.removeEventListener("pointerup", this.#up, true);
328
342
  clearTimeout(this.#timer);
329
343
  this.#timer = undefined;
@@ -418,6 +432,10 @@ export class ChikyuSpace extends HTMLElement {
418
432
  }
419
433
  else if (COUNTRY_NAMES_ATTRIBUTES.includes(name))
420
434
  this.#countries?.refresh();
435
+ else if (name === "satellite-tint") {
436
+ this.#model.satellites.orbitTint = value === "orbit";
437
+ this.#gate?.request();
438
+ }
421
439
  if (name === "air-thickness" || name === "air-label" || name === "lang")
422
440
  setAirNote(this.#airNote, this, this.#model.airThickness);
423
441
  if (name === "bodies-credit" || name === "lang")
@@ -890,6 +908,7 @@ export class ChikyuSpace extends HTMLElement {
890
908
  return;
891
909
  }
892
910
  this.#gate?.request();
911
+ this.#tellFacing();
893
912
  }
894
913
  /**
895
914
  * The controls that are driving this view: a `<kazoku-view-controls for="...">` bound to it (its hands are then the only ones and its controller holds the yaw and tilt), else the element's own hands.
@@ -945,7 +964,15 @@ export class ChikyuSpace extends HTMLElement {
945
964
  const asked = options.view ?? "from";
946
965
  // above a body is meant for a satellite: a body is followed
947
966
  const view = typeof target === "string" && (target === "Earth" || asked === "above") ? "follow" : asked;
948
- 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) };
967
+ // a body followed (a planet, the Moon, the Earth) is looked at from round it as the view turns: it has no ways to face
968
+ const faceable = !(view === "follow" && typeof target === "string");
969
+ const face = faceable && options.face && RIDE_FACES.includes(options.face) ? options.face : null;
970
+ model.ride = { target: typeof target === "string" ? target : { group: target.group, index: target.index }, view, look: face && view === "from" ? "horizon" : (options.look ?? "down"), face, distanceKm: Math.max(100, options.distanceKm ?? 3000) };
971
+ if (face) {
972
+ model.view = { yaw: 0, tilt: 0, zoom: model.view.zoom };
973
+ model.rideTurn = 0;
974
+ this.#controls()?.set({ yaw: 0, tilt: 0, zoom: model.view.zoom }, true, "ride");
975
+ }
949
976
  if (typeof target === "string" && view === "follow")
950
977
  model.focus = target;
951
978
  else if (wasRiding)
@@ -959,7 +986,71 @@ export class ChikyuSpace extends HTMLElement {
959
986
  this.#schedule();
960
987
  this.#gate?.request();
961
988
  this.dispatchEvent(new CustomEvent("chikyu-ride", { detail: this.riding }));
989
+ this.#tellFacing();
962
990
  }
991
+ /**
992
+ * Face one way while riding: `ahead` along the way it goes, `behind`, `left` or `right` (as seen facing ahead), `down` straight at the Earth, `up` straight away from it.
993
+ * In the `above` view, `down` looks straight down at the satellite and the Earth below it. The camera glides there in half a second (at once for a reader who asked for reduced motion) and keeps the zoom.
994
+ * The facing stays pressed until the view is turned or tipped. `chikyu-ride-face` is sent with `{ face }` (`null` when it is let go). Keys, while the element is focused: W ahead, S behind, A left, D right, R up, F down. The arrow keys stay with the view controls.
995
+ *
996
+ * @param face - The way to face.
997
+ * Following a body (a planet, the Moon) there is no way to face: it returns `false`. Held keys do not repeat, and keys typed in a field or in editable text are left to it.
998
+ *
999
+ * @returns Whether the camera faces that way now (`true` too when it already did, and nothing moves).
1000
+ */
1001
+ face(face) {
1002
+ const model = this.#model;
1003
+ const ride = model.ride;
1004
+ if (!ride || !RIDE_FACES.includes(face))
1005
+ return false;
1006
+ // following a body there is no way to face: only from a body or a satellite, following a satellite, or above it
1007
+ if (ride.view === "follow" && typeof ride.target === "string")
1008
+ return false;
1009
+ // already facing that way: nothing to turn, and no glide started again
1010
+ if (this.facing === face)
1011
+ return true;
1012
+ const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
1013
+ const pose = model.pose;
1014
+ const zoom = model.view.zoom;
1015
+ model.ride = { ...ride, look: ride.view === "from" ? "horizon" : ride.look, face };
1016
+ model.view = { yaw: 0, tilt: 0, zoom };
1017
+ model.rideTurn = 0;
1018
+ this.#controls()?.set({ yaw: 0, tilt: 0, zoom }, true, "ride");
1019
+ model.rideTurn = 0;
1020
+ model.view = { yaw: 0, tilt: 0, zoom };
1021
+ model.transition = !reduced && pose.valid ? { start: performance.now(), duration: 500, 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;
1022
+ this.#last = performance.now();
1023
+ this.#schedule();
1024
+ this.#gate?.request();
1025
+ this.#tellFacing();
1026
+ return true;
1027
+ }
1028
+ /** The facing (`face`), while the view has not been turned or tipped from it; `null` otherwise. */
1029
+ get facing() {
1030
+ const ride = this.#model.ride;
1031
+ const view = this.#model.view;
1032
+ return ride?.face && view.yaw === 0 && view.tilt === 0 ? ride.face : null;
1033
+ }
1034
+ #tellFacing() {
1035
+ const now = this.facing;
1036
+ if (now === this.#toldFacing)
1037
+ return;
1038
+ this.#toldFacing = now;
1039
+ this.dispatchEvent(new CustomEvent("chikyu-ride-face", { detail: { face: now } }));
1040
+ }
1041
+ /** W ahead, S behind, A left, D right, R up, F down, while this element is focused and a ride is on. */
1042
+ #faceKey = (event) => {
1043
+ // a held key repeats: the first press turns, the repeats would only start the glide again and again
1044
+ if (event.ctrlKey || event.metaKey || event.altKey || event.defaultPrevented || event.repeat)
1045
+ return;
1046
+ // typing in a field anywhere on the way to this element (its own shadow root and slots included), or in editable text, is typing, not facing
1047
+ const typing = event.composedPath().some((node) => node instanceof HTMLElement && (node.matches("input, textarea, select") || node.isContentEditable));
1048
+ if (typing)
1049
+ return;
1050
+ const face = FACE_KEYS[event.key.toLowerCase()];
1051
+ if (face && this.face(face))
1052
+ event.preventDefault();
1053
+ };
963
1054
  /** From a body the zoom only narrows the field a little, so the range is 0.5 to 6: the `zoom-min` and `zoom-max` attributes, unless the page set them itself. */
964
1055
  #zoomRange(from) {
965
1056
  for (const name of ["zoom-min", "zoom-max"]) {
@@ -1021,10 +1112,22 @@ export class ChikyuSpace extends HTMLElement {
1021
1112
  this.dispatchEvent(new CustomEvent("chikyu-ride-lost", { detail: this.riding }));
1022
1113
  }
1023
1114
  // --- satellites ---------------------------------------------------------------------------------------------------------------------------------
1115
+ /**
1116
+ * Colour each satellite by its orbit class (low, medium, geostationary, highly elliptical, other). Off by default, so a group keeps the colour it was given. The attribute is `satellite-tint="orbit"`.
1117
+ */
1118
+ get satelliteTint() {
1119
+ return this.#model.satellites.orbitTint ? "orbit" : "off";
1120
+ }
1121
+ set satelliteTint(value) {
1122
+ if (value === "orbit")
1123
+ this.setAttribute("satellite-tint", "orbit");
1124
+ else
1125
+ this.removeAttribute("satellite-tint");
1126
+ }
1024
1127
  /**
1025
1128
  * 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
1026
1129
  * 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).
1027
- * 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`.
1130
+ * The groups are placed by SGP4 about once a second and interpolated between. Above `MAX_SATELLITE_SPEED` each satellite is a short streak along its orbit instead of being hidden.
1028
1131
  *
1029
1132
  * @param group - The group's name, for `showSatellites`, `selectSatellite` and the events.
1030
1133
  * @param satellites - The group, or `null` to remove it.
@@ -1163,7 +1266,7 @@ export class ChikyuSpace extends HTMLElement {
1163
1266
  }
1164
1267
  this.#markSeen = now;
1165
1268
  }
1166
- /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period); undefined if it cannot be placed then. */
1269
+ /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period, and `ownerCountry` when the owner is one country); undefined if it cannot be placed then. */
1167
1270
  satelliteInfo(ref) {
1168
1271
  return this.#model.satellites.groups.get(ref.group)?.satellites.info(ref.index, this.#model.time);
1169
1272
  }
@@ -1227,7 +1330,7 @@ export class ChikyuSpace extends HTMLElement {
1227
1330
  time: this.#model.time,
1228
1331
  lookups: this.#model.lookups,
1229
1332
  satellites: this.#satelliteStats(),
1230
- ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null },
1333
+ ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null, facing: this.facing },
1231
1334
  camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], quaternion: [this.#model.pose.q[0], this.#model.pose.q[1], this.#model.pose.q[2], this.#model.pose.q[3]], fov: this.#model.pose.fov },
1232
1335
  bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons, held: this.#model.painted.held, moon: this.#model.painted.moon, tiles: this.#model.painted.tiles },
1233
1336
  meteors: { on: this.#model.meteors.on, strength: this.#model.meteors.strength, ...this.#model.meteors.drawn },
@@ -1251,7 +1354,10 @@ export class ChikyuSpace extends HTMLElement {
1251
1354
  lastBatchMs = Math.max(lastBatchMs, group.satellites.timing.lastBatchMs);
1252
1355
  maxBatchMs = Math.max(maxBatchMs, group.satellites.timing.maxBatchMs);
1253
1356
  }
1254
- 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 };
1357
+ let epochMs = 0;
1358
+ for (const group of this.#model.satellites.groups.values())
1359
+ epochMs = Math.max(epochMs, group.satellites.newestEpochMs);
1360
+ return { groups: this.#model.satellites.groups.size, placed: drawn.placed, segments: drawn.segments, tooFast: drawn.tooFast, dotScale: drawn.dotScale, epochMs, propagations, lastBatchMs, maxBatchMs, updateMs: drawn.updateMs, maxUpdateMs: drawn.maxUpdateMs, averageUpdateMs: drawn.updates ? drawn.totalMs / drawn.updates : 0, updates: drawn.updates };
1255
1361
  }
1256
1362
  // --- the game clock ----------------------------------------------------------------------------------------------------------------------------
1257
1363
  #readSpeed() {
@@ -1259,10 +1365,8 @@ export class ChikyuSpace extends HTMLElement {
1259
1365
  const value = raw === null || raw === "" ? 1 : Number(raw);
1260
1366
  return Number.isFinite(value) ? value : 1;
1261
1367
  }
1262
- /** Is anything on show that moves faster than the Earth turns: a group of satellites the clock is slow enough to place? */
1368
+ /** Is anything on show that moves faster than the Earth turns: a group of satellites, including above the interpolation limit where they are drawn as streaks? */
1263
1369
  #satellitesMoving() {
1264
- if (Math.abs(this.#speed) > MAX_SATELLITE_SPEED)
1265
- return false;
1266
1370
  for (const group of this.#model.satellites.groups.values())
1267
1371
  if (group.visible && group.satellites.count > 0)
1268
1372
  return true;
@@ -1,6 +1,6 @@
1
1
  export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, orbitPath, PLANETS, type Frame, type PlanetName, type Vec3 } from "./ephemeris.ts";
2
2
  export { compress, MOON_COMPRESSED, placeAround, placeMoon, placeSun, RADIUS, SUN_COMPRESSED, truePosition, type ScaleMode } from "./scale.ts";
3
3
  export { fitDistance, plainPainter, type BodyDrawing, type BodyMoon, type BodyPainter, type BodyView, type PaintContext, type SatellitePainter } from "./scene.ts";
4
- export { RIDE_FOV, rideFov, ridePose, rideTiltLimits, rideTurnDegrees, type RideInput, type RideLook, type RidePose } from "./ride.ts";
4
+ export { faceOffset, RIDE_FACES, RIDE_FOV, rideFov, ridePose, rideTiltLimits, rideTurnDegrees, type RideFace, type RideInput, type RideLook, type RidePose } from "./ride.ts";
5
5
  export type { SatelliteScreen } from "./satellite-layer.ts";
6
6
  export { aboveAxes, MODEL_RADIUS_SHARE, modelMatrix, modelRadius, satelliteAxes } from "./satellite-model.ts";
@@ -3,5 +3,5 @@
3
3
  export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, orbitPath, PLANETS } from "./ephemeris.js";
4
4
  export { compress, MOON_COMPRESSED, placeAround, placeMoon, placeSun, RADIUS, SUN_COMPRESSED, truePosition } from "./scale.js";
5
5
  export { fitDistance, plainPainter } from "./scene.js";
6
- export { RIDE_FOV, rideFov, ridePose, rideTiltLimits, rideTurnDegrees } from "./ride.js";
6
+ export { faceOffset, RIDE_FACES, RIDE_FOV, rideFov, ridePose, rideTiltLimits, rideTurnDegrees } from "./ride.js";
7
7
  export { aboveAxes, MODEL_RADIUS_SHARE, modelMatrix, modelRadius, satelliteAxes } from "./satellite-model.js";
@@ -23,6 +23,46 @@ export declare const RIDE_FOV = 60;
23
23
  * ```
24
24
  */
25
25
  export type RideLook = "down" | "horizon";
26
+ /**
27
+ * A way to face while riding, as from the windows of a plane or a boat: `ahead` along the way it goes, `behind` the opposite, `left` and `right` across that way as seen facing ahead, `down` straight at the Earth and `up` straight away from it.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { RIDE_FACES, type RideFace } from "@johnmorrisdotca/chikyu-earth/space";
32
+ *
33
+ * const face: RideFace = "ahead";
34
+ * console.log(RIDE_FACES.includes(face));
35
+ * ```
36
+ */
37
+ export type RideFace = "ahead" | "behind" | "left" | "right" | "down" | "up";
38
+ /**
39
+ * Every facing, in the order of a row of buttons.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { RIDE_FACES } from "@johnmorrisdotca/chikyu-earth/space";
44
+ *
45
+ * console.log(RIDE_FACES.join(" "));
46
+ * ```
47
+ */
48
+ export declare const RIDE_FACES: readonly RideFace[];
49
+ /**
50
+ * Yaw and tilt, in radians, that put a camera looking at a satellite on a facing. `down` is straight above it, looking down at it and the Earth. `ahead` looks along the way it goes.
51
+ *
52
+ * @param face - The facing.
53
+ * @returns The yaw and tilt to give `aboveAxes`.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * import { faceOffset } from "@johnmorrisdotca/chikyu-earth/space";
58
+ *
59
+ * console.log(faceOffset("down").tilt, faceOffset("ahead").tilt > 1);
60
+ * ```
61
+ */
62
+ export declare function faceOffset(face: RideFace): {
63
+ yaw: number;
64
+ tilt: number;
65
+ };
26
66
  /**
27
67
  * The field of view, in degrees, of a riding camera at a zoom: the natural 60 divided by the zoom, held between 5 and 100.
28
68
  *
@@ -101,6 +141,8 @@ export interface RideInput {
101
141
  * The heading in degrees, accumulated by the caller (see `rideTurnDegrees`): used in place of `yaw` when given, so a turn of more than half a way round is not undone by the controls wrapping their yaw, and a change of zoom does not swing it.
102
142
  */
103
143
  turn?: number;
144
+ /** In the `horizon` look, the facing the yaw and tilt look round from. `ahead` when not given. */
145
+ face?: RideFace;
104
146
  }
105
147
  /**
106
148
  * The camera `ridePose` works out: where it is, which way it looks, which way is up in the picture, its field of view in degrees, and how big the Earth looks from there (its angular radius in degrees).