astraeus-data-constellations 0.9.0 → 0.9.2

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.
package/README.md CHANGED
@@ -27,7 +27,21 @@ scene.addSkyFigures(await constellations(["Ori", "Tau"], { shown: "whenTraced" }
27
27
  scene.addSkyFigures(await constellations("all", { outlines: true, color: "#6aa" })); // all 88 with boundary outlines
28
28
  ```
29
29
 
30
- Options: `outlines` (default false), `shown` (`"always"` or `"whenTraced"`), `color`, `labelColor`, `listed` (menu), `idPrefix`. Ids are the abbreviation (`Ori`), `Ori-boundary` for an outline, and `Ser-boundary-1` (Caput) and `Ser-boundary-2` (Cauda) for Serpens. An unknown or repeated abbreviation throws a `RangeError` naming it. Cards carry provenance and no facts; the app adds those. Star ends need the engine's star list, which the viewer loads itself.
30
+ Options: `outlines` (default false), `shown` (`"always"` or `"whenTraced"`), `color`, `labelColor`, `listed` (menu), `idPrefix`, `outlineLabel` (a function from the label an outline would have, such as `"Aries"` or `"Serpens Cauda"`, to the text it gets, so an app can tell an outline's name from its figure's; a non-function, or a result that is not a non-empty string, throws a `RangeError`). Ids are the abbreviation (`Ori`), `Ori-boundary` for an outline, and `Ser-boundary-1` (Caput) and `Ser-boundary-2` (Cauda) for Serpens. An unknown or repeated abbreviation throws a `RangeError` naming it. Cards carry provenance and no facts; the app adds those. Star ends need the engine's star list, which the viewer loads itself.
31
+
32
+ ### Which constellation holds a direction
33
+
34
+ `constellationFinder()` loads the outlines once and resolves to a synchronous function from a J2000 direction to the IAU abbreviation:
35
+
36
+ ```ts
37
+ import { constellationFinder } from "astraeus-data-constellations";
38
+
39
+ const which = await constellationFinder();
40
+ which({ raDeg: 88.79, decDeg: 7.41 }); // "Ori"
41
+ which({ raDeg: 280, decDeg: -3 }); // "Ser" (both Serpens loops answer "Ser")
42
+ ```
43
+
44
+ Right ascension is taken modulo 360; a `decDeg` outside -90 to 90, or a non-finite number, throws a `RangeError` naming the field. The edges are great-circle arcs between the outline points, and the poles and the 0/360 seam are handled. A direction within 1e-9 radian of an edge shared by constellations answers the first abbreviation in alphabetical order among those; if rounding leaves a direction inside no outline, it answers the constellation of the nearest edge. J2000 only: precess a date's direction first.
31
45
 
32
46
  The figures use Hipparcos numbers; one end, xi Ursae Majoris (HIP 55203, Alula Australis), is a position because the engine's star list holds that star without a Hipparcos number.
33
47
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astraeus-data-constellations",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "The 88 IAU constellations for the Astraeus engine: stick figures, boundary outlines in J2000 and names. Optional data; the engine draws without it.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,15 @@
1
+ import type { ConstellationBoundaries } from "./index.js";
2
+ /** A J2000 direction: right ascension (taken modulo 360) and declination in degrees. */
3
+ export interface SkyDirection {
4
+ readonly raDeg: number;
5
+ readonly decDeg: number;
6
+ }
7
+ /** What `buildMatcher` gives: the finder itself, and (for tests) every loop's abbreviation that encloses a direction by the containment test alone, before the edge rule. */
8
+ export interface Matcher {
9
+ readonly find: (direction: SkyDirection) => string;
10
+ readonly enclosing: (direction: SkyDirection) => readonly string[];
11
+ }
12
+ /** Builds the finder from boundary outlines (`loadBoundaries()`'s result). */
13
+ export declare const buildMatcher: (boundaries: ConstellationBoundaries) => Matcher;
14
+ /** Builds the finder from boundary outlines (`loadBoundaries()`'s result). */
15
+ export declare const buildFinder: (boundaries: ConstellationBoundaries) => ((direction: SkyDirection) => string);
package/src/finder.js ADDED
@@ -0,0 +1,123 @@
1
+ /** Tolerance, in radians (1e-9, about 0.2 milliarcseconds), within which a direction counts as lying on a boundary edge. */
2
+ const EDGE_EPS = 1e-9;
3
+ const RAD = Math.PI / 180;
4
+ const unit = (raDeg, decDeg) => {
5
+ const cosDec = Math.cos(decDeg * RAD);
6
+ return [cosDec * Math.cos(raDeg * RAD), cosDec * Math.sin(raDeg * RAD), Math.sin(decDeg * RAD)];
7
+ };
8
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
9
+ const cross = (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]];
10
+ const normalize = (a) => {
11
+ const length = Math.hypot(a[0], a[1], a[2]);
12
+ return length === 0 ? a : [a[0] / length, a[1] / length, a[2] / length];
13
+ };
14
+ const buildLoop = (abbr, flat) => {
15
+ const points = [];
16
+ const raDegs = [];
17
+ let decSum = 0;
18
+ for (let i = 0; i + 1 < flat.length; i += 2) {
19
+ points.push(unit(flat[i], flat[i + 1]));
20
+ raDegs.push(flat[i]);
21
+ decSum += flat[i + 1];
22
+ }
23
+ // A loop that goes once round the polar axis (its right ascension winds by 360 degrees) encloses a pole: the one on the side of its mean declination.
24
+ let wind = 0;
25
+ for (let i = 0; i < raDegs.length; i++) {
26
+ let step = raDegs[(i + 1) % raDegs.length] - raDegs[i];
27
+ if (step > 180)
28
+ step -= 360;
29
+ if (step < -180)
30
+ step += 360;
31
+ wind += step;
32
+ }
33
+ const circles = Math.abs(wind) > 180;
34
+ const normals = points.map((a, i) => normalize(cross(a, points[(i + 1) % points.length])));
35
+ return { abbr, points, normals, pole: !circles ? "none" : decSum > 0 ? "north" : "south" };
36
+ };
37
+ /** Does the loop enclose the direction? Ray casting along the direction's meridian up to the north pole, edges as great-circle arcs; crossings are counted half-open so a vertex on the ray counts once. */
38
+ const contains = (loop, p, raDeg) => {
39
+ const c = Math.cos(raDeg * RAD);
40
+ const s = Math.sin(raDeg * RAD);
41
+ // The meridian plane's normal and the half plane (the direction's own right ascension) the ray lies in.
42
+ const plane = [s, -c, 0];
43
+ let crossings = 0;
44
+ const n = loop.points.length;
45
+ for (let i = 0; i < n; i++) {
46
+ const a = loop.points[i];
47
+ const b = loop.points[(i + 1) % n];
48
+ const da = dot(a, plane);
49
+ const db = dot(b, plane);
50
+ if (da >= 0 === db >= 0)
51
+ continue;
52
+ // The point of the arc on the plane: the convex mix of the ends that cancels the signed distances.
53
+ const x = [a[0] * Math.abs(db) + b[0] * Math.abs(da), a[1] * Math.abs(db) + b[1] * Math.abs(da), a[2] * Math.abs(db) + b[2] * Math.abs(da)];
54
+ if (x[0] * c + x[1] * s > 0 && x[2] / Math.hypot(x[0], x[1], x[2]) > p[2])
55
+ crossings++;
56
+ }
57
+ return (crossings % 2 === 1) !== (loop.pole === "north");
58
+ };
59
+ /** Angular distance, in radians, from the direction to the loop's nearest edge. */
60
+ const edgeDistance = (loop, p) => {
61
+ let best = Infinity;
62
+ const n = loop.points.length;
63
+ for (let i = 0; i < n; i++) {
64
+ const a = loop.points[i];
65
+ const b = loop.points[(i + 1) % n];
66
+ const normal = loop.normals[i];
67
+ const within = dot(cross(a, p), normal) >= 0 && dot(cross(p, b), normal) >= 0;
68
+ const d = within ? Math.asin(Math.min(1, Math.abs(dot(p, normal)))) : Math.acos(Math.min(1, Math.max(dot(p, a), dot(p, b))));
69
+ if (d < best)
70
+ best = d;
71
+ }
72
+ return best;
73
+ };
74
+ const checked = (direction) => {
75
+ if (typeof direction !== "object" || direction === null)
76
+ throw new RangeError("constellationFinder: the direction must be an object { raDeg, decDeg }");
77
+ if (typeof direction.raDeg !== "number" || !Number.isFinite(direction.raDeg))
78
+ throw new RangeError(`constellationFinder: raDeg must be a finite number, got ${String(direction.raDeg)}`);
79
+ if (typeof direction.decDeg !== "number" || !Number.isFinite(direction.decDeg) || direction.decDeg < -90 || direction.decDeg > 90)
80
+ throw new RangeError(`constellationFinder: decDeg must be a number from -90 to 90, got ${String(direction.decDeg)}`);
81
+ };
82
+ /** Builds the finder from boundary outlines (`loadBoundaries()`'s result). */
83
+ export const buildMatcher = (boundaries) => {
84
+ // Alphabetical, so every tie below resolves to the first abbreviation in this order.
85
+ const loops = Object.keys(boundaries).sort().flatMap((abbr) => (boundaries[abbr] ?? []).map((flat) => buildLoop(abbr, flat)));
86
+ const prepare = (direction) => {
87
+ checked(direction);
88
+ const raDeg = ((direction.raDeg % 360) + 360) % 360;
89
+ return { p: unit(raDeg, direction.decDeg), raDeg };
90
+ };
91
+ const find = (direction) => {
92
+ const { p, raDeg } = prepare(direction);
93
+ // 1. On an edge (within EDGE_EPS): the first abbreviation of the constellations whose edge it lies on.
94
+ // 2. Else inside a loop: that loop's abbreviation (the first, should rounding give more than one).
95
+ // 3. Else (rounding left it in no loop): the constellation of the nearest edge, the first on a tie.
96
+ let inside;
97
+ for (const loop of loops) {
98
+ if (edgeDistance(loop, p) <= EDGE_EPS)
99
+ return loop.abbr;
100
+ if (inside === undefined && contains(loop, p, raDeg))
101
+ inside = loop.abbr;
102
+ }
103
+ if (inside !== undefined)
104
+ return inside;
105
+ let nearest = loops[0].abbr;
106
+ let best = Infinity;
107
+ for (const loop of loops) {
108
+ const d = edgeDistance(loop, p);
109
+ if (d < best) {
110
+ best = d;
111
+ nearest = loop.abbr;
112
+ }
113
+ }
114
+ return nearest;
115
+ };
116
+ const enclosing = (direction) => {
117
+ const { p, raDeg } = prepare(direction);
118
+ return loops.filter((loop) => contains(loop, p, raDeg)).map((loop) => loop.abbr);
119
+ };
120
+ return { find, enclosing };
121
+ };
122
+ /** Builds the finder from boundary outlines (`loadBoundaries()`'s result). */
123
+ export const buildFinder = (boundaries) => buildMatcher(boundaries).find;
package/src/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { type SkyDirection } from "./finder.js";
1
2
  import type { SkyFigureInput } from "astraeus";
3
+ export type { SkyDirection } from "./finder.js";
2
4
  /** One end of a figure line: a Hipparcos number the engine's star list holds, or a J2000 position `[raDeg, decDeg]` (a star the list holds without a Hipparcos number). */
3
5
  export type FigureEnd = number | readonly [raDeg: number, decDeg: number];
4
6
  /** Constellation abbreviation (the IAU's three letters, such as `"Ori"`, `"UMa"`, `"CVn"`) to its figure's lines, each a pair of ends. */
@@ -29,6 +31,15 @@ export declare const loadBoundaries: () => Promise<ConstellationBoundaries>;
29
31
  export declare const loadNames: () => Promise<Readonly<Record<string, ConstellationName>>>;
30
32
  /** Sources, licences, changes and the boundary cross-check. */
31
33
  export declare const loadProvenance: () => Promise<ConstellationProvenance>;
34
+ /**
35
+ * Which of the 88 constellations holds a J2000 direction. Loads the boundary outlines once (later calls reuse them) and resolves to a synchronous function giving the IAU abbreviation (`"Ori"`); both Serpens loops answer `"Ser"`.
36
+ * Right ascension is taken modulo 360; a declination outside -90..90 or a non-finite number throws a `RangeError` naming the field.
37
+ * A direction exactly on a shared edge (within 1e-9 radian) answers the first abbreviation in alphabetical order of the constellations that edge touches.
38
+ * @example
39
+ * const which = await constellationFinder();
40
+ * which({ raDeg: 88.79, decDeg: 7.41 }); // "Ori"
41
+ */
42
+ export declare const constellationFinder: () => Promise<(direction: SkyDirection) => string>;
32
43
  /** What `constellations` can be told. */
33
44
  export interface ConstellationsOptions {
34
45
  /** Also return each constellation's boundary outline (`kind: "boundary"`; Serpens has two). Default false. */
@@ -43,6 +54,8 @@ export interface ConstellationsOptions {
43
54
  readonly listed?: boolean;
44
55
  /** Text put before every id, to avoid a clash with the app's own ids (default none). */
45
56
  readonly idPrefix?: string;
57
+ /** Names each outline's label: called with the label it would have had (`"Aries"`, `"Serpens Cauda"`), returns the text to use (non-empty). Figures keep their names. Default: the label as is. */
58
+ readonly outlineLabel?: (name: string) => string;
46
59
  }
47
60
  /**
48
61
  * Ready sky figures (and, when asked, boundary outlines) for constellations, to give to `scene.addSkyFigures`. Pass IAU abbreviations (`["Ori", "UMa"]`) or `"all"` for the 88.
package/src/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { buildFinder } from "./finder.js";
1
2
  // A dynamic import keeps each file its own chunk, so a bundler loads only what the app asks for (as astraeus-data-pluto does for its index).
2
3
  const read = async (load) => {
3
4
  const loaded = (await load());
@@ -11,6 +12,19 @@ export const loadBoundaries = () => read(() => import("../data/boundaries.json",
11
12
  export const loadNames = () => read(() => import("../data/names.json", { with: { type: "json" } }));
12
13
  /** Sources, licences, changes and the boundary cross-check. */
13
14
  export const loadProvenance = () => read(() => import("../data/provenance.json", { with: { type: "json" } }));
15
+ let finder;
16
+ /**
17
+ * Which of the 88 constellations holds a J2000 direction. Loads the boundary outlines once (later calls reuse them) and resolves to a synchronous function giving the IAU abbreviation (`"Ori"`); both Serpens loops answer `"Ser"`.
18
+ * Right ascension is taken modulo 360; a declination outside -90..90 or a non-finite number throws a `RangeError` naming the field.
19
+ * A direction exactly on a shared edge (within 1e-9 radian) answers the first abbreviation in alphabetical order of the constellations that edge touches.
20
+ * @example
21
+ * const which = await constellationFinder();
22
+ * which({ raDeg: 88.79, decDeg: 7.41 }); // "Ori"
23
+ */
24
+ export const constellationFinder = () => {
25
+ finder ??= loadBoundaries().then(buildFinder, (error) => { finder = undefined; throw error; });
26
+ return finder;
27
+ };
14
28
  const provenance = (what, sources) => ({
15
29
  sourceType: "illustrative",
16
30
  sources,
@@ -48,6 +62,17 @@ export const constellations = async (which, options = {}) => {
48
62
  throw new RangeError(`constellations: not an IAU abbreviation: ${unknown.join(", ")}`);
49
63
  if (repeated.length > 0)
50
64
  throw new RangeError(`constellations: repeated: ${repeated.join(", ")}`);
65
+ const outlineLabel = options.outlineLabel;
66
+ if (outlineLabel !== undefined && typeof outlineLabel !== "function")
67
+ throw new RangeError("constellations: outlineLabel must be a function");
68
+ const labelOutline = (name) => {
69
+ if (outlineLabel === undefined)
70
+ return name;
71
+ const text = outlineLabel(name);
72
+ if (typeof text !== "string" || text === "")
73
+ throw new RangeError(`constellations: outlineLabel must return non-empty text, got ${typeof text === "string" ? "an empty string" : typeof text} for "${name}"`);
74
+ return text;
75
+ };
51
76
  const prefix = options.idPrefix ?? "";
52
77
  const common = {
53
78
  ...(options.shown === undefined ? {} : { shown: options.shown }),
@@ -75,7 +100,7 @@ export const constellations = async (which, options = {}) => {
75
100
  const part = loops.length > 1 ? SERPENS_PARTS[index] : undefined;
76
101
  out.push({
77
102
  id: `${prefix}${abbr}-boundary${loops.length > 1 ? `-${index + 1}` : ""}`,
78
- label: part === undefined ? label : `${label} ${part}`,
103
+ label: labelOutline(part === undefined ? label : `${label} ${part}`),
79
104
  kind: "boundary",
80
105
  points,
81
106
  provenance: provenance("Constellation boundaries", BOUNDARY_SOURCES),