@johnmorrisdotca/wakusei-planets 0.23.0 → 0.25.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 (45) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +41 -14
  3. package/dist/blackbody.d.ts +2 -0
  4. package/dist/blackbody.js +10 -0
  5. package/dist/element.d.ts +12 -0
  6. package/dist/element.js +160 -23
  7. package/dist/embed.d.ts +5 -0
  8. package/dist/embed.js +32 -8
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/kids/data.d.ts +109 -0
  12. package/dist/kids/data.js +164 -0
  13. package/dist/kids/index.d.ts +4 -0
  14. package/dist/kids/index.js +5 -0
  15. package/dist/kids/land.d.ts +3 -0
  16. package/dist/kids/land.js +29 -0
  17. package/dist/kids/picture.d.ts +39 -0
  18. package/dist/kids/picture.js +255 -0
  19. package/dist/kids/sheet.d.ts +60 -0
  20. package/dist/kids/sheet.js +79 -0
  21. package/dist/kids/svg.d.ts +46 -0
  22. package/dist/kids/svg.js +193 -0
  23. package/dist/line.d.ts +9 -1
  24. package/dist/line.js +3 -4
  25. package/dist/portrait/element.d.ts +9 -0
  26. package/dist/portrait/element.js +39 -5
  27. package/dist/scene/body.d.ts +8 -1
  28. package/dist/scene/body.js +33 -9
  29. package/dist/scene/glsl.d.ts +7 -2
  30. package/dist/scene/glsl.js +49 -3
  31. package/dist/scene/look.d.ts +43 -0
  32. package/dist/scene/look.js +39 -1
  33. package/dist/scene/store.d.ts +3 -0
  34. package/dist/scene/store.js +3 -1
  35. package/dist/scene/textures.d.ts +2 -2
  36. package/dist/space/element.d.ts +6 -0
  37. package/dist/space/element.js +18 -0
  38. package/dist/star-line.d.ts +20 -0
  39. package/dist/star-line.js +59 -0
  40. package/dist/star.d.ts +193 -0
  41. package/dist/star.js +261 -0
  42. package/dist/stars.js +3 -5
  43. package/dist/version.d.ts +1 -1
  44. package/dist/version.js +1 -1
  45. package/package.json +9 -2
@@ -1,3 +1,4 @@
1
+ import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
1
2
  import { BODIES, MOONS_OF } from "../facts.js";
2
3
  import { createGate, frameCap } from "../gate.js";
3
4
  import { createPainter } from "../scene/painter.js";
@@ -28,6 +29,11 @@ const readBody = (value) => {
28
29
  const id = value.toLowerCase();
29
30
  return SPACE_BODIES.includes(id) ? id : undefined;
30
31
  };
32
+ /**
33
+ * The zoom range of the space view when it carries its own controls. The floor, a millionth, takes the camera out past Neptune in the true scale. The ceiling is where the camera reaches the body: it is held at
34
+ * 1.05 radii from the surface (`FIT_DISTANCE` over the zoom), so past a zoom of about 3.2 nothing moves; 3 shows the surface as sharp as the painted maps (2048 pixels round) and the shader allow.
35
+ */
36
+ const CARRIED_LIMITS = { zoomMin: 1e-6, zoomMax: 3, tiltMax: 90 };
31
37
  const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}</style><div id="stage"></div><div id="labels"></div>`;
32
38
  /**
33
39
  * The `<wakusei-space>` custom element: the Earth, the Moon, the Sun and the planets where they are at a date and time, drawn with three.js through the shared renderer. It takes `center`
@@ -35,6 +41,9 @@ const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;ove
35
41
  * `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
36
42
  * only when something changes, and nothing while it is out of sight.
37
43
  *
44
+ * 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
+ * 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
+ *
38
47
  * @example
39
48
  * ```ts no-run
40
49
  * import type { WakuseiSpace } from "@johnmorrisdotca/wakusei-planets/space/element";
@@ -65,6 +74,11 @@ export class WakuseiSpace extends HTMLElement {
65
74
  #painter;
66
75
  #focusBeforeRide = "earth";
67
76
  #lostTold = false;
77
+ #hands;
78
+ /** 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. */
79
+ get controller() {
80
+ return this.#hands?.controller;
81
+ }
68
82
  connectedCallback() {
69
83
  this.#model.centre = readCentre(this.getAttribute("center")) ?? this.#model.centre;
70
84
  this.#mode = readTime(this.getAttribute("time"));
@@ -116,10 +130,13 @@ export class WakuseiSpace extends HTMLElement {
116
130
  this.#last = performance.now();
117
131
  this.#schedule();
118
132
  this.addEventListener("pointerdown", this.#down);
133
+ this.#hands = carryControls(this, { limits: CARRIED_LIMITS, initial: { drag: "turn" }, onChange: (view, info) => this.setView(view, info.final) });
119
134
  this.#labelBox.addEventListener("click", this.#labelClick);
120
135
  this.#labelBox.addEventListener("focusin", this.#labelFocus);
121
136
  }
122
137
  disconnectedCallback() {
138
+ this.#hands?.unbind();
139
+ this.#hands = undefined;
123
140
  this.removeEventListener("pointerdown", this.#down);
124
141
  window.removeEventListener("pointerup", this.#up, true);
125
142
  clearTimeout(this.#timer);
@@ -235,6 +252,7 @@ export class WakuseiSpace extends HTMLElement {
235
252
  if (view.yaw === now.yaw && view.tilt === now.tilt && view.zoom === now.zoom)
236
253
  return;
237
254
  this.#model.view = { yaw: view.yaw, tilt: view.tilt, zoom: view.zoom };
255
+ this.dispatchEvent(new CustomEvent("wakusei-view", { detail: { yaw: view.yaw, tilt: view.tilt, zoom: view.zoom } }));
238
256
  const drawn = this.#model.drawnView;
239
257
  if (drawn && !final && view.zoom === drawn.zoom) {
240
258
  const turned = Math.max(Math.abs(view.yaw - drawn.yaw), Math.abs(view.tilt - drawn.tilt)) * RAD;
@@ -0,0 +1,20 @@
1
+ import { type LineOptions } from "./line.ts";
2
+ import { type StarLook, type StarNumbers } from "./star.ts";
3
+ /**
4
+ * A star as a line drawing, as an SVG string: its outline (squeezed when it is oblate), its cells and spots as outlines, a ring of rays, and, drawn round it, the Sun's size and the orbits of the Earth and Jupiter
5
+ * wherever they fall in the picture, so the size can be read against what we know. A caption under it gives the radius, the temperature and the class. It takes the options of `lineSvg` (the size, `pose`, `fill`, `zoom`,
6
+ * `pan`, `lang` and the colours); a picture of a star with no `pose` is a portrait of the Sun's axis.
7
+ *
8
+ * @param star - The star's numbers, or a star already made with `starLook`.
9
+ * @param options - The drawing's size, pose and colours.
10
+ * @returns The SVG markup, `<svg ...>` to `</svg>`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { starLineSvg } from "@johnmorrisdotca/wakusei-planets";
15
+ *
16
+ * const svg = starLineSvg({ name: "Betelgeuse", temperatureK: 3600, radiusSun: 760, luminosityClass: "Ia" }, { size: 320 });
17
+ * console.log(svg.startsWith("<svg"), svg.includes("Earth's orbit"));
18
+ * ```
19
+ */
20
+ export declare function starLineSvg(star: StarNumbers | StarLook, options?: LineOptions): string;
@@ -0,0 +1,59 @@
1
+ // A star as a line drawing: the Sun's outline drawing with this star's size, shape, cells and spots, and the Sun and two orbits drawn round it, so the size can be read against what we know. Pure: one SVG string.
2
+ import { portrait } from "./pose.js";
3
+ import { bodyGroup, mix, NAVY } from "./line.js";
4
+ import { starLook } from "./star.js";
5
+ /** What a star's size is drawn beside: the Sun, the Earth's orbit and Jupiter's orbit, in solar radii (one astronomical unit is 215.03). */
6
+ const RINGS = [
7
+ { ratio: 1, en: "Sun", ja: "太陽" },
8
+ { ratio: 215.03, en: "Earth's orbit", ja: "地球の軌道" },
9
+ { ratio: 1118, en: "Jupiter's orbit", ja: "木星の軌道" },
10
+ ];
11
+ const n = (v) => (Math.round(v * 100) / 100).toString();
12
+ const escape = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
13
+ /**
14
+ * A star as a line drawing, as an SVG string: its outline (squeezed when it is oblate), its cells and spots as outlines, a ring of rays, and, drawn round it, the Sun's size and the orbits of the Earth and Jupiter
15
+ * wherever they fall in the picture, so the size can be read against what we know. A caption under it gives the radius, the temperature and the class. It takes the options of `lineSvg` (the size, `pose`, `fill`, `zoom`,
16
+ * `pan`, `lang` and the colours); a picture of a star with no `pose` is a portrait of the Sun's axis.
17
+ *
18
+ * @param star - The star's numbers, or a star already made with `starLook`.
19
+ * @param options - The drawing's size, pose and colours.
20
+ * @returns The SVG markup, `<svg ...>` to `</svg>`.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { starLineSvg } from "@johnmorrisdotca/wakusei-planets";
25
+ *
26
+ * const svg = starLineSvg({ name: "Betelgeuse", temperatureK: 3600, radiusSun: 760, luminosityClass: "Ia" }, { size: 320 });
27
+ * console.log(svg.startsWith("<svg"), svg.includes("Earth's orbit"));
28
+ * ```
29
+ */
30
+ export function starLineSvg(star, options = {}) {
31
+ const made = "look" in star ? star : starLook(star);
32
+ const size = options.size ?? 320;
33
+ const lang = options.lang ?? "en";
34
+ const stroke = options.stroke ?? mix(made.tone, "#ffffff", 0.3);
35
+ const paper = options.paper ?? mix(made.tone, NAVY, 0.7);
36
+ const hair = Math.max(0.6, size / 320);
37
+ const pose = options.pose ?? portrait("sun", options);
38
+ const fit = options.fill === undefined ? 0.94 / 1.08 : options.fill;
39
+ const zoom = options.zoom ?? 1;
40
+ const frame = { cx: (size / 2) * (1 - (options.panX ?? 0)), cy: (size / 2) * (1 + (options.panY ?? 0)), r: (size / 2) * fit * zoom };
41
+ const label = lang === "ja" ? `${made.facts.name.ja}の線画 (数字から描いた絵)` : `Line drawing of ${made.facts.name.en}, drawn from its numbers`;
42
+ const rings = [];
43
+ for (const ring of RINGS) {
44
+ const r = (ring.ratio / made.radiusSun) * frame.r;
45
+ // the star's own edge is drawn already; a ring too small to see or far outside the picture is left out
46
+ if (Math.abs(ring.ratio / made.radiusSun - 1) < 0.04 || r < 3 || r > size * 1.5)
47
+ continue;
48
+ const text = lang === "ja" ? ring.ja : ring.en;
49
+ const x = frame.cx + r * Math.SQRT1_2;
50
+ const y = frame.cy + r * Math.SQRT1_2;
51
+ rings.push(`<circle cx="${n(frame.cx)}" cy="${n(frame.cy)}" r="${n(r)}" fill="none" stroke="${stroke}" stroke-opacity="0.5" stroke-width="${n(hair)}" stroke-dasharray="${n(hair * 4)} ${n(hair * 4)}"/>` +
52
+ (x < size - 4 && y < size - 14 ? `<text x="${n(x)}" y="${n(y)}" font-size="${n(size / 38)}" fill="${stroke}" fill-opacity="0.85" font-family="system-ui,sans-serif">${escape(text)}</text>` : ""));
53
+ }
54
+ const radius = made.radiusSun >= 10 ? Math.round(made.radiusSun).toLocaleString("en-US") : String(Number(made.radiusSun.toPrecision(3)));
55
+ const caption = lang === "ja" ? `太陽の${radius}倍 · ${Math.round(made.temperatureK).toLocaleString("en-US")} K · ${made.luminosityClass}` : `${radius} × Sun · ${Math.round(made.temperatureK).toLocaleString("en-US")} K · ${made.luminosityClass}`;
56
+ const text = `<text x="${n(size / 2)}" y="${n(size - size / 40)}" text-anchor="middle" font-size="${n(size / 34)}" fill="${stroke}" fill-opacity="0.85" font-family="system-ui,sans-serif">${escape(caption)}</text>`;
57
+ const group = bodyGroup("sun", pose, frame, { stroke, paper }, hair, 1, made.facts, `wk-star-${[...made.key].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7).toString(36)}`);
58
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n(size)} ${n(size)}" width="${n(size)}" height="${n(size)}" role="img" aria-label="${escape(label)}"><title>${escape(label)}</title>${rings.join("")}${group}${text}</svg>`;
59
+ }
package/dist/star.d.ts ADDED
@@ -0,0 +1,193 @@
1
+ import { type BodyFacts } from "./facts.ts";
2
+ import type { BodyLook } from "./scene/look.ts";
3
+ /**
4
+ * A star's luminosity class, as the spectral type writes it: `0` a hypergiant, `Ia`, `Iab` and `Ib` supergiants, `II` a bright giant, `III` a giant, `IV` a subgiant, `V` a dwarf (the Sun is G2 V), `VI` a subdwarf and `D` a white dwarf.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { LUMINOSITY_CLASSES, type LuminosityClass } from "@johnmorrisdotca/wakusei-planets";
9
+ *
10
+ * const supergiant: LuminosityClass = LUMINOSITY_CLASSES[1];
11
+ * console.log(supergiant, LUMINOSITY_CLASSES.length);
12
+ * ```
13
+ */
14
+ export declare const LUMINOSITY_CLASSES: readonly ["0", "Ia", "Iab", "Ib", "II", "III", "IV", "V", "VI", "D"];
15
+ /**
16
+ * One of the classes in `LUMINOSITY_CLASSES`.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import type { LuminosityClass } from "@johnmorrisdotca/wakusei-planets";
21
+ *
22
+ * const dwarf: LuminosityClass = "V";
23
+ * console.log(dwarf);
24
+ * ```
25
+ */
26
+ export type LuminosityClass = (typeof LUMINOSITY_CLASSES)[number];
27
+ /**
28
+ * The numbers that make a star's picture in `StarNumbers`, by name: the ones a page may mark as `estimated`.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import type { StarNumberName } from "@johnmorrisdotca/wakusei-planets";
33
+ *
34
+ * const name: StarNumberName = "radiusSun";
35
+ * console.log(name);
36
+ * ```
37
+ */
38
+ export type StarNumberName = "temperatureK" | "radiusSun" | "luminosityClass" | "rotationDays" | "oblateness";
39
+ /**
40
+ * The numbers a star is drawn from. Only the temperature and the radius are needed; the rest has a stated default.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { starLook, type StarNumbers } from "@johnmorrisdotca/wakusei-planets";
45
+ *
46
+ * const betelgeuse: StarNumbers = { name: "Betelgeuse", temperatureK: 3600, radiusSun: 760, luminosityClass: "Ia", rotationDays: 2100 };
47
+ * console.log(starLook(betelgeuse).colour);
48
+ * ```
49
+ */
50
+ export interface StarNumbers {
51
+ /** What to call it: the picture's label. Default `Star`. */
52
+ name?: string;
53
+ /** The effective surface temperature in kelvin, 1,000 to 200,000. It sets the colour. */
54
+ temperatureK: number;
55
+ /** The radius in solar radii (the Sun is 1), above 0 and up to 5,000. It sets the size beside the Sun and the size of the rings drawn round the star. */
56
+ radiusSun: number;
57
+ /** The luminosity class: it sets how coarse the surface is (fine cells on a dwarf, a few giant cells on a supergiant, none on a white dwarf). Default `V`. */
58
+ luminosityClass?: LuminosityClass;
59
+ /** Days for one turn at the equator, negative when it turns backwards. Left out, a slow turn is drawn and the picture says the rotation is not given. */
60
+ rotationDays?: number;
61
+ /** How spotted it is, 0 to 1. Left out it follows the temperature and the class: none on hot stars, many on cool dwarfs and red dwarfs, few and large on giants. The spots are illustrative either way. */
62
+ activity?: number;
63
+ /** (equatorial radius - polar radius) / equatorial radius, 0 to 0.4. A fast spinner such as Altair is about 0.2. The star is drawn squashed, with the poles hotter than the equator (gravity darkening). Default 0. */
64
+ oblateness?: number;
65
+ /** The strength of the soft glow round the star, 0 to 1. Default 0.8. */
66
+ corona?: number;
67
+ /** The numbers above that are estimates, not measurements (a radius worked out from brightness, say). The picture says so. */
68
+ estimated?: readonly StarNumberName[];
69
+ }
70
+ /**
71
+ * How well a part of a star's picture is known: `measured` is a number the page gave, `estimated` one it marked as an estimate, `derived` is worked out from those numbers by a stated rule, and `illustrative` is invented to look right.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import type { StarStatus } from "@johnmorrisdotca/wakusei-planets";
76
+ *
77
+ * const status: StarStatus = "illustrative";
78
+ * console.log(status);
79
+ * ```
80
+ */
81
+ export type StarStatus = "measured" | "estimated" | "derived" | "illustrative";
82
+ /**
83
+ * One part of a star's picture and how well it is known, with a sentence for a page to show in English and Japanese.
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * import { starLook, type StarPart } from "@johnmorrisdotca/wakusei-planets";
88
+ *
89
+ * const parts: readonly StarPart[] = starLook({ temperatureK: 5772, radiusSun: 1 }).parts;
90
+ * console.log(parts.map((part) => `${part.part}: ${part.status}`).join(", "));
91
+ * ```
92
+ */
93
+ export interface StarPart {
94
+ part: "temperature" | "colour" | "size" | "edge" | "surface" | "spots" | "rotation" | "shape" | "poles" | "prominences" | "glow";
95
+ status: StarStatus;
96
+ note: {
97
+ en: string;
98
+ ja: string;
99
+ };
100
+ }
101
+ /**
102
+ * A star ready to draw: its numbers with the defaults filled in, its colour, the shaded look and the facts the line drawing uses, how fast it turns on a page, and which parts of the picture are known and which invented.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * import { starLook } from "@johnmorrisdotca/wakusei-planets";
107
+ *
108
+ * const star = starLook({ name: "Sirius A", temperatureK: 9940, radiusSun: 1.71, luminosityClass: "V", rotationDays: 5.5 });
109
+ * console.log(star.colour, star.disclaimer.en);
110
+ * ```
111
+ */
112
+ export interface StarLook {
113
+ /** The numbers it was made from, as they were given. */
114
+ numbers: StarNumbers;
115
+ name: string;
116
+ temperatureK: number;
117
+ radiusSun: number;
118
+ radiusKm: number;
119
+ /** Which drawing this is: `full` or `low` (see `StarLookOptions`). */
120
+ quality: "full" | "low";
121
+ luminosityClass: LuminosityClass;
122
+ /** `undefined` when the numbers gave none. */
123
+ rotationDays: number | undefined;
124
+ activity: number;
125
+ oblateness: number;
126
+ corona: number;
127
+ /** The black-body colour of the temperature, `#rrggbb`. */
128
+ colour: string;
129
+ /** The colour the line drawing and a page's accents take: the bright cells of the shaded look, a little stronger than the plain black body so a star reads as coloured, `#rrggbb`. */
130
+ tone: string;
131
+ /** The shaded look: its `surface` is shader code with the numbers written into it. Its `id` is `sun`, the one star among the bodies. Draw it through the element's `star` attribute; it is not registered under a body. */
132
+ look: BodyLook;
133
+ /** The facts the line drawing uses: the Sun's, with this star's name, size, shape and the outlines of its cells and spots. */
134
+ facts: BodyFacts;
135
+ /** How it turns on a page: degrees a second (negative for backwards), and how many times faster than the star really turns that is (`undefined` when its rotation is not given). */
136
+ turn: {
137
+ degreesPerSecond: number;
138
+ speedUp: number | undefined;
139
+ };
140
+ /** Which parts of the picture are measured, estimated, derived or illustrative. */
141
+ parts: readonly StarPart[];
142
+ /** The sentence for a page to show with the picture. */
143
+ disclaimer: {
144
+ en: string;
145
+ ja: string;
146
+ };
147
+ /** The same numbers give the same key: the renderer keeps one drawing for each. */
148
+ key: string;
149
+ }
150
+ /**
151
+ * The Sun as numbers: the first example of a star, and the size the others are drawn beside.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * import { STAR_SUN, starLook } from "@johnmorrisdotca/wakusei-planets";
156
+ *
157
+ * console.log(STAR_SUN.temperatureK, starLook(STAR_SUN).turn.degreesPerSecond);
158
+ * ```
159
+ */
160
+ export declare const STAR_SUN: StarNumbers;
161
+ /**
162
+ * How much to spend drawing a star: `full` boils its granulation and draws prominences and flares on the edge of an active star; `low` is a still surface and a soft glow, for weak devices.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * import { starLook, type StarLookOptions } from "@johnmorrisdotca/wakusei-planets";
167
+ *
168
+ * const options: StarLookOptions = { quality: "low" };
169
+ * console.log(starLook({ temperatureK: 3042, radiusSun: 0.154 }, options).quality);
170
+ * ```
171
+ */
172
+ export interface StarLookOptions {
173
+ quality?: "full" | "low";
174
+ }
175
+ /**
176
+ * Everything the package draws a star with, from the numbers alone: the same numbers always give the same star. Throws a `RangeError` that names the number when one is out of range.
177
+ *
178
+ * The colour is the black body of `temperatureK`. The surface is grained by the luminosity class (and faint on hot stars, smooth on a white dwarf), spotted by `activity` (none on hot stars by default, many on
179
+ * cool dwarfs), darker toward the edge by the temperature, flattened by `oblateness` with hotter poles, and ringed with a soft corona. The cells and the spots are invented; `parts` says which parts are not.
180
+ *
181
+ * @param numbers - The star's numbers.
182
+ * @param options - `quality: "low"` for a cheaper drawing for weak devices (no boiling granulation, no prominences or flares); the default is `full`.
183
+ * @returns The star ready to draw.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { starLook } from "@johnmorrisdotca/wakusei-planets";
188
+ *
189
+ * const rigel = starLook({ name: "Rigel", temperatureK: 12100, radiusSun: 78.9, luminosityClass: "Ia", rotationDays: 25 });
190
+ * console.log(rigel.colour, rigel.activity, rigel.parts.filter((part) => part.status === "illustrative").length);
191
+ * ```
192
+ */
193
+ export declare function starLook(numbers: StarNumbers, options?: StarLookOptions): StarLook;
package/dist/star.js ADDED
@@ -0,0 +1,261 @@
1
+ // A star drawn from numbers: its temperature gives the colour, its radius the size, its luminosity class the grain of its surface, its rotation how it turns, its activity the spots, its oblateness
2
+ // the shape and the darker equator. Nothing here is a photograph and the package holds no catalogue of stars: the page hands over the numbers. Pure: strings and numbers, no DOM, no three.js.
3
+ import { blackBodyRgb } from "./blackbody.js";
4
+ import { BODIES } from "./facts.js";
5
+ /**
6
+ * A star's luminosity class, as the spectral type writes it: `0` a hypergiant, `Ia`, `Iab` and `Ib` supergiants, `II` a bright giant, `III` a giant, `IV` a subgiant, `V` a dwarf (the Sun is G2 V), `VI` a subdwarf and `D` a white dwarf.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { LUMINOSITY_CLASSES, type LuminosityClass } from "@johnmorrisdotca/wakusei-planets";
11
+ *
12
+ * const supergiant: LuminosityClass = LUMINOSITY_CLASSES[1];
13
+ * console.log(supergiant, LUMINOSITY_CLASSES.length);
14
+ * ```
15
+ */
16
+ export const LUMINOSITY_CLASSES = ["0", "Ia", "Iab", "Ib", "II", "III", "IV", "V", "VI", "D"];
17
+ const SUN_K = 5772;
18
+ const SUN_R_KM = 695_700;
19
+ /** How long the Sun takes to turn once at its equator, in days, and the turn a page shows for it, in degrees a second. */
20
+ const SUN_DAYS = 25.38;
21
+ const TURN = 12;
22
+ /**
23
+ * The Sun as numbers: the first example of a star, and the size the others are drawn beside.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * import { STAR_SUN, starLook } from "@johnmorrisdotca/wakusei-planets";
28
+ *
29
+ * console.log(STAR_SUN.temperatureK, starLook(STAR_SUN).turn.degreesPerSecond);
30
+ * ```
31
+ */
32
+ export const STAR_SUN = { name: "Sun", temperatureK: SUN_K, radiusSun: 1, luminosityClass: "V", rotationDays: SUN_DAYS };
33
+ function within(name, value, low, high) {
34
+ if (!Number.isFinite(value) || value < low || value > high)
35
+ throw new RangeError(`${name} must be a number from ${low} to ${high}, got ${String(value)}`);
36
+ return value;
37
+ }
38
+ const clamp = (v, low, high) => Math.min(high, Math.max(low, v));
39
+ const lerp = (table, x) => {
40
+ if (x <= table[0][0])
41
+ return table[0][1];
42
+ for (let i = 1; i < table.length; i += 1) {
43
+ const [x1, y1] = table[i];
44
+ if (x <= x1) {
45
+ const [x0, y0] = table[i - 1];
46
+ return y0 + ((y1 - y0) * (x - x0)) / (x1 - x0);
47
+ }
48
+ }
49
+ return table[table.length - 1][1];
50
+ };
51
+ /** How spotted a star is when the page does not say: none on hot stars, many on cool dwarfs and red dwarfs, fewer on giants (their spots are big and few). */
52
+ function defaultActivity(temperatureK, cls, rotationDays) {
53
+ if (cls === "D")
54
+ return 0;
55
+ let a = lerp([[3000, 0.85], [3800, 0.8], [4500, 0.6], [SUN_K, 0.35], [6500, 0.15], [7000, 0.02], [7500, 0]], temperatureK);
56
+ if (cls === "0" || cls === "Ia" || cls === "Iab" || cls === "Ib" || cls === "II" || cls === "III")
57
+ a *= 0.55;
58
+ if (rotationDays !== undefined)
59
+ a *= Math.abs(rotationDays) < 5 ? 1.5 : Math.abs(rotationDays) > 60 ? 0.7 : 1;
60
+ return clamp(a, 0, 1);
61
+ }
62
+ /** The coarseness of the surface by class: the noise frequency of the big cells on the unit sphere (the Sun's is 24), and the share of the finer cells in the mix. */
63
+ const GRAIN = { "0": [1.8, 0.3], Ia: [2.2, 0.3], Iab: [2.7, 0.32], Ib: [3.2, 0.35], II: [4.5, 0.4], III: [7, 0.45], IV: [13, 0.5], V: [24, 0.55], VI: [28, 0.55], D: [0, 0] };
64
+ /** How many cell outlines the line drawing has, and how wide each is, in degrees, by class. */
65
+ const CELLS = { "0": [6, 30], Ia: [7, 28], Iab: [9, 24], Ib: [12, 20], II: [18, 16], III: [28, 12], IV: [40, 9], V: [60, 6.5], VI: [70, 5], D: [0, 0] };
66
+ /** How strongly a surface shows its cells: full for a cool star, fading through the hot ones whose outer layers are not convecting, none for a white dwarf. */
67
+ const visibility = (temperatureK, cls) => (cls === "D" ? 0 : clamp((9500 - temperatureK) / 3000, 0.12, 1));
68
+ const f = (x) => x.toFixed(4);
69
+ const v3 = (c) => `vec3(${f(c[0])}, ${f(c[1])}, ${f(c[2])})`;
70
+ const unit = (kelvin) => blackBodyRgb(kelvin).map((v) => v / 255);
71
+ const saturate = (c, s) => {
72
+ const l = c[0] * 0.3 + c[1] * 0.59 + c[2] * 0.11;
73
+ return [0, 1, 2].map((i) => clamp(l + (c[i] - l) * s, 0, 1));
74
+ };
75
+ const hex = (c) => `#${[0, 1, 2].map((i) => Math.round(clamp(c[i], 0, 1) * 255).toString(16).padStart(2, "0")).join("")}`;
76
+ /** Deterministic random numbers from a seed, so the same numbers give the same spots. */
77
+ function random(seed) {
78
+ let a = seed >>> 0;
79
+ return () => {
80
+ a = (a + 0x6d2b79f5) >>> 0;
81
+ let t = a;
82
+ t = Math.imul(t ^ (t >>> 15), t | 1);
83
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
84
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
85
+ };
86
+ }
87
+ const seedOf = (text) => [...text].reduce((h, ch) => Math.imul(h ^ ch.charCodeAt(0), 16777619) >>> 0, 2166136261);
88
+ /** The outlines of a star's cells and spots for the line drawing, as features on the body (longitude and latitude in degrees). */
89
+ function features(cls, gran, activity, key) {
90
+ const rnd = random(seedOf(key));
91
+ const out = [];
92
+ const [count, width] = CELLS[cls];
93
+ const cells = gran < 0.2 ? 0 : Math.round(count * gran);
94
+ const golden = Math.PI * (3 - Math.sqrt(5));
95
+ for (let i = 0; i < cells; i += 1) {
96
+ const z = 1 - (2 * (i + 0.5)) / cells;
97
+ const lat = (Math.asin(z) * 180) / Math.PI;
98
+ const lon = ((((i * golden * 180) / Math.PI) % 360) + 360) % 360 - 180;
99
+ out.push({ kind: "circle", lon, lat, radius: width * (0.55 + 0.35 * rnd()) });
100
+ }
101
+ const spots = Math.round(activity * 14);
102
+ const giant = cls === "0" || cls === "Ia" || cls === "Iab" || cls === "Ib" || cls === "II" || cls === "III";
103
+ const band = 25 + 43 * activity;
104
+ for (let i = 0; i < spots; i += 1) {
105
+ const lat = (rnd() * 2 - 1) * band;
106
+ const lon = rnd() * 360 - 180;
107
+ const radius = giant ? (cls === "III" ? 7 : 12) + rnd() * 5 : 2.2 + rnd() * 2.4;
108
+ out.push({ kind: "circle", lon, lat, radius, fill: true });
109
+ out.push({ kind: "circle", lon, lat, radius: radius * 1.7 });
110
+ }
111
+ return out;
112
+ }
113
+ const parts = (s) => {
114
+ const known = (name) => (s.estimated.has(name) ? "estimated" : "measured");
115
+ const ratio = s.radiusSun >= 10 ? Math.round(s.radiusSun).toLocaleString("en-US") : String(Number(s.radiusSun.toPrecision(3)));
116
+ const out = [
117
+ { part: "temperature", status: known("temperatureK"), note: { en: `Surface temperature: ${Math.round(s.temperatureK).toLocaleString("en-US")} K, as given.`, ja: `表面の温度: ${Math.round(s.temperatureK)} K (与えられた数字)。` } },
118
+ { part: "colour", status: "derived", note: { en: "Colour: a black body at that temperature, the way a camera shows it. It is not a spectrum.", ja: "色: その温度の黒体の色 (カメラで見た色)。スペクトルではありません。" } },
119
+ { part: "size", status: known("radiusSun"), note: { en: `Size: ${ratio} times the Sun's radius, as given.`, ja: `大きさ: 太陽の半径の${ratio}倍 (与えられた数字)。` } },
120
+ { part: "edge", status: "derived", note: { en: "Edge darkening: worked out from the temperature, roughly.", ja: "ふちの暗さ: 温度からおおよそ計算しています。" } },
121
+ { part: "surface", status: "illustrative", note: { en: `Surface texture: how coarse it is follows the luminosity class (${s.cls}); the pattern itself is invented.`, ja: `表面のもよう: 細かさは明るさの階級 (${s.cls}) で決めています。もようは作りものです。` } },
122
+ { part: "spots", status: "illustrative", note: { en: "Spots: how many follows the temperature and the class; where they are is invented. They are not observations.", ja: "黒点: 数は温度と階級から決めています。場所は作りものです。観測ではありません。" } },
123
+ ];
124
+ if (s.rotationDays === undefined)
125
+ out.push({ part: "rotation", status: "illustrative", note: { en: "Turning: no rotation was given, so a slow turn is drawn.", ja: "自転: 数字がないので、ゆっくり回しています。" } });
126
+ else {
127
+ const times = s.speedUp === undefined ? "" : Math.round(s.speedUp).toLocaleString("en-US");
128
+ out.push({ part: "rotation", status: known("rotationDays"), note: { en: `Turning: one turn in ${Number(Math.abs(s.rotationDays).toPrecision(3))} days, shown ${times} times faster than real.`, ja: `自転: 1周${Number(Math.abs(s.rotationDays).toPrecision(3))}日。実際の${times}倍の速さで見せています。` } });
129
+ }
130
+ if (s.oblateness > 0) {
131
+ out.push({ part: "shape", status: known("oblateness"), note: { en: `Shape: flattened by ${Number(s.oblateness.toPrecision(2))}, as given.`, ja: `形: ${Number(s.oblateness.toPrecision(2))}だけつぶれています (与えられた数字)。` } });
132
+ out.push({ part: "poles", status: "derived", note: { en: "Hotter poles and a darker equator (gravity darkening): worked out from the flattening.", ja: "極は熱く、赤道は暗い (重力暗化): つぶれ方から計算しています。" } });
133
+ }
134
+ if (s.prominence)
135
+ out.push({ part: "prominences", status: "illustrative", note: { en: "Prominences and flares on the edge: drawn for looks on an active star, not observed.", ja: "ふちの炎 (プロミネンスやフレア): 活発な星に見た目のために描いています。観測ではありません。" } });
136
+ out.push({ part: "glow", status: "illustrative", note: { en: "The soft glow round the star is for looks, not a measurement.", ja: "星のまわりのやわらかい光は、見た目のための作りものです。" } });
137
+ return out;
138
+ };
139
+ /**
140
+ * Everything the package draws a star with, from the numbers alone: the same numbers always give the same star. Throws a `RangeError` that names the number when one is out of range.
141
+ *
142
+ * The colour is the black body of `temperatureK`. The surface is grained by the luminosity class (and faint on hot stars, smooth on a white dwarf), spotted by `activity` (none on hot stars by default, many on
143
+ * cool dwarfs), darker toward the edge by the temperature, flattened by `oblateness` with hotter poles, and ringed with a soft corona. The cells and the spots are invented; `parts` says which parts are not.
144
+ *
145
+ * @param numbers - The star's numbers.
146
+ * @param options - `quality: "low"` for a cheaper drawing for weak devices (no boiling granulation, no prominences or flares); the default is `full`.
147
+ * @returns The star ready to draw.
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * import { starLook } from "@johnmorrisdotca/wakusei-planets";
152
+ *
153
+ * const rigel = starLook({ name: "Rigel", temperatureK: 12100, radiusSun: 78.9, luminosityClass: "Ia", rotationDays: 25 });
154
+ * console.log(rigel.colour, rigel.activity, rigel.parts.filter((part) => part.status === "illustrative").length);
155
+ * ```
156
+ */
157
+ export function starLook(numbers, options = {}) {
158
+ const low = options.quality === "low";
159
+ const temperatureK = within("temperatureK", numbers.temperatureK, 1000, 200_000);
160
+ const radiusSun = within("radiusSun", numbers.radiusSun, 1e-4, 5000);
161
+ const cls = numbers.luminosityClass ?? "V";
162
+ if (!LUMINOSITY_CLASSES.includes(cls))
163
+ throw new RangeError(`luminosityClass must be one of ${LUMINOSITY_CLASSES.join(", ")}, got ${String(cls)}`);
164
+ const rotationDays = numbers.rotationDays === undefined ? undefined : within("rotationDays", numbers.rotationDays, -1e6, 1e6);
165
+ if (rotationDays === 0)
166
+ throw new RangeError("rotationDays must not be 0: leave it out when the rotation is not known");
167
+ const oblateness = numbers.oblateness === undefined ? 0 : within("oblateness", numbers.oblateness, 0, 0.4);
168
+ const corona = numbers.corona === undefined ? 0.8 : within("corona", numbers.corona, 0, 1);
169
+ const activity = numbers.activity === undefined ? defaultActivity(temperatureK, cls, rotationDays) : within("activity", numbers.activity, 0, 1);
170
+ const name = numbers.name !== undefined && numbers.name.trim() !== "" ? numbers.name.trim() : "Star";
171
+ const estimated = new Set(numbers.estimated ?? []);
172
+ // colour: the black body for the cells, a cooler and more saturated one for the lanes between them
173
+ const body = unit(temperatureK);
174
+ const cell = saturate(unit(temperatureK * 1.06), 2);
175
+ const lane = saturate(unit(temperatureK * (0.62 + 0.3 * clamp((temperatureK - 5000) / 7000, 0, 1))), 2.6).map((v) => v * 0.85);
176
+ const gran = visibility(temperatureK, cls);
177
+ const [grainFreq, grainFine] = GRAIN[cls];
178
+ const band = 25 + 43 * activity;
179
+ const threshold = 0.74 - 0.2 * activity;
180
+ const spotFreq = cls === "0" || cls === "Ia" ? 2 : cls === "Iab" || cls === "Ib" || cls === "II" ? 2.6 : cls === "III" ? 3.4 : temperatureK < 3900 ? 6.5 : 5;
181
+ // gravity darkening: the pole is hotter than the equator by (1 - 3e)^beta, beta 0.25 for a star whose envelope is radiative and 0.08 for a convective one (von Zeipel; Lucy)
182
+ const beta = temperatureK > 7000 ? 0.25 : 0.08;
183
+ const eq = oblateness > 0 ? Math.pow(Math.max(0.05, 1 - 3 * oblateness), beta) : 1;
184
+ const pole = (2 * temperatureK) / (1 + eq);
185
+ const ratioAt = (k) => {
186
+ const c = unit(k);
187
+ const b = (k / temperatureK) ** 2;
188
+ return [c[0] / body[0] * b, c[1] / body[1] * b, c[2] / body[2] * b];
189
+ };
190
+ const grain = cls === "D"
191
+ ? "float cell = 0.8;"
192
+ : low
193
+ ? `float g = fbm(p * ${f(grainFreq)});
194
+ float g2 = fbm(p * ${f(grainFreq * 2.9)} + 4.0);
195
+ float cell = mix(0.8, smoothstep(0.32, 0.72, mix(g, g2, ${f(grainFine)})), ${f(gran)});`
196
+ : `float boil = 0.5 + 0.5 * sin(uTime * 0.35);
197
+ float g = fbm(p * ${f(grainFreq)} + vec3(0.0, 0.0, uTime * 0.004));
198
+ float g2 = mix(fbm(p * ${f(grainFreq * 2.9)} + 4.0), fbm(p * ${f(grainFreq * 2.9)} + 11.0), boil);
199
+ float cell = mix(0.8, smoothstep(0.32, 0.72, mix(g, g2, ${f(grainFine)})), ${f(gran)});`;
200
+ const shape = oblateness > 0 ? `\n col *= mix(${v3(ratioAt(pole))}, ${v3(ratioAt(eq * pole))}, 1.0 - p.z * p.z);` : "";
201
+ const spots = activity > 0.02
202
+ ? `
203
+ float act = smoothstep(radians(${f(band)}), radians(8.0), abs(lat(p)));
204
+ float sn = fbm(p * ${f(spotFreq)} + 3.0);
205
+ float spot = smoothstep(${f(threshold)}, ${f(threshold + 0.08)}, sn) * act;
206
+ float pen = smoothstep(${f(threshold - 0.07)}, ${f(threshold)}, sn) * act;
207
+ col = mix(col, ${v3(lane.map((v) => v * 0.6))}, pen * 0.55);
208
+ col = mix(col, ${v3(lane.map((v) => v * 0.16))}, spot * 0.92);`
209
+ : "";
210
+ const surface = `${low || cls === "D" ? "" : "\nuniform float uTime;"}
211
+ vec4 surface(vec3 p) {
212
+ ${grain}
213
+ vec3 col = mix(${v3(lane)}, ${v3(cell)}, cell);${low ? "" : "\n col *= 0.8 + 0.4 * smoothstep(0.1, 0.9, cell);"}${shape}${spots}
214
+ return vec4(col * 1.12, 0.0);
215
+ }`;
216
+ // the edge: the exponent of the limb darkening, and the colour the edge shifts to (a cooler layer seen at a slant)
217
+ const limb = clamp(0.5 + (SUN_K - temperatureK) / 30_000, 0.2, 0.7);
218
+ const cool = unit(temperatureK * 0.78);
219
+ const tint = [0, 1, 2].map((i) => Math.min(1, (cool[i] / body[i]) ** 1.4));
220
+ const glowColour = saturate(body, 1.1);
221
+ const spread = clamp(2.4 + (SUN_K - temperatureK) / 12_000, 1.7, 3.4);
222
+ const prominence = low || activity < 0.15 ? 0 : clamp(activity * 1.1, 0, 1);
223
+ const speedReal = rotationDays === undefined ? undefined : 360 / (Math.abs(rotationDays) * 86_400);
224
+ const shown = rotationDays === undefined ? TURN : clamp(TURN * (SUN_DAYS / Math.abs(rotationDays)) ** 0.4, 2, 60);
225
+ const degreesPerSecond = (rotationDays !== undefined && rotationDays < 0 ? -1 : 1) * shown;
226
+ const speedUp = speedReal === undefined ? undefined : shown / speedReal;
227
+ const key = JSON.stringify([low ? "low" : "full", name, temperatureK, radiusSun, cls, rotationDays ?? null, activity, oblateness, corona]);
228
+ const colour = hex(body);
229
+ const look = { id: "sun", surface, emissive: true, limb, limbTint: tint, glow: { colour: glowColour, strength: 0.62 * corona, spread, rim: 0.3 * corona, prominence, seed: (seedOf(key) % 1000) / 1000 } };
230
+ const facts = {
231
+ ...BODIES.sun,
232
+ name: { en: name, ja: name === "Star" ? "恒星" : name },
233
+ radiusKm: radiusSun * SUN_R_KM,
234
+ flattening: oblateness,
235
+ rotationHours: (rotationDays ?? SUN_DAYS) * 24,
236
+ colour,
237
+ features: features(cls, gran, activity, key),
238
+ };
239
+ const lines = parts({ temperatureK, radiusSun, cls, rotationDays, oblateness, speedUp, estimated, prominence: prominence > 0 });
240
+ return {
241
+ numbers,
242
+ name,
243
+ temperatureK,
244
+ radiusSun,
245
+ radiusKm: radiusSun * SUN_R_KM,
246
+ quality: low ? "low" : "full",
247
+ luminosityClass: cls,
248
+ rotationDays,
249
+ activity,
250
+ oblateness,
251
+ corona,
252
+ colour,
253
+ tone: hex(cell),
254
+ look,
255
+ facts,
256
+ turn: { degreesPerSecond, speedUp },
257
+ parts: lines,
258
+ disclaimer: { en: `${name}: drawn from its numbers, not a photo.`, ja: `${name}: 数字から描いた絵で、写真ではありません。` },
259
+ key,
260
+ };
261
+ }
package/dist/stars.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The stars you can see without a telescope: the 5,080 of the Yale Bright Star Catalogue to visual magnitude 6.0, with their names, positions, proper motion, brightness and colour.
2
2
  // An opt-in entry point (`@johnmorrisdotca/wakusei-planets/stars`): the table is about 100 kB gzipped and nothing else imports it. Pure: no DOM, no three.js, no state beyond the parsed table.
3
3
  import { J2000_MS } from "./clock.js";
4
+ import { blackBodyRgb } from "./blackbody.js";
4
5
  import { STAR_NAMES, STAR_ROWS } from "./data/stars.js";
5
6
  import { moment } from "./when.js";
6
7
  const stored = [];
@@ -168,11 +169,8 @@ export function starTemperatureK(colourIndex) {
168
169
  export function blackBodyColour(kelvin) {
169
170
  if (!Number.isFinite(kelvin) || kelvin <= 0)
170
171
  throw new RangeError(`kelvin must be a positive number, got ${kelvin}`);
171
- const t = Math.min(40_000, Math.max(1_000, kelvin)) / 100;
172
- const red = t <= 66 ? 255 : 329.698727446 * (t - 60) ** -0.1332047592;
173
- const green = t <= 66 ? 99.4708025861 * Math.log(t) - 161.1195681661 : 288.1221695283 * (t - 60) ** -0.0755148492;
174
- const blue = t >= 66 ? 255 : t <= 19 ? 0 : 138.5177312231 * Math.log(t - 10) - 305.0447927307;
175
- const byte = (v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, "0");
172
+ const [red, green, blue] = blackBodyRgb(kelvin);
173
+ const byte = (v) => Math.round(v).toString(16).padStart(2, "0");
176
174
  return `#${byte(red)}${byte(green)}${byte(blue)}`;
177
175
  }
178
176
  /**
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.23.0";
1
+ export declare const VERSION = "0.25.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.23.0";
1
+ export const VERSION = "0.25.0";