@spacexr/tiles 0.0.0-stage → 0.1.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 (119) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +57 -2
  3. package/dist/addressing/index.d.ts +16 -0
  4. package/dist/addressing/index.js +4 -0
  5. package/dist/addressing/index.js.map +1 -0
  6. package/dist/bake/index.d.ts +91 -0
  7. package/dist/bake/index.js +3 -0
  8. package/dist/bake/index.js.map +1 -0
  9. package/dist/celestial-dataset-CUIsplKO.d.ts +99 -0
  10. package/dist/chunk-2HLQXRDD.js +246 -0
  11. package/dist/chunk-2HLQXRDD.js.map +1 -0
  12. package/dist/chunk-6YNCRDEE.js +170 -0
  13. package/dist/chunk-6YNCRDEE.js.map +1 -0
  14. package/dist/chunk-7AWV2IEK.js +79 -0
  15. package/dist/chunk-7AWV2IEK.js.map +1 -0
  16. package/dist/chunk-ESLGXWQR.js +219 -0
  17. package/dist/chunk-ESLGXWQR.js.map +1 -0
  18. package/dist/chunk-FB57CZDK.js +312 -0
  19. package/dist/chunk-FB57CZDK.js.map +1 -0
  20. package/dist/chunk-GRTG4WNA.js +44 -0
  21. package/dist/chunk-GRTG4WNA.js.map +1 -0
  22. package/dist/chunk-HVYN4AIT.js +45 -0
  23. package/dist/chunk-HVYN4AIT.js.map +1 -0
  24. package/dist/chunk-IGNRXAW3.js +77 -0
  25. package/dist/chunk-IGNRXAW3.js.map +1 -0
  26. package/dist/chunk-QGTREKHS.js +145 -0
  27. package/dist/chunk-QGTREKHS.js.map +1 -0
  28. package/dist/chunk-SPDRAY37.js +56 -0
  29. package/dist/chunk-SPDRAY37.js.map +1 -0
  30. package/dist/chunk-TA4BEVHL.js +81 -0
  31. package/dist/chunk-TA4BEVHL.js.map +1 -0
  32. package/dist/chunk-TGOB5HT5.js +149 -0
  33. package/dist/chunk-TGOB5HT5.js.map +1 -0
  34. package/dist/chunk-X6ZJ2PDY.js +104 -0
  35. package/dist/chunk-X6ZJ2PDY.js.map +1 -0
  36. package/dist/chunk-XTY4HCPY.js +22 -0
  37. package/dist/chunk-XTY4HCPY.js.map +1 -0
  38. package/dist/chunk-Y66PNDG2.js +107 -0
  39. package/dist/chunk-Y66PNDG2.js.map +1 -0
  40. package/dist/chunk-YEACOJOC.js +51 -0
  41. package/dist/chunk-YEACOJOC.js.map +1 -0
  42. package/dist/cube/index.d.ts +160 -0
  43. package/dist/cube/index.js +9 -0
  44. package/dist/cube/index.js.map +1 -0
  45. package/dist/datasets/index.d.ts +75 -0
  46. package/dist/datasets/index.js +11 -0
  47. package/dist/datasets/index.js.map +1 -0
  48. package/dist/index.d.ts +22 -0
  49. package/dist/index.js +18 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/mercator/index.d.ts +24 -0
  52. package/dist/mercator/index.js +8 -0
  53. package/dist/mercator/index.js.map +1 -0
  54. package/dist/metrics-HGbzqj6L.d.ts +45 -0
  55. package/dist/pyramid/index.d.ts +156 -0
  56. package/dist/pyramid/index.js +4 -0
  57. package/dist/pyramid/index.js.map +1 -0
  58. package/dist/raster-registration-CgBxrhDB.d.ts +19 -0
  59. package/dist/reference-surface-CsTtrNsc.d.ts +49 -0
  60. package/dist/reprojection/index.d.ts +255 -0
  61. package/dist/reprojection/index.js +6 -0
  62. package/dist/reprojection/index.js.map +1 -0
  63. package/dist/sources/index.d.ts +55 -0
  64. package/dist/sources/index.js +7 -0
  65. package/dist/sources/index.js.map +1 -0
  66. package/dist/surface/index.d.ts +15 -0
  67. package/dist/surface/index.js +4 -0
  68. package/dist/surface/index.js.map +1 -0
  69. package/dist/tile-D-jjIRRA.d.ts +53 -0
  70. package/dist/tile-address-BkfSftp6.d.ts +66 -0
  71. package/dist/tile-http-client-BHZOtGX7.d.ts +73 -0
  72. package/dist/tile-neighbors-LfvV7oiX.d.ts +48 -0
  73. package/dist/tile-surface-s9Zi6X9_.d.ts +40 -0
  74. package/dist/tile-topology-B6xHYqPb.d.ts +51 -0
  75. package/dist/web-mercator-dataset-Dmou8byO.d.ts +125 -0
  76. package/dist/web-tile-source-DrZDBIm6.d.ts +92 -0
  77. package/package.json +122 -5
  78. package/src/addressing/index.ts +8 -0
  79. package/src/addressing/metrics.ts +48 -0
  80. package/src/addressing/raster-registration.ts +22 -0
  81. package/src/addressing/tile-address.ts +130 -0
  82. package/src/addressing/tile-edge-rotation.ts +13 -0
  83. package/src/addressing/tile-neighbors.ts +73 -0
  84. package/src/addressing/tile-surface.ts +44 -0
  85. package/src/addressing/tile-topology.ts +86 -0
  86. package/src/addressing/tile.ts +73 -0
  87. package/src/bake/bake-pyramid.ts +106 -0
  88. package/src/bake/index.ts +2 -0
  89. package/src/bake/pyramid-levels.ts +63 -0
  90. package/src/cube/celestial-dataset.ts +182 -0
  91. package/src/cube/cube-face.ts +51 -0
  92. package/src/cube/cube-geometric-error.ts +30 -0
  93. package/src/cube/cube-mapping.ts +101 -0
  94. package/src/cube/cube-neighbors.ts +198 -0
  95. package/src/cube/cube-tile-surface.ts +30 -0
  96. package/src/cube/index.ts +6 -0
  97. package/src/datasets/index.ts +1 -0
  98. package/src/datasets/tile-dataset.ts +121 -0
  99. package/src/index.ts +9 -0
  100. package/src/mercator/index.ts +3 -0
  101. package/src/mercator/web-mercator-dataset.ts +215 -0
  102. package/src/mercator/web-mercator-tile-metrics.ts +119 -0
  103. package/src/mercator/web-mercator-tile-surface.ts +52 -0
  104. package/src/pyramid/index.ts +2 -0
  105. package/src/pyramid/resident-tiles.ts +81 -0
  106. package/src/pyramid/tile-pyramid.ts +285 -0
  107. package/src/reprojection/cube-resampling.ts +159 -0
  108. package/src/reprojection/index.ts +4 -0
  109. package/src/reprojection/source-projection.ts +196 -0
  110. package/src/reprojection/source-tile-matrix.ts +100 -0
  111. package/src/reprojection/wmts-capabilities.ts +112 -0
  112. package/src/sources/index.ts +4 -0
  113. package/src/sources/tile-http-client.ts +154 -0
  114. package/src/sources/tile-layer-changes.ts +88 -0
  115. package/src/sources/url-template.ts +96 -0
  116. package/src/sources/web-tile-source.ts +73 -0
  117. package/src/surface/directions.ts +27 -0
  118. package/src/surface/index.ts +2 -0
  119. package/src/surface/reference-surface.ts +88 -0
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Address of a tile in a quadtree pyramid, in the XYZ convention.
3
+ *
4
+ * `x` grows eastward and `y` grows southward from the north-west corner, as in
5
+ * Slippy Map, Google and Bing tiles. Use {@link toTmsY} for TMS sources, whose
6
+ * `y` grows northward.
7
+ *
8
+ * A pyramid with several roots, such as a multi-root pyramid of a celestial body, has one quadtree per root, selected by
9
+ * `face`. Single-root pyramids, such as Web Mercator, omit it, which means face 0.
10
+ */
11
+ export interface ITileAddress {
12
+ /** Root of the address, from 0 to {@link MAX_TILE_FACE}; omitted for face 0 of single-root pyramids. */
13
+ face?: number;
14
+ /** Level of detail, also called zoom. Level 0 has a single tile. */
15
+ lod: number;
16
+ x: number;
17
+ y: number;
18
+ }
19
+
20
+ /** Highest root of a tile address: the six faces of a multi-root pyramid are 0 to 5. */
21
+ export const MAX_TILE_FACE = 5;
22
+
23
+ /** Copies the face of `source` onto a new address, leaving it out when `source` has none. */
24
+ function withFace(source: ITileAddress, lod: number, x: number, y: number): ITileAddress {
25
+ return source.face === undefined ? { lod, x, y } : { face: source.face, lod, x, y };
26
+ }
27
+
28
+ /** Text of an address for messages and keys: `lod/x/y`, or `face/lod/x/y` when it has a face. */
29
+ export function formatTileAddress(address: ITileAddress): string {
30
+ const path = `${address.lod}/${address.x}/${address.y}`;
31
+ return address.face === undefined ? path : `${address.face}/${path}`;
32
+ }
33
+
34
+ /**
35
+ * Key of a tile within a pyramid: `lod/x/y`, prefixed by the face when it is not 0, so that an address without a face
36
+ * and an address on face 0 are the same tile. Keys are ephemeral: they are not stable identifiers.
37
+ */
38
+ export function tileAddressKey(address: ITileAddress): string {
39
+ const path = `${address.lod}/${address.x}/${address.y}`;
40
+ return address.face ? `${address.face}/${path}` : path;
41
+ }
42
+
43
+ /** Number of tiles along one axis at a level of detail. */
44
+ export function tileCount(lod: number): number {
45
+ return 2 ** lod;
46
+ }
47
+
48
+ /** Returns `true` when the address lies inside its pyramid level. */
49
+ export function isValidTileAddress(address: ITileAddress): boolean {
50
+ const { face, lod, x, y } = address;
51
+ if (face !== undefined && (!Number.isSafeInteger(face) || face < 0 || face > MAX_TILE_FACE)) return false;
52
+ if (!Number.isSafeInteger(lod) || lod < 0 || lod > 52) return false;
53
+ const count = tileCount(lod);
54
+ return Number.isSafeInteger(x) && Number.isSafeInteger(y) && x >= 0 && y >= 0 && x < count && y < count;
55
+ }
56
+
57
+ /**
58
+ * Throws when the address lies outside its pyramid level.
59
+ *
60
+ * @throws RangeError When the address is invalid.
61
+ */
62
+ export function assertValidTileAddress(address: ITileAddress): void {
63
+ if (!isValidTileAddress(address)) throw new RangeError(`Tile ${formatTileAddress(address)} lies outside its pyramid level.`);
64
+ }
65
+
66
+ /**
67
+ * Converts between XYZ and TMS row numbers. The conversion is its own inverse.
68
+ *
69
+ * @param y - Row number in one convention.
70
+ * @param lod - Level of detail.
71
+ * @returns Row number in the other convention.
72
+ */
73
+ export function toTmsY(y: number, lod: number): number {
74
+ return tileCount(lod) - 1 - y;
75
+ }
76
+
77
+ /**
78
+ * Encodes an address as a Bing Maps quadkey.
79
+ *
80
+ * Each digit encodes one level, from the coarsest: `x` bit plus twice the `y` bit.
81
+ * Level 0 has the empty quadkey.
82
+ */
83
+ export function tileAddressToQuadkey(address: ITileAddress): string {
84
+ assertValidTileAddress(address);
85
+ let quadkey = "";
86
+ for (let level = address.lod; level > 0; level--) {
87
+ const mask = 2 ** (level - 1);
88
+ const digit = (Math.floor(address.x / mask) % 2) + 2 * (Math.floor(address.y / mask) % 2);
89
+ quadkey += String(digit);
90
+ }
91
+ return quadkey;
92
+ }
93
+
94
+ /**
95
+ * Decodes a Bing Maps quadkey.
96
+ *
97
+ * @throws RangeError When the quadkey contains a character other than 0 to 3.
98
+ */
99
+ export function quadkeyToTileAddress(quadkey: string): ITileAddress {
100
+ let x = 0;
101
+ let y = 0;
102
+ for (const character of quadkey) {
103
+ const digit = character.charCodeAt(0) - 48;
104
+ if (digit < 0 || digit > 3) throw new RangeError(`Invalid quadkey digit "${character}" in "${quadkey}".`);
105
+ x = x * 2 + (digit % 2);
106
+ y = y * 2 + Math.floor(digit / 2);
107
+ }
108
+ return { lod: quadkey.length, x, y };
109
+ }
110
+
111
+ /** Returns the parent address, or `undefined` at level 0. The face is kept. */
112
+ export function parentTileAddress(address: ITileAddress): ITileAddress | undefined {
113
+ if (address.lod === 0) return undefined;
114
+ return withFace(address, address.lod - 1, Math.floor(address.x / 2), Math.floor(address.y / 2));
115
+ }
116
+
117
+ /** Returns the ancestor `levels` levels above, clamped to level 0. The face is kept. */
118
+ export function ancestorTileAddress(address: ITileAddress, levels: number): ITileAddress {
119
+ const steps = Math.min(Math.max(0, Math.trunc(levels)), address.lod);
120
+ const scale = 2 ** steps;
121
+ return withFace(address, address.lod - steps, Math.floor(address.x / scale), Math.floor(address.y / scale));
122
+ }
123
+
124
+ /** Returns the four children in north-west, north-east, south-west, south-east order. The face is kept. */
125
+ export function childTileAddresses(address: ITileAddress): [ITileAddress, ITileAddress, ITileAddress, ITileAddress] {
126
+ const lod = address.lod + 1;
127
+ const x = address.x * 2;
128
+ const y = address.y * 2;
129
+ return [withFace(address, lod, x, y), withFace(address, lod, x + 1, y), withFace(address, lod, x, y + 1), withFace(address, lod, x + 1, y + 1)];
130
+ }
@@ -0,0 +1,13 @@
1
+ import { TileNeighbor, type TileEdgeNeighbor } from "./tile-neighbors";
2
+ const EDGE_ORDER: readonly TileEdgeNeighbor[] = [TileNeighbor.N, TileNeighbor.E, TileNeighbor.S, TileNeighbor.W];
3
+ /** Rotate a tile edge in quarter turns within its local frame. */
4
+ export function turnTileEdge(edge: TileEdgeNeighbor, turns: number): TileEdgeNeighbor {
5
+ const index = EDGE_ORDER.indexOf(edge);
6
+ if (index < 0) throw new RangeError(`${TileNeighbor[edge] ?? edge} is not an edge.`);
7
+ return EDGE_ORDER[(((index + turns) % 4) + 4) % 4]!;
8
+ }
9
+
10
+ /** Edge on the other side of a tile. */
11
+ export function oppositeTileEdge(edge: TileEdgeNeighbor): TileEdgeNeighbor {
12
+ return turnTileEdge(edge, 2);
13
+ }
@@ -0,0 +1,73 @@
1
+ import { tileCount, type ITileAddress } from "./tile-address";
2
+
3
+ /**
4
+ * Position around a tile, as the SpaceXR `NeighborsIndex`. The values follow the 3 x 3 layout row-major from the
5
+ * north-west, with the tile itself at the centre:
6
+ *
7
+ * ```text
8
+ * NW N NE 0 1 2
9
+ * W C E 3 4 5
10
+ * SW S SE 6 7 8
11
+ * ```
12
+ */
13
+ export enum TileNeighbor {
14
+ NW = 0,
15
+ N = 1,
16
+ NE = 2,
17
+ W = 3,
18
+ C = 4,
19
+ E = 5,
20
+ SW = 6,
21
+ S = 7,
22
+ SE = 8,
23
+ }
24
+
25
+ /** Neighbours sharing an edge with the tile. */
26
+ export type TileEdgeNeighbor = TileNeighbor.N | TileNeighbor.E | TileNeighbor.S | TileNeighbor.W;
27
+
28
+ /** Neighbours sharing only a corner with the tile. */
29
+ export type TileCornerNeighbor = TileNeighbor.NW | TileNeighbor.NE | TileNeighbor.SE | TileNeighbor.SW;
30
+
31
+ /** Edge neighbours, clockwise from the north. */
32
+ export const TILE_EDGE_NEIGHBORS: readonly TileEdgeNeighbor[] = [TileNeighbor.N, TileNeighbor.E, TileNeighbor.S, TileNeighbor.W];
33
+
34
+ /** Corner neighbours, clockwise from the north-west. */
35
+ export const TILE_CORNER_NEIGHBORS: readonly TileCornerNeighbor[] = [TileNeighbor.NW, TileNeighbor.NE, TileNeighbor.SE, TileNeighbor.SW];
36
+
37
+ /** The two edges meeting at each corner, north or south first. */
38
+ export const TILE_CORNER_EDGES: Readonly<Record<TileCornerNeighbor, readonly [TileEdgeNeighbor, TileEdgeNeighbor]>> = {
39
+ [TileNeighbor.NW]: [TileNeighbor.N, TileNeighbor.W],
40
+ [TileNeighbor.NE]: [TileNeighbor.N, TileNeighbor.E],
41
+ [TileNeighbor.SE]: [TileNeighbor.S, TileNeighbor.E],
42
+ [TileNeighbor.SW]: [TileNeighbor.S, TileNeighbor.W],
43
+ };
44
+
45
+ /** Column and row offsets of each neighbour, in XYZ axes: `x` eastward, `y` southward. */
46
+ export function tileNeighborOffset(neighbor: TileNeighbor): readonly [number, number] {
47
+ return [(neighbor % 3) - 1, Math.floor(neighbor / 3) - 1];
48
+ }
49
+
50
+ export interface ITileNeighborOptions {
51
+ /** Wraps columns around the antimeridian, for pyramids covering every longitude. Defaults to false. */
52
+ wrapX?: boolean;
53
+ }
54
+
55
+ /**
56
+ * Returns the neighbour at the same level of detail, or `undefined` beyond the pyramid. Rows never wrap: there is no
57
+ * tile north of the first row or south of the last one. The face is kept; neighbours across root boundaries are given by the supplied topology.
58
+ */
59
+ export function tileNeighborAddress(address: ITileAddress, neighbor: TileNeighbor, options: ITileNeighborOptions = {}): ITileAddress | undefined {
60
+ const [dx, dy] = tileNeighborOffset(neighbor);
61
+ const count = tileCount(address.lod);
62
+ let x = address.x + dx;
63
+ const y = address.y + dy;
64
+ if (y < 0 || y >= count) return undefined;
65
+ if (options.wrapX) x = ((x % count) + count) % count;
66
+ else if (x < 0 || x >= count) return undefined;
67
+ return address.face === undefined ? { lod: address.lod, x, y } : { face: address.face, lod: address.lod, x, y };
68
+ }
69
+
70
+ /** Returns the nine addresses of {@link TileNeighbor} order, the tile itself at `TileNeighbor.C`. */
71
+ export function tileNeighborAddresses(address: ITileAddress, options: ITileNeighborOptions = {}): Array<ITileAddress | undefined> {
72
+ return Array.from({ length: 9 }, (_, neighbor) => tileNeighborAddress(address, neighbor, options));
73
+ }
@@ -0,0 +1,44 @@
1
+ import type { ICartesian3 } from "@spacexr/geodesy";
2
+
3
+ import type { ITileAddress } from "./tile-address";
4
+
5
+ export type { ICartesian3 };
6
+
7
+ /** How tiles share one shape: tiles of the same `key` are the same shape turned about the `Z` axis by `rotation`. */
8
+ export interface ITileShapeFrame {
9
+ /** Identifies the shape among the tiles of a surface. */
10
+ readonly key: string;
11
+ /** Angle about the `Z` axis from the frame of the shape to the body-fixed frame, in radians. */
12
+ readonly rotation: number;
13
+ }
14
+
15
+ /**
16
+ * Places the tiles of a pyramid on a body: the part of a tiling scheme that geometry needs. Positions are Cartesian,
17
+ * in metres, in the body-fixed frame. Tile coordinates `s` and `t` run in `[0, 1]`, `s` along the tile `x` axis and
18
+ * `t` along its `y` axis.
19
+ */
20
+ export interface ITileSurface {
21
+ /**
22
+ * Point of a tile at a height above the reference surface, along {@link up}.
23
+ *
24
+ * @param height - Height in metres. Defaults to 0.
25
+ * @param target - Receives the point.
26
+ * @throws RangeError When the address does not belong to the surface.
27
+ */
28
+ point(address: ITileAddress, s: number, t: number, height?: number, target?: ICartesian3): ICartesian3;
29
+
30
+ /**
31
+ * Unit vector along which heights move a point of the tile.
32
+ *
33
+ * @param target - Receives the vector.
34
+ * @throws RangeError When the address does not belong to the surface.
35
+ */
36
+ up(address: ITileAddress, s: number, t: number, target?: ICartesian3): ICartesian3;
37
+
38
+ /**
39
+ * Shape shared by a tile with others.
40
+ *
41
+ * @throws RangeError When the address does not belong to the surface.
42
+ */
43
+ shape(address: ITileAddress): ITileShapeFrame;
44
+ }
@@ -0,0 +1,86 @@
1
+ import { tileCount, type ITileAddress } from "./tile-address";
2
+ import { TileNeighbor, tileNeighborAddress } from "./tile-neighbors";
3
+
4
+ /** Neighbour of a tile, with the quarter turns from the frame of the tile to the frame of the neighbour. */
5
+ export interface ITileTopologyNeighbor {
6
+ readonly address: ITileAddress;
7
+ /** 0 when both tiles share a frame; within the pyramid root, 1 to 3 across some face edges. */
8
+ readonly turns: number;
9
+ }
10
+
11
+ /**
12
+ * Area of a tile in another tile, in coordinates of the other tile. A point `(u, v)` of the tile lies at
13
+ * `(west + a * size, north + b * size)`, with `(a, b) = turnedTileCoordinates(u, v, turns)`. The area may lie outside
14
+ * the other tile: only the points the two tiles share are inside it.
15
+ */
16
+ export interface ITileAreaAcross {
17
+ readonly west: number;
18
+ readonly north: number;
19
+ readonly size: number;
20
+ /** Quarter turns from the frame of the tile to the frame of the other tile. */
21
+ readonly turns: number;
22
+ }
23
+
24
+ /** How the tiles of a pyramid connect: the part of a tiling scheme that neighbours and junctions need. */
25
+ export interface ITileTopology {
26
+ /**
27
+ * Neighbour at the same level, or `undefined` beyond the pyramid or at a corner where only 3 tiles meet.
28
+ *
29
+ * @throws RangeError When the address is invalid.
30
+ */
31
+ neighbor(address: ITileAddress, position: TileNeighbor): ITileTopologyNeighbor | undefined;
32
+
33
+ /**
34
+ * Area of a tile in another tile that contains or touches it, for reading the data of a neighbour along a shared
35
+ * edge or corner.
36
+ *
37
+ * @throws RangeError When the two tiles cannot touch.
38
+ */
39
+ areaIn(address: ITileAddress, other: ITileAddress): ITileAreaAcross;
40
+ }
41
+
42
+ /**
43
+ * Coordinates of a point of a tile in a frame turned by quarter turns about the centre of the tile. One turn sends the
44
+ * direction `N` to `E`, so `u`, which grows toward `E`, grows toward `S` in the turned frame.
45
+ */
46
+ export function turnedTileCoordinates(u: number, v: number, turns: number): [number, number] {
47
+ switch (((turns % 4) + 4) % 4) {
48
+ case 1:
49
+ return [1 - v, u];
50
+ case 2:
51
+ return [1 - u, 1 - v];
52
+ case 3:
53
+ return [v, 1 - u];
54
+ default:
55
+ return [u, v];
56
+ }
57
+ }
58
+
59
+ /** Options of {@link flatTileTopology}. */
60
+ export interface IFlatTileTopologyOptions {
61
+ /** Wraps columns around the antimeridian, for pyramids covering every longitude. Defaults to false. */
62
+ wrapX?: boolean;
63
+ }
64
+
65
+ /** Topology of a pyramid with one root, such as Web Mercator: neighbours never turn. */
66
+ export function flatTileTopology(options: IFlatTileTopologyOptions = {}): ITileTopology {
67
+ const wrapX = options.wrapX ?? false;
68
+ return {
69
+ neighbor: (address, position) => {
70
+ const neighbor = tileNeighborAddress(address, position, { wrapX });
71
+ return neighbor && { address: neighbor, turns: 0 };
72
+ },
73
+ areaIn: (address, other) => {
74
+ const scale = 2 ** (address.lod - other.lod);
75
+ const size = 1 / scale;
76
+ let west = address.x / scale - other.x;
77
+ if (wrapX) {
78
+ // Take the side of the antimeridian on which the tiles touch.
79
+ const count = tileCount(other.lod);
80
+ if (west > 1) west -= count;
81
+ else if (west + size < 0) west += count;
82
+ }
83
+ return { west, north: address.y / scale - other.y, size, turns: 0 };
84
+ },
85
+ };
86
+ }
@@ -0,0 +1,73 @@
1
+ import type { ITileMetrics } from "./metrics";
2
+ import { assertValidTileAddress, tileAddressToQuadkey, type ITileAddress } from "./tile-address";
3
+
4
+ /** Geographic extent in degrees. `west` may be greater than `east` only for extents crossing the antimeridian. */
5
+ export interface IGeoBounds {
6
+ west: number;
7
+ south: number;
8
+ east: number;
9
+ north: number;
10
+ }
11
+
12
+ /** Extent in map pixels at the tile level of detail, from the north-west corner of the map. */
13
+ export interface IPixelBounds {
14
+ x: number;
15
+ y: number;
16
+ width: number;
17
+ height: number;
18
+ }
19
+
20
+ /** Tile of a pyramid with its location and optional content. */
21
+ export interface ITile<T> {
22
+ readonly address: ITileAddress;
23
+ readonly quadkey: string;
24
+ /** Identifies the pyramid, for example a source id. Empty by default. */
25
+ readonly namespace: string;
26
+ /** Unique key across pyramids: `namespace:quadkey`. */
27
+ readonly key: string;
28
+ readonly geoBounds: IGeoBounds;
29
+ readonly pixelBounds: IPixelBounds;
30
+ content: T | undefined;
31
+ }
32
+
33
+ /** Returns the geographic extent of a tile. */
34
+ export function tileGeoBounds(address: ITileAddress, metrics: ITileMetrics): IGeoBounds {
35
+ const northWest = metrics.getTileXYToLatLon(address.x, address.y, address.lod);
36
+ const southEast = metrics.getTileXYToLatLon(address.x + 1, address.y + 1, address.lod);
37
+ return { west: northWest.longitude, south: southEast.latitude, east: southEast.longitude, north: northWest.latitude };
38
+ }
39
+
40
+ /** Returns the extent of a tile in map pixels. */
41
+ export function tilePixelBounds(address: ITileAddress, metrics: ITileMetrics): IPixelBounds {
42
+ const origin = metrics.getTileXYToPointXY(address.x, address.y);
43
+ return { x: origin.x, y: origin.y, width: metrics.tileSize, height: metrics.tileSize };
44
+ }
45
+
46
+ /** Immutable location of a tile with mutable content. */
47
+ export class Tile<T> implements ITile<T> {
48
+ public readonly address: ITileAddress;
49
+ public readonly quadkey: string;
50
+ public readonly namespace: string;
51
+ public readonly key: string;
52
+ public readonly geoBounds: IGeoBounds;
53
+ public readonly pixelBounds: IPixelBounds;
54
+ public content: T | undefined;
55
+
56
+ /**
57
+ * @param address - XYZ address.
58
+ * @param metrics - Metrics of the pyramid, used to derive the bounds.
59
+ * @param content - Optional content.
60
+ * @param namespace - Pyramid identifier used in {@link key}.
61
+ * @throws RangeError When the address lies outside its pyramid level.
62
+ */
63
+ public constructor(address: ITileAddress, metrics: ITileMetrics, content?: T, namespace = "") {
64
+ assertValidTileAddress(address);
65
+ this.address = { lod: address.lod, x: address.x, y: address.y };
66
+ this.quadkey = tileAddressToQuadkey(this.address);
67
+ this.namespace = namespace;
68
+ this.key = `${namespace}:${this.quadkey}`;
69
+ this.geoBounds = tileGeoBounds(this.address, metrics);
70
+ this.pixelBounds = tilePixelBounds(this.address, metrics);
71
+ this.content = content;
72
+ }
73
+ }
@@ -0,0 +1,106 @@
1
+ import type { ITileAddress } from "../addressing";
2
+ import type { IDatasetBounds } from "../mercator/web-mercator-dataset";
3
+ import type { WebMercatorTileMetrics } from "../mercator/web-mercator-tile-metrics";
4
+ import { tilesInBounds, type IPyramidLevels } from "./pyramid-levels";
5
+
6
+ /** An image of a tile: rows from the north, columns from the west, 8 bits per channel. */
7
+ export interface IBakedRaster {
8
+ readonly width: number;
9
+ readonly height: number;
10
+ /** 3 for RGB, 4 for RGBA. */
11
+ readonly channels: number;
12
+ readonly data: Uint8Array | Uint8ClampedArray;
13
+ }
14
+
15
+ /** Options of {@link bakePyramid}. */
16
+ export interface IBakePyramidOptions {
17
+ metrics: WebMercatorTileMetrics;
18
+ bounds: IDatasetBounds;
19
+ levels: IPyramidLevels;
20
+ /** The image of a tile, or nothing where the source has none. */
21
+ source(address: ITileAddress, signal?: AbortSignal): Promise<IBakedRaster | undefined>;
22
+ /** The bytes of an image in the format of the pyramid, such as PNG. */
23
+ encode(raster: IBakedRaster): Promise<Uint8Array>;
24
+ /** Writes the file of a tile, at a path relative to the folder of the pyramid ({@link bakedTilePath}). */
25
+ write(path: string, bytes: Uint8Array): Promise<void>;
26
+ /** Extension of the files of the tiles, such as `png`. */
27
+ extension: string;
28
+ /** Tiles baked at once; one at a time by default. */
29
+ concurrency?: number;
30
+ signal?: AbortSignal;
31
+ /** Called after each tile, baked or skipped. */
32
+ onProgress?(done: number, total: number): void;
33
+ }
34
+
35
+ /** What a bake did. */
36
+ export interface IBakePyramidResult {
37
+ /** Tiles written. */
38
+ written: number;
39
+ /** Tiles the source had nothing for, or only transparent texels: no file is written for them. */
40
+ empty: number;
41
+ total: number;
42
+ }
43
+
44
+ /** The URL template of the tiles of a baked pyramid, relative to its descriptor: `./{z}/{x}/{y}.<extension>`. */
45
+ export function bakedTileTemplate(extension: string): string {
46
+ return `./{z}/{x}/{y}.${extension}`;
47
+ }
48
+
49
+ /** The path of the file of a tile of a baked pyramid, relative to its folder: `<lod>/<x>/<y>.<extension>`. */
50
+ export function bakedTilePath(address: ITileAddress, extension: string): string {
51
+ return `${address.lod}/${address.x}/${address.y}.${extension}`;
52
+ }
53
+
54
+ /** Whether every texel of an image is transparent: an image without alpha never is. */
55
+ export function isTransparent(raster: IBakedRaster): boolean {
56
+ if (raster.channels !== 4) return false;
57
+ const { data } = raster;
58
+ for (let i = 3; i < data.length; i += 4) if (data[i] !== 0) return false;
59
+ return true;
60
+ }
61
+
62
+ /** The number of tiles of a pyramid over `bounds`, all its levels. */
63
+ export function pyramidTileCount(metrics: WebMercatorTileMetrics, bounds: IDatasetBounds, levels: IPyramidLevels): number {
64
+ let count = 0;
65
+ for (let lod = levels.minLOD; lod <= levels.maxLOD; lod++) {
66
+ const northWest = metrics.getLatLonToTileXY(bounds.north, bounds.west, lod);
67
+ const southEast = metrics.getLatLonToTileXY(bounds.south, bounds.east, lod);
68
+ count += (southEast.x - northWest.x + 1) * (southEast.y - northWest.y + 1);
69
+ }
70
+ return count;
71
+ }
72
+
73
+ /**
74
+ * Bakes a tile pyramid: asks the source for each tile of `bounds` at each level, encodes it and writes it. A tile the
75
+ * source has nothing for, or only transparent texels, is not written: a reader takes an absent tile as empty. The bake
76
+ * knows no canvas and no file system: the source, the encoder and the writer are given, so it runs in a browser as
77
+ * under Node. Writing the descriptor of the pyramid is left to the caller, after the tiles, so that a pyramid without
78
+ * its descriptor reads as unfinished.
79
+ */
80
+ export async function bakePyramid(options: IBakePyramidOptions): Promise<IBakePyramidResult> {
81
+ const { metrics, bounds, levels, source, encode, write, extension, signal, onProgress } = options;
82
+ const concurrency = options.concurrency ?? 1;
83
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError("concurrency must be a positive integer.");
84
+ const total = pyramidTileCount(metrics, bounds, levels);
85
+ const result: IBakePyramidResult = { written: 0, empty: 0, total };
86
+ let done = 0;
87
+ function* addresses(): Generator<ITileAddress> {
88
+ for (let lod = levels.minLOD; lod <= levels.maxLOD; lod++) yield* tilesInBounds(metrics, bounds, lod);
89
+ }
90
+ const queue = addresses();
91
+ const bakeNext = async (): Promise<void> => {
92
+ for (let next = queue.next(); !next.done; next = queue.next()) {
93
+ signal?.throwIfAborted();
94
+ const address = next.value;
95
+ const raster = await source(address, signal);
96
+ if (!raster || isTransparent(raster)) result.empty++;
97
+ else {
98
+ await write(bakedTilePath(address, extension), await encode(raster));
99
+ result.written++;
100
+ }
101
+ onProgress?.(++done, total);
102
+ }
103
+ };
104
+ await Promise.all(Array.from({ length: concurrency }, () => bakeNext()));
105
+ return result;
106
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./bake-pyramid";
2
+ export * from "./pyramid-levels";
@@ -0,0 +1,63 @@
1
+ import type { ITileAddress } from "../addressing";
2
+ import type { IDatasetBounds } from "../mercator/web-mercator-dataset";
3
+ import type { WebMercatorTileMetrics } from "../mercator/web-mercator-tile-metrics";
4
+
5
+ /** Options of {@link pyramidLevels}. */
6
+ export interface IPyramidLevelsOptions {
7
+ /** The deepest level wanted, such as the deepest level of the imagery the pyramid lies on. */
8
+ finest: number;
9
+ /**
10
+ * How many times wider than the bounds a tile may be and still hold the pyramid: from higher up, its content would
11
+ * be a patch of a few pixels. The coarsest level is the first whose tiles are no wider than that.
12
+ */
13
+ coarsestTileRatio: number;
14
+ /**
15
+ * Ground size of a sample of the source, in metres, for a raster: the pyramid stops at the first level whose pixels
16
+ * are as fine as the source when that level is above `finest`. Absent for a source without a resolution of its own,
17
+ * such as vectors.
18
+ */
19
+ pixelSize?: number;
20
+ }
21
+
22
+ /** The levels of a pyramid, from `minLOD` to `maxLOD`. */
23
+ export interface IPyramidLevels {
24
+ readonly minLOD: number;
25
+ readonly maxLOD: number;
26
+ }
27
+
28
+ /** Width in degrees of longitude of a tile of a level. */
29
+ function tileWidth(lod: number): number {
30
+ return 360 / 2 ** lod;
31
+ }
32
+
33
+ /**
34
+ * The levels a pyramid over `bounds` is built for: from the first level whose tiles are at most `coarsestTileRatio`
35
+ * times as wide as the bounds, down to `finest`, or to the level of the pixel size of a raster source when it is less
36
+ * deep. The level range of `metrics` bounds both.
37
+ */
38
+ export function pyramidLevels(metrics: WebMercatorTileMetrics, bounds: IDatasetBounds, options: IPyramidLevelsOptions): IPyramidLevels {
39
+ const { finest, coarsestTileRatio, pixelSize } = options;
40
+ if (!Number.isInteger(finest)) throw new RangeError("finest must be an integer level.");
41
+ if (!(coarsestTileRatio > 0)) throw new RangeError("coarsestTileRatio must be positive.");
42
+ const extent = Math.max(bounds.east - bounds.west, bounds.north - bounds.south);
43
+ if (!(extent > 0)) throw new RangeError("bounds must have an extent.");
44
+ let deepest = Math.min(finest, metrics.maxLOD);
45
+ if (pixelSize !== undefined) {
46
+ if (!(pixelSize > 0)) throw new RangeError("pixelSize must be a positive number of metres.");
47
+ // The pixels of the source are finest where the bounds are nearest the equator, the case that sets the level.
48
+ const latitude = bounds.south > 0 ? bounds.south : bounds.north < 0 ? bounds.north : 0;
49
+ let lod = metrics.minLOD;
50
+ while (lod < deepest && metrics.groundResolution(latitude, lod) > pixelSize) lod++;
51
+ deepest = lod;
52
+ }
53
+ let coarsest = metrics.minLOD;
54
+ while (coarsest < deepest && tileWidth(coarsest) > coarsestTileRatio * extent) coarsest++;
55
+ return { minLOD: coarsest, maxLOD: deepest };
56
+ }
57
+
58
+ /** The tiles of a level that meet `bounds`, row by row from the north-west. */
59
+ export function* tilesInBounds(metrics: WebMercatorTileMetrics, bounds: IDatasetBounds, lod: number): Generator<ITileAddress> {
60
+ const northWest = metrics.getLatLonToTileXY(bounds.north, bounds.west, lod);
61
+ const southEast = metrics.getLatLonToTileXY(bounds.south, bounds.east, lod);
62
+ for (let y = northWest.y; y <= southEast.y; y++) for (let x = northWest.x; x <= southEast.x; x++) yield { lod, x, y };
63
+ }