@math.gl/geospatial 5.0.0-beta.8 → 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.
Files changed (102) hide show
  1. package/dist/index.cjs +1354 -383
  2. package/dist/index.cjs.map +3 -3
  3. package/dist/index.d.ts +10 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +9 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/tasks/index.cjs +1135 -142
  8. package/dist/tasks/index.cjs.map +3 -3
  9. package/dist/tasks/index.d.ts +12 -0
  10. package/dist/tasks/index.d.ts.map +1 -1
  11. package/dist/tasks/index.js +26 -0
  12. package/dist/tasks/index.js.map +1 -1
  13. package/dist/tasks/terrain-coverage-worker.d.ts +2 -0
  14. package/dist/tasks/terrain-coverage-worker.d.ts.map +1 -0
  15. package/dist/tasks/terrain-coverage-worker.js +7 -0
  16. package/dist/tasks/terrain-coverage-worker.js.map +1 -0
  17. package/dist/tasks/terrain-coverage.d.ts +25 -0
  18. package/dist/tasks/terrain-coverage.d.ts.map +1 -0
  19. package/dist/tasks/terrain-coverage.js +15 -0
  20. package/dist/tasks/terrain-coverage.js.map +1 -0
  21. package/dist/tasks/terrain-residency-worker.d.ts +2 -0
  22. package/dist/tasks/terrain-residency-worker.d.ts.map +1 -0
  23. package/dist/tasks/terrain-residency-worker.js +7 -0
  24. package/dist/tasks/terrain-residency-worker.js.map +1 -0
  25. package/dist/tasks/terrain-residency.d.ts +64 -0
  26. package/dist/tasks/terrain-residency.d.ts.map +1 -0
  27. package/dist/tasks/terrain-residency.js +124 -0
  28. package/dist/tasks/terrain-residency.js.map +1 -0
  29. package/dist/terrain/breakline-mesh.d.ts +18 -0
  30. package/dist/terrain/breakline-mesh.d.ts.map +1 -0
  31. package/dist/terrain/breakline-mesh.js +126 -0
  32. package/dist/terrain/breakline-mesh.js.map +1 -0
  33. package/dist/terrain/breakline-preprocess.d.ts +11 -0
  34. package/dist/terrain/breakline-preprocess.d.ts.map +1 -0
  35. package/dist/terrain/breakline-preprocess.js +94 -0
  36. package/dist/terrain/breakline-preprocess.js.map +1 -0
  37. package/dist/terrain/continuous-mesh-error.d.ts +34 -0
  38. package/dist/terrain/continuous-mesh-error.d.ts.map +1 -0
  39. package/dist/terrain/continuous-mesh-error.js +221 -0
  40. package/dist/terrain/continuous-mesh-error.js.map +1 -0
  41. package/dist/terrain/geographic-seam.d.ts +21 -0
  42. package/dist/terrain/geographic-seam.d.ts.map +1 -0
  43. package/dist/terrain/geographic-seam.js +52 -0
  44. package/dist/terrain/geographic-seam.js.map +1 -0
  45. package/dist/terrain/index.cjs +1104 -133
  46. package/dist/terrain/index.cjs.map +3 -3
  47. package/dist/terrain/index.d.ts +10 -0
  48. package/dist/terrain/index.d.ts.map +1 -1
  49. package/dist/terrain/index.js +9 -0
  50. package/dist/terrain/index.js.map +1 -1
  51. package/dist/terrain/lod-select.d.ts +32 -0
  52. package/dist/terrain/lod-select.d.ts.map +1 -0
  53. package/dist/terrain/lod-select.js +60 -0
  54. package/dist/terrain/lod-select.js.map +1 -0
  55. package/dist/terrain/lod-stitch.d.ts +13 -0
  56. package/dist/terrain/lod-stitch.d.ts.map +1 -0
  57. package/dist/terrain/lod-stitch.js +49 -0
  58. package/dist/terrain/lod-stitch.js.map +1 -0
  59. package/dist/terrain/mesh-coverage.d.ts +35 -0
  60. package/dist/terrain/mesh-coverage.d.ts.map +1 -0
  61. package/dist/terrain/mesh-coverage.js +186 -0
  62. package/dist/terrain/mesh-coverage.js.map +1 -0
  63. package/dist/terrain/mesh-regions-data.d.ts +2 -2
  64. package/dist/terrain/mesh-regions-data.d.ts.map +1 -1
  65. package/dist/terrain/mesh-regions-data.js +20 -10
  66. package/dist/terrain/mesh-regions-data.js.map +1 -1
  67. package/dist/terrain/mixed-halo-update.d.ts.map +1 -1
  68. package/dist/terrain/mixed-halo-update.js +93 -16
  69. package/dist/terrain/mixed-halo-update.js.map +1 -1
  70. package/dist/terrain/mixed-vertex-halos.d.ts +11 -1
  71. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -1
  72. package/dist/terrain/mixed-vertex-halos.js +43 -5
  73. package/dist/terrain/mixed-vertex-halos.js.map +1 -1
  74. package/dist/terrain/valid-domain-mesh.d.ts +29 -0
  75. package/dist/terrain/valid-domain-mesh.d.ts.map +1 -0
  76. package/dist/terrain/valid-domain-mesh.js +183 -0
  77. package/dist/terrain/valid-domain-mesh.js.map +1 -0
  78. package/dist/terrain/valid-domain-regions.d.ts +16 -0
  79. package/dist/terrain/valid-domain-regions.d.ts.map +1 -0
  80. package/dist/terrain/valid-domain-regions.js +19 -0
  81. package/dist/terrain/valid-domain-regions.js.map +1 -0
  82. package/package.json +9 -8
  83. package/src/index.ts +43 -0
  84. package/src/tasks/index.ts +34 -0
  85. package/src/tasks/terrain-coverage-worker.ts +6 -0
  86. package/src/tasks/terrain-coverage.ts +25 -0
  87. package/src/tasks/terrain-residency-worker.ts +6 -0
  88. package/src/tasks/terrain-residency.ts +154 -0
  89. package/src/terrain/breakline-mesh.ts +164 -0
  90. package/src/terrain/breakline-preprocess.ts +106 -0
  91. package/src/terrain/cdt2d.d.ts +10 -0
  92. package/src/terrain/continuous-mesh-error.ts +321 -0
  93. package/src/terrain/geographic-seam.ts +73 -0
  94. package/src/terrain/index.ts +39 -0
  95. package/src/terrain/lod-select.ts +95 -0
  96. package/src/terrain/lod-stitch.ts +70 -0
  97. package/src/terrain/mesh-coverage.ts +215 -0
  98. package/src/terrain/mesh-regions-data.ts +21 -13
  99. package/src/terrain/mixed-halo-update.ts +105 -17
  100. package/src/terrain/mixed-vertex-halos.ts +58 -4
  101. package/src/terrain/valid-domain-mesh.ts +221 -0
  102. package/src/terrain/valid-domain-regions.ts +41 -0
@@ -41,7 +41,10 @@ __export(index_exports, {
41
41
  TerrainSurface: () => TerrainSurface,
42
42
  TerrainVertexHaloStatus: () => TerrainVertexHaloStatus,
43
43
  TiledHeightField: () => TiledHeightField,
44
+ boundTerrainMeshError: () => boundTerrainMeshError,
45
+ certifyTerrainMeshCoverage: () => certifyTerrainMeshCoverage,
44
46
  coordinateTerrainLodMorphs: () => coordinateTerrainLodMorphs,
47
+ createBreaklineTerrainMesh: () => createBreaklineTerrainMesh,
45
48
  createDelatinTerrainMesh: () => createDelatinTerrainMesh,
46
49
  createMartiniTerrainMesh: () => createMartiniTerrainMesh,
47
50
  createTerrainContours: () => createTerrainContours,
@@ -57,6 +60,7 @@ __export(index_exports, {
57
60
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
58
61
  createTerrainSurface: () => createTerrainSurface,
59
62
  createTerrainVertexTileHalos: () => createTerrainVertexTileHalos,
63
+ createValidDomainTerrainMesh: () => createValidDomainTerrainMesh,
60
64
  diagnoseTerrainContourBoundaries: () => diagnoseTerrainContourBoundaries,
61
65
  evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
62
66
  getTerrainHierarchyNode: () => getTerrainHierarchyNode,
@@ -66,15 +70,19 @@ __export(index_exports, {
66
70
  getTerrainProfileVisibility: () => getTerrainProfileVisibility,
67
71
  getTerrainSlopeAspect: () => getTerrainSlopeAspect,
68
72
  getTerrainVertexHaloAffectedTiles: () => getTerrainVertexHaloAffectedTiles,
73
+ measureGeographicTerrainSeam: () => measureGeographicTerrainSeam,
69
74
  measureTerrainMeshError: () => measureTerrainMeshError,
70
75
  measureTerrainProfile: () => measureTerrainProfile,
71
76
  packTerrainHeightField: () => packTerrainHeightField,
72
77
  reconcileTerrainVertexTiles: () => reconcileTerrainVertexTiles,
73
78
  sampleTerrainProfile: () => sampleTerrainProfile,
79
+ selectTerrainLod: () => selectTerrainLod,
74
80
  simplifyTerrainContourPaths: () => simplifyTerrainContourPaths,
75
81
  simplifyTerrainContourPathsTopology: () => simplifyTerrainContourPathsTopology,
82
+ splitTerrainBreaklines: () => splitTerrainBreaklines,
76
83
  stitchTerrainContourTiles: () => stitchTerrainContourTiles,
77
84
  stitchTerrainContours: () => stitchTerrainContours,
85
+ stitchTerrainLodCut: () => stitchTerrainLodCut,
78
86
  stitchTerrainMeshEdges: () => stitchTerrainMeshEdges,
79
87
  unpackTerrainHeightField: () => unpackTerrainHeightField,
80
88
  updateTerrainBounds: () => updateTerrainBounds,
@@ -89,9 +97,11 @@ __export(index_exports, {
89
97
  updateTerrainMixedVertexTileHalos: () => updateTerrainMixedVertexTileHalos,
90
98
  updateTerrainPersistentBounds: () => updateTerrainPersistentBounds,
91
99
  updateTerrainPersistentGradients: () => updateTerrainPersistentGradients,
100
+ updateTerrainValidDomainMeshRegions: () => updateTerrainValidDomainMeshRegions,
92
101
  updateTerrainVertexTileHalos: () => updateTerrainVertexTileHalos,
93
102
  weldTerrainContourTiles: () => weldTerrainContourTiles,
94
- weldTerrainMixedContourTiles: () => weldTerrainMixedContourTiles
103
+ weldTerrainMixedContourTiles: () => weldTerrainMixedContourTiles,
104
+ wrapTerrainLongitude: () => wrapTerrainLongitude
95
105
  });
96
106
  module.exports = __toCommonJS(index_exports);
97
107
 
@@ -441,14 +451,14 @@ function createTerrainSkirt(mesh, options) {
441
451
  selected = [];
442
452
  const used = /* @__PURE__ */ new Set();
443
453
  for (let i = 0; i < edges.length; i += 2) {
444
- const key2 = edgeKey(edges[i], edges[i + 1]), edge = boundary.get(key2);
445
- if (!edge || edge.count !== 1 || used.has(key2))
454
+ const key2 = edgeKey(edges[i], edges[i + 1]), edge2 = boundary.get(key2);
455
+ if (!edge2 || edge2.count !== 1 || used.has(key2))
446
456
  throw new Error("Terrain skirt selection must contain unique boundary edges");
447
457
  used.add(key2);
448
- selected.push(edge);
458
+ selected.push(edge2);
449
459
  }
450
460
  } else
451
- selected = [...boundary.values()].filter((edge) => edge.count === 1);
461
+ selected = [...boundary.values()].filter((edge2) => edge2.count === 1);
452
462
  const outputVertices = vertexCount + selected.length * 2, outputTriangles = triangleCount + selected.length * 2;
453
463
  if (!Number.isSafeInteger(outputVertices) || outputVertices > maxVertices || outputVertices > 4294967295 || !Number.isSafeInteger(outputTriangles) || outputTriangles > maxTriangles)
454
464
  throw new Error("Terrain skirt output capacity exceeded");
@@ -599,11 +609,11 @@ var ECCENTRICITY_SQUARED = 0.0066943799901413165;
599
609
  var MAX_MERCATOR_LATITUDE = Math.atan(Math.sinh(Math.PI)) / RADIANS;
600
610
  var GeographicHeightField = class {
601
611
  constructor(props) {
602
- const { bounds } = props;
612
+ const { bounds: bounds2 } = props;
603
613
  this.projection = props.projection ?? "geographic";
604
614
  this.heightReference = props.heightReference ?? "unknown";
605
615
  const limit = this.projection === "web-mercator" ? MAX_MERCATOR_LATITUDE : 90;
606
- if (bounds.length !== 4 || !bounds.every(Number.isFinite) || bounds[2] <= bounds[0] || bounds[2] - bounds[0] > 360 || bounds[3] <= bounds[1] || bounds[1] < -limit || bounds[3] > limit || this.projection === "geographic" && (bounds[1] === -90 || bounds[3] === 90)) {
616
+ if (bounds2.length !== 4 || !bounds2.every(Number.isFinite) || bounds2[2] <= bounds2[0] || bounds2[2] - bounds2[0] > 360 || bounds2[3] <= bounds2[1] || bounds2[1] < -limit || bounds2[3] > limit || this.projection === "geographic" && (bounds2[1] === -90 || bounds2[3] === 90)) {
607
617
  throw new Error("Terrain bounds must be increasing, span at most 360 degrees and exclude the projection limits");
608
618
  }
609
619
  if (this.projection !== "geographic" && this.projection !== "web-mercator")
@@ -611,11 +621,11 @@ var GeographicHeightField = class {
611
621
  const direction = props.rowDirection ?? "north-to-south";
612
622
  if (direction !== "north-to-south" && direction !== "south-to-north")
613
623
  throw new Error("Unknown terrain row direction");
614
- this.bounds = Object.freeze([...bounds]);
615
- const west = this.projectX(bounds[0]);
616
- const east = this.projectX(bounds[2]);
617
- const south = this.projectY(bounds[1]);
618
- const north = this.projectY(bounds[3]);
624
+ this.bounds = Object.freeze([...bounds2]);
625
+ const west = this.projectX(bounds2[0]);
626
+ const east = this.projectX(bounds2[2]);
627
+ const south = this.projectY(bounds2[1]);
628
+ const north = this.projectY(bounds2[3]);
619
629
  const cell = props.registration === "cell";
620
630
  const descending = direction === "north-to-south";
621
631
  this.field = new HeightField({
@@ -1196,7 +1206,7 @@ function createTerrainMesh(field, options = {}) {
1196
1206
  coordinates.set([column, row], (row * field.width + column) * 2);
1197
1207
  const output = new Uint32Array((field.width - 1) * (field.height - 1) * 6);
1198
1208
  let used = 0;
1199
- const add = (a, b, c) => {
1209
+ const add2 = (a, b, c) => {
1200
1210
  for (const i of [a, b, c])
1201
1211
  if (field.getHeight(i % field.width, Math.floor(i / field.width)) === void 0)
1202
1212
  return;
@@ -1208,11 +1218,11 @@ function createTerrainMesh(field, options = {}) {
1208
1218
  for (let column = 0; column < field.width - 1; column++) {
1209
1219
  const a = row * field.width + column, b = a + 1, c = a + field.width, d = c + 1;
1210
1220
  if (field.diagonal === "00-11") {
1211
- add(a, b, d);
1212
- add(a, d, c);
1221
+ add2(a, b, d);
1222
+ add2(a, d, c);
1213
1223
  } else {
1214
- add(a, b, c);
1215
- add(b, d, c);
1224
+ add2(a, b, c);
1225
+ add2(b, d, c);
1216
1226
  }
1217
1227
  }
1218
1228
  return assembleTerrainMesh(field, coordinates, used === output.length ? output : output.slice(0, used), options);
@@ -1245,11 +1255,11 @@ var TerrainSurface = class {
1245
1255
  throw new Error("Terrain vertex index out of bounds");
1246
1256
  this.gradients = new Float64Array(this.triangleCount * 2);
1247
1257
  this.normals = new Float64Array(this.triangleCount * 3);
1248
- const bounds = new Float64Array(this.triangleCount * 4);
1258
+ const bounds2 = new Float64Array(this.triangleCount * 4);
1249
1259
  let active = 0;
1250
1260
  for (let i = 0; i < this.triangleCount; i++) {
1251
1261
  const [a, b, c] = this.triangle(i);
1252
- bounds.set([
1262
+ bounds2.set([
1253
1263
  Math.min(a[0], b[0], c[0]),
1254
1264
  Math.min(a[1], b[1], c[1]),
1255
1265
  Math.max(a[0], b[0], c[0]),
@@ -1275,7 +1285,7 @@ var TerrainSurface = class {
1275
1285
  }
1276
1286
  this.activeTriangleCount = active;
1277
1287
  this.topology = buildTopology(this.indices, this.validity);
1278
- this.xyIndex = new import_geometry2.BoxIndex({ bounds, dimension: 2 });
1288
+ this.xyIndex = new import_geometry2.BoxIndex({ bounds: bounds2, dimension: 2 });
1279
1289
  this.bvh = new import_geometry2.TriangleBVH({ positions: this.positions, indices: this.indices });
1280
1290
  }
1281
1291
  /** Detached source data; changing these buffers never changes this surface. */
@@ -1775,13 +1785,13 @@ function measureTerrainMeshError(field, mesh, options = {}) {
1775
1785
  }
1776
1786
 
1777
1787
  // dist/terrain/mesh-edges.js
1778
- function getTerrainMeshEdge(mesh, edge) {
1788
+ function getTerrainMeshEdge(mesh, edge2) {
1779
1789
  validateTerrainGridMesh(mesh);
1780
- if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge))
1790
+ if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge2))
1781
1791
  throw new Error("Unknown terrain mesh edge");
1782
- const column = edge === "minColumn" || edge === "maxColumn";
1792
+ const column = edge2 === "minColumn" || edge2 === "maxColumn";
1783
1793
  const axis = column ? 0 : 1;
1784
- const value = edge.startsWith("min") ? 0 : (column ? mesh.width : mesh.height) - 1;
1794
+ const value = edge2.startsWith("min") ? 0 : (column ? mesh.width : mesh.height) - 1;
1785
1795
  const vertices = /* @__PURE__ */ new Set();
1786
1796
  for (const index of mesh.indices)
1787
1797
  if (mesh.gridCoordinates[2 * index + axis] === value)
@@ -1806,15 +1816,15 @@ function createMartiniTerrainMesh(field, options) {
1806
1816
  if (field.validCount !== size * size)
1807
1817
  throw new Error("Adaptive terrain requires complete source data; use a regular mesh for holes");
1808
1818
  const edges = options.fullEdges ?? [];
1809
- for (const edge of edges)
1810
- if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge))
1819
+ for (const edge2 of edges)
1820
+ if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge2))
1811
1821
  throw new Error("Unknown adaptive terrain edge");
1812
1822
  const { heights } = field.copyData();
1813
1823
  const tile = new import_martini.default(size).createTile(heights);
1814
- for (const edge of edges)
1824
+ for (const edge2 of edges)
1815
1825
  for (let i = 0; i < size; i++) {
1816
- const column = edge === "minColumn" ? 0 : edge === "maxColumn" ? cells : i;
1817
- const row = edge === "minRow" ? 0 : edge === "maxRow" ? cells : i;
1826
+ const column = edge2 === "minColumn" ? 0 : edge2 === "maxColumn" ? cells : i;
1827
+ const row = edge2 === "minRow" ? 0 : edge2 === "maxRow" ? cells : i;
1818
1828
  tile.errors[row * size + column] = Infinity;
1819
1829
  }
1820
1830
  if (edges.length)
@@ -2443,8 +2453,8 @@ function createTerrainContours(field, levels, options = {}) {
2443
2453
  const intersection = (a, b) => {
2444
2454
  if (a > b)
2445
2455
  [a, b] = [b, a];
2446
- const exact = height(a) === level ? a : height(b) === level ? b : void 0;
2447
- return exact === void 0 ? { a, b, key: `e${a}/${b}` } : { a: exact, b: exact, key: `v${exact}` };
2456
+ const exact2 = height(a) === level ? a : height(b) === level ? b : void 0;
2457
+ return exact2 === void 0 ? { a, b, key: `e${a}/${b}` } : { a: exact2, b: exact2, key: `v${exact2}` };
2448
2458
  };
2449
2459
  const vertex = ({ a, b, key: key2 }) => {
2450
2460
  const existing = vertices.get(key2);
@@ -2610,16 +2620,16 @@ function stitchTerrainContours(contours, options = {}) {
2610
2620
  throw new Error("Terrain contour path capacity exceeded");
2611
2621
  levels.push(assignments[start]);
2612
2622
  append(start);
2613
- let vertex = start, edge = firstEdge;
2614
- while (!visited[edge]) {
2615
- visited[edge] = 1;
2616
- const a = contours.segments[2 * edge], b = contours.segments[2 * edge + 1];
2623
+ let vertex = start, edge2 = firstEdge;
2624
+ while (!visited[edge2]) {
2625
+ visited[edge2] = 1;
2626
+ const a = contours.segments[2 * edge2], b = contours.segments[2 * edge2 + 1];
2617
2627
  vertex = vertex === a ? b : a;
2618
2628
  append(vertex);
2619
2629
  if (vertex === start || degrees[vertex] !== 2)
2620
2630
  break;
2621
2631
  const e0 = adjacency[starts[vertex]], e1 = adjacency[starts[vertex] + 1];
2622
- edge = visited[e0] ? e1 : e0;
2632
+ edge2 = visited[e0] ? e1 : e0;
2623
2633
  }
2624
2634
  closed.push(vertex === start ? 1 : 0);
2625
2635
  offsets.push(indices.length);
@@ -2733,8 +2743,8 @@ function weldTerrainContourTiles(tiles, options) {
2733
2743
  const level = data.levelIndices[i], a = mapVertex(data.segments[2 * i], level), b = mapVertex(data.segments[2 * i + 1], level);
2734
2744
  if (a === b || positions[3 * a] === positions[3 * b] && positions[3 * a + 1] === positions[3 * b + 1])
2735
2745
  throw new Error("Degenerate terrain contour segment after rebasing");
2736
- const edge = a < b ? `${a}/${b}` : `${b}/${a}`;
2737
- const previous = edges.get(edge);
2746
+ const edge2 = a < b ? `${a}/${b}` : `${b}/${a}`;
2747
+ const previous = edges.get(edge2);
2738
2748
  if (previous !== void 0) {
2739
2749
  if (previous === tileIndex)
2740
2750
  throw new Error("Duplicate terrain contour segment");
@@ -2742,7 +2752,7 @@ function weldTerrainContourTiles(tiles, options) {
2742
2752
  }
2743
2753
  if (levelIndices.length >= limits.maxSegments)
2744
2754
  throw new Error("Terrain contour segment capacity exceeded");
2745
- edges.set(edge, tileIndex);
2755
+ edges.set(edge2, tileIndex);
2746
2756
  segments.push(a, b);
2747
2757
  levelIndices.push(level);
2748
2758
  }
@@ -3024,7 +3034,7 @@ function measureTerrainProfile(profile, options = {}) {
3024
3034
  let validSampleCount = 0, minimum = Infinity, maximum = -Infinity, coveredSegmentCount = 0, missingSegmentCount = 0;
3025
3035
  let meanHeight = 0;
3026
3036
  const sums = new Float64Array(6), corrections = new Float64Array(6);
3027
- const add = (index, value) => {
3037
+ const add2 = (index, value) => {
3028
3038
  const y = value - corrections[index], next = sums[index] + y;
3029
3039
  if (!Number.isFinite(value) || !Number.isFinite(next))
3030
3040
  throw new Error("Terrain profile measurement arithmetic overflow");
@@ -3049,17 +3059,17 @@ function measureTerrainProfile(profile, options = {}) {
3049
3059
  const ds = distance - profile.distances[i - 1];
3050
3060
  if (status !== TerrainSampleStatus.VALID || profile.statuses[i - 1] !== TerrainSampleStatus.VALID) {
3051
3061
  missingSegmentCount++;
3052
- add(1, ds);
3062
+ add2(1, ds);
3053
3063
  continue;
3054
3064
  }
3055
3065
  coveredSegmentCount++;
3056
3066
  const previousCovered = sums[0];
3057
- add(0, ds);
3067
+ add2(0, ds);
3058
3068
  const previous = profile.heights[i - 1], dh = height - previous;
3059
- add(dh >= 0 ? 2 : 3, Math.abs(dh));
3060
- add(4, Math.hypot(ds, dh));
3069
+ add2(dh >= 0 ? 2 : 3, Math.abs(dh));
3070
+ add2(4, Math.hypot(ds, dh));
3061
3071
  const average = previous + dh / 2;
3062
- add(5, average * ds);
3072
+ add2(5, average * ds);
3063
3073
  if (previousCovered === 0)
3064
3074
  meanHeight = average;
3065
3075
  else {
@@ -3796,7 +3806,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3796
3806
  throw new Error("Mixed contour boundary-test budget exceeded");
3797
3807
  };
3798
3808
  const sorted = [...tiles].sort((a, b) => a.column - b.column || a.row - b.row || a.spacing - b.spacing);
3799
- const bounds = sorted.map((t) => {
3809
+ const bounds2 = sorted.map((t) => {
3800
3810
  if (![t.column, t.row, t.width, t.height, t.spacing].every(Number.isSafeInteger) || t.width < 2 || t.height < 2 || t.spacing < 1 || 2 ** Math.round(Math.log2(t.spacing)) !== t.spacing)
3801
3811
  throw new Error("Invalid mixed contour tile lattice");
3802
3812
  const x1 = t.column + (t.width - 1) * t.spacing, y1 = t.row + (t.height - 1) * t.spacing;
@@ -3804,10 +3814,10 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3804
3814
  throw new Error("Mixed contour lattice overflow");
3805
3815
  return [t.column, t.row, x1, y1];
3806
3816
  });
3807
- for (let i = 0; i < bounds.length; i++)
3817
+ for (let i = 0; i < bounds2.length; i++)
3808
3818
  for (let j = 0; j < i; j++) {
3809
3819
  charge();
3810
- const a = bounds[i], b = bounds[j];
3820
+ const a = bounds2[i], b = bounds2[j];
3811
3821
  if (Math.max(a[0], b[0]) < Math.min(a[2], b[2]) && Math.max(a[1], b[1]) < Math.min(a[3], b[3]))
3812
3822
  throw new Error("Mixed contour tile interiors overlap");
3813
3823
  }
@@ -3890,18 +3900,18 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3890
3900
  if (localEdges.has(key2))
3891
3901
  throw new Error("Duplicate mixed contour segment");
3892
3902
  localEdges.add(key2);
3893
- const box = bounds[ti];
3903
+ const box = bounds2[ti];
3894
3904
  const seam = grid[2 * a] === grid[2 * b] && (grid[2 * a] === box[0] || grid[2 * a] === box[2]) || grid[2 * a + 1] === grid[2 * b + 1] && (grid[2 * a + 1] === box[1] || grid[2 * a + 1] === box[3]);
3895
3905
  edges.push({ a, b, level, tile: ti, seam });
3896
3906
  }
3897
3907
  }
3898
3908
  const segments = [], levels = [], emitted = /* @__PURE__ */ new Map();
3899
- for (const edge of edges) {
3900
- const { a, b, level } = edge;
3909
+ for (const edge2 of edges) {
3910
+ const { a, b, level } = edge2;
3901
3911
  const axis = grid[2 * a] === grid[2 * b] ? 1 : 0;
3902
3912
  const start = grid[2 * a + axis], end = grid[2 * b + axis];
3903
3913
  const cuts = [a, b];
3904
- if (edge.seam)
3914
+ if (edge2.seam)
3905
3915
  for (const v of boundary) {
3906
3916
  charge();
3907
3917
  const value = grid[2 * v + axis];
@@ -3919,13 +3929,13 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3919
3929
  const u = cuts[i - 1], v = cuts[i], key2 = u < v ? `${u}/${v}` : `${v}/${u}`;
3920
3930
  const prior = emitted.get(key2);
3921
3931
  if (prior !== void 0) {
3922
- if (prior === edge.tile)
3932
+ if (prior === edge2.tile)
3923
3933
  throw new Error("Overlapping mixed contour segments within tile");
3924
3934
  continue;
3925
3935
  }
3926
3936
  if (levels.length >= limits.maxSegments)
3927
3937
  throw new Error("Mixed contour output segment capacity exceeded");
3928
- emitted.set(key2, edge.tile);
3938
+ emitted.set(key2, edge2.tile);
3929
3939
  segments.push(u, v);
3930
3940
  levels.push(level);
3931
3941
  }
@@ -3941,6 +3951,46 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3941
3951
  };
3942
3952
  }
3943
3953
 
3954
+ // dist/terrain/box-index.js
3955
+ var overlaps = (a, b) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
3956
+ function createTerrainBoxIndex(boxes) {
3957
+ const build = (ids) => {
3958
+ const box = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
3959
+ for (const id of ids) {
3960
+ const b = boxes[id];
3961
+ box.minX = Math.min(box.minX, b.minX);
3962
+ box.minY = Math.min(box.minY, b.minY);
3963
+ box.maxX = Math.max(box.maxX, b.maxX);
3964
+ box.maxY = Math.max(box.maxY, b.maxY);
3965
+ }
3966
+ if (ids.length <= 8)
3967
+ return { ...box, ids };
3968
+ const axis = box.maxX - box.minX >= box.maxY - box.minY ? "X" : "Y";
3969
+ ids.sort((a, b) => boxes[a][`min${axis}`] / 2 + boxes[a][`max${axis}`] / 2 - (boxes[b][`min${axis}`] / 2 + boxes[b][`max${axis}`] / 2) || a - b);
3970
+ const mid = ids.length >>> 1;
3971
+ return { ...box, left: build(ids.slice(0, mid)), right: build(ids.slice(mid)) };
3972
+ };
3973
+ const root = build(boxes.map((_, i) => i));
3974
+ return (query, charge) => {
3975
+ const found = [], stack = [root];
3976
+ while (stack.length) {
3977
+ charge();
3978
+ const node = stack.pop();
3979
+ if (!overlaps(node, query))
3980
+ continue;
3981
+ if (node.ids) {
3982
+ for (const id of node.ids) {
3983
+ charge();
3984
+ if (overlaps(boxes[id], query))
3985
+ found.push(id);
3986
+ }
3987
+ } else
3988
+ stack.push(node.right, node.left);
3989
+ }
3990
+ return found.sort((a, b) => a - b);
3991
+ };
3992
+ }
3993
+
3944
3994
  // dist/terrain/sample-triangle-height.js
3945
3995
  function sampleTerrainTriangleHeight(field, x, y) {
3946
3996
  if (Number.isInteger(x) && Number.isInteger(y))
@@ -3988,7 +4038,7 @@ function sampleTerrainTriangleHeight(field, x, y) {
3988
4038
  function createTerrainMixedVertexTileHalos(tiles, options = {}) {
3989
4039
  return buildMixedVertexTileHalos(tiles, options);
3990
4040
  }
3991
- function buildMixedVertexTileHalos(tiles, options = {}, targets) {
4041
+ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
3992
4042
  const maxSamples = options.maxSamples ?? 4e6, maxTests = options.maxTileTests ?? 1e7;
3993
4043
  if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
3994
4044
  throw new Error("Invalid mixed halo capacity");
@@ -4005,7 +4055,11 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets) {
4005
4055
  count += (tile.field.width + 2) * (tile.field.height + 2);
4006
4056
  if (!Number.isSafeInteger(count) || count > maxSamples)
4007
4057
  throw new Error("Mixed halo sample capacity exceeded");
4008
- const field = new HeightField(tile.field);
4058
+ let field = preparation == null ? void 0 : preparation.fields.get(tile);
4059
+ if (!field) {
4060
+ field = new HeightField(tile.field);
4061
+ preparation == null ? void 0 : preparation.fields.set(tile, field);
4062
+ }
4009
4063
  if (field.registration !== "vertex")
4010
4064
  throw new Error("Mixed halos require vertex registration");
4011
4065
  const column = field.columnStep.map((v) => v / tile.spacing);
@@ -4032,19 +4086,47 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets) {
4032
4086
  if (sources.length && !Number.isSafeInteger(max - min))
4033
4087
  throw new Error("Mixed halo lattice span overflow");
4034
4088
  }
4089
+ if (targets && targets.size === 0)
4090
+ return { tiles: [] };
4091
+ let index;
4092
+ if (sources.length > 8) {
4093
+ const keys = preparation && sources.map((tile) => `${tile.spacing}/${tile.column}/${tile.row}/${tile.source.width}/${tile.source.height}`);
4094
+ const cached = preparation == null ? void 0 : preparation.layout;
4095
+ if (keys && cached && keys.length === cached.keys.length && keys.every((key2, i) => key2 === cached.keys[i])) {
4096
+ index = cached.query;
4097
+ } else {
4098
+ index = createTerrainBoxIndex(sources.map((tile) => ({
4099
+ minX: tile.column,
4100
+ minY: tile.row,
4101
+ maxX: tile.column + (tile.source.width - 1) * tile.spacing,
4102
+ maxY: tile.row + (tile.source.height - 1) * tile.spacing
4103
+ })));
4104
+ if (preparation && keys)
4105
+ preparation.layout = { keys, query: index };
4106
+ }
4107
+ }
4035
4108
  let tests = 0;
4109
+ const charge = () => {
4110
+ if (++tests > maxTests)
4111
+ throw new Error("Mixed halo tile-test budget exceeded");
4112
+ };
4036
4113
  return {
4037
4114
  tiles: sources.filter((tile) => !targets || targets.has(`${tile.spacing}/${tile.column}/${tile.row}`)).map((tile) => {
4038
4115
  const source = tile.source, width = source.width + 2, height = source.height + 2;
4039
4116
  const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
4117
+ const candidates = (index == null ? void 0 : index({
4118
+ minX: tile.column - tile.spacing,
4119
+ minY: tile.row - tile.spacing,
4120
+ maxX: tile.column + source.width * tile.spacing,
4121
+ maxY: tile.row + source.height * tile.spacing
4122
+ }, charge).map((id) => sources[id])) ?? sources;
4040
4123
  for (let y = 0; y < height; y++)
4041
4124
  for (let x = 0; x < width; x++) {
4042
4125
  const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
4043
4126
  if (![gx, gy].every(Number.isSafeInteger))
4044
4127
  throw new Error("Mixed halo lattice overflow");
4045
- for (const candidate of sources) {
4046
- if (++tests > maxTests)
4047
- throw new Error("Mixed halo tile-test budget exceeded");
4128
+ for (const candidate of candidates) {
4129
+ charge();
4048
4130
  const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
4049
4131
  const f = candidate.source;
4050
4132
  if (cx < 0 || cy < 0 || cx > f.width - 1 || cy > f.height - 1)
@@ -4089,36 +4171,108 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets) {
4089
4171
 
4090
4172
  // dist/terrain/mixed-halo-update.js
4091
4173
  var key = (t) => `${t.spacing}/${t.column}/${t.row}`;
4174
+ var bounds = (tile, padding = 0) => ({
4175
+ minX: tile.column - padding,
4176
+ minY: tile.row - padding,
4177
+ maxX: tile.column + (tile.field.width - 1) * tile.spacing + padding,
4178
+ maxY: tile.row + (tile.field.height - 1) * tile.spacing + padding
4179
+ });
4180
+ var preparations = /* @__PURE__ */ new WeakMap();
4181
+ var targetIndexes = /* @__PURE__ */ new WeakMap();
4182
+ function editedBounds(old, next) {
4183
+ const a = old.field;
4184
+ const b = next.field;
4185
+ if (a.width !== b.width || a.height !== b.height || (a.diagonal ?? "00-11") !== (b.diagonal ?? "00-11"))
4186
+ return bounds(next);
4187
+ const sample = (field, x, y) => {
4188
+ const i = (field.offset ?? 0) + y * (field.stride ?? field.width) + x;
4189
+ const z = field.heights[i];
4190
+ return Number.isFinite(z) && (field.validity === void 0 || field.validity[i] !== 0) ? z : void 0;
4191
+ };
4192
+ let left = b.width, right = -1, top = b.height, bottom = -1;
4193
+ for (let y = 0; y < b.height; y++) {
4194
+ for (let x = 0; x < b.width; x++) {
4195
+ if (Object.is(sample(a, x, y), sample(b, x, y)))
4196
+ continue;
4197
+ left = Math.min(left, x);
4198
+ right = Math.max(right, x);
4199
+ top = Math.min(top, y);
4200
+ bottom = Math.max(bottom, y);
4201
+ }
4202
+ }
4203
+ if (right < 0)
4204
+ return null;
4205
+ return {
4206
+ minX: next.column + Math.max(0, left - 1) * next.spacing,
4207
+ maxX: next.column + Math.min(b.width - 1, right + 1) * next.spacing,
4208
+ minY: next.row + Math.max(0, top - 1) * next.spacing,
4209
+ maxY: next.row + Math.min(b.height - 1, bottom + 1) * next.spacing
4210
+ };
4211
+ }
4092
4212
  function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4093
4213
  const budget = options.maxDependencyTests ?? 1e7;
4094
4214
  if (!Number.isSafeInteger(budget) || budget < 0)
4095
4215
  throw new Error("Invalid mixed halo dependency budget");
4096
4216
  const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4097
4217
  const current = new Map(resident.map((t) => [key(t), t]));
4098
- const changed = [...old.values()].filter((t) => current.get(key(t)) !== t).concat(resident.filter((t) => old.get(key(t)) !== t));
4099
4218
  const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key(t), t]));
4100
4219
  const targets = /* @__PURE__ */ new Set();
4220
+ const unchangedLayout = (previous == null ? void 0 : previous.sources.length) === resident.length && resident.every((tile, i) => {
4221
+ const prior = previous.sources[i];
4222
+ return key(prior) === key(tile) && prior.field.width === tile.field.width && prior.field.height === tile.field.height;
4223
+ });
4224
+ let index = unchangedLayout && previous ? targetIndexes.get(previous) : void 0;
4101
4225
  let tests = 0;
4226
+ const charge = () => {
4227
+ if (++tests > budget)
4228
+ throw new Error("Mixed halo dependency budget exceeded");
4229
+ };
4230
+ function invalidate(box) {
4231
+ index ?? (index = createTerrainBoxIndex(resident.map((tile) => bounds(tile, tile.spacing))));
4232
+ for (const id of index(box, charge))
4233
+ targets.add(key(resident[id]));
4234
+ }
4102
4235
  for (const tile of resident) {
4103
- if (!cached.has(key(tile)))
4104
- targets.add(key(tile));
4105
- for (const source of changed) {
4106
- if (++tests > budget)
4107
- throw new Error("Mixed halo dependency budget exceeded");
4108
- if (tile.column - tile.spacing <= source.column + (source.field.width - 1) * source.spacing && tile.column + tile.field.width * tile.spacing >= source.column && tile.row - tile.spacing <= source.row + (source.field.height - 1) * source.spacing && tile.row + tile.field.height * tile.spacing >= source.row)
4109
- targets.add(key(tile));
4236
+ const address = key(tile);
4237
+ const prior = old.get(address);
4238
+ if (!cached.has(address) || prior !== tile)
4239
+ targets.add(address);
4240
+ if (prior === tile || !previous)
4241
+ continue;
4242
+ if (!prior) {
4243
+ invalidate(bounds(tile));
4244
+ } else if (prior.field.width !== tile.field.width || prior.field.height !== tile.field.height) {
4245
+ invalidate(bounds(prior));
4246
+ invalidate(bounds(tile));
4247
+ } else {
4248
+ const dirty = editedBounds(prior, tile);
4249
+ if (dirty)
4250
+ invalidate(dirty);
4110
4251
  }
4111
4252
  }
4112
- const built = buildMixedVertexTileHalos(resident, options, targets).tiles;
4253
+ for (const [address, tile] of old) {
4254
+ if (!current.has(address) && resident.length)
4255
+ invalidate(bounds(tile));
4256
+ }
4257
+ const priorPreparation = previous && preparations.get(previous);
4258
+ const preparation = {
4259
+ fields: (priorPreparation == null ? void 0 : priorPreparation.fields) ?? /* @__PURE__ */ new WeakMap(),
4260
+ layout: priorPreparation == null ? void 0 : priorPreparation.layout
4261
+ };
4262
+ const built = buildMixedVertexTileHalos(resident, options, targets, preparation).tiles;
4113
4263
  for (const tile of built)
4114
4264
  cached.set(key(tile), tile);
4115
4265
  const tiles = resident.map((t) => cached.get(key(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
4116
- return {
4266
+ const snapshot = {
4117
4267
  sources: resident.slice(),
4118
4268
  tiles,
4119
4269
  rebuilt: built.map(key),
4120
4270
  removed: [...old.keys()].filter((k) => !current.has(k)).sort()
4121
4271
  };
4272
+ preparations.set(snapshot, preparation);
4273
+ if (index)
4274
+ targetIndexes.set(snapshot, index);
4275
+ return snapshot;
4122
4276
  }
4123
4277
 
4124
4278
  // dist/terrain/mixed-gradient-update.js
@@ -4140,46 +4294,6 @@ function updateTerrainMixedGradientGrids(previous, halos, options = {}) {
4140
4294
  };
4141
4295
  }
4142
4296
 
4143
- // dist/terrain/box-index.js
4144
- var overlaps = (a, b) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
4145
- function createTerrainBoxIndex(boxes) {
4146
- const build = (ids) => {
4147
- const box = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
4148
- for (const id of ids) {
4149
- const b = boxes[id];
4150
- box.minX = Math.min(box.minX, b.minX);
4151
- box.minY = Math.min(box.minY, b.minY);
4152
- box.maxX = Math.max(box.maxX, b.maxX);
4153
- box.maxY = Math.max(box.maxY, b.maxY);
4154
- }
4155
- if (ids.length <= 8)
4156
- return { ...box, ids };
4157
- const axis = box.maxX - box.minX >= box.maxY - box.minY ? "X" : "Y";
4158
- ids.sort((a, b) => boxes[a][`min${axis}`] / 2 + boxes[a][`max${axis}`] / 2 - (boxes[b][`min${axis}`] / 2 + boxes[b][`max${axis}`] / 2) || a - b);
4159
- const mid = ids.length >>> 1;
4160
- return { ...box, left: build(ids.slice(0, mid)), right: build(ids.slice(mid)) };
4161
- };
4162
- const root = build(boxes.map((_, i) => i));
4163
- return (query, charge) => {
4164
- const found = [], stack = [root];
4165
- while (stack.length) {
4166
- charge();
4167
- const node = stack.pop();
4168
- if (!overlaps(node, query))
4169
- continue;
4170
- if (node.ids) {
4171
- for (const id of node.ids) {
4172
- charge();
4173
- if (overlaps(boxes[id], query))
4174
- found.push(id);
4175
- }
4176
- } else
4177
- stack.push(node.right, node.left);
4178
- }
4179
- return found.sort((a, b) => a - b);
4180
- };
4181
- }
4182
-
4183
4297
  // dist/terrain/contour-topology.js
4184
4298
  var bits = new DataView(new ArrayBuffer(8));
4185
4299
  function integer(x) {
@@ -4262,19 +4376,19 @@ function simplifyTerrainContourPathsTopology(paths, options) {
4262
4376
  const interior = new Set(Array.from(paths.indices.subarray(start + 1, end)));
4263
4377
  let unsafe = false;
4264
4378
  for (const edgeId of edgeIndex(box(a, b), charge)) {
4265
- const edge = edges[edgeId];
4266
- if (edge.p === p && edge.i >= start && edge.i < end) {
4379
+ const edge2 = edges[edgeId];
4380
+ if (edge2.p === p && edge2.i >= start && edge2.i < end) {
4267
4381
  if (straight)
4268
4382
  continue;
4269
4383
  charge();
4270
- const others2 = [edge.a, edge.b].filter((v) => v !== a && v !== b);
4271
- if (others2.some((v) => on(points[a], points[b], points[v])) || others2.length === 2 && intersects(points[a], points[b], points[edge.a], points[edge.b]))
4384
+ const others2 = [edge2.a, edge2.b].filter((v) => v !== a && v !== b);
4385
+ if (others2.some((v) => on(points[a], points[b], points[v])) || others2.length === 2 && intersects(points[a], points[b], points[edge2.a], points[edge2.b]))
4272
4386
  unsafe = true;
4273
4387
  continue;
4274
4388
  }
4275
4389
  charge();
4276
- const others = [edge.a, edge.b].filter((v) => v !== a && v !== b);
4277
- if (others.some((v) => on(points[a], points[b], points[v])) || others.length === 2 && intersects(points[a], points[b], points[edge.a], points[edge.b]))
4390
+ const others = [edge2.a, edge2.b].filter((v) => v !== a && v !== b);
4391
+ if (others.some((v) => on(points[a], points[b], points[v])) || others.length === 2 && intersects(points[a], points[b], points[edge2.a], points[edge2.b]))
4278
4392
  unsafe = true;
4279
4393
  }
4280
4394
  const swept = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
@@ -4576,20 +4690,20 @@ function createTerrainIsobands(fields, levels, options = {}) {
4576
4690
  }
4577
4691
  while (edges.size) {
4578
4692
  const first = edges.values().next().value, ring = [];
4579
- let edge = first;
4693
+ let edge2 = first;
4580
4694
  for (; ; ) {
4581
4695
  charge();
4582
- ring.push(edge.a);
4583
- edges.delete(`${edge.a.key}>${edge.b.key}`);
4584
- outgoing.get(edge.a.key).delete(`${edge.a.key}>${edge.b.key}`);
4585
- if (edge.b.key === first.a.key)
4696
+ ring.push(edge2.a);
4697
+ edges.delete(`${edge2.a.key}>${edge2.b.key}`);
4698
+ outgoing.get(edge2.a.key).delete(`${edge2.a.key}>${edge2.b.key}`);
4699
+ if (edge2.b.key === first.a.key)
4586
4700
  break;
4587
- const choices = [...outgoing.get(edge.b.key) ?? []].map((k) => edges.get(k));
4701
+ const choices = [...outgoing.get(edge2.b.key) ?? []].map((k) => edges.get(k));
4588
4702
  if (!choices.length)
4589
4703
  throw new Error("Open isoband boundary");
4590
- const angle = (e) => Math.atan2((edge.b.x - edge.a.x) * (e.b.y - e.a.y) - (edge.b.y - edge.a.y) * (e.b.x - e.a.x), (edge.b.x - edge.a.x) * (e.b.x - e.a.x) + (edge.b.y - edge.a.y) * (e.b.y - e.a.y));
4704
+ const angle = (e) => Math.atan2((edge2.b.x - edge2.a.x) * (e.b.y - e.a.y) - (edge2.b.y - edge2.a.y) * (e.b.x - e.a.x), (edge2.b.x - edge2.a.x) * (e.b.x - e.a.x) + (edge2.b.y - edge2.a.y) * (e.b.y - e.a.y));
4591
4705
  choices.sort((a, b) => angle(b) - angle(a) || a.b.key.localeCompare(b.b.key));
4592
- edge = choices[0];
4706
+ edge2 = choices[0];
4593
4707
  }
4594
4708
  rings.push(ring);
4595
4709
  bands.push(band);
@@ -4726,6 +4840,24 @@ function updateMeshRegions(previous, field, dirty, options, configuration, creat
4726
4840
  let count = 0, tests = 0;
4727
4841
  const regions = [], rebuilt = [];
4728
4842
  const reusable = previous && sameTerrainFrame(previous.field, field) && previous.cellsPerRegion === cells && previous.configuration === configuration;
4843
+ const affectedRegions = /* @__PURE__ */ new Set();
4844
+ const columns = Math.ceil((field.width - 1) / cells);
4845
+ const rows = Math.ceil((field.height - 1) / cells);
4846
+ if (reusable) {
4847
+ for (const window of dirty) {
4848
+ const firstColumn = Math.max(0, Math.ceil(window.minColumn / cells) - 1);
4849
+ const firstRow = Math.max(0, Math.ceil(window.minRow / cells) - 1);
4850
+ const lastColumn = Math.min(columns - 1, Math.floor(window.maxColumn / cells));
4851
+ const lastRow = Math.min(rows - 1, Math.floor(window.maxRow / cells));
4852
+ for (let y = firstRow; y <= lastRow; y++) {
4853
+ for (let x = firstColumn; x <= lastColumn; x++) {
4854
+ if (++tests > budget)
4855
+ throw new Error("Terrain mesh region work budget exceeded");
4856
+ affectedRegions.add(y * columns + x);
4857
+ }
4858
+ }
4859
+ }
4860
+ }
4729
4861
  const cache = new Map(previous == null ? void 0 : previous.regions.map((r) => [`${r.column},${r.row}`, r]));
4730
4862
  for (let row = 0; row < field.height - 1; row += cells)
4731
4863
  for (let column = 0; column < field.width - 1; column += cells) {
@@ -4733,13 +4865,7 @@ function updateMeshRegions(previous, field, dirty, options, configuration, creat
4733
4865
  count += width * height;
4734
4866
  if (!Number.isSafeInteger(count) || count > limit)
4735
4867
  throw new Error("Terrain mesh region sample capacity exceeded");
4736
- let affected = !reusable;
4737
- for (const w of reusable ? dirty : []) {
4738
- if (++tests > budget)
4739
- throw new Error("Terrain mesh region work budget exceeded");
4740
- if (w.minColumn <= column + width - 1 && w.maxColumn >= column && w.minRow <= row + height - 1 && w.maxRow >= row)
4741
- affected = true;
4742
- }
4868
+ const affected = !reusable || affectedRegions.has(row / cells * columns + column / cells);
4743
4869
  const old = cache.get(`${column},${row}`);
4744
4870
  if (!affected && old) {
4745
4871
  regions.push(old);
@@ -4819,7 +4945,7 @@ function updateTerrainBoundsRegions(previous, field, dirty, options = {}) {
4819
4945
  throw new Error("Invalid bounds region capacity");
4820
4946
  validateTerrainDirtyWindows(dirty, field.width, field.height);
4821
4947
  if (!previous || !sameTerrainFrame(previous.field, field)) {
4822
- const bounds = new HeightFieldMinMax(field), levels2 = Array.from({ length: bounds.levelCount }, (_, i) => bounds.copyLevel(i));
4948
+ const bounds2 = new HeightFieldMinMax(field), levels2 = Array.from({ length: bounds2.levelCount }, (_, i) => bounds2.copyLevel(i));
4823
4949
  return { field, levels: levels2, updatedCounts: Uint32Array.from(levels2, (l) => l.width * l.height) };
4824
4950
  }
4825
4951
  let tests = 0;
@@ -5080,8 +5206,8 @@ function updateTerrainPersistentBounds(previous, field, dirty, options = {}) {
5080
5206
  const { nodesPerBlock, charge } = persistentHierarchyOptions(options, field.width * field.height);
5081
5207
  validateTerrainDirtyWindows(dirty, field.width, field.height);
5082
5208
  if (!previous || !sameTerrainFrame(previous.field, field) || previous.levels[0].nodesPerBlock !== nodesPerBlock) {
5083
- const bounds = new HeightFieldMinMax(field), levels = Array.from({ length: bounds.levelCount }, (_, i) => {
5084
- const l = bounds.copyLevel(i), values = new Float64Array(2 * l.width * l.height), counts = new Uint32Array(values.length);
5209
+ const bounds2 = new HeightFieldMinMax(field), levels = Array.from({ length: bounds2.levelCount }, (_, i) => {
5210
+ const l = bounds2.copyLevel(i), values = new Float64Array(2 * l.width * l.height), counts = new Uint32Array(values.length);
5085
5211
  for (let j = 0; j < l.width * l.height; j++) {
5086
5212
  values[2 * j] = l.minimums[j];
5087
5213
  values[2 * j + 1] = l.maximums[j];
@@ -5429,4 +5555,849 @@ function createTerrainMixedIsobands(tiles, levels, options = {}) {
5429
5555
  sharedSamples: surface.sharedSamples
5430
5556
  };
5431
5557
  }
5558
+
5559
+ // dist/terrain/valid-domain-mesh.js
5560
+ var import_cdt2d = __toESM(require("cdt2d"), 1);
5561
+ function capacity(value) {
5562
+ if (!Number.isSafeInteger(value) || value < 1)
5563
+ throw new Error("Invalid mesh work limit");
5564
+ return value;
5565
+ }
5566
+ function createValidDomainTerrainMesh(field, options) {
5567
+ return meshValidDomain(field, options);
5568
+ }
5569
+ function meshValidDomain(field, options, constraints) {
5570
+ const { maxError } = options;
5571
+ const count = field.width * field.height;
5572
+ if (!Number.isFinite(maxError) || maxError < 0)
5573
+ throw new Error("Invalid maximum error");
5574
+ if (count > capacity(options.maxSamples ?? 11e5))
5575
+ throw new Error("Sample limit exceeded");
5576
+ const maxTriangles = capacity(options.maxTriangles ?? 22e5);
5577
+ const maxTests = capacity(options.maxSampleTests ?? 4e7);
5578
+ const regular = createTerrainMesh(field, options);
5579
+ const { width, height, origin, heightReference } = regular;
5580
+ const active = new Uint8Array(count);
5581
+ const boundary = /* @__PURE__ */ new Map();
5582
+ const edgeKey2 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
5583
+ for (let i = 0; i < regular.indices.length; i += 3) {
5584
+ for (let j = 0; j < 3; j++) {
5585
+ const a = regular.indices[i + j], b = regular.indices[i + (j + 1) % 3];
5586
+ active[a] = 1;
5587
+ const key2 = edgeKey2(a, b);
5588
+ if (!boundary.delete(key2))
5589
+ boundary.set(key2, [a, b]);
5590
+ }
5591
+ }
5592
+ const selected = new Int32Array(count).fill(-1);
5593
+ const points = [];
5594
+ const heights = [];
5595
+ const add2 = (i) => {
5596
+ if (selected[i] < 0) {
5597
+ selected[i] = points.length;
5598
+ points.push([i % width, Math.floor(i / width)]);
5599
+ heights.push(regular.positions[3 * i + 2]);
5600
+ }
5601
+ return selected[i];
5602
+ };
5603
+ const edges = Array.from(boundary.values(), ([a, b]) => [add2(a), add2(b)]);
5604
+ const extra = constraints == null ? void 0 : constraints(points, heights, edges, selected, origin[2]);
5605
+ const inDomain = ([a, b, c]) => {
5606
+ const x = (points[a][0] + points[b][0] + points[c][0]) / 3;
5607
+ const y = (points[a][1] + points[b][1] + points[c][1]) / 3;
5608
+ const i = Math.floor(x), j = Math.floor(y);
5609
+ const u = x - i, v = y - j;
5610
+ const valid = (dx, dy) => field.getHeight(i + dx, j + dy) !== void 0;
5611
+ if (field.diagonal === "00-11") {
5612
+ return valid(0, 0) && valid(1, 1) && (u > v ? valid(1, 0) : valid(0, 1));
5613
+ }
5614
+ return valid(1, 0) && valid(0, 1) && (u + v < 1 ? valid(0, 0) : valid(1, 1));
5615
+ };
5616
+ const covered = new Uint8Array(count);
5617
+ let triangles = [];
5618
+ let maxSampleError = 0;
5619
+ let certifiedSamples = 0;
5620
+ let tests = 0;
5621
+ for (let pass = 0; points.length; pass++) {
5622
+ triangles = (0, import_cdt2d.default)(points, (extra == null ? void 0 : extra.edges) ?? edges, {
5623
+ exterior: Boolean(extra),
5624
+ delaunay: false
5625
+ });
5626
+ if (extra)
5627
+ triangles = triangles.filter(inDomain);
5628
+ if (triangles.length > maxTriangles)
5629
+ throw new Error("Triangle limit exceeded");
5630
+ covered.fill(0);
5631
+ const refine = /* @__PURE__ */ new Set();
5632
+ maxSampleError = 0;
5633
+ certifiedSamples = 0;
5634
+ for (const [a, b, c] of triangles) {
5635
+ const [ax, ay] = points[a], [bx, by] = points[b], [cx, cy] = points[c];
5636
+ const det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
5637
+ if (det === 0)
5638
+ throw new Error("Degenerate triangulation");
5639
+ let worst = maxError;
5640
+ let candidate = -1;
5641
+ const sides = [
5642
+ [ax, ay, bx, by],
5643
+ [bx, by, cx, cy],
5644
+ [cx, cy, ax, ay]
5645
+ ];
5646
+ for (let y = Math.ceil(Math.min(ay, by, cy)); y <= Math.floor(Math.max(ay, by, cy)); y++) {
5647
+ let left = Infinity;
5648
+ let right = -Infinity;
5649
+ for (const [x0, y0, x1, y1] of sides) {
5650
+ if (y < Math.min(y0, y1) || y > Math.max(y0, y1))
5651
+ continue;
5652
+ const x = y0 === y1 ? x0 : x0 + (x1 - x0) * (y - y0) / (y1 - y0);
5653
+ left = Math.min(left, x);
5654
+ right = Math.max(right, y0 === y1 ? Math.max(x0, x1) : x);
5655
+ if (y0 === y1)
5656
+ left = Math.min(left, x1);
5657
+ }
5658
+ for (let x = Math.ceil(left - 1e-10); x <= Math.floor(right + 1e-10); x++) {
5659
+ if (++tests > maxTests)
5660
+ throw new Error("Sample test limit exceeded");
5661
+ const i = y * width + x;
5662
+ if (!active[i] || (extra == null ? void 0 : extra.excluded.has(i)))
5663
+ continue;
5664
+ const u = ((x - ax) * (cy - ay) - (y - ay) * (cx - ax)) / det;
5665
+ const v = ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) / det;
5666
+ const w = 1 - u - v;
5667
+ if (Math.min(u, v, w) < -1e-12)
5668
+ continue;
5669
+ if (!covered[i])
5670
+ certifiedSamples++;
5671
+ covered[i] = 1;
5672
+ const error = !extra && (selected[i] === a || selected[i] === b || selected[i] === c) ? 0 : Math.abs(w * heights[a] + u * heights[b] + v * heights[c] - regular.positions[3 * i + 2]);
5673
+ maxSampleError = Math.max(maxSampleError, error);
5674
+ if (error > worst && !(extra == null ? void 0 : extra.fixedSamples.has(i))) {
5675
+ worst = error;
5676
+ candidate = i;
5677
+ }
5678
+ }
5679
+ }
5680
+ if (candidate >= 0)
5681
+ refine.add(candidate);
5682
+ }
5683
+ if (active.some((value, i) => value && !covered[i] && !(extra == null ? void 0 : extra.excluded.has(i))))
5684
+ throw new Error("Incomplete domain triangulation");
5685
+ if (maxSampleError <= maxError)
5686
+ break;
5687
+ if (!Array.from(refine).some((i) => selected[i] < 0))
5688
+ throw new Error("Cannot certify mesh tolerance");
5689
+ if (pass === 63) {
5690
+ for (let i = 0; i < count; i++)
5691
+ if (active[i] && !(extra == null ? void 0 : extra.fixedSamples.has(i)))
5692
+ add2(i);
5693
+ } else {
5694
+ for (const i of refine)
5695
+ add2(i);
5696
+ }
5697
+ }
5698
+ const reverse = field.columnStep[0] * field.rowStep[1] - field.columnStep[1] * field.rowStep[0] < 0;
5699
+ const positions = new Float64Array(points.length * 3);
5700
+ const shift = field.registration === "cell" ? 0.5 : 0;
5701
+ for (let i = 0; i < points.length; i++) {
5702
+ const [x, y] = points[i];
5703
+ positions.set([
5704
+ field.origin[0] - origin[0] + (x + shift) * field.columnStep[0] + (y + shift) * field.rowStep[0],
5705
+ field.origin[1] - origin[1] + (x + shift) * field.columnStep[1] + (y + shift) * field.rowStep[1],
5706
+ heights[i]
5707
+ ], i * 3);
5708
+ }
5709
+ const indices = new Uint32Array(triangles.length * 3);
5710
+ for (let i = 0; i < triangles.length; i++) {
5711
+ const [a, b, c] = triangles[i];
5712
+ const [ax, ay] = points[a], [bx, by] = points[b], [cx, cy] = points[c];
5713
+ const clockwise = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) < 0;
5714
+ indices.set(reverse === clockwise ? [a, b, c] : [a, c, b], 3 * i);
5715
+ }
5716
+ return {
5717
+ positions,
5718
+ indices,
5719
+ gridCoordinates: Float64Array.from(points.flat()),
5720
+ origin,
5721
+ width,
5722
+ height,
5723
+ heightReference,
5724
+ maxSampleError,
5725
+ certifiedSamples
5726
+ };
5727
+ }
5728
+
5729
+ // dist/terrain/breakline-mesh.js
5730
+ var cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
5731
+ var onSegment = (a, b, p) => Math.abs(cross(a, b, p)) <= 8 * Number.EPSILON * (Math.abs((b[0] - a[0]) * (p[1] - a[1])) + Math.abs((b[1] - a[1]) * (p[0] - a[0]))) && p[0] >= Math.min(a[0], b[0]) && p[0] <= Math.max(a[0], b[0]) && p[1] >= Math.min(a[1], b[1]) && p[1] <= Math.max(a[1], b[1]);
5732
+ function createBreaklineTerrainMesh(field, options) {
5733
+ const breaklineEdges = [];
5734
+ let overriddenSamples = 0;
5735
+ const mesh = meshValidDomain(field, options, (points, heights, boundary, selected, originZ) => {
5736
+ const ids = new Map(points.map(([x, y], i) => [`${x},${y}`, i]));
5737
+ const fixed = /* @__PURE__ */ new Map();
5738
+ const excluded = /* @__PURE__ */ new Set();
5739
+ const fixedSamples = /* @__PURE__ */ new Set();
5740
+ const add2 = ([x, y, z]) => {
5741
+ if (![x, y, z, z - originZ].every(Number.isFinite) || x < 0 || y < 0 || x > field.width - 1 || y > field.height - 1) {
5742
+ throw new Error("Breakline endpoint is outside the sample rectangle or nonfinite");
5743
+ }
5744
+ const key2 = `${x},${y}`;
5745
+ const id = ids.get(key2) ?? points.length;
5746
+ if (fixed.has(id) && fixed.get(id) !== z)
5747
+ throw new Error("Conflicting breakline heights");
5748
+ if (!ids.has(key2)) {
5749
+ points.push([x, y]);
5750
+ ids.set(key2, id);
5751
+ }
5752
+ fixed.set(id, z);
5753
+ heights[id] = z - originZ;
5754
+ if (Number.isInteger(x) && Number.isInteger(y))
5755
+ selected[y * field.width + x] = id;
5756
+ return id;
5757
+ };
5758
+ if (options.breaklines.length > 2048)
5759
+ throw new Error("Breakline limit exceeded");
5760
+ for (const [a, b] of options.breaklines) {
5761
+ const p = add2(a), q = add2(b);
5762
+ if (p === q)
5763
+ throw new Error("Zero-length breakline");
5764
+ breaklineEdges.push([p, q]);
5765
+ }
5766
+ const edges2 = [];
5767
+ for (const [a, b] of boundary) {
5768
+ const split = [
5769
+ a,
5770
+ ...Array.from(fixed.keys()).filter((id) => id !== a && id !== b && onSegment(points[a], points[b], points[id])),
5771
+ b
5772
+ ];
5773
+ const [x, y] = points[a];
5774
+ split.sort((i, j) => Math.hypot(points[i][0] - x, points[i][1] - y) - Math.hypot(points[j][0] - x, points[j][1] - y));
5775
+ for (let i = 1; i < split.length; i++)
5776
+ edges2.push([split[i - 1], split[i]]);
5777
+ }
5778
+ const seen = /* @__PURE__ */ new Set();
5779
+ for (const [a, b] of breaklineEdges) {
5780
+ const key2 = `${Math.min(a, b)},${Math.max(a, b)}`;
5781
+ if (seen.has(key2))
5782
+ throw new Error("Duplicate breakline");
5783
+ seen.add(key2);
5784
+ const p = points[a], q = points[b];
5785
+ let coincident = false;
5786
+ for (const [c, d] of edges2) {
5787
+ if (a === c && b === d || a === d && b === c) {
5788
+ coincident = true;
5789
+ continue;
5790
+ }
5791
+ const r = points[c], s = points[d];
5792
+ const intersects2 = Math.sign(cross(p, q, r)) * Math.sign(cross(p, q, s)) < 0 && Math.sign(cross(r, s, p)) * Math.sign(cross(r, s, q)) < 0;
5793
+ if (intersects2 || c !== a && c !== b && onSegment(p, q, r) || d !== a && d !== b && onSegment(p, q, s) || a !== c && a !== d && onSegment(r, s, p) || b !== c && b !== d && onSegment(r, s, q)) {
5794
+ throw new Error("Breaklines and domain edges must meet only at shared endpoints");
5795
+ }
5796
+ }
5797
+ if (!coincident)
5798
+ edges2.push([a, b]);
5799
+ for (let y = Math.ceil(Math.min(p[1], q[1])); y <= Math.floor(Math.max(p[1], q[1])); y++) {
5800
+ for (let x = Math.ceil(Math.min(p[0], q[0])); x <= Math.floor(Math.max(p[0], q[0])); x++) {
5801
+ const source = field.getHeight(x, y);
5802
+ if (source === void 0 || !onSegment(p, q, [x, y]))
5803
+ continue;
5804
+ fixedSamples.add(y * field.width + x);
5805
+ const dx = q[0] - p[0], dy = q[1] - p[1];
5806
+ const f = Math.abs(dx) >= Math.abs(dy) ? (x - p[0]) / dx : (y - p[1]) / dy;
5807
+ const z = (1 - f) * heights[a] + f * heights[b] + originZ;
5808
+ if (Math.abs(source - z) <= options.maxError)
5809
+ continue;
5810
+ if (!options.breaklinesOverrideSamples)
5811
+ throw new Error("Breakline conflicts with source tolerance");
5812
+ excluded.add(y * field.width + x);
5813
+ }
5814
+ }
5815
+ }
5816
+ overriddenSamples = excluded.size;
5817
+ return { edges: edges2, excluded, fixedSamples };
5818
+ });
5819
+ const edges = /* @__PURE__ */ new Set();
5820
+ for (let i = 0; i < mesh.indices.length; i += 3) {
5821
+ for (let j = 0; j < 3; j++) {
5822
+ const a = mesh.indices[i + j], b = mesh.indices[i + (j + 1) % 3];
5823
+ edges.add(`${Math.min(a, b)},${Math.max(a, b)}`);
5824
+ }
5825
+ }
5826
+ if (breaklineEdges.some(([a, b]) => !edges.has(`${Math.min(a, b)},${Math.max(a, b)}`))) {
5827
+ throw new Error("Breakline was not preserved inside the valid terrain domain");
5828
+ }
5829
+ return { ...mesh, breaklineEdges: Uint32Array.from(breaklineEdges.flat()), overriddenSamples };
5830
+ }
5831
+
5832
+ // dist/terrain/continuous-mesh-error.js
5833
+ var exact = (x) => [x, x];
5834
+ function outward(lo, hi) {
5835
+ if (!Number.isFinite(lo) || !Number.isFinite(hi))
5836
+ throw new Error("Continuous error arithmetic overflow");
5837
+ const result = [
5838
+ lo - Math.max(Number.MIN_VALUE, Math.abs(lo) * Number.EPSILON),
5839
+ hi + Math.max(Number.MIN_VALUE, Math.abs(hi) * Number.EPSILON)
5840
+ ];
5841
+ if (!result.every(Number.isFinite))
5842
+ throw new Error("Continuous error arithmetic overflow");
5843
+ return result;
5844
+ }
5845
+ var add = (a, b) => outward(a[0] + b[0], a[1] + b[1]);
5846
+ var sub = (a, b) => outward(a[0] - b[1], a[1] - b[0]);
5847
+ function mul(a, b) {
5848
+ const values = [a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1]];
5849
+ return outward(Math.min(...values), Math.max(...values));
5850
+ }
5851
+ function div(a, b) {
5852
+ if (b[0] <= 0 && b[1] >= 0)
5853
+ throw new Error("Degenerate or numerically unresolved mesh triangle");
5854
+ return mul(a, outward(1 / b[1], 1 / b[0]));
5855
+ }
5856
+ var magnitude = (a) => Math.max(-a[0], a[1]);
5857
+ var minimumMagnitude = (a) => Math.max(0, a[0], -a[1]);
5858
+ var evaluate = (p, x, y) => add(p[0], add(mul(p[1], x), mul(p[2], y)));
5859
+ function edge(a, b, column, row) {
5860
+ const dx = sub(exact(b[0]), exact(a[0]));
5861
+ const dy = sub(exact(b[1]), exact(a[1]));
5862
+ return [
5863
+ sub(mul(dx, sub(exact(row), exact(a[1]))), mul(dy, sub(exact(column), exact(a[0])))),
5864
+ [-dy[1], -dy[0]],
5865
+ dx
5866
+ ];
5867
+ }
5868
+ function polygon(triangle, column, row) {
5869
+ const [a, b, c] = triangle;
5870
+ const first = edge(a, b, a[0], a[1]);
5871
+ const orientation2 = evaluate(first, sub(exact(c[0]), exact(a[0])), sub(exact(c[1]), exact(a[1])));
5872
+ if (orientation2[0] <= 0 && orientation2[1] >= 0)
5873
+ throw new Error("Degenerate or numerically unresolved mesh triangle");
5874
+ const sides = [edge(a, b, column, row), edge(b, c, column, row), edge(c, a, column, row)];
5875
+ return orientation2[0] > 0 ? sides : sides.map((p) => p.map(([lo, hi]) => [-hi, -lo]));
5876
+ }
5877
+ function boundTerrainMeshError(field, mesh, options = {}) {
5878
+ const { reference = "triangle", gap = 0.05, maxBoxes = 2e6, maxDepth = 12 } = options;
5879
+ const { gridCoordinates: xy, positions, indices, origin } = mesh;
5880
+ if (!["triangle", "bilinear"].includes(reference) || !Number.isFinite(gap) || gap < 0 || !Number.isSafeInteger(maxBoxes) || maxBoxes < 1 || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > 24)
5881
+ throw new Error("Invalid continuous error options");
5882
+ if (mesh.heightReference !== field.heightReference || !Number.isFinite(origin[2]) || positions.length % 3 || xy.length !== positions.length / 3 * 2 || indices.length % 3)
5883
+ throw new Error("Invalid continuous error mesh buffers or height reference");
5884
+ let upperBound = null;
5885
+ let lowerBound = 0;
5886
+ let witness = null;
5887
+ let boxes = 0;
5888
+ for (let i = 0; i < indices.length; i += 3) {
5889
+ const ids = [indices[i], indices[i + 1], indices[i + 2]];
5890
+ if (ids.some((id) => !Number.isSafeInteger(id) || id < 0 || id >= xy.length / 2)) {
5891
+ throw new Error("Invalid continuous error index");
5892
+ }
5893
+ const triangle = [
5894
+ [xy[2 * ids[0]], xy[2 * ids[0] + 1]],
5895
+ [xy[2 * ids[1]], xy[2 * ids[1] + 1]],
5896
+ [xy[2 * ids[2]], xy[2 * ids[2] + 1]]
5897
+ ];
5898
+ const [a, b, c] = triangle;
5899
+ const [za, zb, zc] = ids.map((id) => exact(positions[3 * id + 2]));
5900
+ if (triangle.some(([x, y]) => !Number.isFinite(x) || !Number.isFinite(y)) || [za, zb, zc].some((z) => !Number.isFinite(z[0])))
5901
+ throw new Error("Nonfinite continuous error vertex");
5902
+ if (reference === "triangle" && origin[2] === 0 && matchesReferenceHalf(field, triangle, [za[0], zb[0], zc[0]])) {
5903
+ if (++boxes > maxBoxes)
5904
+ throw new Error("Continuous error box limit exceeded");
5905
+ upperBound ?? (upperBound = 0);
5906
+ witness ?? (witness = a);
5907
+ continue;
5908
+ }
5909
+ const dx = sub(exact(b[0]), exact(a[0])), dy = sub(exact(b[1]), exact(a[1]));
5910
+ const ex = sub(exact(c[0]), exact(a[0])), ey = sub(exact(c[1]), exact(a[1]));
5911
+ const det = sub(mul(dx, ey), mul(dy, ex));
5912
+ const dz = sub(zb, za), ez = sub(zc, za);
5913
+ const sx = div(sub(mul(dz, ey), mul(ez, dy)), det);
5914
+ const sy = div(sub(mul(dx, ez), mul(ex, dz)), det);
5915
+ for (let row = Math.max(0, Math.ceil(Math.min(a[1], b[1], c[1])) - 1); row <= Math.min(field.height - 2, Math.floor(Math.max(a[1], b[1], c[1]))); row++) {
5916
+ for (let column = Math.max(0, Math.ceil(Math.min(a[0], b[0], c[0])) - 1); column <= Math.min(field.width - 2, Math.floor(Math.max(a[0], b[0], c[0]))); column++) {
5917
+ let visit = function(constraints, p, mixed, x, y, depth) {
5918
+ if (++boxes > maxBoxes)
5919
+ throw new Error("Continuous error box limit exceeded");
5920
+ if (constraints.some((side) => evaluate(side, x, y)[1] < 0))
5921
+ return;
5922
+ const error = (u2, v2) => add(evaluate(p, u2, v2), mul(mixed, mul(u2, v2)));
5923
+ const centerX = (x[0] + x[1]) / 2;
5924
+ const centerY = (y[0] + y[1]) / 2;
5925
+ const u = exact(centerX), v = exact(centerY);
5926
+ if (constraints.every((side) => evaluate(side, u, v)[0] >= 0)) {
5927
+ const lower = minimumMagnitude(error(u, v));
5928
+ if (!witness || lower > lowerBound) {
5929
+ lowerBound = lower;
5930
+ witness = [column + centerX, row + centerY];
5931
+ }
5932
+ }
5933
+ const upper = Math.max(...x.flatMap((u2) => y.map((v2) => magnitude(error(exact(u2), exact(v2))))));
5934
+ if (upper <= lowerBound + gap || depth === maxDepth) {
5935
+ upperBound = Math.max(upperBound ?? 0, upper);
5936
+ return;
5937
+ }
5938
+ if (x[1] - x[0] >= y[1] - y[0]) {
5939
+ visit(constraints, p, mixed, [x[0], centerX], y, depth + 1);
5940
+ visit(constraints, p, mixed, [centerX, x[1]], y, depth + 1);
5941
+ } else {
5942
+ visit(constraints, p, mixed, x, [y[0], centerY], depth + 1);
5943
+ visit(constraints, p, mixed, x, [centerY, y[1]], depth + 1);
5944
+ }
5945
+ };
5946
+ if (++boxes > maxBoxes)
5947
+ throw new Error("Continuous error box limit exceeded");
5948
+ const vertices = [
5949
+ [0, 0],
5950
+ [1, 0],
5951
+ [0, 1],
5952
+ [1, 1]
5953
+ ];
5954
+ const h = vertices.map(([x, y]) => field.getHeight(column + x, row + y));
5955
+ const sides = polygon(triangle, column, row);
5956
+ const base = add(za, add(mul(sx, sub(exact(column), exact(a[0]))), mul(sy, sub(exact(row), exact(a[1])))));
5957
+ const compare = (constant, x, y, mixed, constraints) => visit(constraints, [sub(base, sub(constant, exact(origin[2]))), sub(sx, x), sub(sy, y)], [-mixed[1], -mixed[0]], [0, 1], [0, 1], 0);
5958
+ if (reference === "bilinear") {
5959
+ const [h00, h10, h01, h11] = h;
5960
+ if (h00 === void 0 || h10 === void 0 || h01 === void 0 || h11 === void 0)
5961
+ continue;
5962
+ const x = sub(exact(h10), exact(h00)), y = sub(exact(h01), exact(h00));
5963
+ compare(exact(h00), x, y, sub(sub(exact(h11), exact(h01)), x), sides);
5964
+ } else {
5965
+ const halves = field.diagonal === "00-11" ? [
5966
+ [0, 1, 3],
5967
+ [0, 3, 2]
5968
+ ] : [
5969
+ [0, 1, 2],
5970
+ [1, 3, 2]
5971
+ ];
5972
+ for (const [j, k, l] of halves) {
5973
+ const z0 = h[j], z1 = h[k], z2 = h[l];
5974
+ if (z0 === void 0 || z1 === void 0 || z2 === void 0)
5975
+ continue;
5976
+ const p = vertices[j], q = vertices[k], r = vertices[l];
5977
+ const x = sub(mul(sub(exact(z1), exact(z0)), exact(r[1] - p[1])), mul(sub(exact(z2), exact(z0)), exact(q[1] - p[1])));
5978
+ const y = sub(mul(exact(q[0] - p[0]), sub(exact(z2), exact(z0))), mul(exact(r[0] - p[0]), sub(exact(z1), exact(z0))));
5979
+ compare(sub(exact(z0), add(mul(x, exact(p[0])), mul(y, exact(p[1])))), x, y, exact(0), [
5980
+ ...sides,
5981
+ ...polygon([p, q, r], 0, 0)
5982
+ ]);
5983
+ }
5984
+ }
5985
+ }
5986
+ }
5987
+ }
5988
+ return {
5989
+ upperBound,
5990
+ lowerBound,
5991
+ witness,
5992
+ boxes,
5993
+ converged: upperBound !== null && upperBound - lowerBound <= gap
5994
+ };
5995
+ }
5996
+ function matchesReferenceHalf(field, triangle, heights) {
5997
+ const column = Math.min(...triangle.map((p) => p[0]));
5998
+ const row = Math.min(...triangle.map((p) => p[1]));
5999
+ if (!Number.isInteger(column) || !Number.isInteger(row) || column < 0 || row < 0 || column >= field.width - 1 || row >= field.height - 1)
6000
+ return false;
6001
+ const corners = /* @__PURE__ */ new Set();
6002
+ for (let i = 0; i < 3; i++) {
6003
+ const [x, y] = triangle[i];
6004
+ const u = x - column, v = y - row;
6005
+ if (u !== 0 && u !== 1 || v !== 0 && v !== 1 || field.getHeight(x, y) !== heights[i])
6006
+ return false;
6007
+ corners.add(u + 2 * v);
6008
+ }
6009
+ return corners.size === 3 && (field.diagonal === "00-11" ? corners.has(0) && corners.has(3) : corners.has(1) && corners.has(2));
6010
+ }
6011
+
6012
+ // dist/terrain/geographic-seam.js
6013
+ function wrapTerrainLongitude(longitude, west, east) {
6014
+ if (![longitude, west, east].every(Number.isFinite) || east <= west || east - west > 360)
6015
+ throw new Error("Invalid terrain longitude interval or query");
6016
+ if (longitude >= west && longitude < east)
6017
+ return longitude;
6018
+ const delta = (longitude % 360 - west % 360) % 360;
6019
+ const offset = delta < 0 ? delta + 360 : delta;
6020
+ const mapped = west + offset;
6021
+ return mapped <= east ? mapped : void 0;
6022
+ }
6023
+ function measureGeographicTerrainSeam(a, b, probes, options = {}) {
6024
+ if (a && b && a.heightReference !== b.heightReference)
6025
+ throw new Error("Terrain seam height references differ");
6026
+ const sample = (field, longitude, latitude) => {
6027
+ if (!field || !Number.isFinite(longitude))
6028
+ return field == null ? void 0 : field.sample(longitude, latitude, options);
6029
+ const mapped = wrapTerrainLongitude(longitude, field.bounds[0], field.bounds[2]);
6030
+ return field.sample(mapped ?? longitude, latitude, options);
6031
+ };
6032
+ return probes.map(([longitude, latitude]) => {
6033
+ const left = sample(a, longitude, latitude);
6034
+ const right = sample(b, longitude, latitude);
6035
+ const valid = (left == null ? void 0 : left.status) === TerrainSampleStatus.VALID && (right == null ? void 0 : right.status) === TerrainSampleStatus.VALID;
6036
+ const derivatives = (left == null ? void 0 : left.gradientStatus) === TerrainSampleStatus.VALID && (right == null ? void 0 : right.gradientStatus) === TerrainSampleStatus.VALID;
6037
+ const normalAngle = derivatives ? Math.atan2(Math.hypot(left.normalY * right.normalZ - left.normalZ * right.normalY, left.normalZ * right.normalX - left.normalX * right.normalZ, left.normalX * right.normalY - left.normalY * right.normalX), left.normalX * right.normalX + left.normalY * right.normalY + left.normalZ * right.normalZ) : null;
6038
+ return {
6039
+ longitude,
6040
+ latitude,
6041
+ statusA: (left == null ? void 0 : left.status) ?? TerrainSampleStatus.NOT_RESIDENT,
6042
+ statusB: (right == null ? void 0 : right.status) ?? TerrainSampleStatus.NOT_RESIDENT,
6043
+ gradientStatusA: (left == null ? void 0 : left.gradientStatus) ?? TerrainSampleStatus.NOT_RESIDENT,
6044
+ gradientStatusB: (right == null ? void 0 : right.gradientStatus) ?? TerrainSampleStatus.NOT_RESIDENT,
6045
+ heightJump: valid ? Math.abs(left.height - right.height) : null,
6046
+ normalAngle
6047
+ };
6048
+ });
6049
+ }
6050
+
6051
+ // dist/terrain/lod-select.js
6052
+ function selectTerrainLod(roots, view) {
6053
+ var _a;
6054
+ const { position, verticalFov, viewportHeight, targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
6055
+ if (!position.every(Number.isFinite) || !Number.isFinite(verticalFov) || verticalFov <= 0 || verticalFov >= Math.PI || !Number.isFinite(viewportHeight) || viewportHeight <= 0 || !Number.isFinite(targetPixels) || targetPixels <= 0 || !(hysteresis >= 0 && hysteresis < 1) || !Number.isSafeInteger(maxVisited) || maxVisited < 1)
6056
+ throw new Error("Invalid terrain LOD view");
6057
+ const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
6058
+ if (!Number.isFinite(scale))
6059
+ throw new Error("Terrain LOD projection scale overflow");
6060
+ const selected = [];
6061
+ const refined = /* @__PURE__ */ new Set();
6062
+ const unavailable = [];
6063
+ const seen = /* @__PURE__ */ new Set();
6064
+ const pending = [...roots].reverse();
6065
+ while (pending.length) {
6066
+ const tile = pending.pop();
6067
+ if (seen.size >= maxVisited)
6068
+ throw new Error("Terrain LOD visit limit exceeded");
6069
+ if (seen.has(tile.id))
6070
+ throw new Error("Duplicate terrain LOD tile or cycle");
6071
+ seen.add(tile.id);
6072
+ if (![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) || tile.geometricError < 0 || tile.min.some((n, i) => n > tile.max[i]))
6073
+ throw new Error("Invalid terrain LOD tile bounds or error");
6074
+ if (!tile.resident) {
6075
+ unavailable.push(tile.id);
6076
+ continue;
6077
+ }
6078
+ const distance = Math.hypot(...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
6079
+ const pixels = tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale;
6080
+ const threshold = targetPixels * ((previouslyRefined == null ? void 0 : previouslyRefined.has(tile.id)) ? 1 - hysteresis : 1);
6081
+ if (pixels > threshold && ((_a = tile.children) == null ? void 0 : _a.length) && tile.children.every((child) => child.resident)) {
6082
+ if (pending.length + seen.size + tile.children.length > maxVisited)
6083
+ throw new Error("Terrain LOD visit limit exceeded");
6084
+ refined.add(tile.id);
6085
+ for (let i = tile.children.length - 1; i >= 0; i--)
6086
+ pending.push(tile.children[i]);
6087
+ } else {
6088
+ selected.push({ tile, pixels });
6089
+ }
6090
+ }
6091
+ return { selected, refined, unavailable };
6092
+ }
6093
+
6094
+ // dist/terrain/lod-stitch.js
6095
+ function stitchTerrainLodCut(input, seams) {
6096
+ const meshes = input.slice();
6097
+ const paired = [];
6098
+ for (const { a, edgeA, b, edgeB, options } of seams) {
6099
+ if (a === b || !Number.isInteger(a) || !Number.isInteger(b) || !meshes[a] || !meshes[b])
6100
+ throw new Error("Invalid terrain LOD seam tile index");
6101
+ const result = stitchTerrainMeshEdges(meshes[a], edgeA, meshes[b], edgeB, options);
6102
+ meshes[a] = result.a;
6103
+ meshes[b] = result.b;
6104
+ paired.push({ a, b, idsA: result.seamA, idsB: result.seamB });
6105
+ }
6106
+ for (const { a, b, idsA, idsB } of paired) {
6107
+ const ma = meshes[a], mb = meshes[b];
6108
+ const path = (mesh, ids) => {
6109
+ const links = /* @__PURE__ */ new Set();
6110
+ for (let i = 1; i < ids.length; i++) {
6111
+ links.add(`${Math.min(ids[i - 1], ids[i])},${Math.max(ids[i - 1], ids[i])}`);
6112
+ }
6113
+ for (let i = 0; i < mesh.indices.length; i += 3) {
6114
+ for (let j = 0; j < 3; j++) {
6115
+ const p = mesh.indices[i + j], q = mesh.indices[i + (j + 1) % 3];
6116
+ links.delete(`${Math.min(p, q)},${Math.max(p, q)}`);
6117
+ }
6118
+ }
6119
+ return links.size === 0;
6120
+ };
6121
+ if (!path(ma, idsA) || !path(mb, idsB))
6122
+ throw new Error("Overlapping terrain LOD seam ranges require a common subdivision");
6123
+ for (let i = 0; i < idsA.length; i++) {
6124
+ for (let axis = 0; axis < 3; axis++) {
6125
+ const offset = mb.origin[axis] - ma.origin[axis];
6126
+ const av = ma.positions[3 * idsA[i] + axis], bv = mb.positions[3 * idsB[i] + axis];
6127
+ const residual = av - bv - offset;
6128
+ const roundoff = 8 * Number.EPSILON * (Math.abs(av) + Math.abs(bv) + Math.abs(offset));
6129
+ if (!Number.isFinite(residual) || Math.abs(residual) > roundoff)
6130
+ throw new Error("Incompatible terrain LOD seam heights or shared corners");
6131
+ }
6132
+ }
6133
+ }
6134
+ return meshes;
6135
+ }
6136
+
6137
+ // dist/terrain/breakline-preprocess.js
6138
+ function splitTerrainBreaklines(input, options = {}) {
6139
+ const { heightTolerance = 1e-8, maxPairTests = 21e5, maxSegments = 2048 } = options;
6140
+ if (!Number.isFinite(heightTolerance) || heightTolerance < 0 || ![maxPairTests, maxSegments].every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 4294967295))
6141
+ throw new Error("Invalid breakline split limits");
6142
+ if (input.length > maxSegments || input.length * (input.length - 1) / 2 > maxPairTests)
6143
+ throw new Error("Breakline preprocessing work limit exceeded");
6144
+ const vertices = /* @__PURE__ */ new Map();
6145
+ const canonical = (p) => {
6146
+ if (!p.every(Number.isFinite))
6147
+ throw new Error("Invalid breakline vertex");
6148
+ const key2 = `${p[0]},${p[1]}`;
6149
+ const prior = vertices.get(key2);
6150
+ if (prior) {
6151
+ if (Math.abs(prior[2] - p[2]) > heightTolerance)
6152
+ throw new Error("Conflicting breakline heights");
6153
+ return prior;
6154
+ }
6155
+ const point = [...p];
6156
+ vertices.set(key2, point);
6157
+ return point;
6158
+ };
6159
+ const lines = input.map(([a, b]) => {
6160
+ const p = canonical(a), q = canonical(b);
6161
+ if (p === q)
6162
+ throw new Error("Zero-length breakline");
6163
+ const knots = [
6164
+ { t: 0, point: p },
6165
+ { t: 1, point: q }
6166
+ ];
6167
+ return { p, q, dx: q[0] - p[0], dy: q[1] - p[1], knots };
6168
+ });
6169
+ let count = input.length;
6170
+ const add2 = (knots, t, point) => {
6171
+ if (knots.some((k) => k.point === point))
6172
+ return;
6173
+ if (knots.some((k) => k.t === t))
6174
+ throw new Error("Unresolved coincident breakline intersections");
6175
+ if (++count > maxSegments)
6176
+ throw new Error("Breakline output limit exceeded");
6177
+ knots.push({ t, point });
6178
+ };
6179
+ const cross2 = (ax, ay, bx, by) => ax * by - ay * bx;
6180
+ for (let i = 0; i < lines.length; i++) {
6181
+ const a = lines[i];
6182
+ for (let j = i + 1; j < lines.length; j++) {
6183
+ const b = lines[j];
6184
+ const x = b.p[0] - a.p[0], y = b.p[1] - a.p[1];
6185
+ const det = cross2(a.dx, a.dy, b.dx, b.dy);
6186
+ const u = cross2(x, y, a.dx, a.dy), t = cross2(x, y, b.dx, b.dy);
6187
+ if (![det, u, t].every(Number.isFinite))
6188
+ throw new Error("Breakline intersection overflow");
6189
+ if (det === 0) {
6190
+ if (u !== 0 || t !== 0)
6191
+ continue;
6192
+ const axis = Math.abs(a.dx) >= Math.abs(a.dy) ? 0 : 1;
6193
+ if (Math.max(Math.min(a.p[axis], a.q[axis]), Math.min(b.p[axis], b.q[axis])) < Math.min(Math.max(a.p[axis], a.q[axis]), Math.max(b.p[axis], b.q[axis])))
6194
+ throw new Error("Overlapping collinear breaklines");
6195
+ continue;
6196
+ }
6197
+ const fa = t / det, fb = u / det;
6198
+ if (fa < 0 || fa > 1 || fb < 0 || fb > 1)
6199
+ continue;
6200
+ const za = (1 - fa) * a.p[2] + fa * a.q[2], zb = (1 - fb) * b.p[2] + fb * b.q[2];
6201
+ if (!Number.isFinite(za) || !Number.isFinite(zb) || Math.abs(za - zb) > heightTolerance)
6202
+ throw new Error("Conflicting breakline heights at intersection");
6203
+ const point = canonical(fa === 0 ? a.p : fa === 1 ? a.q : fb === 0 ? b.p : fb === 1 ? b.q : [a.p[0] + fa * a.dx, a.p[1] + fa * a.dy, za]);
6204
+ add2(a.knots, fa, point);
6205
+ add2(b.knots, fb, point);
6206
+ }
6207
+ }
6208
+ const segments = [];
6209
+ const sourceSegments = new Uint32Array(count);
6210
+ for (let i = 0; i < lines.length; i++) {
6211
+ const knots = lines[i].knots.sort((a, b) => a.t - b.t);
6212
+ for (let j = 1; j < knots.length; j++) {
6213
+ sourceSegments[segments.length] = i;
6214
+ segments.push([knots[j - 1].point, knots[j].point]);
6215
+ }
6216
+ }
6217
+ return { segments, sourceSegments };
6218
+ }
6219
+
6220
+ // dist/terrain/valid-domain-regions.js
6221
+ function updateTerrainValidDomainMeshRegions(previous, field, dirty, options) {
6222
+ const { maxError, maxTrianglesPerRegion, maxSampleTestsPerRegion } = options;
6223
+ if (!Number.isFinite(maxError) || maxError < 0)
6224
+ throw new Error("Invalid regional mesh error");
6225
+ for (const limit of [maxTrianglesPerRegion, maxSampleTestsPerRegion]) {
6226
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 1))
6227
+ throw new Error("Invalid regional mesh work limit");
6228
+ }
6229
+ const configuration = `valid-domain:${maxError}:${maxTrianglesPerRegion ?? ""}:${maxSampleTestsPerRegion ?? ""}`;
6230
+ return updateMeshRegions(previous, field, dirty, options, configuration, (region) => createValidDomainTerrainMesh(region, {
6231
+ maxError,
6232
+ maxTriangles: maxTrianglesPerRegion,
6233
+ maxSampleTests: maxSampleTestsPerRegion
6234
+ }));
6235
+ }
6236
+
6237
+ // dist/terrain/mesh-coverage.js
6238
+ function gcd(a, b) {
6239
+ if (a < 0n)
6240
+ a = -a;
6241
+ if (b < 0n)
6242
+ b = -b;
6243
+ while (b !== 0n)
6244
+ [a, b] = [b, a % b];
6245
+ return a;
6246
+ }
6247
+ function certifyTerrainMeshCoverage(field, mesh, options = {}) {
6248
+ var _a, _b;
6249
+ const { reference = "triangle", maxTriangles = 2e6 } = options;
6250
+ const referenceMesh = typeof reference === "object" ? reference : null;
6251
+ const validShape = (input) => input.indices.length % 3 === 0 && input.gridCoordinates.length % 2 === 0;
6252
+ if (!Number.isSafeInteger(maxTriangles) || maxTriangles < 1 || !referenceMesh && reference !== "triangle" && reference !== "bilinear" || !validShape(mesh) || referenceMesh && !validShape(referenceMesh))
6253
+ throw new Error("Invalid terrain coverage input");
6254
+ const trianglesVisited = mesh.indices.length / 3 + (referenceMesh ? referenceMesh.indices.length / 3 : 2 * (field.width - 1) * (field.height - 1));
6255
+ if (trianglesVisited > maxTriangles) {
6256
+ return {
6257
+ status: "budget-exhausted",
6258
+ unmatchedSegments: 0,
6259
+ witness: null,
6260
+ trianglesVisited: 0,
6261
+ residualEdges: 0
6262
+ };
6263
+ }
6264
+ const bits2 = new DataView(new ArrayBuffer(8));
6265
+ function exact2(value) {
6266
+ bits2.setFloat64(0, value);
6267
+ const raw = bits2.getBigUint64(0);
6268
+ const exponent = Number(raw >> 52n & 2047n);
6269
+ const fraction = raw & (1n << 52n) - 1n;
6270
+ const integer2 = exponent === 0 ? fraction : (1n << 52n | fraction) << BigInt(exponent - 1);
6271
+ return value < 0 ? -integer2 : integer2;
6272
+ }
6273
+ const vertices = [];
6274
+ const vertexIds = /* @__PURE__ */ new Map();
6275
+ const edges = /* @__PURE__ */ new Map();
6276
+ function vertex(x, y) {
6277
+ if (!Number.isFinite(x) || !Number.isFinite(y))
6278
+ throw new Error("Nonfinite coverage coordinate");
6279
+ const key2 = `${x},${y}`;
6280
+ const previous = vertexIds.get(key2);
6281
+ if (previous !== void 0)
6282
+ return previous;
6283
+ const id = vertices.length;
6284
+ vertices.push([x, y]);
6285
+ vertexIds.set(key2, id);
6286
+ return id;
6287
+ }
6288
+ function edge2(a, b, weight) {
6289
+ var _a2;
6290
+ if (a > b) {
6291
+ [a, b] = [b, a];
6292
+ weight = -weight;
6293
+ }
6294
+ const key2 = b < 2 ** 26 ? a * 2 ** 26 + b : `${a},${b}`;
6295
+ const sum = (((_a2 = edges.get(key2)) == null ? void 0 : _a2.weight) ?? 0) + weight;
6296
+ if (sum === 0)
6297
+ edges.delete(key2);
6298
+ else
6299
+ edges.set(key2, { a, b, weight: sum });
6300
+ }
6301
+ function triangle(a, b, c, weight) {
6302
+ edge2(a, b, weight);
6303
+ edge2(b, c, weight);
6304
+ edge2(c, a, weight);
6305
+ }
6306
+ function addMesh({ indices, gridCoordinates }, weight) {
6307
+ for (let i = 0; i < indices.length; i += 3) {
6308
+ const ids = [indices[i], indices[i + 1], indices[i + 2]].map((id) => {
6309
+ if (!Number.isSafeInteger(id) || id < 0 || id >= gridCoordinates.length / 2)
6310
+ throw new Error("Invalid coverage vertex index");
6311
+ return vertex(gridCoordinates[id * 2], gridCoordinates[id * 2 + 1]);
6312
+ });
6313
+ const [a, b, c] = ids.map((id) => vertices[id]);
6314
+ const left = (b[0] - a[0]) * (c[1] - a[1]);
6315
+ const right = (b[1] - a[1]) * (c[0] - a[0]);
6316
+ const det = left - right;
6317
+ const limit = 8 * Number.EPSILON * (Math.abs(left) + Math.abs(right)) + 8 * Number.MIN_VALUE;
6318
+ let sign2 = Math.sign(det);
6319
+ if (!Number.isFinite(det) || Math.abs(det) <= limit) {
6320
+ const [ax, ay] = a.map(exact2), [bx, by] = b.map(exact2), [cx, cy] = c.map(exact2);
6321
+ const determinant = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
6322
+ sign2 = determinant > 0n ? 1 : determinant < 0n ? -1 : 0;
6323
+ }
6324
+ if (!sign2)
6325
+ throw new Error("Degenerate coverage triangle");
6326
+ triangle(ids[0], ids[1], ids[2], weight * sign2);
6327
+ }
6328
+ }
6329
+ addMesh(mesh, 1);
6330
+ if (referenceMesh)
6331
+ addMesh(referenceMesh, -1);
6332
+ else
6333
+ for (let y = 0; y < field.height - 1; y++) {
6334
+ for (let x = 0; x < field.width - 1; x++) {
6335
+ const valid = [
6336
+ field.getHeight(x, y),
6337
+ field.getHeight(x + 1, y),
6338
+ field.getHeight(x, y + 1),
6339
+ field.getHeight(x + 1, y + 1)
6340
+ ].map((z) => z !== void 0);
6341
+ if (reference === "bilinear" && !valid.every(Boolean))
6342
+ continue;
6343
+ const corners = [
6344
+ [x, y],
6345
+ [x + 1, y],
6346
+ [x, y + 1],
6347
+ [x + 1, y + 1]
6348
+ ];
6349
+ const faces = field.diagonal === "00-11" ? [
6350
+ [0, 1, 3],
6351
+ [0, 3, 2]
6352
+ ] : [
6353
+ [0, 1, 2],
6354
+ [1, 3, 2]
6355
+ ];
6356
+ for (const [a, b, c] of faces) {
6357
+ if (!valid[a] || !valid[b] || !valid[c])
6358
+ continue;
6359
+ triangle(vertex(...corners[a]), vertex(...corners[b]), vertex(...corners[c]), -1);
6360
+ }
6361
+ }
6362
+ }
6363
+ const lines = /* @__PURE__ */ new Map();
6364
+ for (const { a, b, weight } of edges.values()) {
6365
+ const p = vertices[a], q = vertices[b];
6366
+ const [x, y] = p.map(exact2), [u, v] = q.map(exact2);
6367
+ const divisor = gcd(u - x, v - y);
6368
+ let dx = (u - x) / divisor, dy = (v - y) / divisor;
6369
+ if (dx < 0n || dx === 0n && dy < 0n)
6370
+ [dx, dy] = [-dx, -dy];
6371
+ const key2 = `${dx},${dy},${dx * y - dy * x}`;
6372
+ let events = lines.get(key2);
6373
+ if (!events) {
6374
+ events = /* @__PURE__ */ new Map();
6375
+ lines.set(key2, events);
6376
+ }
6377
+ const axis = dx === 0n ? 1 : 0;
6378
+ const delta = weight;
6379
+ events.set(p[axis], { point: p, delta: (((_a = events.get(p[axis])) == null ? void 0 : _a.delta) ?? 0) + delta });
6380
+ events.set(q[axis], { point: q, delta: (((_b = events.get(q[axis])) == null ? void 0 : _b.delta) ?? 0) - delta });
6381
+ }
6382
+ let unmatchedSegments = 0;
6383
+ let witness = null;
6384
+ for (const events of lines.values()) {
6385
+ const sorted = [...events].sort(([a], [b]) => a - b);
6386
+ let jump = 0;
6387
+ for (let i = 0; i + 1 < sorted.length; i++) {
6388
+ jump += sorted[i][1].delta;
6389
+ if (!jump)
6390
+ continue;
6391
+ unmatchedSegments++;
6392
+ witness ?? (witness = { start: sorted[i][1].point, end: sorted[i + 1][1].point, multiplicityJump: jump });
6393
+ }
6394
+ }
6395
+ return {
6396
+ status: unmatchedSegments ? "mismatch" : "certified",
6397
+ unmatchedSegments,
6398
+ witness,
6399
+ trianglesVisited,
6400
+ residualEdges: edges.size
6401
+ };
6402
+ }
5432
6403
  //# sourceMappingURL=index.cjs.map