@johnmorrisdotca/wakusei-planets 0.28.0 → 0.31.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/NOTICE.md +20 -0
  3. package/README.md +61 -16
  4. package/dist/embed.d.ts +64 -0
  5. package/dist/embed.js +66 -0
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.js +4 -1
  8. package/dist/lineup/data.d.ts +160 -0
  9. package/dist/lineup/data.js +303 -0
  10. package/dist/lineup/element.d.ts +99 -0
  11. package/dist/lineup/element.js +782 -0
  12. package/dist/lineup/labels.d.ts +141 -0
  13. package/dist/lineup/labels.js +155 -0
  14. package/dist/lineup/layout.d.ts +174 -0
  15. package/dist/lineup/layout.js +162 -0
  16. package/dist/lineup/scene3d.d.ts +47 -0
  17. package/dist/lineup/scene3d.js +155 -0
  18. package/dist/portrait/element.d.ts +5 -2
  19. package/dist/portrait/element.js +57 -6
  20. package/dist/portrait/scene3d.d.ts +13 -0
  21. package/dist/portrait/scene3d.js +21 -2
  22. package/dist/scene/body.d.ts +3 -1
  23. package/dist/scene/body.js +2 -1
  24. package/dist/scene/detail.d.ts +8 -2
  25. package/dist/scene/detail.js +56 -28
  26. package/dist/scene/painter.d.ts +32 -0
  27. package/dist/scene/painter.js +94 -10
  28. package/dist/scene/textures.d.ts +4 -2
  29. package/dist/scene/textures.js +2 -0
  30. package/dist/scene/tiles.d.ts +46 -0
  31. package/dist/scene/tiles.js +165 -19
  32. package/dist/space/arrows.d.ts +87 -0
  33. package/dist/space/arrows.js +117 -0
  34. package/dist/space/beside.d.ts +74 -0
  35. package/dist/space/beside.js +76 -0
  36. package/dist/space/bodies.d.ts +83 -0
  37. package/dist/space/bodies.js +93 -0
  38. package/dist/space/clock.d.ts +31 -0
  39. package/dist/space/clock.js +45 -0
  40. package/dist/space/element.d.ts +98 -15
  41. package/dist/space/element.js +320 -63
  42. package/dist/space/frame.d.ts +45 -2
  43. package/dist/space/frame.js +56 -4
  44. package/dist/space/index.d.ts +6 -1
  45. package/dist/space/index.js +6 -1
  46. package/dist/space/labels.d.ts +52 -0
  47. package/dist/space/labels.js +40 -0
  48. package/dist/space/scale.d.ts +5 -5
  49. package/dist/space/scale.js +10 -4
  50. package/dist/space/scene.d.ts +50 -9
  51. package/dist/space/scene.js +313 -36
  52. package/dist/space/spin.d.ts +37 -0
  53. package/dist/space/spin.js +29 -0
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +1 -1
  56. package/package.json +8 -1
@@ -1,11 +1,13 @@
1
1
  import "../bodies/all.js";
2
2
  import { BODIES, MOONS_OF } from "../facts.js";
3
3
  import { writeBasis } from "./basis.js";
4
- import { TEXTURE_BASE, TEXTURE_FAR_BASE, slash, loadImage } from "./textures.js";
4
+ import { TEXTURE_BASE, TEXTURE_FAR_BASE, TILES_BASE, slash, loadImage, tilesAllowed } from "./textures.js";
5
5
  import { cross } from "../vec.js";
6
- import { bodyFragment, GLOW_FRAGMENT, GLOW_VERTEX, PAINTED_SURFACE, RING_FRAGMENT_WORLD, RING_VERTEX_WORLD, VERTEX_WORLD } from "./glsl.js";
6
+ import { bodyFragment, GLOW_FRAGMENT, GLOW_VERTEX, PAINTED_SURFACE, PAINTED_SURFACE_WINDOWED, RING_FRAGMENT_WORLD, RING_VERTEX_WORLD, VERTEX_WORLD } from "./glsl.js";
7
7
  import { fallbackLook } from "./fallback.js";
8
- import { lookOf } from "./look.js";
8
+ import { createDetail } from "./detail.js";
9
+ import { detailOf, lookOf } from "./look.js";
10
+ import { seenRegion } from "./tiles.js";
9
11
  import { moonOffset, orientation } from "./orient.js";
10
12
  import { ringStrip } from "./rings.js";
11
13
  export { moonOffset, orientation };
@@ -59,10 +61,38 @@ const moonsOf = (planet) => {
59
61
  const id = planet.toLowerCase();
60
62
  return id === "earth" ? [] : id in MOONS_OF ? MOONS_OF[id] : [];
61
63
  };
64
+ /** A body whose disc is at least this many device pixels across its radius is worked out for tiles; a smaller one cannot want them, and is not looked at. */
65
+ const TILES_FROM_PX = 150;
66
+ /** A three.js camera as the region maths sees it. */
67
+ function sightOf(T, view) {
68
+ const { camera, width, height } = view;
69
+ camera.updateMatrixWorld();
70
+ const a = new T.Vector3();
71
+ const b = new T.Vector3();
72
+ const perspective = camera.isPerspectiveCamera === true;
73
+ const eye = perspective ? camera.getWorldPosition(new T.Vector3()) : undefined;
74
+ const forward = camera.getWorldDirection(new T.Vector3());
75
+ return {
76
+ eye: eye === undefined ? null : [eye.x, eye.y, eye.z],
77
+ forward: [forward.x, forward.y, forward.z],
78
+ width,
79
+ height,
80
+ ray(x, y) {
81
+ a.set(x, y, -1).unproject(camera);
82
+ b.set(x, y, 1).unproject(camera);
83
+ b.sub(a).normalize();
84
+ return { origin: [a.x, a.y, a.z], direction: [b.x, b.y, b.z] };
85
+ },
86
+ project(point) {
87
+ a.set(point[0], point[1], point[2]).project(camera);
88
+ return a.z < -1 || a.z > 1 ? undefined : { x: a.x, y: a.y };
89
+ },
90
+ };
91
+ }
62
92
  function paint(T, id, context, bases) {
63
93
  const facts = BODIES[id];
64
94
  const look = lookOf(id) ?? fallbackLook(facts);
65
- const wantPainted = (context.look === "painted" || look.mapped === true) && look.painted !== undefined;
95
+ const wantPainted = (context.look === "painted" || look.mapped === true || context.mapped === true) && look.painted !== undefined;
66
96
  const ratio = context.ratio ?? 1;
67
97
  const maxWidth = context.maxTexture ?? 2048;
68
98
  const redraw = () => context.invalidate?.();
@@ -72,9 +102,20 @@ function paint(T, id, context, bases) {
72
102
  releases.push(sphere.release);
73
103
  const group = new T.Group();
74
104
  group.name = facts.name.en;
105
+ // a glowing body (the Sun) is drawn as it always was: no window of finer map and no generic detail
106
+ const generic = look.emissive !== true;
107
+ const fine = detailOf(look);
75
108
  const uniforms = (painted) => {
76
109
  const a = look.atmosphere;
77
110
  return {
111
+ ...(generic
112
+ ? {
113
+ uTexel: { value: painted ? (2 * Math.PI) / (look.painted?.widths[0] ?? 2048) : 0.005 },
114
+ uDetailAmp: { value: fine.amount },
115
+ uDetailStretch: { value: fine.stretch },
116
+ ...(painted ? { uDetail: { value: null }, uDetailRect: { value: [0, 1, 1, 1] }, uDetailFade: { value: new T.Vector2(0, 0) }, uDetailOn: { value: 0 }, uDetailTexel: { value: 0.003 } } : {}),
117
+ }
118
+ : {}),
78
119
  uLight: { value: new T.Vector3(1, 0, 0) },
79
120
  uRelief: { value: painted ? (look.painted?.relief ?? 0) : (look.relief ?? 0.6) },
80
121
  uAmbient: { value: look.ambient ?? 0.04 },
@@ -95,7 +136,7 @@ function paint(T, id, context, bases) {
95
136
  };
96
137
  };
97
138
  const material = (painted) => {
98
- const m = new T.ShaderMaterial({ vertexShader: VERTEX_WORLD, fragmentShader: bodyFragment(painted ? PAINTED_SURFACE : look.surface, painted, true), uniforms: uniforms(painted) });
139
+ const m = new T.ShaderMaterial({ vertexShader: VERTEX_WORLD, fragmentShader: bodyFragment(painted ? (generic ? PAINTED_SURFACE_WINDOWED : PAINTED_SURFACE) : look.surface, painted, true, undefined, generic), uniforms: uniforms(painted) });
99
140
  disposables.push(m);
100
141
  return m;
101
142
  };
@@ -201,8 +242,10 @@ function paint(T, id, context, bases) {
201
242
  t.colorSpace = T.NoColorSpace;
202
243
  return t;
203
244
  };
204
- const show = (t) => {
245
+ const show = (t, w) => {
205
246
  paintedMaterial.uniforms.uMap.value = t;
247
+ if (paintedMaterial.uniforms.uTexel !== undefined)
248
+ paintedMaterial.uniforms.uTexel.value = (2 * Math.PI) / w;
206
249
  mesh.material = paintedMaterial;
207
250
  // the shaded look was drawn only until the picture came: if it was drawn at all, its program is let go now, so what a body holds does not depend on which came first
208
251
  shader.dispose();
@@ -216,7 +259,7 @@ function paint(T, id, context, bases) {
216
259
  }
217
260
  small = prepare(t);
218
261
  if (sharp === undefined)
219
- show(small);
262
+ show(small, widths[0]);
220
263
  }, () => {
221
264
  failed = true;
222
265
  });
@@ -238,7 +281,7 @@ function paint(T, id, context, bases) {
238
281
  const old = sharp;
239
282
  sharp = prepare(t);
240
283
  sharpWidth = next;
241
- show(sharp);
284
+ show(sharp, next);
242
285
  old?.dispose();
243
286
  }, () => {
244
287
  loading = false;
@@ -250,7 +293,7 @@ function paint(T, id, context, bases) {
250
293
  if (tooBigSince === 0)
251
294
  tooBigSince = now;
252
295
  else if (now - tooBigSince > 4000) {
253
- show(small);
296
+ show(small, widths[0]);
254
297
  sharp.dispose();
255
298
  sharp = undefined;
256
299
  sharpWidth = 0;
@@ -261,6 +304,30 @@ function paint(T, id, context, bases) {
261
304
  else
262
305
  tooBigSince = 0;
263
306
  };
307
+ // the window of finer map tiles for a close view, laid over the painted map by the painted material (see `scene/detail.ts`); only for a body that is told which camera sees it
308
+ const windowUniforms = wantPainted && paintedMaterial !== undefined && generic && bases.tiles !== undefined && look.painted !== undefined ? paintedMaterial.uniforms : undefined;
309
+ const detail = windowUniforms === undefined
310
+ ? undefined
311
+ : createDetail(T, {
312
+ base: () => bases.tiles,
313
+ body: look.painted.map,
314
+ ratio: () => ratio,
315
+ allowed: tilesAllowed,
316
+ redraw,
317
+ ...(context.onLevels === undefined ? {} : { onLevels: (levels) => context.onLevels(levels) }),
318
+ apply: (shown) => {
319
+ if (shown === null) {
320
+ windowUniforms.uDetailOn.value = 0;
321
+ windowUniforms.uDetail.value = null;
322
+ return;
323
+ }
324
+ windowUniforms.uDetail.value = shown.texture;
325
+ windowUniforms.uDetailRect.value = [shown.rect.u0, shown.rect.vTop, shown.rect.du, shown.rect.dv];
326
+ windowUniforms.uDetailFade.value.set(shown.fade.u, shown.fade.v);
327
+ windowUniforms.uDetailTexel.value = shown.texel;
328
+ windowUniforms.uDetailOn.value = 1;
329
+ },
330
+ });
264
331
  const axes = facts.axesKm;
265
332
  const scaleX = axes ? axes[1] / facts.radiusKm : 1;
266
333
  const scaleY = axes ? axes[2] / facts.radiusKm : 1 - facts.flattening;
@@ -270,12 +337,22 @@ function paint(T, id, context, bases) {
270
337
  return {
271
338
  object: group,
272
339
  ...(look.emissive === true ? { billboard: true } : {}),
340
+ get tiles() {
341
+ return detail?.stats;
342
+ },
273
343
  update(info) {
274
344
  light.set(info.toSun[0], info.toSun[1], info.toSun[2]);
275
345
  const scale = group.scale.x || 1;
276
346
  if (look.emissive !== true) {
277
347
  const { pole, meridian } = info.pose ?? orientation(id, info.ms);
278
348
  const east = cross(pole, meridian);
349
+ if (detail !== undefined) {
350
+ // a body big enough in the view, seen by a camera we were told of, is worked out for a window of finer map; any other keeps the pictures it has
351
+ if (info.view === undefined || mesh.material !== paintedMaterial || info.radiusPx * ratio < TILES_FROM_PX)
352
+ detail.rest();
353
+ else
354
+ detail.follow(seenRegion(sightOf(T, info.view), { centre: [group.position.x, group.position.y, group.position.z], radius: scale, axes: { east, pole, meridian, scale: [scaleX, scaleY, scaleZ] } }));
355
+ }
279
356
  writeBasis(mesh.matrix, east, pole, meridian, scaleX, scaleY, scaleZ);
280
357
  if (ringMesh !== undefined)
281
358
  writeBasis(ringMesh.matrix, meridian, east, pole);
@@ -301,6 +378,11 @@ function paint(T, id, context, bases) {
301
378
  },
302
379
  dispose() {
303
380
  gone = true;
381
+ if (windowUniforms !== undefined) {
382
+ windowUniforms.uDetailOn.value = 0;
383
+ windowUniforms.uDetail.value = null;
384
+ }
385
+ detail?.dispose();
304
386
  small?.dispose();
305
387
  sharp?.dispose();
306
388
  ringTexture?.dispose();
@@ -329,9 +411,11 @@ function paint(T, id, context, bases) {
329
411
  export function createPainter(options = {}) {
330
412
  const near = slash(options.textureBase ?? TEXTURE_BASE);
331
413
  const far = slash(options.farBase ?? (options.textureBase !== undefined ? options.textureBase : TEXTURE_FAR_BASE));
414
+ const own = options.tiles;
415
+ const tiles = own === "off" || own === "none" || own === "" ? undefined : own !== undefined ? slash(own) : options.textureBase !== undefined ? undefined : TILES_BASE;
332
416
  return {
333
417
  looks: LOOKS,
334
- make: (three, name, context = {}) => paint(three, idOf(name), context, { near, far }),
418
+ make: (three, name, context = {}) => paint(three, idOf(name), context, { near, far, tiles }),
335
419
  moons(planet, ms) {
336
420
  const radius = BODIES[idOf(planet)]?.radiusKm;
337
421
  if (radius === undefined)
@@ -9,7 +9,7 @@ import type * as THREE from "three";
9
9
  * console.log(TEXTURE_BASE);
10
10
  * ```
11
11
  */
12
- export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdotca/wakusei-planets@0.28.0/dist/textures/";
12
+ export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdotca/wakusei-planets@0.31.0/dist/textures/";
13
13
  /**
14
14
  * Where the sharpest surface pictures are: the files of this exact version in the repository, on jsDelivr's GitHub address. The npm package holds only the two smaller widths, so a page that
15
15
  * never zooms in never fetches them. Set `texture-far-base` on an element to serve them yourself.
@@ -21,7 +21,7 @@ export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdot
21
21
  * console.log(TEXTURE_FAR_BASE);
22
22
  * ```
23
23
  */
24
- export declare const TEXTURE_FAR_BASE = "https://cdn.jsdelivr.net/gh/johnmorrisdotca/wakusei-planets@v0.28.0/textures/";
24
+ export declare const TEXTURE_FAR_BASE = "https://cdn.jsdelivr.net/gh/johnmorrisdotca/wakusei-planets@v0.31.0/textures/";
25
25
  /**
26
26
  * Where the finer map tiles are by default: the demo site's `tiles/` folder (GitHub Pages sends `access-control-allow-origin: *`). The tiles are made by `scripts/make-body-tiles.py` and are in no package and no repository:
27
27
  * a page that serves its own gives the folder in the `tiles` attribute, and `tiles="off"` turns them off. A page that sets `texture-base` (it serves its own pictures) has none unless it says where they are.
@@ -42,3 +42,5 @@ export declare function texturePaths(element: Element): {
42
42
  farBase(): string;
43
43
  };
44
44
  export declare function loadImage(three: Pick<typeof THREE, "TextureLoader">, url: string): Promise<THREE.Texture>;
45
+ /** False on a device that says it has 2 GB of memory or less: it keeps to the package's own pictures. */
46
+ export declare const tilesAllowed: () => boolean;
@@ -66,3 +66,5 @@ export function loadImage(three, url) {
66
66
  loader.load(url, resolve, undefined, (error) => reject(error instanceof Error ? error : new Error("texture failed")));
67
67
  });
68
68
  }
69
+ /** False on a device that says it has 2 GB of memory or less: it keeps to the package's own pictures. */
70
+ export const tilesAllowed = () => ((typeof navigator === "undefined" ? undefined : navigator.deviceMemory) ?? 8) > 2;
@@ -106,3 +106,49 @@ export declare const tilePath: (body: string, tile: {
106
106
  export declare function covers(window: TileWindow, region: Region): boolean;
107
107
  /** The angle one texel of a level covers, in radians along the equator (`2 pi / width`). */
108
108
  export declare const texelAngle: (width: number) => number;
109
+ /**
110
+ * A camera as the region maths needs it: where the eye is, which way it looks, the ray through any point of the view and where a world point lands in it. The parts of a three.js camera are all it takes (`unproject` and `project`),
111
+ * so an orthographic camera (the portrait) and a perspective one (the space view) are the same to the maths below.
112
+ */
113
+ export interface Sight {
114
+ /** Where the eye is, or `null` for a camera whose rays are parallel (orthographic). */
115
+ eye: Vec3 | null;
116
+ /** The way the camera looks, a unit vector. */
117
+ forward: Vec3;
118
+ /** The ray through a point of the view, `x` and `y` from -1 (left, bottom) to 1 (right, top): its origin and a unit direction. */
119
+ ray(x: number, y: number): {
120
+ origin: Vec3;
121
+ direction: Vec3;
122
+ };
123
+ /** Where a world point lies in the view, `x` and `y` from -1 to 1, or `undefined` when it is behind the camera or beyond what the camera draws. */
124
+ project(point: Vec3): {
125
+ x: number;
126
+ y: number;
127
+ } | undefined;
128
+ /** The view's width and height in CSS pixels. */
129
+ width: number;
130
+ height: number;
131
+ }
132
+ /** Where a body is in the camera's world: its centre, its mean radius, and its axes (`east`, `pole` and `meridian` in the world, `scale` the lengths of its semi-axes in radii, in that order). */
133
+ export interface Placing {
134
+ centre: Vec3;
135
+ radius: number;
136
+ axes: Axes;
137
+ }
138
+ /** What a camera sees of a body: the part of the surface in view with a margin and without, and how many device pixels (at a pixel ratio of 1) run along a radian of the surface where it is nearest the camera. */
139
+ export interface Seen {
140
+ region: Region;
141
+ inside: Region;
142
+ radiansPixels: number;
143
+ }
144
+ /**
145
+ * The part of a body's surface a camera sees: rays through a grid of the view are met with the body (turned into its own frame, where the surface is the unit sphere), and so are points of the cap that faces the eye (they
146
+ * find a small patch at a deep zoom, and the whole near side when the body is small in the view), with its edge, and the poles are looked for separately. The region is a little too large rather than too small. The same maths
147
+ * works for an orthographic camera and a perspective one, and for a body off to one side of the view.
148
+ *
149
+ * @param sight - The camera.
150
+ * @param placing - Where the body is.
151
+ * @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.
152
+ * @returns The region with its margin, the region without, and the finest device pixels along a radian anywhere in view; or `undefined` when the camera sees none of the body.
153
+ */
154
+ export declare function seenRegion(sight: Sight, placing: Placing, pad?: number): Seen | undefined;
@@ -108,6 +108,21 @@ export function visibleRegion(box, axes, pad = 0.06) {
108
108
  }
109
109
  if (lons.length === 0)
110
110
  return undefined;
111
+ const raw = closeRegion(lons, lats, ref, poleIn(box, axes, 1), poleIn(box, axes, -1));
112
+ return padRegion(raw, pad);
113
+ }
114
+ /** True when the pole (`sign` 1 north, -1 south) lies on the front of the disc and inside the box. */
115
+ function poleIn(box, axes, sign) {
116
+ const px = axes.pole[0] * axes.scale[1] * sign;
117
+ const py = axes.pole[1] * axes.scale[1] * sign;
118
+ const pz = axes.pole[2] * sign;
119
+ return pz > 0 && px >= box.left && px <= box.right && py >= box.bottom && py <= box.top;
120
+ }
121
+ /**
122
+ * The longitudes and latitudes of the points seen, as a region with no margin: the stretch of longitude measured from `ref` (the longitude of the point nearest the middle of the view, so a spread across the antimeridian is
123
+ * one stretch), the whole turn when a pole is in view or the spread is nearly all of it, and the poles' latitudes when they are in view.
124
+ */
125
+ function closeRegion(lons, lats, ref, north, south) {
111
126
  let lo = Infinity;
112
127
  let hi = -Infinity;
113
128
  for (const lon of lons) {
@@ -117,38 +132,38 @@ export function visibleRegion(box, axes, pad = 0.06) {
117
132
  if (rel > hi)
118
133
  hi = rel;
119
134
  }
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
+ let latMin = Infinity;
136
+ let latMax = -Infinity;
137
+ for (const lat of lats) {
138
+ if (lat < latMin)
139
+ latMin = lat;
140
+ if (lat > latMax)
141
+ latMax = lat;
135
142
  }
143
+ if (north)
144
+ latMax = Math.PI / 2;
145
+ if (south)
146
+ latMin = -Math.PI / 2;
136
147
  let lonMin = ref + lo;
137
148
  let lonMax = ref + hi;
138
- if (polar || hi - lo > TAU * 0.98) {
149
+ if (north || south || hi - lo > TAU * 0.98) {
139
150
  lonMin = ref - Math.PI;
140
151
  lonMax = ref + Math.PI;
141
152
  }
142
- // a margin, so a small turn or pan does not at once leave the window
153
+ return { lonMin, lonMax, latMin, latMax };
154
+ }
155
+ /** A margin all round a region, so a small turn or pan does not at once leave the window: a fraction of its size, and at least two degrees when `pad` is not 0. */
156
+ function padRegion(region, pad) {
157
+ let { lonMin, lonMax } = region;
143
158
  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;
159
+ const padLat = pad > 0 ? Math.max(2 * RAD, (region.latMax - region.latMin) * pad) : 0;
145
160
  if (lonMax - lonMin < TAU) {
146
161
  const spread = Math.min(TAU, lonMax - lonMin + 2 * padLon);
147
162
  const middle = (lonMin + lonMax) / 2;
148
163
  lonMin = middle - spread / 2;
149
164
  lonMax = middle + spread / 2;
150
165
  }
151
- return { lonMin, lonMax, latMin: Math.max(-Math.PI / 2, latMin - padLat), latMax: Math.min(Math.PI / 2, latMax + padLat) };
166
+ return { lonMin, lonMax, latMin: Math.max(-Math.PI / 2, region.latMin - padLat), latMax: Math.min(Math.PI / 2, region.latMax + padLat) };
152
167
  }
153
168
  /** The window of a level that holds the region, or `undefined` when it would be more tiles than a window may hold. */
154
169
  export function windowOf(level, region) {
@@ -226,3 +241,134 @@ export function covers(window, region) {
226
241
  }
227
242
  /** The angle one texel of a level covers, in radians along the equator (`2 pi / width`). */
228
243
  export const texelAngle = (width) => TAU / width;
244
+ const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
245
+ const norm3 = (a) => {
246
+ const l = Math.hypot(a[0], a[1], a[2]) || 1;
247
+ return [a[0] / l, a[1] / l, a[2] / l];
248
+ };
249
+ const cross3 = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
250
+ const GRID = 17;
251
+ const CAP = 33;
252
+ const RING = 64;
253
+ /**
254
+ * The part of a body's surface a camera sees: rays through a grid of the view are met with the body (turned into its own frame, where the surface is the unit sphere), and so are points of the cap that faces the eye (they
255
+ * find a small patch at a deep zoom, and the whole near side when the body is small in the view), with its edge, and the poles are looked for separately. The region is a little too large rather than too small. The same maths
256
+ * works for an orthographic camera and a perspective one, and for a body off to one side of the view.
257
+ *
258
+ * @param sight - The camera.
259
+ * @param placing - Where the body is.
260
+ * @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.
261
+ * @returns The region with its margin, the region without, and the finest device pixels along a radian anywhere in view; or `undefined` when the camera sees none of the body.
262
+ */
263
+ export function seenRegion(sight, placing, pad = 0.06) {
264
+ const { centre, radius, axes } = placing;
265
+ const [se, sp, sm] = axes.scale;
266
+ // a world vector in the body's frame: x along the prime meridian, y east, z along the pole, the surface the unit sphere
267
+ const inBody = (v) => [dot(axes.meridian, v) / (radius * sm), dot(axes.east, v) / (radius * se), dot(axes.pole, v) / (radius * sp)];
268
+ const around = (unitSphere) => {
269
+ const m = dot(axes.meridian, unitSphere);
270
+ const e = dot(axes.east, unitSphere);
271
+ const q = dot(axes.pole, unitSphere);
272
+ return [
273
+ centre[0] + radius * (sm * m * axes.meridian[0] + se * e * axes.east[0] + sp * q * axes.pole[0]),
274
+ centre[1] + radius * (sm * m * axes.meridian[1] + se * e * axes.east[1] + sp * q * axes.pole[1]),
275
+ centre[2] + radius * (sm * m * axes.meridian[2] + se * e * axes.east[2] + sp * q * axes.pole[2]),
276
+ ];
277
+ };
278
+ const first = sight.ray(0, 0).origin;
279
+ const lons = [];
280
+ const lats = [];
281
+ let middle = Infinity;
282
+ let ref = 0;
283
+ let depth = Infinity;
284
+ let nearest;
285
+ const take = (h, at, world) => {
286
+ const length = Math.hypot(h[0], h[1], h[2]) || 1;
287
+ const lon = Math.atan2(h[1], h[0]);
288
+ const d = at.x * at.x + at.y * at.y;
289
+ if (d < middle) {
290
+ middle = d;
291
+ ref = lon;
292
+ }
293
+ const away = dot(sub3(world, first), sight.forward);
294
+ if (away < depth) {
295
+ depth = away;
296
+ nearest = world;
297
+ }
298
+ lons.push(lon);
299
+ lats.push(Math.asin(Math.max(-1, Math.min(1, h[2] / length))));
300
+ };
301
+ // rays through a grid of the view
302
+ for (let i = 0; i < GRID; i += 1) {
303
+ for (let j = 0; j < GRID; j += 1) {
304
+ const x = -1 + (2 * i) / (GRID - 1);
305
+ const y = -1 + (2 * j) / (GRID - 1);
306
+ const { origin, direction } = sight.ray(x, y);
307
+ const o = inBody(sub3(origin, centre));
308
+ const d = inBody(direction);
309
+ const a = dot(d, d);
310
+ const b = dot(o, d);
311
+ const c = dot(o, o) - 1;
312
+ const disc = b * b - a * c;
313
+ if (disc <= 0 || a === 0)
314
+ continue;
315
+ const t = (-b - Math.sqrt(disc)) / a;
316
+ if (t < 0)
317
+ continue;
318
+ take([o[0] + t * d[0], o[1] + t * d[1], o[2] + t * d[2]], { x, y }, [origin[0] + t * direction[0], origin[1] + t * direction[1], origin[2] + t * direction[2]]);
319
+ }
320
+ }
321
+ // the cap that faces the eye, and the edge of it: the part of the body a small view of a distant body, or a view at its edge, shows
322
+ const eye = sight.eye;
323
+ const distance = eye === null ? Infinity : Math.hypot(eye[0] - centre[0], eye[1] - centre[1], eye[2] - centre[2]) / radius;
324
+ if (distance <= 1.0001)
325
+ return undefined;
326
+ const n0 = eye === null ? [-sight.forward[0], -sight.forward[1], -sight.forward[2]] : norm3(sub3(eye, centre));
327
+ const helper = Math.abs(n0[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
328
+ const t1 = norm3(cross3(helper, n0));
329
+ const t2 = cross3(n0, t1);
330
+ const reach = eye === null ? 1 : Math.sqrt(1 - 1 / (distance * distance));
331
+ const tryCap = (a, b) => {
332
+ const u = a * reach;
333
+ const v = b * reach;
334
+ const w = Math.sqrt(Math.max(0, 1 - u * u - v * v));
335
+ const n = [u * t1[0] + v * t2[0] + w * n0[0], u * t1[1] + v * t2[1] + w * n0[1], u * t1[2] + v * t2[2] + w * n0[2]];
336
+ const world = around(n);
337
+ const at = sight.project(world);
338
+ if (at === undefined || Math.abs(at.x) > 1 || Math.abs(at.y) > 1)
339
+ return;
340
+ take([dot(axes.meridian, n), dot(axes.east, n), dot(axes.pole, n)], at, world);
341
+ };
342
+ for (let i = 0; i < CAP; i += 1) {
343
+ for (let j = 0; j < CAP; j += 1) {
344
+ const a = -1 + (2 * i) / (CAP - 1);
345
+ const b = -1 + (2 * j) / (CAP - 1);
346
+ if (a * a + b * b <= 1)
347
+ tryCap(a, b);
348
+ }
349
+ }
350
+ for (let k = 0; k < RING; k += 1)
351
+ tryCap(Math.cos((k / RING) * TAU), Math.sin((k / RING) * TAU));
352
+ if (lons.length === 0 || nearest === undefined)
353
+ return undefined;
354
+ // a pole in view: it faces the camera and lands inside the view
355
+ const poleSeen = (sign) => {
356
+ const normal = [axes.pole[0] * sign, axes.pole[1] * sign, axes.pole[2] * sign];
357
+ const point = [centre[0] + radius * sp * normal[0], centre[1] + radius * sp * normal[1], centre[2] + radius * sp * normal[2]];
358
+ const toEye = eye === null ? [-sight.forward[0], -sight.forward[1], -sight.forward[2]] : sub3(eye, point);
359
+ if (dot(normal, toEye) <= 0)
360
+ return false;
361
+ const at = sight.project(point);
362
+ return at !== undefined && Math.abs(at.x) <= 1 && Math.abs(at.y) <= 1;
363
+ };
364
+ const inside = closeRegion(lons, lats, ref, poleSeen(1), poleSeen(-1));
365
+ // how many pixels run along a radian of the surface where it is nearest: a small step across the line of sight, projected
366
+ const across = norm3(cross3(sight.forward, Math.abs(sight.forward[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0]));
367
+ const step = radius * 0.01;
368
+ const a = sight.project(nearest);
369
+ const b = sight.project([nearest[0] + across[0] * step, nearest[1] + across[1] * step, nearest[2] + across[2] * step]);
370
+ if (a === undefined || b === undefined)
371
+ return undefined;
372
+ const pixels = Math.hypot(((b.x - a.x) * sight.width) / 2, ((b.y - a.y) * sight.height) / 2) / step;
373
+ return { region: padRegion(inside, pad), inside, radiansPixels: pixels * radius * ((se + sp + sm) / 3) };
374
+ }
@@ -0,0 +1,87 @@
1
+ import { type Vec3 } from "../vec.ts";
2
+ /**
3
+ * How many arrowheads an orbit line carries.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { ARROWS_PER_ORBIT } from "@johnmorrisdotca/wakusei-planets/space";
8
+ *
9
+ * console.log(ARROWS_PER_ORBIT);
10
+ * ```
11
+ */
12
+ export declare const ARROWS_PER_ORBIT = 6;
13
+ /**
14
+ * One arrowhead on an orbit line: where its tip is and the way it points, the way the body goes along the line.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import type { OrbitArrow } from "@johnmorrisdotca/wakusei-planets/space";
19
+ *
20
+ * const arrow: OrbitArrow = { position: [1, 0, 0], direction: [0, 1, 0] };
21
+ * console.log(arrow.direction);
22
+ * ```
23
+ */
24
+ export interface OrbitArrow {
25
+ position: Vec3;
26
+ direction: Vec3;
27
+ }
28
+ /**
29
+ * Where the arrowheads go on an orbit line, and which way each points. The line is the points of `planetOrbit` as the view places them: they run from where the body is now once round in the order the body
30
+ * goes, so the direction of each arrow is the line's own direction there, from the point before to the point after. The arrows are spread evenly round the line and stay clear of the body, which is at its first point.
31
+ * They show the real way the body travels, which is the same whichever way the clock runs.
32
+ *
33
+ * @param line - The orbit line, `count + 1` points whose last is near the first.
34
+ * @param arrows - How many arrowheads (`ARROWS_PER_ORBIT` by default).
35
+ * @returns The arrows, each at a point of the line.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { arrowSites } from "@johnmorrisdotca/wakusei-planets/space";
40
+ *
41
+ * const circle = Array.from({ length: 97 }, (_, i) => [Math.cos((i / 96) * 2 * Math.PI), 0, Math.sin((i / 96) * 2 * Math.PI)] as const);
42
+ * console.log(arrowSites(circle, 4).map((a) => a.direction.map((n) => n.toFixed(2)).join(",")).join(" | "));
43
+ * ```
44
+ */
45
+ export declare function arrowSites(line: readonly (readonly [number, number, number])[], arrows?: number): OrbitArrow[];
46
+ /**
47
+ * The three points of a small arrowhead that is `size` long in the picture: its tip at `position`, and the ends of its two wings, laid in the plane of the picture so it points the way `direction` goes on the screen.
48
+ * A direction straight into or out of the picture has no way on the screen and gives none.
49
+ *
50
+ * @param position - The tip, in the scene's units.
51
+ * @param direction - The way it points in the scene.
52
+ * @param right - The camera's right-hand direction (a unit vector).
53
+ * @param up - The camera's up direction (a unit vector).
54
+ * @param size - The length of a wing, in the scene's units at the tip (pixels times the size of a pixel there).
55
+ * @returns The tip and the two wing ends, or `null`.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * import { chevron } from "@johnmorrisdotca/wakusei-planets/space";
60
+ *
61
+ * console.log(chevron([0, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], 2)?.map((p) => p.map((n) => n.toFixed(1)).join(",")).join(" "));
62
+ * ```
63
+ */
64
+ export declare function chevron(position: Vec3, direction: Vec3, right: Vec3, up: Vec3, size: number): [Vec3, Vec3, Vec3] | null;
65
+ /**
66
+ * The curved arrow of the help mode: points on a circle round the axis a body spins about, turning the way it turns (by the right-hand rule about `axis`), as `segments + 1` points from its tail to its head, and the
67
+ * two ends of the head's wings. The circle has radius `radius` and sits `lift` along the axis from `centre`; the arc covers 250 degrees, ending where it started 250 degrees on.
68
+ *
69
+ * @param centre - The body's centre.
70
+ * @param axis - The unit axis it spins about (the right-hand rule: the fingers curl the way it turns).
71
+ * @param radius - The circle's radius, in the scene's units.
72
+ * @param lift - How far along the axis the circle is from the centre.
73
+ * @param segments - How many pieces the arc is cut into.
74
+ * @returns The points of the arc, and the points of the arrowhead's wings (the head is at the arc's last point).
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { spinArrow } from "@johnmorrisdotca/wakusei-planets/space";
79
+ *
80
+ * const { arc } = spinArrow([0, 0, 0], [0, 1, 0], 1.3, 0.5, 20);
81
+ * console.log(arc.length);
82
+ * ```
83
+ */
84
+ export declare function spinArrow(centre: Vec3, axis: Vec3, radius: number, lift: number, segments?: number): {
85
+ arc: Vec3[];
86
+ head: [Vec3, Vec3];
87
+ };