@johnmorrisdotca/chikyu-earth 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,249 @@
1
+ // Which satellites are nearest a place, a direction in the sky, or another satellite. Positions come from the group's SGP4 (`exact`), once per call, never on a timer.
2
+ // The Earth-fixed frame is the same turn `groundUnder` uses (src/paint/math.ts): the view's x, y, z, then Greenwich sidereal time.
3
+ import { greenwichSidereal } from "../realistic/sun.js";
4
+ /** The sphere the positions use, kilometres, the same one `groundUnder` uses. */
5
+ const EARTH_KM = 6371;
6
+ const RAD = Math.PI / 180;
7
+ /** A rough uncertainty: 1 km at the epoch, and 1 km more for each day the elements have aged. Not a published covariance. */
8
+ const uncertaintyOf = (ageDays) => 1 + Math.max(0, ageDays);
9
+ /**
10
+ * How many neighbours `nearest` returns when `count` is left out.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { NEAREST_COUNT } from "@johnmorrisdotca/chikyu-earth/satellites";
15
+ *
16
+ * console.log(NEAREST_COUNT);
17
+ * ```
18
+ */
19
+ export const NEAREST_COUNT = 5;
20
+ const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
21
+ const sub = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
22
+ const norm = (a) => {
23
+ const length = Math.hypot(a.x, a.y, a.z) || 1;
24
+ return { x: a.x / length, y: a.y / length, z: a.z / length };
25
+ };
26
+ const hypot = (a) => Math.hypot(a.x, a.y, a.z);
27
+ /** A place on the sphere, in kilometres, in the Earth-fixed frame (x east of Greenwich, y north, z the meridian of 0). */
28
+ function groundKm(place, heightM = 0) {
29
+ const lat = place.lat * RAD;
30
+ const lon = place.lon * RAD;
31
+ const radius = EARTH_KM + heightM / 1000;
32
+ const c = Math.cos(lat);
33
+ return { x: c * Math.sin(lon) * radius, y: Math.sin(lat) * radius, z: c * Math.cos(lon) * radius };
34
+ }
35
+ /** `exact`'s position (Earth radii, the view's axes) as kilometres fixed to the Earth. The same turn as `groundUnder`. */
36
+ function fixedKm(x, y, z, ms) {
37
+ const theta = greenwichSidereal(ms) * RAD;
38
+ const sin = Math.sin(theta);
39
+ const cos = Math.cos(theta);
40
+ const temeX = x;
41
+ const temeY = -z;
42
+ const temeZ = y;
43
+ const east = -temeX * sin + temeY * cos;
44
+ const north = temeZ;
45
+ const prime = temeX * cos + temeY * sin;
46
+ return { x: east * EARTH_KM, y: north * EARTH_KM, z: prime * EARTH_KM };
47
+ }
48
+ /** A direction in the sky, as a unit vector in the Earth-fixed frame. Azimuth is degrees clockwise from north. */
49
+ function skyDirection(observer, azimuth, elevation) {
50
+ const lat = observer.lat * RAD;
51
+ const lon = observer.lon * RAD;
52
+ const east = { x: Math.cos(lon), y: 0, z: -Math.sin(lon) };
53
+ const north = { x: -Math.sin(lat) * Math.sin(lon), y: Math.cos(lat), z: -Math.sin(lat) * Math.cos(lon) };
54
+ const up = { x: Math.cos(lat) * Math.sin(lon), y: Math.sin(lat), z: Math.cos(lat) * Math.cos(lon) };
55
+ const el = elevation * RAD;
56
+ const az = azimuth * RAD;
57
+ const ce = Math.cos(el);
58
+ return norm({
59
+ x: north.x * ce * Math.cos(az) + east.x * ce * Math.sin(az) + up.x * Math.sin(el),
60
+ y: north.y * ce * Math.cos(az) + east.y * ce * Math.sin(az) + up.y * Math.sin(el),
61
+ z: north.z * ce * Math.cos(az) + east.z * ce * Math.sin(az) + up.z * Math.sin(el),
62
+ });
63
+ }
64
+ /** An element set's epoch, milliseconds since the Unix epoch; a text with no zone is read as UTC. */
65
+ const epochOf = (text) => Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) ? text : `${text}Z`);
66
+ function placedAt(group, ms) {
67
+ const out = [];
68
+ const buf = new Float64Array(6);
69
+ for (let index = 0; index < group.count; index += 1) {
70
+ if (!group.exact(index, ms, buf))
71
+ continue;
72
+ const set = group.sets[index];
73
+ out.push({ index, name: set.OBJECT_NAME, noradId: set.NORAD_CAT_ID, at: fixedKm(buf[0], buf[1], buf[2], ms), uncertaintyKm: uncertaintyOf((ms - epochOf(set.EPOCH)) / 86_400_000) });
74
+ }
75
+ return out;
76
+ }
77
+ const scoreOf = (placed, target, by, observer, others) => {
78
+ if ("satellite" in target) {
79
+ if (!others || placed.index === target.satellite)
80
+ return null;
81
+ if (by === "space")
82
+ return { kilometres: hypot(sub(placed.at, others.at)) };
83
+ const eye = observer ? groundKm(observer, observer.heightM) : { x: norm(others.at).x * EARTH_KM, y: norm(others.at).y * EARTH_KM, z: norm(others.at).z * EARTH_KM };
84
+ const a = norm(sub(others.at, eye));
85
+ const b = norm(sub(placed.at, eye));
86
+ return { angle: (Math.acos(Math.max(-1, Math.min(1, dot(a, b)))) / RAD) };
87
+ }
88
+ if ("azimuth" in target) {
89
+ const eye = groundKm(target.observer, target.observer.heightM);
90
+ const toward = skyDirection(target.observer, target.azimuth, target.elevation);
91
+ const seen = norm(sub(placed.at, eye));
92
+ return { angle: (Math.acos(Math.max(-1, Math.min(1, dot(toward, seen)))) / RAD) };
93
+ }
94
+ const eye = groundKm(target.place, target.heightM);
95
+ if (by === "sky") {
96
+ const up = norm(eye);
97
+ const seen = norm(sub(placed.at, eye));
98
+ return { angle: (Math.acos(Math.max(-1, Math.min(1, dot(up, seen)))) / RAD) };
99
+ }
100
+ return { kilometres: hypot(sub(placed.at, eye)) };
101
+ };
102
+ function rank(rows, target, options) {
103
+ const by = options.by ?? "space";
104
+ const count = options.count ?? NEAREST_COUNT;
105
+ const self = "satellite" in target ? rows.find((row) => row.index === target.satellite) : undefined;
106
+ const hits = [];
107
+ for (const row of rows) {
108
+ const score = scoreOf(row, target, by, options.observer, self);
109
+ if (!score)
110
+ continue;
111
+ const measure = by === "sky" ? score.angle : score.kilometres;
112
+ if (measure === undefined)
113
+ continue;
114
+ if (options.within !== undefined && measure > options.within)
115
+ continue;
116
+ const neighbour = { index: row.index, name: row.name, noradId: row.noradId };
117
+ if (by === "sky")
118
+ neighbour.angle = score.angle;
119
+ else
120
+ neighbour.distance = { kilometres: score.kilometres, uncertaintyKm: row.uncertaintyKm, unit: "km" };
121
+ hits.push(neighbour);
122
+ }
123
+ hits.sort((a, b) => (a.angle ?? a.distance?.kilometres ?? 0) - (b.angle ?? b.distance?.kilometres ?? 0));
124
+ return hits.slice(0, Math.max(0, count));
125
+ }
126
+ /**
127
+ * The satellites nearest a place, a direction in the sky, or another satellite, at one moment. One SGP4 call (`exact`) for each satellite that can be placed.
128
+ * It does not run again by itself. `by: "space"` answers with kilometres; `by: "sky"` with the angle in degrees. Nearest first.
129
+ *
130
+ * @param group - The satellites, from `createSatellites`.
131
+ * @param target - A place, a direction (`azimuth`, `elevation`, `observer`), or `{ satellite: index }`.
132
+ * @param options - `date` (required), `count` (5), `within`, `by` (`"space"`), and `observer` for a satellite seen in the sky.
133
+ * @returns The neighbours, nearest first.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * import { createSatellites, nearest } from "@johnmorrisdotca/chikyu-earth/satellites";
138
+ *
139
+ * const group = createSatellites([]);
140
+ * console.log(nearest(group, { place: { lon: 0, lat: 0 } }, { date: Date.UTC(2026, 10, 2) }).length);
141
+ * ```
142
+ */
143
+ export function nearest(group, target, options) {
144
+ return rank(placedAt(group, options.date), target, options);
145
+ }
146
+ /**
147
+ * Every satellite within `radius` of a target, nearest first. Kilometres for `by: "space"`, degrees for `by: "sky"`. The same one pass as `nearest`.
148
+ *
149
+ * @param group - The satellites.
150
+ * @param target - A place, a direction, or a satellite.
151
+ * @param radius - The limit, in the unit `by` uses.
152
+ * @param options - As `nearest`, without `count` and `within`.
153
+ * @returns The neighbours inside the limit.
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * import { createSatellites, within } from "@johnmorrisdotca/chikyu-earth/satellites";
158
+ *
159
+ * const group = createSatellites([]);
160
+ * console.log(within(group, { place: { lon: 0, lat: 0 } }, 1000, { date: Date.UTC(2026, 10, 2) }).length);
161
+ * ```
162
+ */
163
+ export function within(group, target, radius, options) {
164
+ return nearest(group, target, { ...options, count: group.count, within: radius });
165
+ }
166
+ /**
167
+ * The closest the two satellites come between `from` and `to`. The span is sampled every `stepMs` (60 seconds when left out), and the moment of the closest sample is then refined between its two neighbours,
168
+ * to a tenth of a second, because two satellites close in at several kilometres a second and the closest sample alone can be hundreds of kilometres too far. The uncertainty is the elements' own: the
169
+ * square root of the sum of the squares of the two satellites' rough uncertainties (1 km, and 1 km more for each day the elements have aged at that moment), not a published covariance.
170
+ * Two SGP4 calls a sample, and about 20 more for the refinement. It does not run again by itself.
171
+ *
172
+ * @param group - The satellites.
173
+ * @param a - The index of one satellite.
174
+ * @param b - The index of the other.
175
+ * @param from - The start, milliseconds since the Unix epoch.
176
+ * @param to - The end.
177
+ * @param stepMs - The sample step, at least 1000.
178
+ * @returns The closest moment, or null when either satellite cannot be placed.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * import { closeApproach, createSatellites } from "@johnmorrisdotca/chikyu-earth/satellites";
183
+ *
184
+ * const group = createSatellites([]);
185
+ * console.log(closeApproach(group, 0, 1, 0, 60_000));
186
+ * ```
187
+ */
188
+ export function closeApproach(group, a, b, from, to, stepMs = 60_000) {
189
+ const step = Math.max(1000, stepMs);
190
+ const bufA = new Float64Array(6);
191
+ const bufB = new Float64Array(6);
192
+ const apart = (at) => (group.exact(a, at, bufA) && group.exact(b, at, bufB) ? hypot(sub(fixedKm(bufA[0], bufA[1], bufA[2], at), fixedKm(bufB[0], bufB[1], bufB[2], at))) : null);
193
+ const samples = [];
194
+ for (let at = from; at <= to; at += step) {
195
+ const kilometres = apart(at);
196
+ if (kilometres !== null)
197
+ samples.push({ at, kilometres });
198
+ }
199
+ if (samples.length === 0)
200
+ return null;
201
+ let atBest = 0;
202
+ for (const [i, sample] of samples.entries())
203
+ if (sample.kilometres < samples[atBest].kilometres)
204
+ atBest = i;
205
+ let best = samples[atBest];
206
+ // between the neighbours of the closest sample the distance falls and then rises: a ternary search for the lowest point
207
+ let low = Math.max(from, (samples[atBest - 1] ?? best).at);
208
+ let high = Math.min(to, (samples[atBest + 1] ?? best).at);
209
+ while (high - low > 100) {
210
+ const left = low + (high - low) / 3;
211
+ const right = high - (high - low) / 3;
212
+ const dl = apart(left);
213
+ const dr = apart(right);
214
+ if (dl === null || dr === null)
215
+ break;
216
+ if (dl < dr)
217
+ high = right;
218
+ else
219
+ low = left;
220
+ }
221
+ const mid = Math.round((low + high) / 2);
222
+ const refined = apart(mid);
223
+ if (refined !== null && refined < best.kilometres)
224
+ best = { at: mid, kilometres: refined };
225
+ const age = (index) => {
226
+ const epoch = epochOf(group.sets[index].EPOCH);
227
+ return uncertaintyOf((best.at - epoch) / 86_400_000);
228
+ };
229
+ return { at: best.at, kilometres: best.kilometres, uncertaintyKm: Math.hypot(age(a), age(b)) };
230
+ }
231
+ /**
232
+ * The slant range from a place to a satellite that is straight overhead, for a test or a page: it is the satellite's height. Positions are kilometres in one frame.
233
+ *
234
+ * @param heightKm - How far above the ground the satellite is.
235
+ * @returns The distance, which is `heightKm`.
236
+ *
237
+ * @example
238
+ * ```ts
239
+ * import { overheadKm } from "@johnmorrisdotca/chikyu-earth/satellites";
240
+ *
241
+ * console.log(overheadKm(420));
242
+ * ```
243
+ */
244
+ export function overheadKm(heightKm) {
245
+ const ground = groundKm({ lon: 0, lat: 0 });
246
+ const up = norm(ground);
247
+ const sat = { x: up.x * (EARTH_KM + heightKm), y: up.y * (EARTH_KM + heightKm), z: up.z * (EARTH_KM + heightKm) };
248
+ return hypot(sub(sat, ground));
249
+ }
@@ -7,6 +7,7 @@ import { type Place, type PlaceLook } from "../markers/places.ts";
7
7
  import { type CityNamesStyle } from "../cities/host.ts";
8
8
  import { type BorderSets } from "../borders/lines.ts";
9
9
  import type { BorderData, BorderStats } from "../borders/layer.ts";
10
+ import { type RouteLeg } from "../route.ts";
10
11
  import type { GridStats } from "../grid/layer.ts";
11
12
  import { type CountryNamesStats, type CountryNamesStyle } from "../country-names/host.ts";
12
13
  import type { TileStats } from "../realistic/tile-set.ts";
@@ -260,6 +261,38 @@ export declare class ChikyuSpace extends HTMLElement {
260
261
  */
261
262
  get places(): Place[];
262
263
  set places(value: readonly Place[]);
264
+ /**
265
+ * Name each `here` place with the nearest city (the attribute `here-city`). `false` (the default) leaves the page's label and loads nothing.
266
+ * `true` looks within 100 km (`HERE_CITY_KM`). A number is that limit in kilometres, at most 20,000 (`HERE_CITY_MAX_KM`); a city further away is not used, and the page's label stays.
267
+ * The cities are kuni's capitals, the other cities of a million and the others of 100,000, an optional peer loaded only when this is on and a `here` place is set. The name follows the page's language
268
+ * (the short Japanese name, then the Japanese name, else English). `places` is not changed: only the drawn name is. Nothing is drawn again at rest.
269
+ *
270
+ * @example
271
+ * ```ts no-run
272
+ * import type { ChikyuSpace } from "@johnmorrisdotca/chikyu-earth/space/element";
273
+ *
274
+ * const space = document.querySelector("chikyu-space") as ChikyuSpace;
275
+ * space.hereCity = true;
276
+ * console.log(space.hereCity); // 100
277
+ * space.hereCity = false;
278
+ * ```
279
+ */
280
+ get hereCity(): false | number;
281
+ set hereCity(value: false | true | number);
282
+ /**
283
+ * A route between two places (the attribute `route`, `lon,lat,lon,lat`). Null, the default, draws none. The line is the WGS84 geodesic, split at the date line, and it turns with the Earth.
284
+ * Setting the property writes the attribute. Nothing is drawn again at rest: the line is drawn with the picture, and only when the route or the view changes.
285
+ */
286
+ get route(): {
287
+ from: GeoPoint;
288
+ to: GeoPoint;
289
+ } | null;
290
+ set route(value: {
291
+ from: GeoPoint;
292
+ to: GeoPoint;
293
+ } | null);
294
+ /** The distance, bearings and flight-time estimate for `route`, or null when none is set. The flight time assumes 900 km/h. */
295
+ get routeInfo(): RouteLeg | null;
263
296
  /**
264
297
  * Turn the view so a place of `places` is in the middle, at a pace a reader can follow (at once with `smooth: false`, for a reader who asked for less motion, or before the picture is live); the zoom stays.
265
298
  * The place is named by its `id`, or by its label in any case. The camera must be looking at the Earth: while it rides along or looks at another body nothing moves. The tilt is held to 90 degrees either
@@ -468,6 +501,12 @@ export declare class ChikyuSpace extends HTMLElement {
468
501
  * @param on - `true` to ring and name its members (the default), `false` to stop.
469
502
  */
470
503
  labelSatellites(group: string, on?: boolean): void;
504
+ /**
505
+ * Ring and name these satellites, besides any group `labelSatellites` names. Pass an empty list to take them off. One draw, then nothing at rest.
506
+ *
507
+ * @param refs - The satellites, by group and index, as `setSatellites` knows them.
508
+ */
509
+ ringSatellites(refs: readonly SatelliteRef[]): void;
471
510
  /** The groups whose satellites are ringed and named now (`labelSatellites`). */
472
511
  get labelledSatellites(): string[];
473
512
  /**
@@ -528,7 +567,7 @@ export declare class ChikyuSpace extends HTMLElement {
528
567
  quaternion: [number, number, number, number];
529
568
  fov: number;
530
569
  };
531
- /** What the body painter has made at the last draw: the Sun and planets with a drawing, the moons shown round a planet that is near and the moons held (shown, or gone from the view for less than four seconds), whether the Moon is the painter's (`moon`), and the bodies with finer map tiles on them (`tiles`). */
570
+ /** What the body painter has made at the last draw: the Sun and planets with a drawing, the moons shown round a planet that is near and the moons held (shown, or gone from the view for less than four seconds), whether the Moon is the painter's (`moon`), and the bodies with finer map tiles on them (`tiles`). `mapped` is how many drawings are the painter's, with its pictures: a body out of the view, or too small to show its map, is a plain sphere and the painter is not asked for it. `pending` is how many pictures asked of the painter have not yet arrived, and one more while a gathered draw (reduced motion) waits for its second: while it is above 0 a draw is still to come that nothing but the view itself asked for. */
532
571
  bodies: {
533
572
  look: string;
534
573
  painted: number;
@@ -536,6 +575,8 @@ export declare class ChikyuSpace extends HTMLElement {
536
575
  held: number;
537
576
  moon: boolean;
538
577
  tiles: number;
578
+ mapped: number;
579
+ pending: number;
539
580
  };
540
581
  /** The meteors: whether they are on, the streaks alive now and started so far, the streaks a second being drawn, and the strongest active shower's code and rate. */
541
582
  meteors: {
@@ -599,6 +640,13 @@ export declare class ChikyuSpace extends HTMLElement {
599
640
  dots: number;
600
641
  omitted: number;
601
642
  };
643
+ /** The nearest city on a `here` marker (`here-city`): whether it is on, the kilometre limit (0 when off), whether kuni's cities have arrived, and whether that load is still going. */
644
+ hereCity: {
645
+ on: boolean;
646
+ maxKm: number;
647
+ loaded: boolean;
648
+ pending: boolean;
649
+ };
602
650
  /** The names of cities: whether `city-names` is set and the most it asks for, the Earth's radius on the screen, the tiers of kuni's cities that have arrived and how many cities, the names shown at the last draw and how many times the layer was drawn. */
603
651
  cityNames: {
604
652
  on: boolean;
@@ -613,6 +661,13 @@ export declare class ChikyuSpace extends HTMLElement {
613
661
  borders: BorderStats;
614
662
  /** The grid: whether it was drawn at the last draw, whether every 15 degrees (else 30), its segments then, how many times its lines were made, and whether it could not be made. */
615
663
  grid: GridStats;
664
+ /** The route between two places: whether one is set, and its geodesic distance, great-circle distance and flight time at 900 km/h. */
665
+ route: {
666
+ on: boolean;
667
+ kilometres: number;
668
+ greatCircleKm: number;
669
+ flightHours: number;
670
+ };
616
671
  /** The names of countries: whether `country-names` is set and the most it asks for, the countries loaded, the names shown at the last draw, how many times they were laid out, and whether the outlines could not be loaded. */
617
672
  countryNames: CountryNamesStats;
618
673
  };
@@ -4,6 +4,8 @@ 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
6
  import { cleanPlaces, readPlaceGroups, readPlaces } from "../markers/places.js";
7
+ import { readHereCity } from "../markers/here-city.js";
8
+ import { createHereCity } from "../markers/here-city-host.js";
7
9
  import { createPlaceLayer, PLACE_STYLE, placesLostNotice, readPlaceLook } from "../markers/place-layer.js";
8
10
  import { aimAt, findPlace, glideView } from "../markers/go-to-place.js";
9
11
  import { subsolarPoint } from "../realistic/sun.js";
@@ -11,6 +13,8 @@ import { SHORT_NAMES } from "../satellites/names.js";
11
13
  import { CITY_NAMES_ATTRIBUTES, CITY_NAMES_STYLE, createCityHost } from "../cities/host.js";
12
14
  import { BORDER_ATTRIBUTES, readBorders } from "../borders/lines.js";
13
15
  import { GRID_ATTRIBUTES, readGrid } from "../grid/lines.js";
16
+ import { readRoute, routeLeg, routeText } from "../route.js";
17
+ import { applyRoute } from "../route/layer.js";
14
18
  import { COUNTRY_NAMES_ATTRIBUTES } from "../country-names/geometry.js";
15
19
  import { COUNTRY_NAMES_STYLE, createCountryHost } from "../country-names/host.js";
16
20
  import { createGate, frameCap } from "../realistic/gate.js";
@@ -149,7 +153,7 @@ const STYLE = `:host{display:block;aspect-ratio:1/1;position:relative;overflow:h
149
153
  * ```
150
154
  */
151
155
  export class ChikyuSpace extends HTMLElement {
152
- 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, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "bodies-credit", "satellite-tint", "tiles"];
156
+ 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, ...BORDER_ATTRIBUTES, ...GRID_ATTRIBUTES, ...COUNTRY_NAMES_ATTRIBUTES, "air-thickness", "air-label", "lang", "places", "places-look", "place-groups", "here-city", "route", "bodies-credit", "satellite-tint", "tiles"];
153
157
  #model = newSpaceModel();
154
158
  #paint = createPaintState();
155
159
  #mode = "now";
@@ -197,6 +201,8 @@ export class ChikyuSpace extends HTMLElement {
197
201
  #ridden = {};
198
202
  #toldFacing = null;
199
203
  #placeLayer;
204
+ /** The nearest city's name on a `here` marker (`here-city`), loaded only when that is on. */
205
+ #here;
200
206
  /** Whether the page has been told that places in sight were left undrawn. */
201
207
  #placesLost = { told: false };
202
208
  #placeList = [];
@@ -250,8 +256,9 @@ export class ChikyuSpace extends HTMLElement {
250
256
  this.#sky.setStyle(this.#skyStyle);
251
257
  this.#sky.setKeepClear(this.#keepClear);
252
258
  this.#placeLayer = createPlaceLayer(root.getElementById("places"));
259
+ this.#here = this.#openHereCity();
253
260
  this.#placeList = readPlaces(this.getAttribute("places"));
254
- this.#placeLayer.set(this.#placeList);
261
+ this.#placeLayer.set(this.#here.named(this.#placeList));
255
262
  this.#placeLayer.look = readPlaceLook(this.getAttribute("places-look"));
256
263
  this.#placeLayer.grouping = readPlaceGroups(this.getAttribute("place-groups"));
257
264
  this.#cities = createCityHost({
@@ -299,6 +306,7 @@ export class ChikyuSpace extends HTMLElement {
299
306
  cap: () => this.#textureCap(),
300
307
  air: () => airFor(this.getAttribute("air")),
301
308
  invalidate: () => this.#gate?.request(),
309
+ onBodies: () => this.#showBodiesCredit(),
302
310
  onError: (error) => this.#fail(error instanceof Error ? error.message : String(error)),
303
311
  onTier: (layer, width) => {
304
312
  this.#tiers[layer] = width;
@@ -372,6 +380,8 @@ export class ChikyuSpace extends HTMLElement {
372
380
  this.#taken = undefined;
373
381
  this.#sky?.dispose();
374
382
  this.#sky = undefined;
383
+ this.#here?.dispose();
384
+ this.#here = undefined;
375
385
  this.#placeLayer?.dispose();
376
386
  this.#placeLayer = undefined;
377
387
  this.#cities?.dispose();
@@ -425,6 +435,7 @@ export class ChikyuSpace extends HTMLElement {
425
435
  this.#sky?.refresh();
426
436
  this.#cities?.refresh();
427
437
  this.#countries?.refresh();
438
+ this.#here?.refresh();
428
439
  }
429
440
  }
430
441
  else if (BODY_LABEL_ATTRIBUTES.includes(name))
@@ -433,8 +444,11 @@ export class ChikyuSpace extends HTMLElement {
433
444
  this.#sky?.refresh();
434
445
  else if (name === "places") {
435
446
  this.#placeList = readPlaces(value);
436
- this.#placeLayer?.set(this.#placeList);
437
- this.#gate?.request();
447
+ this.#applyPlaces();
448
+ }
449
+ else if (name === "here-city") {
450
+ this.#here?.setLimit(readHereCity(value));
451
+ this.#applyPlaces();
438
452
  }
439
453
  else if (name === "places-look" && this.#placeLayer) {
440
454
  this.#placeLayer.look = readPlaceLook(value);
@@ -444,6 +458,10 @@ export class ChikyuSpace extends HTMLElement {
444
458
  this.#placeLayer.grouping = readPlaceGroups(value);
445
459
  this.#gate?.request();
446
460
  }
461
+ else if (name === "route") {
462
+ if (applyRoute(this.#model.route, readRoute(value)))
463
+ this.#gate?.request();
464
+ }
447
465
  else if (CITY_NAMES_ATTRIBUTES.includes(name))
448
466
  this.#cities?.refresh();
449
467
  else if (name === "borders") {
@@ -487,15 +505,30 @@ export class ChikyuSpace extends HTMLElement {
487
505
  this.setAttribute("tiles", value);
488
506
  }
489
507
  /** The body painter's credit under the picture, in the element's or the page's language: shown while the painter draws the bodies (not `plain`), unless `bodies-credit` is `off`. */
508
+ /** The painter's credit as last told to the page (`chikyu-bodies-credit`): both languages, or empty for none. */
509
+ #creditKey = "";
490
510
  #showBodiesCredit() {
491
511
  const note = this.#bodiesNote;
492
512
  if (!note)
493
513
  return;
494
514
  const lang = (this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en";
495
- const credit = painter?.credit?.[lang] ?? "";
496
- note.textContent = credit;
497
- note.lang = lang;
498
- note.hidden = credit === "" || this.bodies === "plain" || this.getAttribute("bodies-credit") === "off";
515
+ // read again at each redraw a body asks for (a picture arrived, a window of tiles changed): a painter's credit names the pictures on the screen now. Written only when the text changed, never at every frame.
516
+ const given = painter?.credit;
517
+ // a page that writes the credit itself (`bodies-credit="off"`) hears when the painter's credit changed
518
+ const key = given ? `${given.en}\n${given.ja}` : "";
519
+ if (key !== this.#creditKey) {
520
+ this.#creditKey = key;
521
+ this.dispatchEvent(new CustomEvent("chikyu-bodies-credit", { detail: given ? { en: given.en, ja: given.ja } : null }));
522
+ }
523
+ const credit = given?.[lang] ?? "";
524
+ if (note.textContent !== credit)
525
+ note.textContent = credit;
526
+ if (note.lang !== lang)
527
+ note.lang = lang;
528
+ // the painter holds no picture while no body is big enough in the view for its map: a painter that has made nothing names all its pictures, so no line then
529
+ const hidden = credit === "" || this.#model.painted.mapped === 0 || this.bodies === "plain" || this.getAttribute("bodies-credit") === "off";
530
+ if (note.hidden !== hidden)
531
+ note.hidden = hidden;
499
532
  }
500
533
  /**
501
534
  * True for the full-screen mode (the `immersive` attribute): the element fills its box in any shape (the Earth fits the shorter side with its glow inside it, `earth-size`), a plain wheel zooms instead of scrolling
@@ -625,6 +658,77 @@ export class ChikyuSpace extends HTMLElement {
625
658
  else
626
659
  this.setAttribute("places", JSON.stringify(clean));
627
660
  }
661
+ /**
662
+ * Name each `here` place with the nearest city (the attribute `here-city`). `false` (the default) leaves the page's label and loads nothing.
663
+ * `true` looks within 100 km (`HERE_CITY_KM`). A number is that limit in kilometres, at most 20,000 (`HERE_CITY_MAX_KM`); a city further away is not used, and the page's label stays.
664
+ * The cities are kuni's capitals, the other cities of a million and the others of 100,000, an optional peer loaded only when this is on and a `here` place is set. The name follows the page's language
665
+ * (the short Japanese name, then the Japanese name, else English). `places` is not changed: only the drawn name is. Nothing is drawn again at rest.
666
+ *
667
+ * @example
668
+ * ```ts no-run
669
+ * import type { ChikyuSpace } from "@johnmorrisdotca/chikyu-earth/space/element";
670
+ *
671
+ * const space = document.querySelector("chikyu-space") as ChikyuSpace;
672
+ * space.hereCity = true;
673
+ * console.log(space.hereCity); // 100
674
+ * space.hereCity = false;
675
+ * ```
676
+ */
677
+ get hereCity() {
678
+ return readHereCity(this.getAttribute("here-city"));
679
+ }
680
+ set hereCity(value) {
681
+ if (value === true)
682
+ this.setAttribute("here-city", "");
683
+ else if (value === false)
684
+ this.removeAttribute("here-city");
685
+ else {
686
+ const km = readHereCity(String(value));
687
+ if (km === false)
688
+ this.removeAttribute("here-city");
689
+ else
690
+ this.setAttribute("here-city", String(km));
691
+ }
692
+ }
693
+ /** The cities for `here-city`, asked for only when the attribute is on. */
694
+ #openHereCity() {
695
+ const host = createHereCity({
696
+ language: () => ((this.closest("[lang]")?.getAttribute("lang") ?? "").toLowerCase().startsWith("ja") ? "ja" : "en"),
697
+ onChange: () => {
698
+ if (this.isConnected)
699
+ this.#applyPlaces();
700
+ },
701
+ onError: (error) => this.dispatchEvent(new CustomEvent("chikyu-here-city-unavailable", { detail: { reason: error instanceof Error ? error.message : String(error) } })),
702
+ });
703
+ host.setLimit(readHereCity(this.getAttribute("here-city")));
704
+ return host;
705
+ }
706
+ /** Hand the places to the layer, with a here marker's city name when one is known, and draw once. */
707
+ #applyPlaces() {
708
+ const layer = this.#placeLayer;
709
+ if (!layer)
710
+ return;
711
+ layer.set(this.#here?.named(this.#placeList) ?? this.#placeList);
712
+ this.#gate?.request();
713
+ }
714
+ /**
715
+ * A route between two places (the attribute `route`, `lon,lat,lon,lat`). Null, the default, draws none. The line is the WGS84 geodesic, split at the date line, and it turns with the Earth.
716
+ * Setting the property writes the attribute. Nothing is drawn again at rest: the line is drawn with the picture, and only when the route or the view changes.
717
+ */
718
+ get route() {
719
+ return readRoute(this.getAttribute("route"));
720
+ }
721
+ set route(value) {
722
+ if (!value)
723
+ this.removeAttribute("route");
724
+ else
725
+ this.setAttribute("route", routeText(value));
726
+ }
727
+ /** The distance, bearings and flight-time estimate for `route`, or null when none is set. The flight time assumes 900 km/h. */
728
+ get routeInfo() {
729
+ const route = this.route;
730
+ return route ? routeLeg(route.from, route.to) : null;
731
+ }
628
732
  /**
629
733
  * Turn the view so a place of `places` is in the middle, at a pace a reader can follow (at once with `smooth: false`, for a reader who asked for less motion, or before the picture is live); the zoom stays.
630
734
  * The place is named by its `id`, or by its label in any case. The camera must be looking at the Earth: while it rides along or looks at another body nothing moves. The tilt is held to 90 degrees either
@@ -1306,6 +1410,16 @@ export class ChikyuSpace extends HTMLElement {
1306
1410
  this.#model.satellites.marked.delete(group);
1307
1411
  this.#gate?.request();
1308
1412
  }
1413
+ /**
1414
+ * Ring and name these satellites, besides any group `labelSatellites` names. Pass an empty list to take them off. One draw, then nothing at rest.
1415
+ *
1416
+ * @param refs - The satellites, by group and index, as `setSatellites` knows them.
1417
+ */
1418
+ ringSatellites(refs) {
1419
+ this.#model.satellites.pinned = refs.map((ref) => ({ group: ref.group, index: ref.index }));
1420
+ this.#gate?.request();
1421
+ this.#gate?.soon();
1422
+ }
1309
1423
  /** The groups whose satellites are ringed and named now (`labelSatellites`). */
1310
1424
  get labelledSatellites() {
1311
1425
  return [...this.#model.satellites.marked];
@@ -1441,16 +1555,18 @@ export class ChikyuSpace extends HTMLElement {
1441
1555
  satellites: this.#satelliteStats(),
1442
1556
  ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null, facing: this.facing },
1443
1557
  camera: { position: [this.#model.pose.p[0], this.#model.pose.p[1], this.#model.pose.p[2]], quaternion: [this.#model.pose.q[0], this.#model.pose.q[1], this.#model.pose.q[2], this.#model.pose.q[3]], fov: this.#model.pose.fov },
1444
- bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons, held: this.#model.painted.held, moon: this.#model.painted.moon, tiles: this.#model.painted.tiles },
1558
+ bodies: { look: this.#model.bodies || painter?.looks?.[0] || "plain", painted: this.#model.painted.bodies, moons: this.#model.painted.moons, held: this.#model.painted.held, moon: this.#model.painted.moon, tiles: this.#model.painted.tiles, mapped: this.#model.painted.mapped, pending: this.#model.painted.pending },
1445
1559
  meteors: { on: this.#model.meteors.on, strength: this.#model.meteors.strength, ...this.#model.meteors.drawn },
1446
1560
  bodyLabel: { on: this.#model.bodyLabel.settings !== null, text: this.#model.bodyLabel.text, ...this.#model.bodyLabel.drawn },
1447
1561
  sky: this.#sky?.stats ?? { on: false, loaded: false, names: 0, figures: 0, picked: null, pick: null, hover: null, constellations: 0, culture: "iau", renders: 0, lang: "", stars: [] },
1448
1562
  followModel: this.#model.followModel,
1449
1563
  tiles: this.#model.tiles?.stats ?? { ready: false, level: null, held: 0, shown: 0, loading: 0, failed: 0, requested: 0, heldBytes: 0, refused: 0, used: {} },
1450
1564
  places: { ...(this.#placeLayer?.stats ?? { places: 0, shown: 0, labels: 0, renders: 0, rings: 0, satelliteNames: 0, marks: 0, groups: 0, sprites: 0, dots: 0, omitted: 0 }) },
1565
+ hereCity: this.#here?.stats ?? { on: false, maxKm: 0, loaded: false, pending: false },
1451
1566
  cityNames: this.#cities?.stats ?? { on: false, max: 0, radius: 0, tiers: [], cities: 0, names: 0, renders: 0 },
1452
1567
  borders: { ...this.#model.borders.stats, shown: { ...this.#model.borders.stats.shown }, loaded: [...this.#model.borders.stats.loaded] },
1453
1568
  grid: { ...this.#model.grid.stats },
1569
+ route: { ...this.#model.route.stats },
1454
1570
  countryNames: this.#countries?.stats ?? { on: false, max: 0, countries: 0, names: 0, renders: 0, failed: false },
1455
1571
  };
1456
1572
  }
@@ -18,6 +18,8 @@ export interface SatelliteState {
18
18
  selected: SatelliteRef | null;
19
19
  /** The groups whose members are ringed and named (`labelSatellites`): the scene tells the page where each is, at every draw. */
20
20
  marked: Set<string>;
21
+ /** Satellites ringed besides a whole group: the nearest ones a page asked to mark. Empty unless set. */
22
+ pinned: SatelliteRef[];
21
23
  /** Written at each draw: satellites placed, whether the clock is too fast for the groups, and the milliseconds the last update took. */
22
24
  /** Colour each dot by its orbit class. Off by default: a group keeps the one colour it was given. */
23
25
  orbitTint: boolean;
@@ -1,5 +1,5 @@
1
1
  import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
2
- export const newSatelliteState = () => ({ groups: new Map(), selected: null, marked: new Set(), orbitTint: false, drawn: { placed: 0, segments: 0, tooFast: false, dotScale: 1, updateMs: 0, maxUpdateMs: 0, updates: 0, totalMs: 0 } });
2
+ export const newSatelliteState = () => ({ groups: new Map(), selected: null, marked: new Set(), pinned: [], orbitTint: false, drawn: { placed: 0, segments: 0, tooFast: false, dotScale: 1, 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;