@math.gl/geometry 5.0.0-beta.1 → 5.0.0-beta.10

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 (140) hide show
  1. package/README.md +61 -0
  2. package/THIRD-PARTY-NOTICES.md +1 -1
  3. package/dist/color/color-lut-types.d.ts +16 -0
  4. package/dist/color/color-lut-types.d.ts.map +1 -0
  5. package/dist/color/color-lut-types.js +5 -0
  6. package/dist/color/color-lut-types.js.map +1 -0
  7. package/dist/color/index.cjs +132 -0
  8. package/dist/color/index.cjs.map +6 -0
  9. package/dist/color/index.d.ts +4 -0
  10. package/dist/color/index.d.ts.map +1 -0
  11. package/dist/color/index.js +5 -0
  12. package/dist/color/index.js.map +1 -0
  13. package/dist/color/sample-lut.d.ts +13 -0
  14. package/dist/color/sample-lut.d.ts.map +1 -0
  15. package/dist/color/sample-lut.js +132 -0
  16. package/dist/color/sample-lut.js.map +1 -0
  17. package/dist/culling/bounds.d.ts +20 -0
  18. package/dist/culling/bounds.d.ts.map +1 -0
  19. package/dist/culling/bounds.js +121 -0
  20. package/dist/culling/bounds.js.map +1 -0
  21. package/dist/culling/frustum-planes.d.ts +5 -0
  22. package/dist/culling/frustum-planes.d.ts.map +1 -0
  23. package/dist/culling/frustum-planes.js +37 -0
  24. package/dist/culling/frustum-planes.js.map +1 -0
  25. package/dist/culling/geometric-queries.d.ts +34 -0
  26. package/dist/culling/geometric-queries.d.ts.map +1 -0
  27. package/dist/culling/geometric-queries.js +208 -0
  28. package/dist/culling/geometric-queries.js.map +1 -0
  29. package/dist/culling/index.cjs +944 -508
  30. package/dist/culling/index.cjs.map +3 -3
  31. package/dist/culling/index.d.ts +7 -1
  32. package/dist/culling/index.d.ts.map +1 -1
  33. package/dist/culling/index.js +4 -0
  34. package/dist/culling/index.js.map +1 -1
  35. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts +3 -3
  36. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts.map +1 -1
  37. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js +25 -8
  38. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js.map +1 -1
  39. package/dist/culling/lib/culling-volume.d.ts +3 -0
  40. package/dist/culling/lib/culling-volume.d.ts.map +1 -1
  41. package/dist/culling/lib/culling-volume.js +7 -0
  42. package/dist/culling/lib/culling-volume.js.map +1 -1
  43. package/dist/culling/lib/ray.d.ts +5 -0
  44. package/dist/culling/lib/ray.d.ts.map +1 -1
  45. package/dist/culling/lib/ray.js +21 -0
  46. package/dist/culling/lib/ray.js.map +1 -1
  47. package/dist/culling/screen-ray.d.ts +22 -0
  48. package/dist/culling/screen-ray.d.ts.map +1 -0
  49. package/dist/culling/screen-ray.js +55 -0
  50. package/dist/culling/screen-ray.js.map +1 -0
  51. package/dist/curves/adaptive-sampling.d.ts +16 -0
  52. package/dist/curves/adaptive-sampling.d.ts.map +1 -0
  53. package/dist/curves/adaptive-sampling.js +59 -0
  54. package/dist/curves/adaptive-sampling.js.map +1 -0
  55. package/dist/curves/index.d.ts +4 -0
  56. package/dist/curves/index.d.ts.map +1 -1
  57. package/dist/curves/index.js +2 -0
  58. package/dist/curves/index.js.map +1 -1
  59. package/dist/curves/parallel-transport.d.ts +12 -0
  60. package/dist/curves/parallel-transport.d.ts.map +1 -0
  61. package/dist/curves/parallel-transport.js +83 -0
  62. package/dist/curves/parallel-transport.js.map +1 -0
  63. package/dist/index.cjs +1922 -817
  64. package/dist/index.cjs.map +3 -3
  65. package/dist/index.d.ts +15 -3
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +8 -1
  68. package/dist/index.js.map +1 -1
  69. package/dist/lighting/index.cjs +175 -0
  70. package/dist/lighting/index.cjs.map +6 -0
  71. package/dist/lighting/index.d.ts +4 -0
  72. package/dist/lighting/index.d.ts.map +1 -0
  73. package/dist/lighting/index.js +5 -0
  74. package/dist/lighting/index.js.map +1 -0
  75. package/dist/lighting/lighting-types.d.ts +16 -0
  76. package/dist/lighting/lighting-types.d.ts.map +1 -0
  77. package/dist/lighting/lighting-types.js +5 -0
  78. package/dist/lighting/lighting-types.js.map +1 -0
  79. package/dist/lighting/photometry.d.ts +36 -0
  80. package/dist/lighting/photometry.d.ts.map +1 -0
  81. package/dist/lighting/photometry.js +181 -0
  82. package/dist/lighting/photometry.js.map +1 -0
  83. package/dist/polygon/earcut.d.ts.map +1 -1
  84. package/dist/polygon/earcut.js +100 -34
  85. package/dist/polygon/earcut.js.map +1 -1
  86. package/dist/polygon/index.d.ts +2 -0
  87. package/dist/polygon/index.d.ts.map +1 -1
  88. package/dist/polygon/index.js +1 -0
  89. package/dist/polygon/index.js.map +1 -1
  90. package/dist/polygon/pole-of-inaccessibility.d.ts +21 -0
  91. package/dist/polygon/pole-of-inaccessibility.d.ts.map +1 -0
  92. package/dist/polygon/pole-of-inaccessibility.js +285 -0
  93. package/dist/polygon/pole-of-inaccessibility.js.map +1 -0
  94. package/dist/polygon/subdivide-triangle-mesh.d.ts +10 -0
  95. package/dist/polygon/subdivide-triangle-mesh.d.ts.map +1 -1
  96. package/dist/polygon/subdivide-triangle-mesh.js +13 -3
  97. package/dist/polygon/subdivide-triangle-mesh.js.map +1 -1
  98. package/dist/utils/compose-attribute-provenance.d.ts +13 -0
  99. package/dist/utils/compose-attribute-provenance.d.ts.map +1 -0
  100. package/dist/utils/compose-attribute-provenance.js +63 -0
  101. package/dist/utils/compose-attribute-provenance.js.map +1 -0
  102. package/dist/utils/project-bounds.d.ts +44 -0
  103. package/dist/utils/project-bounds.d.ts.map +1 -0
  104. package/dist/utils/project-bounds.js +93 -0
  105. package/dist/utils/project-bounds.js.map +1 -0
  106. package/dist/utils/project-texture-coordinates.d.ts +19 -0
  107. package/dist/utils/project-texture-coordinates.d.ts.map +1 -0
  108. package/dist/utils/project-texture-coordinates.js +49 -0
  109. package/dist/utils/project-texture-coordinates.js.map +1 -0
  110. package/dist/utils/qualify-surface-transition.d.ts +21 -0
  111. package/dist/utils/qualify-surface-transition.d.ts.map +1 -0
  112. package/dist/utils/qualify-surface-transition.js +140 -0
  113. package/dist/utils/qualify-surface-transition.js.map +1 -0
  114. package/package.json +15 -3
  115. package/src/color/color-lut-types.ts +19 -0
  116. package/src/color/index.ts +6 -0
  117. package/src/color/sample-lut.ts +175 -0
  118. package/src/culling/bounds.ts +152 -0
  119. package/src/culling/frustum-planes.ts +41 -0
  120. package/src/culling/geometric-queries.ts +299 -0
  121. package/src/culling/index.ts +39 -1
  122. package/src/culling/lib/bounding-volumes/axis-aligned-bounding-box.ts +26 -8
  123. package/src/culling/lib/culling-volume.ts +9 -1
  124. package/src/culling/lib/ray.ts +21 -0
  125. package/src/culling/screen-ray.ts +75 -0
  126. package/src/curves/adaptive-sampling.ts +85 -0
  127. package/src/curves/index.ts +4 -0
  128. package/src/curves/parallel-transport.ts +104 -0
  129. package/src/index.ts +51 -0
  130. package/src/lighting/index.ts +10 -0
  131. package/src/lighting/lighting-types.ts +20 -0
  132. package/src/lighting/photometry.ts +264 -0
  133. package/src/polygon/earcut.ts +98 -37
  134. package/src/polygon/index.ts +6 -0
  135. package/src/polygon/pole-of-inaccessibility.ts +330 -0
  136. package/src/polygon/subdivide-triangle-mesh.ts +22 -2
  137. package/src/utils/compose-attribute-provenance.ts +74 -0
  138. package/src/utils/project-bounds.ts +154 -0
  139. package/src/utils/project-texture-coordinates.ts +67 -0
  140. package/src/utils/qualify-surface-transition.ts +169 -0
@@ -33,7 +33,7 @@
33
33
  /* eslint-disable */
34
34
 
35
35
  import type {NumericArray} from '@math.gl/core';
36
- import {getPolygonSignedArea, DimIndex, Plane2D} from './polygon-utils';
36
+ import {DimIndex, Plane2D} from './polygon-utils';
37
37
 
38
38
  /**
39
39
  * Computes a triangulation of a polygon
@@ -51,6 +51,25 @@ export function earcut(
51
51
  areas?: NumericArray,
52
52
  plane: Plane2D = 'xy'
53
53
  ): number[] {
54
+ // Keep nested calls from numeric array getters isolated.
55
+ const savedIndex = vertexPoolIndex;
56
+ const savedQueue = activeHoleQueue;
57
+ if (!holeQueues[callDepth]) holeQueues[callDepth] = [];
58
+ activeHoleQueue = holeQueues[callDepth];
59
+ callDepth++;
60
+ try {
61
+ return triangulate(positions, holeIndices, dim, areas, plane);
62
+ } finally {
63
+ activeHoleQueue.length = 0;
64
+ activeHoleQueue = savedQueue;
65
+ vertexPoolIndex = savedIndex;
66
+ callDepth--;
67
+ // Do not retain arbitrarily large object graphs after a one-off polygon.
68
+ if (callDepth === 0 && vertexPool.length > 65536) vertexPool.length = 0;
69
+ }
70
+ }
71
+
72
+ function triangulate(positions, holeIndices, dim, areas, plane): number[] {
54
73
  const hasHoles = holeIndices && holeIndices.length;
55
74
  const outerLen = hasHoles ? holeIndices[0] * dim : positions.length;
56
75
  let outerNode = linkedList(positions, 0, outerLen, dim, true, areas && areas[0], plane);
@@ -70,12 +89,14 @@ export function earcut(
70
89
 
71
90
  // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
72
91
  if (positions.length > 80 * dim) {
73
- minX = maxX = positions[0];
74
- minY = maxY = positions[1];
92
+ const i0 = DimIndex[plane[0]];
93
+ const i1 = DimIndex[plane[1]];
94
+ minX = maxX = positions[i0];
95
+ minY = maxY = positions[i1];
75
96
 
76
97
  for (let i = dim; i < outerLen; i += dim) {
77
- x = positions[i];
78
- y = positions[i + 1];
98
+ x = positions[i + i0];
99
+ y = positions[i + i1];
79
100
  if (x < minX) minX = x;
80
101
  if (y < minY) minY = y;
81
102
  if (x > maxX) maxX = x;
@@ -87,7 +108,7 @@ export function earcut(
87
108
  invSize = invSize !== 0 ? 32767 / invSize : 0;
88
109
  }
89
110
 
90
- earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
111
+ earcutLinked(outerNode, triangles, minX, minY, invSize, 0);
91
112
 
92
113
  return triangles;
93
114
  }
@@ -102,22 +123,40 @@ function linkedList(
102
123
  area: number | undefined,
103
124
  plane: Plane2D
104
125
  ): Vertex {
126
+ if (start >= end) return null;
105
127
  let i;
106
128
  let last;
129
+ const i0 = DimIndex[plane[0]];
130
+ const i1 = DimIndex[plane[1]];
107
131
  if (area === undefined) {
108
- area = getPolygonSignedArea(data, {start, end, size: dim, plane});
109
- }
110
-
111
- let i0 = DimIndex[plane[0]];
112
- let i1 = DimIndex[plane[1]];
113
- // Note that the signed area calculation in math.gl
114
- // has the opposite sign to that which was originally
115
- // present in earcut, thus the `< 0` is reversed
116
- if (clockwise === area < 0) {
117
- for (i = start; i < end; i += dim) last = insertNode(i, data[i + i0], data[i + i1], last);
132
+ // Combine coordinate reads and area accumulation, as in loaders.gl.
133
+ let sum = 0;
134
+ let previousX = data[end - dim + i0];
135
+ let previousY = data[end - dim + i1];
136
+ for (i = start; i < end; i += dim) {
137
+ const x = data[i + i0];
138
+ const y = data[i + i1];
139
+ sum += (x - previousX) * (y + previousY);
140
+ last = insertNode(i / dim, x, y, last);
141
+ previousX = x;
142
+ previousY = y;
143
+ }
144
+ if (last && clockwise !== sum / 2 < 0) {
145
+ let node = last;
146
+ do {
147
+ const next = node.next;
148
+ node.next = node.prev;
149
+ node.prev = next;
150
+ node = next;
151
+ } while (node !== last);
152
+ // Preserve the starting vertex and triangle order of reverse insertion.
153
+ last = last.prev;
154
+ }
155
+ } else if (clockwise === area < 0) {
156
+ for (i = start; i < end; i += dim) last = insertNode(i / dim, data[i + i0], data[i + i1], last);
118
157
  } else {
119
158
  for (i = end - dim; i >= start; i -= dim)
120
- last = insertNode(i, data[i + i0], data[i + i1], last);
159
+ last = insertNode(i / dim, data[i + i0], data[i + i1], last);
121
160
  }
122
161
 
123
162
  if (last && equals(last, last.next)) {
@@ -152,7 +191,7 @@ function filterPoints(start, end?) {
152
191
  }
153
192
 
154
193
  // main ear slicing loop which triangulates a polygon (given as a linked list)
155
- function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass?) {
194
+ function earcutLinked(ear, triangles, minX, minY, invSize, pass?) {
156
195
  if (!ear) return;
157
196
 
158
197
  // interlink polygon nodes in z-order
@@ -169,9 +208,9 @@ function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass?) {
169
208
 
170
209
  if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
171
210
  // cut off the triangle
172
- triangles.push((prev.i / dim) | 0);
173
- triangles.push((ear.i / dim) | 0);
174
- triangles.push((next.i / dim) | 0);
211
+ triangles.push(prev.i);
212
+ triangles.push(ear.i);
213
+ triangles.push(next.i);
175
214
 
176
215
  removeNode(ear);
177
216
 
@@ -188,16 +227,16 @@ function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass?) {
188
227
  if (ear === stop) {
189
228
  // try filtering points and slicing again
190
229
  if (!pass) {
191
- earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
230
+ earcutLinked(filterPoints(ear), triangles, minX, minY, invSize, 1);
192
231
 
193
232
  // if this didn't work, try curing all small self-intersections locally
194
233
  } else if (pass === 1) {
195
- ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
196
- earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
234
+ ear = cureLocalIntersections(filterPoints(ear), triangles);
235
+ earcutLinked(ear, triangles, minX, minY, invSize, 2);
197
236
 
198
237
  // as a last resort, try splitting the remaining polygon into two
199
238
  } else if (pass === 2) {
200
- splitEarcut(ear, triangles, dim, minX, minY, invSize);
239
+ splitEarcut(ear, triangles, minX, minY, invSize);
201
240
  }
202
241
 
203
242
  break;
@@ -336,7 +375,7 @@ function isEarHashed(ear, minX, minY, invSize) {
336
375
  }
337
376
 
338
377
  // go through all polygon nodes and cure small local self-intersections
339
- function cureLocalIntersections(start, triangles, dim) {
378
+ function cureLocalIntersections(start, triangles) {
340
379
  let p = start;
341
380
  do {
342
381
  const a = p.prev;
@@ -348,9 +387,9 @@ function cureLocalIntersections(start, triangles, dim) {
348
387
  locallyInside(a, b) &&
349
388
  locallyInside(b, a)
350
389
  ) {
351
- triangles.push((a.i / dim) | 0);
352
- triangles.push((p.i / dim) | 0);
353
- triangles.push((b.i / dim) | 0);
390
+ triangles.push(a.i);
391
+ triangles.push(p.i);
392
+ triangles.push(b.i);
354
393
 
355
394
  // remove two nodes involved
356
395
  removeNode(p);
@@ -365,7 +404,7 @@ function cureLocalIntersections(start, triangles, dim) {
365
404
  }
366
405
 
367
406
  // try splitting polygon into two and triangulate them independently
368
- function splitEarcut(start, triangles, dim, minX, minY, invSize) {
407
+ function splitEarcut(start, triangles, minX, minY, invSize) {
369
408
  // look for a valid diagonal that divides the polygon into two
370
409
  let a = start;
371
410
  do {
@@ -380,8 +419,8 @@ function splitEarcut(start, triangles, dim, minX, minY, invSize) {
380
419
  c = filterPoints(c, c.next);
381
420
 
382
421
  // run earcut on each half
383
- earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
384
- earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
422
+ earcutLinked(a, triangles, minX, minY, invSize, 0);
423
+ earcutLinked(c, triangles, minX, minY, invSize, 0);
385
424
  return;
386
425
  }
387
426
  b = b.next;
@@ -399,7 +438,8 @@ function eliminateHoles(
399
438
  areas: NumericArray | undefined,
400
439
  plane: Plane2D
401
440
  ): Vertex {
402
- const queue = [];
441
+ const queue = activeHoleQueue;
442
+ queue.length = 0;
403
443
  let i;
404
444
  let len;
405
445
  let start;
@@ -410,6 +450,7 @@ function eliminateHoles(
410
450
  start = holeIndices[i] * dim;
411
451
  end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
412
452
  list = linkedList(data, start, end, dim, false, areas && areas[i + 1], plane);
453
+ if (!list) continue;
413
454
  if (list === list.next) list.steiner = true;
414
455
  queue.push(getLeftmost(list));
415
456
  }
@@ -724,8 +765,8 @@ function middleInside(a, b) {
724
765
  // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
725
766
  // if one belongs to the outer ring and another to a hole, it merges it into a single ring
726
767
  function splitPolygon(a, b) {
727
- const a2 = new Vertex(a.i, a.x, a.y);
728
- const b2 = new Vertex(b.i, b.x, b.y);
768
+ const a2 = allocateVertex(a.i, a.x, a.y);
769
+ const b2 = allocateVertex(b.i, b.x, b.y);
729
770
  const an = a.next;
730
771
  const bp = b.prev;
731
772
 
@@ -746,7 +787,7 @@ function splitPolygon(a, b) {
746
787
 
747
788
  // create a node and optionally link it with previous one (in a circular doubly linked list)
748
789
  function insertNode(i, x, y, last) {
749
- const p = new Vertex(i, x, y);
790
+ const p = allocateVertex(i, x, y);
750
791
 
751
792
  if (!last) {
752
793
  p.prev = p;
@@ -768,8 +809,28 @@ function removeNode(p) {
768
809
  if (p.nextZ) p.nextZ.prevZ = p.prevZ;
769
810
  }
770
811
 
812
+ // Reuse scratch nodes and queues across calls; no input or output arrays are retained.
813
+ const vertexPool: Vertex[] = [];
814
+ let vertexPoolIndex = 0;
815
+ const holeQueues: Vertex[][] = [];
816
+ let activeHoleQueue: Vertex[] = [];
817
+ let callDepth = 0;
818
+
819
+ function allocateVertex(i: number, x: number, y: number): Vertex {
820
+ let vertex = vertexPool[vertexPoolIndex];
821
+ if (!vertex) vertexPool[vertexPoolIndex] = vertex = new Vertex(i, x, y);
822
+ vertexPoolIndex++;
823
+ vertex.i = i;
824
+ vertex.x = x;
825
+ vertex.y = y;
826
+ vertex.prev = vertex.next = vertex.prevZ = vertex.nextZ = null;
827
+ vertex.z = 0;
828
+ vertex.steiner = false;
829
+ return vertex;
830
+ }
831
+
771
832
  class Vertex {
772
- // vertex index in coordinates array
833
+ // vertex index, independent of coordinate stride
773
834
  i: number;
774
835
 
775
836
  // vertex coordinates
@@ -16,6 +16,12 @@ export {earcut} from './earcut';
16
16
 
17
17
  export {clipPolygon, clipPolyline} from './lineclip';
18
18
 
19
+ export {
20
+ getPoleOfInaccessibility,
21
+ DEFAULT_POLE_SEARCH_SEGMENT_TESTS
22
+ } from './pole-of-inaccessibility';
23
+ export type {PoleSearchBudget} from './pole-of-inaccessibility';
24
+
19
25
  export {cutPolygonByGrid, cutPolylineByGrid} from './cut-by-grid';
20
26
 
21
27
  export {cutPolylineByMercatorBounds, cutPolygonByMercatorBounds} from './cut-by-mercator-bounds';
@@ -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
+ }
@@ -36,6 +36,15 @@ export type SubdivideTriangleMeshOptions = SubdivisionOptions &
36
36
  refinement?: 'transform-error';
37
37
  /** Positive, finite sampled error tolerance across target components, in target units. */
38
38
  tolerance: number;
39
+ /** Optional application metric in tolerance units. Receives fresh sample arrays.
40
+ * Must return a finite nonnegative value. Exceptions propagate.
41
+ * Does not change output coordinates or provide a continuous error guarantee.
42
+ */
43
+ errorMetric?: (sample: {
44
+ source: readonly number[];
45
+ exact: readonly number[];
46
+ interpolated: readonly number[];
47
+ }) => number;
39
48
  /** Positive maximum Euclidean source-edge length. Default Infinity. */
40
49
  maxEdgeLength?: number;
41
50
  }
@@ -44,6 +53,7 @@ export type SubdivideTriangleMeshOptions = SubdivisionOptions &
44
53
  refinement: 'source-edge';
45
54
  /** No target-space tolerance is evaluated in source-edge mode. */
46
55
  tolerance?: never;
56
+ errorMetric?: never;
47
57
  /** Positive, finite maximum Euclidean edge length across all source components. */
48
58
  maxEdgeLength: number;
49
59
  }
@@ -93,6 +103,7 @@ export function subdivideTriangleMesh(
93
103
  const {
94
104
  transform,
95
105
  tolerance,
106
+ errorMetric,
96
107
  refinement = 'transform-error',
97
108
  size = 2,
98
109
  targetSize = size,
@@ -148,11 +159,14 @@ export function subdivideTriangleMesh(
148
159
  function validateOptions(): void {
149
160
  if (
150
161
  typeof transform !== 'function' ||
162
+ (errorMetric !== undefined && typeof errorMetric !== 'function') ||
151
163
  (refinement !== 'transform-error' && refinement !== 'source-edge') ||
152
164
  (refinement === 'transform-error' &&
153
165
  (tolerance === undefined || !Number.isFinite(tolerance) || tolerance <= 0)) ||
154
166
  (refinement === 'source-edge' &&
155
- (tolerance !== undefined || !Number.isFinite(maxEdgeLength))) ||
167
+ (tolerance !== undefined ||
168
+ errorMetric !== undefined ||
169
+ !Number.isFinite(maxEdgeLength))) ||
156
170
  (size !== 2 && size !== 3) ||
157
171
  (targetSize !== 2 && targetSize !== 3) ||
158
172
  !(maxEdgeLength > 0) ||
@@ -195,7 +209,13 @@ export function subdivideTriangleMesh(
195
209
  points.map(p => p.target),
196
210
  weights
197
211
  );
198
- return Math.hypot(...project(source).map((value, i) => value - linearTarget[i]));
212
+ const exact = project(source);
213
+ if (!errorMetric) return Math.hypot(...exact.map((value, i) => value - linearTarget[i]));
214
+ const value = errorMetric({source, exact, interpolated: linearTarget});
215
+ if (!Number.isFinite(value) || value < 0) {
216
+ throw new RangeError('errorMetric must return a finite nonnegative value');
217
+ }
218
+ return value;
199
219
  }
200
220
 
201
221
  function needsRefinement(face: Face): boolean {