@johnmorrisdotca/chikyu-earth 0.33.2 → 0.34.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.
@@ -3,6 +3,10 @@ import { adoptStyles } from "../adopt.js";
3
3
  import { airFor, readAirThickness } from "../realistic/air.js";
4
4
  import { BODY_LABEL_ATTRIBUTES, bodyLabelText, loadMichroma, readBodyLabel } from "../realistic/body-label.js";
5
5
  import { createSkyHost, SKY_ATTRIBUTES, SKY_STYLE } from "../sky/host.js";
6
+ import { cleanPlaces, readPlaces } from "../markers/places.js";
7
+ import { createPlaceLayer, PLACE_STYLE, readPlaceLook } from "../markers/place-layer.js";
8
+ import { SHORT_NAMES } from "../satellites/names.js";
9
+ import { CITY_NAMES_ATTRIBUTES, CITY_NAMES_STYLE, createCityHost } from "../cities/host.js";
6
10
  import { createGate, frameCap } from "../realistic/gate.js";
7
11
  import { setThreeLoader, takeRenderer } from "../realistic/shared.js";
8
12
  import { NOTES_STYLE, setAirNote } from "../realistic/air-note.js";
@@ -17,6 +21,7 @@ import { placeAround, placeMoon, placeSun, RADIUS } from "./scale.js";
17
21
  import { BODY_NAMES, createSpaceItem, DEFAULT_EARTH_SIZE, newSpaceModel } from "./scene.js";
18
22
  export { BODY_NAMES };
19
23
  let painter;
24
+ let satellitePainter;
20
25
  /**
21
26
  * Change how the Sun and the planets are drawn (before the first element connects): the space view keeps their places, sizes, light, names and orbits and asks
22
27
  * the painter only for what to draw at each place (see `BodyPainter`). Left alone, they are plain spheres in the right colours.
@@ -34,6 +39,22 @@ let painter;
34
39
  export function setBodyPainter(next) {
35
40
  painter = next;
36
41
  }
42
+ /**
43
+ * Where the 3D models of large satellites come from if the page has any: the package ships none. With a painter set, a satellite followed (`ride(ref, { view: "follow" })`) that the painter has a model for is drawn as that model, in the middle
44
+ * of the picture at a size that reads, pointed the way it flies, lit by the Sun; a satellite it has none for stays a dot. See `SatellitePainter`.
45
+ *
46
+ * @param next - The painter, or `undefined` for none.
47
+ *
48
+ * @example
49
+ * ```ts no-run
50
+ * import { setSatellitePainter } from "@johnmorrisdotca/chikyu-earth/space/element";
51
+ *
52
+ * setSatellitePainter({ has: (norad) => norad === 25544, make: async () => null });
53
+ * ```
54
+ */
55
+ export function setSatellitePainter(next) {
56
+ satellitePainter = next;
57
+ }
37
58
  /** Mean radii in kilometres (IAU), for what a click tells. */
38
59
  const RADIUS_KM = { Sun: 695_700, Mercury: 2439.7, Venus: 6051.8, Earth: 6371, Moon: 1737.4, Mars: 3389.5, Jupiter: 69_911, Saturn: 58_232, Uranus: 25_362, Neptune: 24_622, Pluto: 1188.3 };
39
60
  export { setThreeLoader };
@@ -77,7 +98,7 @@ const readTime = (value) => {
77
98
  const ms = Date.parse(value);
78
99
  return Number.isFinite(ms) ? ms : "now";
79
100
  };
80
- const 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}.sp-sat{position:absolute;left:0;top:0;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-sat[hidden]{display:none}${SKY_STYLE}${METEOR_NOTE_STYLE}${NOTES_STYLE}`;
101
+ const 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}.sp-sat{position:absolute;left:0;top:0;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-sat[hidden]{display:none}${PLACE_STYLE}${SKY_STYLE}${CITY_NAMES_STYLE}${METEOR_NOTE_STYLE}${NOTES_STYLE}`;
81
102
  /**
82
103
  * The `<chikyu-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`, `time` (`now` or an ISO date), `speed` (1 is real time, 0 holds, 86400 is a day a second, negative runs backwards), `scale` (`compressed` or `true`), `labels` and `orbits` (`off` hides them); positions are computed in the browser by astronomy-engine, an optional peer dependency. It draws only when something changes, and nothing while it is out of sight.
83
104
  *
@@ -103,7 +124,7 @@ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:h
103
124
  * ```
104
125
  */
105
126
  export class ChikyuSpace extends HTMLElement {
106
- static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, "air-thickness", "air-label", "lang"];
127
+ static observedAttributes = ["cloud-drift", "camera", "earth-size", "earth-x", "earth-y", "center", "time", "speed", "scale", "labels", "orbits", "bodies", "light", "meteors", "meteors-label", "meteors-strength", ...BODY_LABEL_ATTRIBUTES, ...SKY_ATTRIBUTES, ...CITY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look"];
107
128
  #model = newSpaceModel();
108
129
  #mode = "now";
109
130
  #speed = 1;
@@ -114,6 +135,12 @@ export class ChikyuSpace extends HTMLElement {
114
135
  /** The names of the stars and the constellation lines (`star-names`, `constellation-lines`), and the look of the names. */
115
136
  #sky;
116
137
  #skyStyle = {};
138
+ /** The names of cities on the Earth (`city-names`), and the look of the names. */
139
+ #cities;
140
+ #citiesStyle = {};
141
+ #satNames = {};
142
+ /** The ringed satellites of the last draw (`labelSatellites`), laid out with the places. */
143
+ #marks = [];
117
144
  #airNote;
118
145
  #gate;
119
146
  #taken;
@@ -133,6 +160,9 @@ export class ChikyuSpace extends HTMLElement {
133
160
  #tiers = {};
134
161
  #hands;
135
162
  #ridden = {};
163
+ #placeLayer;
164
+ #placeList = [];
165
+ #nameBoxes = new Map();
136
166
  /** The controller behind the element's own hands (`set`, `fit`, `state`), while it is in a page. */
137
167
  get controller() {
138
168
  return this.#hands?.controller;
@@ -157,7 +187,7 @@ export class ChikyuSpace extends HTMLElement {
157
187
  if (!this.hasAttribute("aria-label"))
158
188
  this.setAttribute("aria-label", "The Earth, the Moon, the Sun and the planets in their places for the date shown");
159
189
  const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
160
- root.innerHTML = `<div id="stage"></div><div id="labels" aria-hidden="true"></div><div id="notes"><p id="air-note" hidden></p><p id="meteor-note" hidden></p></div>`;
190
+ root.innerHTML = `<div id="stage"></div><div id="places"></div><div id="labels" aria-hidden="true"></div><div id="notes"><p id="air-note" hidden></p><p id="meteor-note" hidden></p></div>`;
161
191
  adoptStyles(root, STYLE, this.nonce);
162
192
  this.#stage = root.getElementById("stage");
163
193
  this.#labelBox = root.getElementById("labels");
@@ -171,6 +201,17 @@ export class ChikyuSpace extends HTMLElement {
171
201
  loadFont: loadMichroma,
172
202
  });
173
203
  this.#sky.setStyle(this.#skyStyle);
204
+ this.#placeLayer = createPlaceLayer(root.getElementById("places"));
205
+ this.#placeList = readPlaces(this.getAttribute("places"));
206
+ this.#placeLayer.set(this.#placeList);
207
+ this.#placeLayer.look = readPlaceLook(this.getAttribute("places-look"));
208
+ this.#cities = createCityHost({
209
+ root,
210
+ attribute: (name) => this.getAttribute(name),
211
+ language: () => ((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en"),
212
+ onError: (error) => this.dispatchEvent(new CustomEvent("chikyu-city-names-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
213
+ });
214
+ this.#cities.setStyle(this.#citiesStyle);
174
215
  this.#model.airThickness = readAirThickness(this.getAttribute("air-thickness"));
175
216
  this.#applyBodyLabel();
176
217
  setAirNote(this.#airNote, this, this.#model.airThickness);
@@ -202,12 +243,16 @@ export class ChikyuSpace extends HTMLElement {
202
243
  },
203
244
  onLabels: (places) => this.#placeLabels(places),
204
245
  onSky: (sky) => this.#sky?.frame(sky),
246
+ onPlaces: (view) => this.#drawPlaces(view),
247
+ onCities: (frame) => this.#cities?.frame(frame),
205
248
  onLabelError: (error) => this.dispatchEvent(new CustomEvent("chikyu-body-label-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
249
+ onSatelliteMarks: (marks) => this.#showMarks(marks),
206
250
  onSelected: (place) => this.#placeChosen(place),
207
251
  onMoving: () => this.#gate?.request(),
208
252
  onRideLost: () => this.#rideLost(),
209
253
  onSatellitesError: (error) => this.dispatchEvent(new CustomEvent("chikyu-satellites-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
210
254
  ...(painter ? { painter } : {}),
255
+ satellitePainter: () => satellitePainter,
211
256
  onPainterError: (error) => this.dispatchEvent(new CustomEvent("chikyu-bodies-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
212
257
  });
213
258
  this.#view = taken.renderer.view(this.#stage, item, { still: null });
@@ -242,6 +287,10 @@ export class ChikyuSpace extends HTMLElement {
242
287
  this.#taken = undefined;
243
288
  this.#sky?.dispose();
244
289
  this.#sky = undefined;
290
+ this.#placeLayer?.dispose();
291
+ this.#placeLayer = undefined;
292
+ this.#cities?.dispose();
293
+ this.#cities = undefined;
245
294
  }
246
295
  attributeChangedCallback(name, _old, value) {
247
296
  if (name === "center")
@@ -287,12 +336,24 @@ export class ChikyuSpace extends HTMLElement {
287
336
  if (name === "lang") {
288
337
  this.#applyBodyLabel();
289
338
  this.#sky?.refresh();
339
+ this.#cities?.refresh();
290
340
  }
291
341
  }
292
342
  else if (BODY_LABEL_ATTRIBUTES.includes(name))
293
343
  this.#applyBodyLabel();
294
344
  else if (SKY_ATTRIBUTES.includes(name))
295
345
  this.#sky?.refresh();
346
+ else if (name === "places") {
347
+ this.#placeList = readPlaces(value);
348
+ this.#placeLayer?.set(this.#placeList);
349
+ this.#gate?.request();
350
+ }
351
+ else if (name === "places-look" && this.#placeLayer) {
352
+ this.#placeLayer.look = readPlaceLook(value);
353
+ this.#gate?.request();
354
+ }
355
+ else if (CITY_NAMES_ATTRIBUTES.includes(name))
356
+ this.#cities?.refresh();
296
357
  if (name === "air-thickness" || name === "air-label" || name === "lang")
297
358
  setAirNote(this.#airNote, this, this.#model.airThickness);
298
359
  }
@@ -372,6 +433,64 @@ export class ChikyuSpace extends HTMLElement {
372
433
  this.#skyStyle = { ...value };
373
434
  this.#sky?.setStyle(this.#skyStyle);
374
435
  }
436
+ /**
437
+ * 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`
438
+ * (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
439
+ * one another or the bodies' names; 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
440
+ * the attribute; at most `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.
441
+ */
442
+ get places() {
443
+ return this.#placeList.map((place) => ({ ...place }));
444
+ }
445
+ set places(value) {
446
+ const clean = cleanPlaces(value);
447
+ if (clean.length === 0)
448
+ this.removeAttribute("places");
449
+ else
450
+ this.setAttribute("places", JSON.stringify(clean));
451
+ }
452
+ /** 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). */
453
+ get placesLook() {
454
+ return this.#placeLayer?.look ?? readPlaceLook(this.getAttribute("places-look"));
455
+ }
456
+ set placesLook(value) {
457
+ this.setAttribute("places-look", value);
458
+ }
459
+ /** Lays the places on the picture just drawn, clear of the bodies' names shown beside it. */
460
+ #drawPlaces(view) {
461
+ const layer = this.#placeLayer;
462
+ if (!layer || (this.#placeList.length === 0 && this.#marks.length === 0 && layer.stats.shown === 0 && layer.stats.rings === 0))
463
+ return;
464
+ const taken = [];
465
+ if (this.#model.labels && this.#places) {
466
+ for (const name of BODY_NAMES) {
467
+ const at = this.#places[name];
468
+ const label = this.#pool.get(name);
469
+ if (!at || !label || label.hidden)
470
+ continue;
471
+ const text = label.textContent ?? "";
472
+ let box = this.#nameBoxes.get(text);
473
+ if (!box) {
474
+ const rect = label.getBoundingClientRect();
475
+ box = { width: Math.ceil(rect.width), height: Math.ceil(rect.height) };
476
+ if (box.width > 0)
477
+ this.#nameBoxes.set(text, box);
478
+ }
479
+ taken.push({ left: at.x + Math.max(4, Math.min(at.r, 40)), top: at.y - 8, ...box });
480
+ }
481
+ }
482
+ layer.frame(view, taken, this.#marks);
483
+ }
484
+ /**
485
+ * 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.
486
+ */
487
+ get cityNamesStyle() {
488
+ return { ...this.#citiesStyle };
489
+ }
490
+ set cityNamesStyle(value) {
491
+ this.#citiesStyle = { ...value };
492
+ this.#cities?.setStyle(this.#citiesStyle);
493
+ }
375
494
  /** Puts the name's settings and text right from the attributes (`body-label` and its family, `lang`). */
376
495
  #applyBodyLabel() {
377
496
  this.#model.bodyLabel.settings = readBodyLabel((name) => this.getAttribute(name));
@@ -628,6 +747,37 @@ export class ChikyuSpace extends HTMLElement {
628
747
  }
629
748
  }
630
749
  }
750
+ /**
751
+ * The satellites the page has a model for (`setSatellitePainter`) in the groups now set, each with its name in the page's language: the large satellites that can be followed as a model. Empty with no painter.
752
+ */
753
+ largeSatellites() {
754
+ const out = [];
755
+ if (!satellitePainter)
756
+ return out;
757
+ for (const [group, state] of this.#model.satellites.groups) {
758
+ state.satellites.sets.forEach((set, index) => {
759
+ if (satellitePainter.has(set.NORAD_CAT_ID))
760
+ out.push({ ref: { group, index }, noradId: set.NORAD_CAT_ID, name: this.#satelliteName({ group, index }) });
761
+ });
762
+ }
763
+ return out;
764
+ }
765
+ /**
766
+ * Follow the next (or, with a negative `step`, the previous) of the large satellites in `largeSatellites()`, going round: the first when none is followed yet. The followed satellite stays in the middle of the picture, as a model where the page has one,
767
+ * with the Earth turning and sliding beneath. Returns the satellite now followed, or `null` when there is none to follow.
768
+ *
769
+ * @param step - How many places to hop: 1 (the default) is the next.
770
+ */
771
+ followNext(step = 1) {
772
+ const list = this.largeSatellites();
773
+ if (list.length === 0)
774
+ return null;
775
+ const ride = this.#model.ride;
776
+ const current = ride && typeof ride.target !== "string" ? list.findIndex((one) => one.ref.group === ride.target.group && one.ref.index === ride.target.index) : -1;
777
+ const next = list[(((current < 0 ? (step > 0 ? -1 : 0) : current) + step) % list.length + list.length) % list.length];
778
+ this.ride(next.ref, { view: "follow" });
779
+ return next;
780
+ }
631
781
  /** What the camera is riding along with now, or null. */
632
782
  get riding() {
633
783
  const ride = this.#model.ride;
@@ -696,6 +846,69 @@ export class ChikyuSpace extends HTMLElement {
696
846
  const chosen = this.#model.satellites.selected;
697
847
  return chosen ? { ...chosen } : null;
698
848
  }
849
+ /**
850
+ * Ring and name every satellite of a group (or stop): a ring round each and its name beside it, in the page's language (the ISS, Tiangong and Hubble by their short names, the rest as their elements name them, or as `satelliteNames` says), never over another name, a place's or a ring's.
851
+ * Names and rings are drawn with the places, only for satellites that are in the picture and not behind the Earth, and nothing is drawn at rest. `chikyu-satellite-visibility` is sent with `detail: { ref, visible }` when a labelled satellite comes into view or goes out of it (not at every frame).
852
+ * At most 80 satellites are ringed, over all the groups. A group that is not set, or is not shown, has none.
853
+ *
854
+ * @param group - The group's name, as given to `setSatellites`.
855
+ * @param on - `true` to ring and name its members (the default), `false` to stop.
856
+ */
857
+ labelSatellites(group, on = true) {
858
+ if (on)
859
+ this.#model.satellites.marked.add(group);
860
+ else
861
+ this.#model.satellites.marked.delete(group);
862
+ this.#gate?.request();
863
+ }
864
+ /** The groups whose satellites are ringed and named now (`labelSatellites`). */
865
+ get labelledSatellites() {
866
+ return [...this.#model.satellites.marked];
867
+ }
868
+ /**
869
+ * The names written beside the ringed satellites, by NORAD number, for a page in another language or with names of its own (`{ 25544: "Space Station" }`). One left out keeps its short name (the ISS, Tiangong and Hubble) or the name in its elements.
870
+ */
871
+ get satelliteNames() {
872
+ return { ...this.#satNames };
873
+ }
874
+ set satelliteNames(value) {
875
+ this.#satNames = { ...value };
876
+ this.#gate?.request();
877
+ }
878
+ /**
879
+ * Where a satellite is on the screen as of the last draw: `{ x, y, visible, heightKm }` in CSS pixels from the view's top left, `visible` meaning it is inside the box and not behind the Earth. `null` when its group is not set or not shown, it cannot be
880
+ * placed (its elements are too old), or it is behind the camera. It is the picture's own camera maths and its own test for the Earth in the way, so a page that draws its own rings need not repeat either.
881
+ */
882
+ placeSatellite(ref) {
883
+ return this.#model.placeSatellite?.(ref) ?? null;
884
+ }
885
+ /** The name beside a ringed satellite: the page's own (`satelliteNames`), else the short one in the page's language, else the name in its elements. */
886
+ #satelliteName(ref) {
887
+ const info = this.satelliteInfo(ref);
888
+ if (!info)
889
+ return "";
890
+ const lang = (this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en";
891
+ return this.#satNames[info.noradId] ?? SHORT_NAMES[info.noradId]?.[lang] ?? info.name;
892
+ }
893
+ #markSeen = new Map();
894
+ /** Hands the places layer the ringed satellites of this draw, and tells the page when one comes into view or goes out of it. */
895
+ #showMarks(marks) {
896
+ this.#marks = marks.map((m) => ({ id: `${m.ref.group}:${m.ref.index}`, label: this.#satelliteName(m.ref), x: m.x, y: m.y, visible: m.visible }));
897
+ const now = new Map();
898
+ for (const m of marks) {
899
+ const key = `${m.ref.group}:${m.ref.index}`;
900
+ now.set(key, m.visible);
901
+ if (this.#markSeen.get(key) !== m.visible && (this.#markSeen.has(key) || m.visible))
902
+ this.dispatchEvent(new CustomEvent("chikyu-satellite-visibility", { detail: { ref: m.ref, visible: m.visible }, bubbles: true, composed: true }));
903
+ }
904
+ for (const [key, was] of this.#markSeen) {
905
+ if (!now.has(key) && was) {
906
+ const [group, index] = key.split(":");
907
+ this.dispatchEvent(new CustomEvent("chikyu-satellite-visibility", { detail: { ref: { group: group, index: Number(index) }, visible: false }, bubbles: true, composed: true }));
908
+ }
909
+ }
910
+ this.#markSeen = now;
911
+ }
699
912
  /** Facts about one satellite at the moment shown (name, number, element age, height, speed, period); undefined if it cannot be placed then. */
700
913
  satelliteInfo(ref) {
701
914
  return this.#model.satellites.groups.get(ref.group)?.satellites.info(ref.index, this.#model.time);
@@ -766,6 +979,9 @@ export class ChikyuSpace extends HTMLElement {
766
979
  meteors: { on: this.#model.meteors.on, strength: this.#model.meteors.strength, ...this.#model.meteors.drawn },
767
980
  bodyLabel: { on: this.#model.bodyLabel.settings !== null, text: this.#model.bodyLabel.text, ...this.#model.bodyLabel.drawn },
768
981
  sky: this.#sky?.stats ?? { on: false, loaded: false, names: 0, figures: 0, picked: null, renders: 0, lang: "", stars: [] },
982
+ followModel: this.#model.followModel,
983
+ places: { ...(this.#placeLayer?.stats ?? { places: 0, shown: 0, labels: 0, renders: 0, rings: 0, satelliteNames: 0 }) },
984
+ cityNames: this.#cities?.stats ?? { on: false, max: 0, radius: 0, tiers: [], cities: 0, names: 0, renders: 0 },
769
985
  };
770
986
  }
771
987
  #satelliteStats() {
@@ -1,4 +1,6 @@
1
1
  export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, orbitPath, PLANETS, type Frame, type PlanetName, type Vec3 } from "./ephemeris.ts";
2
2
  export { compress, MOON_COMPRESSED, placeAround, placeMoon, placeSun, RADIUS, SUN_COMPRESSED, truePosition, type ScaleMode } from "./scale.ts";
3
- export { fitDistance, plainPainter, type BodyDrawing, type BodyMoon, type BodyPainter, type PaintContext } from "./scene.ts";
3
+ export { fitDistance, plainPainter, type BodyDrawing, type BodyMoon, type BodyPainter, type PaintContext, type SatellitePainter } from "./scene.ts";
4
4
  export { RIDE_FOV, rideFov, ridePose, rideTiltLimits, rideTurnDegrees, type RideInput, type RideLook, type RidePose } from "./ride.ts";
5
+ export type { SatelliteScreen } from "./satellite-layer.ts";
6
+ export { MODEL_RADIUS_SHARE, modelMatrix, modelRadius, satelliteAxes } from "./satellite-model.ts";
@@ -4,3 +4,4 @@ export { AU_IN_EARTH_RADII, blend, createTrack, EARTH_RADIUS_KM, frameAt, orbitP
4
4
  export { compress, MOON_COMPRESSED, placeAround, placeMoon, placeSun, RADIUS, SUN_COMPRESSED, truePosition } from "./scale.js";
5
5
  export { fitDistance, plainPainter } from "./scene.js";
6
6
  export { RIDE_FOV, rideFov, ridePose, rideTiltLimits, rideTurnDegrees } from "./ride.js";
7
+ export { MODEL_RADIUS_SHARE, modelMatrix, modelRadius, satelliteAxes } from "./satellite-model.js";
@@ -16,6 +16,8 @@ export interface SatelliteGroupState extends SatelliteStyle {
16
16
  export interface SatelliteState {
17
17
  groups: Map<string, SatelliteGroupState>;
18
18
  selected: SatelliteRef | null;
19
+ /** The groups whose members are ringed and named (`labelSatellites`): the scene tells the page where each is, at every draw. */
20
+ marked: Set<string>;
19
21
  /** Written at each draw: satellites placed, whether the clock is too fast for the groups, and the milliseconds the last update took. */
20
22
  drawn: {
21
23
  placed: number;
@@ -29,7 +31,31 @@ export interface SatelliteState {
29
31
  export declare const newSatelliteState: () => SatelliteState;
30
32
  /** The most orbits a group may draw all at once, one line each. */
31
33
  export declare const MAX_ORBIT_GROUP = 40;
34
+ /**
35
+ * Where a satellite is on the screen now: in CSS pixels in the view's box, whether it can be seen (inside the box and not behind the Earth) and how high it is.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import type { SatelliteScreen } from "@johnmorrisdotca/chikyu-earth/space";
40
+ *
41
+ * const seen = (place: SatelliteScreen | null): boolean => place !== null && place.visible;
42
+ * console.log(typeof seen);
43
+ * ```
44
+ */
45
+ export interface SatelliteScreen {
46
+ x: number;
47
+ y: number;
48
+ /** Inside the box and in front of the Earth (not hidden by it). */
49
+ visible: boolean;
50
+ /** Height above the mean Earth radius, in kilometres, at the moment drawn. */
51
+ heightKm: number;
52
+ }
32
53
  export interface SatelliteLayer {
54
+ /** Where one satellite of a shown group is on the screen as of the last update, or `null` when its group is not shown, it is not placed (its elements are too old) or it is behind the camera. */
55
+ placeOf(ref: SatelliteRef, camera: THREE.Camera, size: {
56
+ width: number;
57
+ height: number;
58
+ }): SatelliteScreen | null;
33
59
  /** Place every shown group for `model.time` and the chosen satellite exactly. */
34
60
  update(time: number, speed: number): void;
35
61
  /** The satellite nearest to a point of the view (CSS pixels) within `radius`, if one is in front of the Earth. */
@@ -1,5 +1,5 @@
1
1
  import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
2
- export const newSatelliteState = () => ({ groups: new Map(), selected: null, drawn: { placed: 0, tooFast: false, updateMs: 0, maxUpdateMs: 0, updates: 0, totalMs: 0 } });
2
+ export const newSatelliteState = () => ({ groups: new Map(), selected: null, marked: new Set(), drawn: { placed: 0, tooFast: false, updateMs: 0, maxUpdateMs: 0, updates: 0, totalMs: 0 } });
3
3
  /** The most orbits a group may draw all at once, one line each. */
4
4
  export const MAX_ORBIT_GROUP = 40;
5
5
  const ORBIT_POINTS = 120;
@@ -229,6 +229,42 @@ export function createSatelliteLayer(three, scene, state, ratio) {
229
229
  }
230
230
  return best;
231
231
  },
232
+ placeOf(ref, camera, size) {
233
+ const entry = drawn.get(ref.group);
234
+ const group = state.groups.get(ref.group);
235
+ if (!entry || !group || !entry.points.visible || !Number.isInteger(ref.index) || ref.index < 0 || ref.index >= group.satellites.count || !group.satellites.visible(ref.index))
236
+ return null;
237
+ const p = entry.positions;
238
+ const i = ref.index * 3;
239
+ world.set(p[i], p[i + 1], p[i + 2]).applyMatrix4(scene.matrixWorld);
240
+ const heightKm = (Math.hypot(p[i], p[i + 1], p[i + 2]) - 1) * 6371;
241
+ projected.copy(world).project(camera);
242
+ if (projected.z > 1 || projected.z < -1)
243
+ return null;
244
+ const x = ((projected.x + 1) / 2) * size.width;
245
+ const y = ((1 - projected.y) / 2) * size.height;
246
+ const ortho = camera.isOrthographicCamera === true;
247
+ const c = camera.position;
248
+ let hidden;
249
+ if (ortho) {
250
+ const centreDepth = view.set(0, 0, 0).applyMatrix4(camera.matrixWorldInverse).z;
251
+ view.copy(world).applyMatrix4(camera.matrixWorldInverse);
252
+ hidden = view.z < centreDepth && view.x * view.x + view.y * view.y < 0.996;
253
+ }
254
+ else {
255
+ // behind the Earth: the line from the camera to the satellite passes through the unit sphere before it gets there
256
+ const px = world.x - c.x;
257
+ const py = world.y - c.y;
258
+ const pz = world.z - c.z;
259
+ const len2 = px * px + py * py + pz * pz;
260
+ const t = Math.max(0, Math.min(1, -(c.x * px + c.y * py + c.z * pz) / len2));
261
+ const nx = c.x + px * t;
262
+ const ny = c.y + py * t;
263
+ const nz = c.z + pz * t;
264
+ hidden = nx * nx + ny * ny + nz * nz < 0.998;
265
+ }
266
+ return { x, y, visible: !hidden && x >= 0 && x <= size.width && y >= 0 && y <= size.height, heightKm };
267
+ },
232
268
  place(camera, size) {
233
269
  if (!selectedPoints.visible)
234
270
  return null;
@@ -0,0 +1,72 @@
1
+ import type { Vec3 } from "./ephemeris.ts";
2
+ /**
3
+ * How big a followed satellite's model is drawn: its radius is this share of the height of the view (0.17), so it reads at any distance the camera keeps.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { MODEL_RADIUS_SHARE } from "@johnmorrisdotca/chikyu-earth/space";
8
+ *
9
+ * console.log(MODEL_RADIUS_SHARE);
10
+ * ```
11
+ */
12
+ export declare const MODEL_RADIUS_SHARE = 0.17;
13
+ /**
14
+ * The axes of a satellite flying: `x` along the way it goes (its velocity, taken level with the ground below it), `z` straight away from the Earth's centre, and `y` to complete them (`z` cross `x`, so it points to the left of the way it goes).
15
+ * The family's convention for a model: its nose or long axis along +x, its top (the side that faces space) along +z.
16
+ *
17
+ * @param position - Where the satellite is, from the Earth's centre, in any unit.
18
+ * @param velocity - The way it is going, in any unit.
19
+ * @returns Three unit vectors, `x`, `y` and `z`, in the scene's axes; `null` when the position is the centre or the satellite does not move.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { satelliteAxes } from "@johnmorrisdotca/chikyu-earth/space";
24
+ *
25
+ * const axes = satelliteAxes([1.066, 0, 0], [0, 0, -7.66]);
26
+ * console.log(axes?.x, axes?.z);
27
+ * ```
28
+ */
29
+ export declare function satelliteAxes(position: Vec3, velocity: Vec3): {
30
+ x: Vec3;
31
+ y: Vec3;
32
+ z: Vec3;
33
+ } | null;
34
+ /**
35
+ * The 4 by 4 matrix, row by row (what three.js's `Matrix4.set` takes), that puts a model of radius 1 at a place, turned to the satellite's axes and scaled: its columns are the axes times the scale, then the place.
36
+ *
37
+ * @param place - Where the model's middle goes, in the scene's units.
38
+ * @param axes - The satellite's axes (`satelliteAxes`).
39
+ * @param scale - The model's radius in the scene's units.
40
+ * @returns Sixteen numbers, row by row.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { modelMatrix, satelliteAxes } from "@johnmorrisdotca/chikyu-earth/space";
45
+ *
46
+ * const axes = satelliteAxes([1.066, 0, 0], [0, 0, -7.66])!;
47
+ * console.log(modelMatrix([1.066, 0, 0], axes, 0.01));
48
+ * ```
49
+ */
50
+ export declare function modelMatrix(place: Vec3, axes: {
51
+ x: Vec3;
52
+ y: Vec3;
53
+ z: Vec3;
54
+ }, scale: number): number[];
55
+ /**
56
+ * The radius to draw a model at so that it is `share` of the height of the view across its radius, seen from `away` with the half field of view `half` (the tangent of half the field, as the view uses it): the model grows with the distance, so it reads
57
+ * at any distance the camera keeps. Never under `real`, its true size, so a camera that comes in close still sees it as big as it is.
58
+ *
59
+ * @param away - The camera's distance from the satellite, in the scene's units.
60
+ * @param half - The tangent of half the field of view.
61
+ * @param share - The share of the view's height that the radius should take (`MODEL_RADIUS_SHARE`).
62
+ * @param real - The model's true radius, in the same units.
63
+ * @returns The radius to draw it at.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { MODEL_RADIUS_SHARE, modelRadius } from "@johnmorrisdotca/chikyu-earth/space";
68
+ *
69
+ * console.log(modelRadius(0.5, Math.tan((35 / 2) * (Math.PI / 180)), MODEL_RADIUS_SHARE, 1e-8));
70
+ * ```
71
+ */
72
+ export declare function modelRadius(away: number, half: number, share: number, real: number): number;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * How big a followed satellite's model is drawn: its radius is this share of the height of the view (0.17), so it reads at any distance the camera keeps.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import { MODEL_RADIUS_SHARE } from "@johnmorrisdotca/chikyu-earth/space";
7
+ *
8
+ * console.log(MODEL_RADIUS_SHARE);
9
+ * ```
10
+ */
11
+ export const MODEL_RADIUS_SHARE = 0.17;
12
+ /**
13
+ * The axes of a satellite flying: `x` along the way it goes (its velocity, taken level with the ground below it), `z` straight away from the Earth's centre, and `y` to complete them (`z` cross `x`, so it points to the left of the way it goes).
14
+ * The family's convention for a model: its nose or long axis along +x, its top (the side that faces space) along +z.
15
+ *
16
+ * @param position - Where the satellite is, from the Earth's centre, in any unit.
17
+ * @param velocity - The way it is going, in any unit.
18
+ * @returns Three unit vectors, `x`, `y` and `z`, in the scene's axes; `null` when the position is the centre or the satellite does not move.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { satelliteAxes } from "@johnmorrisdotca/chikyu-earth/space";
23
+ *
24
+ * const axes = satelliteAxes([1.066, 0, 0], [0, 0, -7.66]);
25
+ * console.log(axes?.x, axes?.z);
26
+ * ```
27
+ */
28
+ export function satelliteAxes(position, velocity) {
29
+ const length = Math.hypot(position[0], position[1], position[2]);
30
+ if (!(length > 0))
31
+ return null;
32
+ const z = [position[0] / length, position[1] / length, position[2] / length];
33
+ // the velocity without the part that points up or down
34
+ const along = velocity[0] * z[0] + velocity[1] * z[1] + velocity[2] * z[2];
35
+ const level = [velocity[0] - along * z[0], velocity[1] - along * z[1], velocity[2] - along * z[2]];
36
+ const speed = Math.hypot(level[0], level[1], level[2]);
37
+ if (!(speed > 1e-12))
38
+ return null;
39
+ const x = [level[0] / speed, level[1] / speed, level[2] / speed];
40
+ const y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
41
+ return { x, y, z };
42
+ }
43
+ /**
44
+ * The 4 by 4 matrix, row by row (what three.js's `Matrix4.set` takes), that puts a model of radius 1 at a place, turned to the satellite's axes and scaled: its columns are the axes times the scale, then the place.
45
+ *
46
+ * @param place - Where the model's middle goes, in the scene's units.
47
+ * @param axes - The satellite's axes (`satelliteAxes`).
48
+ * @param scale - The model's radius in the scene's units.
49
+ * @returns Sixteen numbers, row by row.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * import { modelMatrix, satelliteAxes } from "@johnmorrisdotca/chikyu-earth/space";
54
+ *
55
+ * const axes = satelliteAxes([1.066, 0, 0], [0, 0, -7.66])!;
56
+ * console.log(modelMatrix([1.066, 0, 0], axes, 0.01));
57
+ * ```
58
+ */
59
+ export function modelMatrix(place, axes, scale) {
60
+ const { x, y, z } = axes;
61
+ return [x[0] * scale, y[0] * scale, z[0] * scale, place[0], x[1] * scale, y[1] * scale, z[1] * scale, place[1], x[2] * scale, y[2] * scale, z[2] * scale, place[2], 0, 0, 0, 1];
62
+ }
63
+ /**
64
+ * The radius to draw a model at so that it is `share` of the height of the view across its radius, seen from `away` with the half field of view `half` (the tangent of half the field, as the view uses it): the model grows with the distance, so it reads
65
+ * at any distance the camera keeps. Never under `real`, its true size, so a camera that comes in close still sees it as big as it is.
66
+ *
67
+ * @param away - The camera's distance from the satellite, in the scene's units.
68
+ * @param half - The tangent of half the field of view.
69
+ * @param share - The share of the view's height that the radius should take (`MODEL_RADIUS_SHARE`).
70
+ * @param real - The model's true radius, in the same units.
71
+ * @returns The radius to draw it at.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { MODEL_RADIUS_SHARE, modelRadius } from "@johnmorrisdotca/chikyu-earth/space";
76
+ *
77
+ * console.log(modelRadius(0.5, Math.tan((35 / 2) * (Math.PI / 180)), MODEL_RADIUS_SHARE, 1e-8));
78
+ * ```
79
+ */
80
+ export function modelRadius(away, half, share, real) {
81
+ return Math.max(real, away * half * share * 2);
82
+ }