@johnmorrisdotca/chikyu-earth 0.33.2 → 0.34.1

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 (41) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +23 -5
  3. package/dist/cities/geometry.d.ts +233 -0
  4. package/dist/cities/geometry.js +174 -0
  5. package/dist/cities/host.d.ts +73 -0
  6. package/dist/cities/host.js +240 -0
  7. package/dist/element.d.ts +1 -1
  8. package/dist/element.js +3 -14
  9. package/dist/markers/index.d.ts +1 -0
  10. package/dist/markers/index.js +1 -0
  11. package/dist/markers/labels.d.ts +7 -1
  12. package/dist/markers/labels.js +12 -1
  13. package/dist/markers/place-layer.d.ts +43 -0
  14. package/dist/markers/place-layer.js +238 -0
  15. package/dist/markers/places.d.ts +279 -0
  16. package/dist/markers/places.js +213 -0
  17. package/dist/passes/element.js +2 -5
  18. package/dist/realistic/body-label.js +19 -11
  19. package/dist/realistic/earth.js +1 -1
  20. package/dist/realistic/element.d.ts +35 -0
  21. package/dist/realistic/element.js +94 -11
  22. package/dist/realistic/index.d.ts +2 -0
  23. package/dist/realistic/index.js +2 -0
  24. package/dist/satellites/index.d.ts +1 -0
  25. package/dist/satellites/index.js +1 -0
  26. package/dist/satellites/names.d.ts +14 -0
  27. package/dist/satellites/names.js +16 -0
  28. package/dist/sky/cover.d.ts +48 -0
  29. package/dist/sky/cover.js +100 -0
  30. package/dist/sky/host.js +48 -18
  31. package/dist/space/element.d.ts +103 -1
  32. package/dist/space/element.js +219 -3
  33. package/dist/space/index.d.ts +3 -1
  34. package/dist/space/index.js +1 -0
  35. package/dist/space/satellite-layer.d.ts +26 -0
  36. package/dist/space/satellite-layer.js +37 -1
  37. package/dist/space/satellite-model.d.ts +72 -0
  38. package/dist/space/satellite-model.js +82 -0
  39. package/dist/space/scene.d.ts +44 -1
  40. package/dist/space/scene.js +154 -2
  41. package/package.json +7 -3
@@ -15,11 +15,15 @@ import { folderSource } from "../door/map.js";
15
15
  import { ownCredit } from "../door/own.js";
16
16
  import { BODY_LABEL_ATTRIBUTES, bodyLabelText, loadMichroma, readBodyLabel } from "./body-label.js";
17
17
  import { createSkyHost, SKY_ATTRIBUTES, SKY_STYLE } from "../sky/host.js";
18
+ import { cleanPlaces, orthoView, readPlaces } from "../markers/places.js";
19
+ import { createPlaceLayer, PLACE_STYLE, readPlaceLook } from "../markers/place-layer.js";
20
+ import { CITY_NAMES_ATTRIBUTES, CITY_NAMES_STYLE, createCityHost } from "../cities/host.js";
21
+ import { project } from "../markers/project.js";
18
22
  import { createGate, frameCap } from "./gate.js";
19
23
  import { setSharedRenderer, setThreeLoader, takeRenderer } from "./shared.js";
20
24
  export { setSharedRenderer, setThreeLoader };
21
25
  import { MAX_TEXTURE, TIERS } from "./tiers.js";
22
- const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative}:host([immersive]){aspect-ratio:auto;width:100%;height:100%;touch-action:none!important;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}" + SKY_STYLE + METEOR_NOTE_STYLE + NOTES_STYLE;
26
+ const STYLE = ":host{display:block;aspect-ratio:1/1;position:relative;isolation:isolate}:host([immersive]){aspect-ratio:auto;width:100%;height:100%;touch-action:none!important;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#stage,#overlay{position:absolute;inset:0}#overlay{pointer-events:none}" + PLACE_STYLE + SKY_STYLE + CITY_NAMES_STYLE + METEOR_NOTE_STYLE + NOTES_STYLE;
23
27
  const RAD = Math.PI / 180;
24
28
  /** The Sun and the clouds are re-placed this often at real time: 15 degrees an hour is 0.25 degree a minute. */
25
29
  const LIVE_TICK_MS = 60_000;
@@ -130,7 +134,7 @@ export const readTime = (value) => {
130
134
  * ```
131
135
  */
132
136
  export class ChikyuEarthRealistic extends HTMLElement {
133
- static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "data", "camera", "immersive", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, "air-thickness", "air-label", "lang"];
137
+ static observedAttributes = ["cloud-drift", "center", "time", "speed", "clouds", "lights", "light", "live-seconds", "tiles", "data", "camera", "immersive", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look"];
134
138
  #model = newModel();
135
139
  #mode = "now";
136
140
  #view;
@@ -154,7 +158,12 @@ export class ChikyuEarthRealistic extends HTMLElement {
154
158
  #stage;
155
159
  #overlay;
156
160
  #pose = null;
161
+ /** The names of cities on the Earth (`city-names`), and the look of the names. */
162
+ #cities;
163
+ #citiesStyle = {};
157
164
  #listeners = new Set();
165
+ #placeLayer;
166
+ #placeList = [];
158
167
  #hands;
159
168
  #reach = null;
160
169
  /** The page has set a `speed` since the element came into the page: for a reader who prefers reduced motion, that is the Play that lets meteors start. */
@@ -191,7 +200,7 @@ export class ChikyuEarthRealistic extends HTMLElement {
191
200
  if (!this.hasAttribute("aria-label"))
192
201
  this.setAttribute("aria-label", "The Earth from space, with its sunlit and dark sides");
193
202
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
194
- root.innerHTML = `<div id="stage"></div><div id="overlay"></div><div id="notes"><p id="air-note" hidden></p><p id="meteor-note" hidden></p></div>`;
203
+ root.innerHTML = `<div id="stage"></div><div id="places"></div><div id="overlay"></div><div id="notes"><p id="air-note" hidden></p><p id="meteor-note" hidden></p></div>`;
195
204
  adoptStyles(root, STYLE, this.nonce);
196
205
  this.#stage = root.getElementById("stage");
197
206
  this.#overlay = root.getElementById("overlay");
@@ -205,6 +214,17 @@ export class ChikyuEarthRealistic extends HTMLElement {
205
214
  loadFont: loadMichroma,
206
215
  });
207
216
  this.#sky.setStyle(this.#skyStyle);
217
+ this.#placeLayer = createPlaceLayer(root.getElementById("places"));
218
+ this.#placeList = readPlaces(this.getAttribute("places"));
219
+ this.#placeLayer.set(this.#placeList);
220
+ this.#placeLayer.look = readPlaceLook(this.getAttribute("places-look"));
221
+ this.#cities = createCityHost({
222
+ root,
223
+ attribute: (name) => this.getAttribute(name),
224
+ language: () => ((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en"),
225
+ onError: (error) => this.dispatchEvent(new CustomEvent("chikyu-city-names-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
226
+ });
227
+ this.#cities.setStyle(this.#citiesStyle);
208
228
  this.#played = false;
209
229
  this.#model.meteors.on = this.#meteorsAsked();
210
230
  this.#model.meteors.strength = readMeteorStrength(this.getAttribute("meteors-strength"));
@@ -252,6 +272,9 @@ export class ChikyuEarthRealistic extends HTMLElement {
252
272
  this.#pose = { ...pose, transform: "" };
253
273
  for (const listener of this.#listeners)
254
274
  listener(this.#pose);
275
+ if (this.#placeLayer && (this.#placeList.length > 0 || this.#placeLayer.stats.shown > 0))
276
+ this.#placeLayer.frame(orthoView(pose));
277
+ this.#cityFrame();
255
278
  },
256
279
  onSatellitesError: (error) => this.dispatchEvent(new CustomEvent("chikyu-satellites-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
257
280
  onError: (error) => this.#fail(error instanceof Error ? error.message : String(error)),
@@ -279,7 +302,6 @@ export class ChikyuEarthRealistic extends HTMLElement {
279
302
  this.#hands = carryControls(this, { initial: this.#model.view, limits: LIMITS, onChange: (state, info) => this.setView(state, info.final) });
280
303
  this.#startTick();
281
304
  document.addEventListener("visibilitychange", this.#onVisible);
282
- this.#locate();
283
305
  }
284
306
  disconnectedCallback() {
285
307
  this.removeEventListener("pointerdown", this.#take);
@@ -303,6 +325,10 @@ export class ChikyuEarthRealistic extends HTMLElement {
303
325
  this.#taken = undefined;
304
326
  this.#sky?.dispose();
305
327
  this.#sky = undefined;
328
+ this.#placeLayer?.dispose();
329
+ this.#placeLayer = undefined;
330
+ this.#cities?.dispose();
331
+ this.#cities = undefined;
306
332
  }
307
333
  attributeChangedCallback(name, _old, value) {
308
334
  if (name === "center")
@@ -344,12 +370,24 @@ export class ChikyuEarthRealistic extends HTMLElement {
344
370
  if (name === "lang") {
345
371
  this.#applyBodyLabel();
346
372
  this.#sky?.refresh();
373
+ this.#cities?.refresh();
347
374
  }
348
375
  }
349
376
  else if (BODY_LABEL_ATTRIBUTES.includes(name))
350
377
  this.#applyBodyLabel();
351
378
  else if (SKY_ATTRIBUTES.includes(name))
352
379
  this.#sky?.refresh();
380
+ else if (name === "places") {
381
+ this.#placeList = readPlaces(value);
382
+ this.#placeLayer?.set(this.#placeList);
383
+ this.#gate?.soon();
384
+ }
385
+ else if (name === "places-look" && this.#placeLayer) {
386
+ this.#placeLayer.look = readPlaceLook(value);
387
+ this.#gate?.soon();
388
+ }
389
+ else if (CITY_NAMES_ATTRIBUTES.includes(name))
390
+ this.#cities?.refresh();
353
391
  if (name === "air-thickness" || name === "air-label" || name === "lang")
354
392
  setAirNote(this.#airNote, this, this.#model.airThickness);
355
393
  }
@@ -440,6 +478,56 @@ export class ChikyuEarthRealistic extends HTMLElement {
440
478
  this.#skyStyle = { ...value };
441
479
  this.#sky?.setStyle(this.#skyStyle);
442
480
  }
481
+ /**
482
+ * Places marked on the Earth (the attribute `places`, a JSON array): each `{ id, lon, lat, label, kind }`, `kind` being `here` (where the reader is: drawn bright and taller, with a quiet pulse) or `favourite`
483
+ * (the default: quieter). Each stands up out of the ground, turns with the Earth, is hidden on its far side and keeps its size in pixels at any zoom. Names go at the top, `here` first, and never overlap
484
+ * one another; one with no room is left out. The element stores nothing and sends nothing: the page hands the places over and keeps them where it likes. Setting the property writes the attribute; at most
485
+ * `MAX_PLACES` are drawn. Nothing is drawn again at rest: the pulse is the page's own animation, stopped out of sight and for a reader who asked for less motion.
486
+ */
487
+ get places() {
488
+ return this.#placeList.map((place) => ({ ...place }));
489
+ }
490
+ set places(value) {
491
+ const clean = cleanPlaces(value);
492
+ if (clean.length === 0)
493
+ this.removeAttribute("places");
494
+ else
495
+ this.setAttribute("places", JSON.stringify(clean));
496
+ }
497
+ /** How the places are drawn (the attribute `places-look`): `beam` (a light rising out of the ground with a ring at its foot, the default), `pin` (a thin stick with a round head) or `ring` (only the ring on the ground). */
498
+ get placesLook() {
499
+ return this.#placeLayer?.look ?? readPlaceLook(this.getAttribute("places-look"));
500
+ }
501
+ set placesLook(value) {
502
+ this.setAttribute("places-look", value);
503
+ }
504
+ /**
505
+ * The look of the names of cities (`city-names`): font, size, weight, colour, the outline round the text, and the dot's colour and size. Any of them may be left out; the Earth's size, the language and the data are not set here.
506
+ */
507
+ get cityNamesStyle() {
508
+ return { ...this.#citiesStyle };
509
+ }
510
+ set cityNamesStyle(value) {
511
+ this.#citiesStyle = { ...value };
512
+ this.#cities?.setStyle(this.#citiesStyle);
513
+ }
514
+ /** Tells the names of cities where the Earth is in the picture just drawn: the orthographic view the markers share. */
515
+ #cityFrame() {
516
+ const pose = this.#pose;
517
+ if (!this.#cities || !pose)
518
+ return;
519
+ this.#cities.frame({
520
+ width: pose.width,
521
+ height: pose.height,
522
+ radius: pose.radius,
523
+ project: (lon, lat, out) => {
524
+ const at = project(lon, lat, pose);
525
+ out.x = at.x;
526
+ out.y = at.y;
527
+ return at.z;
528
+ },
529
+ });
530
+ }
443
531
  /** Puts the name's settings and text right from the attributes (`body-label` and its family, `lang`). */
444
532
  #applyBodyLabel() {
445
533
  this.#model.bodyLabel.settings = readBodyLabel((name) => this.getAttribute(name));
@@ -626,6 +714,8 @@ export class ChikyuEarthRealistic extends HTMLElement {
626
714
  meteors: { on: this.#model.meteors.on, strength: this.#model.meteors.strength, ...this.#model.meteors.drawn },
627
715
  bodyLabel: { on: this.#model.bodyLabel.settings !== null, text: this.#model.bodyLabel.text, ...this.#model.bodyLabel.drawn },
628
716
  sky: this.#sky?.stats ?? { on: false, loaded: false, names: 0, figures: 0, picked: null, renders: 0, lang: "", stars: [] },
717
+ places: { ...(this.#placeLayer?.stats ?? { places: 0, shown: 0, labels: 0, renders: 0 }) },
718
+ cityNames: this.#cities?.stats ?? { on: false, max: 0, radius: 0, tiers: [], cities: 0, names: 0, renders: 0 },
629
719
  };
630
720
  }
631
721
  /**
@@ -842,13 +932,6 @@ export class ChikyuEarthRealistic extends HTMLElement {
842
932
  this.#set("unavailable");
843
933
  this.dispatchEvent(new CustomEvent("chikyu-unavailable", { detail: { reason } }));
844
934
  }
845
- #locate() {
846
- if (readCentre(this.getAttribute("center")) || typeof navigator === "undefined" || !navigator.geolocation)
847
- return;
848
- navigator.geolocation.getCurrentPosition((position) => {
849
- this.centre = { lon: position.coords.longitude, lat: position.coords.latitude };
850
- }, () => undefined, { timeout: 8000, maximumAge: 600000 });
851
- }
852
935
  }
853
936
  if (typeof customElements !== "undefined" && !customElements.get("chikyu-earth-realistic")) {
854
937
  customElements.define("chikyu-earth-realistic", ChikyuEarthRealistic);
@@ -9,3 +9,5 @@ export { BODY_LABEL_ATTRIBUTES, bodyLabelText, readBodyLabel, loadMichroma, setB
9
9
  export { AIR_QUALITY, AIR_THICKNESS_DEFAULT, AIR_THICKNESS_MAX, AIR_TOP, AIR_VERT, airFor, airFrag, airTop, readAirThickness, type AirSamples } from "./air.ts";
10
10
  export { AIR_NOTE } from "./air-note.ts";
11
11
  export type { SkyLabelStyle } from "../sky/style.ts";
12
+ export { CITY_NAMES_DEFAULT, CITY_NAMES_MAX, TIER_RADIUS, cityNameText, cityRank, cityTiersFor, layoutCities, nameWidth, readCityNames, type CityFrame, type CityLayoutOptions, type CityName, type CityNameTier, type NamedCity } from "../cities/geometry.ts";
13
+ export { CITY_NAMES_ATTRIBUTES, type CityNamesStyle } from "../cities/host.ts";
@@ -9,3 +9,5 @@ export { TILE_KEEP_MS, TILE_LIMIT } from "./tile-set.js";
9
9
  export { BODY_LABEL_ATTRIBUTES, bodyLabelText, readBodyLabel, loadMichroma, setBodyLabelFontUrl } from "./body-label.js";
10
10
  export { AIR_QUALITY, AIR_THICKNESS_DEFAULT, AIR_THICKNESS_MAX, AIR_TOP, AIR_VERT, airFor, airFrag, airTop, readAirThickness } from "./air.js";
11
11
  export { AIR_NOTE } from "./air-note.js";
12
+ export { CITY_NAMES_DEFAULT, CITY_NAMES_MAX, TIER_RADIUS, cityNameText, cityRank, cityTiersFor, layoutCities, nameWidth, readCityNames } from "../cities/geometry.js";
13
+ export { CITY_NAMES_ATTRIBUTES } from "../cities/host.js";
@@ -1,6 +1,7 @@
1
1
  export { createSatellites, type SatellitesOptions } from "./track.ts";
2
2
  export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.ts";
3
3
  export type { ElementSet, RefusedElementSet, SatelliteInfo, SatelliteRef, Satellites } from "./types.ts";
4
+ export { SHORT_NAMES } from "./names.ts";
4
5
  export { CATALOGUE, SATELLITE_GROUPS, catalogueEntry, findInCatalogue, type CatalogueEntry, type OrbitKind, type SatelliteGroupInfo } from "./catalogue.ts";
5
6
  export { ElementSourceError, fetchElements, forgetElements, parseElements, type ElementFormat, type ElementSource, type FetchElementsOptions, type ParsedElements } from "./source.ts";
6
7
  export { missionElements, missionOf, missionPosition, missions, type HubbleVisit, type Mission, type MissionFile, type MissionPosition, type Orbiter } from "./missions.ts";
@@ -1,6 +1,7 @@
1
1
  // The satellites' pure parts: orbital elements in, positions out (SGP4 by satellite.js, an optional peer). They import on a server. The space view takes a group with `setSatellites`.
2
2
  export { createSatellites } from "./track.js";
3
3
  export { DEFAULT_DIM_AFTER_DAYS, DEFAULT_MAX_AGE_DAYS, MAX_SATELLITE_SPEED } from "./limits.js";
4
+ export { SHORT_NAMES } from "./names.js";
4
5
  export { CATALOGUE, SATELLITE_GROUPS, catalogueEntry, findInCatalogue } from "./catalogue.js";
5
6
  export { ElementSourceError, fetchElements, forgetElements, parseElements } from "./source.js";
6
7
  export { missionElements, missionOf, missionPosition, missions } from "./missions.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The short names of the satellites the package knows by name, by NORAD number, in English and in Japanese: the ISS, Tiangong and Hubble.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import { SHORT_NAMES } from "@johnmorrisdotca/chikyu-earth/satellites";
7
+ *
8
+ * console.log(SHORT_NAMES[48274]?.ja);
9
+ * ```
10
+ */
11
+ export declare const SHORT_NAMES: Readonly<Record<number, {
12
+ en: string;
13
+ ja: string;
14
+ }>>;
@@ -0,0 +1,16 @@
1
+ // The short names of the large satellites the package knows, in each language, for a label or a list: any other satellite is shown under the name in its elements. Pure.
2
+ /**
3
+ * The short names of the satellites the package knows by name, by NORAD number, in English and in Japanese: the ISS, Tiangong and Hubble.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { SHORT_NAMES } from "@johnmorrisdotca/chikyu-earth/satellites";
8
+ *
9
+ * console.log(SHORT_NAMES[48274]?.ja);
10
+ * ```
11
+ */
12
+ export const SHORT_NAMES = {
13
+ 25544: { en: "ISS", ja: "ISS" },
14
+ 48274: { en: "Tiangong", ja: "天宮" },
15
+ 20580: { en: "Hubble", ja: "ハッブル" },
16
+ };
@@ -25,3 +25,51 @@ export declare function coverBody(position: readonly number[], camera: readonly
25
25
  * @returns True where the ray meets a body.
26
26
  */
27
27
  export declare function covers(bodies: readonly CoverBody[], x: number, y: number, z: number): boolean;
28
+ /** What `pathOutside` draws with: a canvas's context. */
29
+ export interface Path {
30
+ moveTo(x: number, y: number): void;
31
+ lineTo(x: number, y: number): void;
32
+ }
33
+ /**
34
+ * Adds a segment to the path, less the part of it a body covers. What a body covers of the picture is convex (a disc, or an ellipse towards the edges of a wide view), so a line meets it once at most: the segment is walked in short steps, and where one step
35
+ * is covered and the next is not, the edge between them is found by halving. Nothing is made; the path takes the pieces.
36
+ *
37
+ * @param path - The path to add the pieces to (a canvas's context).
38
+ * @param x0 - The segment's start, x.
39
+ * @param y0 - The start, y.
40
+ * @param x1 - The end, x.
41
+ * @param y1 - The end, y.
42
+ * @param covered - Whether a body covers a point of the picture, or `undefined` where none does.
43
+ * @param inset - How far, in pixels, a piece is held back from the edge it is cut at: half the line's width and its round end, so the stroke stays off the body.
44
+ */
45
+ export declare function pathOutside(path: Path, x0: number, y0: number, x1: number, y1: number, covered: ((x: number, y: number) => boolean) | undefined, inset?: number): void;
46
+ /**
47
+ * Whether any part of a label is on a body: the corners and the middle of the name's edges, the star's own point and eight points of the ring round it, and the end of its leader.
48
+ *
49
+ * @param covered - Whether a body covers a point of the picture.
50
+ * @param left - The name's box, from the picture's top left.
51
+ * @param top - The box's top.
52
+ * @param right - The box's right.
53
+ * @param bottom - The box's bottom.
54
+ * @param label - The star's label, for its point, ring and leader.
55
+ * @returns True where some part is over a body.
56
+ */
57
+ export declare function touches(covered: (x: number, y: number) => boolean, left: number, top: number, right: number, bottom: number, label: {
58
+ x: number;
59
+ y: number;
60
+ ring: number;
61
+ leader?: boolean;
62
+ leaderX1: number;
63
+ leaderY1: number;
64
+ }): boolean;
65
+ /**
66
+ * Whether any part of a box is on a body: its corners and the middle of its edges.
67
+ *
68
+ * @param covered - Whether a body covers a point of the picture.
69
+ * @param left - The box's left.
70
+ * @param top - The top.
71
+ * @param right - The right.
72
+ * @param bottom - The bottom.
73
+ * @returns True where some part is over a body.
74
+ */
75
+ export declare function boxCovered(covered: (x: number, y: number) => boolean, left: number, top: number, right: number, bottom: number): boolean;
package/dist/sky/cover.js CHANGED
@@ -30,3 +30,103 @@ export function covers(bodies, x, y, z) {
30
30
  return true;
31
31
  return false;
32
32
  }
33
+ /** How far apart, in pixels, a line is tested for the cover: a line that dips under the edge of a body for less is not seen to (at the edge of a large body, a chord of this length is less than a pixel deep). */
34
+ const CLIP_STEP = 6;
35
+ /** How many times the edge of a body is halved to find where a line meets it: 6 narrows a step to a tenth of a pixel. */
36
+ const CLIP_HALVINGS = 6;
37
+ /**
38
+ * Adds a segment to the path, less the part of it a body covers. What a body covers of the picture is convex (a disc, or an ellipse towards the edges of a wide view), so a line meets it once at most: the segment is walked in short steps, and where one step
39
+ * is covered and the next is not, the edge between them is found by halving. Nothing is made; the path takes the pieces.
40
+ *
41
+ * @param path - The path to add the pieces to (a canvas's context).
42
+ * @param x0 - The segment's start, x.
43
+ * @param y0 - The start, y.
44
+ * @param x1 - The end, x.
45
+ * @param y1 - The end, y.
46
+ * @param covered - Whether a body covers a point of the picture, or `undefined` where none does.
47
+ * @param inset - How far, in pixels, a piece is held back from the edge it is cut at: half the line's width and its round end, so the stroke stays off the body.
48
+ */
49
+ export function pathOutside(path, x0, y0, x1, y1, covered, inset = 0) {
50
+ if (!covered) {
51
+ path.moveTo(x0, y0);
52
+ path.lineTo(x1, y1);
53
+ return;
54
+ }
55
+ const dx = x1 - x0;
56
+ const dy = y1 - y0;
57
+ const length = Math.hypot(dx, dy);
58
+ const steps = Math.max(1, Math.ceil(length / CLIP_STEP));
59
+ const back = length > 0 ? inset / length : 0;
60
+ let hidden = covered(x0, y0);
61
+ /** Where the piece being walked began along the segment (0 to 1), or -1 while it is under a body. */
62
+ let from = hidden ? -1 : 0;
63
+ let before = 0;
64
+ for (let i = 1; i <= steps; i += 1) {
65
+ const t = i / steps;
66
+ const now = covered(x0 + dx * t, y0 + dy * t);
67
+ if (now !== hidden) {
68
+ // the edge lies between `before` and `t`: `seen` is the side outside the body
69
+ let seen = hidden ? t : before;
70
+ let under = hidden ? before : t;
71
+ for (let h = 0; h < CLIP_HALVINGS; h += 1) {
72
+ const mid = (seen + under) / 2;
73
+ if (covered(x0 + dx * mid, y0 + dy * mid))
74
+ under = mid;
75
+ else
76
+ seen = mid;
77
+ }
78
+ if (now) {
79
+ const end = Math.max(from, seen - back);
80
+ path.moveTo(x0 + dx * from, y0 + dy * from);
81
+ path.lineTo(x0 + dx * end, y0 + dy * end);
82
+ from = -1;
83
+ }
84
+ else
85
+ from = Math.min(1, seen + back);
86
+ hidden = now;
87
+ }
88
+ before = t;
89
+ }
90
+ if (!hidden && from <= 1) {
91
+ path.moveTo(x0 + dx * from, y0 + dy * from);
92
+ path.lineTo(x1, y1);
93
+ }
94
+ }
95
+ /**
96
+ * Whether any part of a label is on a body: the corners and the middle of the name's edges, the star's own point and eight points of the ring round it, and the end of its leader.
97
+ *
98
+ * @param covered - Whether a body covers a point of the picture.
99
+ * @param left - The name's box, from the picture's top left.
100
+ * @param top - The box's top.
101
+ * @param right - The box's right.
102
+ * @param bottom - The box's bottom.
103
+ * @param label - The star's label, for its point, ring and leader.
104
+ * @returns True where some part is over a body.
105
+ */
106
+ export function touches(covered, left, top, right, bottom, label) {
107
+ if (boxCovered(covered, left, top, right, bottom))
108
+ return true;
109
+ if (covered(label.x, label.y))
110
+ return true;
111
+ // the ring is drawn a pixel wide and round: eight points of it, a pixel out
112
+ const ring = label.ring + 1;
113
+ const diagonal = ring * 0.7071;
114
+ if (label.ring > 0 && (covered(label.x - ring, label.y) || covered(label.x + ring, label.y) || covered(label.x, label.y - ring) || covered(label.x, label.y + ring) || covered(label.x - diagonal, label.y - diagonal) || covered(label.x + diagonal, label.y - diagonal) || covered(label.x - diagonal, label.y + diagonal) || covered(label.x + diagonal, label.y + diagonal)))
115
+ return true;
116
+ return Boolean(label.leader) && covered(label.leaderX1, label.leaderY1);
117
+ }
118
+ /**
119
+ * Whether any part of a box is on a body: its corners and the middle of its edges.
120
+ *
121
+ * @param covered - Whether a body covers a point of the picture.
122
+ * @param left - The box's left.
123
+ * @param top - The top.
124
+ * @param right - The right.
125
+ * @param bottom - The bottom.
126
+ * @returns True where some part is over a body.
127
+ */
128
+ export function boxCovered(covered, left, top, right, bottom) {
129
+ const middle = (left + right) / 2;
130
+ const centre = (top + bottom) / 2;
131
+ return covered(left, top) || covered(middle, top) || covered(right, top) || covered(left, bottom) || covered(middle, bottom) || covered(right, bottom) || covered(left, centre) || covered(right, centre);
132
+ }
package/dist/sky/host.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { canvasRatio } from "../markers/project.js";
2
+ import { boxCovered, pathOutside, touches } from "./cover.js";
2
3
  /** The styles of the layer, for an element to add to its own (`#sk-canvas`, `#sk-names` and the labels in its shadow root). */
3
4
  export const SKY_STYLE = "#sk-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}#sk-names{position:absolute;inset:0;overflow:hidden;pointer-events:none}" +
4
5
  ".sk-name,.sk-figure,.sk-designation{position:absolute;left:0;top:0;margin:0;white-space:nowrap;pointer-events:none;font-family:var(--hoshi-label-font,Michroma,system-ui,sans-serif);font-size:calc(var(--hoshi-label-size,11) * 1px);font-weight:var(--hoshi-label-weight,400);color:var(--hoshi-label-colour,#e9f1ff);letter-spacing:calc(var(--hoshi-label-letter-spacing,.14) * 1em);font-variant:var(--hoshi-label-case-variant,small-caps);text-transform:var(--hoshi-label-case-transform,none);text-shadow:0 0 calc(var(--hoshi-label-halo-width,3) * 1px) var(--hoshi-label-halo,#0a1230)}" +
@@ -62,7 +63,8 @@ export function createSkyHost(options) {
62
63
  if (!lines || event.pointerType === "touch")
63
64
  return;
64
65
  const at = place(event);
65
- if (lines.point(at.x, at.y))
66
+ // the lines on the Earth are not drawn, so none is lit there
67
+ if ((covered?.(at.x, at.y) ? lines.point() : lines.point(at.x, at.y)))
66
68
  drawLines();
67
69
  });
68
70
  host.addEventListener("pointerleave", (event) => {
@@ -75,7 +77,7 @@ export function createSkyHost(options) {
75
77
  if (!lines || event.pointerType !== "touch")
76
78
  return;
77
79
  const at = place(event);
78
- if (lines.point(at.x, at.y))
80
+ if ((covered?.(at.x, at.y) ? lines.point() : lines.point(at.x, at.y)))
79
81
  drawLines();
80
82
  });
81
83
  };
@@ -91,6 +93,34 @@ export function createSkyHost(options) {
91
93
  context?.setTransform(ratio, 0, 0, ratio, 0, 0);
92
94
  return context;
93
95
  };
96
+ const spot = { x: 0, y: 0 };
97
+ /**
98
+ * Where the picked figure's name goes: where hoshi-stars put it, or, where a body covers that, the nearest place round it that is clear of every body and inside the picture. Answers `null` where there is none. The name's box is set from its middle, the way it is drawn (up from its point, centred).
99
+ */
100
+ function placeFigureName(x, y, frame) {
101
+ if (!covered) {
102
+ spot.x = x;
103
+ spot.y = y;
104
+ return spot;
105
+ }
106
+ const box = typeof figureName.getBoundingClientRect === "function" ? figureName.getBoundingClientRect() : undefined;
107
+ const w = box && box.width > 0 ? box.width : 80;
108
+ const h = box && box.height > 0 ? box.height : 14;
109
+ let best = Number.POSITIVE_INFINITY;
110
+ for (const down of [0, -1, 1, -2, 2, -3, 3, -4, 4]) {
111
+ for (const across of [0, -0.5, 0.5, -1, 1, -1.5, 1.5]) {
112
+ const cx = Math.max(w / 2 + 2, Math.min(frame.width - w / 2 - 2, x + across * w));
113
+ const cy = Math.max(h + 2, Math.min(frame.height - 2, y + down * h * 1.4));
114
+ const away = Math.abs(cx - x) + Math.abs(cy - y);
115
+ if (away < best && !boxCovered(covered, cx - w / 2, cy - h, cx + w / 2, cy)) {
116
+ best = away;
117
+ spot.x = cx;
118
+ spot.y = cy;
119
+ }
120
+ }
121
+ }
122
+ return best === Number.POSITIVE_INFINITY ? null : spot;
123
+ }
94
124
  /** The lines and the rings, and the names: drawn again from what `update` laid out. */
95
125
  function drawLines() {
96
126
  const frame = last;
@@ -111,10 +141,8 @@ export function createSkyHost(options) {
111
141
  continue;
112
142
  context.globalAlpha = opacity;
113
143
  context.beginPath();
114
- for (let i = figure.start; i < figure.end; i += 1) {
115
- context.moveTo(lines.segments[i * 4], lines.segments[i * 4 + 1]);
116
- context.lineTo(lines.segments[i * 4 + 2], lines.segments[i * 4 + 3]);
117
- }
144
+ for (let i = figure.start; i < figure.end; i += 1)
145
+ pathOutside(context, lines.segments[i * 4], lines.segments[i * 4 + 1], lines.segments[i * 4 + 2], lines.segments[i * 4 + 3], covered, 0.75);
118
146
  context.stroke();
119
147
  }
120
148
  context.globalAlpha = 1;
@@ -148,7 +176,11 @@ export function createSkyHost(options) {
148
176
  figureName.hidden = false;
149
177
  if (figureName.textContent !== name.text)
150
178
  figureName.textContent = name.text;
151
- figureName.style.transform = `translate(${Math.round(name.x)}px,${Math.round(name.y)}px) translate(-50%,-100%)`;
179
+ const at = placeFigureName(name.x, name.y, frame);
180
+ if (at)
181
+ figureName.style.transform = `translate(${Math.round(at.x)}px,${Math.round(at.y)}px) translate(-50%,-100%)`;
182
+ else
183
+ figureName.hidden = true;
152
184
  }
153
185
  else
154
186
  figureName.hidden = true;
@@ -217,18 +249,16 @@ export function createSkyHost(options) {
217
249
  continue;
218
250
  }
219
251
  const rect = name.getBoundingClientRect();
220
- // a name whose whole top edge is over a body (the Earth, the Moon, the Sun) lies on it: hoshi-stars tests the star's point only, so a name set below a star at the Earth's edge can be left entirely on the Earth, and is left out
252
+ // no part of a name or of its ring is drawn over a body (the Earth, the Moon, the Sun): the sky is behind them. hoshi-stars tests the star's own point only, so a name set beside a star at the Earth's edge can run onto it, and the label (name, ring and all) is left out
221
253
  const own = covered ? root.host.getBoundingClientRect() : undefined;
222
- if (covered && own) {
223
- const top = rect.top - own.top;
224
- const left = rect.left - own.left;
225
- const right = rect.right - own.left;
226
- if (covered(left, top) && covered((left + right) / 2, top) && covered(right, top)) {
227
- name.hidden = true;
228
- designations[i].hidden = true;
229
- culled.push(true);
230
- continue;
231
- }
254
+ // the catalogue letter set under the name is part of the label
255
+ const under = designations[i].hidden || typeof designations[i].getBoundingClientRect !== "function" ? undefined : designations[i].getBoundingClientRect();
256
+ const bottom = under ? Math.max(rect.bottom, under.bottom) : rect.bottom;
257
+ if (covered && own && touches(covered, rect.left - own.left, rect.top - own.top, rect.right - own.left, bottom - own.top, names.labels[i])) {
258
+ name.hidden = true;
259
+ designations[i].hidden = true;
260
+ culled.push(true);
261
+ continue;
232
262
  }
233
263
  const over = kept.some((one) => rect.left < one.r && rect.right > one.l && rect.top < one.b && rect.bottom > one.t);
234
264
  if (over) {