@math.gl/geometry 5.0.0-beta.7 → 5.0.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,330 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ // The pole of inaccessibility of a polygon is the interior point farthest from its outline, for
6
+ // example the position of a point label. This file finds that point with the grid refinement of
7
+ // Garcia-Castellanos and Lombardo, "Poles of inaccessibility: a calculation algorithm for the
8
+ // remotest places on Earth" (Scottish Geographical Journal 123(3), 2007), in its best-first form.
9
+ // A priority queue holds the candidate squares, ordered by the largest distance that a point in
10
+ // each square can have. The search splits a square into four only if the square can improve the
11
+ // best point by more than the precision.
12
+ //
13
+ // Polygon input can come from an untrusted source, for example a vector tile. Thus the work of
14
+ // the search has a limit. To score one candidate costs one point-to-segment test for each vertex.
15
+ // The search counts these tests against a budget, and returns the best point found when the
16
+ // budget is empty. A caller can share one budget across many polygons, so that many large
17
+ // polygons together cannot block the main thread. The first grid also has at most
18
+ // MAX_GRID_CELLS_PER_AXIS squares along the longer side, and the precision has a floor relative
19
+ // to the size of the polygon.
20
+
21
+ const MAX_GRID_CELLS_PER_AXIS = 64;
22
+ const MIN_RELATIVE_PRECISION = 1e-6;
23
+ /** Default budget for one search: point-to-segment distance tests. */
24
+ export const DEFAULT_POLE_SEARCH_SEGMENT_TESTS = 5e6;
25
+
26
+ /** Remaining work, in point-to-segment distance tests, shared by the searches that use it. */
27
+ export type PoleSearchBudget = {
28
+ segmentTests: number;
29
+ };
30
+
31
+ /**
32
+ * Returns the point inside a polygon farthest from its outline, to within `precision` in the
33
+ * polygon's units. `polygon` is GeoJSON-style: an outer ring followed by hole rings. Coordinates
34
+ * must be planar.
35
+ *
36
+ * The search spends at most `budget.segmentTests` point-to-segment distance tests and deducts
37
+ * what it spends, so one budget can bound several searches. When the budget runs out, the best
38
+ * point found so far is returned. The returned point is always strictly inside the polygon: not
39
+ * in a hole and not on an edge.
40
+ *
41
+ * Returns null for a polygon without vertices, with a non-finite coordinate, or with no area, and
42
+ * when the budget runs out before the search finds a point inside the polygon.
43
+ */
44
+ export function getPoleOfInaccessibility(
45
+ polygon: number[][][],
46
+ precision: number,
47
+ budget: PoleSearchBudget = {
48
+ segmentTests: DEFAULT_POLE_SEARCH_SEGMENT_TESTS
49
+ }
50
+ ): [number, number] | null {
51
+ const outline = polygon[0];
52
+ if (!outline || outline.length === 0) {
53
+ return null;
54
+ }
55
+ const vertexCount = countFiniteVertices(polygon);
56
+ if (vertexCount < 0) {
57
+ return null;
58
+ }
59
+
60
+ const box = getRingBox(outline);
61
+ const width = box.right - box.left;
62
+ const height = box.top - box.bottom;
63
+ if (width === 0 || height === 0) {
64
+ return null;
65
+ }
66
+ const longSide = Math.max(width, height);
67
+ const minTolerance = longSide * MIN_RELATIVE_PRECISION;
68
+ const tolerance = Math.max(
69
+ Number.isFinite(precision) && precision > 0 ? precision : 0,
70
+ minTolerance
71
+ );
72
+
73
+ const search = new PoleSearch(polygon, vertexCount, budget);
74
+
75
+ // Two cheap first guesses: the area centroid, which is inside most convex-ish shapes, and the
76
+ // middle of the bounding box.
77
+ const [centroidX, centroidY] = getAreaCentroid(polygon[0]);
78
+ if (!search.score(centroidX, centroidY, 0)) {
79
+ return null;
80
+ }
81
+ if (!search.score(box.left + width / 2, box.bottom + height / 2, 0)) {
82
+ return search.bestPoint();
83
+ }
84
+
85
+ // The first grid uses squares as wide as the polygon's short side, so a long, thin polygon is
86
+ // covered by squares that fit it. The cap keeps a sliver from starting with millions of them.
87
+ const side = Math.max(Math.min(width, height), longSide / MAX_GRID_CELLS_PER_AXIS);
88
+ const columns = Math.ceil(width / side);
89
+ const rows = Math.ceil(height / side);
90
+ for (let column = 0; column < columns; column++) {
91
+ for (let row = 0; row < rows; row++) {
92
+ const x = box.left + (column + 0.5) * side;
93
+ const y = box.bottom + (row + 0.5) * side;
94
+ if (!search.score(x, y, side / 2)) {
95
+ return search.bestPoint();
96
+ }
97
+ }
98
+ }
99
+
100
+ search.refine(tolerance, minTolerance);
101
+ return search.bestPoint();
102
+ }
103
+
104
+ /** Returns the number of vertices in all rings, or -1 if any coordinate is not finite. */
105
+ function countFiniteVertices(polygon: number[][][]): number {
106
+ let count = 0;
107
+ for (const ring of polygon) {
108
+ for (const point of ring) {
109
+ if (!Number.isFinite(point[0]) || !Number.isFinite(point[1])) {
110
+ return -1;
111
+ }
112
+ }
113
+ count += ring.length;
114
+ }
115
+ return count;
116
+ }
117
+
118
+ function getRingBox(ring: number[][]): {
119
+ left: number;
120
+ bottom: number;
121
+ right: number;
122
+ top: number;
123
+ } {
124
+ let left = Infinity;
125
+ let bottom = Infinity;
126
+ let right = -Infinity;
127
+ let top = -Infinity;
128
+ for (const point of ring) {
129
+ left = Math.min(left, point[0]);
130
+ right = Math.max(right, point[0]);
131
+ bottom = Math.min(bottom, point[1]);
132
+ top = Math.max(top, point[1]);
133
+ }
134
+ return {left, bottom, right, top};
135
+ }
136
+
137
+ /** The centroid of the area a ring encloses, or its first vertex when that area is zero. */
138
+ function getAreaCentroid(ring: number[][]): [number, number] {
139
+ let twiceArea = 0;
140
+ let sumX = 0;
141
+ let sumY = 0;
142
+ let previous = ring[ring.length - 1];
143
+ for (const current of ring) {
144
+ const cross = previous[0] * current[1] - current[0] * previous[1];
145
+ twiceArea += cross;
146
+ sumX += (previous[0] + current[0]) * cross;
147
+ sumY += (previous[1] + current[1]) * cross;
148
+ previous = current;
149
+ }
150
+ if (twiceArea === 0) {
151
+ return [ring[0][0], ring[0][1]];
152
+ }
153
+ return [sumX / (3 * twiceArea), sumY / (3 * twiceArea)];
154
+ }
155
+
156
+ /**
157
+ * The state of one search: the best point so far and a max-heap of candidate squares. The
158
+ * squares are kept in parallel arrays, and the heap holds their indices, ordered by `reach`.
159
+ */
160
+ class PoleSearch {
161
+ private readonly polygon: number[][][];
162
+ private readonly vertexCount: number;
163
+ private readonly budget: PoleSearchBudget;
164
+
165
+ private readonly centerX: number[] = [];
166
+ private readonly centerY: number[] = [];
167
+ private readonly halfSide: number[] = [];
168
+ /** The largest distance to the outline that any point of the square can have. */
169
+ private readonly reach: number[] = [];
170
+ private readonly heap: number[] = [];
171
+
172
+ private bestX = NaN;
173
+ private bestY = NaN;
174
+ private bestDistance = -Infinity;
175
+
176
+ constructor(polygon: number[][][], vertexCount: number, budget: PoleSearchBudget) {
177
+ this.polygon = polygon;
178
+ this.vertexCount = vertexCount;
179
+ this.budget = budget;
180
+ }
181
+
182
+ /** The best point so far, or null if no scored point is inside the polygon. */
183
+ bestPoint(): [number, number] | null {
184
+ return this.bestDistance > 0 ? [this.bestX, this.bestY] : null;
185
+ }
186
+
187
+ /**
188
+ * Scores the square centered at (x, y), keeps its center if it is the best so far, and queues
189
+ * the square if it has area. Returns false, without scoring, when the budget cannot pay.
190
+ */
191
+ score(x: number, y: number, half: number): boolean {
192
+ if (this.budget.segmentTests < this.vertexCount) {
193
+ return false;
194
+ }
195
+ this.budget.segmentTests -= this.vertexCount;
196
+ const distance = getSignedOutlineDistance(this.polygon, x, y);
197
+ if (distance > this.bestDistance) {
198
+ this.bestX = x;
199
+ this.bestY = y;
200
+ this.bestDistance = distance;
201
+ }
202
+ if (half > 0) {
203
+ // No point in the square is farther from the center than half its diagonal.
204
+ this.enqueue(x, y, half, distance + half * Math.SQRT2);
205
+ }
206
+ return true;
207
+ }
208
+
209
+ /**
210
+ * Splits the most promising squares until none can beat the best point by `tolerance`. While no
211
+ * scored point is inside the polygon, `tolerance` does not apply: the search continues while a
212
+ * square can hold an inside point and is larger than `minTolerance`.
213
+ */
214
+ refine(tolerance: number, minTolerance: number): void {
215
+ while (this.heap.length > 0) {
216
+ const index = this.dequeue();
217
+ const reach = this.reach[index];
218
+ if (this.bestDistance > 0 ? reach - this.bestDistance <= tolerance : reach <= 0) {
219
+ // The heap is ordered by reach, so no remaining square can do better either.
220
+ return;
221
+ }
222
+ if (this.bestDistance <= 0 && this.halfSide[index] * Math.SQRT2 <= minTolerance) {
223
+ // The square is too small to search further. Larger squares can remain in the heap.
224
+ continue;
225
+ }
226
+ const quarter = this.halfSide[index] / 2;
227
+ const x = this.centerX[index];
228
+ const y = this.centerY[index];
229
+ if (
230
+ !this.score(x - quarter, y - quarter, quarter) ||
231
+ !this.score(x + quarter, y - quarter, quarter) ||
232
+ !this.score(x - quarter, y + quarter, quarter) ||
233
+ !this.score(x + quarter, y + quarter, quarter)
234
+ ) {
235
+ return;
236
+ }
237
+ }
238
+ }
239
+
240
+ private enqueue(x: number, y: number, half: number, reach: number): void {
241
+ const index = this.reach.length;
242
+ this.centerX.push(x);
243
+ this.centerY.push(y);
244
+ this.halfSide.push(half);
245
+ this.reach.push(reach);
246
+
247
+ const {heap} = this;
248
+ let slot = heap.length;
249
+ heap.push(index);
250
+ while (slot > 0) {
251
+ const parentSlot = (slot - 1) >> 1;
252
+ if (this.reach[heap[parentSlot]] >= reach) {
253
+ break;
254
+ }
255
+ heap[slot] = heap[parentSlot];
256
+ slot = parentSlot;
257
+ }
258
+ heap[slot] = index;
259
+ }
260
+
261
+ private dequeue(): number {
262
+ const {heap, reach} = this;
263
+ const top = heap[0];
264
+ const moved = heap.pop() as number;
265
+ const size = heap.length;
266
+ if (size === 0) {
267
+ return top;
268
+ }
269
+ let slot = 0;
270
+ for (;;) {
271
+ let next = slot * 2 + 1;
272
+ if (next >= size) {
273
+ break;
274
+ }
275
+ if (next + 1 < size && reach[heap[next + 1]] > reach[heap[next]]) {
276
+ next += 1;
277
+ }
278
+ if (reach[heap[next]] <= reach[moved]) {
279
+ break;
280
+ }
281
+ heap[slot] = heap[next];
282
+ slot = next;
283
+ }
284
+ heap[slot] = moved;
285
+ return top;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Distance from (x, y) to the nearest edge of any ring: positive inside the polygon, negative
291
+ * outside, and 0 on an edge. Inside is decided by the even-odd rule, so holes count as outside.
292
+ */
293
+ function getSignedOutlineDistance(polygon: number[][][], x: number, y: number): number {
294
+ let nearestSquared = Infinity;
295
+ let crossings = 0;
296
+ for (const ring of polygon) {
297
+ let start = ring[ring.length - 1];
298
+ for (const end of ring) {
299
+ // Count edges that cross the horizontal ray from (x, y) toward +x.
300
+ if (start[1] <= y !== end[1] <= y) {
301
+ const t = (y - start[1]) / (end[1] - start[1]);
302
+ if (start[0] + t * (end[0] - start[0]) > x) {
303
+ crossings++;
304
+ }
305
+ }
306
+ nearestSquared = Math.min(nearestSquared, getSquaredSegmentDistance(x, y, start, end));
307
+ start = end;
308
+ }
309
+ }
310
+ if (nearestSquared === 0) {
311
+ return 0;
312
+ }
313
+ const distance = Math.sqrt(nearestSquared);
314
+ return crossings % 2 === 1 ? distance : -distance;
315
+ }
316
+
317
+ /** Squared distance from (x, y) to the segment from `start` to `end`. */
318
+ function getSquaredSegmentDistance(x: number, y: number, start: number[], end: number[]): number {
319
+ const edgeX = end[0] - start[0];
320
+ const edgeY = end[1] - start[1];
321
+ const lengthSquared = edgeX * edgeX + edgeY * edgeY;
322
+ // Where the perpendicular from (x, y) meets the edge's line, as a fraction of the edge.
323
+ const along =
324
+ lengthSquared === 0
325
+ ? 0
326
+ : Math.max(0, Math.min(1, ((x - start[0]) * edgeX + (y - start[1]) * edgeY) / lengthSquared));
327
+ const offsetX = start[0] + along * edgeX - x;
328
+ const offsetY = start[1] + along * edgeY - y;
329
+ return offsetX * offsetX + offsetY * offsetY;
330
+ }