@johnmorrisdotca/chikyu-earth 0.34.1 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/NOTICE.md +23 -1
  3. package/README.md +20 -2
  4. package/dist/borders/layer.d.ts +75 -0
  5. package/dist/borders/layer.js +136 -0
  6. package/dist/borders/lines.d.ts +138 -0
  7. package/dist/borders/lines.js +227 -0
  8. package/dist/cities/host.d.ts +9 -0
  9. package/dist/cities/host.js +14 -2
  10. package/dist/country-names/geometry.d.ts +264 -0
  11. package/dist/country-names/geometry.js +372 -0
  12. package/dist/country-names/host.d.ts +82 -0
  13. package/dist/country-names/host.js +212 -0
  14. package/dist/grid/layer.d.ts +45 -0
  15. package/dist/grid/layer.js +66 -0
  16. package/dist/grid/lines.d.ts +85 -0
  17. package/dist/grid/lines.js +113 -0
  18. package/dist/markers/go-to-place.d.ts +27 -0
  19. package/dist/markers/go-to-place.js +35 -0
  20. package/dist/markers/index.d.ts +2 -1
  21. package/dist/markers/index.js +2 -1
  22. package/dist/markers/layer.d.ts +7 -0
  23. package/dist/markers/layer.js +7 -0
  24. package/dist/markers/place-layer.d.ts +58 -7
  25. package/dist/markers/place-layer.js +326 -64
  26. package/dist/markers/place-sprites.d.ts +33 -0
  27. package/dist/markers/place-sprites.js +161 -0
  28. package/dist/markers/places.d.ts +91 -6
  29. package/dist/markers/places.js +135 -6
  30. package/dist/realistic/earth.d.ts +11 -0
  31. package/dist/realistic/earth.js +54 -0
  32. package/dist/realistic/element.d.ts +84 -4
  33. package/dist/realistic/element.js +224 -27
  34. package/dist/realistic/immersive.d.ts +7 -0
  35. package/dist/realistic/immersive.js +17 -0
  36. package/dist/realistic/index.d.ts +7 -0
  37. package/dist/realistic/index.js +3 -0
  38. package/dist/realistic/textures.d.ts +3 -0
  39. package/dist/sky/culture-lines.d.ts +56 -0
  40. package/dist/sky/culture-lines.js +82 -0
  41. package/dist/sky/figure-pick.d.ts +75 -0
  42. package/dist/sky/figure-pick.js +200 -0
  43. package/dist/sky/host.d.ts +17 -1
  44. package/dist/sky/host.js +615 -71
  45. package/dist/sky/keep-clear.d.ts +63 -0
  46. package/dist/sky/keep-clear.js +55 -0
  47. package/dist/space/element.d.ts +105 -10
  48. package/dist/space/element.js +275 -18
  49. package/dist/space/index.d.ts +2 -2
  50. package/dist/space/index.js +1 -1
  51. package/dist/space/satellite-model.d.ts +22 -0
  52. package/dist/space/satellite-model.js +38 -0
  53. package/dist/space/scene.d.ts +56 -7
  54. package/dist/space/scene.js +124 -23
  55. package/package.json +3 -3
@@ -0,0 +1,161 @@
1
+ const VERT = /* glsl */ `
2
+ attribute vec3 tint;
3
+ attribute vec2 shape;
4
+ uniform float ratio;
5
+ uniform vec2 viewport;
6
+ uniform vec3 sunDir;
7
+ uniform float lit;
8
+ varying vec3 vTint;
9
+ varying float vAlpha;
10
+ varying vec2 vAxis;
11
+ varying float vSquash;
12
+ varying float vRing;
13
+ varying float vPx;
14
+ varying float vFill;
15
+ void main() {
16
+ vec3 normal = normalize(mat3(modelMatrix) * position);
17
+ vec4 world = modelMatrix * vec4(position * 1.002, 1.0);
18
+ bool ortho = projectionMatrix[3][3] == 1.0;
19
+ vec3 toCamera = ortho ? normalize(vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2])) : normalize(cameraPosition - world.xyz);
20
+ float facing = dot(normal, toCamera);
21
+ if (shape.x <= 0.0 || facing <= 0.02) {
22
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
23
+ gl_PointSize = 1.0;
24
+ return;
25
+ }
26
+ vec4 clip = projectionMatrix * viewMatrix * world;
27
+ vec4 lifted = projectionMatrix * viewMatrix * vec4(world.xyz + normal * 0.01, 1.0);
28
+ vec2 lean = (lifted.xy / lifted.w - clip.xy / clip.w) * viewport;
29
+ vAxis = length(lean) > 1e-6 ? normalize(vec2(lean.x, -lean.y)) : vec2(0.0, -1.0);
30
+ vSquash = clamp(facing, 0.08, 1.0);
31
+ float extent = shape.x + 3.0;
32
+ gl_PointSize = min(2.0 * extent * ratio, 64.0);
33
+ vRing = shape.x / extent;
34
+ vPx = 1.0 / extent;
35
+ vFill = shape.y;
36
+ float night = lit > 0.5 ? 0.0 : 1.0 - smoothstep(-0.12, 0.05, dot(normal, sunDir));
37
+ vAlpha = min(1.0, (facing - 0.02) / 0.12) * mix(1.0, 0.5, night);
38
+ vTint = tint;
39
+ gl_Position = clip;
40
+ }
41
+ `;
42
+ const FRAG = /* glsl */ `
43
+ varying vec3 vTint;
44
+ varying float vAlpha;
45
+ varying vec2 vAxis;
46
+ varying float vSquash;
47
+ varying float vRing;
48
+ varying float vPx;
49
+ varying float vFill;
50
+ void main() {
51
+ vec2 q = gl_PointCoord * 2.0 - 1.0;
52
+ float along = dot(q, vAxis) / vSquash;
53
+ float across = dot(q, vec2(-vAxis.y, vAxis.x));
54
+ float r = length(vec2(along, across));
55
+ float away = abs(r - vRing) / vPx;
56
+ float stroke = 1.0 - smoothstep(0.5, 1.4, away);
57
+ float glow = exp(-away * away / 5.0) * 0.45;
58
+ float middle = 1.0 - smoothstep(0.2 * vRing - vPx, 0.2 * vRing + vPx, r);
59
+ float inside = (1.0 - smoothstep(vRing - vPx, vRing, r)) * vFill;
60
+ float alpha = max(max(stroke, glow), max(middle * 0.9, inside)) * vAlpha;
61
+ if (alpha < 0.01) discard;
62
+ gl_FragColor = vec4(mix(vTint, vec3(1.0), stroke * 0.25 + middle * 0.35), alpha);
63
+ }
64
+ `;
65
+ /**
66
+ * Make the rings for one picture, as a child of the Earth (so they turn with it). Without three.js's `Points` (a subset of three.js that leaves it out) there are none: `null`.
67
+ *
68
+ * @param three - The page's three.js.
69
+ * @param parent - The Earth, or the group that turns it (radius 1).
70
+ * @param sun - The direction to the Sun in the scene's axes, the uniform the Earth's own surface uses.
71
+ * @returns The rings, or null.
72
+ */
73
+ export function createPlaceSprites(three, parent, sun) {
74
+ const Points = three.Points;
75
+ if (!Points)
76
+ return null;
77
+ const material = new three.ShaderMaterial({
78
+ vertexShader: VERT,
79
+ fragmentShader: FRAG,
80
+ uniforms: { ratio: { value: 1 }, viewport: { value: [1, 1] }, sunDir: sun, lit: { value: 0 } },
81
+ transparent: true,
82
+ depthWrite: false,
83
+ depthTest: false,
84
+ });
85
+ let points = null;
86
+ let capacity = 0;
87
+ let version = -1;
88
+ let shapesVersion = -1;
89
+ const color = new three.Color();
90
+ const drop = () => {
91
+ if (!points)
92
+ return;
93
+ parent.remove(points);
94
+ points.geometry.dispose();
95
+ points = null;
96
+ capacity = 0;
97
+ version = -1;
98
+ shapesVersion = -1;
99
+ };
100
+ return {
101
+ sync(data, ratio, width, height, lit) {
102
+ if (!data || data.count === 0) {
103
+ drop();
104
+ return;
105
+ }
106
+ if (data.count > capacity) {
107
+ drop();
108
+ capacity = 2 ** Math.ceil(Math.log2(Math.max(64, data.count)));
109
+ const geometry = new three.BufferGeometry();
110
+ geometry.setAttribute("position", new three.BufferAttribute(new Float32Array(capacity * 3), 3));
111
+ geometry.setAttribute("tint", new three.BufferAttribute(new Float32Array(capacity * 3), 3));
112
+ geometry.setAttribute("shape", new three.BufferAttribute(new Float32Array(capacity * 2), 2));
113
+ points = new Points(geometry, material);
114
+ points.frustumCulled = false;
115
+ points.renderOrder = 6;
116
+ parent.add(points);
117
+ }
118
+ const geometry = points.geometry;
119
+ if (data.version !== version) {
120
+ version = data.version;
121
+ const position = geometry.getAttribute("position");
122
+ const tint = geometry.getAttribute("tint");
123
+ position.array.set(data.points.subarray(0, data.count * 3));
124
+ const tints = tint.array;
125
+ for (let i = 0; i < data.count; i += 1) {
126
+ // the page's colour as CSS shows it: the shader writes it to the screen as it is
127
+ color.set(0xffd27a);
128
+ color.setStyle(data.colors[i] ?? "#ffd27a");
129
+ const hex = color.getHex();
130
+ tints[i * 3] = ((hex >> 16) & 255) / 255;
131
+ tints[i * 3 + 1] = ((hex >> 8) & 255) / 255;
132
+ tints[i * 3 + 2] = (hex & 255) / 255;
133
+ }
134
+ position.needsUpdate = true;
135
+ tint.needsUpdate = true;
136
+ geometry.setDrawRange(0, data.count);
137
+ shapesVersion = -1;
138
+ }
139
+ if (data.shapesVersion !== shapesVersion) {
140
+ shapesVersion = data.shapesVersion;
141
+ const shape = geometry.getAttribute("shape");
142
+ const shapes = data.shapes.subarray(0, data.count * 2);
143
+ shape.array.set(shapes);
144
+ shape.needsUpdate = true;
145
+ // every place in sight has a marker of its own: no draw call at all for the rings
146
+ let any = false;
147
+ for (let i = 0; i < shapes.length && !any; i += 2)
148
+ any = shapes[i] > 0;
149
+ points.visible = any;
150
+ }
151
+ const uniforms = material.uniforms;
152
+ uniforms["ratio"].value = ratio;
153
+ uniforms["viewport"].value = [width / 2, height / 2];
154
+ uniforms["lit"].value = lit ? 1 : 0;
155
+ },
156
+ dispose() {
157
+ drop();
158
+ material.dispose();
159
+ },
160
+ };
161
+ }
@@ -36,6 +36,8 @@ export interface Place {
36
36
  label?: string;
37
37
  /** `here` or `favourite` (the default). */
38
38
  kind?: PlaceKind;
39
+ /** A CSS colour for this place alone (`#e8475f`, `rgb(...)`, `hsl(...)` or a colour's name); left out, the kind's colour. */
40
+ color?: string;
39
41
  }
40
42
  /**
41
43
  * How a place is drawn: `beam` (a light rising out of the ground with a ring at its foot), `pin` (a thin stick with a round head) or `ring` (only the ring on the ground).
@@ -67,10 +69,10 @@ export declare const PLACE_LOOKS: readonly PlaceLook[];
67
69
  * ```ts
68
70
  * import { MAX_PLACES } from "@johnmorrisdotca/chikyu-earth/markers";
69
71
  *
70
- * console.log(MAX_PLACES);
72
+ * console.log(MAX_PLACES); // 5000
71
73
  * ```
72
74
  */
73
- export declare const MAX_PLACES = 200;
75
+ export declare const MAX_PLACES = 5000;
74
76
  /**
75
77
  * A point of the Earth's surface as one picture shows it: where it falls (CSS pixels in the box), which way is straight up from the ground there on the screen (`upX`, `upY`: a direction whose
76
78
  * length is how much of an upright stick the reader sees, 0 looking straight down on it and 1 seeing it side on) and `facing`, the cosine between the ground's upright and the way to the camera
@@ -106,6 +108,8 @@ export interface PlaceView {
106
108
  width: number;
107
109
  height: number;
108
110
  at(lon: number, lat: number, out: SurfacePoint): boolean;
111
+ /** The Earth's radius in the picture, in CSS pixels: how close places may be before they are gathered into a group. Left out, none are gathered. */
112
+ radius?: number;
109
113
  }
110
114
  /**
111
115
  * Where one place's marker is drawn: the foot on the ground, the top of the stick, the stick's turn and length, the ring's turn, how flat it is and its radius, and how strongly it shows (it fades at the Earth's edge).
@@ -136,6 +140,8 @@ export interface PlaceShape {
136
140
  /** The ring's radius in CSS pixels. */
137
141
  ring: number;
138
142
  opacity: number;
143
+ /** How far into the night the place is: 0 by day, 1 in full night, between in the twilight. Always 0 when no Sun is given. */
144
+ night: number;
139
145
  }
140
146
  /**
141
147
  * Where one place's name goes: which place it is and the top-left corner of its box.
@@ -191,10 +197,13 @@ export interface PlaceLayoutOptions {
191
197
  height: number;
192
198
  }[];
193
199
  maxLabels?: number;
200
+ /** Where the Sun is overhead, for each shape's `night`; left out (or null), every place is in daylight. */
201
+ sun?: GeoPoint | null;
194
202
  }
195
203
  /**
196
204
  * The places of a list a page handed over, made safe to draw: each needs a longitude from -180 to 180 and a latitude from -90 to 90; one without an `id` is given its place in the list, a
197
- * label is cut to 80 letters, a kind that is not `here` is `favourite`. Anything else is left out, and at most {@link MAX_PLACES} are kept.
205
+ * label is cut to 80 letters, a kind that is not `here` is `favourite`, and a colour is kept only when it is a hex colour, `rgb()` or `hsl()` with numbers, or a colour's name. Anything else is left out,
206
+ * and at most {@link MAX_PLACES} are kept.
198
207
  *
199
208
  * @param list - What the page gave: an array of places, or anything.
200
209
  * @returns The places to draw.
@@ -203,7 +212,7 @@ export interface PlaceLayoutOptions {
203
212
  * ```ts
204
213
  * import { cleanPlaces } from "@johnmorrisdotca/chikyu-earth/markers";
205
214
  *
206
- * console.log(cleanPlaces([{ lon: 2.35, lat: 48.86, label: "Paris" }, { lon: 500, lat: 0 }]));
215
+ * console.log(cleanPlaces([{ lon: 2.35, lat: 48.86, label: "Paris", color: "#e8475f" }, { lon: 500, lat: 0 }]));
207
216
  * ```
208
217
  */
209
218
  export declare function cleanPlaces(list: unknown): Place[];
@@ -259,12 +268,13 @@ export declare function orthoView(pose: Pose & {
259
268
  /**
260
269
  * Where each place's marker and name go in one picture. A place on the far side of the Earth, or off the picture, is left out; one near the Earth's edge fades. The stick stands up from the ground as the picture
261
270
  * sees it, leaning towards the top of the screen where the reader looks straight down on it, so it never shrinks to a dot; the ring at its foot is flattened as the ground is. A `here` place is taller and wider
262
- * than a favourite. Names go at the top of the stick, `here` first and then in the order given, never over one another or over a box in `taken`; a name with no free place is left out.
271
+ * than a favourite. Names go at the top of the stick, `here` first and then in the order given, never over one another or over a box in `taken`; a name with no free place is left out. With `sun`, each shape says
272
+ * how far into the night its place is, so it can be drawn dimmer there.
263
273
  *
264
274
  * @param places - The places, as {@link cleanPlaces} makes them.
265
275
  * @param view - The picture.
266
276
  * @param look - `beam`, `pin` or `ring`.
267
- * @param options - The size of each name, boxes already used and the most names (16).
277
+ * @param options - The size of each name, boxes already used, the most names (16) and where the Sun is overhead.
268
278
  * @returns The markers to draw and where the names go.
269
279
  *
270
280
  * @example
@@ -277,3 +287,78 @@ export declare function orthoView(pose: Pose & {
277
287
  * ```
278
288
  */
279
289
  export declare function layoutPlaces(places: readonly Place[], view: PlaceView, look: PlaceLook, options?: PlaceLayoutOptions): PlaceLayout;
290
+ /**
291
+ * Places gathered together on the ground: where the group is drawn (the middle of its places, or the place itself when it is alone) and which places of the list are in it.
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * import { groupPlaces, type PlaceGroup } from "@johnmorrisdotca/chikyu-earth/markers";
296
+ *
297
+ * const groups: PlaceGroup[] = groupPlaces([{ id: "a", lon: 0, lat: 0 }], 8);
298
+ * console.log(groups[0]?.members);
299
+ * ```
300
+ */
301
+ export interface PlaceGroup {
302
+ lon: number;
303
+ lat: number;
304
+ /** Indices of its places in the list given, in the list's order. */
305
+ members: number[];
306
+ }
307
+ /**
308
+ * About how many CSS pixels apart two places must be on the screen before they are drawn on their own rather than as one group.
309
+ *
310
+ * @example
311
+ * ```ts
312
+ * import { PLACE_GROUP_PX } from "@johnmorrisdotca/chikyu-earth/markers";
313
+ *
314
+ * console.log(PLACE_GROUP_PX); // 24
315
+ * ```
316
+ */
317
+ export declare const PLACE_GROUP_PX = 24;
318
+ /**
319
+ * The size, in degrees, of the ground's cells that crowded places are gathered in, for an Earth drawn `radius` CSS pixels across: about {@link PLACE_GROUP_PX} on the screen, rounded up to a power of two so the
320
+ * groups change at only a few zooms and stay put while the Earth turns. 0 (gather none) when a cell would be under 1/64 of a degree, about 1.7 km.
321
+ *
322
+ * @param radius - The Earth's radius on the screen, in CSS pixels.
323
+ * @returns The cell's size in degrees, from 1/64 to 32, or 0.
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * import { groupCell } from "@johnmorrisdotca/chikyu-earth/markers";
328
+ *
329
+ * console.log(groupCell(200), groupCell(1_000_000)); // 8 0
330
+ * ```
331
+ */
332
+ export declare function groupCell(radius: number): number;
333
+ /**
334
+ * Gather crowded places: the ground is cut into bands of `cell` degrees of latitude, and each band into cells about as wide on the ground, and the places in one cell become one group drawn at their middle.
335
+ * The cells are fixed to the ground, so the groups turn with the Earth and do not change as it turns. A `here` place is never gathered. Groups come in the order of their first place; a `cell` of 0 leaves every
336
+ * place on its own. Thousands of places cost one pass.
337
+ *
338
+ * @param places - The places, as {@link cleanPlaces} makes them.
339
+ * @param cell - The cell's size in degrees ({@link groupCell}), or 0.
340
+ * @returns The groups, a place on its own being a group of one.
341
+ *
342
+ * @example
343
+ * ```ts
344
+ * import { groupPlaces } from "@johnmorrisdotca/chikyu-earth/markers";
345
+ *
346
+ * const places = [{ id: "a", lon: 139.69, lat: 35.69 }, { id: "b", lon: 139.75, lat: 35.66 }, { id: "c", lon: -0.13, lat: 51.51 }];
347
+ * console.log(groupPlaces(places, 8).map((group) => group.members)); // [[0, 1], [2]]
348
+ * ```
349
+ */
350
+ export declare function groupPlaces(places: readonly Place[], cell: number): PlaceGroup[];
351
+ /**
352
+ * Whether places that crowd are gathered into one ring with their count (the attribute `place-groups`): on unless the value is `off`.
353
+ *
354
+ * @param value - The attribute's value, or null when it is not set.
355
+ * @returns False for `off`, true for anything else.
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * import { readPlaceGroups } from "@johnmorrisdotca/chikyu-earth/markers";
360
+ *
361
+ * console.log(readPlaceGroups(null), readPlaceGroups("off")); // true false
362
+ * ```
363
+ */
364
+ export declare const readPlaceGroups: (value: string | null) => boolean;
@@ -18,20 +18,38 @@ export const PLACE_LOOKS = ["beam", "pin", "ring"];
18
18
  * ```ts
19
19
  * import { MAX_PLACES } from "@johnmorrisdotca/chikyu-earth/markers";
20
20
  *
21
- * console.log(MAX_PLACES);
21
+ * console.log(MAX_PLACES); // 5000
22
22
  * ```
23
23
  */
24
- export const MAX_PLACES = 200;
24
+ export const MAX_PLACES = 5000;
25
25
  const RAD = Math.PI / 180;
26
+ const toUnit = (lon, lat) => [Math.cos(lat * RAD) * Math.sin(lon * RAD), Math.sin(lat * RAD), Math.cos(lat * RAD) * Math.cos(lon * RAD)];
27
+ const dotUnit = (lon, lat, v) => {
28
+ const u = toUnit(lon, lat);
29
+ return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
30
+ };
26
31
  /** A place this close to the Earth's edge (the cosine of its angle from the reader) is left out; up to FADE beyond it, it fades in. */
27
32
  const EDGE = 0.02;
28
33
  const FADE = 0.12;
29
34
  const MARGIN = 60;
30
35
  const SIZES = { here: { length: 46, ring: 9 }, favourite: { length: 28, ring: 6 } };
31
36
  const isObject = (value) => typeof value === "object" && value !== null;
37
+ /** A colour a page may give a place: a hex colour, `rgb()`/`hsl()` with numbers only, or a colour's name. Anything else is left out, so no other CSS gets in. */
38
+ const COLOR = /^(?:#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:rgb|hsl)a?\([0-9.,%\s/+-]{1,60}\)|[a-z]{3,24})$/i;
39
+ /**
40
+ * How far into the night a point is, from the cosine of its angle from the point the Sun is overhead: 0 in daylight, 1 once the Sun is 7 degrees below the horizon, eased between.
41
+ *
42
+ * @param cosine - The cosine of the angle between the point and the sub-solar point.
43
+ * @returns 0 to 1.
44
+ */
45
+ const nightOf = (cosine) => {
46
+ const k = Math.max(0, Math.min(1, (0.05 - cosine) / 0.17));
47
+ return k * k * (3 - 2 * k);
48
+ };
32
49
  /**
33
50
  * The places of a list a page handed over, made safe to draw: each needs a longitude from -180 to 180 and a latitude from -90 to 90; one without an `id` is given its place in the list, a
34
- * label is cut to 80 letters, a kind that is not `here` is `favourite`. Anything else is left out, and at most {@link MAX_PLACES} are kept.
51
+ * label is cut to 80 letters, a kind that is not `here` is `favourite`, and a colour is kept only when it is a hex colour, `rgb()` or `hsl()` with numbers, or a colour's name. Anything else is left out,
52
+ * and at most {@link MAX_PLACES} are kept.
35
53
  *
36
54
  * @param list - What the page gave: an array of places, or anything.
37
55
  * @returns The places to draw.
@@ -40,7 +58,7 @@ const isObject = (value) => typeof value === "object" && value !== null;
40
58
  * ```ts
41
59
  * import { cleanPlaces } from "@johnmorrisdotca/chikyu-earth/markers";
42
60
  *
43
- * console.log(cleanPlaces([{ lon: 2.35, lat: 48.86, label: "Paris" }, { lon: 500, lat: 0 }]));
61
+ * console.log(cleanPlaces([{ lon: 2.35, lat: 48.86, label: "Paris", color: "#e8475f" }, { lon: 500, lat: 0 }]));
44
62
  * ```
45
63
  */
46
64
  export function cleanPlaces(list) {
@@ -59,6 +77,8 @@ export function cleanPlaces(list) {
59
77
  const place = { id: typeof item["id"] === "string" && item["id"] ? item["id"] : String(i), lon, lat, kind: item["kind"] === "here" ? "here" : "favourite" };
60
78
  if (typeof item["label"] === "string" && item["label"].trim())
61
79
  place.label = item["label"].trim().slice(0, 80);
80
+ if (typeof item["color"] === "string" && COLOR.test(item["color"].trim()))
81
+ place.color = item["color"].trim();
62
82
  out.push(place);
63
83
  }
64
84
  return out;
@@ -132,6 +152,7 @@ export function orthoView(pose) {
132
152
  return {
133
153
  width: pose.width,
134
154
  height: pose.height,
155
+ radius: pose.radius,
135
156
  at(lon, lat, out) {
136
157
  const p = project(lon, lat, pose);
137
158
  out.x = p.x;
@@ -146,12 +167,13 @@ export function orthoView(pose) {
146
167
  /**
147
168
  * Where each place's marker and name go in one picture. A place on the far side of the Earth, or off the picture, is left out; one near the Earth's edge fades. The stick stands up from the ground as the picture
148
169
  * sees it, leaning towards the top of the screen where the reader looks straight down on it, so it never shrinks to a dot; the ring at its foot is flattened as the ground is. A `here` place is taller and wider
149
- * than a favourite. Names go at the top of the stick, `here` first and then in the order given, never over one another or over a box in `taken`; a name with no free place is left out.
170
+ * than a favourite. Names go at the top of the stick, `here` first and then in the order given, never over one another or over a box in `taken`; a name with no free place is left out. With `sun`, each shape says
171
+ * how far into the night its place is, so it can be drawn dimmer there.
150
172
  *
151
173
  * @param places - The places, as {@link cleanPlaces} makes them.
152
174
  * @param view - The picture.
153
175
  * @param look - `beam`, `pin` or `ring`.
154
- * @param options - The size of each name, boxes already used and the most names (16).
176
+ * @param options - The size of each name, boxes already used, the most names (16) and where the Sun is overhead.
155
177
  * @returns The markers to draw and where the names go.
156
178
  *
157
179
  * @example
@@ -168,6 +190,7 @@ export function layoutPlaces(places, view, look, options = {}) {
168
190
  const shapes = [];
169
191
  const items = [];
170
192
  const named = [];
193
+ const sun = options.sun ? toUnit(options.sun.lon, options.sun.lat) : null;
171
194
  for (const [index, place] of places.entries()) {
172
195
  if (!view.at(place.lon, place.lat, point) || point.facing <= EDGE)
173
196
  continue;
@@ -200,6 +223,7 @@ export function layoutPlaces(places, view, look, options = {}) {
200
223
  squash: Math.max(0.08, Math.min(1, point.facing)),
201
224
  ring: size.ring,
202
225
  opacity: Math.min(1, (point.facing - EDGE) / FADE),
226
+ night: sun ? nightOf(dotUnit(place.lon, place.lat, sun)) : 0,
203
227
  };
204
228
  shapes.push(shape);
205
229
  const box = place.label ? options.size?.(place, index) : null;
@@ -211,3 +235,108 @@ export function layoutPlaces(places, view, look, options = {}) {
211
235
  const placed = placeLabels(items, view.width, view.height, options.maxLabels ?? 16, 64, options.taken ?? []);
212
236
  return { shapes, labels: placed.map((p) => ({ index: named[p.item], left: p.left, top: p.top })) };
213
237
  }
238
+ /**
239
+ * About how many CSS pixels apart two places must be on the screen before they are drawn on their own rather than as one group.
240
+ *
241
+ * @example
242
+ * ```ts
243
+ * import { PLACE_GROUP_PX } from "@johnmorrisdotca/chikyu-earth/markers";
244
+ *
245
+ * console.log(PLACE_GROUP_PX); // 24
246
+ * ```
247
+ */
248
+ export const PLACE_GROUP_PX = 24;
249
+ /**
250
+ * The size, in degrees, of the ground's cells that crowded places are gathered in, for an Earth drawn `radius` CSS pixels across: about {@link PLACE_GROUP_PX} on the screen, rounded up to a power of two so the
251
+ * groups change at only a few zooms and stay put while the Earth turns. 0 (gather none) when a cell would be under 1/64 of a degree, about 1.7 km.
252
+ *
253
+ * @param radius - The Earth's radius on the screen, in CSS pixels.
254
+ * @returns The cell's size in degrees, from 1/64 to 32, or 0.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * import { groupCell } from "@johnmorrisdotca/chikyu-earth/markers";
259
+ *
260
+ * console.log(groupCell(200), groupCell(1_000_000)); // 8 0
261
+ * ```
262
+ */
263
+ export function groupCell(radius) {
264
+ if (!(radius > 0))
265
+ return 0;
266
+ const degrees = PLACE_GROUP_PX / radius / RAD;
267
+ if (degrees < 1 / 64)
268
+ return 0;
269
+ return 2 ** Math.ceil(Math.log2(Math.min(degrees, 32)));
270
+ }
271
+ /**
272
+ * Gather crowded places: the ground is cut into bands of `cell` degrees of latitude, and each band into cells about as wide on the ground, and the places in one cell become one group drawn at their middle.
273
+ * The cells are fixed to the ground, so the groups turn with the Earth and do not change as it turns. A `here` place is never gathered. Groups come in the order of their first place; a `cell` of 0 leaves every
274
+ * place on its own. Thousands of places cost one pass.
275
+ *
276
+ * @param places - The places, as {@link cleanPlaces} makes them.
277
+ * @param cell - The cell's size in degrees ({@link groupCell}), or 0.
278
+ * @returns The groups, a place on its own being a group of one.
279
+ *
280
+ * @example
281
+ * ```ts
282
+ * import { groupPlaces } from "@johnmorrisdotca/chikyu-earth/markers";
283
+ *
284
+ * const places = [{ id: "a", lon: 139.69, lat: 35.69 }, { id: "b", lon: 139.75, lat: 35.66 }, { id: "c", lon: -0.13, lat: 51.51 }];
285
+ * console.log(groupPlaces(places, 8).map((group) => group.members)); // [[0, 1], [2]]
286
+ * ```
287
+ */
288
+ export function groupPlaces(places, cell) {
289
+ if (!(cell > 0))
290
+ return places.map((place, i) => ({ lon: place.lon, lat: place.lat, members: [i] }));
291
+ const out = [];
292
+ const sums = [];
293
+ const cells = new Map();
294
+ const bands = Math.ceil(180 / cell);
295
+ for (const [i, place] of places.entries()) {
296
+ if (place.kind === "here") {
297
+ out.push({ lon: place.lon, lat: place.lat, members: [i] });
298
+ sums.push([0, 0, 0]);
299
+ continue;
300
+ }
301
+ const band = Math.min(bands - 1, Math.floor((place.lat + 90) / cell));
302
+ const across = Math.max(1, Math.floor((360 * Math.cos((-90 + (band + 0.5) * cell) * RAD)) / cell));
303
+ const key = band * 100_000 + Math.min(across - 1, Math.floor(((place.lon + 180) / 360) * across));
304
+ const u = toUnit(place.lon, place.lat);
305
+ const found = cells.get(key);
306
+ if (found === undefined) {
307
+ cells.set(key, out.length);
308
+ out.push({ lon: place.lon, lat: place.lat, members: [i] });
309
+ sums.push(u);
310
+ }
311
+ else {
312
+ out[found].members.push(i);
313
+ const sum = sums[found];
314
+ sum[0] += u[0];
315
+ sum[1] += u[1];
316
+ sum[2] += u[2];
317
+ }
318
+ }
319
+ for (const [g, group] of out.entries()) {
320
+ if (group.members.length < 2)
321
+ continue;
322
+ const [x, y, z] = sums[g];
323
+ const length = Math.hypot(x, y, z) || 1;
324
+ group.lat = Math.asin(Math.max(-1, Math.min(1, y / length))) / RAD;
325
+ group.lon = Math.atan2(x, z) / RAD;
326
+ }
327
+ return out;
328
+ }
329
+ /**
330
+ * Whether places that crowd are gathered into one ring with their count (the attribute `place-groups`): on unless the value is `off`.
331
+ *
332
+ * @param value - The attribute's value, or null when it is not set.
333
+ * @returns False for `off`, true for anything else.
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * import { readPlaceGroups } from "@johnmorrisdotca/chikyu-earth/markers";
338
+ *
339
+ * console.log(readPlaceGroups(null), readPlaceGroups("off")); // true false
340
+ * ```
341
+ */
342
+ export const readPlaceGroups = (value) => (value ?? "").trim().toLowerCase() !== "off";
@@ -9,7 +9,10 @@ import { type ThreeParts } from "./textures.ts";
9
9
  import { type TileSet, type TileSources } from "./tile-set.ts";
10
10
  import type { SkyFrame } from "../sky/frame.ts";
11
11
  import { type BodyLabelState } from "./body-label.ts";
12
+ import { type PlaceSpriteData } from "../markers/place-sprites.ts";
12
13
  import { type MeteorState } from "../meteors/layer.ts";
14
+ import { type BorderState } from "../borders/layer.ts";
15
+ import { type GridState } from "../grid/layer.ts";
13
16
  export type { ThreeParts };
14
17
  type Three = ThreeParts;
15
18
  /**
@@ -89,6 +92,10 @@ export interface EarthModel {
89
92
  meteors: MeteorState;
90
93
  /** The name written on the Earth (src/realistic/body-label.ts): off unless the element sets it. */
91
94
  bodyLabel: BodyLabelState;
95
+ /** The borders of the countries and of their regions (src/borders/layer.ts): off unless the element switches them on. */
96
+ borders: BorderState;
97
+ /** The meridians and parallels (src/grid/layer.ts): off unless the element switches them on. */
98
+ grid: GridState;
92
99
  }
93
100
  export interface EarthDeps {
94
101
  assets: AssetCache;
@@ -125,6 +132,10 @@ export interface EarthDeps {
125
132
  width: number;
126
133
  height: number;
127
134
  }) => void;
135
+ /** The rings the places' layer wants drawn in one draw call, read right after `onPose`. */
136
+ placeSprites?: () => PlaceSpriteData | null;
137
+ /** Told once, when the rings of the places that are not markers of their own were first wanted: whether the picture can draw them (false when the three.js parts handed over lack `Points`). */
138
+ onPlaceRings?: (drawn: boolean) => void;
128
139
  }
129
140
  export declare const newModel: () => EarthModel;
130
141
  /**
@@ -6,7 +6,11 @@ import { createSatelliteLayer, newSatelliteState } from "../space/satellite-laye
6
6
  import { createTextureSet } from "./textures.js";
7
7
  import { createTileSet } from "./tile-set.js";
8
8
  import { createBodyLabelLayer, newBodyLabelState } from "./body-label.js";
9
+ import { createPlaceSprites } from "../markers/place-sprites.js";
9
10
  import { createMeteorLayer, newMeteorState } from "../meteors/layer.js";
11
+ import { createBorderLayer, newBorderState } from "../borders/layer.js";
12
+ import { createGridLayer, newGridState } from "../grid/layer.js";
13
+ import { pointOnEarth } from "./tiles.js";
10
14
  const RAD = Math.PI / 180;
11
15
  /**
12
16
  * The glow reaches this many radii from the centre; the globe at 1x is drawn to fit inside it.
@@ -40,6 +44,8 @@ export const newModel = () => ({
40
44
  ratio: () => Math.min(globalThis.devicePixelRatio || 1, 2),
41
45
  meteors: newMeteorState(),
42
46
  bodyLabel: newBodyLabelState(),
47
+ borders: newBorderState(),
48
+ grid: newGridState(),
43
49
  });
44
50
  /**
45
51
  * The disc's radius in CSS pixels in a box of `width` x `height` at `zoom`: it fits the glow in the box at 1x.
@@ -186,6 +192,10 @@ export function createEarthItem(model, deps) {
186
192
  let meteors = null;
187
193
  let meteorTimer;
188
194
  let nameOn = null;
195
+ let borders = null;
196
+ let placeSprites = null;
197
+ let placeSpritesTried = false;
198
+ let gridLayer = null;
189
199
  return {
190
200
  scene,
191
201
  camera,
@@ -256,6 +266,47 @@ export function createEarthItem(model, deps) {
256
266
  });
257
267
  }
258
268
  deps.onPose?.({ lon: look.lon, lat: look.lat, radius, cx: size.width / 2 + view.panX, cy: size.height / 2 + view.panY, width: size.width, height: size.height });
269
+ // the borders: made the first time a set is switched on, above the clouds and under the air
270
+ if ((model.borders.countries || model.borders.regions) && !borders && !model.borders.stats.failed) {
271
+ try {
272
+ borders = createBorderLayer(three, turned, model.borders, deps.invalidate, 2.5);
273
+ }
274
+ catch (error) {
275
+ model.borders.stats.failed = true;
276
+ model.borders.onError?.(error);
277
+ }
278
+ }
279
+ if (borders) {
280
+ // the ground the view shows, as a grid of 5 by 5 points across the box, each reaching half a cell's diagonal and a margin for the ground leaning away towards the edge
281
+ const pose = { lon: look.lon, lat: look.lat, width: size.width, height: size.height, panX: view.panX, panY: view.panY, radius };
282
+ const points = [];
283
+ for (let i = 0; i <= 4; i += 1)
284
+ for (let j = 0; j <= 4; j += 1) {
285
+ const at = pointOnEarth(pose, (size.width * i) / 4, (size.height * j) / 4);
286
+ if (at)
287
+ points.push(at);
288
+ }
289
+ borders.sync({ points: points.length > 0 ? points : [look], angle: Math.asin(Math.min(1, (1.4 * Math.hypot(size.width, size.height)) / 8 / radius)) / RAD, radius });
290
+ }
291
+ const spriteData = deps.placeSprites?.() ?? null;
292
+ if (spriteData && !placeSprites && !placeSpritesTried) {
293
+ placeSprites = createPlaceSprites(three, turned, sunDir);
294
+ placeSpritesTried = true;
295
+ // told once: without `Points` the page's layer draws these rings itself
296
+ deps.onPlaceRings?.(placeSprites !== null);
297
+ }
298
+ placeSprites?.sync(spriteData, model.ratio(), size.width, size.height, model.light === "lit");
299
+ // the grid: made the first time it is switched on, over the ground and under the clouds
300
+ if (model.grid.on && !gridLayer && !model.grid.stats.failed) {
301
+ try {
302
+ gridLayer = createGridLayer(three, turned, model.grid, sunDir, 1.5);
303
+ }
304
+ catch (error) {
305
+ model.grid.stats.failed = true;
306
+ model.grid.onError?.(error);
307
+ }
308
+ }
309
+ gridLayer?.sync(radius);
259
310
  if (model.meteors.on && !meteors)
260
311
  meteors = createMeteorLayer(three, turned, model.meteors);
261
312
  if (meteors) {
@@ -274,6 +325,9 @@ export function createEarthItem(model, deps) {
274
325
  clearTimeout(meteorTimer);
275
326
  meteors?.dispose();
276
327
  nameOn?.dispose();
328
+ borders?.dispose();
329
+ placeSprites?.dispose();
330
+ gridLayer?.dispose();
277
331
  model.tiles = null;
278
332
  tiles.dispose();
279
333
  textures.dispose();