@johnmorrisdotca/wakusei-planets 0.22.0 → 0.24.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,399 @@
1
+ // Which bodies are nearest to a body on a date, and when two bodies come closest over a span: for the Sun, the planets, the dwarf planets and the moons, by the angle between them in the sky of an observer
2
+ // or by the distance between them in space. The positions are this package's own (heliocentric, ephemeris.ts): a sky angle is astrometric (the Earth's or the observer's place at the date, the body's place when
3
+ // its light left, no aberration or light bending), a distance is the geometry at one instant. Each result carries the accuracy the theories are held to (docs/guides/accuracy.md). Pure: no DOM, no three.js.
4
+ import { heliocentric, heliocentricModel, meanSunAu, moonVector } from "./ephemeris.js";
5
+ import { julianCenturies } from "./clock.js";
6
+ import { BODIES, BODY_IDS } from "./facts.js";
7
+ import { ORBITS } from "./data/orbits.js";
8
+ import { moonTheoryOf } from "./data/theories.js";
9
+ import { eclipticJ2000ToTrueEquatorialOfDate } from "./sky/frames.js";
10
+ import { observerVector } from "./sky/engine.js";
11
+ import { cross, DEG, length, scale, sub } from "./vec.js";
12
+ import { moment } from "./when.js";
13
+ const AU_KM = 149_597_870.7;
14
+ const LIGHT_SECONDS_PER_AU = 499.004784;
15
+ const DAY_MS = 86_400_000;
16
+ const ARCSECONDS_PER_RADIAN = 206_264.806;
17
+ const KINDS = ["star", "planet", "dwarf-planet", "moon"];
18
+ /** The worst direction error from the Sun in arc-seconds over 60 dates from 1800 to 2200, as the accuracy guide holds each planet to. */
19
+ const PLANET_ARCSECONDS = { mercury: 4.5, venus: 2.6, earth: 4, mars: 6, jupiter: 3.6, saturn: 5.7, uranus: 5, neptune: 3.4, pluto: 0.2 };
20
+ /** The same for a dwarf planet inside its fitted table's years. */
21
+ const DWARF_ARCSECONDS = { ceres: 0.3, orcus: 0.1, haumea: 0.1, quaoar: 0.15, makemake: 0.15, gonggong: 0.1, eris: 0.1, sedna: 0.1 };
22
+ /** A dwarf planet outside its table's years runs on the osculating elements of one epoch, and Pluto outside 1800 to 2200 on JPL's approximate elements. */
23
+ const OSCULATING_ARCSECONDS = 3600;
24
+ const APPROXIMATE_ARCSECONDS = 120;
25
+ /** The worst direction error from the planet in degrees over 60 dates, for the Moon and each moon; a moon the accuracy guide does not measure is given 5 degrees. */
26
+ const MOON_DEGREES = {
27
+ moon: 0.0016, phobos: 0.55, deimos: 0.55, io: 0.15, europa: 0.05, ganymede: 0.03, callisto: 0.02,
28
+ mimas: 2.1, enceladus: 0.72, tethys: 0.27, dione: 0.23, rhea: 0.27, titan: 0.06, iapetus: 0.04,
29
+ miranda: 3, ariel: 0.3, umbriel: 0.28, titania: 0.52, oberon: 0.6,
30
+ triton: 0.17, nereid: 6.3, proteus: 0.17, charon: 0.06, nix: 2.6, hydra: 2.1,
31
+ };
32
+ /** The same for the moons of Jupiter and Saturn when `tables` has not been imported and their fitted orbits answer. */
33
+ const FITTED_MOON_DEGREES = { io: 0.15, europa: 0.18, ganymede: 0.6, callisto: 0.09, mimas: 7.5, enceladus: 0.72, tethys: 0.45, dione: 0.23, rhea: 0.27, titan: 0.08, iapetus: 0.72 };
34
+ const finite = (name, value) => {
35
+ if (typeof value !== "number" || !Number.isFinite(value))
36
+ throw new RangeError(`${name} must be a finite number, got ${String(value)}`);
37
+ return value;
38
+ };
39
+ function bodyOf(name, value) {
40
+ if (typeof value !== "string" || !BODY_IDS.includes(value))
41
+ throw new RangeError(`${name} must be a body such as "mars" or "io", got ${JSON.stringify(value)}`);
42
+ return value;
43
+ }
44
+ function byOf(by) {
45
+ if (by === undefined)
46
+ return "sky";
47
+ if (by !== "sky" && by !== "space")
48
+ throw new RangeError(`by must be "sky" or "space", got ${JSON.stringify(by)}`);
49
+ return by;
50
+ }
51
+ function viewOf(observer) {
52
+ if (observer === undefined)
53
+ return { body: "earth" };
54
+ if (typeof observer === "string")
55
+ return { body: bodyOf("observer", observer) };
56
+ if (typeof observer !== "object" || observer === null)
57
+ throw new TypeError(`observer must be a body name or { latitude, longitude }, got ${String(observer)}`);
58
+ const latitude = finite("observer.latitude", observer.latitude);
59
+ const longitude = finite("observer.longitude", observer.longitude);
60
+ if (latitude < -90 || latitude > 90)
61
+ throw new RangeError(`observer.latitude must be between -90 and 90, got ${latitude}`);
62
+ return { body: "earth", place: { latitude, longitude, heightM: observer.heightM === undefined ? 0 : finite("observer.heightM", observer.heightM) } };
63
+ }
64
+ /** A body's centre in the Sun's frame (J2000 ecliptic, au) at an instant. */
65
+ function placeAu(id, ms) {
66
+ if (id === "sun")
67
+ return [0, 0, 0];
68
+ const facts = BODIES[id];
69
+ if (facts.kind !== "moon")
70
+ return heliocentric(id, ms);
71
+ const host = heliocentric(facts.parent ?? "earth", ms);
72
+ const offset = moonVector(id, ms);
73
+ return [host[0] + offset[0] / AU_KM, host[1] + offset[1] / AU_KM, host[2] + offset[2] / AU_KM];
74
+ }
75
+ /** The unit direction to a body and its distance in km from a view at an instant, with the light time allowed for. */
76
+ function sight(view, id, ms) {
77
+ const origin = placeAu(view.body, ms);
78
+ let emit = ms;
79
+ let v = sub(placeAu(id, emit), origin);
80
+ for (let i = 0; i < 2; i += 1) {
81
+ emit = ms - length(v) * LIGHT_SECONDS_PER_AU * 1000;
82
+ v = sub(placeAu(id, emit), origin);
83
+ }
84
+ if (view.place !== undefined) {
85
+ const turned = eclipticJ2000ToTrueEquatorialOfDate(scale(v, AU_KM), julianCenturies(ms));
86
+ const topocentric = sub(turned, observerVector(view.place, ms));
87
+ const km = length(topocentric);
88
+ return { v: scale(topocentric, 1 / km), km };
89
+ }
90
+ const km = length(v) * AU_KM;
91
+ return { v: scale(v, 1 / length(v)), km };
92
+ }
93
+ function sample(by, view, ids, ms) {
94
+ const at = new Map();
95
+ for (const id of ids)
96
+ at.set(id, by === "sky" ? sight(view, id, ms) : { v: placeAu(id, ms), km: 0 });
97
+ return at;
98
+ }
99
+ /** Degrees between two unit directions, or kilometres between two positions in au; atan2 keeps it exact near 0 and 180 degrees. */
100
+ function separation(by, a, b) {
101
+ if (by === "space")
102
+ return length(sub(a.v, b.v)) * AU_KM;
103
+ return Math.atan2(length(cross(a.v, b.v)), a.v[0] * b.v[0] + a.v[1] * b.v[1] + a.v[2] * b.v[2]) * DEG;
104
+ }
105
+ function hostErrorKm(host, ms) {
106
+ const model = heliocentricModel(host, ms);
107
+ const arcseconds = model.theory === "vsop87b" ? PLANET_ARCSECONDS[host] : model.theory === "chebyshev" ? (PLANET_ARCSECONDS[host] ?? DWARF_ARCSECONDS[host]) : model.theory === "osculating-elements" ? OSCULATING_ARCSECONDS : APPROXIMATE_ARCSECONDS;
108
+ return length(heliocentric(host, ms)) * AU_KM * Math.tan(arcseconds / ARCSECONDS_PER_RADIAN);
109
+ }
110
+ /** The independent parts of how far a body's place may be off, kilometres: the planet it goes round (which its moons share) and its own part. */
111
+ function partsOf(id, ms) {
112
+ const parts = new Map();
113
+ if (id === "sun")
114
+ return parts;
115
+ const facts = BODIES[id];
116
+ if (facts.kind !== "moon")
117
+ return parts.set(id, hostErrorKm(id, ms));
118
+ const host = facts.parent ?? "earth";
119
+ const fitted = host === "jupiter" || host === "saturn" ? moonTheoryOf(id) === undefined : false;
120
+ const degrees = (fitted ? FITTED_MOON_DEGREES[id] : undefined) ?? MOON_DEGREES[id] ?? 5;
121
+ parts.set(host, hostErrorKm(host, ms));
122
+ return parts.set(`${id} orbit`, length(moonVector(id, ms)) * Math.tan((degrees * Math.PI) / 180));
123
+ }
124
+ /**
125
+ * How far the separation of a and b may be off: each part of the places' errors moves a and b by its size over their distance, in the same direction for a part they share (the planet two moons go round,
126
+ * the Earth's own error seen from the Earth), so a shared part cancels in the difference. The parts add in quadrature; a part is taken as acting across the line of sight, the worst case.
127
+ */
128
+ function separationError(a, b, from, distanceA, distanceB, ms) {
129
+ const parts = [partsOf(a, ms), partsOf(b, ms), from === undefined ? new Map() : partsOf(from, ms)];
130
+ let sum = 0;
131
+ for (const key of new Set(parts.flatMap((part) => [...part.keys()]))) {
132
+ const size = parts.find((part) => part.has(key)).get(key);
133
+ const onA = (parts[0].has(key) ? 1 : 0) - (parts[2].has(key) ? 1 : 0);
134
+ const onB = (parts[1].has(key) ? 1 : 0) - (parts[2].has(key) ? 1 : 0);
135
+ sum += (size * onA / distanceA - size * onB / distanceB) ** 2;
136
+ }
137
+ return Math.sqrt(sum);
138
+ }
139
+ function skyUncertainty(view, a, b, at, ms) {
140
+ return separationError(a, b, view.body, at.get(a).km, at.get(b).km, ms) * ARCSECONDS_PER_RADIAN;
141
+ }
142
+ function spaceUncertainty(a, b, ms) {
143
+ return separationError(a, b, undefined, 1, 1, ms);
144
+ }
145
+ function kindsOf(kind) {
146
+ if (kind === undefined)
147
+ return undefined;
148
+ const list = typeof kind === "string" ? [kind] : kind;
149
+ for (const one of list)
150
+ if (!KINDS.includes(one))
151
+ throw new RangeError(`kind must be one of ${KINDS.join(", ")}, got ${JSON.stringify(one)}`);
152
+ return list;
153
+ }
154
+ function lookup(target, options, defaultCount) {
155
+ bodyOf("target", target);
156
+ const by = byOf(options.by);
157
+ const view = viewOf(options.observer);
158
+ const ms = options.date === undefined ? Date.now() : moment(options.date, "date");
159
+ const kinds = kindsOf(options.kind);
160
+ const radius = options.within === undefined ? Infinity : finite("within", options.within);
161
+ if (radius < 0)
162
+ throw new RangeError(`within must not be negative, got ${radius}`);
163
+ const count = options.count === undefined ? (options.within === undefined ? defaultCount ?? 5 : Infinity) : finite("count", options.count);
164
+ if (count < 0 || !Number.isInteger(count) && count !== Infinity)
165
+ throw new RangeError(`count must be a whole number of 0 or more, got ${count}`);
166
+ if (by === "sky" && target === view.body)
167
+ throw new RangeError(`target ${target} is where the sky is seen from (the observer), so it is not in that sky`);
168
+ const pool = (options.bodies ?? BODY_IDS).map((id) => bodyOf("bodies", id));
169
+ const ids = pool.filter((id) => id !== target && (by === "space" || id !== view.body) && (kinds === undefined || kinds.includes(BODIES[id].kind)));
170
+ const at = sample(by, view, [target, ...ids], ms);
171
+ const here = at.get(target);
172
+ const rows = ids.map((id) => ({ id, value: separation(by, here, at.get(id)) })).filter((row) => row.value <= radius).sort((a, b) => a.value - b.value).slice(0, count);
173
+ if (by === "sky")
174
+ return rows.map((row) => ({ id: row.id, kind: BODIES[row.id].kind, angle: row.value, uncertaintyArcseconds: skyUncertainty(view, target, row.id, at, ms) }));
175
+ return rows.map((row) => ({ id: row.id, kind: BODIES[row.id].kind, distanceKm: row.value, distanceAu: row.value / AU_KM, uncertaintyKm: spaceUncertainty(target, row.id, ms) }));
176
+ }
177
+ export function nearest(target, options = {}) {
178
+ return lookup(target, options, undefined);
179
+ }
180
+ export function within(target, radius, options = {}) {
181
+ return lookup(target, { ...options, within: radius, count: undefined }, undefined);
182
+ }
183
+ /** Days a body takes to go once round what it goes round (the Earth's own orbit for the Earth). */
184
+ function periodDays(id) {
185
+ if (id === "sun")
186
+ return Infinity;
187
+ const facts = BODIES[id];
188
+ if (facts.kind === "moon")
189
+ return 360 / Math.abs(ORBITS[id]?.sid ?? 1);
190
+ return 365.25 * Math.pow(meanSunAu(id), 1.5);
191
+ }
192
+ /** How far apart to look: the fastest body of the pairs goes round forty times in this many steps, never more than two days. */
193
+ function stepMs(ids, view) {
194
+ const fastest = Math.min(...ids.map(periodDays), periodDays(view.body));
195
+ return Math.max(60_000, Math.min(2 * DAY_MS, (fastest * DAY_MS) / 40));
196
+ }
197
+ const GOLDEN = (Math.sqrt(5) - 1) / 2;
198
+ /** The moment of the smallest value of a function with one minimum in [low, high], to within `tolerance` ms. */
199
+ function golden(f, low, high, tolerance) {
200
+ let a = low;
201
+ let b = high;
202
+ let c = b - GOLDEN * (b - a);
203
+ let d = a + GOLDEN * (b - a);
204
+ let fc = f(c);
205
+ let fd = f(d);
206
+ while (b - a > tolerance) {
207
+ if (fc < fd) {
208
+ b = d;
209
+ d = c;
210
+ fd = fc;
211
+ c = b - GOLDEN * (b - a);
212
+ fc = f(c);
213
+ }
214
+ else {
215
+ a = c;
216
+ c = d;
217
+ fc = fd;
218
+ d = a + GOLDEN * (b - a);
219
+ fd = f(d);
220
+ }
221
+ }
222
+ return (a + b) / 2;
223
+ }
224
+ function valueAt(by, view, a, b, ms) {
225
+ const at = sample(by, view, [a, b], ms);
226
+ return separation(by, at.get(a), at.get(b));
227
+ }
228
+ /** Every minimum of the separation of each pair inside [from, to] (every maximum, for a sign of -1): a coarse scan, then each bracket narrowed to about a second. */
229
+ function minima(pairs, by, view, from, to, sign = 1) {
230
+ const ids = [...new Set(pairs.flat())];
231
+ const step = stepMs(ids, view);
232
+ const count = Math.ceil((to - from) / step) + 3;
233
+ const times = Array.from({ length: count }, (_, i) => from - step + i * step);
234
+ const values = pairs.map(() => new Float64Array(count));
235
+ times.forEach((ms, i) => {
236
+ const at = sample(by, view, ids, ms);
237
+ pairs.forEach(([a, b], p) => {
238
+ values[p][i] = sign * separation(by, at.get(a), at.get(b));
239
+ });
240
+ });
241
+ const found = [];
242
+ pairs.forEach(([a, b], p) => {
243
+ const v = values[p];
244
+ for (let i = 1; i < count - 1; i += 1) {
245
+ if (!(v[i] <= v[i - 1] && v[i] < v[i + 1]))
246
+ continue;
247
+ const ms = golden((t) => sign * valueAt(by, view, a, b, t), times[i - 1], times[i + 1], 500);
248
+ if (ms >= from && ms <= to)
249
+ found.push({ a, b, ms, value: valueAt(by, view, a, b, ms) });
250
+ }
251
+ });
252
+ return found;
253
+ }
254
+ /** The expected accuracy of a separation and of the moment of its minimum. */
255
+ function describe(by, view, a, b, ms, value, atEdge) {
256
+ const at = sample(by, view, [a, b], ms);
257
+ const half = 30_000;
258
+ const before = sample(by, view, [a, b], ms - half);
259
+ const after = sample(by, view, [a, b], ms + half);
260
+ const chord = (s) => sub(s.get(b).v, s.get(a).v);
261
+ const moved = length(sub(chord(after), chord(before))) / (2 * half / 1000);
262
+ const base = { a, b, time: new Date(ms), atEdge };
263
+ if (by === "sky") {
264
+ const uncertaintyArcseconds = skyUncertainty(view, a, b, at, ms);
265
+ return { ...base, angle: value, uncertaintyArcseconds, uncertaintySeconds: moved > 0 ? uncertaintyArcseconds / ARCSECONDS_PER_RADIAN / moved : Infinity };
266
+ }
267
+ const uncertaintyKm = spaceUncertainty(a, b, ms);
268
+ return { ...base, distanceKm: value, distanceAu: value / AU_KM, uncertaintyKm, uncertaintySeconds: moved > 0 ? uncertaintyKm / (moved * AU_KM) : Infinity };
269
+ }
270
+ function span(options) {
271
+ const from = moment(options.from, "from");
272
+ const to = moment(options.to, "to");
273
+ if (to < from)
274
+ throw new RangeError("to must not be before from");
275
+ return { from, to, by: byOf(options.by), view: viewOf(options.observer) };
276
+ }
277
+ /**
278
+ * When two bodies come closest in a span, and how close: the span is scanned in coarse steps (the fastest body goes round forty times in the step, at most two days), then the smallest minimum is narrowed to about a second of time by golden-section search. If the separation only falls or only rises through the span, the end that is smaller is returned and `atEdge` says so. With `by: "sky"` the separation is the angle in the sky of the observer and a minimum may be an occultation, the angle falling through 0; with `by: "space"` it is the distance between the centres.
279
+ *
280
+ * The result carries `uncertaintyArcseconds` (or `uncertaintyKm`) for the separation, from the accuracy guide's limits, and `uncertaintySeconds` for the moment: that error over how fast the pair moves past each other.
281
+ *
282
+ * @param a - One body.
283
+ * @param b - The other.
284
+ * @param options - `from` and `to` (the span), `by` and `observer` as in `nearest`.
285
+ * @returns The moment, the separation, and the accuracy to expect.
286
+ * @throws RangeError for bodies, a span or an observer that is not valid, or two bodies that are the same, or one of them the observer.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * import { closestApproach } from "@johnmorrisdotca/wakusei-planets/nearest";
291
+ *
292
+ * const great = closestApproach("jupiter", "saturn", { from: Date.UTC(2020, 11, 1), to: Date.UTC(2021, 0, 1) });
293
+ * console.log(great.time.toISOString(), great.angle?.toFixed(3), "degrees");
294
+ * ```
295
+ */
296
+ export function closestApproach(a, b, options) {
297
+ bodyOf("a", a);
298
+ bodyOf("b", b);
299
+ if (a === b)
300
+ throw new RangeError(`a and b must be different bodies, got ${a} twice`);
301
+ const { from, to, by, view } = span(options);
302
+ if (by === "sky" && (a === view.body || b === view.body))
303
+ throw new RangeError(`${a === view.body ? a : b} is where the sky is seen from (the observer), so it is not in that sky`);
304
+ const inside = minima([[a, b]], by, view, from, to);
305
+ const best = inside.sort((x, y) => x.value - y.value)[0];
306
+ const start = valueAt(by, view, a, b, from);
307
+ const end = valueAt(by, view, a, b, to);
308
+ const edge = start <= end ? { ms: from, value: start } : { ms: to, value: end };
309
+ if (best !== undefined && best.value <= edge.value)
310
+ return describe(by, view, a, b, best.ms, best.value, false);
311
+ return describe(by, view, a, b, edge.ms, edge.value, true);
312
+ }
313
+ const DEFAULT_BODIES = ["sun", "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"];
314
+ /**
315
+ * The close approaches of every pair of bodies in a span, soonest first: each pair's separation is scanned in coarse steps (the fastest body goes round forty times in the step, at most two days), and every minimum inside the span that is within `within` is narrowed to about a second of time. Each is the same as `closestApproach` would return for that pair and that minimum.
316
+ *
317
+ * @param options - `from` and `to`, `within` (degrees for the sky, default 5; kilometres for space, default all), `bodies` (default the Sun and Mercury to Neptune, less the body the sky is seen from), `by` and `observer`.
318
+ * @returns The approaches, soonest first, each with its moment, separation and the accuracy to expect.
319
+ * @throws RangeError for a span, body or observer that is not valid.
320
+ *
321
+ * @example
322
+ * ```ts
323
+ * import { conjunctions } from "@johnmorrisdotca/wakusei-planets/nearest";
324
+ *
325
+ * const found = conjunctions({ from: Date.UTC(2023, 0, 1), to: Date.UTC(2024, 0, 1), bodies: ["venus", "jupiter"], within: 2 });
326
+ * console.log(found.map((one) => `${one.a}-${one.b} ${one.time.toISOString().slice(0, 10)} ${one.angle?.toFixed(2)}`).join("\n"));
327
+ * ```
328
+ */
329
+ export function conjunctions(options) {
330
+ const { from, to, by, view } = span(options);
331
+ const radius = options.within === undefined ? (by === "sky" ? 5 : Infinity) : finite("within", options.within);
332
+ const ids = [...new Set((options.bodies ?? DEFAULT_BODIES).map((id) => bodyOf("bodies", id)))].filter((id) => by === "space" || id !== view.body);
333
+ const pairs = [];
334
+ ids.forEach((a, i) => ids.slice(i + 1).forEach((b) => pairs.push([a, b])));
335
+ if (pairs.length === 0)
336
+ return [];
337
+ return minima(pairs, by, view, from, to)
338
+ .filter((found) => found.value <= radius)
339
+ .sort((x, y) => x.ms - y.ms)
340
+ .map((found) => describe(by, view, found.a, found.b, found.ms, found.value, false));
341
+ }
342
+ /**
343
+ * The distance between two bodies on a date: the straight line between their centres at that instant, in kilometres and astronomical units, with no light time. Any two of the Sun, the planets, the dwarf planets and the moons.
344
+ *
345
+ * @param a - One body.
346
+ * @param b - The other.
347
+ * @param date - The moment, a `Date` or milliseconds since 1970 (UTC). Default: now.
348
+ * @returns The distance and the accuracy to expect of it.
349
+ * @throws RangeError for a body or a date that is not valid, or two bodies that are the same.
350
+ *
351
+ * @example
352
+ * ```ts
353
+ * import { distance } from "@johnmorrisdotca/wakusei-planets/nearest";
354
+ *
355
+ * const mars = distance("earth", "mars", Date.UTC(2003, 7, 27, 9));
356
+ * console.log(mars.distanceAu.toFixed(4), Math.round(mars.distanceKm), "km");
357
+ * ```
358
+ */
359
+ export function distance(a, b, date) {
360
+ bodyOf("a", a);
361
+ bodyOf("b", b);
362
+ if (a === b)
363
+ throw new RangeError(`a and b must be different bodies, got ${a} twice`);
364
+ const ms = date === undefined ? Date.now() : moment(date, "date");
365
+ const km = valueAt("space", viewOf(undefined), a, b, ms);
366
+ return { a, b, time: ms, distanceKm: km, distanceAu: km / AU_KM, uncertaintyKm: spaceUncertainty(a, b, ms) };
367
+ }
368
+ /**
369
+ * The least and the greatest distance between two bodies over a span, each with its moment: the span is scanned in coarse steps (as `closestApproach` does) and each turning point is narrowed to about a second of time by golden-section search, the greatest on the negated distance. If the distance only falls or only rises through the span, the end that is the extreme is returned and `atEdge` says so.
370
+ *
371
+ * @param a - One body.
372
+ * @param b - The other.
373
+ * @param options - `from` and `to`, the span.
374
+ * @returns `min` and `max`, each `{ time, distanceKm, distanceAu, uncertaintyKm, atEdge }`.
375
+ * @throws RangeError for a body or a span that is not valid, or two bodies that are the same.
376
+ *
377
+ * @example
378
+ * ```ts
379
+ * import { distanceRange } from "@johnmorrisdotca/wakusei-planets/nearest";
380
+ *
381
+ * const { min, max } = distanceRange("earth", "mars", { from: Date.UTC(1990, 0, 1), to: Date.UTC(2020, 0, 1) });
382
+ * console.log(min.time.toISOString().slice(0, 10), min.distanceAu.toFixed(3), "to", max.distanceAu.toFixed(3), "au");
383
+ * ```
384
+ */
385
+ export function distanceRange(a, b, options) {
386
+ bodyOf("a", a);
387
+ bodyOf("b", b);
388
+ if (a === b)
389
+ throw new RangeError(`a and b must be different bodies, got ${a} twice`);
390
+ const { from, to, view } = span({ ...options, by: "space" });
391
+ const start = valueAt("space", view, a, b, from);
392
+ const end = valueAt("space", view, a, b, to);
393
+ const pick = (sign) => {
394
+ const candidates = [...minima([[a, b]], "space", view, from, to, sign).map((found) => ({ ms: found.ms, value: found.value, atEdge: false })), { ms: from, value: start, atEdge: true }, { ms: to, value: end, atEdge: true }];
395
+ const best = candidates.sort((x, y) => sign * (x.value - y.value) || Number(x.atEdge) - Number(y.atEdge))[0];
396
+ return { time: new Date(best.ms), distanceKm: best.value, distanceAu: best.value / AU_KM, uncertaintyKm: spaceUncertainty(a, b, best.ms), atEdge: best.atEdge };
397
+ };
398
+ return { a, b, min: pick(1), max: pick(-1) };
399
+ }
@@ -22,6 +22,9 @@ export type PortraitState = "line" | "loading" | "still" | "live" | "lost" | "un
22
22
  * Attributes: `scene` (the scene as the portrait builder writes it in its address), `look` (`line`, `realistic` or `painted`: replaces the scene's), `size` (pixels across), `lang` (`en` or `ja`: the names),
23
23
  * `live` (`always`, `hover` or `off`: when it takes the page's one WebGL context), `texture-base` and `texture-far-base` (where the surface pictures are).
24
24
  *
25
+ * It carries the shared view controls itself: a drag moves the picture, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page at Fit), and the arrow keys, + and - and 0 work once it is focused.
26
+ * `controls="none"` turns them off (the portrait builder does, for it edits the scene by dragging its bodies); `zoom-min` and `zoom-max` set the range (0.1 to 8 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
27
+ *
25
28
  * @example
26
29
  * ```ts no-run
27
30
  * import { WakuseiPortrait } from "@johnmorrisdotca/wakusei-planets/portrait";
@@ -67,6 +70,12 @@ export declare class WakuseiPortrait extends HTMLElement {
67
70
  connectedCallback(): void;
68
71
  disconnectedCallback(): void;
69
72
  attributeChangedCallback(name: string): void;
73
+ /** The shared controllers' camera over the scene's own (and a `wakusei-view` event with the `zoom`, `panX` and `panY`): `zoom` scales the picture about its middle, `panX` and `panY` move it by that many CSS pixels. The scene's camera, and what `portrait` holds, are left as they are. */
74
+ setView(view: {
75
+ zoom?: number;
76
+ panX?: number;
77
+ panY?: number;
78
+ }): void;
70
79
  /** Take the page's one WebGL context and draw the scene on it. Resolves true when it is live; a line scene has nothing to take and resolves false. */
71
80
  goLive(): Promise<boolean>;
72
81
  /** Give the WebGL context back: the picture stays as a still. */
@@ -1,3 +1,4 @@
1
+ import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
1
2
  import { BODIES } from "../facts.js";
2
3
  import { createGate, frameCap } from "../gate.js";
3
4
  import { setThreeLoader, takeRenderer } from "../scene/shared.js";
@@ -10,6 +11,11 @@ import { REDUCED_TURN } from "../live.js";
10
11
  import { poseOf } from "./pose.js";
11
12
  import { createPortraitItem } from "./scene3d.js";
12
13
  export { setThreeLoader };
14
+ /**
15
+ * The zoom range of a portrait that carries its own controls. The floor is arbitrary: a tenth of Fit leaves room to see the whole scene small. The ceiling is the painted maps: the sharpest is 2048 pixels round
16
+ * a body, which stays sharp to a few times the size at Fit and softens after that; 8 times is as far as the bodies' own shader detail goes. A scene of a line look has detail at any scale.
17
+ */
18
+ const CARRIED_LIMITS = { zoomMin: 0.1, zoomMax: 8 };
13
19
  const TEMPLATE = `<style>
14
20
  :host { display: block; width: var(--wakusei-size, 720px); max-width: 100%; aspect-ratio: var(--wakusei-ratio, 16 / 9); position: relative; overflow: hidden; contain: layout style; touch-action: none; user-select: none; }
15
21
  #bg, #stage, #over { position: absolute; inset: 0; width: 100%; height: 100%; }
@@ -26,6 +32,9 @@ const num = (value, fallback) => {
26
32
  * Attributes: `scene` (the scene as the portrait builder writes it in its address), `look` (`line`, `realistic` or `painted`: replaces the scene's), `size` (pixels across), `lang` (`en` or `ja`: the names),
27
33
  * `live` (`always`, `hover` or `off`: when it takes the page's one WebGL context), `texture-base` and `texture-far-base` (where the surface pictures are).
28
34
  *
35
+ * It carries the shared view controls itself: a drag moves the picture, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page at Fit), and the arrow keys, + and - and 0 work once it is focused.
36
+ * `controls="none"` turns them off (the portrait builder does, for it edits the scene by dragging its bodies); `zoom-min` and `zoom-max` set the range (0.1 to 8 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
37
+ *
29
38
  * @example
30
39
  * ```ts no-run
31
40
  * import { WakuseiPortrait } from "@johnmorrisdotca/wakusei-planets/portrait";
@@ -61,6 +70,10 @@ export class WakuseiPortrait extends HTMLElement {
61
70
  #edit = {};
62
71
  #overKey = "";
63
72
  #lineKey = "";
73
+ #zoom = 1;
74
+ #panX = 0;
75
+ #panY = 0;
76
+ #hands;
64
77
  #hover = () => void this.goLive();
65
78
  #onContext = (state) => {
66
79
  if (state === "unavailable")
@@ -147,6 +160,7 @@ export class WakuseiPortrait extends HTMLElement {
147
160
  document.addEventListener("visibilitychange", this.#onHidden);
148
161
  this.#applyHover();
149
162
  this.#readAttributes();
163
+ this.#hands = carryControls(this, { turnable: false, limits: CARRIED_LIMITS, onChange: (view) => this.setView(view) });
150
164
  this.#queue();
151
165
  }
152
166
  disconnectedCallback() {
@@ -154,6 +168,8 @@ export class WakuseiPortrait extends HTMLElement {
154
168
  this.#io?.disconnect();
155
169
  document.removeEventListener("visibilitychange", this.#onHidden);
156
170
  this.#applyHover(false);
171
+ this.#hands?.unbind();
172
+ this.#hands = undefined;
157
173
  this.#disposeView(true);
158
174
  }
159
175
  attributeChangedCallback(name) {
@@ -165,6 +181,24 @@ export class WakuseiPortrait extends HTMLElement {
165
181
  this.#readAttributes();
166
182
  this.#queue();
167
183
  }
184
+ /** The shared controllers' camera over the scene's own (and a `wakusei-view` event with the `zoom`, `panX` and `panY`): `zoom` scales the picture about its middle, `panX` and `panY` move it by that many CSS pixels. The scene's camera, and what `portrait` holds, are left as they are. */
185
+ setView(view) {
186
+ const [zoom, panX, panY] = [Math.max(1e-6, view.zoom ?? 1), view.panX ?? 0, view.panY ?? 0];
187
+ if (zoom === this.#zoom && panX === this.#panX && panY === this.#panY)
188
+ return;
189
+ [this.#zoom, this.#panX, this.#panY] = [zoom, panX, panY];
190
+ this.dispatchEvent(new CustomEvent("wakusei-view", { detail: { zoom: this.#zoom, panX: this.#panX, panY: this.#panY } }));
191
+ this.#changed();
192
+ }
193
+ /** The scene's resolved camera with the view's zoom and pan put over it. */
194
+ #resolveNow() {
195
+ const resolved = resolve(this.#portrait);
196
+ if (this.#zoom === 1 && this.#panX === 0 && this.#panY === 0)
197
+ return resolved;
198
+ const h = resolved.camera.h / this.#zoom;
199
+ const scale = this.#size().height / (2 * h);
200
+ return { ...resolved, camera: { x: resolved.camera.x - this.#panX / scale, y: resolved.camera.y + this.#panY / scale, h } };
201
+ }
168
202
  /** Take the page's one WebGL context and draw the scene on it. Resolves true when it is live; a line scene has nothing to take and resolves false. */
169
203
  async goLive() {
170
204
  if (this.#portrait.look === "line")
@@ -260,7 +294,7 @@ export class WakuseiPortrait extends HTMLElement {
260
294
  if (!this.isConnected)
261
295
  return;
262
296
  if (this.#view?.live === true && !this.#queued) {
263
- this.#resolved = resolve(this.#portrait);
297
+ this.#resolved = this.#resolveNow();
264
298
  this.#style();
265
299
  this.#gate?.request();
266
300
  }
@@ -303,7 +337,7 @@ export class WakuseiPortrait extends HTMLElement {
303
337
  if (!this.isConnected)
304
338
  return;
305
339
  const p = this.#portrait;
306
- this.#resolved = resolve(p);
340
+ this.#resolved = this.#resolveNow();
307
341
  this.#style();
308
342
  this.setAttribute("aria-label", this.#label());
309
343
  const wants3d = p.look !== "line" && this.#state !== "unavailable" && p.items.length > 0;
@@ -360,7 +394,7 @@ export class WakuseiPortrait extends HTMLElement {
360
394
  #drawLine() {
361
395
  const { width, height } = this.#size();
362
396
  const markup = this.#lineBody(width, height);
363
- const key = `${width}x${height}|${markup.length}|${this.#portrait.light.az}`;
397
+ const key = `${width}x${height}|${markup.length}|${this.#portrait.light.az}|${this.#zoom.toFixed(3)},${this.#panX.toFixed(1)},${this.#panY.toFixed(1)}`;
364
398
  if (this.#portrait.look !== "line") {
365
399
  if (this.#stage.firstChild !== null && this.#lineKey !== "")
366
400
  this.#stage.innerHTML = "";
@@ -374,7 +408,7 @@ export class WakuseiPortrait extends HTMLElement {
374
408
  }
375
409
  #key() {
376
410
  const { width } = this.#size();
377
- return `${encodeScene(this.#portrait)}|${width}`;
411
+ return `${encodeScene(this.#portrait)}|${width}|${this.#zoom.toFixed(3)},${this.#panX.toFixed(1)},${this.#panY.toFixed(1)}`;
378
412
  }
379
413
  // Replacing a view keeps the renderer lease; leaving 3D gives it back.
380
414
  #disposeView(releaseRenderer = false) {
@@ -436,7 +470,7 @@ export class WakuseiPortrait extends HTMLElement {
436
470
  }
437
471
  // --- moving -------------------------------------------------------------------------------------------------------------------------------------------
438
472
  #frame() {
439
- this.#resolved = resolve(this.#portrait);
473
+ this.#resolved = this.#resolveNow();
440
474
  this.#paintOver();
441
475
  if (this.#portrait.look === "line") {
442
476
  this.#drawLine();
@@ -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.22.0/dist/textures/";
12
+ export declare const TEXTURE_BASE = "https://cdn.jsdelivr.net/npm/@johnmorrisdotca/wakusei-planets@0.24.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.22.0/textures/";
24
+ export declare const TEXTURE_FAR_BASE = "https://cdn.jsdelivr.net/gh/johnmorrisdotca/wakusei-planets@v0.24.0/textures/";
25
25
  export declare const slash: (base: string) => string;
26
26
  export declare function texturePaths(element: Element): {
27
27
  textureBase(): string;
@@ -1,4 +1,5 @@
1
1
  import { greenwichApparentSiderealTime as greenwichSiderealTime } from "../sidereal.ts";
2
+ import type { Vec3 as Vec } from "../vec.ts";
2
3
  import type { EquatorialAngles, HorizontalAngles, Observer } from "./types.ts";
3
4
  export type { Observer } from "./types.ts";
4
5
  /** A body's place on the sky of date, as the Earth's centre sees it (apparent: light time, aberration for the Sun, nutation): angles in degrees, distance in kilometres. */
@@ -18,6 +19,8 @@ export declare function sunEquatorial(ms: number): Equatorial;
18
19
  export declare function moonEquatorial(ms: number): Equatorial;
19
20
  /** The apparent sidereal time at Greenwich in degrees, from the UTC instant taken as UT1. */
20
21
  export { greenwichSiderealTime };
22
+ /** The observer's place from the Earth's centre in the true equator of date, in kilometres, with the turn of the Earth (Meeus ch. 11). */
23
+ export declare function observerVector(observer: Observer, ms: number): Vec;
21
24
  /**
22
25
  * Altitude, azimuth, hour angle and parallactic angle of a body for an observer: topocentric (parallax taken out of the Earth's centre to the place) and geometric, with no refraction.
23
26
  * `ms` is the instant the observer's sky turns for; the body's place `equatorial` is its apparent place at that instant.
@@ -45,7 +45,7 @@ export function moonEquatorial(ms) {
45
45
  /** The apparent sidereal time at Greenwich in degrees, from the UTC instant taken as UT1. */
46
46
  export { greenwichSiderealTime };
47
47
  /** The observer's place from the Earth's centre in the true equator of date, in kilometres, with the turn of the Earth (Meeus ch. 11). */
48
- function observerVector(observer, ms) {
48
+ export function observerVector(observer, ms) {
49
49
  const lat = observer.latitude * RAD;
50
50
  const height = (observer.heightM ?? 0) / 1000;
51
51
  const u = Math.atan((1 - EARTH_FLATTENING) * Math.tan(lat));
@@ -1,3 +1,4 @@
1
+ import { type ViewController } from "@johnmorrisdotca/kazoku-ui/view-controls";
1
2
  import { setThreeLoader } from "../scene/shared.ts";
2
3
  import { type SpacePlanet } from "./frame.ts";
3
4
  import { type ScaleMode } from "./scale.ts";
@@ -86,6 +87,9 @@ export type Riding = RideState;
86
87
  * `light` (`sun` or `lit`), `lang` (`en` or `ja`: the names), `labels` and `orbits` (`off` hides them), and `texture-base`, `texture-far-base` and `max-texture`. Positions come from this package's own models. It draws
87
88
  * only when something changes, and nothing while it is out of sight.
88
89
  *
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
+ * 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
+ *
89
93
  * @example
90
94
  * ```ts no-run
91
95
  * import type { WakuseiSpace } from "@johnmorrisdotca/wakusei-planets/space/element";
@@ -99,6 +103,8 @@ export type Riding = RideState;
99
103
  export declare class WakuseiSpace extends HTMLElement {
100
104
  #private;
101
105
  static observedAttributes: string[];
106
+ /** The shared controller behind the element's own hands: for a page that moves the view itself, such as `controller.set({ zoom: space.zoomFor("moon") })`. It is there while the element is connected, whether `controls` is `none` or not. */
107
+ get controller(): ViewController | undefined;
102
108
  connectedCallback(): void;
103
109
  disconnectedCallback(): void;
104
110
  attributeChangedCallback(name: string, _old: string | null, value: string | null): void;