@math.gl/geospatial 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/line-simplification.d.ts +7 -0
  2. package/dist/line-simplification.d.ts.map +1 -1
  3. package/dist/line-simplification.js +4 -13
  4. package/dist/line-simplification.js.map +1 -1
  5. package/dist/linear-referencing.d.ts +13 -1
  6. package/dist/linear-referencing.d.ts.map +1 -1
  7. package/dist/linear-referencing.js +29 -9
  8. package/dist/linear-referencing.js.map +1 -1
  9. package/dist/measure-referencing.d.ts +16 -0
  10. package/dist/measure-referencing.d.ts.map +1 -0
  11. package/dist/measure-referencing.js +143 -0
  12. package/dist/measure-referencing.js.map +1 -0
  13. package/dist/polygon-simplification.d.ts +6 -0
  14. package/dist/polygon-simplification.d.ts.map +1 -0
  15. package/dist/polygon-simplification.js +141 -0
  16. package/dist/polygon-simplification.js.map +1 -0
  17. package/dist/spatial-box-clipping.d.ts +9 -0
  18. package/dist/spatial-box-clipping.d.ts.map +1 -0
  19. package/dist/spatial-box-clipping.js +123 -0
  20. package/dist/spatial-box-clipping.js.map +1 -0
  21. package/dist/spatial-dwithin.d.ts +19 -0
  22. package/dist/spatial-dwithin.d.ts.map +1 -0
  23. package/dist/spatial-dwithin.js +107 -0
  24. package/dist/spatial-dwithin.js.map +1 -0
  25. package/dist/spatial-hulls.d.ts +6 -0
  26. package/dist/spatial-hulls.d.ts.map +1 -0
  27. package/dist/spatial-hulls.js +176 -0
  28. package/dist/spatial-hulls.js.map +1 -0
  29. package/dist/spatial-line-intersection-result.d.ts +4 -0
  30. package/dist/spatial-line-intersection-result.d.ts.map +1 -0
  31. package/dist/spatial-line-intersection-result.js +79 -0
  32. package/dist/spatial-line-intersection-result.js.map +1 -0
  33. package/dist/spatial-line-polygon-intersection.d.ts +4 -0
  34. package/dist/spatial-line-polygon-intersection.d.ts.map +1 -0
  35. package/dist/spatial-line-polygon-intersection.js +130 -0
  36. package/dist/spatial-line-polygon-intersection.js.map +1 -0
  37. package/dist/spatial-planar-intersects.d.ts +11 -0
  38. package/dist/spatial-planar-intersects.d.ts.map +1 -1
  39. package/dist/spatial-planar-intersects.js +20 -12
  40. package/dist/spatial-planar-intersects.js.map +1 -1
  41. package/dist/spatial-planar.d.ts +9 -0
  42. package/dist/spatial-planar.d.ts.map +1 -1
  43. package/dist/spatial-planar.js +13 -1
  44. package/dist/spatial-planar.js.map +1 -1
  45. package/dist/spatial-polygon-overlay.d.ts +5 -0
  46. package/dist/spatial-polygon-overlay.d.ts.map +1 -0
  47. package/dist/spatial-polygon-overlay.js +23 -0
  48. package/dist/spatial-polygon-overlay.js.map +1 -0
  49. package/dist/spatial-sql.d.ts +13 -2
  50. package/dist/spatial-sql.d.ts.map +1 -1
  51. package/dist/spatial-sql.js +30 -12
  52. package/dist/spatial-sql.js.map +1 -1
  53. package/dist/spatial-subdivision.d.ts +9 -0
  54. package/dist/spatial-subdivision.d.ts.map +1 -0
  55. package/dist/spatial-subdivision.js +61 -0
  56. package/dist/spatial-subdivision.js.map +1 -0
  57. package/dist/spatial-touches.d.ts +13 -0
  58. package/dist/spatial-touches.d.ts.map +1 -0
  59. package/dist/spatial-touches.js +192 -0
  60. package/dist/spatial-touches.js.map +1 -0
  61. package/dist/st-functions.cjs +2411 -112
  62. package/dist/st-functions.cjs.map +3 -3
  63. package/dist/st-functions.d.ts +67 -2
  64. package/dist/st-functions.d.ts.map +1 -1
  65. package/dist/st-functions.js +195 -12
  66. package/dist/st-functions.js.map +1 -1
  67. package/dist/st-geodesic-functions.d.ts +33 -0
  68. package/dist/st-geodesic-functions.d.ts.map +1 -0
  69. package/dist/st-geodesic-functions.js +84 -0
  70. package/dist/st-geodesic-functions.js.map +1 -0
  71. package/dist/st-hull-functions.cjs +386 -0
  72. package/dist/st-hull-functions.cjs.map +6 -0
  73. package/dist/st-hull-functions.d.ts +17 -0
  74. package/dist/st-hull-functions.d.ts.map +1 -0
  75. package/dist/st-hull-functions.js +14 -0
  76. package/dist/st-hull-functions.js.map +1 -0
  77. package/dist/st-overlay-functions.cjs +621 -0
  78. package/dist/st-overlay-functions.cjs.map +6 -0
  79. package/dist/st-overlay-functions.d.ts +36 -0
  80. package/dist/st-overlay-functions.d.ts.map +1 -0
  81. package/dist/st-overlay-functions.js +183 -0
  82. package/dist/st-overlay-functions.js.map +1 -0
  83. package/dist/st-viewport-functions.cjs +481 -0
  84. package/dist/st-viewport-functions.cjs.map +6 -0
  85. package/dist/st-viewport-functions.d.ts +13 -0
  86. package/dist/st-viewport-functions.d.ts.map +1 -0
  87. package/dist/st-viewport-functions.js +81 -0
  88. package/dist/st-viewport-functions.js.map +1 -0
  89. package/dist/terrain/index.cjs +93 -20
  90. package/dist/terrain/index.cjs.map +3 -3
  91. package/dist/terrain/index.d.ts +1 -0
  92. package/dist/terrain/index.d.ts.map +1 -1
  93. package/dist/terrain/index.js +1 -0
  94. package/dist/terrain/index.js.map +1 -1
  95. package/dist/terrain/regional-watersheds.d.ts +44 -0
  96. package/dist/terrain/regional-watersheds.d.ts.map +1 -0
  97. package/dist/terrain/regional-watersheds.js +108 -0
  98. package/dist/terrain/regional-watersheds.js.map +1 -0
  99. package/dist/terrain/tile-cutout-update.d.ts.map +1 -1
  100. package/dist/terrain/tile-cutout-update.js +28 -22
  101. package/dist/terrain/tile-cutout-update.js.map +1 -1
  102. package/dist/turf-functions.cjs +16 -9
  103. package/dist/turf-functions.cjs.map +1 -1
  104. package/package.json +21 -6
  105. package/src/line-simplification.ts +4 -16
  106. package/src/linear-referencing.ts +44 -16
  107. package/src/measure-referencing.ts +165 -0
  108. package/src/polygon-simplification.ts +185 -0
  109. package/src/spatial-box-clipping.ts +140 -0
  110. package/src/spatial-dwithin.ts +135 -0
  111. package/src/spatial-hulls.ts +203 -0
  112. package/src/spatial-line-intersection-result.ts +93 -0
  113. package/src/spatial-line-polygon-intersection.ts +147 -0
  114. package/src/spatial-planar-intersects.ts +21 -15
  115. package/src/spatial-planar.ts +20 -1
  116. package/src/spatial-polygon-overlay.ts +30 -0
  117. package/src/spatial-sql.ts +47 -12
  118. package/src/spatial-subdivision.ts +75 -0
  119. package/src/spatial-touches.ts +218 -0
  120. package/src/st-functions.ts +283 -15
  121. package/src/st-geodesic-functions.ts +121 -0
  122. package/src/st-hull-functions.ts +25 -0
  123. package/src/st-overlay-functions.ts +244 -0
  124. package/src/st-viewport-functions.ts +98 -0
  125. package/src/terrain/index.ts +7 -0
  126. package/src/terrain/regional-watersheds.ts +153 -0
  127. package/src/terrain/tile-cutout-update.ts +32 -26
@@ -0,0 +1,244 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {WellKnownGeometry} from '@math.gl/core/arrow';
6
+ import type {ScalarFunction} from '@math.gl/sql/arrow';
7
+ import {lineIntersectionResult} from './spatial-line-intersection-result';
8
+ import {intersectLinePolygon} from './spatial-line-polygon-intersection';
9
+ import polygonClipping from 'polygon-clipping';
10
+ import {polygonSet} from './spatial-polygon-overlay';
11
+ import {
12
+ EXTENSION_METADATA,
13
+ EXTENSION_NAME,
14
+ lineKinds,
15
+ nativePolygonResult,
16
+ pointCoordinates,
17
+ pointKinds,
18
+ polygonKinds,
19
+ spatialFunction
20
+ } from './spatial-sql';
21
+
22
+ /** Eight unit directions per quadrant with exact cardinal axes. */
23
+ const unitCircle = /* @__PURE__ */ Array.from({length: 32}, (_, index) => {
24
+ const angle = ((index % 8) * Math.PI) / 16;
25
+ const x = Math.cos(angle);
26
+ const y = Math.sin(angle);
27
+ switch (index >>> 3) {
28
+ case 0:
29
+ return [x, y];
30
+ case 1:
31
+ return [-y, x];
32
+ case 2:
33
+ return [-x, -y];
34
+ default:
35
+ return [y, -x];
36
+ }
37
+ });
38
+
39
+ /** Bounds the number of pieces passed to one polygon union. */
40
+ const corridorUnionFanout = 64;
41
+
42
+ /** Checks the radius for point and line buffers. */
43
+ function checkBufferRadius(radius: number): void {
44
+ if (!Number.isFinite(radius)) throw new Error('ST_Buffer requires a finite radius');
45
+ }
46
+
47
+ /** Checks a generated ring before passing it to the polygon kernel. */
48
+ function checkedRing(ring: polygonClipping.Ring): polygonClipping.Ring {
49
+ if (ring.some(point => !point.every(Number.isFinite))) {
50
+ throw new Error('ST_Buffer produced a nonfinite coordinate');
51
+ }
52
+ return ring;
53
+ }
54
+
55
+ /** Returns a circle approximation with eight segments per quadrant. */
56
+ function circleRing(x: number, y: number, radius: number): polygonClipping.Ring {
57
+ const ring: polygonClipping.Ring = unitCircle.map(([dx, dy]) => [
58
+ x + radius * dx!,
59
+ y + radius * dy!
60
+ ]);
61
+ ring.push(ring[0]!);
62
+ return checkedRing(ring);
63
+ }
64
+
65
+ /** Buffers a point without changing its established output schema. */
66
+ function bufferPoint(point: WellKnownGeometry, radius: number): WellKnownGeometry {
67
+ checkBufferRadius(radius);
68
+ const location = pointCoordinates(point);
69
+ if (!location || radius <= 0) return {type: 'Polygon', coordinates: []};
70
+ return {type: 'Polygon', coordinates: [circleRing(location[0]!, location[1]!, radius)]};
71
+ }
72
+
73
+ /** Unions a bounded group of pieces at a time, then combines groups at each level. */
74
+ function unionCorridorPieces(pieces: polygonClipping.MultiPolygon[]): polygonClipping.MultiPolygon {
75
+ if (!pieces.length) return [];
76
+ while (pieces.length > 1) {
77
+ const groups: polygonClipping.MultiPolygon[] = [];
78
+ for (let first = 0; first < pieces.length; first += corridorUnionFanout) {
79
+ groups.push(
80
+ polygonClipping.union(
81
+ pieces[first]!,
82
+ ...pieces.slice(first + 1, first + corridorUnionFanout)
83
+ )
84
+ );
85
+ }
86
+ pieces = groups;
87
+ }
88
+ return pieces[0]!;
89
+ }
90
+
91
+ /** Buffers line segments with rectangles and adds disks for round joins and caps. */
92
+ function bufferLine(geometry: WellKnownGeometry, radius: number): WellKnownGeometry {
93
+ checkBufferRadius(radius);
94
+ if (radius <= 0) return {type: 'MultiPolygon', coordinates: []};
95
+ const lines =
96
+ geometry.type === 'MultiLineString'
97
+ ? geometry.coordinates
98
+ : geometry.type === 'LineString'
99
+ ? [geometry.coordinates]
100
+ : [];
101
+ const pieces: polygonClipping.MultiPolygon[] = [];
102
+ for (const line of lines) {
103
+ let previous: readonly number[] | undefined;
104
+ for (const coordinate of line) {
105
+ const [x, y] = coordinate as polygonClipping.Pair;
106
+ if (previous && x === previous[0] && y === previous[1]) continue;
107
+ pieces.push([[circleRing(x, y, radius)]]);
108
+ if (previous) {
109
+ const x0 = previous[0]!;
110
+ const y0 = previous[1]!;
111
+ const dx = x - x0;
112
+ const dy = y - y0;
113
+ const length = Math.hypot(dx, dy);
114
+ if (!Number.isFinite(length))
115
+ throw new Error('ST_Buffer produced a nonfinite segment length');
116
+ const nx = (-dy / length) * radius;
117
+ const ny = (dx / length) * radius;
118
+ pieces.push([
119
+ [
120
+ checkedRing([
121
+ [x0 + nx, y0 + ny],
122
+ [x + nx, y + ny],
123
+ [x - nx, y - ny],
124
+ [x0 - nx, y0 - ny],
125
+ [x0 + nx, y0 + ny]
126
+ ])
127
+ ]
128
+ ]);
129
+ }
130
+ previous = coordinate;
131
+ }
132
+ }
133
+ return {type: 'MultiPolygon', coordinates: unionCorridorPieces(pieces)};
134
+ }
135
+
136
+ /** Implements the existing planar point overload. */
137
+ const pointBuffer = /* @__PURE__ */ spatialFunction(
138
+ 'ST_Buffer',
139
+ [pointKinds],
140
+ /* @__PURE__ */ nativePolygonResult('geoarrow.polygon'),
141
+ ([geometry], radius) => bufferPoint(geometry!, radius!),
142
+ 1
143
+ );
144
+
145
+ /** Implements native planar line and multiline buffers with multipart output. */
146
+ const lineBuffer = /* @__PURE__ */ spatialFunction(
147
+ 'ST_Buffer',
148
+ [lineKinds],
149
+ /* @__PURE__ */ nativePolygonResult('geoarrow.multipolygon'),
150
+ ([geometry], radius) => bufferLine(geometry!, radius!),
151
+ 1
152
+ );
153
+
154
+ /** Buffers planar points and native lines with round caps and joins. */
155
+ export const ST_BUFFER: ScalarFunction = {
156
+ ...pointBuffer,
157
+ /** Selects the result schema from the input column's GeoArrow encoding. */
158
+ resolvePrototype(fields) {
159
+ const encoding = fields[0]?.metadata.get(EXTENSION_NAME);
160
+ const buffer =
161
+ encoding === 'geoarrow.linestring' || encoding === 'geoarrow.multilinestring'
162
+ ? lineBuffer
163
+ : pointBuffer;
164
+ return buffer.resolvePrototype!(fields);
165
+ }
166
+ };
167
+
168
+ /** Creates a row-preserving areal overlay with the first geometry's metadata. */
169
+ function polygonOverlay(name: string, operation: typeof polygonClipping.intersection) {
170
+ const spatial = spatialFunction(
171
+ name,
172
+ [polygonKinds, polygonKinds],
173
+ nativePolygonResult('geoarrow.multipolygon'),
174
+ ([left, right]): WellKnownGeometry => {
175
+ const a = polygonSet(left!);
176
+ const b = polygonSet(right!);
177
+ return {type: 'MultiPolygon', coordinates: operation(a, b)};
178
+ }
179
+ );
180
+ return withFirstInputMetadata(spatial);
181
+ }
182
+
183
+ /** Keeps overlay metadata tied to the first argument in either operand order. */
184
+ function withFirstInputMetadata(spatial: ScalarFunction): ScalarFunction {
185
+ return {
186
+ ...spatial,
187
+ /** Preserves the first input's metadata. Overlay does not assign a missing CRS. */
188
+ resolvePrototype(fields: Parameters<NonNullable<typeof spatial.resolvePrototype>>[0]) {
189
+ const result = spatial.resolvePrototype!(fields);
190
+ if (!fields[0]?.metadata.has(EXTENSION_METADATA)) {
191
+ result?.result.metadata.delete(EXTENSION_METADATA);
192
+ }
193
+ return result;
194
+ }
195
+ };
196
+ }
197
+
198
+ /** Binds polygon overlays or mixed-dimensional line clipping from the Arrow schema. */
199
+ function intersection(): ScalarFunction {
200
+ const polygons = polygonOverlay('ST_Intersection', polygonClipping.intersection);
201
+ const output = lineIntersectionResult();
202
+ const linearFirst = spatialFunction(
203
+ 'ST_Intersection',
204
+ [lineKinds, polygonKinds],
205
+ output,
206
+ ([line, area]) => intersectLinePolygon(line!, area!)
207
+ );
208
+ const linearSecond = spatialFunction(
209
+ 'ST_Intersection',
210
+ [polygonKinds, lineKinds],
211
+ output,
212
+ ([area, line]) => intersectLinePolygon(line!, area!)
213
+ );
214
+ return withFirstInputMetadata({
215
+ ...polygons,
216
+ /** A specialized line argument selects a mixed native GeoArrow result before evaluation. */
217
+ resolvePrototype(fields) {
218
+ const a = fields[0]?.metadata.get(EXTENSION_NAME);
219
+ const b = fields[1]?.metadata.get(EXTENSION_NAME);
220
+ if (a === 'geoarrow.linestring' || a === 'geoarrow.multilinestring')
221
+ return linearFirst.resolvePrototype!(fields);
222
+ if (b === 'geoarrow.linestring' || b === 'geoarrow.multilinestring')
223
+ return linearSecond.resolvePrototype!(fields);
224
+ return polygons.resolvePrototype!(fields);
225
+ }
226
+ });
227
+ }
228
+
229
+ /** Intersects two areal geometries or clips a native line by a polygon. */
230
+ export const ST_INTERSECTION = /* @__PURE__ */ intersection();
231
+ /** Returns the portion of the first polygonal geometry outside the second. */
232
+ export const ST_DIFFERENCE = /* @__PURE__ */ polygonOverlay(
233
+ 'ST_Difference',
234
+ polygonClipping.difference
235
+ );
236
+
237
+ /** Returns the combined polygon area as a native GeoArrow MultiPolygon. */
238
+ export const ST_UNION = /* @__PURE__ */ polygonOverlay('ST_Union', polygonClipping.union);
239
+
240
+ /** Returns the area covered by exactly one input as a native GeoArrow MultiPolygon. */
241
+ export const ST_SYMDIFFERENCE = /* @__PURE__ */ polygonOverlay(
242
+ 'ST_SymDifference',
243
+ polygonClipping.xor
244
+ );
@@ -0,0 +1,98 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {Binary, DataType, Field, Schema, Table, vectorFromArray} from 'apache-arrow';
6
+ import type {ScalarFunction, TableFunction} from '@math.gl/sql/arrow';
7
+ import {getGeoArrowFieldInfo, writeWKB} from '@math.gl/core/arrow';
8
+ import {clipGeometryByBox} from './spatial-box-clipping';
9
+ import {subdividePolygons} from './spatial-subdivision';
10
+ import {
11
+ EXTENSION_METADATA,
12
+ EXTENSION_NAME,
13
+ geometryTypes,
14
+ planarGeometry,
15
+ readGeometryValue,
16
+ spatialFunction
17
+ } from './spatial-sql';
18
+
19
+ /** Binds the box clip while limiting output metadata to the geometry being clipped. */
20
+ function makeClipFunction(): ScalarFunction {
21
+ const clip = spatialFunction(
22
+ 'ST_ClipByBox2D',
23
+ [
24
+ [...geometryTypes, 'GeometryCollection'],
25
+ [...geometryTypes, 'GeometryCollection']
26
+ ],
27
+ new Binary(),
28
+ ([geometry, bounds]) => {
29
+ const clipped = clipGeometryByBox(geometry!, bounds!);
30
+ return clipped ? writeWKB(clipped, 'xy') : null;
31
+ }
32
+ );
33
+ return {
34
+ ...clip,
35
+ /** Clips in place in coordinate space, so the bounds cannot supply a missing CRS. */
36
+ resolvePrototype(fields) {
37
+ const prototype = clip.resolvePrototype!(fields);
38
+ if (!fields[0]?.metadata.has(EXTENSION_METADATA)) {
39
+ prototype?.result.metadata.delete(EXTENSION_METADATA);
40
+ }
41
+ return prototype;
42
+ }
43
+ };
44
+ }
45
+
46
+ /** Clips a geometry to the XY bounds of an envelope in the same coordinate system. */
47
+ export const ST_CLIPBYBOX2D = /* @__PURE__ */ makeClipFunction();
48
+
49
+ /** Emits polygon subdivisions through a lateral Arrow SQL join using the default vertex cap. */
50
+ export const ST_SUBDIVIDE: TableFunction = {
51
+ kind: 'table',
52
+ name: 'ST_Subdivide',
53
+ /** Binds one polygon column and declares a GeoArrow WKB output with its CRS. */
54
+ bindLateral({argument, ordinality}) {
55
+ if (ordinality) throw new Error('ST_Subdivide does not support WITH ORDINALITY');
56
+ const extension = getGeoArrowFieldInfo(argument);
57
+ const encoding = extension?.encoding;
58
+ const isWKB =
59
+ encoding === 'geoarrow.wkb' &&
60
+ (DataType.isBinary(argument.type) || DataType.isLargeBinary(argument.type));
61
+ const isPolygon = encoding === 'geoarrow.polygon' || encoding === 'geoarrow.multipolygon';
62
+ if (!isWKB && !(isPolygon && extension?.dimension === 'xy')) {
63
+ throw new Error('ST_Subdivide requires a 2D GeoArrow Polygon or MultiPolygon');
64
+ }
65
+ if (extension?.metadata['edges'] === 'spherical') {
66
+ throw new Error('ST_Subdivide requires planar geometry');
67
+ }
68
+ const type = new Binary();
69
+ const metadata = new Map(argument.metadata);
70
+ metadata.set(EXTENSION_NAME, 'geoarrow.wkb');
71
+ const outputSchema = new Schema([new Field('geometry', type, false, metadata)]);
72
+ return {
73
+ outputSchema,
74
+ /** Outputs polygon parts grouped by their original parent row indices. */
75
+ evaluate(input, {signal}) {
76
+ const values = input.getChild(argument.name)!;
77
+ const active = Uint8Array.from({length: values.length}, (_, row) =>
78
+ Number(values.isValid(row))
79
+ );
80
+ const read = readGeometryValue(values, argument, active, planarGeometry);
81
+ const parts: Uint8Array[] = [];
82
+ const parentRows: number[] = [];
83
+ for (let row = 0; row < values.length; row++) {
84
+ signal?.throwIfAborted();
85
+ if (!active[row]) continue;
86
+ for (const part of subdividePolygons(read(row), signal)) {
87
+ parts.push(writeWKB(part, 'xy'));
88
+ parentRows.push(row);
89
+ }
90
+ }
91
+ return {
92
+ table: new Table(outputSchema, {geometry: vectorFromArray(parts, type)}),
93
+ parentRows: Int32Array.from(parentRows)
94
+ };
95
+ }
96
+ };
97
+ }
98
+ };
@@ -326,3 +326,10 @@ export type {
326
326
  TerrainCutoutPolygonSet,
327
327
  TerrainCutoutRegion
328
328
  } from './cutout-region';
329
+
330
+ export {
331
+ createTerrainRegionalWatersheds,
332
+ type TerrainWatershedTile,
333
+ type TerrainRegionalWatershedOptions,
334
+ type TerrainRegionalWatersheds
335
+ } from './regional-watersheds';
@@ -0,0 +1,153 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {HeightField} from './height-field';
6
+ import {fillTerrainDepressions} from './depression-fill';
7
+ import {
8
+ accumulateTerrainWatersheds,
9
+ type TerrainWatershedAccumulation
10
+ } from './watershed-accumulation';
11
+
12
+ /** A cell-registered tile at an integer offset within a regional affine grid. */
13
+ export type TerrainWatershedTile = {
14
+ /** Column of the tile's first cell. */
15
+ column: number;
16
+ /** Row of the tile's first cell. */
17
+ row: number;
18
+ /** Tile in the regional frame, with its own translated origin. */
19
+ field: HeightField;
20
+ };
21
+
22
+ /** Regional raster dimensions, frame and confirmed outlets. */
23
+ export type TerrainRegionalWatershedOptions = {
24
+ /** Number of columns in the modeled window. */
25
+ width: number;
26
+ /** Number of rows in the modeled window. */
27
+ height: number;
28
+ /** Affine origin of the modeled window. */
29
+ origin: readonly [number, number];
30
+ /** Regional row-major indices of confirmed valid outlets. */
31
+ outlets: readonly number[];
32
+ /** Maximum window cells, including absent tiles. Defaults to 4,194,304. */
33
+ maxCells?: number;
34
+ };
35
+
36
+ /** Conditioning and accumulation over the known cells of a regional window. */
37
+ export type TerrainRegionalWatersheds = TerrainWatershedAccumulation & {
38
+ /** Conditioned grid in the supplied regional frame. */
39
+ field: HeightField;
40
+ /** Regional routing forest: -1 at outlets and -2 for excluded cells. */
41
+ receiver: Int32Array;
42
+ /** Per-cell coverage: 0 for absent, 1 for known nodata, 2 for valid. */
43
+ coverage: Uint8Array;
44
+ /** Valid cells face-connected to an absent cell in the window. */
45
+ touchesUnknown: Uint8Array;
46
+ };
47
+
48
+ /**
49
+ * Condition and accumulate across aligned, nonoverlapping tiles.
50
+ * Missing cells and known nodata block modeled paths. Outside the rectangular
51
+ * window is closed. Results are conditional on known coverage and declared
52
+ * outlets; touchesUnknown identifies components that could change as gaps fill.
53
+ * Storage scales with window area. Use bounded windows for sparse regions.
54
+ */
55
+ export function createTerrainRegionalWatersheds(
56
+ tiles: readonly TerrainWatershedTile[],
57
+ {width, height, origin, outlets, maxCells = 4_194_304}: TerrainRegionalWatershedOptions
58
+ ): TerrainRegionalWatersheds {
59
+ const count = width * height;
60
+ if (
61
+ !Number.isSafeInteger(width) ||
62
+ width < 2 ||
63
+ !Number.isSafeInteger(height) ||
64
+ height < 2 ||
65
+ !Number.isSafeInteger(maxCells) ||
66
+ maxCells < 0 ||
67
+ origin.length !== 2 ||
68
+ !origin.every(Number.isFinite) ||
69
+ count > maxCells ||
70
+ count > 0x7fffffff ||
71
+ !tiles.length
72
+ )
73
+ throw new RangeError('Invalid regional watershed window or cell budget');
74
+ const {columnStep, rowStep, heightReference, diagonal} = tiles[0].field;
75
+ const heights = new Float64Array(count);
76
+ const validity = new Uint8Array(count);
77
+ const coverage = new Uint8Array(count);
78
+ for (const {column, row, field} of tiles) {
79
+ if (
80
+ !Number.isSafeInteger(column) ||
81
+ !Number.isSafeInteger(row) ||
82
+ column < 0 ||
83
+ row < 0 ||
84
+ column + field.width > width ||
85
+ row + field.height > height ||
86
+ field.registration !== 'cell' ||
87
+ field.heightReference !== heightReference ||
88
+ field.diagonal !== diagonal ||
89
+ !origin.every(
90
+ (value, axis) =>
91
+ field.origin[axis] === value + column * columnStep[axis] + row * rowStep[axis] &&
92
+ field.columnStep[axis] === columnStep[axis] &&
93
+ field.rowStep[axis] === rowStep[axis]
94
+ )
95
+ )
96
+ throw new RangeError('Regional watershed tiles must align to the shared cell grid');
97
+ for (let y = 0; y < field.height; y++) {
98
+ for (let x = 0; x < field.width; x++) {
99
+ const index = (row + y) * width + column + x;
100
+ if (coverage[index]) throw new RangeError('Regional watershed tiles overlap');
101
+ const value = field.getHeight(x, y);
102
+ coverage[index] = value === undefined ? 1 : 2;
103
+ if (value !== undefined) {
104
+ heights[index] = value;
105
+ validity[index] = 1;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ const mosaic = new HeightField({
111
+ width,
112
+ height,
113
+ origin,
114
+ columnStep,
115
+ rowStep,
116
+ heightReference,
117
+ diagonal,
118
+ registration: 'cell',
119
+ heights,
120
+ validity
121
+ });
122
+ const {field, receiver} = fillTerrainDepressions(mosaic, {outlets, maxCells});
123
+ const touchesUnknown = new Uint8Array(count);
124
+ const queue = new Int32Array(count);
125
+ let end = 0;
126
+
127
+ /** Mark and enqueue a valid cell once. */
128
+ function mark(index: number): void {
129
+ if (coverage[index] !== 2 || touchesUnknown[index]) return;
130
+ touchesUnknown[index] = 1;
131
+ queue[end++] = index;
132
+ }
133
+
134
+ /** Expand from absent cells into the adjacent known valid domain. */
135
+ function markNeighbors(index: number): void {
136
+ const x = index % width;
137
+ if (x > 0) mark(index - 1);
138
+ if (x + 1 < width) mark(index + 1);
139
+ if (index >= width) mark(index - width);
140
+ if (index < count - width) mark(index + width);
141
+ }
142
+
143
+ for (let i = 0; i < count; i++) if (coverage[i] === 0) markNeighbors(i);
144
+ for (let i = 0; i < end; i++) markNeighbors(queue[i]);
145
+
146
+ return {
147
+ field,
148
+ receiver,
149
+ coverage,
150
+ touchesUnknown,
151
+ ...accumulateTerrainWatersheds(receiver, {maxCells})
152
+ };
153
+ }
@@ -120,6 +120,8 @@ export function updateTerrainTileCutouts(
120
120
  splitTerrainMesh({positions: new Float64Array(), indices: new Uint32Array()}, polygon, limits);
121
121
  const entries = new Map<string, Entry>();
122
122
  const rebuilt: string[] = [];
123
+ /** Rebuilt entries keyed to their position in resident order. */
124
+ const dirty = new Map<Entry, number>();
123
125
  let boundaryCount = 0;
124
126
  for (const resident of residents) {
125
127
  if (
@@ -148,6 +150,7 @@ export function updateTerrainTileCutouts(
148
150
  }
149
151
  entry = {resident: {...resident}, split, displayed: split, bounds, edges};
150
152
  rebuilt.push(resident.id);
153
+ dirty.set(entry, entries.size);
151
154
  }
152
155
  boundaryCount += entry.edges.length;
153
156
  if (boundaryCount > limits.maxBoundaryEdges)
@@ -155,13 +158,13 @@ export function updateTerrainTileCutouts(
155
158
  entries.set(resident.id, entry);
156
159
  }
157
160
  const values = [...entries.values()];
158
- let pairs = 0;
159
- for (let i = 0; i < values.length; i++)
160
- for (let j = i + 1; j < values.length; j++) {
161
- if (++pairs > limits.maxPairChecks)
162
- throw new RangeError('Terrain cutout pair budget exceeded');
163
- const a = values[i],
164
- b = values[j];
161
+ /** Total possible pairs, including pairs already validated by the cache. */
162
+ const pairCount = (values.length * (values.length - 1)) / 2;
163
+ if (pairCount > limits.maxPairChecks) throw new RangeError('Terrain cutout pair budget exceeded');
164
+ // Cached pairs were checked when their current revisions first coexisted.
165
+ for (const [a, index] of dirty)
166
+ for (const b of values) {
167
+ if (a === b || (dirty.get(b) ?? Infinity) < index) continue;
165
168
  if (
166
169
  a.bounds[2] < b.bounds[0] ||
167
170
  b.bounds[2] < a.bounds[0] ||
@@ -169,42 +172,45 @@ export function updateTerrainTileCutouts(
169
172
  b.bounds[3] < a.bounds[1]
170
173
  )
171
174
  continue;
172
- if (
173
- compatible &&
174
- prior.entries.get(a.resident.id) === a &&
175
- prior.entries.get(b.resident.id) === b
176
- )
177
- continue;
178
175
  const combined = assembleTerrainCutoutTiles([a.resident.mesh, b.resident.mesh], limits);
179
176
  validateTerrainCutoutTopology(combined.mesh, combined.remainingWork);
180
177
  }
181
- const boundaries = new Map<string, {edge: Boundary; paired: boolean}>();
182
- const cutKeys = new Map<string, number>();
178
+ /** Unpaired edge, polygon ID for a cut pair, or null for a same-side pair. */
179
+ const boundaries = new Map<string, Boundary | number | null>();
183
180
  for (let tile = 0; tile < values.length; tile++)
184
181
  for (const edge of values[tile].edges) {
185
182
  const other = boundaries.get(edge.key);
186
- if (!other) {
187
- boundaries.set(edge.key, {edge, paired: false});
183
+ if (other === undefined) {
184
+ boundaries.set(edge.key, edge);
188
185
  continue;
189
186
  }
190
- if (other.paired || other.edge.start !== edge.end || other.edge.end !== edge.start)
187
+ if (
188
+ typeof other !== 'object' ||
189
+ other === null ||
190
+ other.start !== edge.end ||
191
+ other.end !== edge.start
192
+ )
191
193
  throw new RangeError('Nonconforming terrain cutout tile boundary');
192
- other.paired = true;
193
- if (other.edge.side !== edge.side) {
194
- cutKeys.set(edge.key, edge.side === 0 ? edge.polygon : other.edge.polygon);
195
- }
194
+ boundaries.set(
195
+ edge.key,
196
+ other.side === edge.side ? null : edge.side === 0 ? edge.polygon : other.polygon
197
+ );
196
198
  }
197
199
  const tiles = new Map<string, TerrainCutout>();
198
200
  const changed: string[] = [];
201
+ /** Scratch endpoints, copied only when a displayed boundary changes. */
202
+ const cuts: [number[], number[]] = [[], []];
203
+ /** Scratch polygon IDs aligned with the scratch endpoints. */
204
+ const polygons: [number[], number[]] = [[], []];
199
205
  for (let i = 0; i < values.length; i++) {
200
206
  const entry = values[i];
201
207
  const old = prior?.entries.get(entry.resident.id);
202
208
  // Emit in cached tile-local order, independent of resident visitation order.
203
- const cuts: [number[], number[]] = [[], []];
204
- const polygons: [number[], number[]] = [[], []];
209
+ cuts[0].length = cuts[1].length = 0;
210
+ polygons[0].length = polygons[1].length = 0;
205
211
  for (const edge of entry.edges) {
206
- const polygonIndex = cutKeys.get(edge.key);
207
- if (polygonIndex !== undefined) {
212
+ const polygonIndex = boundaries.get(edge.key);
213
+ if (typeof polygonIndex === 'number') {
208
214
  cuts[edge.side].push(edge.a, edge.b);
209
215
  polygons[edge.side].push(polygonIndex);
210
216
  }