@johnmorrisdotca/chikyu-earth 0.55.0 → 0.57.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.
@@ -38,7 +38,8 @@ import { COUNTRY_NAMES_ATTRIBUTES } from "../country-names/geometry.js";
38
38
  import { COUNTRY_NAMES_STYLE, createCountryHost } from "../country-names/host.js";
39
39
  import { SEA_NAMES_ATTRIBUTES, readSeaNames } from "../sea-names/geometry.js";
40
40
  import { SEA_NAMES_STYLE, createSeaHost } from "../sea-names/host.js";
41
- import { createGate, frameCap } from "./gate.js";
41
+ import { createGate, frameCap, smallDevice } from "./gate.js";
42
+ import { framesPerSecond, readSmoothFps, smoothCap, SMOOTH_UP_TO, waitFor, watchLowBattery } from "./pace.js";
42
43
  import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
43
44
  export { setSharedRenderer, setThreeLoader };
44
45
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
@@ -165,12 +166,16 @@ export const readTime = (value) => {
165
166
  * ```
166
167
  */
167
168
  export class ChikyuEarthRealistic extends HTMLElement {
168
- static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "tiles-finer", "tiles-finer-layer", "tiles-finer-date", "tiles-finer-timeout", "data", "camera", "immersive", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, ...SEA_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "here-city", "route", "satellite-tint", "satellite-streak-max", "hover-path", "names-on-hover", "selected-path", "path-light", "path-hit", "path-priority", "estimate-far"];
169
+ static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "smooth-fps", "tiles", "tiles-finer", "tiles-finer-layer", "tiles-finer-date", "tiles-finer-timeout", "data", "camera", "immersive", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, ...SEA_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "here-city", "route", "satellite-tint", "satellite-streak-max", "hover-path", "names-on-hover", "selected-path", "path-light", "path-hit", "path-priority", "estimate-far"];
169
170
  #model = newModel();
170
171
  #paint = createPaintState();
171
172
  #mode = "now";
172
173
  #view;
173
174
  #gate;
175
+ /** Whether the battery is low (at 20% or less and not charging): the smooth frame rate is halved. */
176
+ #lowBattery = false;
177
+ /** What `#wait` last worked out, for `stats`. */
178
+ #pace = { pixelsPerSecond: 0, perSecond: 0, cap: 0, waitMs: 0 };
174
179
  #tick;
175
180
  /** The clock's speed when `speed` is given (attribute or property); `null` follows `time`: real time for "now", held for a date. */
176
181
  #speed = null;
@@ -310,10 +315,12 @@ export class ChikyuEarthRealistic extends HTMLElement {
310
315
  const nav = navigator;
311
316
  const cap = frameCap(30, { deviceMemory: nav.deviceMemory, hardwareConcurrency: nav.hardwareConcurrency });
312
317
  this.#gate = createGate(1000 / cap, () => this.#view?.invalidate());
313
- nav.getBattery?.().then((battery) => {
314
- if (!battery.charging && battery.level <= 0.2)
315
- this.#gate?.setMinMs(1000 / Math.min(cap, 15));
316
- }, () => undefined);
318
+ this.#lowBattery = false;
319
+ watchLowBattery(nav, () => {
320
+ this.#lowBattery = true;
321
+ this.#gate?.setMinMs(1000 / Math.min(cap, 15));
322
+ this.#startTick();
323
+ });
317
324
  const maxRatio = readRatio(this.getAttribute("max-ratio"));
318
325
  if (maxRatio)
319
326
  this.#model.ratio = () => Math.min(globalThis.devicePixelRatio || 1, 2, maxRatio);
@@ -473,7 +480,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
473
480
  this.lights = value !== "off";
474
481
  else if (name === "light")
475
482
  this.light = readLight(value);
476
- else if (name === "live-seconds")
483
+ else if (name === "live-seconds" || name === "smooth-fps")
477
484
  this.#startTick();
478
485
  else if (name === "tiles" || name === "tiles-finer" || name === "tiles-finer-layer" || name === "tiles-finer-date" || name === "tiles-finer-timeout")
479
486
  this.#gate?.soon();
@@ -1219,6 +1226,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
1219
1226
  state: this.#state,
1220
1227
  tiers: { ...this.#tiers },
1221
1228
  satellites: this.#satelliteStats(),
1229
+ pace: { ...this.#pace },
1222
1230
  lightFade: { mix: this.#model.lightFade.mix, fading: this.#model.lightFade.fading },
1223
1231
  paths: this.#pathControls?.stats() ?? emptyPathStats(),
1224
1232
  tiles: this.#model.tiles?.stats ?? { ready: false, level: null, held: 0, shown: 0, loading: 0, failed: 0, requested: 0, heldBytes: 0, refused: 0, used: {}, finer: null, fading: false },
@@ -1270,6 +1278,27 @@ export class ChikyuEarthRealistic extends HTMLElement {
1270
1278
  else
1271
1279
  this.removeAttribute("satellite-tint");
1272
1280
  }
1281
+ /**
1282
+ * The most steps a second drawn for a clock at real time, or up to 60 times it (the attribute `smooth-fps`; 15 when the page says nothing; 1 to 30). The picture is drawn each time the quickest thing in it (the Sun's turn at this zoom, a satellite dot)
1283
+ * has moved half a pixel, at least once a second while satellites are on show, and at most this many. Half as many on a small device or a battery at 20% or lower; one a second for a reader who asked for reduced motion.
1284
+ *
1285
+ * @example
1286
+ * ```ts
1287
+ * import "@johnmorrisdotca/chikyu-earth/realistic/element";
1288
+ *
1289
+ * const earth = document.querySelector("chikyu-earth-realistic")!;
1290
+ * earth.smoothFps = 24;
1291
+ * ```
1292
+ */
1293
+ get smoothFps() {
1294
+ return readSmoothFps(this.getAttribute("smooth-fps"));
1295
+ }
1296
+ set smoothFps(value) {
1297
+ if (Number.isFinite(value) && value > 0)
1298
+ this.setAttribute("smooth-fps", String(value));
1299
+ else
1300
+ this.removeAttribute("smooth-fps");
1301
+ }
1273
1302
  /**
1274
1303
  * The longest a satellite's streak may be on the screen, in CSS pixels (the attribute `satellite-streak-max`; 8 when the page says nothing; `0` or `off` for no cap). Above 60 times real time each satellite is drawn as a streak along its orbit
1275
1304
  * for the stretch one frame spans, and at a fast clock that stretch is long: at an hour a second a low satellite would cross a tenth of the Earth in one frame. The cap is a length on the screen, so a low and a high satellite are drawn equally long, and the streak keeps the look it has at 10 minutes a second at any speed. It is the smaller of this number of pixels and 0.025 of the Earth's drawn radius (about 160 km of orbit, what a low satellite covers in a frame at 10 minutes a second), so as the Earth is drawn smaller the streak shrinks in proportion, to a dot, instead of staying as long on a small Earth as on a large one. The marks also lose weight on a small Earth: below a drawn radius of 150 pixels the streaks are fainter and the dark rim of the dots fades, gone at 40 pixels, and a crowd of satellites on a small Earth is drawn fainter in proportion so thousands of them do not wash it. Pointing along the orbit and ending at the satellite, it is the same length at any frame rate. Off restores the whole stretch.
@@ -1678,19 +1707,33 @@ export class ChikyuEarthRealistic extends HTMLElement {
1678
1707
  this.#model.time += (now - this.#last) * this.speed;
1679
1708
  this.#last = now;
1680
1709
  }
1681
- /** The wait before the next step: real time every `live-seconds` (a minute by default); faster time as often as the Sun's turn moves a pixel, 1 to 30 times a second (once a second for a reader who prefers reduced motion). */
1710
+ /** The quickest a satellite on show goes, in Earth radii for each second of game time: the quickest the groups report between their two SGP4 moments, or, before they have any (and above the interpolation limit, where they do not), a low orbit's. */
1711
+ #satelliteRate() {
1712
+ let most = 0;
1713
+ for (const [name, group] of this.#model.satellites.groups)
1714
+ if (satelliteEmphasis(name, group.visible, this.#model.satellites.focus).drawn)
1715
+ most = Math.max(most, group.satellites.fastest);
1716
+ return most > 0 && Math.abs(this.speed) <= SMOOTH_UP_TO ? most : SATELLITE_RATE * RAD;
1717
+ }
1718
+ /**
1719
+ * The wait before the next step: a step each time the quickest thing in the picture has moved half a pixel (the Sun's turn at this zoom, or a satellite dot: the quickest of the groups on show, from the places they hold for the interpolation),
1720
+ * at most `smooth-fps` a second (15), half as many on a small device or a low battery, and at least once a second while satellites are on show. With only the Earth turning, real time waits up to `live-seconds` (a minute by default).
1721
+ * A reader who asked for reduced motion gets one a second at most. Faster than 60 times real time it is a step for each pixel, up to 30 a second.
1722
+ */
1682
1723
  #wait() {
1683
1724
  const seconds = Number(this.getAttribute("live-seconds"));
1684
1725
  const live = Number.isFinite(seconds) && seconds > 0 ? Math.max(MIN_TICK_MS, seconds * 1000) : LIVE_TICK_MS;
1685
1726
  const speed = Math.abs(this.speed);
1686
1727
  const satellites = this.#satellitesMoving();
1687
- // satellites go round in 90 minutes, so with any on show even real time is drawn about once a second
1688
- if (speed <= 1 && !satellites)
1689
- return live;
1690
- if (typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches)
1691
- return Math.min(live, 1000);
1692
1728
  const radius = this.#model.drawn?.radius ?? 200;
1693
- return Math.min(live, 1000 / Math.min(30, Math.max(1, (satellites ? SATELLITE_RATE : SUN_RATE) * RAD * speed * radius)));
1729
+ const pixelsPerSecond = Math.max(SUN_RATE * RAD * speed * radius, satellites ? this.#satelliteRate() * speed * radius : 0);
1730
+ const nav = navigator;
1731
+ const cap = smoothCap(this.smoothFps, this.#lowBattery || smallDevice({ deviceMemory: nav.deviceMemory, hardwareConcurrency: nav.hardwareConcurrency }));
1732
+ const perSecond = framesPerSecond({ pixelsPerSecond, speed: this.speed, cap, reduced: prefersLessMotion(), always: satellites });
1733
+ // a hidden tab is not drawn: it is looked at once a second, as the browser would have it anyway
1734
+ const wait = Math.max(waitFor(perSecond, live), document.visibilityState === "hidden" ? 1000 : 0);
1735
+ this.#pace = { pixelsPerSecond, perSecond, cap, waitMs: wait };
1736
+ return wait;
1694
1737
  }
1695
1738
  /** 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? */
1696
1739
  #satellitesMoving() {
@@ -71,3 +71,8 @@ export declare function frameCap(maxFps?: number, device?: {
71
71
  deviceMemory?: number;
72
72
  hardwareConcurrency?: number;
73
73
  }): number;
74
+ /** Whether this is a small device: 2 GB of memory or less, or 2 cores or fewer (`deviceMemory` and `hardwareConcurrency` from `navigator`, either may be left out). */
75
+ export declare function smallDevice(device?: {
76
+ deviceMemory?: number;
77
+ hardwareConcurrency?: number;
78
+ }): boolean;
@@ -88,6 +88,9 @@ export function createGate(minMs, fire, timers = browserTimers) {
88
88
  * ```
89
89
  */
90
90
  export function frameCap(maxFps = 30, device = {}) {
91
- const small = (device.deviceMemory !== undefined && device.deviceMemory <= 2) || (device.hardwareConcurrency !== undefined && device.hardwareConcurrency <= 2);
92
- return Math.max(1, small ? Math.min(maxFps, 20) : maxFps);
91
+ return Math.max(1, smallDevice(device) ? Math.min(maxFps, 20) : maxFps);
92
+ }
93
+ /** Whether this is a small device: 2 GB of memory or less, or 2 cores or fewer (`deviceMemory` and `hardwareConcurrency` from `navigator`, either may be left out). */
94
+ export function smallDevice(device = {}) {
95
+ return (device.deviceMemory !== undefined && device.deviceMemory <= 2) || (device.hardwareConcurrency !== undefined && device.hardwareConcurrency <= 2);
93
96
  }
@@ -1,6 +1,7 @@
1
1
  export { greenwichSidereal, subsolarPoint, unitVector, julianDay } from "./sun.ts";
2
2
  export { chooseTier, textureBytes, textureCap, MAX_TEXTURE, TIERS, TEXELS_PER_RADIUS_PIXEL, type Layer } from "./tiers.ts";
3
3
  export { createGate, frameCap, type Gate } from "./gate.ts";
4
+ export { framesPerSecond, readSmoothFps, smoothCap, waitFor, watchLowBattery } from "./pace.ts";
4
5
  export { lookAt, discRadius, ATMOSPHERE_OUTER, cameraCentre, type CameraMode, type LightMode } from "./earth.ts";
5
6
  export type { ThreeParts } from "./earth.ts";
6
7
  export { TEXEL_SLACK, coveringTile, gridTilesInView, parseManifest, pointOnEarth, tileColumns, tileLevel, tileRect, tileRows, tilesInView, type TileCamera, type TileId, type TileLayer, type TilePerspective, type VisibleTile } from "./tiles.ts";
@@ -3,6 +3,7 @@
3
3
  export { greenwichSidereal, subsolarPoint, unitVector, julianDay } from "./sun.js";
4
4
  export { chooseTier, textureBytes, textureCap, MAX_TEXTURE, TIERS, TEXELS_PER_RADIUS_PIXEL } from "./tiers.js";
5
5
  export { createGate, frameCap } from "./gate.js";
6
+ export { framesPerSecond, readSmoothFps, smoothCap, waitFor, watchLowBattery } from "./pace.js";
6
7
  export { lookAt, discRadius, ATMOSPHERE_OUTER, cameraCentre } from "./earth.js";
7
8
  export { TEXEL_SLACK, coveringTile, gridTilesInView, parseManifest, pointOnEarth, tileColumns, tileLevel, tileRect, tileRows, tilesInView } from "./tiles.js";
8
9
  export { TILE_KEEP_MS, TILE_LIMIT } from "./tile-set.js";
@@ -0,0 +1,98 @@
1
+ /** The most frames a second a clock at real time (or up to 60 times it) draws by default: `smooth-fps` changes it. */
2
+ export declare const SMOOTH_FPS = 15;
3
+ /** The most `smooth-fps` allows. */
4
+ export declare const SMOOTH_FPS_MAX = 30;
5
+ /** How far, in CSS pixels, the fastest thing on show may move between two frames before the next one is drawn: half a pixel is under what the eye reads as a step. */
6
+ export declare const SMOOTH_STEP_PX = 0.5;
7
+ /** The fastest clock, in seconds of game time for each real second, that is paced by half a pixel and the `smooth-fps` cap (at real time exactly; above it never less often than a frame a pixel). Beyond it the picture is drawn once for each pixel moved, up to 30 a second. */
8
+ export declare const SMOOTH_UP_TO = 60;
9
+ /**
10
+ * Read `smooth-fps`: a number of frames a second from 1 to 30, and 15 for nothing or anything else.
11
+ *
12
+ * @param value - The attribute's text, or `null` when it is not set.
13
+ * @returns The frames a second.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { readSmoothFps } from "@johnmorrisdotca/chikyu-earth/realistic";
18
+ *
19
+ * console.log(readSmoothFps(null), readSmoothFps("24"), readSmoothFps("500"), readSmoothFps("many"));
20
+ * ```
21
+ */
22
+ export declare function readSmoothFps(value: string | null): number;
23
+ /**
24
+ * The cap on the frames a second of a running clock for this device: `smoothFps`, or half of it (at least 1) on a small device (2 GB of memory or less, or 2 cores or fewer) or on a battery at 20% or lower that is not charging.
25
+ *
26
+ * @param smoothFps - The page's own cap (`smooth-fps`).
27
+ * @param tight - Whether the device is small or its battery low.
28
+ * @returns The frames a second to allow.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { smoothCap } from "@johnmorrisdotca/chikyu-earth/realistic";
33
+ *
34
+ * console.log(smoothCap(15, false), smoothCap(15, true));
35
+ * ```
36
+ */
37
+ export declare function smoothCap(smoothFps: number, tight: boolean): number;
38
+ /** What `framesPerSecond` reads. */
39
+ export interface PaceInput {
40
+ /** How fast the quickest thing on show moves across the screen, in CSS pixels a second of real time: the Earth's turn at this zoom, a satellite dot, the ridden craft and the camera in a ride. */
41
+ pixelsPerSecond: number;
42
+ /** The clock's speed, in seconds of game time for each real second. */
43
+ speed: number;
44
+ /** The most frames a second from `smoothCap`. */
45
+ cap: number;
46
+ /** A reader who asked for reduced motion: at most one a second. */
47
+ reduced?: boolean;
48
+ /** Something moves that the Earth's own turn does not account for (satellites on show, a ride): at least one a second. Otherwise a still picture may be drawn less often than that. */
49
+ always?: boolean;
50
+ }
51
+ /**
52
+ * How many frames a second a running clock should draw (a number below 1 means a frame less often than every second, which only a picture with nothing quick in it gets).
53
+ * At real time a frame is drawn each time the quickest thing has moved half a pixel on the screen, at most `cap` a second. Above real time, up to 60 times it, that or a frame for every pixel it moves (up to 30 a second, as it always was), whichever is more often,
54
+ * so a faster clock is never drawn less often than it was; above that a frame for every pixel, up to 30 a second. A reader who asked for reduced motion gets one a second at most. At least one a second when `always` or the clock is faster than real time.
55
+ *
56
+ * @param input - How fast things move and the limits.
57
+ * @returns Frames a second, 0 when nothing moves at all.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * import { framesPerSecond } from "@johnmorrisdotca/chikyu-earth/realistic";
62
+ *
63
+ * // a low satellite on a whole Earth, then the same zoomed in, then a reader who asked for reduced motion
64
+ * console.log(framesPerSecond({ pixelsPerSecond: 0.3, speed: 1, cap: 15, always: true }));
65
+ * console.log(framesPerSecond({ pixelsPerSecond: 6, speed: 1, cap: 15, always: true }));
66
+ * console.log(framesPerSecond({ pixelsPerSecond: 6, speed: 1, cap: 15, always: true, reduced: true }));
67
+ * ```
68
+ */
69
+ export declare function framesPerSecond(input: PaceInput): number;
70
+ /**
71
+ * The wait, in milliseconds, before the next frame at `perSecond`: never under a frame's share of a second and never over `longest`.
72
+ *
73
+ * @param perSecond - Frames a second from `framesPerSecond`.
74
+ * @param longest - The longest wait, in milliseconds (a minute at real time with nothing quick on show).
75
+ * @returns Milliseconds.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * import { waitFor } from "@johnmorrisdotca/chikyu-earth/realistic";
80
+ *
81
+ * console.log(waitFor(4, 60_000), waitFor(0, 60_000));
82
+ * ```
83
+ */
84
+ export declare function waitFor(perSecond: number, longest: number): number;
85
+ /**
86
+ * Ask the browser (where it can say) whether the battery is at 20% or lower and not charging, and tell `set` when it is. Browsers without the battery API, and a refusal, say nothing: the device counts as plugged in.
87
+ *
88
+ * @param nav - `navigator`, or anything with its `getBattery`.
89
+ * @param set - Called with `true` when the battery is low.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * import { watchLowBattery } from "@johnmorrisdotca/chikyu-earth/realistic";
94
+ *
95
+ * watchLowBattery(navigator, (low) => console.log("low battery", low));
96
+ * ```
97
+ */
98
+ export declare function watchLowBattery(nav: object, set: (low: boolean) => void): void;
@@ -0,0 +1,112 @@
1
+ // How often a running clock draws: the pure rule, with no browser in it, so a test can ask it anything. Both live views (the realistic Earth and the space view) use it.
2
+ /** The most frames a second a clock at real time (or up to 60 times it) draws by default: `smooth-fps` changes it. */
3
+ export const SMOOTH_FPS = 15;
4
+ /** The most `smooth-fps` allows. */
5
+ export const SMOOTH_FPS_MAX = 30;
6
+ /** How far, in CSS pixels, the fastest thing on show may move between two frames before the next one is drawn: half a pixel is under what the eye reads as a step. */
7
+ export const SMOOTH_STEP_PX = 0.5;
8
+ /** The fastest clock, in seconds of game time for each real second, that is paced by half a pixel and the `smooth-fps` cap (at real time exactly; above it never less often than a frame a pixel). Beyond it the picture is drawn once for each pixel moved, up to 30 a second. */
9
+ export const SMOOTH_UP_TO = 60;
10
+ /**
11
+ * Read `smooth-fps`: a number of frames a second from 1 to 30, and 15 for nothing or anything else.
12
+ *
13
+ * @param value - The attribute's text, or `null` when it is not set.
14
+ * @returns The frames a second.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { readSmoothFps } from "@johnmorrisdotca/chikyu-earth/realistic";
19
+ *
20
+ * console.log(readSmoothFps(null), readSmoothFps("24"), readSmoothFps("500"), readSmoothFps("many"));
21
+ * ```
22
+ */
23
+ export function readSmoothFps(value) {
24
+ if (value === null || value.trim() === "")
25
+ return SMOOTH_FPS;
26
+ const number = Number(value);
27
+ return Number.isFinite(number) ? Math.min(SMOOTH_FPS_MAX, Math.max(1, number)) : SMOOTH_FPS;
28
+ }
29
+ /**
30
+ * The cap on the frames a second of a running clock for this device: `smoothFps`, or half of it (at least 1) on a small device (2 GB of memory or less, or 2 cores or fewer) or on a battery at 20% or lower that is not charging.
31
+ *
32
+ * @param smoothFps - The page's own cap (`smooth-fps`).
33
+ * @param tight - Whether the device is small or its battery low.
34
+ * @returns The frames a second to allow.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { smoothCap } from "@johnmorrisdotca/chikyu-earth/realistic";
39
+ *
40
+ * console.log(smoothCap(15, false), smoothCap(15, true));
41
+ * ```
42
+ */
43
+ export function smoothCap(smoothFps, tight) {
44
+ return tight ? Math.max(1, Math.round(smoothFps / 2)) : Math.max(1, smoothFps);
45
+ }
46
+ /**
47
+ * How many frames a second a running clock should draw (a number below 1 means a frame less often than every second, which only a picture with nothing quick in it gets).
48
+ * At real time a frame is drawn each time the quickest thing has moved half a pixel on the screen, at most `cap` a second. Above real time, up to 60 times it, that or a frame for every pixel it moves (up to 30 a second, as it always was), whichever is more often,
49
+ * so a faster clock is never drawn less often than it was; above that a frame for every pixel, up to 30 a second. A reader who asked for reduced motion gets one a second at most. At least one a second when `always` or the clock is faster than real time.
50
+ *
51
+ * @param input - How fast things move and the limits.
52
+ * @returns Frames a second, 0 when nothing moves at all.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { framesPerSecond } from "@johnmorrisdotca/chikyu-earth/realistic";
57
+ *
58
+ * // a low satellite on a whole Earth, then the same zoomed in, then a reader who asked for reduced motion
59
+ * console.log(framesPerSecond({ pixelsPerSecond: 0.3, speed: 1, cap: 15, always: true }));
60
+ * console.log(framesPerSecond({ pixelsPerSecond: 6, speed: 1, cap: 15, always: true }));
61
+ * console.log(framesPerSecond({ pixelsPerSecond: 6, speed: 1, cap: 15, always: true, reduced: true }));
62
+ * ```
63
+ */
64
+ export function framesPerSecond(input) {
65
+ const pixels = Number.isFinite(input.pixelsPerSecond) ? Math.max(0, input.pixelsPerSecond) : 0;
66
+ const speed = Math.abs(input.speed);
67
+ const smooth = Math.min(Math.max(1, input.cap), pixels / SMOOTH_STEP_PX);
68
+ const pixelwise = Math.min(SMOOTH_FPS_MAX, pixels);
69
+ // real time is strictly within the cap; above it the picture is never drawn less often than it was (a frame for each pixel, up to 30 a second), and above 60 times it is that alone
70
+ let rate = speed <= 1 ? smooth : speed <= SMOOTH_UP_TO ? Math.max(smooth, pixelwise) : pixelwise;
71
+ if (input.reduced)
72
+ rate = Math.min(rate, 1);
73
+ if (input.always || speed > 1)
74
+ rate = Math.max(rate, 1);
75
+ return rate;
76
+ }
77
+ /**
78
+ * The wait, in milliseconds, before the next frame at `perSecond`: never under a frame's share of a second and never over `longest`.
79
+ *
80
+ * @param perSecond - Frames a second from `framesPerSecond`.
81
+ * @param longest - The longest wait, in milliseconds (a minute at real time with nothing quick on show).
82
+ * @returns Milliseconds.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * import { waitFor } from "@johnmorrisdotca/chikyu-earth/realistic";
87
+ *
88
+ * console.log(waitFor(4, 60_000), waitFor(0, 60_000));
89
+ * ```
90
+ */
91
+ export function waitFor(perSecond, longest) {
92
+ return perSecond > 0 ? Math.min(longest, 1000 / perSecond) : longest;
93
+ }
94
+ /**
95
+ * Ask the browser (where it can say) whether the battery is at 20% or lower and not charging, and tell `set` when it is. Browsers without the battery API, and a refusal, say nothing: the device counts as plugged in.
96
+ *
97
+ * @param nav - `navigator`, or anything with its `getBattery`.
98
+ * @param set - Called with `true` when the battery is low.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { watchLowBattery } from "@johnmorrisdotca/chikyu-earth/realistic";
103
+ *
104
+ * watchLowBattery(navigator, (low) => console.log("low battery", low));
105
+ * ```
106
+ */
107
+ export function watchLowBattery(nav, set) {
108
+ nav.getBattery?.().then((battery) => {
109
+ if (!battery.charging && battery.level <= 0.2)
110
+ set(true);
111
+ }, () => undefined);
112
+ }
@@ -138,6 +138,10 @@ export function createSatellites(sets, options = {}) {
138
138
  let bMs = 0;
139
139
  let ready = false;
140
140
  let stepMs = MIN_STEP_MS;
141
+ // the quickest satellite between the two samples now held, in Earth radii for each second of game time, worked out once for each pair (see `at`) and not at every frame
142
+ let fastest = 0;
143
+ let fastestAt = Number.NaN;
144
+ let fastestTo = Number.NaN;
141
145
  let propagations = 0;
142
146
  let placed = 0;
143
147
  const timing = { lastBatchMs: 0, maxBatchMs: 0 };
@@ -236,6 +240,9 @@ export function createSatellites(sets, options = {}) {
236
240
  get placed() {
237
241
  return placed;
238
242
  },
243
+ get fastest() {
244
+ return fastest;
245
+ },
239
246
  get estimateFar() {
240
247
  return estimate;
241
248
  },
@@ -388,6 +395,24 @@ export function createSatellites(sets, options = {}) {
388
395
  ready = true;
389
396
  }
390
397
  }
398
+ // how far the quickest one went between the two samples: once for each pair of samples (about once a second), never at a frame, so it costs one pass over the group a second
399
+ if (fastestAt !== aMs || fastestTo !== bMs) {
400
+ fastestAt = aMs;
401
+ fastestTo = bMs;
402
+ let most = 0;
403
+ for (let i = 0; i < n; i += 1) {
404
+ if (okA[i] !== 1 || okB[i] !== 1)
405
+ continue;
406
+ const k = i * 3;
407
+ const dx = b[k] - a[k];
408
+ const dy = b[k + 1] - a[k + 1];
409
+ const dz = b[k + 2] - a[k + 2];
410
+ const squared = dx * dx + dy * dy + dz * dz;
411
+ if (squared > most)
412
+ most = squared;
413
+ }
414
+ fastest = Math.sqrt(most) / ((bMs - aMs) / 1000);
415
+ }
391
416
  const t = (ms - aMs) / (bMs - aMs);
392
417
  let count = 0;
393
418
  for (let i = 0; i < n; i += 1) {
@@ -170,6 +170,11 @@ export interface Satellites {
170
170
  visible(index: number): boolean;
171
171
  /** How many of them the last `at` or `arc` placed. */
172
172
  readonly placed: number;
173
+ /**
174
+ * How fast the quickest satellite goes, in Earth radii for each second of the clock's time, between the two moments SGP4 was last run at for `at` (0 before the first `at`). It is worked out once for each pair of moments from
175
+ * the places already held, so it costs nothing at a frame; the view uses it to draw a frame whenever the quickest dot has moved half a pixel. Multiply by the Earth's radius on the screen for pixels.
176
+ */
177
+ readonly fastest: number;
173
178
  /** Place satellites beyond `maxAgeDays` from their elements as an estimate (`estimateFar`, off by default). Setting it places everything again at the next draw. */
174
179
  estimateFar: boolean;
175
180
  /** How many satellites the last `at` or `arc` placed as an estimate. */
@@ -130,6 +130,13 @@ export interface RideOptions {
130
130
  drag?: RideDrag;
131
131
  /** Which way is up in the view above a satellite (`view: "above"`): `travel` (the default, or the element's `ride-up`) puts the way the satellite is going at the top of the picture, `north` puts north there, so the satellite is seen to go the way it really goes over the ground. Within 3 degrees of a pole it is `travel` (mixed in smoothly out to 6). A drag turns the picture from there. */
132
132
  up?: RideUp;
133
+ /** How far back the camera is kept from the satellite in an outside ride, in kilometres (`view: "from"`; the element's `ride-outside-km` when not given, else 25). It is never more than half the satellite's height. */
134
+ outsideKm?: number;
135
+ /** How long the glide to this ride lasts: a number of milliseconds (1200 by default), or `{ minMs, maxMs }` for a length that follows how far the camera has to move (`rideGlideMs`: 800 to 4000 ms by default, about 1.2 s for a 25 km hop and 3 s for 3,000 km). */
136
+ glide?: number | {
137
+ minMs?: number;
138
+ maxMs?: number;
139
+ };
133
140
  distanceKm?: number;
134
141
  smooth?: boolean;
135
142
  }
@@ -152,6 +159,8 @@ export interface Riding {
152
159
  distanceKm: number;
153
160
  /** `outside` or `inside` (see `RideOptions`). */
154
161
  viewpoint: RideViewpoint;
162
+ /** How far back an outside ride keeps the camera, in kilometres (see `RideOptions`). */
163
+ outsideKm: number;
155
164
  /** `distance` or `fixed` (see `RideOptions`). */
156
165
  modelSize: RideModelSize;
157
166
  /** `head` or `orbit` (see `RideOptions`). */
@@ -574,6 +583,21 @@ export declare class ChikyuSpace extends HTMLElement {
574
583
  noradId: number;
575
584
  name: string;
576
585
  } | null;
586
+ /**
587
+ * How far back an outside ride keeps the camera from the satellite, in kilometres (the attribute `ride-outside-km`), or `null` for the package's own, `OUTSIDE_KM` (25). It is the default for the next `ride` (`RideOptions.outsideKm`) and, set while riding,
588
+ * moves the camera there in a glide of 0.8 s (a jump for a reader who asked for less motion). The camera is never more than half the satellite's height back.
589
+ *
590
+ * @example
591
+ * ```ts
592
+ * import type { ChikyuSpace } from "@johnmorrisdotca/chikyu-earth/space/element";
593
+ *
594
+ * const space = document.createElement("chikyu-space") as ChikyuSpace;
595
+ * space.rideOutsideKm = 100;
596
+ * console.log(space.rideOutsideKm);
597
+ * ```
598
+ */
599
+ get rideOutsideKm(): number | null;
600
+ set rideOutsideKm(value: number | null);
577
601
  /**
578
602
  * Where a ride puts the camera: `outside` (the default; the attribute `ride-viewpoint`) shows the satellite, `inside` puts the camera at it. It is the default for the next `ride` and, set while riding, moves the ride there in one eased glide (a jump for a reader who asked for reduced motion), keeping the ride and the clock.
579
603
  * See `RideOptions.viewpoint`.
@@ -707,6 +731,20 @@ export declare class ChikyuSpace extends HTMLElement {
707
731
  */
708
732
  get satelliteStreakMax(): number;
709
733
  set satelliteStreakMax(value: number);
734
+ /**
735
+ * The most frames a second drawn for a clock at real time, or up to 60 times it (the attribute `smooth-fps`; 15 when the page says nothing; 1 to 30). The picture is drawn each time the quickest thing in it (the Earth's turn at this zoom, a satellite dot,
736
+ * the ridden craft and the camera in a ride) has moved half a pixel, at least once a second while anything but the Earth is moving, and at most this many. Half as many on a small device or a battery at 20% or lower; one a second for a reader who asked for reduced motion.
737
+ *
738
+ * @example
739
+ * ```ts
740
+ * import "@johnmorrisdotca/chikyu-earth/space/element";
741
+ *
742
+ * const space = document.querySelector("chikyu-space")!;
743
+ * space.smoothFps = 24;
744
+ * ```
745
+ */
746
+ get smoothFps(): number;
747
+ set smoothFps(value: number);
710
748
  /**
711
749
  * 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
712
750
  * 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).
@@ -927,6 +965,13 @@ export declare class ChikyuSpace extends HTMLElement {
927
965
  time: number;
928
966
  lookups: number;
929
967
  satellites: SatelliteStats;
968
+ /** How often the running clock draws, as last worked out: the quickest thing's speed on the screen (CSS pixels a second of real time), the frames a second that asks for, the most allowed (`smooth-fps`, halved on a small device or a low battery) and the wait before the next step in milliseconds. */
969
+ pace: {
970
+ pixelsPerSecond: number;
971
+ perSecond: number;
972
+ cap: number;
973
+ waitMs: number;
974
+ };
930
975
  /** The cross-fade when `light` changes to or from `lit` (300 ms, a cut under reduced motion): `mix` is 0 for the true light and 1 for `lit`, and `fading` is true while it moves and another frame is wanted. */
931
976
  lightFade: {
932
977
  mix: number;