@johnmorrisdotca/chikyu-earth 0.23.0 → 0.25.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,252 @@
1
+ import { METEOR_SHOWERS } from "../data/meteor-showers.js";
2
+ const RAD = Math.PI / 180;
3
+ const DAY_MS = 86_400_000;
4
+ const wrap360 = (degrees) => ((degrees % 360) + 360) % 360;
5
+ const wrap180 = (degrees) => ((((degrees + 180) % 360) + 360) % 360) - 180;
6
+ /**
7
+ * The heights between which most meteors shine, in kilometres above the ground: they light up near the top and have burnt out by the bottom.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { METEOR_HEIGHT_KM } from "@johnmorrisdotca/chikyu-earth/meteors";
12
+ *
13
+ * console.log(METEOR_HEIGHT_KM.top, METEOR_HEIGHT_KM.bottom); // 120 80
14
+ * ```
15
+ */
16
+ export const METEOR_HEIGHT_KM = { top: 120, bottom: 80 };
17
+ /**
18
+ * The hourly rate taken for the meteors that belong to no shower (the sporadic background), for an ideal watcher under a perfect sky.
19
+ * It is an assumed round figure, not one from the shower list: the real count runs from a few an hour in the evening to over ten before dawn.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { SPORADIC_HOURLY_RATE } from "@johnmorrisdotca/chikyu-earth/meteors";
24
+ *
25
+ * console.log(SPORADIC_HOURLY_RATE); // 8
26
+ * ```
27
+ */
28
+ export const SPORADIC_HOURLY_RATE = 8;
29
+ /**
30
+ * The Sun's longitude along the ecliptic for the equinox of 2000.0, in degrees: the measure the shower list times its maxima by.
31
+ * Low precision (Meeus, Astronomical Algorithms, ch. 25, with the precession since 2000 taken off), good to about 0.01 degree from 1900 to 2100.
32
+ *
33
+ * @param ms - The moment, in milliseconds since the epoch.
34
+ * @returns The longitude, 0 up to 360.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { solarLongitude } from "@johnmorrisdotca/chikyu-earth/meteors";
39
+ *
40
+ * // The Perseids' maximum is at 140.0 degrees.
41
+ * console.log(solarLongitude(Date.UTC(2026, 7, 13, 2)).toFixed(1));
42
+ * ```
43
+ */
44
+ export function solarLongitude(ms) {
45
+ const t = (ms / DAY_MS + 2_440_587.5 - 2_451_545) / 36_525;
46
+ const meanLongitude = 280.46646 + t * (36_000.76983 + t * 0.0003032);
47
+ const meanAnomaly = (357.52911 + t * (35_999.05029 - t * 0.0001537)) * RAD;
48
+ const centre = (1.914602 - t * (0.004817 + 0.000014 * t)) * Math.sin(meanAnomaly) + (0.019993 - 0.000101 * t) * Math.sin(2 * meanAnomaly) + 0.000289 * Math.sin(3 * meanAnomaly);
49
+ // the longitude of the date, taken back to the equinox of 2000.0 (the equinox slides 1.397 degrees a century)
50
+ return wrap360(meanLongitude + centre - 1.397 * t);
51
+ }
52
+ /** Greenwich sidereal time, in degrees: how far the Earth has turned against the stars. */
53
+ function siderealGreenwich(ms) {
54
+ const days = ms / DAY_MS + 2_440_587.5 - 2_451_545;
55
+ const t = days / 36_525;
56
+ return wrap360(280.46061837 + 360.98564736629 * days + 0.000387933 * t * t);
57
+ }
58
+ /** How far the Sun's longitude is from a shower's maximum at the start of its first day and the end of its last, in degrees (both positive). The list's dates are right for 2026, so that year's Sun is read. */
59
+ const spans = new WeakMap();
60
+ function span(shower) {
61
+ let found = spans.get(shower);
62
+ if (!found) {
63
+ const first = solarLongitude(Date.UTC(2026, shower.start[0] - 1, shower.start[1]));
64
+ const last = solarLongitude(Date.UTC(2026, shower.end[0] - 1, shower.end[1] + 1));
65
+ found = { before: Math.max(0, -wrap180(first - shower.peakSolarLongitude)), after: Math.max(0, wrap180(last - shower.peakSolarLongitude)) };
66
+ spans.set(shower, found);
67
+ }
68
+ return found;
69
+ }
70
+ /**
71
+ * How strong a shower is at a moment: its zenithal hourly rate then, 0 outside its dates.
72
+ * The list gives the rate at the maximum and the first and last days of activity; between them this draws the simplest curve that fits:
73
+ * the rate falls away from the maximum by the same factor for each degree the Earth moves on, down to half a meteor an hour at the start of the first day and the end of the last.
74
+ * A real shower's curve differs (the Quadrantids' maximum lasts hours, the Taurids' weeks). A shower the list calls variable gives 0.
75
+ *
76
+ * @param shower - A shower of `METEOR_SHOWERS`.
77
+ * @param ms - The moment, in milliseconds since the epoch.
78
+ * @returns The zenithal hourly rate, in meteors an hour.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * import { METEOR_SHOWERS, showerRate } from "@johnmorrisdotca/chikyu-earth/meteors";
83
+ *
84
+ * const geminids = METEOR_SHOWERS.find((shower) => shower.code === "GEM")!;
85
+ * console.log(showerRate(geminids, Date.UTC(2026, 11, 14, 8)).toFixed(0), showerRate(geminids, Date.UTC(2026, 5, 1))); // "150" 0
86
+ * ```
87
+ */
88
+ export function showerRate(shower, ms) {
89
+ if (shower.zhr === null)
90
+ return 0;
91
+ const from = wrap180(solarLongitude(ms) - shower.peakSolarLongitude);
92
+ const { before, after } = span(shower);
93
+ const reach = from < 0 ? before : after;
94
+ if (Math.abs(from) > reach)
95
+ return 0;
96
+ if (reach === 0 || shower.zhr <= FLOOR)
97
+ return shower.zhr;
98
+ return shower.zhr * Math.pow(FLOOR / shower.zhr, Math.abs(from) / reach);
99
+ }
100
+ /** The rate a shower is taken to have on its first and last day, in meteors an hour. */
101
+ const FLOOR = 0.5;
102
+ /**
103
+ * The showers active at a moment, strongest first, each with its rate then.
104
+ *
105
+ * @param ms - The moment, in milliseconds since the epoch.
106
+ * @returns The active showers and their zenithal hourly rates (see `showerRate`).
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { activeShowers } from "@johnmorrisdotca/chikyu-earth/meteors";
111
+ *
112
+ * for (const { shower, zhr } of activeShowers(Date.UTC(2026, 7, 12))) console.log(shower.name, zhr.toFixed(1));
113
+ * ```
114
+ */
115
+ export function activeShowers(ms) {
116
+ return METEOR_SHOWERS.map((shower) => ({ shower, zhr: showerRate(shower, ms) }))
117
+ .filter((entry) => entry.zhr > 0)
118
+ .sort((a, b) => b.zhr - a.zhr);
119
+ }
120
+ /**
121
+ * The place on the Earth where a point of the sky stands overhead at a moment: for a shower's radiant, the middle of the half
122
+ * of the Earth its meteors fall on.
123
+ *
124
+ * @param sky - Right ascension and declination, in degrees.
125
+ * @param ms - The moment, in milliseconds since the epoch.
126
+ * @returns The longitude and latitude of that place, in degrees.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * import { METEOR_SHOWERS, pointBeneath } from "@johnmorrisdotca/chikyu-earth/meteors";
131
+ *
132
+ * const perseids = METEOR_SHOWERS.find((shower) => shower.code === "PER")!;
133
+ * const place = pointBeneath(perseids.radiant, Date.UTC(2026, 7, 13, 2));
134
+ * console.log(place.lat, place.lon.toFixed(0)); // 58 and the longitude then
135
+ * ```
136
+ */
137
+ export function pointBeneath(sky, ms) {
138
+ return { lon: wrap180(sky.ra - siderealGreenwich(ms)), lat: sky.dec };
139
+ }
140
+ /**
141
+ * The place on the Earth that faces the way the Earth is travelling round the Sun (the apex of its way): it sits on the morning side,
142
+ * which sweeps up more meteors than the evening side.
143
+ *
144
+ * @param ms - The moment, in milliseconds since the epoch.
145
+ * @returns The longitude and latitude of that place, in degrees.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * import { apexPoint } from "@johnmorrisdotca/chikyu-earth/meteors";
150
+ *
151
+ * console.log(Math.abs(apexPoint(Date.UTC(2026, 2, 20, 12)).lat) < 24); // true: it stays within the tropics
152
+ * ```
153
+ */
154
+ export function apexPoint(ms) {
155
+ // the Earth moves towards the point of the ecliptic 90 degrees behind the Sun
156
+ const longitude = (solarLongitude(ms) - 90) * RAD;
157
+ const obliquity = 23.4393 * RAD;
158
+ const ra = Math.atan2(Math.cos(obliquity) * Math.sin(longitude), Math.cos(longitude)) / RAD;
159
+ const dec = Math.asin(Math.sin(obliquity) * Math.sin(longitude)) / RAD;
160
+ return pointBeneath({ ra: wrap360(ra), dec }, ms);
161
+ }
162
+ /**
163
+ * A place as a unit vector: x to longitude 90 east on the equator, y to the north pole, z to longitude 0 on the equator (the realistic Earth's own axes).
164
+ *
165
+ * @param point - Longitude and latitude, in degrees.
166
+ * @returns The unit vector from the Earth's centre to that place.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * import { placeVector } from "@johnmorrisdotca/chikyu-earth/meteors";
171
+ *
172
+ * console.log(placeVector({ lon: 0, lat: 90 }).map((n) => Math.round(n))); // [0, 1, 0]
173
+ * ```
174
+ */
175
+ export const placeVector = (point) => {
176
+ const lon = point.lon * RAD;
177
+ const lat = point.lat * RAD;
178
+ return [Math.cos(lat) * Math.sin(lon), Math.sin(lat), Math.cos(lat) * Math.cos(lon)];
179
+ };
180
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
181
+ /**
182
+ * The meteor sky of a moment (see `MeteorSky`).
183
+ *
184
+ * @param ms - The moment, in milliseconds since the epoch.
185
+ * @returns The active showers with their rates and radiant places, and the apex.
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * import { hourlyRateAt, meteorSky } from "@johnmorrisdotca/chikyu-earth/meteors";
190
+ *
191
+ * const sky = meteorSky(Date.UTC(2026, 7, 13, 2));
192
+ * console.log(hourlyRateAt(sky, { lon: 139.7, lat: 35.7 }).toFixed(1));
193
+ * ```
194
+ */
195
+ export function meteorSky(ms) {
196
+ return {
197
+ ms,
198
+ showers: activeShowers(ms).map(({ shower, zhr }) => ({ shower, zhr, overhead: placeVector(pointBeneath(shower.radiant, ms)) })),
199
+ apex: placeVector(apexPoint(ms)),
200
+ };
201
+ }
202
+ /**
203
+ * How many meteors an ideal watcher at a place would count in an hour under a perfect dark sky, whether or not it is dark there:
204
+ * the sporadic background, a little more on the side that faces the Earth's way and a little less on the other, plus each active
205
+ * shower's rate times the sine of its radiant's height (none where the radiant is below the horizon).
206
+ * The lean towards the morning side (from 0.4 to 1.6 times `SPORADIC_HOURLY_RATE`) is a simple stand-in for the real daily swing.
207
+ *
208
+ * @param sky - The meteor sky of the moment (`meteorSky`).
209
+ * @param place - The place, or its unit vector (`placeVector`).
210
+ * @returns Meteors an hour.
211
+ *
212
+ * @example
213
+ * ```ts
214
+ * import { hourlyRateAt, meteorSky, pointBeneath } from "@johnmorrisdotca/chikyu-earth/meteors";
215
+ *
216
+ * const moment = Date.UTC(2026, 11, 14, 8);
217
+ * const sky = meteorSky(moment);
218
+ * // Under the Geminids' radiant the rate is the shower's whole rate and the background on top.
219
+ * console.log(hourlyRateAt(sky, pointBeneath(sky.showers[0]!.shower.radiant, moment)) > 150);
220
+ * ```
221
+ */
222
+ export function hourlyRateAt(sky, place) {
223
+ const p = Array.isArray(place) ? place : placeVector(place);
224
+ let rate = SPORADIC_HOURLY_RATE * (1 + 0.6 * dot(p, sky.apex));
225
+ for (const entry of sky.showers) {
226
+ const height = dot(p, entry.overhead);
227
+ if (height > 0)
228
+ rate += entry.zhr * height;
229
+ }
230
+ return rate;
231
+ }
232
+ /**
233
+ * How dark the sky is at a place, from 0 (the Sun is up) to 1 (the Sun is 6 degrees or more below the horizon, the end of civil twilight),
234
+ * rising evenly between: meteors are counted as seen only where it is dark.
235
+ *
236
+ * @param place - The place's unit vector (`placeVector`).
237
+ * @param sun - The unit vector of the place the Sun is overhead.
238
+ * @returns 0 to 1.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * import { darkness, placeVector } from "@johnmorrisdotca/chikyu-earth/meteors";
243
+ *
244
+ * const sun = placeVector({ lon: 0, lat: 0 });
245
+ * console.log(darkness(placeVector({ lon: 0, lat: 0 }), sun), darkness(placeVector({ lon: 180, lat: 0 }), sun)); // 0 1
246
+ * ```
247
+ */
248
+ export function darkness(place, sun) {
249
+ const sine = dot(place, sun);
250
+ const edge = Math.sin(6 * RAD);
251
+ return sine >= 0 ? 0 : Math.min(1, -sine / edge);
252
+ }
@@ -5,6 +5,7 @@ import { lookAt } from "../view.ts";
5
5
  import type { Layer } from "./tiers.ts";
6
6
  import { type ThreeParts } from "./textures.ts";
7
7
  import { type TileSet } from "./tile-set.ts";
8
+ import { type MeteorState } from "../meteors/layer.ts";
8
9
  export type { ThreeParts };
9
10
  type Three = ThreeParts;
10
11
  /**
@@ -53,6 +54,8 @@ export interface EarthModel {
53
54
  tiles: TileSet | null;
54
55
  /** The pixel ratio the textures are chosen for. */
55
56
  ratio(): number;
57
+ /** Meteors seen from space (src/meteors/layer.ts): off unless the element switches them on. */
58
+ meteors: MeteorState;
56
59
  }
57
60
  export interface EarthDeps {
58
61
  assets: AssetCache;
@@ -69,6 +72,8 @@ export interface EarthDeps {
69
72
  invalidate: () => void;
70
73
  onError?: (error: unknown) => void;
71
74
  onTier?: (layer: Layer, width: number) => void;
75
+ /** Told at the start of every draw, before anything is read for it. */
76
+ onDraw?: () => void;
72
77
  /** Told at every draw where the disc is, for what is laid over it (markers). */
73
78
  onPose?: (pose: {
74
79
  lon: number;
@@ -3,6 +3,7 @@ import { ATMOSPHERE_FRAG, ATMOSPHERE_VERT, CLOUD_FRAG, SURFACE_FRAG, SURFACE_VER
3
3
  import { subsolarPoint, unitVector } from "./sun.js";
4
4
  import { createTextureSet } from "./textures.js";
5
5
  import { createTileSet } from "./tile-set.js";
6
+ import { createMeteorLayer, newMeteorState } from "../meteors/layer.js";
6
7
  const RAD = Math.PI / 180;
7
8
  /**
8
9
  * The glow reaches this many radii from the centre; the globe at 1x is drawn to fit inside it.
@@ -27,6 +28,7 @@ export const newModel = () => ({
27
28
  drawn: null,
28
29
  tiles: null,
29
30
  ratio: () => Math.min(globalThis.devicePixelRatio || 1, 2),
31
+ meteors: newMeteorState(),
30
32
  });
31
33
  /**
32
34
  * The disc's radius in CSS pixels in a box of `width` x `height` at `zoom`: it fits the glow in the box at 1x.
@@ -129,10 +131,14 @@ export function createEarthItem(model, deps) {
129
131
  scene.add(turned, glow);
130
132
  const camera = new three.OrthographicCamera(-1, 1, 1, -1, 0.1, 20);
131
133
  camera.position.set(0, 0, 5);
134
+ // the meteors: made the first time they are switched on, and asking for their own next draw while a streak is alive or one is due
135
+ let meteors = null;
136
+ let meteorTimer;
132
137
  return {
133
138
  scene,
134
139
  camera,
135
140
  update() {
141
+ deps.onDraw?.();
136
142
  const view = model.view;
137
143
  const look = lookAt(model.centre, view);
138
144
  turned.rotation.set(look.lat * RAD, -look.lon * RAD, 0, "XYZ");
@@ -154,12 +160,21 @@ export function createEarthItem(model, deps) {
154
160
  textures.sync(radius * model.ratio());
155
161
  tiles.sync({ lon: look.lon, lat: look.lat, width: size.width, height: size.height, panX: view.panX, panY: view.panY, radius }, [sunDir.value.x, sunDir.value.y, sunDir.value.z], true, model.ratio());
156
162
  deps.onPose?.({ lon: look.lon, lat: look.lat, radius, cx: size.width / 2 + view.panX, cy: size.height / 2 + view.panY, width: size.width, height: size.height });
163
+ if (model.meteors.on && !meteors)
164
+ meteors = createMeteorLayer(three, turned, model.meteors);
165
+ if (meteors) {
166
+ const wait = meteors.step({ now: performance.now(), time: model.time, facing: unitVector({ lon: look.lon, lat: look.lat }), sun: [sx, sy, sz], radius, width: size.width, height: size.height });
167
+ clearTimeout(meteorTimer);
168
+ meteorTimer = Number.isFinite(wait) ? setTimeout(deps.invalidate, wait) : undefined;
169
+ }
157
170
  return false;
158
171
  },
159
172
  resize(next, nextHeight) {
160
173
  size = { width: next, height: nextHeight };
161
174
  },
162
175
  dispose() {
176
+ clearTimeout(meteorTimer);
177
+ meteors?.dispose();
163
178
  model.tiles = null;
164
179
  tiles.dispose();
165
180
  textures.dispose();
@@ -58,6 +58,13 @@ export declare const readTime: (value: string | null) => number | "now";
58
58
  * While time runs it sends `chikyu-timechange` with `detail: { time, running: true }` (the moment shown in milliseconds since 1970), at most four times a second however fast the picture is drawn and not from a hidden tab, and once with `running: false` when the clock holds
59
59
  * (a date is set, or `speed` is set to 0): a page writes the date into its date box from it. It is not sent for a `time` the page sets itself.
60
60
  *
61
+ * `meteors` (the attribute, with or without a value other than `off`; the property is a boolean) draws meteors as they look from space: short streaks 80 to 120 km up,
62
+ * only where it is dark or twilight, more of them where an active shower's radiant stands high and on the side that faces the Earth's way. Each streak's place and
63
+ * moment are drawn at random (and said so in a line under the picture, which `meteors-label="off"` takes away for a page that says it itself); how many there are,
64
+ * where they fall, their height and the showers' dates are real (`@johnmorrisdotca/chikyu-earth/meteors`). They run while the clock runs, at any speed, and not
65
+ * at all while it is held, out of sight, in a hidden tab, or for a reader who prefers reduced motion until the page sets a `speed` (a Play). `chikyu-meteors`
66
+ * is sent when the strongest active shower changes, with `detail: { shower, zhr }` (`shower` is `null` when none is active).
67
+ *
61
68
  * @example
62
69
  * ```ts no-run
63
70
  * import type { ChikyuEarthRealistic } from "@johnmorrisdotca/chikyu-earth/realistic/element";
@@ -81,6 +88,11 @@ export declare class ChikyuEarthRealistic extends HTMLElement {
81
88
  connectedCallback(): void;
82
89
  disconnectedCallback(): void;
83
90
  attributeChangedCallback(name: string, _old: string | null, value: string | null): void;
91
+ /**
92
+ * Meteors seen from space, on or off (the attribute `meteors`): see the class's description. Off by default, and nothing of theirs is made until they are first switched on.
93
+ */
94
+ get meteors(): boolean;
95
+ set meteors(value: boolean);
84
96
  /** The controller behind the element's own hands (`set`, `fit`, `state`), while it is in a page. */
85
97
  get controller(): ViewController | undefined;
86
98
  /** Where the finer map tiles are served from (a folder with `manifest.json`), or `null` for none; the attribute `tiles`. The Earth loads only the tiles in view, over its own pictures. */
@@ -123,6 +135,15 @@ export declare class ChikyuEarthRealistic extends HTMLElement {
123
135
  entries: number;
124
136
  refs: number;
125
137
  };
138
+ /** The meteors: whether they are on, the streaks alive now and started so far, the streaks a second being drawn, and the strongest active shower's code and rate. */
139
+ meteors: {
140
+ on: boolean;
141
+ alive: number;
142
+ spawned: number;
143
+ perSecond: number;
144
+ shower: string | null;
145
+ zhr: number;
146
+ };
126
147
  };
127
148
  /**
128
149
  * Apply a shared view controller's camera (yaw, tilt, zoom, pan). A change under half a pixel is not drawn, a settled change always is,
@@ -3,12 +3,13 @@
3
3
  // changes, at most 30 times a second, and nothing at all while it is out of sight or the tab is hidden.
4
4
  import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
5
5
  import { adoptStyles } from "../adopt.js";
6
+ import { METEOR_NOTE_STYLE, prefersLessMotion, setMeteorNote } from "../meteors/note.js";
6
7
  import { createEarthItem, discRadius, lookAt, newModel } from "./earth.js";
7
8
  import { createGate, frameCap } from "./gate.js";
8
9
  import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
9
10
  export { setSharedRenderer, setThreeLoader };
10
11
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
11
- const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}";
12
+ const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}" + METEOR_NOTE_STYLE;
12
13
  const RAD = Math.PI / 180;
13
14
  /** The Sun and the clouds are re-placed this often at real time: 15 degrees an hour is 0.25 degree a minute. */
14
15
  const LIVE_TICK_MS = 60_000;
@@ -84,6 +85,13 @@ export const readTime = (value) => {
84
85
  * While time runs it sends `chikyu-timechange` with `detail: { time, running: true }` (the moment shown in milliseconds since 1970), at most four times a second however fast the picture is drawn and not from a hidden tab, and once with `running: false` when the clock holds
85
86
  * (a date is set, or `speed` is set to 0): a page writes the date into its date box from it. It is not sent for a `time` the page sets itself.
86
87
  *
88
+ * `meteors` (the attribute, with or without a value other than `off`; the property is a boolean) draws meteors as they look from space: short streaks 80 to 120 km up,
89
+ * only where it is dark or twilight, more of them where an active shower's radiant stands high and on the side that faces the Earth's way. Each streak's place and
90
+ * moment are drawn at random (and said so in a line under the picture, which `meteors-label="off"` takes away for a page that says it itself); how many there are,
91
+ * where they fall, their height and the showers' dates are real (`@johnmorrisdotca/chikyu-earth/meteors`). They run while the clock runs, at any speed, and not
92
+ * at all while it is held, out of sight, in a hidden tab, or for a reader who prefers reduced motion until the page sets a `speed` (a Play). `chikyu-meteors`
93
+ * is sent when the strongest active shower changes, with `detail: { shower, zhr }` (`shower` is `null` when none is active).
94
+ *
87
95
  * @example
88
96
  * ```ts no-run
89
97
  * import type { ChikyuEarthRealistic } from "@johnmorrisdotca/chikyu-earth/realistic/element";
@@ -102,7 +110,7 @@ export const readTime = (value) => {
102
110
  * ```
103
111
  */
104
112
  export class ChikyuEarthRealistic extends HTMLElement {
105
- static observedAttributes = ["center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles"];
113
+ static observedAttributes = ["center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "meteors", "meteors-label", "lang"];
106
114
  #model = newModel();
107
115
  #mode = "now";
108
116
  #view;
@@ -124,6 +132,9 @@ export class ChikyuEarthRealistic extends HTMLElement {
124
132
  #listeners = new Set();
125
133
  #hands;
126
134
  #reach = null;
135
+ /** The page has set a `speed` since the element came into the page: for a reader who prefers reduced motion, that is the Play that lets meteors start. */
136
+ #played = false;
137
+ #note;
127
138
  #onContext = (state) => {
128
139
  if (state === "unavailable")
129
140
  this.#fail("WebGL is not available");
@@ -145,10 +156,16 @@ export class ChikyuEarthRealistic extends HTMLElement {
145
156
  if (!this.hasAttribute("aria-label"))
146
157
  this.setAttribute("aria-label", "The Earth from space, with its sunlit and dark sides");
147
158
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
148
- root.innerHTML = `<div id="stage"></div><div id="overlay"></div>`;
159
+ root.innerHTML = `<div id="stage"></div><div id="overlay"></div><p id="meteor-note" hidden></p>`;
149
160
  adoptStyles(root, STYLE, this.nonce);
150
161
  this.#stage = root.getElementById("stage");
151
162
  this.#overlay = root.getElementById("overlay");
163
+ this.#note = root.getElementById("meteor-note");
164
+ this.#played = false;
165
+ this.#model.meteors.on = this.#meteorsAsked();
166
+ this.#model.meteors.running = () => this.speed !== 0 && document.visibilityState !== "hidden" && (this.#played || !prefersLessMotion());
167
+ this.#model.meteors.onShower = (shower, zhr) => this.dispatchEvent(new CustomEvent("chikyu-meteors", { detail: { shower, zhr } }));
168
+ this.#meteorNote();
152
169
  this.#stage.addEventListener("webglcontextlost", this.#lost, true);
153
170
  this.#stage.addEventListener("webglcontextrestored", this.#restored, true);
154
171
  const nav = navigator;
@@ -177,6 +194,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
177
194
  },
178
195
  drift: 1.5,
179
196
  invalidate: () => this.#gate?.soon(),
197
+ onDraw: () => this.#gate?.drawn(),
180
198
  onPose: (pose) => {
181
199
  if (this.#hands)
182
200
  this.#hands.controller.grabRadius = discRadius(pose.width, pose.height, 1);
@@ -243,6 +261,35 @@ export class ChikyuEarthRealistic extends HTMLElement {
243
261
  this.#startTick();
244
262
  else if (name === "tiles")
245
263
  this.#gate?.soon();
264
+ else if (name === "meteors")
265
+ this.meteors = this.#meteorsAsked();
266
+ else if (name === "meteors-label" || name === "lang")
267
+ this.#meteorNote();
268
+ }
269
+ #meteorsAsked() {
270
+ return this.hasAttribute("meteors") && this.getAttribute("meteors") !== "off";
271
+ }
272
+ /** The line under the picture that says the streaks are an illustration, in the language of the element or the page. */
273
+ #meteorNote() {
274
+ setMeteorNote(this.#note, this, this.#model.meteors.on);
275
+ }
276
+ /**
277
+ * Meteors seen from space, on or off (the attribute `meteors`): see the class's description. Off by default, and nothing of theirs is made until they are first switched on.
278
+ */
279
+ get meteors() {
280
+ return this.#model.meteors.on;
281
+ }
282
+ set meteors(value) {
283
+ if (value !== this.#meteorsAsked()) {
284
+ if (value)
285
+ this.setAttribute("meteors", "");
286
+ else
287
+ this.removeAttribute("meteors");
288
+ return;
289
+ }
290
+ this.#model.meteors.on = value;
291
+ this.#meteorNote();
292
+ this.#gate?.soon();
246
293
  }
247
294
  /** The controller behind the element's own hands (`set`, `fit`, `state`), while it is in a page. */
248
295
  get controller() {
@@ -312,6 +359,8 @@ export class ChikyuEarthRealistic extends HTMLElement {
312
359
  #setSpeed(next) {
313
360
  if (this.isConnected && this.speed !== 0)
314
361
  this.#advance(performance.now());
362
+ if (this.isConnected && this.#view)
363
+ this.#played = true;
315
364
  this.#speed = next;
316
365
  this.#last = performance.now();
317
366
  this.#startTick();
@@ -350,6 +399,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
350
399
  contexts: stats?.contexts ?? 0,
351
400
  canvas: stats?.canvas ?? { width: 0, height: 0, pixels: 0 },
352
401
  assets: { entries: stats?.assets.entries ?? 0, refs: stats?.assets.refs ?? 0 },
402
+ meteors: { on: this.#model.meteors.on, ...this.#model.meteors.drawn },
353
403
  };
354
404
  }
355
405
  /**
@@ -13,6 +13,7 @@ export declare const browserTimers: Timers;
13
13
  *
14
14
  * const gate: Gate = createGate(33, () => console.log("draw"));
15
15
  * gate.request();
16
+ * gate.drawn();
16
17
  * gate.cancel();
17
18
  * ```
18
19
  */
@@ -25,6 +26,12 @@ export interface Gate {
25
26
  cancel(): void;
26
27
  /** Change the least time between runs (a lower frame rate on a battery). */
27
28
  setMinMs(minMs: number): void;
29
+ /**
30
+ * Tell the gate a draw has begun (call it first thing in the draw). From the first call, an ask made after a run and before the draw it asked for is dropped, since that draw reads the state as it is
31
+ * when it runs and so shows the change too: two tiles that arrive a few milliseconds apart are one draw, not a draw and a second, empty one 33 ms later. A draw that does not come within `minMs`
32
+ * (a hidden tab, a busy machine) no longer holds asks back.
33
+ */
34
+ drawn(): void;
28
35
  }
29
36
  /**
30
37
  * A rate gate for the draw: asks that come faster than `minMs` apart become one, and the last ask is never lost, so a burst of changes costs one draw.
@@ -28,15 +28,21 @@ export function createGate(minMs, fire, timers = browserTimers) {
28
28
  let last = -Infinity;
29
29
  let waiting;
30
30
  let soon = false;
31
+ let tracking = false;
32
+ let undrawn = false;
31
33
  const run = () => {
32
34
  waiting = undefined;
33
35
  last = timers.now();
36
+ undrawn = true;
34
37
  fire();
35
38
  };
36
39
  const request = () => {
37
40
  if (waiting !== undefined)
38
41
  return;
39
- const wait = last + least - timers.now();
42
+ const now = timers.now();
43
+ if (tracking && undrawn && now - last < least)
44
+ return;
45
+ const wait = last + least - now;
40
46
  if (wait <= 0)
41
47
  run();
42
48
  else
@@ -61,6 +67,10 @@ export function createGate(minMs, fire, timers = browserTimers) {
61
67
  setMinMs(value) {
62
68
  least = value;
63
69
  },
70
+ drawn() {
71
+ tracking = true;
72
+ undrawn = false;
73
+ },
64
74
  };
65
75
  }
66
76
  /**
@@ -147,6 +147,14 @@ export declare class ChikyuSpace extends HTMLElement {
147
147
  connectedCallback(): void;
148
148
  disconnectedCallback(): void;
149
149
  attributeChangedCallback(name: string, _old: string | null, value: string | null): void;
150
+ /**
151
+ * Meteors seen from space, on or off (the attribute `meteors`): short streaks where meteors burn, on the dark side of the Earth and in its twilight, more of them under an active shower, only while the
152
+ * clock runs, and for a reader who prefers reduced motion only once the page has set a `speed` (a Play). Each streak's place and moment are drawn at random, and a line under the picture says so
153
+ * (`meteors-label="off"` takes it away); how often they appear, where, how high and when follow real data (`@johnmorrisdotca/chikyu-earth/meteors`). None are drawn while the Earth is under 40 pixels in radius.
154
+ * `chikyu-meteors` is sent when the strongest active shower changes, with `detail: { shower, zhr }`. Off by default, and nothing of theirs is made until they are first switched on.
155
+ */
156
+ get meteors(): boolean;
157
+ set meteors(value: boolean);
150
158
  get centre(): GeoPoint;
151
159
  set centre(value: GeoPoint);
152
160
  /** The moment shown: milliseconds since the epoch, or "now" to follow the clock. Setting it points the camera at the same place on the ground again. */
@@ -268,6 +276,15 @@ export declare class ChikyuSpace extends HTMLElement {
268
276
  painted: number;
269
277
  moons: number;
270
278
  };
279
+ /** The meteors: whether they are on, the streaks alive now and started so far, the streaks a second being drawn, and the strongest active shower's code and rate. */
280
+ meteors: {
281
+ on: boolean;
282
+ alive: number;
283
+ spawned: number;
284
+ perSecond: number;
285
+ shower: string | null;
286
+ zhr: number;
287
+ };
271
288
  };
272
289
  }
273
290
  declare global {