@math.gl/geospatial 5.0.0-beta.5 → 5.0.0-beta.6

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 (139) hide show
  1. package/dist/index.cjs +1526 -192
  2. package/dist/index.cjs.map +3 -3
  3. package/dist/index.d.ts +38 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +19 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/terrain/bounds-regions.d.ts +15 -0
  8. package/dist/terrain/bounds-regions.d.ts.map +1 -0
  9. package/dist/terrain/bounds-regions.js +84 -0
  10. package/dist/terrain/bounds-regions.js.map +1 -0
  11. package/dist/terrain/bounds-update.d.ts +11 -0
  12. package/dist/terrain/bounds-update.d.ts.map +1 -0
  13. package/dist/terrain/bounds-update.js +10 -0
  14. package/dist/terrain/bounds-update.js.map +1 -0
  15. package/dist/terrain/box-index.d.ts +9 -0
  16. package/dist/terrain/box-index.d.ts.map +1 -0
  17. package/dist/terrain/box-index.js +43 -0
  18. package/dist/terrain/box-index.js.map +1 -0
  19. package/dist/terrain/contour-simplify.d.ts +1 -0
  20. package/dist/terrain/contour-simplify.d.ts.map +1 -1
  21. package/dist/terrain/contour-simplify.js +5 -1
  22. package/dist/terrain/contour-simplify.js.map +1 -1
  23. package/dist/terrain/contour-topology.d.ts +30 -0
  24. package/dist/terrain/contour-topology.d.ts.map +1 -0
  25. package/dist/terrain/contour-topology.js +236 -0
  26. package/dist/terrain/contour-topology.js.map +1 -0
  27. package/dist/terrain/delatin-regions.d.ts +14 -0
  28. package/dist/terrain/delatin-regions.d.ts.map +1 -0
  29. package/dist/terrain/delatin-regions.js +15 -0
  30. package/dist/terrain/delatin-regions.js.map +1 -0
  31. package/dist/terrain/dirty-regions.d.ts +11 -0
  32. package/dist/terrain/dirty-regions.d.ts.map +1 -0
  33. package/dist/terrain/dirty-regions.js +34 -0
  34. package/dist/terrain/dirty-regions.js.map +1 -0
  35. package/dist/terrain/gradient-pyramid-regions.d.ts +15 -0
  36. package/dist/terrain/gradient-pyramid-regions.d.ts.map +1 -0
  37. package/dist/terrain/gradient-pyramid-regions.js +112 -0
  38. package/dist/terrain/gradient-pyramid-regions.js.map +1 -0
  39. package/dist/terrain/gradient-pyramid-update.d.ts +11 -0
  40. package/dist/terrain/gradient-pyramid-update.d.ts.map +1 -0
  41. package/dist/terrain/gradient-pyramid-update.js +17 -0
  42. package/dist/terrain/gradient-pyramid-update.js.map +1 -0
  43. package/dist/terrain/index.cjs +1422 -88
  44. package/dist/terrain/index.cjs.map +3 -3
  45. package/dist/terrain/index.d.ts +38 -0
  46. package/dist/terrain/index.d.ts.map +1 -1
  47. package/dist/terrain/index.js +19 -0
  48. package/dist/terrain/index.js.map +1 -1
  49. package/dist/terrain/isobands.d.ts +24 -0
  50. package/dist/terrain/isobands.d.ts.map +1 -0
  51. package/dist/terrain/isobands.js +281 -0
  52. package/dist/terrain/isobands.js.map +1 -0
  53. package/dist/terrain/lod-morph-evaluate.d.ts +8 -0
  54. package/dist/terrain/lod-morph-evaluate.d.ts.map +1 -0
  55. package/dist/terrain/lod-morph-evaluate.js +30 -0
  56. package/dist/terrain/lod-morph-evaluate.js.map +1 -0
  57. package/dist/terrain/lod-morph.d.ts +35 -0
  58. package/dist/terrain/lod-morph.d.ts.map +1 -0
  59. package/dist/terrain/lod-morph.js +87 -0
  60. package/dist/terrain/lod-morph.js.map +1 -0
  61. package/dist/terrain/martini-regions.d.ts +14 -0
  62. package/dist/terrain/martini-regions.d.ts.map +1 -0
  63. package/dist/terrain/martini-regions.js +26 -0
  64. package/dist/terrain/martini-regions.js.map +1 -0
  65. package/dist/terrain/mesh-error.d.ts.map +1 -1
  66. package/dist/terrain/mesh-error.js +9 -1
  67. package/dist/terrain/mesh-error.js.map +1 -1
  68. package/dist/terrain/mesh-regions-data.d.ts +24 -0
  69. package/dist/terrain/mesh-regions-data.d.ts.map +1 -0
  70. package/dist/terrain/mesh-regions-data.js +80 -0
  71. package/dist/terrain/mesh-regions-data.js.map +1 -0
  72. package/dist/terrain/mesh-regions.d.ts +12 -0
  73. package/dist/terrain/mesh-regions.d.ts.map +1 -0
  74. package/dist/terrain/mesh-regions.js +10 -0
  75. package/dist/terrain/mesh-regions.js.map +1 -0
  76. package/dist/terrain/mesh-update.d.ts +11 -0
  77. package/dist/terrain/mesh-update.d.ts.map +1 -0
  78. package/dist/terrain/mesh-update.js +10 -0
  79. package/dist/terrain/mesh-update.js.map +1 -0
  80. package/dist/terrain/mixed-gradient-update.d.ts +15 -0
  81. package/dist/terrain/mixed-gradient-update.d.ts.map +1 -0
  82. package/dist/terrain/mixed-gradient-update.js +24 -0
  83. package/dist/terrain/mixed-gradient-update.js.map +1 -0
  84. package/dist/terrain/mixed-halo-update.d.ts +16 -0
  85. package/dist/terrain/mixed-halo-update.d.ts.map +1 -0
  86. package/dist/terrain/mixed-halo-update.js +46 -0
  87. package/dist/terrain/mixed-halo-update.js.map +1 -0
  88. package/dist/terrain/mixed-vertex-halos.d.ts +32 -0
  89. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -0
  90. package/dist/terrain/mixed-vertex-halos.js +125 -0
  91. package/dist/terrain/mixed-vertex-halos.js.map +1 -0
  92. package/dist/terrain/persistent-bounds.d.ts +16 -0
  93. package/dist/terrain/persistent-bounds.d.ts.map +1 -0
  94. package/dist/terrain/persistent-bounds.js +51 -0
  95. package/dist/terrain/persistent-bounds.js.map +1 -0
  96. package/dist/terrain/persistent-gradients.d.ts +16 -0
  97. package/dist/terrain/persistent-gradients.d.ts.map +1 -0
  98. package/dist/terrain/persistent-gradients.js +69 -0
  99. package/dist/terrain/persistent-gradients.js.map +1 -0
  100. package/dist/terrain/persistent-hierarchy-data.d.ts +41 -0
  101. package/dist/terrain/persistent-hierarchy-data.d.ts.map +1 -0
  102. package/dist/terrain/persistent-hierarchy-data.js +130 -0
  103. package/dist/terrain/persistent-hierarchy-data.js.map +1 -0
  104. package/dist/terrain/sample-triangle-height.d.ts +4 -0
  105. package/dist/terrain/sample-triangle-height.d.ts.map +1 -0
  106. package/dist/terrain/sample-triangle-height.js +46 -0
  107. package/dist/terrain/sample-triangle-height.js.map +1 -0
  108. package/dist/terrain/tile-update-data.d.ts +14 -0
  109. package/dist/terrain/tile-update-data.d.ts.map +1 -0
  110. package/dist/terrain/tile-update-data.js +23 -0
  111. package/dist/terrain/tile-update-data.js.map +1 -0
  112. package/package.json +7 -7
  113. package/src/index.ts +59 -0
  114. package/src/terrain/bounds-regions.ts +106 -0
  115. package/src/terrain/bounds-update.ts +19 -0
  116. package/src/terrain/box-index.ts +47 -0
  117. package/src/terrain/contour-simplify.ts +10 -2
  118. package/src/terrain/contour-topology.ts +263 -0
  119. package/src/terrain/delatin-regions.ts +25 -0
  120. package/src/terrain/dirty-regions.ts +61 -0
  121. package/src/terrain/gradient-pyramid-regions.ts +140 -0
  122. package/src/terrain/gradient-pyramid-update.ts +25 -0
  123. package/src/terrain/index.ts +56 -0
  124. package/src/terrain/isobands.ts +348 -0
  125. package/src/terrain/lod-morph-evaluate.ts +36 -0
  126. package/src/terrain/lod-morph.ts +138 -0
  127. package/src/terrain/martini-regions.ts +38 -0
  128. package/src/terrain/mesh-error.ts +14 -1
  129. package/src/terrain/mesh-regions-data.ts +113 -0
  130. package/src/terrain/mesh-regions.ts +18 -0
  131. package/src/terrain/mesh-update.ts +15 -0
  132. package/src/terrain/mixed-gradient-update.ts +40 -0
  133. package/src/terrain/mixed-halo-update.ts +56 -0
  134. package/src/terrain/mixed-vertex-halos.ts +170 -0
  135. package/src/terrain/persistent-bounds.ts +95 -0
  136. package/src/terrain/persistent-gradients.ts +117 -0
  137. package/src/terrain/persistent-hierarchy-data.ts +196 -0
  138. package/src/terrain/sample-triangle-height.ts +50 -0
  139. package/src/terrain/tile-update-data.ts +32 -0
@@ -10,9 +10,9 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __copyProps = (to, from, except, desc) => {
12
12
  if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ for (let key2 of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
15
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
16
16
  }
17
17
  return to;
18
18
  };
@@ -35,6 +35,7 @@ __export(index_exports, {
35
35
  HeightFieldMinMax: () => HeightFieldMinMax,
36
36
  TERRAIN_BUFFER_VERSION: () => TERRAIN_BUFFER_VERSION,
37
37
  TerrainContourBoundaryAxis: () => TerrainContourBoundaryAxis,
38
+ TerrainMorphStatus: () => TerrainMorphStatus,
38
39
  TerrainProfileViewStatus: () => TerrainProfileViewStatus,
39
40
  TerrainSampleStatus: () => TerrainSampleStatus,
40
41
  TerrainSurface: () => TerrainSurface,
@@ -46,12 +47,17 @@ __export(index_exports, {
46
47
  createTerrainFilteredPyramid: () => createTerrainFilteredPyramid,
47
48
  createTerrainGradientGrid: () => createTerrainGradientGrid,
48
49
  createTerrainGradientPyramid: () => createTerrainGradientPyramid,
50
+ createTerrainIsobands: () => createTerrainIsobands,
51
+ createTerrainLodMorph: () => createTerrainLodMorph,
49
52
  createTerrainMesh: () => createTerrainMesh,
53
+ createTerrainMixedVertexTileHalos: () => createTerrainMixedVertexTileHalos,
50
54
  createTerrainSkirt: () => createTerrainSkirt,
51
55
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
52
56
  createTerrainSurface: () => createTerrainSurface,
53
57
  createTerrainVertexTileHalos: () => createTerrainVertexTileHalos,
54
58
  diagnoseTerrainContourBoundaries: () => diagnoseTerrainContourBoundaries,
59
+ evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
60
+ getTerrainHierarchyNode: () => getTerrainHierarchyNode,
55
61
  getTerrainMeshEdge: () => getTerrainMeshEdge,
56
62
  getTerrainProfileHorizon: () => getTerrainProfileHorizon,
57
63
  getTerrainProfileViewshed: () => getTerrainProfileViewshed,
@@ -64,10 +70,23 @@ __export(index_exports, {
64
70
  reconcileTerrainVertexTiles: () => reconcileTerrainVertexTiles,
65
71
  sampleTerrainProfile: () => sampleTerrainProfile,
66
72
  simplifyTerrainContourPaths: () => simplifyTerrainContourPaths,
73
+ simplifyTerrainContourPathsTopology: () => simplifyTerrainContourPathsTopology,
67
74
  stitchTerrainContourTiles: () => stitchTerrainContourTiles,
68
75
  stitchTerrainContours: () => stitchTerrainContours,
69
76
  stitchTerrainMeshEdges: () => stitchTerrainMeshEdges,
70
77
  unpackTerrainHeightField: () => unpackTerrainHeightField,
78
+ updateTerrainBounds: () => updateTerrainBounds,
79
+ updateTerrainBoundsRegions: () => updateTerrainBoundsRegions,
80
+ updateTerrainDelatinMeshRegions: () => updateTerrainDelatinMeshRegions,
81
+ updateTerrainGradientPyramidRegions: () => updateTerrainGradientPyramidRegions,
82
+ updateTerrainGradientPyramids: () => updateTerrainGradientPyramids,
83
+ updateTerrainMartiniMeshRegions: () => updateTerrainMartiniMeshRegions,
84
+ updateTerrainMeshRegions: () => updateTerrainMeshRegions,
85
+ updateTerrainMeshes: () => updateTerrainMeshes,
86
+ updateTerrainMixedGradientGrids: () => updateTerrainMixedGradientGrids,
87
+ updateTerrainMixedVertexTileHalos: () => updateTerrainMixedVertexTileHalos,
88
+ updateTerrainPersistentBounds: () => updateTerrainPersistentBounds,
89
+ updateTerrainPersistentGradients: () => updateTerrainPersistentGradients,
71
90
  updateTerrainVertexTileHalos: () => updateTerrainVertexTileHalos,
72
91
  weldTerrainContourTiles: () => weldTerrainContourTiles,
73
92
  weldTerrainMixedContourTiles: () => weldTerrainMixedContourTiles
@@ -358,19 +377,19 @@ function validateBatch(positions, output) {
358
377
  }
359
378
  const count = positions.length / 2;
360
379
  const buffers = [positions];
361
- for (const [key, size] of [
380
+ for (const [key2, size] of [
362
381
  ["heights", 1],
363
382
  ["statuses", 1],
364
383
  ["gradients", 2],
365
384
  ["normals", 3],
366
385
  ["gradientStatuses", 1]
367
386
  ]) {
368
- const buffer = output[key];
369
- if (buffer === void 0 && key !== "heights" && key !== "statuses")
387
+ const buffer = output[key2];
388
+ if (buffer === void 0 && key2 !== "heights" && key2 !== "statuses")
370
389
  continue;
371
- const byte = key === "statuses" || key === "gradientStatuses";
390
+ const byte = key2 === "statuses" || key2 === "gradientStatuses";
372
391
  if ((byte ? !(buffer instanceof Uint8Array) : !isTerrainArray(buffer)) || buffer.length < count * size) {
373
- throw new Error(`Terrain batch ${key} has an invalid type or insufficient length`);
392
+ throw new Error(`Terrain batch ${key2} has an invalid type or insufficient length`);
374
393
  }
375
394
  for (const other of buffers) {
376
395
  if (buffer.buffer === other.buffer && buffer.byteOffset < other.byteOffset + other.byteLength && other.byteOffset < buffer.byteOffset + buffer.byteLength) {
@@ -405,9 +424,9 @@ function createTerrainSkirt(mesh, options) {
405
424
  if (!Number.isFinite(area) || area <= 0)
406
425
  throw new Error("Terrain skirt requires upward nondegenerate XY triangles");
407
426
  for (let j = 0; j < 3; j++) {
408
- const u = ids[j], v = ids[(j + 1) % 3], key = edgeKey(u, v), prior = boundary.get(key);
427
+ const u = ids[j], v = ids[(j + 1) % 3], key2 = edgeKey(u, v), prior = boundary.get(key2);
409
428
  if (!prior)
410
- boundary.set(key, { a: u, b: v, count: 1 });
429
+ boundary.set(key2, { a: u, b: v, count: 1 });
411
430
  else {
412
431
  if (prior.count !== 1 || prior.a !== v || prior.b !== u)
413
432
  throw new Error("Terrain skirt mesh has nonmanifold or inconsistent edges");
@@ -420,10 +439,10 @@ function createTerrainSkirt(mesh, options) {
420
439
  selected = [];
421
440
  const used = /* @__PURE__ */ new Set();
422
441
  for (let i = 0; i < edges.length; i += 2) {
423
- const key = edgeKey(edges[i], edges[i + 1]), edge = boundary.get(key);
424
- if (!edge || edge.count !== 1 || used.has(key))
442
+ const key2 = edgeKey(edges[i], edges[i + 1]), edge = boundary.get(key2);
443
+ if (!edge || edge.count !== 1 || used.has(key2))
425
444
  throw new Error("Terrain skirt selection must contain unique boundary edges");
426
- used.add(key);
445
+ used.add(key2);
427
446
  selected.push(edge);
428
447
  }
429
448
  } else
@@ -708,10 +727,10 @@ var TiledHeightField = class _TiledHeightField {
708
727
  throw new Error("Terrain requires unique matrix identifiers");
709
728
  for (const tile of props.tiles) {
710
729
  const matrix = this.validateTileId(tile);
711
- const key = tileKey(tile.matrixId, tile.column, tile.row);
712
- if (this.tiles.has(key))
730
+ const key2 = tileKey(tile.matrixId, tile.column, tile.row);
731
+ if (this.tiles.has(key2))
713
732
  throw new Error("Duplicate terrain tile");
714
- this.tiles.set(key, copyTileData(tile, matrix));
733
+ this.tiles.set(key2, copyTileData(tile, matrix));
715
734
  }
716
735
  for (const tile of props.tiles)
717
736
  this.buildHalo(this.getMatrix(tile.matrixId), tile.column, tile.row, props.diagonal);
@@ -740,10 +759,10 @@ var TiledHeightField = class _TiledHeightField {
740
759
  const touched = /* @__PURE__ */ new Map();
741
760
  for (const tile of [...update.tiles ?? [], ...update.remove ?? []]) {
742
761
  this.validateTileId(tile);
743
- const key = tileKey(tile.matrixId, tile.column, tile.row);
744
- if (touched.has(key))
762
+ const key2 = tileKey(tile.matrixId, tile.column, tile.row);
763
+ if (touched.has(key2))
745
764
  throw new Error("Terrain update contains duplicate or conflicting tile identifiers");
746
- touched.set(key, tile);
765
+ touched.set(key2, tile);
747
766
  }
748
767
  for (const tile of update.tiles ?? [])
749
768
  replacements.set(tileKey(tile.matrixId, tile.column, tile.row), copyTileData(tile, this.getMatrix(tile.matrixId)));
@@ -754,18 +773,18 @@ var TiledHeightField = class _TiledHeightField {
754
773
  diagonal: this.diagonal,
755
774
  heightReference: this.heightReference
756
775
  });
757
- for (const [key, tile] of this.tiles)
758
- next.tiles.set(key, tile);
759
- for (const [key, halo] of this.halos)
760
- next.halos.set(key, halo);
776
+ for (const [key2, tile] of this.tiles)
777
+ next.tiles.set(key2, tile);
778
+ for (const [key2, halo] of this.halos)
779
+ next.halos.set(key2, halo);
761
780
  const affected = /* @__PURE__ */ new Map();
762
- for (const [key, tile] of touched) {
763
- if (replacements.has(key))
764
- next.tiles.set(key, replacements.get(key));
781
+ for (const [key2, tile] of touched) {
782
+ if (replacements.has(key2))
783
+ next.tiles.set(key2, replacements.get(key2));
765
784
  else {
766
- if (!next.tiles.delete(key))
785
+ if (!next.tiles.delete(key2))
767
786
  continue;
768
- next.halos.delete(key);
787
+ next.halos.delete(key2);
769
788
  }
770
789
  for (let row = tile.row - 1; row <= tile.row + 1; row++)
771
790
  for (let column = tile.column - 1; column <= tile.column + 1; column++) {
@@ -778,11 +797,11 @@ var TiledHeightField = class _TiledHeightField {
778
797
  }
779
798
  }
780
799
  const changes = [];
781
- for (const [key, tile] of affected) {
782
- if (next.tiles.has(key)) {
800
+ for (const [key2, tile] of affected) {
801
+ if (next.tiles.has(key2)) {
783
802
  next.buildHalo(next.getMatrix(tile.matrixId), tile.column, tile.row, this.diagonal);
784
803
  changes.push({ ...tile, resident: true });
785
- } else if (this.tiles.has(key))
804
+ } else if (this.tiles.has(key2))
786
805
  changes.push(tile);
787
806
  }
788
807
  next.changes = freezeChanges(changes);
@@ -1505,10 +1524,10 @@ function buildTopology(indices, validity) {
1505
1524
  if (!validity[triangle])
1506
1525
  continue;
1507
1526
  const a = indices[i], b = indices[triangle * 3 + (i % 3 + 1) % 3];
1508
- const key = a < b ? `${a}/${b}` : `${b}/${a}`;
1509
- const opposite = edges.get(key);
1527
+ const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
1528
+ const opposite = edges.get(key2);
1510
1529
  if (opposite === void 0)
1511
- edges.set(key, i);
1530
+ edges.set(key2, i);
1512
1531
  else {
1513
1532
  if (halfedges[opposite] !== -1)
1514
1533
  throw new Error("Nonmanifold terrain edge");
@@ -1678,7 +1697,8 @@ function measureTerrainMeshError(field, mesh, options = {}) {
1678
1697
  const x = mesh.gridCoordinates[i * 2] + shift, y = mesh.gridCoordinates[i * 2 + 1] + shift;
1679
1698
  for (let axis = 0; axis < 2; axis++) {
1680
1699
  const expected = field.origin[axis] - mesh.origin[axis] + x * field.columnStep[axis] + y * field.rowStep[axis];
1681
- if (!Number.isFinite(expected) || mesh.positions[i * 3 + axis] !== expected)
1700
+ const tolerance = Math.min(16 * Number.EPSILON * (Math.abs(field.origin[axis] - mesh.origin[axis]) + Math.abs(x * field.columnStep[axis]) + Math.abs(y * field.rowStep[axis])), 1e-9 * Math.max(Math.abs(field.columnStep[axis]), Math.abs(field.rowStep[axis])));
1701
+ if (!Number.isFinite(expected) || Math.abs(mesh.positions[i * 3 + axis] - expected) > tolerance)
1682
1702
  throw new Error("Terrain mesh XY does not match the source grid frame");
1683
1703
  }
1684
1704
  }
@@ -1713,9 +1733,9 @@ function measureTerrainMeshError(field, mesh, options = {}) {
1713
1733
  throw new Error("Terrain mesh sample-test budget exceeded");
1714
1734
  const dx = baseX + (column + shift) * columnX + (row + shift) * rowX - px;
1715
1735
  const dy = baseY + (column + shift) * columnY + (row + shift) * rowY - py;
1716
- const sign = Math.sign(xyArea), area = Math.abs(xyArea);
1717
- const nu = (dx * vy - dy * vx) * sign;
1718
- const nv = (ux * dy - uy * dx) * sign;
1736
+ const sign2 = Math.sign(xyArea), area = Math.abs(xyArea);
1737
+ const nu = (dx * vy - dy * vx) * sign2;
1738
+ const nv = (ux * dy - uy * dx) * sign2;
1719
1739
  const tolerance = 16 * Number.EPSILON * (Math.abs(dx * vy) + Math.abs(dy * vx) + Math.abs(ux * dy) + Math.abs(uy * dx) + area);
1720
1740
  if (nu < -tolerance || nv < -tolerance || nu + nv > area + tolerance)
1721
1741
  continue;
@@ -2424,8 +2444,8 @@ function createTerrainContours(field, levels, options = {}) {
2424
2444
  const exact = height(a) === level ? a : height(b) === level ? b : void 0;
2425
2445
  return exact === void 0 ? { a, b, key: `e${a}/${b}` } : { a: exact, b: exact, key: `v${exact}` };
2426
2446
  };
2427
- const vertex = ({ a, b, key }) => {
2428
- const existing = vertices.get(key);
2447
+ const vertex = ({ a, b, key: key2 }) => {
2448
+ const existing = vertices.get(key2);
2429
2449
  if (existing !== void 0)
2430
2450
  return existing;
2431
2451
  if (positions.length / 3 >= maxVertices)
@@ -2452,7 +2472,7 @@ function createTerrainContours(field, levels, options = {}) {
2452
2472
  const index = positions.length / 3;
2453
2473
  positions.push(px, py, pz);
2454
2474
  coordinates.push(x, y);
2455
- vertices.set(key, index);
2475
+ vertices.set(key2, index);
2456
2476
  return index;
2457
2477
  };
2458
2478
  const triangle = (a, b, c) => {
@@ -2469,14 +2489,14 @@ function createTerrainContours(field, levels, options = {}) {
2469
2489
  if (hits.length !== 2 || hits[0].key === hits[1].key)
2470
2490
  return;
2471
2491
  const va = vertex(hits[0]), vb = vertex(hits[1]);
2472
- const key = va < vb ? `${va}/${vb}` : `${vb}/${va}`;
2473
- if (edges.has(key))
2492
+ const key2 = va < vb ? `${va}/${vb}` : `${vb}/${va}`;
2493
+ if (edges.has(key2))
2474
2494
  return;
2475
2495
  if (segments.length / 2 >= maxSegments)
2476
2496
  throw new Error("Terrain contour segment capacity exceeded");
2477
2497
  if (positions[3 * va] === positions[3 * vb] && positions[3 * va + 1] === positions[3 * vb + 1])
2478
2498
  throw new Error("Terrain contour segment collapses; use a local origin");
2479
- edges.add(key);
2499
+ edges.add(key2);
2480
2500
  segments.push(va, vb);
2481
2501
  levelIndices.push(levelIndex);
2482
2502
  };
@@ -2563,10 +2583,10 @@ function stitchTerrainContours(contours, options = {}) {
2563
2583
  validateContourVertex(contours, b, level, assignments);
2564
2584
  if (a === b || contours.positions[3 * a] === contours.positions[3 * b] && contours.positions[3 * a + 1] === contours.positions[3 * b + 1])
2565
2585
  throw new Error("Degenerate terrain contour segment");
2566
- const key = a < b ? `${a}/${b}` : `${b}/${a}`;
2567
- if (unique.has(key))
2586
+ const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
2587
+ if (unique.has(key2))
2568
2588
  throw new Error("Duplicate terrain contour segment");
2569
- unique.add(key);
2589
+ unique.add(key2);
2570
2590
  degrees[a]++;
2571
2591
  degrees[b]++;
2572
2592
  }
@@ -2754,10 +2774,10 @@ function diagnoseTerrainContourBoundaries(contours, options) {
2754
2774
  validateContourVertex(contours, b, level, assignments);
2755
2775
  if (a === b || contours.positions[3 * a] === contours.positions[3 * b] && contours.positions[3 * a + 1] === contours.positions[3 * b + 1])
2756
2776
  throw new Error("Degenerate terrain contour segment");
2757
- const key = a < b ? `${a}/${b}` : `${b}/${a}`;
2758
- if (seen.has(key))
2777
+ const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
2778
+ if (seen.has(key2))
2759
2779
  throw new Error("Duplicate terrain contour segment");
2760
- seen.add(key);
2780
+ seen.add(key2);
2761
2781
  degrees[a]++;
2762
2782
  degrees[b]++;
2763
2783
  }
@@ -2893,6 +2913,10 @@ function simplifyTerrainContourPaths(paths, options) {
2893
2913
  uses[vertex]++;
2894
2914
  }
2895
2915
  }
2916
+ const protectedIds = new Set(options.protectedVertexIndices);
2917
+ for (const id of protectedIds)
2918
+ if (id >= count)
2919
+ throw new Error("Invalid protected contour vertex");
2896
2920
  const keep = new Uint8Array(paths.indices.length);
2897
2921
  let distanceTests = 0, maxDeviation = 0;
2898
2922
  for (let p = 0; p < pathCount; p++) {
@@ -2903,7 +2927,7 @@ function simplifyTerrainContourPaths(paths, options) {
2903
2927
  keep[start + Math.floor(2 * (end - start) / 3)] = 1;
2904
2928
  }
2905
2929
  for (let i = start; i <= end; i++)
2906
- if (uses[paths.indices[i]] > 1)
2930
+ if (uses[paths.indices[i]] > 1 || protectedIds.has(paths.indices[i]))
2907
2931
  keep[i] = 1;
2908
2932
  const stack = [];
2909
2933
  let previous = start;
@@ -3124,9 +3148,9 @@ function compareTerrainSlopes(a, ad, b, bd) {
3124
3148
  const bytes = new DataView(new ArrayBuffer(8));
3125
3149
  const parts = (value) => {
3126
3150
  bytes.setFloat64(0, Math.abs(value));
3127
- const bits = bytes.getBigUint64(0);
3128
- const exponent = Number(bits >> 52n & 0x7ffn);
3129
- const fraction = bits & 0xfffffffffffffn;
3151
+ const bits2 = bytes.getBigUint64(0);
3152
+ const exponent = Number(bits2 >> 52n & 0x7ffn);
3153
+ const fraction = bits2 & 0xfffffffffffffn;
3130
3154
  return exponent ? [fraction | 0x10000000000000n, exponent - 1075] : [fraction, -1074];
3131
3155
  };
3132
3156
  const [am, ae] = parts(a), [bdm, bde] = parts(bd);
@@ -3243,10 +3267,10 @@ function reconcileTerrainVertexTiles(tiles, options) {
3243
3267
  const shared = /* @__PURE__ */ new Map();
3244
3268
  const result = [];
3245
3269
  for (const tile of sorted) {
3246
- const key = `${tile.column},${tile.row}`;
3247
- if (!Number.isSafeInteger(tile.column) || !Number.isSafeInteger(tile.row) || seen.has(key))
3270
+ const key2 = `${tile.column},${tile.row}`;
3271
+ if (!Number.isSafeInteger(tile.column) || !Number.isSafeInteger(tile.row) || seen.has(key2))
3248
3272
  throw new Error("Invalid or duplicate vertex tile address");
3249
- seen.add(key);
3273
+ seen.add(key2);
3250
3274
  const x = tile.column * (width - 1), y = tile.row * (height - 1);
3251
3275
  if (![x, y, x + width - 1, y + height - 1].every(Number.isSafeInteger))
3252
3276
  throw new Error("Vertex tile lattice overflow");
@@ -3397,20 +3421,20 @@ function getTerrainVertexHaloAffectedTiles(resident, changed, options) {
3397
3421
  if (!Number.isSafeInteger(limit) || limit < 0 || resident.length > limit || changed.length > limit || !Number.isSafeInteger(options.width) || options.width < 2 || !Number.isSafeInteger(options.height) || options.height < 2)
3398
3422
  throw new Error("Invalid vertex halo tile capacity");
3399
3423
  const addresses = /* @__PURE__ */ new Map();
3400
- const key = (tile) => {
3424
+ const key2 = (tile) => {
3401
3425
  if (!Number.isSafeInteger(tile.column) || !Number.isSafeInteger(tile.row))
3402
3426
  throw new Error("Invalid vertex tile address");
3403
3427
  return `${tile.column},${tile.row}`;
3404
3428
  };
3405
3429
  for (const tile of resident) {
3406
- const id = key(tile);
3430
+ const id = key2(tile);
3407
3431
  if (addresses.has(id))
3408
3432
  throw new Error("Duplicate resident vertex tile address");
3409
3433
  addresses.set(id, { column: tile.column, row: tile.row });
3410
3434
  }
3411
3435
  const affected = /* @__PURE__ */ new Map();
3412
3436
  for (const tile of changed) {
3413
- key(tile);
3437
+ key2(tile);
3414
3438
  const rx = options.width === 2 ? 2 : 1, ry = options.height === 2 ? 2 : 1;
3415
3439
  for (let x = -rx; x <= rx; x++)
3416
3440
  for (let y = -ry; y <= ry; y++) {
@@ -3437,26 +3461,26 @@ function updateTerrainVertexTileHalos(previous, resident, changed, options) {
3437
3461
  const equalPair = (a, b) => a[0] === b[0] && a[1] === b[1];
3438
3462
  if (prior.width !== options.width || prior.height !== options.height || !equalPair(prior.origin ?? [0, 0], options.origin ?? [0, 0]) || !equalPair(prior.columnStep ?? [1, 0], options.columnStep ?? [1, 0]) || !equalPair(prior.rowStep ?? [0, 1], options.rowStep ?? [0, 1]) || (prior.heightReference ?? "unknown") !== (options.heightReference ?? "unknown") || (prior.maxHeightDifference ?? 0) !== (options.maxHeightDifference ?? 0))
3439
3463
  throw new Error("Vertex tile options changed; rebuild the full snapshot");
3440
- const key = (t) => `${t.column},${t.row}`;
3464
+ const key2 = (t) => `${t.column},${t.row}`;
3441
3465
  const affected = getTerrainVertexHaloAffectedTiles(resident, changed, options);
3442
3466
  getTerrainVertexHaloAffectedTiles(previous, [], options);
3443
- const previousMap = new Map(previous.map((tile) => [key(tile), tile]));
3444
- const currentKeys = new Set(resident.map(key));
3445
- const changedKeys = new Set(changed.map(key));
3467
+ const previousMap = new Map(previous.map((tile) => [key2(tile), tile]));
3468
+ const currentKeys = new Set(resident.map(key2));
3469
+ const changedKeys = new Set(changed.map(key2));
3446
3470
  for (const tile of resident) {
3447
- if (!previousMap.has(key(tile)) && !changedKeys.has(key(tile)))
3471
+ if (!previousMap.has(key2(tile)) && !changedKeys.has(key2(tile)))
3448
3472
  throw new Error("Unreported vertex tile arrival");
3449
3473
  }
3450
3474
  const removed = [];
3451
3475
  for (const tile of previous) {
3452
- if (!currentKeys.has(key(tile))) {
3453
- if (!changedKeys.has(key(tile)))
3476
+ if (!currentKeys.has(key2(tile))) {
3477
+ if (!changedKeys.has(key2(tile)))
3454
3478
  throw new Error("Unreported vertex tile eviction");
3455
3479
  removed.push({ column: tile.column, row: tile.row });
3456
3480
  }
3457
3481
  }
3458
3482
  removed.sort((a, b) => a.column - b.column || a.row - b.row);
3459
- const affectedKeys = new Set(affected.map(key));
3483
+ const affectedKeys = new Set(affected.map(key2));
3460
3484
  const rx = options.width === 2 ? 2 : 1;
3461
3485
  const ry = options.height === 2 ? 2 : 1;
3462
3486
  const needed = /* @__PURE__ */ new Set();
@@ -3467,12 +3491,12 @@ function updateTerrainVertexTileHalos(previous, resident, changed, options) {
3467
3491
  if (Number.isSafeInteger(column) && Number.isSafeInteger(row))
3468
3492
  needed.add(`${column},${row}`);
3469
3493
  }
3470
- const source = resident.filter((tile) => needed.has(key(tile)));
3494
+ const source = resident.filter((tile) => needed.has(key2(tile)));
3471
3495
  const rebuilt = createTerrainVertexTileHalos(source, options).tiles;
3472
- const results = new Map(previous.filter((tile) => currentKeys.has(key(tile)) && !affectedKeys.has(key(tile))).map((tile) => [key(tile), tile]));
3496
+ const results = new Map(previous.filter((tile) => currentKeys.has(key2(tile)) && !affectedKeys.has(key2(tile))).map((tile) => [key2(tile), tile]));
3473
3497
  for (const tile of rebuilt)
3474
- if (affectedKeys.has(key(tile)))
3475
- results.set(key(tile), tile);
3498
+ if (affectedKeys.has(key2(tile)))
3499
+ results.set(key2(tile), tile);
3476
3500
  if (results.size !== resident.length)
3477
3501
  throw new Error("Incomplete vertex halo update");
3478
3502
  return {
@@ -3583,9 +3607,9 @@ function stitchTerrainMeshEdges(a, edgeA, b, edgeB, options = {}) {
3583
3607
  let direction = 0;
3584
3608
  for (let i = 0; i < mesh.indices.length; i += 3)
3585
3609
  for (let j = 0; j < 3; j++) {
3586
- const u = mesh.indices[i + j], v = mesh.indices[i + (j + 1) % 3], key = pair(u, v);
3587
- if (pairs.has(key)) {
3588
- pairs.set(key, pairs.get(key) + 1);
3610
+ const u = mesh.indices[i + j], v = mesh.indices[i + (j + 1) % 3], key2 = pair(u, v);
3611
+ if (pairs.has(key2)) {
3612
+ pairs.set(key2, pairs.get(key2) + 1);
3589
3613
  const nextDirection = Math.sign(mesh.gridCoordinates[2 * v + 1 - axis] - mesh.gridCoordinates[2 * u + 1 - axis]);
3590
3614
  if (direction && direction !== nextDirection)
3591
3615
  throw new Error("Inconsistent stitching boundary orientation");
@@ -3824,19 +3848,19 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3824
3848
  throw new Error("Mixed contour frame overflow");
3825
3849
  const onEdge = x === 0 || y === 0 || x === tile.width - 1 || y === tile.height - 1;
3826
3850
  const xi = Math.floor(sx), yi = Math.floor(sy);
3827
- const key = `${level}/${tile.column + xi}/${sx - xi}/${tile.row + yi}/${sy - yi}`;
3851
+ const key2 = `${level}/${tile.column + xi}/${sx - xi}/${tile.row + yi}/${sy - yi}`;
3828
3852
  if (onEdge) {
3829
3853
  const rounded = `${level}/${gx}/${gy}`;
3830
3854
  const identity = roundedBoundary.get(rounded);
3831
- if (identity !== void 0 && identity !== key)
3855
+ if (identity !== void 0 && identity !== key2)
3832
3856
  throw new Error("Mixed contour lattice loses precision");
3833
- roundedBoundary.set(rounded, key);
3857
+ roundedBoundary.set(rounded, key2);
3834
3858
  }
3835
- if (onEdge && local.has(key))
3859
+ if (onEdge && local.has(key2))
3836
3860
  throw new Error("Duplicate mixed contour boundary vertex");
3837
3861
  if (onEdge)
3838
- local.add(key);
3839
- let id = onEdge ? shared.get(key) : void 0;
3862
+ local.add(key2);
3863
+ let id = onEdge ? shared.get(key2) : void 0;
3840
3864
  if (id !== void 0) {
3841
3865
  if (Math.hypot(px - positions[3 * id], py - positions[3 * id + 1]) > tolerance)
3842
3866
  throw new Error("Mixed contour boundary positions disagree");
@@ -3848,7 +3872,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3848
3872
  grid.push(gx, gy);
3849
3873
  vertexLevels.push(level);
3850
3874
  if (onEdge) {
3851
- shared.set(key, id);
3875
+ shared.set(key2, id);
3852
3876
  boundary.add(id);
3853
3877
  }
3854
3878
  }
@@ -3860,10 +3884,10 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3860
3884
  const level = data.levelIndices[i], a = vertex(data.segments[2 * i], level), b = vertex(data.segments[2 * i + 1], level);
3861
3885
  if (a === b || positions[3 * a] === positions[3 * b] && positions[3 * a + 1] === positions[3 * b + 1])
3862
3886
  throw new Error("Degenerate mixed contour segment");
3863
- const key = a < b ? `${a}/${b}` : `${b}/${a}`;
3864
- if (localEdges.has(key))
3887
+ const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
3888
+ if (localEdges.has(key2))
3865
3889
  throw new Error("Duplicate mixed contour segment");
3866
- localEdges.add(key);
3890
+ localEdges.add(key2);
3867
3891
  const box = bounds[ti];
3868
3892
  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]);
3869
3893
  edges.push({ a, b, level, tile: ti, seam });
@@ -3890,8 +3914,8 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3890
3914
  }
3891
3915
  cuts.sort((u, v) => grid[2 * u + axis] - grid[2 * v + axis]);
3892
3916
  for (let i = 1; i < cuts.length; i++) {
3893
- const u = cuts[i - 1], v = cuts[i], key = u < v ? `${u}/${v}` : `${v}/${u}`;
3894
- const prior = emitted.get(key);
3917
+ const u = cuts[i - 1], v = cuts[i], key2 = u < v ? `${u}/${v}` : `${v}/${u}`;
3918
+ const prior = emitted.get(key2);
3895
3919
  if (prior !== void 0) {
3896
3920
  if (prior === edge.tile)
3897
3921
  throw new Error("Overlapping mixed contour segments within tile");
@@ -3899,7 +3923,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3899
3923
  }
3900
3924
  if (levels.length >= limits.maxSegments)
3901
3925
  throw new Error("Mixed contour output segment capacity exceeded");
3902
- emitted.set(key, edge.tile);
3926
+ emitted.set(key2, edge.tile);
3903
3927
  segments.push(u, v);
3904
3928
  levels.push(level);
3905
3929
  }
@@ -3914,4 +3938,1314 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3914
3938
  heightReference: first.heightReference
3915
3939
  };
3916
3940
  }
3941
+
3942
+ // dist/terrain/sample-triangle-height.js
3943
+ function sampleTerrainTriangleHeight(field, x, y) {
3944
+ if (Number.isInteger(x) && Number.isInteger(y))
3945
+ return field.getHeight(x, y);
3946
+ const column = Math.min(Math.floor(x), field.width - 2);
3947
+ const row = Math.min(Math.floor(y), field.height - 2);
3948
+ const u = x - column, v = y - row;
3949
+ let a, b, c, d;
3950
+ if (field.diagonal === "00-11") {
3951
+ if (v <= u) {
3952
+ a = 1 - u;
3953
+ b = u - v;
3954
+ c = 0;
3955
+ d = v;
3956
+ } else {
3957
+ a = 1 - v;
3958
+ b = 0;
3959
+ c = v - u;
3960
+ d = u;
3961
+ }
3962
+ } else if (u + v <= 1) {
3963
+ a = 1 - u - v;
3964
+ b = u;
3965
+ c = v;
3966
+ d = 0;
3967
+ } else {
3968
+ a = 0;
3969
+ b = 1 - v;
3970
+ c = 1 - u;
3971
+ d = u + v - 1;
3972
+ }
3973
+ const za = a ? field.getHeight(column, row) : 0;
3974
+ const zb = b ? field.getHeight(column + 1, row) : 0;
3975
+ const zc = c ? field.getHeight(column, row + 1) : 0;
3976
+ const zd = d ? field.getHeight(column + 1, row + 1) : 0;
3977
+ if (za === void 0 || zb === void 0 || zc === void 0 || zd === void 0)
3978
+ return void 0;
3979
+ const height = a * za + b * zb + c * zc + d * zd;
3980
+ if (!Number.isFinite(height))
3981
+ throw new Error("Terrain triangle numeric sampling failure");
3982
+ return height;
3983
+ }
3984
+
3985
+ // dist/terrain/mixed-vertex-halos.js
3986
+ function createTerrainMixedVertexTileHalos(tiles, options = {}) {
3987
+ return buildMixedVertexTileHalos(tiles, options);
3988
+ }
3989
+ function buildMixedVertexTileHalos(tiles, options = {}, targets) {
3990
+ const maxSamples = options.maxSamples ?? 4e6, maxTests = options.maxTileTests ?? 1e7;
3991
+ if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
3992
+ throw new Error("Invalid mixed halo capacity");
3993
+ let count = 0;
3994
+ const addresses = /* @__PURE__ */ new Set();
3995
+ let frame;
3996
+ const sources = [...tiles].sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row).map((tile) => {
3997
+ if (![tile.column, tile.row, tile.spacing].every(Number.isSafeInteger) || tile.spacing < 1 || 2 ** Math.round(Math.log2(tile.spacing)) !== tile.spacing)
3998
+ throw new Error("Invalid mixed halo lattice");
3999
+ const key2 = `${tile.spacing}/${tile.column}/${tile.row}`;
4000
+ if (addresses.has(key2))
4001
+ throw new Error("Duplicate mixed halo tile");
4002
+ addresses.add(key2);
4003
+ count += (tile.field.width + 2) * (tile.field.height + 2);
4004
+ if (!Number.isSafeInteger(count) || count > maxSamples)
4005
+ throw new Error("Mixed halo sample capacity exceeded");
4006
+ const field = new HeightField(tile.field);
4007
+ if (field.registration !== "vertex")
4008
+ throw new Error("Mixed halos require vertex registration");
4009
+ const column = field.columnStep.map((v) => v / tile.spacing);
4010
+ const row = field.rowStep.map((v) => v / tile.spacing);
4011
+ const origin = field.origin.map((v, axis) => v - tile.column * column[axis] - tile.row * row[axis]);
4012
+ const scale = field.origin.map((v, i) => Math.max(1, Math.abs(v), Math.abs(tile.column * column[i]), Math.abs(tile.row * row[i])));
4013
+ if (!origin.every(Number.isFinite))
4014
+ throw new Error("Mixed halo coordinate overflow");
4015
+ if (frame && (frame.reference !== field.heightReference || column.some((v, i) => v !== frame.column[i]) || row.some((v, i) => v !== frame.row[i]) || origin.some((v, i) => Math.abs(v - frame.origin[i]) > Math.min(16 * Number.EPSILON * Math.max(scale[i], frame.scale[i]), 1e-9 * Math.max(Math.abs(column[i]), Math.abs(row[i]))))))
4016
+ throw new Error("Mixed halo frames or height references differ");
4017
+ frame ?? (frame = { origin, column, row, reference: field.heightReference, scale });
4018
+ return { ...tile, source: field };
4019
+ });
4020
+ for (const axis of ["column", "row"]) {
4021
+ let min = Infinity, max = -Infinity;
4022
+ for (const tile of sources) {
4023
+ const size = axis === "column" ? tile.source.width : tile.source.height;
4024
+ const low = tile[axis] - tile.spacing, high = tile[axis] + size * tile.spacing;
4025
+ if (![low, high].every(Number.isSafeInteger))
4026
+ throw new Error("Mixed halo lattice overflow");
4027
+ min = Math.min(min, low);
4028
+ max = Math.max(max, high);
4029
+ }
4030
+ if (sources.length && !Number.isSafeInteger(max - min))
4031
+ throw new Error("Mixed halo lattice span overflow");
4032
+ }
4033
+ let tests = 0;
4034
+ return {
4035
+ tiles: sources.filter((tile) => !targets || targets.has(`${tile.spacing}/${tile.column}/${tile.row}`)).map((tile) => {
4036
+ const source = tile.source, width = source.width + 2, height = source.height + 2;
4037
+ const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
4038
+ for (let y = 0; y < height; y++)
4039
+ for (let x = 0; x < width; x++) {
4040
+ const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
4041
+ if (![gx, gy].every(Number.isSafeInteger))
4042
+ throw new Error("Mixed halo lattice overflow");
4043
+ for (const candidate of sources) {
4044
+ if (++tests > maxTests)
4045
+ throw new Error("Mixed halo tile-test budget exceeded");
4046
+ const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
4047
+ const f = candidate.source;
4048
+ if (cx < 0 || cy < 0 || cx > f.width - 1 || cy > f.height - 1)
4049
+ continue;
4050
+ const value = sampleTerrainTriangleHeight(f, cx, cy);
4051
+ const i = y * width + x;
4052
+ statuses[i] = value === void 0 ? 1 : 2;
4053
+ if (value !== void 0) {
4054
+ heights[i] = value;
4055
+ validity[i] = 1;
4056
+ }
4057
+ break;
4058
+ }
4059
+ }
4060
+ const origin = [
4061
+ source.origin[0] - source.columnStep[0] - source.rowStep[0],
4062
+ source.origin[1] - source.columnStep[1] - source.rowStep[1]
4063
+ ];
4064
+ if (!origin.every(Number.isFinite))
4065
+ throw new Error("Mixed halo coordinate overflow");
4066
+ return {
4067
+ column: tile.column,
4068
+ row: tile.row,
4069
+ spacing: tile.spacing,
4070
+ statuses,
4071
+ field: {
4072
+ ...tile.field,
4073
+ width,
4074
+ height,
4075
+ heights,
4076
+ validity,
4077
+ offset: 0,
4078
+ stride: width,
4079
+ origin,
4080
+ columnStep: [...source.columnStep],
4081
+ rowStep: [...source.rowStep]
4082
+ }
4083
+ };
4084
+ })
4085
+ };
4086
+ }
4087
+
4088
+ // dist/terrain/mixed-halo-update.js
4089
+ var key = (t) => `${t.spacing}/${t.column}/${t.row}`;
4090
+ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4091
+ const budget = options.maxDependencyTests ?? 1e7;
4092
+ if (!Number.isSafeInteger(budget) || budget < 0)
4093
+ throw new Error("Invalid mixed halo dependency budget");
4094
+ const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4095
+ const current = new Map(resident.map((t) => [key(t), t]));
4096
+ const changed = [...old.values()].filter((t) => current.get(key(t)) !== t).concat(resident.filter((t) => old.get(key(t)) !== t));
4097
+ const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key(t), t]));
4098
+ const targets = /* @__PURE__ */ new Set();
4099
+ let tests = 0;
4100
+ for (const tile of resident) {
4101
+ if (!cached.has(key(tile)))
4102
+ targets.add(key(tile));
4103
+ for (const source of changed) {
4104
+ if (++tests > budget)
4105
+ throw new Error("Mixed halo dependency budget exceeded");
4106
+ 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)
4107
+ targets.add(key(tile));
4108
+ }
4109
+ }
4110
+ const built = buildMixedVertexTileHalos(resident, options, targets).tiles;
4111
+ for (const tile of built)
4112
+ cached.set(key(tile), tile);
4113
+ const tiles = resident.map((t) => cached.get(key(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
4114
+ return {
4115
+ sources: resident.slice(),
4116
+ tiles,
4117
+ rebuilt: built.map(key),
4118
+ removed: [...old.keys()].filter((k) => !current.has(k)).sort()
4119
+ };
4120
+ }
4121
+
4122
+ // dist/terrain/mixed-gradient-update.js
4123
+ function updateTerrainMixedGradientGrids(previous, halos, options = {}) {
4124
+ const method = options.method ?? "horn";
4125
+ if (method !== "horn" && method !== "zevenbergen-thorne")
4126
+ throw new Error("Unknown terrain gradient method");
4127
+ const limit = options.maxSamples ?? 4e6;
4128
+ const count = halos.tiles.reduce((n, t) => n + t.field.width * t.field.height, 0);
4129
+ if (!Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(count) || count > limit)
4130
+ throw new Error("Mixed gradient sample capacity exceeded");
4131
+ const cache = new Map((previous == null ? void 0 : previous.method) === method ? previous.tiles.map((t) => [t.halo, t]) : []);
4132
+ return {
4133
+ method,
4134
+ tiles: halos.tiles.map((halo) => cache.get(halo) ?? {
4135
+ halo,
4136
+ grid: createTerrainGradientGrid(new HeightField(halo.field), { method, maxSamples: limit })
4137
+ })
4138
+ };
4139
+ }
4140
+
4141
+ // dist/terrain/box-index.js
4142
+ var overlaps = (a, b) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
4143
+ function createTerrainBoxIndex(boxes) {
4144
+ const build = (ids) => {
4145
+ const box = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
4146
+ for (const id of ids) {
4147
+ const b = boxes[id];
4148
+ box.minX = Math.min(box.minX, b.minX);
4149
+ box.minY = Math.min(box.minY, b.minY);
4150
+ box.maxX = Math.max(box.maxX, b.maxX);
4151
+ box.maxY = Math.max(box.maxY, b.maxY);
4152
+ }
4153
+ if (ids.length <= 8)
4154
+ return { ...box, ids };
4155
+ const axis = box.maxX - box.minX >= box.maxY - box.minY ? "X" : "Y";
4156
+ 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);
4157
+ const mid = ids.length >>> 1;
4158
+ return { ...box, left: build(ids.slice(0, mid)), right: build(ids.slice(mid)) };
4159
+ };
4160
+ const root = build(boxes.map((_, i) => i));
4161
+ return (query, charge) => {
4162
+ const found = [], stack = [root];
4163
+ while (stack.length) {
4164
+ charge();
4165
+ const node = stack.pop();
4166
+ if (!overlaps(node, query))
4167
+ continue;
4168
+ if (node.ids) {
4169
+ for (const id of node.ids) {
4170
+ charge();
4171
+ if (overlaps(boxes[id], query))
4172
+ found.push(id);
4173
+ }
4174
+ } else
4175
+ stack.push(node.right, node.left);
4176
+ }
4177
+ return found.sort((a, b) => a - b);
4178
+ };
4179
+ }
4180
+
4181
+ // dist/terrain/contour-topology.js
4182
+ var bits = new DataView(new ArrayBuffer(8));
4183
+ function integer(x) {
4184
+ bits.setFloat64(0, x);
4185
+ const high = bits.getUint32(0), low = bits.getUint32(4);
4186
+ const exponent = high >>> 20 & 2047;
4187
+ const mantissa = BigInt(high & 1048575) << 32n | BigInt(low);
4188
+ const value = exponent ? (1n << 52n | mantissa) << BigInt(exponent - 1) : mantissa;
4189
+ return high >>> 31 ? -value : value;
4190
+ }
4191
+ var orientation = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
4192
+ var sign = (v) => v < 0n ? -1 : v > 0n ? 1 : 0;
4193
+ var between = (a, b, p) => p >= (a < b ? a : b) && p <= (a > b ? a : b);
4194
+ var on = (a, b, p) => orientation(a, b, p) === 0n && between(a.x, b.x, p.x) && between(a.y, b.y, p.y);
4195
+ function intersects(a, b, c, d) {
4196
+ return on(a, b, c) || on(a, b, d) || on(c, d, a) || on(c, d, b) || sign(orientation(a, b, c)) * sign(orientation(a, b, d)) < 0 && sign(orientation(c, d, a)) * sign(orientation(c, d, b)) < 0;
4197
+ }
4198
+ function simplifyTerrainContourPathsTopology(paths, options) {
4199
+ if (options.rejection !== void 0 && options.rejection !== "batch" && options.rejection !== "path")
4200
+ throw new Error("Invalid contour rejection policy");
4201
+ const candidate = simplifyTerrainContourPaths(paths, options);
4202
+ const budget = options.maxTopologyTests ?? 1e6;
4203
+ if (!Number.isSafeInteger(budget) || budget < 0)
4204
+ throw new Error("Invalid contour topology budget");
4205
+ let topologyTests = 0;
4206
+ const charge = () => {
4207
+ if (++topologyTests > budget)
4208
+ throw new Error("Contour topology work budget exceeded");
4209
+ };
4210
+ const points = new Array(paths.positions.length / 3);
4211
+ for (const i of new Set(paths.indices))
4212
+ points[i] = { x: integer(paths.positions[3 * i]), y: integer(paths.positions[3 * i + 1]) };
4213
+ const edges = [];
4214
+ for (let p = 0; p < paths.closed.length; p++)
4215
+ for (let i = paths.offsets[p]; i + 1 < paths.offsets[p + 1]; i++)
4216
+ edges.push({ a: paths.indices[i], b: paths.indices[i + 1], p, i });
4217
+ const box = (a, b) => ({
4218
+ minX: Math.min(paths.positions[3 * a], paths.positions[3 * b]),
4219
+ maxX: Math.max(paths.positions[3 * a], paths.positions[3 * b]),
4220
+ minY: Math.min(paths.positions[3 * a + 1], paths.positions[3 * b + 1]),
4221
+ maxY: Math.max(paths.positions[3 * a + 1], paths.positions[3 * b + 1])
4222
+ });
4223
+ const edgeBoxes = edges.map((e) => box(e.a, e.b)), edgeIndex = createTerrainBoxIndex(edgeBoxes);
4224
+ const vertexIds = [...new Set(paths.indices)], vertexIndex = createTerrainBoxIndex(vertexIds.map((v) => box(v, v)));
4225
+ for (let i = 0; i < edges.length; i++)
4226
+ for (const j of edgeIndex(edgeBoxes[i], charge)) {
4227
+ if (j <= i)
4228
+ continue;
4229
+ charge();
4230
+ const a = edges[i], b = edges[j];
4231
+ const common = [a.a, a.b].filter((v) => v === b.a || v === b.b);
4232
+ if (common.length === 1) {
4233
+ const v = common[0], x = a.a === v ? a.b : a.a, y = b.a === v ? b.b : b.a;
4234
+ if (on(points[v], points[x], points[y]) || on(points[v], points[y], points[x]))
4235
+ throw new Error("Overlapping contour edges");
4236
+ } else if (intersects(points[a.a], points[a.b], points[b.a], points[b.b]))
4237
+ throw new Error("Contour input has crossings or unshared touches");
4238
+ }
4239
+ let rejected = false;
4240
+ const rejectedPaths = /* @__PURE__ */ new Set();
4241
+ for (let p = 0; p < paths.closed.length; p++) {
4242
+ let start = paths.offsets[p];
4243
+ for (let k = candidate.offsets[p] + 1; k < candidate.offsets[p + 1]; k++) {
4244
+ const endId = candidate.sourceVertexIndices[candidate.indices[k]];
4245
+ let end = start + 1;
4246
+ while (paths.indices[end] !== endId)
4247
+ end++;
4248
+ if (end > start + 1) {
4249
+ const a = paths.indices[start], b = paths.indices[end];
4250
+ const pa = points[a], pb = points[b];
4251
+ const axis = pa.x !== pb.x ? "x" : "y";
4252
+ const direction = sign(pb[axis] - pa[axis]);
4253
+ let straight = true;
4254
+ for (let i = start + 1; i <= end; i++) {
4255
+ charge();
4256
+ const q = points[paths.indices[i]], prior = points[paths.indices[i - 1]];
4257
+ if (!on(pa, pb, q) || sign(q[axis] - prior[axis]) !== direction)
4258
+ straight = false;
4259
+ }
4260
+ const interior = new Set(Array.from(paths.indices.subarray(start + 1, end)));
4261
+ let unsafe = false;
4262
+ for (const edgeId of edgeIndex(box(a, b), charge)) {
4263
+ const edge = edges[edgeId];
4264
+ if (edge.p === p && edge.i >= start && edge.i < end) {
4265
+ if (straight)
4266
+ continue;
4267
+ charge();
4268
+ const others2 = [edge.a, edge.b].filter((v) => v !== a && v !== b);
4269
+ 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]))
4270
+ unsafe = true;
4271
+ continue;
4272
+ }
4273
+ charge();
4274
+ const others = [edge.a, edge.b].filter((v) => v !== a && v !== b);
4275
+ 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]))
4276
+ unsafe = true;
4277
+ }
4278
+ const swept = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
4279
+ for (let i = start; i <= end; i++) {
4280
+ const v = paths.indices[i];
4281
+ swept.minX = Math.min(swept.minX, paths.positions[3 * v]);
4282
+ swept.maxX = Math.max(swept.maxX, paths.positions[3 * v]);
4283
+ swept.minY = Math.min(swept.minY, paths.positions[3 * v + 1]);
4284
+ swept.maxY = Math.max(swept.maxY, paths.positions[3 * v + 1]);
4285
+ }
4286
+ for (const vertexId of vertexIndex(swept, charge)) {
4287
+ const vertex = vertexIds[vertexId];
4288
+ if (vertex === a || vertex === b || interior.has(vertex))
4289
+ continue;
4290
+ let inside = false;
4291
+ for (let i = start, j = end; i <= end; j = i++) {
4292
+ charge();
4293
+ const u = points[paths.indices[i]], v = points[paths.indices[j]], q = points[vertex];
4294
+ if (on(u, v, q)) {
4295
+ unsafe = true;
4296
+ break;
4297
+ }
4298
+ if (u.y > q.y !== v.y > q.y && orientation(u, v, q) > 0n === v.y > u.y)
4299
+ inside = !inside;
4300
+ }
4301
+ if (inside)
4302
+ unsafe = true;
4303
+ }
4304
+ if (unsafe) {
4305
+ rejected = true;
4306
+ rejectedPaths.add(p);
4307
+ }
4308
+ }
4309
+ start = end;
4310
+ }
4311
+ }
4312
+ const outputEdges = [];
4313
+ for (let p = 0; p < candidate.closed.length; p++)
4314
+ for (let i = candidate.offsets[p]; i + 1 < candidate.offsets[p + 1]; i++)
4315
+ outputEdges.push({
4316
+ p,
4317
+ a: candidate.sourceVertexIndices[candidate.indices[i]],
4318
+ b: candidate.sourceVertexIndices[candidate.indices[i + 1]]
4319
+ });
4320
+ const outputBoxes = outputEdges.map((e) => box(e.a, e.b)), outputIndex = createTerrainBoxIndex(outputBoxes);
4321
+ for (let i = 0; i < outputEdges.length; i++)
4322
+ for (const j of outputIndex(outputBoxes[i], charge)) {
4323
+ if (j <= i)
4324
+ continue;
4325
+ charge();
4326
+ const a = outputEdges[i], b = outputEdges[j];
4327
+ const common = [a.a, a.b].filter((v) => v === b.a || v === b.b);
4328
+ if (common.length === 1) {
4329
+ const v = common[0], x = a.a === v ? a.b : a.a, y = b.a === v ? b.b : b.a;
4330
+ if (on(points[v], points[x], points[y]) || on(points[v], points[y], points[x])) {
4331
+ rejected = true;
4332
+ rejectedPaths.add(a.p);
4333
+ rejectedPaths.add(b.p);
4334
+ }
4335
+ } else if (intersects(points[a.a], points[a.b], points[b.a], points[b.b])) {
4336
+ rejected = true;
4337
+ rejectedPaths.add(a.p);
4338
+ rejectedPaths.add(b.p);
4339
+ }
4340
+ }
4341
+ if (rejected && options.rejection === "path") {
4342
+ const indices = [], offsets = [0];
4343
+ for (let p = 0; p < paths.closed.length; p++) {
4344
+ if (rejectedPaths.has(p))
4345
+ for (let i = paths.offsets[p]; i < paths.offsets[p + 1]; i++)
4346
+ indices.push(paths.indices[i]);
4347
+ else
4348
+ for (let i = candidate.offsets[p]; i < candidate.offsets[p + 1]; i++)
4349
+ indices.push(candidate.sourceVertexIndices[candidate.indices[i]]);
4350
+ offsets.push(indices.length);
4351
+ }
4352
+ return {
4353
+ ...paths,
4354
+ positions: paths.positions.slice(),
4355
+ gridCoordinates: paths.gridCoordinates.slice(),
4356
+ indices: Uint32Array.from(indices),
4357
+ offsets: Uint32Array.from(offsets),
4358
+ closed: paths.closed.slice(),
4359
+ levelIndices: paths.levelIndices.slice(),
4360
+ levels: paths.levels.slice(),
4361
+ origin: Object.freeze([...paths.origin]),
4362
+ sourceVertexIndices: Uint32Array.from({ length: points.length }, (_, i) => i),
4363
+ maxDeviation: candidate.maxDeviation,
4364
+ requestedMaxError: options.maxError,
4365
+ distanceTests: candidate.distanceTests,
4366
+ topologyTests,
4367
+ rejected: true
4368
+ };
4369
+ }
4370
+ if (!rejected)
4371
+ return { ...candidate, topologyTests, rejected: false };
4372
+ return {
4373
+ ...paths,
4374
+ positions: paths.positions.slice(),
4375
+ gridCoordinates: paths.gridCoordinates.slice(),
4376
+ indices: paths.indices.slice(),
4377
+ offsets: paths.offsets.slice(),
4378
+ levelIndices: paths.levelIndices.slice(),
4379
+ closed: paths.closed.slice(),
4380
+ levels: paths.levels.slice(),
4381
+ origin: Object.freeze([...paths.origin]),
4382
+ sourceVertexIndices: Uint32Array.from({ length: points.length }, (_, i) => i),
4383
+ maxDeviation: 0,
4384
+ requestedMaxError: options.maxError,
4385
+ distanceTests: candidate.distanceTests,
4386
+ topologyTests,
4387
+ rejected: true
4388
+ };
4389
+ }
4390
+
4391
+ // dist/terrain/isobands.js
4392
+ function createTerrainIsobands(fields, levels, options = {}) {
4393
+ const maxLevels = options.maxLevels ?? 256;
4394
+ if (!Number.isSafeInteger(maxLevels) || maxLevels < 2 || levels.length > maxLevels)
4395
+ throw new Error("Isoband level capacity exceeded");
4396
+ if (levels.length < 2 || levels.some((v, i) => !Number.isFinite(v) || i > 0 && v <= levels[i - 1]))
4397
+ throw new Error("Invalid isoband levels");
4398
+ const maxTriangles = options.maxTriangles ?? 2e6, maxVertices = options.maxVertices ?? 2e6, maxEdges = options.maxEdges ?? 6 * maxTriangles, maxTests = options.maxTests ?? 32 * maxTriangles;
4399
+ if (![maxTriangles, maxVertices, maxEdges, maxTests].every((n) => Number.isSafeInteger(n) && n >= 0))
4400
+ throw new Error("Invalid isoband capacity");
4401
+ const count = fields.reduce((n, f) => n + 2 * (f.width - 1) * (f.height - 1), 0);
4402
+ if (!Number.isSafeInteger(count) || count > maxTriangles)
4403
+ throw new Error("Isoband triangle capacity exceeded");
4404
+ const originals = /* @__PURE__ */ new Map(), vertices = /* @__PURE__ */ new Map();
4405
+ const frame = fields[0];
4406
+ for (const f of fields)
4407
+ if (f.heightReference !== frame.heightReference)
4408
+ throw new Error("Isoband height references differ");
4409
+ let tests = 0, edgeCount = 0;
4410
+ const charge = () => {
4411
+ if (++tests > maxTests)
4412
+ throw new Error("Isoband work budget exceeded");
4413
+ };
4414
+ const rectangles = fields.map((f) => {
4415
+ if (f.registration !== frame.registration || f.columnStep.some((v, i) => v !== frame.columnStep[i]) || f.rowStep.some((v, i) => v !== frame.rowStep[i]))
4416
+ throw new Error("Isoband tiles require a conforming common frame");
4417
+ const dx = f.origin[0] - frame.origin[0], dy = f.origin[1] - frame.origin[1];
4418
+ const determinant = frame.columnStep[0] * frame.rowStep[1] - frame.columnStep[1] * frame.rowStep[0];
4419
+ const x = Math.round((dx * frame.rowStep[1] - dy * frame.rowStep[0]) / determinant), y = Math.round((dy * frame.columnStep[0] - dx * frame.columnStep[1]) / determinant);
4420
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y))
4421
+ throw new Error("Isoband tiles require integral lattice origins");
4422
+ for (let axis = 0; axis < 2; axis++) {
4423
+ const a = x * frame.columnStep[axis], b = y * frame.rowStep[axis];
4424
+ const expected = frame.origin[axis] + a + b;
4425
+ const tolerance = Math.min(16 * Number.EPSILON * Math.max(1, Math.abs(f.origin[axis]), Math.abs(frame.origin[axis]), Math.abs(a), Math.abs(b)), 1e-9 * Math.max(Math.abs(frame.columnStep[axis]), Math.abs(frame.rowStep[axis])));
4426
+ if (!Number.isFinite(expected) || Math.abs(f.origin[axis] - expected) > tolerance)
4427
+ throw new Error("Isoband tiles require integral lattice origins");
4428
+ }
4429
+ return { x, y, right: x + f.width - 1, top: y + f.height - 1 };
4430
+ });
4431
+ const rectangleBoxes = rectangles.map((r) => ({ minX: r.x, minY: r.y, maxX: r.right, maxY: r.top })), rectangleIndex = createTerrainBoxIndex(rectangleBoxes);
4432
+ const rangeIndex = createTerrainBoxIndex(fields.map((f) => {
4433
+ var _a, _b;
4434
+ return {
4435
+ minX: ((_a = f.heightRange) == null ? void 0 : _a[0]) ?? Infinity,
4436
+ maxX: ((_b = f.heightRange) == null ? void 0 : _b[1]) ?? -Infinity,
4437
+ minY: 0,
4438
+ maxY: 0
4439
+ };
4440
+ }));
4441
+ for (let i = 0; i < rectangles.length; i++)
4442
+ for (const j of rectangleIndex(rectangleBoxes[i], charge)) {
4443
+ if (j <= i)
4444
+ continue;
4445
+ charge();
4446
+ const a = rectangles[i], b = rectangles[j];
4447
+ if (a.x < b.right && b.x < a.right && a.y < b.top && b.y < a.top)
4448
+ throw new Error("Overlapping isoband tiles");
4449
+ for (let y = Math.max(a.y, b.y); y <= Math.min(a.top, b.top); y++)
4450
+ for (let x = Math.max(a.x, b.x); x <= Math.min(a.right, b.right); x++) {
4451
+ charge();
4452
+ const u = fields[i].getHeight(x - a.x, y - a.y), v = fields[j].getHeight(x - b.x, y - b.y);
4453
+ if (u !== void 0 && v !== void 0 && u !== v)
4454
+ throw new Error("Isoband shared heights differ");
4455
+ }
4456
+ }
4457
+ const rings = [], bands = [];
4458
+ const register = (v) => {
4459
+ if (!vertices.has(v.key)) {
4460
+ if (vertices.size >= maxVertices)
4461
+ throw new Error("Isoband vertex capacity exceeded");
4462
+ vertices.set(v.key, v);
4463
+ }
4464
+ return vertices.get(v.key);
4465
+ };
4466
+ const clip = (poly, level, above) => {
4467
+ const out = [];
4468
+ for (let i = 0; i < poly.length; i++) {
4469
+ charge();
4470
+ const a = poly[i], b = poly[(i + 1) % poly.length], ia = above ? a.z >= level : a.z <= level, ib = above ? b.z >= level : b.z <= level;
4471
+ if (ia)
4472
+ out.push(a);
4473
+ if (ia !== ib) {
4474
+ if (a.z === level) {
4475
+ out.push(a);
4476
+ continue;
4477
+ }
4478
+ if (b.z === level) {
4479
+ out.push(b);
4480
+ continue;
4481
+ }
4482
+ const support = [.../* @__PURE__ */ new Set([...a.support, ...b.support])].sort();
4483
+ if (support.length !== 2)
4484
+ throw new Error("Invalid isoband intersection support");
4485
+ const u = originals.get(support[0]), v = originals.get(support[1]);
4486
+ const scale = Math.max(Math.abs(u.z), Math.abs(v.z), Math.abs(level), 1);
4487
+ const t = (level / scale - u.z / scale) / (v.z / scale - u.z / scale);
4488
+ const point = {
4489
+ x: u.x * (1 - t) + v.x * t,
4490
+ y: u.y * (1 - t) + v.y * t,
4491
+ z: level,
4492
+ key: `e:${support.join("|")}:${level}`,
4493
+ support
4494
+ };
4495
+ if (![point.x, point.y, t].every(Number.isFinite))
4496
+ throw new Error("Isoband arithmetic overflow");
4497
+ out.push(register(point));
4498
+ }
4499
+ }
4500
+ return out.filter((v, i) => v.key !== out[(i + 1) % out.length].key);
4501
+ };
4502
+ for (let band = 0; band + 1 < levels.length; band++) {
4503
+ const edges = /* @__PURE__ */ new Map();
4504
+ for (const fieldId of rangeIndex({ minX: levels[band], maxX: levels[band + 1], minY: 0, maxY: 0 }, charge))
4505
+ for (let y = 0; y < fields[fieldId].height - 1; y++)
4506
+ for (let x = 0; x < fields[fieldId].width - 1; x++) {
4507
+ const f = fields[fieldId];
4508
+ const nodes = [
4509
+ [x, y],
4510
+ [x + 1, y],
4511
+ [x, y + 1],
4512
+ [x + 1, y + 1]
4513
+ ].map(([c, r]) => {
4514
+ const z = f.getHeight(c, r);
4515
+ if (z === void 0)
4516
+ return void 0;
4517
+ const shift = f.registration === "cell" ? 0.5 : 0;
4518
+ const px = frame.origin[0] + (rectangles[fieldId].x + c + shift) * frame.columnStep[0] + (rectangles[fieldId].y + r + shift) * frame.rowStep[0], py = frame.origin[1] + (rectangles[fieldId].x + c + shift) * frame.columnStep[1] + (rectangles[fieldId].y + r + shift) * frame.rowStep[1];
4519
+ if (![px, py].every(Number.isFinite))
4520
+ throw new Error("Isoband coordinate overflow");
4521
+ const key2 = `v:${px},${py}`, v = { x: px, y: py, z, key: key2, support: [key2] };
4522
+ const old = originals.get(key2);
4523
+ if (old && old.z !== z)
4524
+ throw new Error("Isoband shared heights differ");
4525
+ originals.set(key2, v);
4526
+ return v;
4527
+ });
4528
+ for (const ids of f.diagonal === "00-11" ? [
4529
+ [0, 1, 3],
4530
+ [0, 3, 2]
4531
+ ] : [
4532
+ [0, 1, 2],
4533
+ [1, 3, 2]
4534
+ ]) {
4535
+ charge();
4536
+ if (ids.some((i) => !nodes[i]))
4537
+ continue;
4538
+ let poly = ids.map((i) => nodes[i]);
4539
+ if (poly.every((v) => v.z === levels[band + 1]) && band + 2 < levels.length)
4540
+ continue;
4541
+ if ((poly[1].x - poly[0].x) * (poly[2].y - poly[0].y) - (poly[1].y - poly[0].y) * (poly[2].x - poly[0].x) < 0)
4542
+ poly.reverse();
4543
+ poly = clip(clip(poly, levels[band], true), levels[band + 1], false);
4544
+ if (poly.length < 3)
4545
+ continue;
4546
+ const area2 = poly.reduce((n, a, i) => {
4547
+ const b = poly[(i + 1) % poly.length], o = poly[0];
4548
+ return n + (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
4549
+ }, 0);
4550
+ if (!Number.isFinite(area2))
4551
+ throw new Error("Isoband area arithmetic overflow");
4552
+ if (area2 === 0)
4553
+ continue;
4554
+ for (let i = 0; i < poly.length; i++) {
4555
+ const a = register(poly[i]), b = register(poly[(i + 1) % poly.length]);
4556
+ if (++edgeCount > maxEdges)
4557
+ throw new Error("Isoband edge capacity exceeded");
4558
+ const key2 = `${a.key}>${b.key}`, reverse = `${b.key}>${a.key}`;
4559
+ if (edges.has(reverse))
4560
+ edges.delete(reverse);
4561
+ else {
4562
+ if (edges.has(key2))
4563
+ throw new Error("Overlapping isoband tiles");
4564
+ edges.set(key2, { a, b });
4565
+ }
4566
+ }
4567
+ }
4568
+ }
4569
+ const outgoing = /* @__PURE__ */ new Map();
4570
+ for (const [key2, e] of edges) {
4571
+ if (!outgoing.has(e.a.key))
4572
+ outgoing.set(e.a.key, /* @__PURE__ */ new Set());
4573
+ outgoing.get(e.a.key).add(key2);
4574
+ }
4575
+ while (edges.size) {
4576
+ const first = edges.values().next().value, ring = [];
4577
+ let edge = first;
4578
+ for (; ; ) {
4579
+ charge();
4580
+ ring.push(edge.a);
4581
+ edges.delete(`${edge.a.key}>${edge.b.key}`);
4582
+ outgoing.get(edge.a.key).delete(`${edge.a.key}>${edge.b.key}`);
4583
+ if (edge.b.key === first.a.key)
4584
+ break;
4585
+ const choices = [...outgoing.get(edge.b.key) ?? []].map((k) => edges.get(k));
4586
+ if (!choices.length)
4587
+ throw new Error("Open isoband boundary");
4588
+ 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));
4589
+ choices.sort((a, b) => angle(b) - angle(a) || a.b.key.localeCompare(b.b.key));
4590
+ edge = choices[0];
4591
+ }
4592
+ rings.push(ring);
4593
+ bands.push(band);
4594
+ }
4595
+ }
4596
+ const area = (ring) => ring.reduce((n, a, i) => {
4597
+ const b = ring[(i + 1) % ring.length], o = ring[0];
4598
+ return n + (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
4599
+ }, 0);
4600
+ const areas = rings.map(area), parents = new Int32Array(rings.length).fill(-1);
4601
+ const ringBoxes = rings.map((r) => r.reduce((b, v) => ({
4602
+ minX: Math.min(b.minX, v.x),
4603
+ minY: Math.min(b.minY, v.y),
4604
+ maxX: Math.max(b.maxX, v.x),
4605
+ maxY: Math.max(b.maxY, v.y)
4606
+ }), { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }));
4607
+ const ringIndex = createTerrainBoxIndex(ringBoxes);
4608
+ for (let i = 0; i < rings.length; i++)
4609
+ if (areas[i] < 0) {
4610
+ let best = Infinity;
4611
+ const q = rings[i][0];
4612
+ for (const j of ringIndex({ minX: q.x, maxX: q.x, minY: q.y, maxY: q.y }, charge))
4613
+ if (bands[j] === bands[i] && areas[j] > 0) {
4614
+ let inside = false;
4615
+ const ring = rings[j];
4616
+ for (let k = 0, l = ring.length - 1; k < ring.length; l = k++) {
4617
+ charge();
4618
+ const a = ring[k], b = ring[l];
4619
+ if (a.y > q.y !== b.y > q.y && q.x < (b.x - a.x) * (q.y - a.y) / (b.y - a.y) + a.x)
4620
+ inside = !inside;
4621
+ }
4622
+ if (inside && areas[j] < best) {
4623
+ parents[i] = j;
4624
+ best = areas[j];
4625
+ }
4626
+ }
4627
+ if (parents[i] < 0)
4628
+ throw new Error("Uncontained isoband hole");
4629
+ }
4630
+ const used = /* @__PURE__ */ new Map(), positions = [], indices = [], offsets = [0];
4631
+ for (const ring of rings) {
4632
+ for (const v of [...ring, ring[0]]) {
4633
+ if (!used.has(v.key)) {
4634
+ used.set(v.key, used.size);
4635
+ positions.push(v.x, v.y);
4636
+ }
4637
+ indices.push(used.get(v.key));
4638
+ }
4639
+ offsets.push(indices.length);
4640
+ }
4641
+ return {
4642
+ positions: Float64Array.from(positions),
4643
+ indices: Uint32Array.from(indices),
4644
+ offsets: Uint32Array.from(offsets),
4645
+ bandIndices: Uint32Array.from(bands),
4646
+ parents,
4647
+ levels: Float64Array.from(levels),
4648
+ heightReference: (frame == null ? void 0 : frame.heightReference) ?? "unknown"
4649
+ };
4650
+ }
4651
+
4652
+ // dist/terrain/tile-update-data.js
4653
+ function updateTerrainTileData(previous, resident, create, maxSamples = 4e6) {
4654
+ if (!Number.isSafeInteger(maxSamples) || maxSamples < 0)
4655
+ throw new Error("Invalid terrain update sample capacity");
4656
+ let count = 0;
4657
+ const ids = /* @__PURE__ */ new Set();
4658
+ for (const tile of resident) {
4659
+ if (typeof tile.id !== "string" || ids.has(tile.id))
4660
+ throw new Error("Invalid or duplicate terrain update tile");
4661
+ ids.add(tile.id);
4662
+ count += tile.field.width * tile.field.height;
4663
+ if (!Number.isSafeInteger(count) || count > maxSamples)
4664
+ throw new Error("Terrain update sample capacity exceeded");
4665
+ }
4666
+ const cached = new Map(previous == null ? void 0 : previous.map((t) => [t.source.id, t]));
4667
+ return resident.map((source) => {
4668
+ const old = cached.get(source.id);
4669
+ return (old == null ? void 0 : old.source.field) === source.field ? { source, data: old.data } : { source, data: create(source.field) };
4670
+ });
4671
+ }
4672
+
4673
+ // dist/terrain/mesh-update.js
4674
+ function updateTerrainMeshes(previous, resident, options = {}) {
4675
+ return updateTerrainTileData(previous, resident, createTerrainMesh, options.maxSamples);
4676
+ }
4677
+
4678
+ // dist/terrain/bounds-update.js
4679
+ function updateTerrainBounds(previous, resident, options = {}) {
4680
+ return updateTerrainTileData(previous, resident, (f) => new HeightFieldMinMax(f), options.maxSamples);
4681
+ }
4682
+
4683
+ // dist/terrain/gradient-pyramid-update.js
4684
+ function updateTerrainGradientPyramids(previous, gradients, options = {}) {
4685
+ const limit = options.maxSamples ?? 4e6;
4686
+ const count = gradients.tiles.reduce((n, t) => n + t.grid.width * t.grid.height, 0);
4687
+ if (!Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(count) || count > limit)
4688
+ throw new Error("Gradient pyramid update sample capacity exceeded");
4689
+ const cached = new Map(previous == null ? void 0 : previous.map((t) => [t.source.grid, t.data]));
4690
+ return gradients.tiles.map((source) => ({
4691
+ source,
4692
+ data: cached.get(source.grid) ?? createTerrainGradientPyramid(source.grid, { maxSamples: limit })
4693
+ }));
4694
+ }
4695
+
4696
+ // dist/terrain/dirty-regions.js
4697
+ function validateTerrainDirtyWindows(windows, width, height, maxWindows = 1e5) {
4698
+ if (windows.length > maxWindows)
4699
+ throw new Error("Terrain dirty window capacity exceeded");
4700
+ for (const w of windows)
4701
+ if (![w.minColumn, w.minRow, w.maxColumn, w.maxRow].every(Number.isSafeInteger) || w.minColumn < 0 || w.minRow < 0 || w.maxColumn >= width || w.maxRow >= height || w.minColumn > w.maxColumn || w.minRow > w.maxRow)
4702
+ throw new Error("Invalid terrain dirty sample window");
4703
+ }
4704
+ function sameTerrainFrame(a, b) {
4705
+ return a.width === b.width && a.height === b.height && a.registration === b.registration && a.diagonal === b.diagonal && a.heightReference === b.heightReference && a.origin.every((v, i) => v === b.origin[i]) && a.columnStep.every((v, i) => v === b.columnStep[i]) && a.rowStep.every((v, i) => v === b.rowStep[i]);
4706
+ }
4707
+ function terrainDirtyIndices(windows, width, height, expand, charge) {
4708
+ const ids = /* @__PURE__ */ new Set();
4709
+ for (const w of windows)
4710
+ for (let y = Math.max(0, w.minRow - expand); y <= Math.min(height - 1, w.maxRow + expand); y++)
4711
+ for (let x = Math.max(0, w.minColumn - expand); x <= Math.min(width - 1, w.maxColumn + expand); x++) {
4712
+ charge();
4713
+ ids.add(y * width + x);
4714
+ }
4715
+ return ids;
4716
+ }
4717
+
4718
+ // dist/terrain/mesh-regions-data.js
4719
+ function updateMeshRegions(previous, field, dirty, options, configuration, create) {
4720
+ const cells = options.cellsPerRegion ?? 32, limit = options.maxSamples ?? 4e6, budget = options.maxTests ?? 1e7;
4721
+ if (![cells, limit, budget].every(Number.isSafeInteger) || cells < 1 || limit < 0 || budget < 0)
4722
+ throw new Error("Invalid terrain mesh region capacity");
4723
+ validateTerrainDirtyWindows(dirty, field.width, field.height);
4724
+ let count = 0, tests = 0;
4725
+ const regions = [], rebuilt = [];
4726
+ const reusable = previous && sameTerrainFrame(previous.field, field) && previous.cellsPerRegion === cells && previous.configuration === configuration;
4727
+ const cache = new Map(previous == null ? void 0 : previous.regions.map((r) => [`${r.column},${r.row}`, r]));
4728
+ for (let row = 0; row < field.height - 1; row += cells)
4729
+ for (let column = 0; column < field.width - 1; column += cells) {
4730
+ const width = Math.min(cells, field.width - 1 - column) + 1, height = Math.min(cells, field.height - 1 - row) + 1;
4731
+ count += width * height;
4732
+ if (!Number.isSafeInteger(count) || count > limit)
4733
+ throw new Error("Terrain mesh region sample capacity exceeded");
4734
+ let affected = !reusable;
4735
+ for (const w of reusable ? dirty : []) {
4736
+ if (++tests > budget)
4737
+ throw new Error("Terrain mesh region work budget exceeded");
4738
+ if (w.minColumn <= column + width - 1 && w.maxColumn >= column && w.minRow <= row + height - 1 && w.maxRow >= row)
4739
+ affected = true;
4740
+ }
4741
+ const old = cache.get(`${column},${row}`);
4742
+ if (!affected && old) {
4743
+ regions.push(old);
4744
+ continue;
4745
+ }
4746
+ const heights = Float64Array.from({ length: width * height }, (_, i) => field.getHeight(column + i % width, row + Math.floor(i / width)) ?? NaN);
4747
+ const source = new HeightField({
4748
+ width,
4749
+ height,
4750
+ heights,
4751
+ origin: [
4752
+ column * field.columnStep[0] + row * field.rowStep[0],
4753
+ column * field.columnStep[1] + row * field.rowStep[1]
4754
+ ],
4755
+ columnStep: field.columnStep,
4756
+ rowStep: field.rowStep,
4757
+ registration: field.registration,
4758
+ diagonal: field.diagonal,
4759
+ heightReference: field.heightReference
4760
+ });
4761
+ rebuilt.push(regions.length);
4762
+ let data = create(source);
4763
+ if (data) {
4764
+ const mesh = data;
4765
+ const positions = mesh.positions.map((value, i) => {
4766
+ const axis = i % 3;
4767
+ if (axis === 2)
4768
+ return value;
4769
+ const vertex = Math.floor(i / 3), shift = field.registration === "cell" ? 0.5 : 0;
4770
+ const c = column + mesh.gridCoordinates[2 * vertex] + shift, r = row + mesh.gridCoordinates[2 * vertex + 1] + shift;
4771
+ const coordinate = c * field.columnStep[axis] + r * field.rowStep[axis];
4772
+ if (!Number.isFinite(coordinate))
4773
+ throw new Error("Terrain region coordinate overflow");
4774
+ return coordinate;
4775
+ });
4776
+ data = { ...mesh, origin: [0, 0, 0], positions };
4777
+ }
4778
+ regions.push({ column, row, field: source, data });
4779
+ }
4780
+ return {
4781
+ field,
4782
+ origin: [field.origin[0], field.origin[1], 0],
4783
+ cellsPerRegion: cells,
4784
+ configuration,
4785
+ regions,
4786
+ rebuilt: Uint32Array.from(rebuilt)
4787
+ };
4788
+ }
4789
+
4790
+ // dist/terrain/mesh-regions.js
4791
+ function updateTerrainMeshRegions(previous, field, dirty, options = {}) {
4792
+ return updateMeshRegions(previous, field, dirty, options, "regular", createTerrainMesh);
4793
+ }
4794
+
4795
+ // dist/terrain/martini-regions.js
4796
+ function updateTerrainMartiniMeshRegions(previous, field, dirty, options) {
4797
+ const cells = options.cellsPerRegion ?? 32;
4798
+ if (!Number.isSafeInteger(cells) || cells < 1 || cells > 32768 || (cells & cells - 1) !== 0 || (field.width - 1) % cells || (field.height - 1) % cells || !Number.isFinite(options.maxError) || options.maxError < 0)
4799
+ throw new Error("Invalid MARTINI region dimensions or error");
4800
+ return updateMeshRegions(previous, field, dirty, options, `martini:${options.maxError}`, (f) => f.validCount !== f.width * f.height ? null : createMartiniTerrainMesh(f, {
4801
+ maxError: options.maxError,
4802
+ fullEdges: ["minColumn", "maxColumn", "minRow", "maxRow"]
4803
+ }));
4804
+ }
4805
+
4806
+ // dist/terrain/delatin-regions.js
4807
+ function updateTerrainDelatinMeshRegions(previous, field, dirty, options) {
4808
+ if (!Number.isFinite(options.maxError) || options.maxError < 0)
4809
+ throw new Error("Invalid Delatin region error");
4810
+ return updateMeshRegions(previous, field, dirty, options, `delatin:${options.maxError}`, (f) => f.validCount !== f.width * f.height ? null : createDelatinTerrainMesh(f, { maxError: options.maxError }));
4811
+ }
4812
+
4813
+ // dist/terrain/bounds-regions.js
4814
+ function updateTerrainBoundsRegions(previous, field, dirty, options = {}) {
4815
+ const limit = options.maxSamples ?? 4e6, budget = options.maxTests ?? 1e7;
4816
+ if (![limit, budget].every(Number.isSafeInteger) || limit < 0 || budget < 0 || field.width * field.height > limit)
4817
+ throw new Error("Invalid bounds region capacity");
4818
+ validateTerrainDirtyWindows(dirty, field.width, field.height);
4819
+ if (!previous || !sameTerrainFrame(previous.field, field)) {
4820
+ const bounds = new HeightFieldMinMax(field), levels2 = Array.from({ length: bounds.levelCount }, (_, i) => bounds.copyLevel(i));
4821
+ return { field, levels: levels2, updatedCounts: Uint32Array.from(levels2, (l) => l.width * l.height) };
4822
+ }
4823
+ let tests = 0;
4824
+ const charge = () => {
4825
+ if (++tests > budget)
4826
+ throw new Error("Bounds region work budget exceeded");
4827
+ };
4828
+ let ids = terrainDirtyIndices(dirty, field.width - 1, field.height - 1, 1, charge);
4829
+ const counts = [], levels = previous.levels.slice();
4830
+ for (let l = 0; l < levels.length; l++) {
4831
+ counts.push(ids.size);
4832
+ if (!ids.size)
4833
+ continue;
4834
+ const old = levels[l], next = {
4835
+ ...old,
4836
+ minimums: old.minimums.slice(),
4837
+ maximums: old.maximums.slice(),
4838
+ populatedCellCounts: old.populatedCellCounts.slice(),
4839
+ completeCellCounts: old.completeCellCounts.slice()
4840
+ };
4841
+ const parents = /* @__PURE__ */ new Set();
4842
+ for (const id of ids) {
4843
+ charge();
4844
+ const x = id % next.width, y = Math.floor(id / next.width);
4845
+ let min = Infinity, max = -Infinity, populated = 0, complete = 0;
4846
+ if (l === 0) {
4847
+ let valid = 0;
4848
+ for (let dy = 0; dy < 2; dy++)
4849
+ for (let dx = 0; dx < 2; dx++) {
4850
+ const h = field.getHeight(x + dx, y + dy);
4851
+ if (h !== void 0) {
4852
+ valid++;
4853
+ min = Math.min(min, h);
4854
+ max = Math.max(max, h);
4855
+ }
4856
+ }
4857
+ populated = valid ? 1 : 0;
4858
+ complete = valid === 4 ? 1 : 0;
4859
+ } else {
4860
+ const child = levels[l - 1];
4861
+ for (let dy = 0; dy < 2; dy++)
4862
+ for (let dx = 0; dx < 2; dx++) {
4863
+ const cx = x * 2 + dx, cy = y * 2 + dy;
4864
+ if (cx >= child.width || cy >= child.height)
4865
+ continue;
4866
+ const i = cy * child.width + cx;
4867
+ if (child.populatedCellCounts[i]) {
4868
+ min = Math.min(min, child.minimums[i]);
4869
+ max = Math.max(max, child.maximums[i]);
4870
+ }
4871
+ populated += child.populatedCellCounts[i];
4872
+ complete += child.completeCellCounts[i];
4873
+ }
4874
+ }
4875
+ next.minimums[id] = populated ? min : 0;
4876
+ next.maximums[id] = populated ? max : 0;
4877
+ next.populatedCellCounts[id] = populated;
4878
+ next.completeCellCounts[id] = complete;
4879
+ parents.add(Math.floor(y / 2) * Math.ceil(next.width / 2) + Math.floor(x / 2));
4880
+ }
4881
+ levels[l] = next;
4882
+ ids = parents;
4883
+ }
4884
+ return { field, levels, updatedCounts: Uint32Array.from(counts) };
4885
+ }
4886
+
4887
+ // dist/terrain/gradient-pyramid-regions.js
4888
+ function updateTerrainGradientPyramidRegions(previous, grid, dirty, options = {}) {
4889
+ const limit = options.maxSamples ?? 4e6, budget = options.maxTests ?? 1e7;
4890
+ if (![limit, budget].every(Number.isSafeInteger) || limit < 0 || budget < 0 || !Number.isSafeInteger(grid.width) || grid.width < 1 || !Number.isSafeInteger(grid.height) || grid.height < 1 || grid.width * grid.height > limit)
4891
+ throw new Error("Invalid gradient region capacity");
4892
+ if (grid.method !== "horn" && grid.method !== "zevenbergen-thorne" || grid.registration !== "vertex" && grid.registration !== "cell" || typeof grid.heightReference !== "string" || ![grid.origin, grid.columnStep, grid.rowStep].every((v) => v.length === 2 && v.every(Number.isFinite)))
4893
+ throw new Error("Invalid gradient region metadata");
4894
+ validateTerrainDirtyWindows(dirty, grid.width, grid.height);
4895
+ const old = previous == null ? void 0 : previous.source;
4896
+ if (!old || old.width !== grid.width || old.height !== grid.height || old.method !== grid.method || old.registration !== grid.registration || old.heightReference !== grid.heightReference || !old.origin.every((v, i) => v === grid.origin[i]) || !old.columnStep.every((v, i) => v === grid.columnStep[i]) || !old.rowStep.every((v, i) => v === grid.rowStep[i])) {
4897
+ const pyramid = createTerrainGradientPyramid(grid, { maxSamples: limit });
4898
+ return {
4899
+ source: grid,
4900
+ pyramid,
4901
+ updatedCounts: Uint32Array.from(pyramid.levels, (l) => l.width * l.height)
4902
+ };
4903
+ }
4904
+ if (!(grid.gradients instanceof Float64Array) || grid.gradients.length !== 2 * grid.width * grid.height || !(grid.statuses instanceof Uint8Array) || grid.statuses.length !== grid.width * grid.height)
4905
+ throw new Error("Invalid gradient region buffers");
4906
+ const levels = previous.pyramid.levels.slice();
4907
+ let tests = 0;
4908
+ const charge = () => {
4909
+ if (++tests > budget)
4910
+ throw new Error("Gradient region work budget exceeded");
4911
+ };
4912
+ let ids = terrainDirtyIndices(dirty, grid.width, grid.height, 0, charge);
4913
+ const counts = [];
4914
+ for (let l = 0; l < levels.length; l++) {
4915
+ counts.push(ids.size);
4916
+ if (!ids.size)
4917
+ continue;
4918
+ const oldLevel = levels[l], next = {
4919
+ ...oldLevel,
4920
+ gradients: oldLevel.gradients.slice(),
4921
+ validCounts: oldLevel.validCounts.slice(),
4922
+ sampleCounts: oldLevel.sampleCounts
4923
+ };
4924
+ const parents = /* @__PURE__ */ new Set();
4925
+ for (const id of ids) {
4926
+ charge();
4927
+ const x = id % next.width, y = Math.floor(id / next.width);
4928
+ next.validCounts[id] = 0;
4929
+ next.gradients[2 * id] = next.gradients[2 * id + 1] = 0;
4930
+ if (l === 0) {
4931
+ if (grid.statuses[id] > 6)
4932
+ throw new Error("Invalid terrain gradient status");
4933
+ if (grid.statuses[id] === 0) {
4934
+ if (!Number.isFinite(grid.gradients[2 * id]) || !Number.isFinite(grid.gradients[2 * id + 1]))
4935
+ throw new Error("Invalid terrain gradient value");
4936
+ next.validCounts[id] = 1;
4937
+ next.gradients[2 * id] = grid.gradients[2 * id];
4938
+ next.gradients[2 * id + 1] = grid.gradients[2 * id + 1];
4939
+ }
4940
+ } else {
4941
+ const child = levels[l - 1];
4942
+ for (let dy = 0; dy < 2; dy++)
4943
+ for (let dx = 0; dx < 2; dx++) {
4944
+ const cx = x * 2 + dx, cy = y * 2 + dy;
4945
+ if (cx >= child.width || cy >= child.height)
4946
+ continue;
4947
+ const i = cy * child.width + cx, n = child.validCounts[i], count = next.validCounts[id];
4948
+ if (n) {
4949
+ const total = count + n;
4950
+ for (let axis = 0; axis < 2; axis++) {
4951
+ const a = next.gradients[2 * id + axis], b = child.gradients[2 * i + axis];
4952
+ next.gradients[2 * id + axis] = count ? a * (count / total) + b * (n / total) : b;
4953
+ }
4954
+ next.validCounts[id] = total;
4955
+ }
4956
+ }
4957
+ }
4958
+ parents.add(Math.floor(y / 2) * Math.ceil(next.width / 2) + Math.floor(x / 2));
4959
+ }
4960
+ levels[l] = next;
4961
+ ids = parents;
4962
+ }
4963
+ return {
4964
+ source: grid,
4965
+ pyramid: { ...previous.pyramid, levels },
4966
+ updatedCounts: Uint32Array.from(counts)
4967
+ };
4968
+ }
4969
+
4970
+ // dist/terrain/persistent-hierarchy-data.js
4971
+ function getTerrainHierarchyNode(level, column, row) {
4972
+ if (!Number.isSafeInteger(level.width) || level.width < 1 || !Number.isSafeInteger(level.height) || level.height < 1 || !Number.isSafeInteger(level.nodesPerBlock) || level.nodesPerBlock < 1 || !Array.isArray(level.blocks))
4973
+ throw new Error("Invalid persistent hierarchy level");
4974
+ if (!Number.isSafeInteger(column) || !Number.isSafeInteger(row) || column < 0 || row < 0 || column >= level.width || row >= level.height)
4975
+ throw new Error("Invalid persistent hierarchy node");
4976
+ const id = row * level.width + column, block = level.blocks[Math.floor(id / level.nodesPerBlock)], i = block ? 2 * (id - block.offset) : -1;
4977
+ const expectedOffset = Math.floor(id / level.nodesPerBlock) * level.nodesPerBlock;
4978
+ if (!block || block.offset !== expectedOffset || block.count !== Math.min(level.nodesPerBlock, level.width * level.height - expectedOffset) || !(block.values instanceof Float64Array) || !(block.counts instanceof Uint32Array) || block.values.length !== 2 * block.count || block.counts.length !== 2 * block.count)
4979
+ throw new Error("Invalid persistent hierarchy block");
4980
+ return {
4981
+ values: [block.values[i], block.values[i + 1]],
4982
+ counts: [block.counts[i], block.counts[i + 1]]
4983
+ };
4984
+ }
4985
+ function packTerrainHierarchyLevel(width, height, blockSize, values, counts, nodesPerBlock) {
4986
+ if (values.length !== 2 * width * height || counts.length !== values.length || !values.every(Number.isFinite))
4987
+ throw new Error("Invalid persistent hierarchy buffers");
4988
+ const blocks = [];
4989
+ for (let offset = 0; offset < width * height; offset += nodesPerBlock) {
4990
+ const count = Math.min(nodesPerBlock, width * height - offset);
4991
+ blocks.push({
4992
+ offset,
4993
+ count,
4994
+ values: values.slice(2 * offset, 2 * (offset + count)),
4995
+ counts: counts.slice(2 * offset, 2 * (offset + count))
4996
+ });
4997
+ }
4998
+ return { width, height, blockSize, nodesPerBlock, blocks };
4999
+ }
5000
+ function persistentHierarchyOptions(options, count) {
5001
+ const nodesPerBlock = options.nodesPerBlock ?? 256, maxSamples = options.maxSamples ?? 4e6, maxTests = options.maxTests ?? 1e7;
5002
+ if (![nodesPerBlock, maxSamples, maxTests, count].every(Number.isSafeInteger) || nodesPerBlock < 1 || maxSamples < 0 || maxTests < 0 || count < 1 || count > maxSamples)
5003
+ throw new Error("Invalid persistent terrain hierarchy capacity");
5004
+ let tests = 0;
5005
+ return {
5006
+ nodesPerBlock,
5007
+ maxSamples,
5008
+ charge: () => {
5009
+ if (++tests > maxTests)
5010
+ throw new Error("Persistent hierarchy work budget exceeded");
5011
+ }
5012
+ };
5013
+ }
5014
+ function updatePersistentHierarchy(previous, ids, mode, base, charge) {
5015
+ const levels = previous.slice(), updatedNodes = [];
5016
+ let copiedBlocks = 0, copiedBytes = 0;
5017
+ for (let l = 0; l < levels.length; l++) {
5018
+ updatedNodes.push(ids.size);
5019
+ if (!ids.size)
5020
+ continue;
5021
+ const old = levels[l], blocks = old.blocks.slice(), cloned = /* @__PURE__ */ new Set(), parents = /* @__PURE__ */ new Set();
5022
+ const node = (level, x, y) => getTerrainHierarchyNode(level, x, y);
5023
+ for (const id of ids) {
5024
+ charge();
5025
+ const x = id % old.width, y = Math.floor(id / old.width);
5026
+ let value;
5027
+ if (l === 0)
5028
+ value = base(x, y);
5029
+ else {
5030
+ const child = levels[l - 1];
5031
+ let a = mode === "bounds" ? Infinity : 0, b = mode === "bounds" ? -Infinity : 0, c = 0, d = 0;
5032
+ for (let dy = 0; dy < 2; dy++)
5033
+ for (let dx = 0; dx < 2; dx++) {
5034
+ const cx = x * 2 + dx, cy = y * 2 + dy;
5035
+ if (cx >= child.width || cy >= child.height)
5036
+ continue;
5037
+ const v = node(child, cx, cy), n = v.counts[0];
5038
+ d += v.counts[1];
5039
+ if (n) {
5040
+ if (mode === "bounds") {
5041
+ a = Math.min(a, v.values[0]);
5042
+ b = Math.max(b, v.values[1]);
5043
+ } else {
5044
+ const total = c + n;
5045
+ a = c ? a * (c / total) + v.values[0] * (n / total) : v.values[0];
5046
+ b = c ? b * (c / total) + v.values[1] * (n / total) : v.values[1];
5047
+ }
5048
+ c += n;
5049
+ }
5050
+ }
5051
+ if (c && (!Number.isFinite(a) || !Number.isFinite(b)))
5052
+ throw new Error("Persistent hierarchy arithmetic overflow");
5053
+ value = { values: c ? [a, b] : [0, 0], counts: [c, d] };
5054
+ }
5055
+ const blockId = Math.floor(id / old.nodesPerBlock);
5056
+ if (!cloned.has(blockId)) {
5057
+ const source = blocks[blockId];
5058
+ blocks[blockId] = { ...source, values: source.values.slice(), counts: source.counts.slice() };
5059
+ cloned.add(blockId);
5060
+ copiedBlocks++;
5061
+ copiedBytes += blocks[blockId].values.byteLength + blocks[blockId].counts.byteLength;
5062
+ }
5063
+ const block = blocks[blockId], i = 2 * (id - block.offset);
5064
+ block.values[i] = value.values[0];
5065
+ block.values[i + 1] = value.values[1];
5066
+ block.counts[i] = value.counts[0];
5067
+ block.counts[i + 1] = value.counts[1];
5068
+ parents.add(Math.floor(y / 2) * Math.ceil(old.width / 2) + Math.floor(x / 2));
5069
+ }
5070
+ levels[l] = { ...old, blocks };
5071
+ ids = parents;
5072
+ }
5073
+ return { levels, stats: { copiedBlocks, copiedBytes, updatedNodes: Uint32Array.from(updatedNodes) } };
5074
+ }
5075
+
5076
+ // dist/terrain/persistent-bounds.js
5077
+ function updateTerrainPersistentBounds(previous, field, dirty, options = {}) {
5078
+ const { nodesPerBlock, charge } = persistentHierarchyOptions(options, field.width * field.height);
5079
+ validateTerrainDirtyWindows(dirty, field.width, field.height);
5080
+ if (!previous || !sameTerrainFrame(previous.field, field) || previous.levels[0].nodesPerBlock !== nodesPerBlock) {
5081
+ const bounds = new HeightFieldMinMax(field), levels = Array.from({ length: bounds.levelCount }, (_, i) => {
5082
+ const l = bounds.copyLevel(i), values = new Float64Array(2 * l.width * l.height), counts = new Uint32Array(values.length);
5083
+ for (let j = 0; j < l.width * l.height; j++) {
5084
+ values[2 * j] = l.minimums[j];
5085
+ values[2 * j + 1] = l.maximums[j];
5086
+ counts[2 * j] = l.populatedCellCounts[j];
5087
+ counts[2 * j + 1] = l.completeCellCounts[j];
5088
+ }
5089
+ return packTerrainHierarchyLevel(l.width, l.height, l.blockSize, values, counts, nodesPerBlock);
5090
+ });
5091
+ return {
5092
+ field,
5093
+ levels,
5094
+ stats: {
5095
+ copiedBlocks: levels.reduce((n, l) => n + l.blocks.length, 0),
5096
+ copiedBytes: levels.reduce((n, l) => n + l.blocks.reduce((s, b) => s + b.values.byteLength + b.counts.byteLength, 0), 0),
5097
+ updatedNodes: Uint32Array.from(levels, (l) => l.width * l.height)
5098
+ }
5099
+ };
5100
+ }
5101
+ const ids = terrainDirtyIndices(dirty, field.width - 1, field.height - 1, 1, charge);
5102
+ const result = updatePersistentHierarchy(previous.levels, ids, "bounds", (x, y) => {
5103
+ let min = Infinity, max = -Infinity, n = 0;
5104
+ for (let dy = 0; dy < 2; dy++)
5105
+ for (let dx = 0; dx < 2; dx++) {
5106
+ const z = field.getHeight(x + dx, y + dy);
5107
+ if (z !== void 0) {
5108
+ min = Math.min(min, z);
5109
+ max = Math.max(max, z);
5110
+ n++;
5111
+ }
5112
+ }
5113
+ return { values: n ? [min, max] : [0, 0], counts: [n ? 1 : 0, n === 4 ? 1 : 0] };
5114
+ }, charge);
5115
+ return { field, ...result };
5116
+ }
5117
+
5118
+ // dist/terrain/persistent-gradients.js
5119
+ function updateTerrainPersistentGradients(previous, grid, dirty, options = {}) {
5120
+ const { nodesPerBlock, maxSamples, charge } = persistentHierarchyOptions(options, grid.width * grid.height);
5121
+ if (!Number.isSafeInteger(grid.width) || grid.width < 1 || !Number.isSafeInteger(grid.height) || grid.height < 1 || !(grid.gradients instanceof Float64Array) || grid.gradients.length !== 2 * grid.width * grid.height || !(grid.statuses instanceof Uint8Array) || grid.statuses.length !== grid.width * grid.height || grid.method !== "horn" && grid.method !== "zevenbergen-thorne" || grid.registration !== "vertex" && grid.registration !== "cell" || typeof grid.heightReference !== "string" || ![grid.origin, grid.columnStep, grid.rowStep].every((v) => v.length === 2 && v.every(Number.isFinite)))
5122
+ throw new Error("Invalid persistent gradient grid");
5123
+ validateTerrainDirtyWindows(dirty, grid.width, grid.height);
5124
+ const old = previous == null ? void 0 : previous.source;
5125
+ if (!old || old.width !== grid.width || old.height !== grid.height || old.method !== grid.method || old.registration !== grid.registration || old.heightReference !== grid.heightReference || !old.origin.every((v, i) => v === grid.origin[i]) || !old.columnStep.every((v, i) => v === grid.columnStep[i]) || !old.rowStep.every((v, i) => v === grid.rowStep[i]) || previous.levels[0].nodesPerBlock !== nodesPerBlock) {
5126
+ const pyramid = createTerrainGradientPyramid(grid, { maxSamples }), levels = pyramid.levels.map((l) => {
5127
+ const counts = new Uint32Array(2 * l.width * l.height);
5128
+ for (let i = 0; i < l.width * l.height; i++) {
5129
+ counts[2 * i] = l.validCounts[i];
5130
+ counts[2 * i + 1] = l.sampleCounts[i];
5131
+ }
5132
+ return packTerrainHierarchyLevel(l.width, l.height, l.blockSize, l.gradients, counts, nodesPerBlock);
5133
+ });
5134
+ return {
5135
+ source: grid,
5136
+ levels,
5137
+ stats: {
5138
+ copiedBlocks: levels.reduce((n, l) => n + l.blocks.length, 0),
5139
+ copiedBytes: levels.reduce((n, l) => n + l.blocks.reduce((s, b) => s + b.values.byteLength + b.counts.byteLength, 0), 0),
5140
+ updatedNodes: Uint32Array.from(levels, (l) => l.width * l.height)
5141
+ }
5142
+ };
5143
+ }
5144
+ const ids = terrainDirtyIndices(dirty, grid.width, grid.height, 0, charge);
5145
+ const result = updatePersistentHierarchy(previous.levels, ids, "gradient", (x, y) => {
5146
+ const i = y * grid.width + x, s = grid.statuses[i];
5147
+ if (s > 6)
5148
+ throw new Error("Invalid terrain gradient status");
5149
+ if (s === 0 && (!Number.isFinite(grid.gradients[2 * i]) || !Number.isFinite(grid.gradients[2 * i + 1])))
5150
+ throw new Error("Invalid terrain gradient value");
5151
+ return {
5152
+ values: s === 0 ? [grid.gradients[2 * i], grid.gradients[2 * i + 1]] : [0, 0],
5153
+ counts: [s === 0 ? 1 : 0, 1]
5154
+ };
5155
+ }, charge);
5156
+ return { source: grid, ...result };
5157
+ }
5158
+
5159
+ // dist/terrain/lod-morph.js
5160
+ var TerrainMorphStatus = {
5161
+ VALID: 0,
5162
+ FINE_NO_DATA: 1,
5163
+ COARSE_NO_DATA: 2,
5164
+ OUTSIDE_COARSE: 3
5165
+ };
5166
+ function createTerrainLodMorph(fine, coarse, options) {
5167
+ const { ratio } = options, offset = options.coarseOrigin ?? [0, 0], limit = options.maxSamples ?? 4e6, count = fine.width * fine.height;
5168
+ if (!Number.isSafeInteger(ratio) || ratio < 2 || 2 ** Math.round(Math.log2(ratio)) !== ratio || offset.length !== 2 || !offset.every(Number.isSafeInteger) || !Number.isSafeInteger(limit) || limit < 0 || count > limit)
5169
+ throw new Error("Invalid terrain LOD ratio, origin or sample capacity");
5170
+ if (fine.registration !== "vertex" || coarse.registration !== "vertex" || fine.diagonal !== coarse.diagonal || fine.heightReference !== coarse.heightReference)
5171
+ throw new Error("Incompatible terrain LOD registration, diagonal or height reference");
5172
+ for (let axis = 0; axis < 2; axis++) {
5173
+ if (fine.columnStep[axis] * ratio !== coarse.columnStep[axis] || fine.rowStep[axis] * ratio !== coarse.rowStep[axis])
5174
+ throw new Error("Terrain LOD steps differ");
5175
+ const a = offset[0] * fine.columnStep[axis], b = offset[1] * fine.rowStep[axis], expected = fine.origin[axis] + a + b;
5176
+ const tolerance = Math.min(16 * Number.EPSILON * Math.max(1, Math.abs(fine.origin[axis]), Math.abs(coarse.origin[axis]), Math.abs(a), Math.abs(b)), 1e-9 * Math.max(Math.abs(fine.columnStep[axis]), Math.abs(fine.rowStep[axis])));
5177
+ if (!Number.isFinite(expected) || Math.abs(coarse.origin[axis] - expected) > tolerance)
5178
+ throw new Error("Terrain LOD origins differ");
5179
+ }
5180
+ const fineHeights = new Float64Array(count), coarseHeights = new Float64Array(count), deltas = new Float64Array(count), statuses = new Uint8Array(count), coarseCoordinates = new Float64Array(2 * count);
5181
+ let maxNodalDisplacement = 0;
5182
+ for (let y = 0; y < fine.height; y++)
5183
+ for (let x = 0; x < fine.width; x++) {
5184
+ const i = y * fine.width + x, u = (x - offset[0]) / ratio, v = (y - offset[1]) / ratio;
5185
+ if (!Number.isSafeInteger(x - offset[0]) || !Number.isSafeInteger(y - offset[1]))
5186
+ throw new Error("Terrain LOD lattice overflow");
5187
+ coarseCoordinates[2 * i] = u;
5188
+ coarseCoordinates[2 * i + 1] = v;
5189
+ const source = fine.getHeight(x, y);
5190
+ if (source === void 0) {
5191
+ statuses[i] = TerrainMorphStatus.FINE_NO_DATA;
5192
+ continue;
5193
+ }
5194
+ fineHeights[i] = source;
5195
+ if (u < 0 || v < 0 || u > coarse.width - 1 || v > coarse.height - 1) {
5196
+ statuses[i] = TerrainMorphStatus.OUTSIDE_COARSE;
5197
+ continue;
5198
+ }
5199
+ const target = sampleTerrainTriangleHeight(coarse, u, v);
5200
+ if (target === void 0) {
5201
+ statuses[i] = TerrainMorphStatus.COARSE_NO_DATA;
5202
+ continue;
5203
+ }
5204
+ const delta = target - source;
5205
+ if (!Number.isFinite(delta))
5206
+ throw new Error("Terrain LOD displacement overflow");
5207
+ coarseHeights[i] = target;
5208
+ deltas[i] = delta;
5209
+ maxNodalDisplacement = Math.max(maxNodalDisplacement, Math.abs(delta));
5210
+ }
5211
+ return {
5212
+ width: fine.width,
5213
+ height: fine.height,
5214
+ origin: [...fine.origin],
5215
+ columnStep: [...fine.columnStep],
5216
+ rowStep: [...fine.rowStep],
5217
+ heightReference: fine.heightReference,
5218
+ fineHeights,
5219
+ coarseHeights,
5220
+ deltas,
5221
+ statuses,
5222
+ coarseCoordinates,
5223
+ maxNodalDisplacement,
5224
+ ratio,
5225
+ coarseOrigin: [...offset],
5226
+ diagonal: fine.diagonal
5227
+ };
5228
+ }
5229
+
5230
+ // dist/terrain/lod-morph-evaluate.js
5231
+ function evaluateTerrainLodMorph(morph, factor) {
5232
+ const count = morph.width * morph.height;
5233
+ if (!Number.isFinite(factor) || factor < 0 || factor > 1 || !Number.isSafeInteger(count) || count < 1 || morph.fineHeights.length !== count || morph.coarseHeights.length !== count || morph.statuses.length !== count)
5234
+ throw new Error("Invalid terrain morph evaluation");
5235
+ const heights = new Float64Array(count), validity = new Uint8Array(count);
5236
+ for (let i = 0; i < count; i++) {
5237
+ if (morph.statuses[i] > 3)
5238
+ throw new Error("Invalid terrain morph status");
5239
+ if (morph.statuses[i] !== 0)
5240
+ continue;
5241
+ const a = morph.fineHeights[i], b = morph.coarseHeights[i];
5242
+ if (!Number.isFinite(a) || !Number.isFinite(b))
5243
+ throw new Error("Invalid terrain morph height");
5244
+ heights[i] = factor === 0 ? a : factor === 1 ? b : a * (1 - factor) + b * factor;
5245
+ if (!Number.isFinite(heights[i]))
5246
+ throw new Error("Terrain morph arithmetic overflow");
5247
+ validity[i] = 1;
5248
+ }
5249
+ return { heights, validity };
5250
+ }
3917
5251
  //# sourceMappingURL=index.cjs.map