@johnmorrisdotca/chikyu-earth 0.9.1 → 0.11.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,8 +1,13 @@
1
+ // <chikyu-earth-realistic>: the Earth from space as a web component, drawn by kazoku-ui's shared 3D renderer (one WebGL context for the
2
+ // page) with three.js, which is the page's own. Optional entry point: the flat `<chikyu-earth>` needs neither. It draws only when something
3
+ // changes, at most 30 times a second, and nothing at all while it is out of sight or the tab is hidden.
4
+ import { adoptStyles } from "../adopt.js";
1
5
  import { createEarthItem, lookAt, newModel } from "./earth.js";
2
6
  import { createGate, frameCap } from "./gate.js";
3
- import { setThreeLoader, takeRenderer } from "./shared.js";
4
- export { setThreeLoader };
7
+ import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
8
+ export { setSharedRenderer, setThreeLoader };
5
9
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
10
+ const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}";
6
11
  const RAD = Math.PI / 180;
7
12
  /** The Sun and the clouds are re-placed this often while the time is "now": 15 degrees an hour is 0.25 degree a minute. */
8
13
  const LIVE_TICK_MS = 60_000;
@@ -15,6 +20,12 @@ const readCentre = (value) => {
15
20
  return null;
16
21
  return { lon: lon, lat: lat };
17
22
  };
23
+ /** A `light` attribute: `lit` or `boost`, else the true sun. */
24
+ const readLight = (value) => (value === "lit" || value === "boost" ? value : "sun");
25
+ const readRatio = (value) => {
26
+ const ratio = Number(value);
27
+ return value !== null && Number.isFinite(ratio) && ratio > 0 ? Math.min(ratio, 2) : undefined;
28
+ };
18
29
  /**
19
30
  * A `time` attribute: "now" (or none) follows the clock, else an ISO date such as 2026-06-21T12:00:00Z.
20
31
  *
@@ -35,7 +46,7 @@ export const readTime = (value) => {
35
46
  return Number.isFinite(ms) ? ms : "now";
36
47
  };
37
48
  /**
38
- * The `<chikyu-earth-realistic>` custom element: the Earth from space, drawn with three.js through kazoku-ui's shared renderer (one WebGL context for the page). It takes `center` (`"lon,lat"`), `time` (`now` or an ISO date; the real Sun at that moment), `clouds="off"`, `lights="off"`, `live-seconds` and `texture-base` (where the pictures are served from), and a shared view controller's camera through `setView`. It draws only when something changes, at most 30 times a second, and nothing while it is out of sight or the tab is hidden.
49
+ * The `<chikyu-earth-realistic>` custom element: the Earth from space, drawn with three.js through kazoku-ui's shared renderer (one WebGL context for the page). It takes `center` (`"lon,lat"`), `time` (`now` or an ISO date; the real Sun at that moment), `clouds="off"`, `lights="off"`, `live-seconds`, `texture-base` (where the pictures are served from) and `max-ratio` (the most device pixels to a CSS pixel the canvas is drawn at, 2 at most, and `0.5` draws at half the size and scales it up: for a background; read when the element connects, and it is the shared renderer's cap for the whole page), and a shared view controller's camera through `setView`. It draws only when something changes, at most 30 times a second, and nothing while it is out of sight or the tab is hidden.
39
50
  *
40
51
  * @example
41
52
  * ```ts no-run
@@ -49,7 +60,7 @@ export const readTime = (value) => {
49
60
  * ```
50
61
  */
51
62
  export class ChikyuEarthRealistic extends HTMLElement {
52
- static observedAttributes = ["center", "time", "clouds", "lights", "live-seconds"];
63
+ static observedAttributes = ["center", "time", "clouds", "lights", "light", "live-seconds"];
53
64
  #model = newModel();
54
65
  #mode = "now";
55
66
  #view;
@@ -75,12 +86,14 @@ export class ChikyuEarthRealistic extends HTMLElement {
75
86
  this.#model.time = this.#mode === "now" ? Date.now() : this.#mode;
76
87
  this.#model.clouds = this.getAttribute("clouds") !== "off";
77
88
  this.#model.lights = this.getAttribute("lights") !== "off";
89
+ this.#model.light = readLight(this.getAttribute("light"));
78
90
  if (!this.hasAttribute("role"))
79
91
  this.setAttribute("role", "img");
80
92
  if (!this.hasAttribute("aria-label"))
81
93
  this.setAttribute("aria-label", "The Earth from space, with its sunlit and dark sides");
82
94
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
83
- root.innerHTML = `<style>:host{display:block;aspect-ratio:1/1;position:relative}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}</style><div id="stage"></div><div id="overlay"></div>`;
95
+ root.innerHTML = `<div id="stage"></div><div id="overlay"></div>`;
96
+ adoptStyles(root, STYLE, this.nonce);
84
97
  this.#stage = root.getElementById("stage");
85
98
  this.#overlay = root.getElementById("overlay");
86
99
  this.#stage.addEventListener("webglcontextlost", this.#lost, true);
@@ -92,14 +105,17 @@ export class ChikyuEarthRealistic extends HTMLElement {
92
105
  if (!battery.charging && battery.level <= 0.2)
93
106
  this.#gate?.setMinMs(1000 / Math.min(cap, 15));
94
107
  }, () => undefined);
95
- const taken = takeRenderer(this.#onContext);
108
+ const maxRatio = readRatio(this.getAttribute("max-ratio"));
109
+ if (maxRatio)
110
+ this.#model.ratio = () => Math.min(globalThis.devicePixelRatio || 1, 2, maxRatio);
111
+ const taken = takeRenderer(this.#onContext, maxRatio);
96
112
  this.#taken = taken;
97
113
  const item = createEarthItem(this.#model, {
98
114
  assets: taken.renderer.assets,
99
115
  textureBase: () => this.#textureBase(),
100
116
  cap: () => this.#textureCap(),
101
117
  drift: 1.5,
102
- invalidate: () => this.#gate?.request(),
118
+ invalidate: () => this.#gate?.soon(),
103
119
  onPose: (pose) => {
104
120
  this.#pose = { ...pose, transform: "" };
105
121
  for (const listener of this.#listeners)
@@ -147,6 +163,8 @@ export class ChikyuEarthRealistic extends HTMLElement {
147
163
  this.clouds = value !== "off";
148
164
  else if (name === "lights")
149
165
  this.lights = value !== "off";
166
+ else if (name === "light")
167
+ this.light = readLight(value);
150
168
  else if (name === "live-seconds")
151
169
  this.#startTick();
152
170
  }
@@ -169,7 +187,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
169
187
  }
170
188
  set centre(value) {
171
189
  this.#model.centre = { ...value };
172
- this.#gate?.request();
190
+ this.#gate?.soon();
173
191
  }
174
192
  /** The moment shown: milliseconds since the epoch, or "now" to follow the clock. */
175
193
  get time() {
@@ -182,21 +200,29 @@ export class ChikyuEarthRealistic extends HTMLElement {
182
200
  else
183
201
  this.#model.time = this.#mode;
184
202
  this.#startTick();
185
- this.#gate?.request();
203
+ this.#gate?.soon();
186
204
  }
187
205
  get clouds() {
188
206
  return this.#model.clouds;
189
207
  }
190
208
  set clouds(value) {
191
209
  this.#model.clouds = value;
192
- this.#gate?.request();
210
+ this.#gate?.soon();
211
+ }
212
+ /** How the Earth is lit: `sun` (true, the default), `lit` (always lit: the night side is never a black frame) or `boost` (the true terminator with the night side raised). */
213
+ get light() {
214
+ return this.#model.light;
215
+ }
216
+ set light(value) {
217
+ this.#model.light = value;
218
+ this.#gate?.soon();
193
219
  }
194
220
  get lights() {
195
221
  return this.#model.lights;
196
222
  }
197
223
  set lights(value) {
198
224
  this.#model.lights = value;
199
- this.#gate?.request();
225
+ this.#gate?.soon();
200
226
  }
201
227
  /** What the element is doing, for a page or a test: its state, the texture widths held, the draws made. */
202
228
  get stats() {
@@ -218,7 +244,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
218
244
  this.#model.view = { ...view };
219
245
  const drawn = this.#model.drawn;
220
246
  if (!drawn) {
221
- this.#gate?.request();
247
+ this.#gate?.soon();
222
248
  return;
223
249
  }
224
250
  const shifted = view.zoom !== drawn.view.zoom || view.panX !== drawn.view.panX || view.panY !== drawn.view.panY;
@@ -226,7 +252,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
226
252
  const b = lookAt(this.#model.centre, view);
227
253
  const px = (Math.abs(b.lon - a.lon) * Math.cos(((a.lat + b.lat) / 2) * RAD) + Math.abs(b.lat - a.lat)) * RAD * drawn.radius;
228
254
  if (shifted || px >= 0.5 || (final && px > 0.01))
229
- this.#gate?.request();
255
+ this.#gate?.soon();
230
256
  }
231
257
  /** The view as it is (for a page that wants to read it back). */
232
258
  get view() {
@@ -244,7 +270,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
244
270
  }
245
271
  #onTick = () => {
246
272
  this.#model.time = Date.now();
247
- this.#gate?.request();
273
+ this.#gate?.soon();
248
274
  };
249
275
  #take = () => {
250
276
  if (this.#view && !this.#view.live)
@@ -19,6 +19,8 @@ export declare const browserTimers: Timers;
19
19
  export interface Gate {
20
20
  /** Ask for `fire` to run: now if the last run was `minMs` ago or more, else once, when that time has passed. */
21
21
  request(): void;
22
+ /** Like `request`, but every ask made in one task is one ask, made when the task ends: a time and a view set together are one draw. */
23
+ soon(): void;
22
24
  /** Forget a run that is waiting. */
23
25
  cancel(): void;
24
26
  /** Change the least time between runs (a lower frame rate on a battery). */
@@ -27,20 +27,31 @@ export function createGate(minMs, fire, timers = browserTimers) {
27
27
  let least = minMs;
28
28
  let last = -Infinity;
29
29
  let waiting;
30
+ let soon = false;
30
31
  const run = () => {
31
32
  waiting = undefined;
32
33
  last = timers.now();
33
34
  fire();
34
35
  };
36
+ const request = () => {
37
+ if (waiting !== undefined)
38
+ return;
39
+ const wait = last + least - timers.now();
40
+ if (wait <= 0)
41
+ run();
42
+ else
43
+ waiting = timers.set(run, wait);
44
+ };
35
45
  return {
36
- request() {
37
- if (waiting !== undefined)
46
+ request,
47
+ soon() {
48
+ if (soon)
38
49
  return;
39
- const wait = last + least - timers.now();
40
- if (wait <= 0)
41
- run();
42
- else
43
- waiting = timers.set(run, wait);
50
+ soon = true;
51
+ queueMicrotask(() => {
52
+ soon = false;
53
+ request();
54
+ });
44
55
  },
45
56
  cancel() {
46
57
  if (waiting !== undefined)
@@ -1,5 +1,5 @@
1
1
  export { 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 { lookAt, discRadius, ATMOSPHERE_OUTER } from "./earth.ts";
4
+ export { lookAt, discRadius, ATMOSPHERE_OUTER, type LightMode } from "./earth.ts";
5
5
  export type { ThreeParts } from "./earth.ts";
@@ -1,5 +1,5 @@
1
1
  export declare const SURFACE_VERT = "\nvarying vec2 vUv;\nvarying vec3 vNormal;\nvarying vec3 vWorld;\nvoid main() {\n vUv = uv;\n vNormal = normalize(mat3(modelMatrix) * position);\n vWorld = (modelMatrix * vec4(position, 1.0)).xyz;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}";
2
- export declare const SURFACE_FRAG = "\nuniform sampler2D dayMap;\nuniform sampler2D nightMap;\nuniform sampler2D waterMap;\nuniform vec3 sunDir;\nuniform float lights;\nuniform float ortho;\nvarying vec2 vUv;\nvarying vec3 vNormal;\nvarying vec3 vWorld;\nvoid main() {\n vec3 n = normalize(vNormal);\n vec3 toEye = ortho > 0.5 ? vec3(0.0, 0.0, 1.0) : normalize(cameraPosition - vWorld);\n float ndl = dot(n, sunDir);\n float day = smoothstep(-0.10, 0.22, ndl);\n vec3 albedo = texture2D(dayMap, vUv).rgb;\n float water = texture2D(waterMap, vUv).r;\n\n vec3 lit = albedo * (0.07 + 1.0 * pow(max(ndl, 0.0), 0.5));\n float dusk = smoothstep(-0.14, 0.0, ndl) * (1.0 - smoothstep(0.0, 0.30, ndl));\n lit += vec3(0.55, 0.28, 0.14) * dusk * 0.30 * (0.35 + 0.65 * albedo.g);\n\n vec3 h = normalize(sunDir + toEye);\n float glint = pow(max(dot(n, h), 0.0), 220.0) * water * day;\n lit += vec3(1.0, 0.93, 0.80) * glint * 0.7;\n\n vec3 night = texture2D(nightMap, vUv).rgb;\n night = night * night * vec3(1.6, 1.5, 1.3) * lights + night * 0.25;\n vec3 col = mix(night, lit, day);\n\n float rim = pow(1.0 - clamp(dot(n, toEye), 0.0, 1.0), 3.0);\n float sunSide = 0.12 + 0.88 * smoothstep(-0.25, 0.5, ndl);\n col += vec3(0.20, 0.45, 1.0) * rim * sunSide * 0.55;\n gl_FragColor = vec4(col, 1.0);\n}";
2
+ export declare const SURFACE_FRAG = "\nuniform sampler2D dayMap;\nuniform sampler2D nightMap;\nuniform sampler2D waterMap;\nuniform vec3 sunDir;\nuniform float lights;\nuniform float boost;\nuniform float ortho;\nvarying vec2 vUv;\nvarying vec3 vNormal;\nvarying vec3 vWorld;\nvoid main() {\n vec3 n = normalize(vNormal);\n vec3 toEye = ortho > 0.5 ? vec3(0.0, 0.0, 1.0) : normalize(cameraPosition - vWorld);\n float ndl = dot(n, sunDir);\n float day = smoothstep(-0.10, 0.22, ndl);\n vec3 albedo = texture2D(dayMap, vUv).rgb;\n float water = texture2D(waterMap, vUv).r;\n\n vec3 lit = albedo * (0.07 + 1.0 * pow(max(ndl, 0.0), 0.5));\n float dusk = smoothstep(-0.14, 0.0, ndl) * (1.0 - smoothstep(0.0, 0.30, ndl));\n lit += vec3(0.55, 0.28, 0.14) * dusk * 0.30 * (0.35 + 0.65 * albedo.g);\n\n vec3 h = normalize(sunDir + toEye);\n float glint = pow(max(dot(n, h), 0.0), 220.0) * water * day;\n lit += vec3(1.0, 0.93, 0.80) * glint * 0.7;\n\n vec3 night = texture2D(nightMap, vUv).rgb;\n night = night * night * vec3(1.6, 1.5, 1.3) * lights + night * 0.25;\n vec3 col = mix(night, lit, day);\n col += pow(albedo, vec3(0.75)) * boost * 0.65 * (1.0 - day);\n\n float rim = pow(1.0 - clamp(dot(n, toEye), 0.0, 1.0), 3.0);\n float sunSide = 0.12 + 0.88 * smoothstep(-0.25, 0.5, ndl);\n col += vec3(0.20, 0.45, 1.0) * rim * sunSide * 0.55;\n gl_FragColor = vec4(col, 1.0);\n}";
3
3
  export declare const CLOUD_FRAG = "\nuniform sampler2D cloudMap;\nuniform vec3 sunDir;\nuniform float shift;\nuniform float opacity;\nvarying vec2 vUv;\nvarying vec3 vNormal;\nvoid main() {\n vec3 n = normalize(vNormal);\n float ndl = dot(n, sunDir);\n float c = texture2D(cloudMap, vec2(vUv.x + shift, vUv.y)).r;\n float a = smoothstep(0.28, 0.88, c) * opacity;\n float day = smoothstep(-0.10, 0.25, ndl);\n vec3 col = mix(vec3(0.015, 0.02, 0.04), vec3(1.0), day * (0.18 + 0.82 * pow(max(ndl, 0.0), 0.45)));\n col += vec3(0.55, 0.28, 0.14) * smoothstep(-0.14, 0.0, ndl) * (1.0 - smoothstep(0.0, 0.25, ndl)) * 0.35;\n gl_FragColor = vec4(col, a);\n}";
4
4
  export declare const ATMOSPHERE_VERT = "\nvarying vec3 vPosView;\nvarying vec3 vNormalView;\nvoid main() {\n vec4 view = modelViewMatrix * vec4(position, 1.0);\n vPosView = view.xyz;\n vNormalView = normalize(normalMatrix * position);\n gl_Position = projectionMatrix * view;\n}";
5
5
  export declare const ATMOSPHERE_FRAG = "\nuniform vec3 sunView;\nuniform float outer;\nuniform float ortho;\nvarying vec3 vPosView;\nvarying vec3 vNormalView;\nvoid main() {\n vec3 n = normalize(vNormalView);\n vec3 v = ortho > 0.5 ? vec3(0.0, 0.0, 1.0) : normalize(-vPosView);\n float nz = clamp(dot(n, v), -1.0, 1.0);\n float rho = outer * sqrt(max(0.0, 1.0 - nz * nz));\n float t = clamp((rho - 1.0) / (outer - 1.0), 0.0, 1.0);\n vec2 dir = normalize(n.xy + vec2(1e-5, 0.0));\n float side = smoothstep(-0.40, 0.55, dot(vec3(dir, 0.0), sunView));\n float glow = pow(1.0 - t, 3.0) * (0.10 + 0.90 * side);\n vec3 col = mix(vec3(0.10, 0.22, 0.60), vec3(0.42, 0.68, 1.0), side);\n gl_FragColor = vec4(col, glow * 0.9);\n}";
@@ -16,6 +16,7 @@ uniform sampler2D nightMap;
16
16
  uniform sampler2D waterMap;
17
17
  uniform vec3 sunDir;
18
18
  uniform float lights;
19
+ uniform float boost;
19
20
  uniform float ortho;
20
21
  varying vec2 vUv;
21
22
  varying vec3 vNormal;
@@ -39,6 +40,7 @@ void main() {
39
40
  vec3 night = texture2D(nightMap, vUv).rgb;
40
41
  night = night * night * vec3(1.6, 1.5, 1.3) * lights + night * 0.25;
41
42
  vec3 col = mix(night, lit, day);
43
+ col += pow(albedo, vec3(0.75)) * boost * 0.65 * (1.0 - day);
42
44
 
43
45
  float rim = pow(1.0 - clamp(dot(n, toEye), 0.0, 1.0), 3.0);
44
46
  float sunSide = 0.12 + 0.88 * smoothstep(-0.25, 0.5, ndl);
@@ -15,8 +15,22 @@ export type ContextState = "lost" | "restored" | "unavailable";
15
15
  * ```
16
16
  */
17
17
  export declare function setThreeLoader(load: () => Promise<Three>): void;
18
- /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. */
19
- export declare function takeRenderer(onContext: (state: ContextState) => void): {
18
+ /**
19
+ * Hands the elements a renderer the page made, so a page that draws other things with kazoku-ui's shared renderer keeps one WebGL context for all of them. Call it before the first element connects, or while none is in the page. The page owns the renderer: the elements never dispose it, and its own `maxRatio` and `onContext` apply. Pass `undefined` to go back to the package's own.
20
+ *
21
+ * @param renderer - A renderer made with `createSharedRenderer` from `@johnmorrisdotca/kazoku-ui/renderer`, whose `load` gives the same three.js, or `undefined`.
22
+ *
23
+ * @example
24
+ * ```ts no-run
25
+ * import { createSharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
26
+ * import { setSharedRenderer } from "@johnmorrisdotca/chikyu-earth/realistic/element";
27
+ *
28
+ * setSharedRenderer(createSharedRenderer({ load: () => import("three"), maxRatio: 1.5 }));
29
+ * ```
30
+ */
31
+ export declare function setSharedRenderer(renderer: SharedRenderer<Three> | undefined): void;
32
+ /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. A `maxRatio` lower than the one it was made with makes a new one if no element holds it. */
33
+ export declare function takeRenderer(onContext: (state: ContextState) => void, maxRatio?: number): {
20
34
  renderer: SharedRenderer<Three>;
21
35
  release(): void;
22
36
  };
@@ -2,6 +2,9 @@
2
2
  // WebGL context between them. The last element to leave lets it go (after a second, in case it is only moving).
3
3
  import { createSharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
4
4
  let shared;
5
+ // A renderer the page made and handed over: used as it is, and never disposed here.
6
+ let given;
7
+ let sharedRatio;
5
8
  let loader = () => import("three");
6
9
  const contextListeners = new Set();
7
10
  let elements = 0;
@@ -21,24 +24,55 @@ let releaseTimer;
21
24
  export function setThreeLoader(load) {
22
25
  loader = load;
23
26
  }
24
- /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. */
25
- export function takeRenderer(onContext) {
27
+ /**
28
+ * Hands the elements a renderer the page made, so a page that draws other things with kazoku-ui's shared renderer keeps one WebGL context for all of them. Call it before the first element connects, or while none is in the page. The page owns the renderer: the elements never dispose it, and its own `maxRatio` and `onContext` apply. Pass `undefined` to go back to the package's own.
29
+ *
30
+ * @param renderer - A renderer made with `createSharedRenderer` from `@johnmorrisdotca/kazoku-ui/renderer`, whose `load` gives the same three.js, or `undefined`.
31
+ *
32
+ * @example
33
+ * ```ts no-run
34
+ * import { createSharedRenderer } from "@johnmorrisdotca/kazoku-ui/renderer";
35
+ * import { setSharedRenderer } from "@johnmorrisdotca/chikyu-earth/realistic/element";
36
+ *
37
+ * setSharedRenderer(createSharedRenderer({ load: () => import("three"), maxRatio: 1.5 }));
38
+ * ```
39
+ */
40
+ export function setSharedRenderer(renderer) {
41
+ if (renderer !== given && elements > 0)
42
+ throw new Error("chikyu-earth: setSharedRenderer must be called before an element connects");
43
+ if (renderer !== given) {
44
+ clearTimeout(releaseTimer);
45
+ shared?.dispose();
46
+ shared = undefined;
47
+ }
48
+ given = renderer;
49
+ }
50
+ /** The page's renderer, made on first use. Call `release()` (from the result) when the element leaves. A `maxRatio` lower than the one it was made with makes a new one if no element holds it. */
51
+ export function takeRenderer(onContext, maxRatio) {
26
52
  clearTimeout(releaseTimer);
53
+ if (!given && shared && elements <= 0 && sharedRatio !== maxRatio) {
54
+ shared.dispose();
55
+ shared = undefined;
56
+ }
27
57
  elements += 1;
28
58
  contextListeners.add(onContext);
29
- shared ??= createSharedRenderer({
30
- load: () => loader(),
31
- onContext: (state) => {
32
- for (const listener of contextListeners)
33
- listener(state);
34
- },
35
- });
59
+ if (!given && !shared) {
60
+ sharedRatio = maxRatio;
61
+ shared = createSharedRenderer({
62
+ load: () => loader(),
63
+ ...(maxRatio === undefined ? {} : { maxRatio }),
64
+ onContext: (state) => {
65
+ for (const listener of contextListeners)
66
+ listener(state);
67
+ },
68
+ });
69
+ }
36
70
  return {
37
- renderer: shared,
71
+ renderer: (given ?? shared),
38
72
  release() {
39
73
  contextListeners.delete(onContext);
40
74
  elements -= 1;
41
- if (elements <= 0) {
75
+ if (elements <= 0 && !given) {
42
76
  releaseTimer = setTimeout(() => {
43
77
  if (elements <= 0) {
44
78
  shared?.dispose();
@@ -1,6 +1,8 @@
1
1
  import type { GeoPoint } from "../types.ts";
2
2
  import { setThreeLoader } from "../realistic/shared.ts";
3
+ import type { LightMode } from "../realistic/earth.ts";
3
4
  import type { SatelliteInfo, SatelliteRef, Satellites } from "../satellites/types.ts";
5
+ import { type PlanetName } from "./ephemeris.ts";
4
6
  import { type SatelliteStyle } from "./satellite-layer.ts";
5
7
  import type { RideLook } from "./ride.ts";
6
8
  import { type ScaleMode } from "./scale.ts";
@@ -53,7 +55,7 @@ export { setThreeLoader };
53
55
  */
54
56
  export type SpaceState = "loading" | "live" | "unavailable" | "lost" | "idle";
55
57
  /**
56
- * A named distance for `zoomFor`: the Earth, the Moon, the Sun, the inner planets or the whole solar system.
58
+ * A named distance for `zoomFor`: the Earth, the Moon, the Sun, the inner planets, the whole solar system, or a planet with its nearer moons (`Jupiter-moons`: the zoom that shows them, when a body painter that draws moons is set).
57
59
  *
58
60
  * @example
59
61
  * ```ts no-run
@@ -63,7 +65,7 @@ export type SpaceState = "loading" | "live" | "unavailable" | "lost" | "idle";
63
65
  * console.log(typeof zoomTo);
64
66
  * ```
65
67
  */
66
- export type SpacePreset = "earth" | "moon" | "sun" | "inner" | "solar-system";
68
+ export type SpacePreset = "earth" | "moon" | "sun" | "inner" | "solar-system" | `${Exclude<PlanetName, "Mercury" | "Venus">}-moons`;
67
69
  /**
68
70
  * How a ride along is done: `view` `from` (the default) puts the camera at the body looking at the Earth, `follow` keeps it a fixed distance from the body looking at it (`distanceKm`, 3000 by default,
69
71
  * for a satellite; a planet or the Moon is kept at the distance the zoom says); `look` `down` (the default) or `horizon` is where a camera at the body points; `smooth` (the default) glides
@@ -143,6 +145,17 @@ export declare class ChikyuSpace extends HTMLElement {
143
145
  set scale(value: ScaleMode);
144
146
  get labels(): boolean;
145
147
  set labels(value: boolean);
148
+ /**
149
+ * How the Sun, the planets, Pluto and their moons are drawn: one of the `looks` of the body painter set with `setBodyPainter` (wakusei-planets has `realistic` and `painted`), or `plain` (the sphere in the right colour, no moons); empty for the painter's first.
150
+ * With no painter they are plain spheres and this does nothing. Changing it draws the bodies again with the new look.
151
+ */
152
+ get bodies(): string;
153
+ set bodies(value: string);
154
+ /** How the Earth is lit: `sun` (true, the default), `lit` (always lit, as if by daylight from the camera's side, so a ride on the night side is never a black frame) or `boost` (the true terminator, with the night side raised). The Sun, the Moon and the planets keep their true places. */
155
+ get light(): LightMode;
156
+ set light(value: LightMode);
157
+ /** The looks the body painter offers (empty with no painter), for a page to build its choice from. */
158
+ get bodyLooks(): readonly string[];
146
159
  get orbits(): boolean;
147
160
  set orbits(value: boolean);
148
161
  /**
@@ -235,6 +248,12 @@ export declare class ChikyuSpace extends HTMLElement {
235
248
  position: [number, number, number];
236
249
  fov: number;
237
250
  };
251
+ /** What the body painter has made at the last draw: the Sun and planets with a drawing, and the moons shown round a planet that is near. */
252
+ bodies: {
253
+ look: string;
254
+ painted: number;
255
+ moons: number;
256
+ };
238
257
  };
239
258
  }
240
259
  declare global {
@@ -1,10 +1,11 @@
1
+ import { adoptStyles } from "../adopt.js";
1
2
  import { createGate, frameCap } from "../realistic/gate.js";
2
3
  import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
3
4
  import { MAX_TEXTURE } from "../realistic/tiers.js";
4
5
  import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
5
6
  import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt } from "./ephemeris.js";
6
7
  import { MAX_ORBIT_GROUP } from "./satellite-layer.js";
7
- import { placeAround, placeMoon, placeSun } from "./scale.js";
8
+ import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
8
9
  import { BODY_NAMES, createSpaceItem, FIT_DISTANCE, newSpaceModel } from "./scene.js";
9
10
  export { BODY_NAMES };
10
11
  let painter;
@@ -26,8 +27,10 @@ export function setBodyPainter(next) {
26
27
  painter = next;
27
28
  }
28
29
  /** Mean radii in kilometres (IAU), for what a click tells. */
29
- 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 };
30
+ 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 };
30
31
  export { setThreeLoader };
32
+ /** A `light` attribute: `lit` or `boost`, else the true sun. */
33
+ const readLight = (value) => (value === "lit" || value === "boost" ? value : "sun");
31
34
  const RAD = Math.PI / 180;
32
35
  /** The Earth's own turn, degrees a second. */
33
36
  const EARTH_RATE = 360 / 86_164.0905;
@@ -49,6 +52,7 @@ const readTime = (value) => {
49
52
  const ms = Date.parse(value);
50
53
  return Number.isFinite(ms) ? ms : "now";
51
54
  };
55
+ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}.sp-sat{position:absolute;left:0;top:0;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-sat[hidden]{display:none}`;
52
56
  /**
53
57
  * The `<chikyu-space>` custom element: the Earth, the Moon, the Sun and the planets where they are at a date and time, drawn with three.js through the shared renderer. It takes `center`, `time` (`now` or an ISO date), `speed` (1 is real time, 0 holds, 86400 is a day a second, negative runs backwards), `scale` (`compressed` or `true`), `labels` and `orbits` (`off` hides them); positions are computed in the browser by astronomy-engine, an optional peer dependency. It draws only when something changes, and nothing while it is out of sight.
54
58
  *
@@ -63,7 +67,7 @@ const readTime = (value) => {
63
67
  * ```
64
68
  */
65
69
  export class ChikyuSpace extends HTMLElement {
66
- static observedAttributes = ["center", "time", "speed", "scale", "labels", "orbits"];
70
+ static observedAttributes = ["center", "time", "speed", "scale", "labels", "orbits", "bodies", "light"];
67
71
  #model = newSpaceModel();
68
72
  #mode = "now";
69
73
  #speed = 1;
@@ -91,6 +95,8 @@ export class ChikyuSpace extends HTMLElement {
91
95
  this.#model.mode = this.getAttribute("scale") === "true" ? "true" : "compressed";
92
96
  this.#model.labels = this.getAttribute("labels") !== "off";
93
97
  this.#model.orbits = this.getAttribute("orbits") !== "off";
98
+ this.#model.bodies = this.getAttribute("bodies") ?? "";
99
+ this.#model.light = readLight(this.getAttribute("light"));
94
100
  this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
95
101
  this.#model.speed = this.#speed;
96
102
  if (!this.hasAttribute("role"))
@@ -98,7 +104,8 @@ export class ChikyuSpace extends HTMLElement {
98
104
  if (!this.hasAttribute("aria-label"))
99
105
  this.setAttribute("aria-label", "The Earth, the Moon, the Sun and the planets in their places for the date shown");
100
106
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
101
- root.innerHTML = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}.sp-sat{position:absolute;left:0;top:0;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-sat[hidden]{display:none}</style><div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
107
+ root.innerHTML = `<div id="stage"></div><div id="labels" aria-hidden="true"></div>`;
108
+ adoptStyles(root, STYLE, this.nonce);
102
109
  this.#stage = root.getElementById("stage");
103
110
  this.#labelBox = root.getElementById("labels");
104
111
  this.#pool.clear();
@@ -126,6 +133,7 @@ export class ChikyuSpace extends HTMLElement {
126
133
  onRideLost: () => this.#rideLost(),
127
134
  onSatellitesError: (error) => this.dispatchEvent(new CustomEvent("chikyu-satellites-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
128
135
  ...(painter ? { painter } : {}),
136
+ onPainterError: (error) => this.dispatchEvent(new CustomEvent("chikyu-bodies-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
129
137
  });
130
138
  this.#view = taken.renderer.view(this.#stage, item, { still: null });
131
139
  this.#set("loading");
@@ -167,6 +175,10 @@ export class ChikyuSpace extends HTMLElement {
167
175
  this.labels = value !== "off";
168
176
  else if (name === "orbits")
169
177
  this.orbits = value !== "off";
178
+ else if (name === "bodies")
179
+ this.bodies = value ?? "";
180
+ else if (name === "light")
181
+ this.light = readLight(value);
170
182
  }
171
183
  get centre() {
172
184
  return { ...this.#model.centre };
@@ -216,6 +228,29 @@ export class ChikyuSpace extends HTMLElement {
216
228
  label.hidden = true;
217
229
  this.#gate?.request();
218
230
  }
231
+ /**
232
+ * How the Sun, the planets, Pluto and their moons are drawn: one of the `looks` of the body painter set with `setBodyPainter` (wakusei-planets has `realistic` and `painted`), or `plain` (the sphere in the right colour, no moons); empty for the painter's first.
233
+ * With no painter they are plain spheres and this does nothing. Changing it draws the bodies again with the new look.
234
+ */
235
+ get bodies() {
236
+ return this.#model.bodies;
237
+ }
238
+ set bodies(value) {
239
+ this.#model.bodies = value;
240
+ this.#gate?.request();
241
+ }
242
+ /** How the Earth is lit: `sun` (true, the default), `lit` (always lit, as if by daylight from the camera's side, so a ride on the night side is never a black frame) or `boost` (the true terminator, with the night side raised). The Sun, the Moon and the planets keep their true places. */
243
+ get light() {
244
+ return this.#model.light;
245
+ }
246
+ set light(value) {
247
+ this.#model.light = value;
248
+ this.#gate?.request();
249
+ }
250
+ /** The looks the body painter offers (empty with no painter), for a page to build its choice from. */
251
+ get bodyLooks() {
252
+ return painter?.looks ?? [];
253
+ }
219
254
  get orbits() {
220
255
  return this.#model.orbits;
221
256
  }
@@ -391,6 +426,13 @@ export class ChikyuSpace extends HTMLElement {
391
426
  }
392
427
  /** The zoom that shows a part of the sky: the Earth alone, the Moon's orbit, the Sun, the planets out to Mars, or all of them, at this scale and moment. */
393
428
  zoomFor(preset) {
429
+ if (preset.endsWith("-moons")) {
430
+ const name = preset.slice(0, -6);
431
+ const sites = painter?.moons?.(name, this.#model.time) ?? [];
432
+ const reach = Math.max(1, ...sites.map((site) => Math.hypot(...site.offset)).filter((r) => r <= 22));
433
+ const radius = RADIUS[name][this.#model.mode];
434
+ return Math.min(1, (FIT_DISTANCE * radius) / ((reach * radius * 1.15) / Math.tan(17.5 * RAD)));
435
+ }
394
436
  const frame = this.#model.drawn?.frame ?? frameAt(this.#model.time);
395
437
  const mode = this.#model.mode;
396
438
  const sun = placeSun(mode, frame.sun);
@@ -420,6 +462,7 @@ export class ChikyuSpace extends HTMLElement {
420
462
  satellites: this.#satelliteStats(),
421
463
  ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null },
422
464
  camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], fov: this.#model.pose.fov },
465
+ bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons },
423
466
  };
424
467
  }
425
468
  #satelliteStats() {
@@ -20,9 +20,9 @@ export type Vec3 = [number, number, number];
20
20
  * console.log(PLANETS.join(", "));
21
21
  * ```
22
22
  */
23
- export declare const PLANETS: readonly ["Mercury", "Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"];
23
+ export declare const PLANETS: readonly ["Mercury", "Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"];
24
24
  /**
25
- * One of the seven planets drawn, by name.
25
+ * One of the planets drawn (Pluto too), by name.
26
26
  *
27
27
  * @example
28
28
  * ```ts
@@ -11,7 +11,7 @@ import { Body, GeoVector, HelioVector, SiderealTime } from "astronomy-engine";
11
11
  * console.log(PLANETS.join(", "));
12
12
  * ```
13
13
  */
14
- export const PLANETS = ["Mercury", "Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"];
14
+ export const PLANETS = ["Mercury", "Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"];
15
15
  /** Equatorial J2000 axes (x to the vernal equinox, z to the north pole) to the scene's (y up). */
16
16
  const scene = (v) => [v.x, v.z, -v.y];
17
17
  const AU_KM = 149_597_870.7;
@@ -157,7 +157,7 @@ export function createTrack(initialStepMs = 1000) {
157
157
  * ```
158
158
  */
159
159
  export function orbitPath(name, ms, count = 96) {
160
- const periodDays = { Mercury: 87.97, Venus: 224.7, Mars: 686.98, Jupiter: 4332.6, Saturn: 10759, Uranus: 30688, Neptune: 60182 }[name];
160
+ const periodDays = { Mercury: 87.97, Venus: 224.7, Mars: 686.98, Jupiter: 4332.6, Saturn: 10759, Uranus: 30688, Neptune: 60182, Pluto: 90560 }[name];
161
161
  const points = [];
162
162
  for (let i = 0; i <= count; i += 1)
163
163
  points.push(scene(HelioVector(Body[name], new Date(ms + (i / count) * periodDays * 86_400_000))));
@@ -1,4 +1,4 @@
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
- export { plainPainter, type BodyDrawing, type BodyPainter } from "./scene.ts";
3
+ export { plainPainter, type BodyDrawing, type BodyMoon, type BodyPainter, type PaintContext } from "./scene.ts";
4
4
  export { RIDE_FOV, ridePose, type RideInput, type RideLook, type RidePose } from "./ride.ts";
@@ -138,4 +138,5 @@ export const RADIUS = {
138
138
  Saturn: { true: 9.14, compressed: 1.6 },
139
139
  Uranus: { true: 3.98, compressed: 1.0 },
140
140
  Neptune: { true: 3.86, compressed: 1.0 },
141
+ Pluto: { true: 0.186, compressed: 0.4 },
141
142
  };