@johnmorrisdotca/wakusei-planets 0.26.1 → 0.28.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,228 @@
1
+ /** The side of a tile in pixels. */
2
+ export const TILE_SIZE = 512;
3
+ /** The width of the package's own map, the pyramid's level 0. */
4
+ export const BASE_WIDTH = 2048;
5
+ /** The most tiles in a window of picture (a 2048 pixel square, or 4096 by 1024 round a pole) and the most along one side: the graphics memory a window takes is about 22 MB. */
6
+ export const WINDOW_TILES = 16;
7
+ export const WINDOW_SIDE = 8;
8
+ /** How much larger than a device pixel a texel may be before the next level is wanted: 1.25 is a quarter larger. */
9
+ export const TEXEL_SLACK = 1.25;
10
+ const TAU = Math.PI * 2;
11
+ const RAD = Math.PI / 180;
12
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13
+ const whole = (value, min) => typeof value === "number" && Number.isInteger(value) && value >= min;
14
+ /**
15
+ * Read a tile set's `manifest.json`. A manifest that is not the shape this reads, or whose tile size is not the one the loader cuts windows for, is `undefined`: the bodies are then drawn from their own pictures.
16
+ *
17
+ * @param value - The parsed JSON.
18
+ * @returns The manifest, or `undefined`.
19
+ */
20
+ export function parseManifest(value) {
21
+ if (!isRecord(value) || value["tileSize"] !== TILE_SIZE || !isRecord(value["bodies"]))
22
+ return undefined;
23
+ const bodies = {};
24
+ for (const [id, entry] of Object.entries(value["bodies"])) {
25
+ if (!isRecord(entry) || !Array.isArray(entry["levels"]))
26
+ continue;
27
+ const levels = [];
28
+ for (const item of entry["levels"]) {
29
+ if (!isRecord(item))
30
+ continue;
31
+ const { level, width, height, columns, rows } = item;
32
+ if (!whole(level, 1) || !whole(width, TILE_SIZE) || !whole(height, TILE_SIZE) || !whole(columns, 1) || !whole(rows, 1))
33
+ continue;
34
+ if (width !== BASE_WIDTH * 2 ** level || height !== width / 2 || columns !== width / TILE_SIZE || rows !== height / TILE_SIZE)
35
+ continue;
36
+ levels.push({ level, width, height, columns, rows });
37
+ }
38
+ levels.sort((a, b) => a.level - b.level);
39
+ if (levels.length > 0)
40
+ bodies[id] = levels;
41
+ }
42
+ return { tileSize: TILE_SIZE, bodies };
43
+ }
44
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
45
+ const wrapPi = (a) => a - TAU * Math.floor((a + Math.PI) / TAU);
46
+ const SAMPLES = 17;
47
+ /**
48
+ * The longitudes and latitudes of the body's surface that the camera's box shows: the front of the globe is sampled on a grid and round the limb, each point turned into the body's own frame,
49
+ * and the two poles are looked for separately (a pole in view means every longitude is). The region is a little too large rather than too small.
50
+ *
51
+ * @param box - The camera's box.
52
+ * @param axes - The body's axes in the view.
53
+ * @param pad - The margin added all round, as a fraction of the region (and at least two degrees when it is not 0). Default 0.06.
54
+ * @returns The region, or `undefined` when the box shows none of the disc.
55
+ */
56
+ export function visibleRegion(box, axes, pad = 0.06) {
57
+ const lons = [];
58
+ const lats = [];
59
+ const mx = (box.left + box.right) / 2;
60
+ const my = (box.bottom + box.top) / 2;
61
+ let nearest = Infinity;
62
+ let ref = 0;
63
+ const take = (x, y) => {
64
+ const r2 = x * x + y * y;
65
+ if (r2 > 1)
66
+ return;
67
+ const w = [x, y, Math.sqrt(1 - r2)];
68
+ const pm = dot(axes.meridian, w) / axes.scale[2];
69
+ const pe = dot(axes.east, w) / axes.scale[0];
70
+ const pp = dot(axes.pole, w) / axes.scale[1];
71
+ const length = Math.hypot(pm, pe, pp) || 1;
72
+ const lon = Math.atan2(pe, pm);
73
+ // the middle longitude is the one of the sample nearest the middle of the box, so a spread across the antimeridian is measured from there
74
+ const d = (x - mx) * (x - mx) + (y - my) * (y - my);
75
+ if (d < nearest) {
76
+ nearest = d;
77
+ ref = lon;
78
+ }
79
+ lons.push(lon);
80
+ lats.push(Math.asin(Math.max(-1, Math.min(1, pp / length))));
81
+ };
82
+ for (let i = 0; i < SAMPLES; i += 1) {
83
+ for (let j = 0; j < SAMPLES; j += 1)
84
+ take(box.left + ((box.right - box.left) * i) / (SAMPLES - 1), box.bottom + ((box.top - box.bottom) * j) / (SAMPLES - 1));
85
+ }
86
+ // the limb: where the box cuts the edge of the disc, and the edge inside the box
87
+ for (let k = 0; k < 64; k += 1) {
88
+ const a = (k / 64) * TAU;
89
+ const x = Math.cos(a) * 0.999;
90
+ const y = Math.sin(a) * 0.999;
91
+ if (x >= box.left && x <= box.right && y >= box.bottom && y <= box.top)
92
+ take(x, y);
93
+ }
94
+ // the points where the box's own edges cross the disc (a box that cuts the disc without a grid point on it near the edge)
95
+ for (const x of [box.left, box.right]) {
96
+ const half = Math.sqrt(Math.max(0, 1 - x * x));
97
+ if (Math.abs(x) < 1)
98
+ for (const y of [-half * 0.999, half * 0.999])
99
+ if (y >= box.bottom && y <= box.top)
100
+ take(x, y);
101
+ }
102
+ for (const y of [box.bottom, box.top]) {
103
+ const half = Math.sqrt(Math.max(0, 1 - y * y));
104
+ if (Math.abs(y) < 1)
105
+ for (const x of [-half * 0.999, half * 0.999])
106
+ if (x >= box.left && x <= box.right)
107
+ take(x, y);
108
+ }
109
+ if (lons.length === 0)
110
+ return undefined;
111
+ let lo = Infinity;
112
+ let hi = -Infinity;
113
+ for (const lon of lons) {
114
+ const rel = wrapPi(lon - ref);
115
+ if (rel < lo)
116
+ lo = rel;
117
+ if (rel > hi)
118
+ hi = rel;
119
+ }
120
+ let latMin = Math.min(...lats);
121
+ let latMax = Math.max(...lats);
122
+ // a pole in the box: its point is on the front of the disc (it faces the viewer) and inside the box
123
+ let polar = false;
124
+ for (const sign of [1, -1]) {
125
+ const px = axes.pole[0] * axes.scale[1] * sign;
126
+ const py = axes.pole[1] * axes.scale[1] * sign;
127
+ const pz = axes.pole[2] * sign;
128
+ if (pz > 0 && px >= box.left && px <= box.right && py >= box.bottom && py <= box.top) {
129
+ polar = true;
130
+ if (sign > 0)
131
+ latMax = Math.PI / 2;
132
+ else
133
+ latMin = -Math.PI / 2;
134
+ }
135
+ }
136
+ let lonMin = ref + lo;
137
+ let lonMax = ref + hi;
138
+ if (polar || hi - lo > TAU * 0.98) {
139
+ lonMin = ref - Math.PI;
140
+ lonMax = ref + Math.PI;
141
+ }
142
+ // a margin, so a small turn or pan does not at once leave the window
143
+ const padLon = pad > 0 ? Math.max(2 * RAD, (lonMax - lonMin) * pad) : 0;
144
+ const padLat = pad > 0 ? Math.max(2 * RAD, (latMax - latMin) * pad) : 0;
145
+ if (lonMax - lonMin < TAU) {
146
+ const spread = Math.min(TAU, lonMax - lonMin + 2 * padLon);
147
+ const middle = (lonMin + lonMax) / 2;
148
+ lonMin = middle - spread / 2;
149
+ lonMax = middle + spread / 2;
150
+ }
151
+ return { lonMin, lonMax, latMin: Math.max(-Math.PI / 2, latMin - padLat), latMax: Math.min(Math.PI / 2, latMax + padLat) };
152
+ }
153
+ /** The window of a level that holds the region, or `undefined` when it would be more tiles than a window may hold. */
154
+ export function windowOf(level, region) {
155
+ const { columns, rows: rowsTotal } = level;
156
+ const full = region.lonMax - region.lonMin >= TAU - 1e-9;
157
+ let col0 = 0;
158
+ let cols = columns;
159
+ if (!full) {
160
+ const u0 = (region.lonMin / TAU + 0.5) * columns;
161
+ const u1 = (region.lonMax / TAU + 0.5) * columns;
162
+ const first = Math.floor(u0);
163
+ cols = Math.min(columns, Math.ceil(u1) - first);
164
+ col0 = ((first % columns) + columns) % columns;
165
+ }
166
+ const r0 = Math.max(0, Math.floor((0.5 - region.latMax / Math.PI) * rowsTotal));
167
+ const r1 = Math.min(rowsTotal, Math.ceil((0.5 - region.latMin / Math.PI) * rowsTotal));
168
+ const rows = Math.max(1, r1 - r0);
169
+ if (cols * rows > WINDOW_TILES || cols > WINDOW_SIDE || rows > WINDOW_SIDE)
170
+ return undefined;
171
+ return { level: level.level, col0, cols, row0: Math.min(r0, rowsTotal - rows), rows, columns, rowsTotal };
172
+ }
173
+ /**
174
+ * The window the view needs: the lowest level whose texels are no wider than a device pixel (a quarter wider, `TEXEL_SLACK`), or the finest there is, brought down to the finest level whose
175
+ * window fits. `undefined` when the body's own 2048 pixel map is sharp enough, or no level has a window that fits.
176
+ *
177
+ * @param region - The part of the surface in view.
178
+ * @param levels - The body's levels, level 1 up.
179
+ * @param radiansPixels - Device pixels along one radian of the body at the middle of the view.
180
+ * @returns The window, or `undefined`.
181
+ */
182
+ export function chooseWindow(region, levels, radiansPixels) {
183
+ if (levels.length === 0 || !(radiansPixels > 0))
184
+ return undefined;
185
+ const need = radiansPixels / TEXEL_SLACK;
186
+ if (BASE_WIDTH / TAU >= need)
187
+ return undefined;
188
+ const wanted = levels.findIndex((l) => l.width / TAU >= need);
189
+ for (let i = wanted === -1 ? levels.length - 1 : wanted; i >= 0; i -= 1) {
190
+ const window = windowOf(levels[i], region);
191
+ if (window !== undefined)
192
+ return window;
193
+ }
194
+ return undefined;
195
+ }
196
+ /** The window's place on the map, for the shader: `u0` the map's longitude coordinate of its west edge (0 to 1), `du` its width, `vTop` the latitude coordinate of its north edge (1 is the north pole) and `dv` its height. */
197
+ export function windowRect(window) {
198
+ return { u0: window.col0 / window.columns, du: window.cols / window.columns, vTop: 1 - window.row0 / window.rowsTotal, dv: window.rows / window.rowsTotal };
199
+ }
200
+ /** The tiles of a window, with where each goes in the window's picture (`x`, `y` in pixels from its top left). */
201
+ export function windowTiles(window) {
202
+ const out = [];
203
+ for (let j = 0; j < window.rows; j += 1) {
204
+ for (let i = 0; i < window.cols; i += 1)
205
+ out.push({ level: window.level, col: (window.col0 + i) % window.columns, row: window.row0 + j, x: i * TILE_SIZE, y: j * TILE_SIZE });
206
+ }
207
+ return out;
208
+ }
209
+ /** `layer/level/column/row` as the tile's path under the tile set (without the `.webp`). */
210
+ export const tilePath = (body, tile) => `${body}/${tile.level}/${tile.col}/${tile.row}`;
211
+ /** True when the region lies inside the window (the window is then still the right one for the view, whatever else changed). */
212
+ export function covers(window, region) {
213
+ const need = region.lonMax - region.lonMin;
214
+ const width = (window.cols / window.columns) * TAU;
215
+ if (window.cols < window.columns) {
216
+ const start = (window.col0 / window.columns - 0.5) * TAU;
217
+ const shift = ((((region.lonMin - start) % TAU) + TAU) % TAU);
218
+ // a region that starts a hair before the window's edge is a turn later
219
+ const inside = shift + need <= width + 1e-9;
220
+ if (!inside)
221
+ return false;
222
+ }
223
+ const north = (0.5 - window.row0 / window.rowsTotal) * Math.PI;
224
+ const south = (0.5 - (window.row0 + window.rows) / window.rowsTotal) * Math.PI;
225
+ return region.latMax <= north + 1e-9 && region.latMin >= south - 1e-9;
226
+ }
227
+ /** The angle one texel of a level covers, in radians along the equator (`2 pi / width`). */
228
+ export const texelAngle = (width) => TAU / width;
@@ -90,13 +90,20 @@ export type Riding = RideState;
90
90
  * It carries the shared view controls itself: a drag turns the camera round the body, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page), and the arrow keys, + and - and 0 work once it is
91
91
  * focused. `controls="none"` turns them off; `zoom-min` and `zoom-max` set the range (a millionth to 3 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
92
92
  *
93
+ * While time runs (`speed` is not 0) it sends `wakusei-timechange` with `detail: { time, running: true }`, `time` being the moment shown in milliseconds since 1970, at most four times a second however fast the picture is
94
+ * drawn, and once with `running: false` when the clock holds (`speed` 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. `wakusei-time` is sent at every step the clock takes.
95
+ *
93
96
  * @example
94
97
  * ```ts no-run
95
98
  * import type { WakuseiSpace } from "@johnmorrisdotca/wakusei-planets/space/element";
96
99
  *
97
100
  * const space = document.createElement("wakusei-space") as WakuseiSpace;
98
101
  * space.setAttribute("time", "2026-11-02T12:00Z");
99
- * space.setAttribute("speed", "0");
102
+ * space.setAttribute("speed", "86400");
103
+ * space.addEventListener("wakusei-timechange", (event) => {
104
+ * const { time, running } = (event as CustomEvent<{ time: number; running: boolean }>).detail;
105
+ * console.log(new Date(time).toISOString(), running ? "running" : "held");
106
+ * });
100
107
  * document.body.append(space);
101
108
  * ```
102
109
  */
@@ -11,6 +11,8 @@ export { setThreeLoader, SPACE_BODIES };
11
11
  const readLight = (value) => (value === "lit" ? "lit" : "sun");
12
12
  const RAD = Math.PI / 180;
13
13
  const REAL_TIME_TICK_MS = 60_000;
14
+ /** The least time between two `wakusei-timechange` events while time runs: a few a second at most, however fast the picture is drawn. */
15
+ const TIME_EVENT_MS = 250;
14
16
  const readCentre = (value) => {
15
17
  if (!value)
16
18
  return null;
@@ -44,13 +46,20 @@ const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;ove
44
46
  * It carries the shared view controls itself: a drag turns the camera round the body, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page), and the arrow keys, + and - and 0 work once it is
45
47
  * focused. `controls="none"` turns them off; `zoom-min` and `zoom-max` set the range (a millionth to 3 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
46
48
  *
49
+ * While time runs (`speed` is not 0) it sends `wakusei-timechange` with `detail: { time, running: true }`, `time` being the moment shown in milliseconds since 1970, at most four times a second however fast the picture is
50
+ * drawn, and once with `running: false` when the clock holds (`speed` 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. `wakusei-time` is sent at every step the clock takes.
51
+ *
47
52
  * @example
48
53
  * ```ts no-run
49
54
  * import type { WakuseiSpace } from "@johnmorrisdotca/wakusei-planets/space/element";
50
55
  *
51
56
  * const space = document.createElement("wakusei-space") as WakuseiSpace;
52
57
  * space.setAttribute("time", "2026-11-02T12:00Z");
53
- * space.setAttribute("speed", "0");
58
+ * space.setAttribute("speed", "86400");
59
+ * space.addEventListener("wakusei-timechange", (event) => {
60
+ * const { time, running } = (event as CustomEvent<{ time: number; running: boolean }>).detail;
61
+ * console.log(new Date(time).toISOString(), running ? "running" : "held");
62
+ * });
54
63
  * document.body.append(space);
55
64
  * ```
56
65
  */
@@ -67,6 +76,7 @@ export class WakuseiSpace extends HTMLElement {
67
76
  #state = "loading";
68
77
  #timer;
69
78
  #last = 0;
79
+ #announced = -Infinity;
70
80
  #pool = new Map();
71
81
  #places;
72
82
  #names = {};
@@ -132,7 +142,7 @@ export class WakuseiSpace extends HTMLElement {
132
142
  this.#last = performance.now();
133
143
  this.#schedule();
134
144
  this.addEventListener("pointerdown", this.#down);
135
- this.#hands = carryControls(this, { limits: CARRIED_LIMITS, initial: { drag: "turn" }, onChange: (view, info) => this.setView(view, info.final) });
145
+ this.#hands = carryControls(this, { limits: CARRIED_LIMITS, onChange: (view, info) => this.setView(view, info.final) });
136
146
  this.#labelBox.addEventListener("click", this.#labelClick);
137
147
  this.#labelBox.addEventListener("focusin", this.#labelFocus);
138
148
  }
@@ -195,11 +205,17 @@ export class WakuseiSpace extends HTMLElement {
195
205
  return this.#speed;
196
206
  }
197
207
  set speed(value) {
208
+ // time up to this moment is worked out at the old speed, so a hold keeps the moment the reader saw last
209
+ if (this.#speed !== 0 && this.isConnected)
210
+ this.#advance(performance.now());
211
+ const was = this.#speed;
198
212
  this.#speed = Number.isFinite(value) ? value : 1;
199
213
  this.#model.stepMs = Math.max(1000, Math.abs(this.#speed) * 1000);
200
214
  this.#last = performance.now();
201
215
  this.#schedule();
202
216
  this.#gate?.request();
217
+ if (this.#speed === 0 && was !== 0)
218
+ this.#announce(false);
203
219
  }
204
220
  /** `compressed` (the default: every direction real, the distances squeezed) or `true` (real distances and sizes). */
205
221
  get scale() {
@@ -423,16 +439,28 @@ export class WakuseiSpace extends HTMLElement {
423
439
  const wait = !riding && this.#speed === 1 ? REAL_TIME_TICK_MS : 1000 / perSecond;
424
440
  this.#timer = setTimeout(this.#tick, wait);
425
441
  }
426
- #tick = () => {
427
- const now = performance.now();
442
+ /** Bring the moment shown up to `now` (the page's own clock, in milliseconds) at the speed it has run at. */
443
+ #advance(now) {
428
444
  if (this.#speed === 1 && this.#mode === "now")
429
445
  this.#model.time = Date.now();
430
446
  else
431
447
  this.#model.time += (now - this.#last) * this.#speed;
432
448
  this.#last = now;
449
+ }
450
+ /** Tell the page the moment shown: at most four times a second while time runs (`running`), and once, at once, when it holds. */
451
+ #announce(running) {
452
+ const now = performance.now();
453
+ if (running && now - this.#announced < TIME_EVENT_MS)
454
+ return;
455
+ this.#announced = running ? now : -Infinity;
456
+ this.dispatchEvent(new CustomEvent("wakusei-timechange", { detail: { time: this.#model.time, running } }));
457
+ }
458
+ #tick = () => {
459
+ this.#advance(performance.now());
433
460
  this.#gate?.request();
434
461
  this.#schedule();
435
462
  this.dispatchEvent(new CustomEvent("wakusei-time", { detail: { time: this.#model.time } }));
463
+ this.#announce(this.#speed !== 0);
436
464
  };
437
465
  // --- labels --------------------------------------------------------------------------------------------------------------------------------------
438
466
  #nameOf(id) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.26.1";
1
+ export declare const VERSION = "0.28.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.26.1";
1
+ export const VERSION = "0.28.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/wakusei-planets",
3
- "version": "0.26.1",
3
+ "version": "0.28.0",
4
4
  "description": "Wakusei Planets 惑星 — The Sun, planets and moons for the web: each as a clean line drawing, a shaded realistic drawing or a painted surface map, with real sizes, axial tilt and rotation as data, and positions of the moons for any date and time. SVG for the lines, three.js (optional) for the rest.",
5
5
  "keywords": [
6
6
  "planets",
@@ -330,6 +330,8 @@
330
330
  "test:package": "pnpm build && node scripts/check-package.ts",
331
331
  "check": "pnpm lint && pnpm typecheck && pnpm test && pnpm build && node scripts/check-package.ts",
332
332
  "prepublishOnly": "pnpm check",
333
+ "tiles": ".cache/venv/bin/python -I scripts/make-body-tiles.py build",
334
+ "test:tiles": ".cache/venv/bin/python -I scripts/make-body-tiles.py selftest",
333
335
  "family:readme": "node scripts/family-readme.mjs",
334
336
  "readme:images": "node scripts/readme-images.mjs",
335
337
  "site": "pnpm build && node scripts/site.ts",
@@ -385,7 +387,7 @@
385
387
  },
386
388
  "packageManager": "pnpm@10.28.0",
387
389
  "dependencies": {
388
- "@johnmorrisdotca/kazoku-ui": "^0.24.0"
390
+ "@johnmorrisdotca/kazoku-ui": "^0.27.0"
389
391
  },
390
392
  "peerDependencies": {
391
393
  "@johnmorrisdotca/chikyu-earth": ">=0.10.0",