@math.gl/geospatial 5.0.0-beta.8 → 5.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (620) hide show
  1. package/README.md +3 -3
  2. package/dist/crs/crs-descriptor-types.d.ts +2 -1
  3. package/dist/crs/crs-descriptor-types.d.ts.map +1 -1
  4. package/dist/crs/index.cjs +54 -0
  5. package/dist/crs/index.cjs.map +2 -2
  6. package/dist/crs/index.d.ts +1 -0
  7. package/dist/crs/index.d.ts.map +1 -1
  8. package/dist/crs/index.js +1 -0
  9. package/dist/crs/index.js.map +1 -1
  10. package/dist/crs/spatial-reference-metadata.d.ts +20 -0
  11. package/dist/crs/spatial-reference-metadata.d.ts.map +1 -0
  12. package/dist/crs/spatial-reference-metadata.js +86 -0
  13. package/dist/crs/spatial-reference-metadata.js.map +1 -0
  14. package/dist/ellipsoid-helpers/ellipsoid-transform.d.ts +1 -1
  15. package/dist/ellipsoid-helpers/ellipsoid-transform.d.ts.map +1 -1
  16. package/dist/ellipsoid-helpers/ellipsoid-transform.js +2 -2
  17. package/dist/ellipsoid-helpers/ellipsoid-transform.js.map +1 -1
  18. package/dist/ellipsoid-helpers/scale-to-geodetic-surface.js +1 -1
  19. package/dist/ellipsoid-helpers/scale-to-geodetic-surface.js.map +1 -1
  20. package/dist/ellipsoid-helpers/tangent-plane-numerics.d.ts +1 -1
  21. package/dist/ellipsoid-helpers/tangent-plane-numerics.d.ts.map +1 -1
  22. package/dist/ellipsoid-tangent-plane.d.ts +2 -2
  23. package/dist/ellipsoid-tangent-plane.d.ts.map +1 -1
  24. package/dist/ellipsoid-tangent-plane.js +1 -1
  25. package/dist/ellipsoid-tangent-plane.js.map +1 -1
  26. package/dist/ellipsoid-transforms.d.ts +2 -2
  27. package/dist/ellipsoid-transforms.d.ts.map +1 -1
  28. package/dist/ellipsoid-transforms.js +1 -1
  29. package/dist/ellipsoid-transforms.js.map +1 -1
  30. package/dist/ellipsoid.d.ts +2 -2
  31. package/dist/ellipsoid.d.ts.map +1 -1
  32. package/dist/ellipsoid.js +2 -2
  33. package/dist/ellipsoid.js.map +1 -1
  34. package/dist/expressions.d.ts +1 -1
  35. package/dist/expressions.d.ts.map +1 -1
  36. package/dist/expressions.js +1 -1
  37. package/dist/expressions.js.map +1 -1
  38. package/dist/geodesic-buffer.d.ts +1 -1
  39. package/dist/geodesic-buffer.d.ts.map +1 -1
  40. package/dist/geodesic-path.d.ts +1 -1
  41. package/dist/geodesic-path.d.ts.map +1 -1
  42. package/dist/geometry-constructors.d.ts +6 -0
  43. package/dist/geometry-constructors.d.ts.map +1 -0
  44. package/dist/geometry-constructors.js +37 -0
  45. package/dist/geometry-constructors.js.map +1 -0
  46. package/dist/geometry-inspection.d.ts +8 -0
  47. package/dist/geometry-inspection.d.ts.map +1 -0
  48. package/dist/geometry-inspection.js +61 -0
  49. package/dist/geometry-inspection.js.map +1 -0
  50. package/dist/index.cjs +3773 -846
  51. package/dist/index.cjs.map +3 -3
  52. package/dist/index.d.ts +173 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +115 -0
  55. package/dist/index.js.map +1 -1
  56. package/dist/line-simplification.d.ts +4 -0
  57. package/dist/line-simplification.d.ts.map +1 -0
  58. package/dist/line-simplification.js +83 -0
  59. package/dist/line-simplification.js.map +1 -0
  60. package/dist/linear-referencing.d.ts +6 -0
  61. package/dist/linear-referencing.d.ts.map +1 -0
  62. package/dist/linear-referencing.js +74 -0
  63. package/dist/linear-referencing.js.map +1 -0
  64. package/dist/lng-lat-rectangle.d.ts +1 -1
  65. package/dist/lng-lat-rectangle.d.ts.map +1 -1
  66. package/dist/lng-lat-rectangle.js +1 -1
  67. package/dist/lng-lat-rectangle.js.map +1 -1
  68. package/dist/local-reference-frame.d.ts +3 -3
  69. package/dist/local-reference-frame.d.ts.map +1 -1
  70. package/dist/local-reference-frame.js +2 -2
  71. package/dist/local-reference-frame.js.map +1 -1
  72. package/dist/make-obb-from-region.d.ts +1 -1
  73. package/dist/make-obb-from-region.d.ts.map +1 -1
  74. package/dist/make-obb-from-region.js +1 -1
  75. package/dist/make-obb-from-region.js.map +1 -1
  76. package/dist/maps/air-ocean-mesh.js +1 -1
  77. package/dist/maps/air-ocean-mesh.js.map +1 -1
  78. package/dist/maps/myriahedral/unfold.d.ts +1 -1
  79. package/dist/maps/myriahedral/unfold.d.ts.map +1 -1
  80. package/dist/maps/myriahedral/unfold.js +1 -1
  81. package/dist/maps/myriahedral/unfold.js.map +1 -1
  82. package/dist/maps/presets.cjs +6 -6
  83. package/dist/maps/presets.cjs.map +2 -2
  84. package/dist/maps.cjs +6 -6
  85. package/dist/maps.cjs.map +2 -2
  86. package/dist/projection/deformation.cjs +5 -5
  87. package/dist/projection/deformation.cjs.map +2 -2
  88. package/dist/projection/experimental/core.cjs +8 -4
  89. package/dist/projection/experimental/core.cjs.map +1 -1
  90. package/dist/projection/experimental/crs/spatial-reference.d.ts.map +1 -1
  91. package/dist/projection/experimental/crs/spatial-reference.js.map +1 -1
  92. package/dist/projection/experimental/crs/types.d.ts +1 -1
  93. package/dist/projection/experimental/crs/types.d.ts.map +1 -1
  94. package/dist/projection/experimental/crs-rendering-scale.d.ts.map +1 -1
  95. package/dist/projection/experimental/crs-rendering-scale.js +13 -2
  96. package/dist/projection/experimental/crs-rendering-scale.js.map +1 -1
  97. package/dist/projection/experimental/datum.js +1 -1
  98. package/dist/projection/experimental/datum.js.map +1 -1
  99. package/dist/projection/experimental/entries/projections/geocent.cjs +3 -3
  100. package/dist/projection/experimental/entries/projections/geocent.cjs.map +1 -1
  101. package/dist/projection/experimental/lazy-projections/aea.cjs +4 -1
  102. package/dist/projection/experimental/lazy-projections/aea.cjs.map +1 -1
  103. package/dist/projection/experimental/lazy-projections/aea.d.ts.map +1 -1
  104. package/dist/projection/experimental/lazy-projections/aea.js +4 -1
  105. package/dist/projection/experimental/lazy-projections/aea.js.map +1 -1
  106. package/dist/projection/experimental/lazy-projections/bonne.cjs +4 -1
  107. package/dist/projection/experimental/lazy-projections/bonne.cjs.map +1 -1
  108. package/dist/projection/experimental/lazy-projections/bonne.d.ts.map +1 -1
  109. package/dist/projection/experimental/lazy-projections/bonne.js +4 -1
  110. package/dist/projection/experimental/lazy-projections/bonne.js.map +1 -1
  111. package/dist/projection/experimental/lazy-projections/cass.cjs +4 -1
  112. package/dist/projection/experimental/lazy-projections/cass.cjs.map +1 -1
  113. package/dist/projection/experimental/lazy-projections/cass.d.ts.map +1 -1
  114. package/dist/projection/experimental/lazy-projections/cass.js +4 -1
  115. package/dist/projection/experimental/lazy-projections/cass.js.map +1 -1
  116. package/dist/projection/experimental/lazy-projections/eck6.cjs +4 -1
  117. package/dist/projection/experimental/lazy-projections/eck6.cjs.map +1 -1
  118. package/dist/projection/experimental/lazy-projections/eck6.d.ts.map +1 -1
  119. package/dist/projection/experimental/lazy-projections/eck6.js +4 -1
  120. package/dist/projection/experimental/lazy-projections/eck6.js.map +1 -1
  121. package/dist/projection/experimental/lazy-projections/eqdc.cjs +4 -1
  122. package/dist/projection/experimental/lazy-projections/eqdc.cjs.map +1 -1
  123. package/dist/projection/experimental/lazy-projections/eqdc.d.ts.map +1 -1
  124. package/dist/projection/experimental/lazy-projections/eqdc.js +4 -1
  125. package/dist/projection/experimental/lazy-projections/eqdc.js.map +1 -1
  126. package/dist/projection/experimental/lazy-projections/eqearth.cjs +4 -1
  127. package/dist/projection/experimental/lazy-projections/eqearth.cjs.map +1 -1
  128. package/dist/projection/experimental/lazy-projections/eqearth.d.ts.map +1 -1
  129. package/dist/projection/experimental/lazy-projections/eqearth.js +4 -1
  130. package/dist/projection/experimental/lazy-projections/eqearth.js.map +1 -1
  131. package/dist/projection/experimental/lazy-projections/equi.cjs +4 -1
  132. package/dist/projection/experimental/lazy-projections/equi.cjs.map +1 -1
  133. package/dist/projection/experimental/lazy-projections/equi.d.ts.map +1 -1
  134. package/dist/projection/experimental/lazy-projections/equi.js +4 -1
  135. package/dist/projection/experimental/lazy-projections/equi.js.map +1 -1
  136. package/dist/projection/experimental/lazy-projections/geocent.cjs +4 -1
  137. package/dist/projection/experimental/lazy-projections/geocent.cjs.map +1 -1
  138. package/dist/projection/experimental/lazy-projections/geocent.d.ts.map +1 -1
  139. package/dist/projection/experimental/lazy-projections/geocent.js +4 -1
  140. package/dist/projection/experimental/lazy-projections/geocent.js.map +1 -1
  141. package/dist/projection/experimental/lazy-projections/geos.cjs +4 -1
  142. package/dist/projection/experimental/lazy-projections/geos.cjs.map +1 -1
  143. package/dist/projection/experimental/lazy-projections/geos.d.ts.map +1 -1
  144. package/dist/projection/experimental/lazy-projections/geos.js +4 -1
  145. package/dist/projection/experimental/lazy-projections/geos.js.map +1 -1
  146. package/dist/projection/experimental/lazy-projections/gnom.cjs +4 -1
  147. package/dist/projection/experimental/lazy-projections/gnom.cjs.map +1 -1
  148. package/dist/projection/experimental/lazy-projections/gnom.d.ts.map +1 -1
  149. package/dist/projection/experimental/lazy-projections/gnom.js +4 -1
  150. package/dist/projection/experimental/lazy-projections/gnom.js.map +1 -1
  151. package/dist/projection/experimental/lazy-projections/index.cjs +100 -27
  152. package/dist/projection/experimental/lazy-projections/index.cjs.map +1 -1
  153. package/dist/projection/experimental/lazy-projections/krovak.cjs +4 -1
  154. package/dist/projection/experimental/lazy-projections/krovak.cjs.map +1 -1
  155. package/dist/projection/experimental/lazy-projections/krovak.d.ts.map +1 -1
  156. package/dist/projection/experimental/lazy-projections/krovak.js +4 -1
  157. package/dist/projection/experimental/lazy-projections/krovak.js.map +1 -1
  158. package/dist/projection/experimental/lazy-projections/merc.cjs +4 -1
  159. package/dist/projection/experimental/lazy-projections/merc.cjs.map +1 -1
  160. package/dist/projection/experimental/lazy-projections/merc.d.ts.map +1 -1
  161. package/dist/projection/experimental/lazy-projections/merc.js +4 -1
  162. package/dist/projection/experimental/lazy-projections/merc.js.map +1 -1
  163. package/dist/projection/experimental/lazy-projections/mill.cjs +4 -1
  164. package/dist/projection/experimental/lazy-projections/mill.cjs.map +1 -1
  165. package/dist/projection/experimental/lazy-projections/mill.d.ts.map +1 -1
  166. package/dist/projection/experimental/lazy-projections/mill.js +4 -1
  167. package/dist/projection/experimental/lazy-projections/mill.js.map +1 -1
  168. package/dist/projection/experimental/lazy-projections/moll.cjs +4 -1
  169. package/dist/projection/experimental/lazy-projections/moll.cjs.map +1 -1
  170. package/dist/projection/experimental/lazy-projections/moll.d.ts.map +1 -1
  171. package/dist/projection/experimental/lazy-projections/moll.js +4 -1
  172. package/dist/projection/experimental/lazy-projections/moll.js.map +1 -1
  173. package/dist/projection/experimental/lazy-projections/nzmg.cjs +4 -1
  174. package/dist/projection/experimental/lazy-projections/nzmg.cjs.map +1 -1
  175. package/dist/projection/experimental/lazy-projections/nzmg.d.ts.map +1 -1
  176. package/dist/projection/experimental/lazy-projections/nzmg.js +4 -1
  177. package/dist/projection/experimental/lazy-projections/nzmg.js.map +1 -1
  178. package/dist/projection/experimental/lazy-projections/omerc.cjs +4 -1
  179. package/dist/projection/experimental/lazy-projections/omerc.cjs.map +1 -1
  180. package/dist/projection/experimental/lazy-projections/omerc.d.ts.map +1 -1
  181. package/dist/projection/experimental/lazy-projections/omerc.js +4 -1
  182. package/dist/projection/experimental/lazy-projections/omerc.js.map +1 -1
  183. package/dist/projection/experimental/lazy-projections/ortho.cjs +4 -1
  184. package/dist/projection/experimental/lazy-projections/ortho.cjs.map +1 -1
  185. package/dist/projection/experimental/lazy-projections/ortho.d.ts.map +1 -1
  186. package/dist/projection/experimental/lazy-projections/ortho.js +4 -1
  187. package/dist/projection/experimental/lazy-projections/ortho.js.map +1 -1
  188. package/dist/projection/experimental/lazy-projections/poly.cjs +4 -1
  189. package/dist/projection/experimental/lazy-projections/poly.cjs.map +1 -1
  190. package/dist/projection/experimental/lazy-projections/poly.d.ts.map +1 -1
  191. package/dist/projection/experimental/lazy-projections/poly.js +4 -1
  192. package/dist/projection/experimental/lazy-projections/poly.js.map +1 -1
  193. package/dist/projection/experimental/lazy-projections/robin.cjs +4 -1
  194. package/dist/projection/experimental/lazy-projections/robin.cjs.map +1 -1
  195. package/dist/projection/experimental/lazy-projections/robin.d.ts.map +1 -1
  196. package/dist/projection/experimental/lazy-projections/robin.js +4 -1
  197. package/dist/projection/experimental/lazy-projections/robin.js.map +1 -1
  198. package/dist/projection/experimental/lazy-projections/sinu.cjs +4 -1
  199. package/dist/projection/experimental/lazy-projections/sinu.cjs.map +1 -1
  200. package/dist/projection/experimental/lazy-projections/sinu.d.ts.map +1 -1
  201. package/dist/projection/experimental/lazy-projections/sinu.js +4 -1
  202. package/dist/projection/experimental/lazy-projections/sinu.js.map +1 -1
  203. package/dist/projection/experimental/lazy-projections/stere.cjs +4 -1
  204. package/dist/projection/experimental/lazy-projections/stere.cjs.map +1 -1
  205. package/dist/projection/experimental/lazy-projections/stere.d.ts.map +1 -1
  206. package/dist/projection/experimental/lazy-projections/stere.js +4 -1
  207. package/dist/projection/experimental/lazy-projections/stere.js.map +1 -1
  208. package/dist/projection/experimental/lazy-projections/tpers.cjs +4 -1
  209. package/dist/projection/experimental/lazy-projections/tpers.cjs.map +1 -1
  210. package/dist/projection/experimental/lazy-projections/tpers.d.ts.map +1 -1
  211. package/dist/projection/experimental/lazy-projections/tpers.js +4 -1
  212. package/dist/projection/experimental/lazy-projections/tpers.js.map +1 -1
  213. package/dist/projection/experimental/lazy-projections/vandg.cjs +4 -1
  214. package/dist/projection/experimental/lazy-projections/vandg.cjs.map +1 -1
  215. package/dist/projection/experimental/lazy-projections/vandg.d.ts.map +1 -1
  216. package/dist/projection/experimental/lazy-projections/vandg.js +4 -1
  217. package/dist/projection/experimental/lazy-projections/vandg.js.map +1 -1
  218. package/dist/projection/experimental/spatial-deformation.js +1 -1
  219. package/dist/projection/experimental/spatial-deformation.js.map +1 -1
  220. package/dist/projection/index.cjs +8 -4
  221. package/dist/projection/index.cjs.map +1 -1
  222. package/dist/projection/index.d.ts.map +1 -1
  223. package/dist/projection/index.js.map +1 -1
  224. package/dist/projection/lib/projection.js.map +1 -1
  225. package/dist/projection/pipeline.cjs +3 -3
  226. package/dist/projection/pipeline.cjs.map +1 -1
  227. package/dist/projection/temporal.cjs +5 -5
  228. package/dist/projection/temporal.cjs.map +2 -2
  229. package/dist/projection/transform-analysis.cjs +3 -3
  230. package/dist/projection/transform-analysis.cjs.map +1 -1
  231. package/dist/rhumb-path.d.ts +1 -1
  232. package/dist/rhumb-path.d.ts.map +1 -1
  233. package/dist/spatial-planar-intersects.d.ts +4 -0
  234. package/dist/spatial-planar-intersects.d.ts.map +1 -0
  235. package/dist/spatial-planar-intersects.js +108 -0
  236. package/dist/spatial-planar-intersects.js.map +1 -0
  237. package/dist/spatial-planar.d.ts +16 -0
  238. package/dist/spatial-planar.d.ts.map +1 -0
  239. package/dist/spatial-planar.js +240 -0
  240. package/dist/spatial-planar.js.map +1 -0
  241. package/dist/spatial-sql.d.ts +45 -0
  242. package/dist/spatial-sql.d.ts.map +1 -0
  243. package/dist/spatial-sql.js +192 -0
  244. package/dist/spatial-sql.js.map +1 -0
  245. package/dist/st-functions.cjs +1616 -0
  246. package/dist/st-functions.cjs.map +6 -0
  247. package/dist/st-functions.d.ts +307 -0
  248. package/dist/st-functions.d.ts.map +1 -0
  249. package/dist/st-functions.js +593 -0
  250. package/dist/st-functions.js.map +1 -0
  251. package/dist/subdivide-globe-mesh.js +1 -1
  252. package/dist/subdivide-globe-mesh.js.map +1 -1
  253. package/dist/tasks/index.cjs +1266 -155
  254. package/dist/tasks/index.cjs.map +3 -3
  255. package/dist/tasks/index.d.ts +12 -0
  256. package/dist/tasks/index.d.ts.map +1 -1
  257. package/dist/tasks/index.js +26 -0
  258. package/dist/tasks/index.js.map +1 -1
  259. package/dist/tasks/terrain-coverage-worker.d.ts +2 -0
  260. package/dist/tasks/terrain-coverage-worker.d.ts.map +1 -0
  261. package/dist/tasks/terrain-coverage-worker.js +7 -0
  262. package/dist/tasks/terrain-coverage-worker.js.map +1 -0
  263. package/dist/tasks/terrain-coverage.d.ts +25 -0
  264. package/dist/tasks/terrain-coverage.d.ts.map +1 -0
  265. package/dist/tasks/terrain-coverage.js +15 -0
  266. package/dist/tasks/terrain-coverage.js.map +1 -0
  267. package/dist/tasks/terrain-residency-worker.d.ts +2 -0
  268. package/dist/tasks/terrain-residency-worker.d.ts.map +1 -0
  269. package/dist/tasks/terrain-residency-worker.js +7 -0
  270. package/dist/tasks/terrain-residency-worker.js.map +1 -0
  271. package/dist/tasks/terrain-residency.d.ts +73 -0
  272. package/dist/tasks/terrain-residency.d.ts.map +1 -0
  273. package/dist/tasks/terrain-residency.js +203 -0
  274. package/dist/tasks/terrain-residency.js.map +1 -0
  275. package/dist/terrain/breakline-mesh.d.ts +18 -0
  276. package/dist/terrain/breakline-mesh.d.ts.map +1 -0
  277. package/dist/terrain/breakline-mesh.js +126 -0
  278. package/dist/terrain/breakline-mesh.js.map +1 -0
  279. package/dist/terrain/breakline-preprocess.d.ts +11 -0
  280. package/dist/terrain/breakline-preprocess.d.ts.map +1 -0
  281. package/dist/terrain/breakline-preprocess.js +94 -0
  282. package/dist/terrain/breakline-preprocess.js.map +1 -0
  283. package/dist/terrain/continuous-mesh-error.d.ts +34 -0
  284. package/dist/terrain/continuous-mesh-error.d.ts.map +1 -0
  285. package/dist/terrain/continuous-mesh-error.js +221 -0
  286. package/dist/terrain/continuous-mesh-error.js.map +1 -0
  287. package/dist/terrain/cutout-polygons.d.ts +21 -0
  288. package/dist/terrain/cutout-polygons.d.ts.map +1 -0
  289. package/dist/terrain/cutout-polygons.js +172 -0
  290. package/dist/terrain/cutout-polygons.js.map +1 -0
  291. package/dist/terrain/cutout-region.d.ts +34 -0
  292. package/dist/terrain/cutout-region.d.ts.map +1 -0
  293. package/dist/terrain/cutout-region.js +33 -0
  294. package/dist/terrain/cutout-region.js.map +1 -0
  295. package/dist/terrain/cutout-skirts.d.ts +34 -0
  296. package/dist/terrain/cutout-skirts.d.ts.map +1 -0
  297. package/dist/terrain/cutout-skirts.js +29 -0
  298. package/dist/terrain/cutout-skirts.js.map +1 -0
  299. package/dist/terrain/depression-fill.d.ts +25 -0
  300. package/dist/terrain/depression-fill.d.ts.map +1 -0
  301. package/dist/terrain/depression-fill.js +106 -0
  302. package/dist/terrain/depression-fill.js.map +1 -0
  303. package/dist/terrain/geographic-cutout.d.ts +38 -0
  304. package/dist/terrain/geographic-cutout.d.ts.map +1 -0
  305. package/dist/terrain/geographic-cutout.js +120 -0
  306. package/dist/terrain/geographic-cutout.js.map +1 -0
  307. package/dist/terrain/geographic-lod-seams.d.ts +10 -0
  308. package/dist/terrain/geographic-lod-seams.d.ts.map +1 -0
  309. package/dist/terrain/geographic-lod-seams.js +100 -0
  310. package/dist/terrain/geographic-lod-seams.js.map +1 -0
  311. package/dist/terrain/geographic-neighbor.d.ts +18 -0
  312. package/dist/terrain/geographic-neighbor.d.ts.map +1 -0
  313. package/dist/terrain/geographic-neighbor.js +44 -0
  314. package/dist/terrain/geographic-neighbor.js.map +1 -0
  315. package/dist/terrain/geographic-poles.d.ts +24 -0
  316. package/dist/terrain/geographic-poles.d.ts.map +1 -0
  317. package/dist/terrain/geographic-poles.js +34 -0
  318. package/dist/terrain/geographic-poles.js.map +1 -0
  319. package/dist/terrain/geographic-seam.d.ts +21 -0
  320. package/dist/terrain/geographic-seam.d.ts.map +1 -0
  321. package/dist/terrain/geographic-seam.js +52 -0
  322. package/dist/terrain/geographic-seam.js.map +1 -0
  323. package/dist/terrain/hydrology.d.ts +42 -0
  324. package/dist/terrain/hydrology.d.ts.map +1 -0
  325. package/dist/terrain/hydrology.js +112 -0
  326. package/dist/terrain/hydrology.js.map +1 -0
  327. package/dist/terrain/index.cjs +3158 -213
  328. package/dist/terrain/index.cjs.map +3 -3
  329. package/dist/terrain/index.d.ts +32 -0
  330. package/dist/terrain/index.d.ts.map +1 -1
  331. package/dist/terrain/index.js +30 -0
  332. package/dist/terrain/index.js.map +1 -1
  333. package/dist/terrain/lod-screen-error.d.ts +28 -0
  334. package/dist/terrain/lod-screen-error.d.ts.map +1 -0
  335. package/dist/terrain/lod-screen-error.js +95 -0
  336. package/dist/terrain/lod-screen-error.js.map +1 -0
  337. package/dist/terrain/lod-select.d.ts +48 -0
  338. package/dist/terrain/lod-select.d.ts.map +1 -0
  339. package/dist/terrain/lod-select.js +73 -0
  340. package/dist/terrain/lod-select.js.map +1 -0
  341. package/dist/terrain/lod-stitch.d.ts +15 -0
  342. package/dist/terrain/lod-stitch.d.ts.map +1 -0
  343. package/dist/terrain/lod-stitch.js +64 -0
  344. package/dist/terrain/lod-stitch.js.map +1 -0
  345. package/dist/terrain/mesh-coverage.d.ts +35 -0
  346. package/dist/terrain/mesh-coverage.d.ts.map +1 -0
  347. package/dist/terrain/mesh-coverage.js +186 -0
  348. package/dist/terrain/mesh-coverage.js.map +1 -0
  349. package/dist/terrain/mesh-cutout.d.ts +45 -0
  350. package/dist/terrain/mesh-cutout.d.ts.map +1 -0
  351. package/dist/terrain/mesh-cutout.js +336 -0
  352. package/dist/terrain/mesh-cutout.js.map +1 -0
  353. package/dist/terrain/mesh-regions-data.d.ts +2 -2
  354. package/dist/terrain/mesh-regions-data.d.ts.map +1 -1
  355. package/dist/terrain/mesh-regions-data.js +20 -10
  356. package/dist/terrain/mesh-regions-data.js.map +1 -1
  357. package/dist/terrain/mesh-skirts.d.ts +8 -2
  358. package/dist/terrain/mesh-skirts.d.ts.map +1 -1
  359. package/dist/terrain/mesh-skirts.js +5 -4
  360. package/dist/terrain/mesh-skirts.js.map +1 -1
  361. package/dist/terrain/mixed-halo-update.d.ts.map +1 -1
  362. package/dist/terrain/mixed-halo-update.js +138 -26
  363. package/dist/terrain/mixed-halo-update.js.map +1 -1
  364. package/dist/terrain/mixed-vertex-halos.d.ts +34 -1
  365. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -1
  366. package/dist/terrain/mixed-vertex-halos.js +98 -43
  367. package/dist/terrain/mixed-vertex-halos.js.map +1 -1
  368. package/dist/terrain/regional-viewshed.d.ts +55 -0
  369. package/dist/terrain/regional-viewshed.d.ts.map +1 -0
  370. package/dist/terrain/regional-viewshed.js +119 -0
  371. package/dist/terrain/regional-viewshed.js.map +1 -0
  372. package/dist/terrain/surface.d.ts +1 -1
  373. package/dist/terrain/surface.d.ts.map +1 -1
  374. package/dist/terrain/surface.js +1 -1
  375. package/dist/terrain/surface.js.map +1 -1
  376. package/dist/terrain/sweep-capsule.d.ts +27 -0
  377. package/dist/terrain/sweep-capsule.d.ts.map +1 -0
  378. package/dist/terrain/sweep-capsule.js +104 -0
  379. package/dist/terrain/sweep-capsule.js.map +1 -0
  380. package/dist/terrain/sweep-cylinder.d.ts +16 -0
  381. package/dist/terrain/sweep-cylinder.d.ts.map +1 -0
  382. package/dist/terrain/sweep-cylinder.js +52 -0
  383. package/dist/terrain/sweep-cylinder.js.map +1 -0
  384. package/dist/terrain/sweep-plane.d.ts +9 -0
  385. package/dist/terrain/sweep-plane.d.ts.map +1 -0
  386. package/dist/terrain/sweep-plane.js +52 -0
  387. package/dist/terrain/sweep-plane.js.map +1 -0
  388. package/dist/terrain/sweep-polytope.d.ts +42 -0
  389. package/dist/terrain/sweep-polytope.d.ts.map +1 -0
  390. package/dist/terrain/sweep-polytope.js +189 -0
  391. package/dist/terrain/sweep-polytope.js.map +1 -0
  392. package/dist/terrain/sweep-rotating-capsule.d.ts +17 -0
  393. package/dist/terrain/sweep-rotating-capsule.d.ts.map +1 -0
  394. package/dist/terrain/sweep-rotating-capsule.js +118 -0
  395. package/dist/terrain/sweep-rotating-capsule.js.map +1 -0
  396. package/dist/terrain/sweep-rotation.d.ts +35 -0
  397. package/dist/terrain/sweep-rotation.d.ts.map +1 -0
  398. package/dist/terrain/sweep-rotation.js +114 -0
  399. package/dist/terrain/sweep-rotation.js.map +1 -0
  400. package/dist/terrain/sweep-sphere.d.ts +27 -0
  401. package/dist/terrain/sweep-sphere.d.ts.map +1 -0
  402. package/dist/terrain/sweep-sphere.js +69 -0
  403. package/dist/terrain/sweep-sphere.js.map +1 -0
  404. package/dist/terrain/tile-cutout-update.d.ts +73 -0
  405. package/dist/terrain/tile-cutout-update.d.ts.map +1 -0
  406. package/dist/terrain/tile-cutout-update.js +181 -0
  407. package/dist/terrain/tile-cutout-update.js.map +1 -0
  408. package/dist/terrain/tile-cutout.d.ts +33 -0
  409. package/dist/terrain/tile-cutout.d.ts.map +1 -0
  410. package/dist/terrain/tile-cutout.js +93 -0
  411. package/dist/terrain/tile-cutout.js.map +1 -0
  412. package/dist/terrain/valid-domain-mesh.d.ts +29 -0
  413. package/dist/terrain/valid-domain-mesh.d.ts.map +1 -0
  414. package/dist/terrain/valid-domain-mesh.js +183 -0
  415. package/dist/terrain/valid-domain-mesh.js.map +1 -0
  416. package/dist/terrain/valid-domain-regions.d.ts +16 -0
  417. package/dist/terrain/valid-domain-regions.d.ts.map +1 -0
  418. package/dist/terrain/valid-domain-regions.js +19 -0
  419. package/dist/terrain/valid-domain-regions.js.map +1 -0
  420. package/dist/terrain/watershed-accumulation.d.ts +20 -0
  421. package/dist/terrain/watershed-accumulation.d.ts.map +1 -0
  422. package/dist/terrain/watershed-accumulation.js +53 -0
  423. package/dist/terrain/watershed-accumulation.js.map +1 -0
  424. package/dist/triaxial.d.ts +1 -1
  425. package/dist/triaxial.d.ts.map +1 -1
  426. package/dist/turf-expressions.cjs +1997 -0
  427. package/dist/turf-expressions.cjs.map +6 -0
  428. package/dist/turf-expressions.d.ts +3 -0
  429. package/dist/turf-expressions.d.ts.map +1 -0
  430. package/dist/turf-expressions.js +7 -0
  431. package/dist/turf-expressions.js.map +1 -0
  432. package/dist/turf-functions.cjs +743 -0
  433. package/dist/turf-functions.cjs.map +6 -0
  434. package/dist/turf-functions.d.ts +90 -0
  435. package/dist/turf-functions.d.ts.map +1 -0
  436. package/dist/{turf/expressions.js → turf-functions.js} +51 -5
  437. package/dist/turf-functions.js.map +1 -0
  438. package/dist/turf.cjs +25 -25
  439. package/dist/turf.cjs.map +2 -2
  440. package/dist/turf.d.ts +1 -1
  441. package/dist/turf.d.ts.map +1 -1
  442. package/dist/turf.js +2 -2
  443. package/dist/turf.js.map +1 -1
  444. package/dist/type-utils.d.ts +1 -1
  445. package/dist/type-utils.d.ts.map +1 -1
  446. package/dist/type-utils.js +1 -1
  447. package/dist/type-utils.js.map +1 -1
  448. package/dist/web-mercator/assert.d.ts +2 -0
  449. package/dist/web-mercator/assert.d.ts.map +1 -0
  450. package/dist/web-mercator/assert.js +12 -0
  451. package/dist/web-mercator/assert.js.map +1 -0
  452. package/dist/web-mercator/fit-bounds.d.ts +52 -0
  453. package/dist/web-mercator/fit-bounds.d.ts.map +1 -0
  454. package/dist/web-mercator/fit-bounds.js +70 -0
  455. package/dist/web-mercator/fit-bounds.js.map +1 -0
  456. package/dist/web-mercator/fly-to-viewport.d.ts +19 -0
  457. package/dist/web-mercator/fly-to-viewport.d.ts.map +1 -0
  458. package/dist/web-mercator/fly-to-viewport.js +94 -0
  459. package/dist/web-mercator/fly-to-viewport.js.map +1 -0
  460. package/dist/web-mercator/get-bounds.d.ts +3 -0
  461. package/dist/web-mercator/get-bounds.d.ts.map +1 -0
  462. package/dist/web-mercator/get-bounds.js +56 -0
  463. package/dist/web-mercator/get-bounds.js.map +1 -0
  464. package/dist/web-mercator/index.cjs +705 -0
  465. package/dist/web-mercator/index.cjs.map +6 -0
  466. package/dist/web-mercator/index.d.ts +14 -0
  467. package/dist/web-mercator/index.d.ts.map +1 -0
  468. package/dist/web-mercator/index.js +14 -0
  469. package/dist/web-mercator/index.js.map +1 -0
  470. package/dist/web-mercator/math-utils.d.ts +7 -0
  471. package/dist/web-mercator/math-utils.d.ts.map +1 -0
  472. package/dist/web-mercator/math-utils.js +30 -0
  473. package/dist/web-mercator/math-utils.js.map +1 -0
  474. package/dist/web-mercator/mercator-meters.d.ts +29 -0
  475. package/dist/web-mercator/mercator-meters.d.ts.map +1 -0
  476. package/dist/web-mercator/mercator-meters.js +61 -0
  477. package/dist/web-mercator/mercator-meters.js.map +1 -0
  478. package/dist/web-mercator/normalize-viewport-props.d.ts +16 -0
  479. package/dist/web-mercator/normalize-viewport-props.d.ts.map +1 -0
  480. package/dist/web-mercator/normalize-viewport-props.js +45 -0
  481. package/dist/web-mercator/normalize-viewport-props.js.map +1 -0
  482. package/dist/web-mercator/web-mercator-utils.d.ts +192 -0
  483. package/dist/web-mercator/web-mercator-utils.d.ts.map +1 -0
  484. package/dist/web-mercator/web-mercator-utils.js +321 -0
  485. package/dist/web-mercator/web-mercator-utils.js.map +1 -0
  486. package/dist/web-mercator/web-mercator-viewport.d.ts +177 -0
  487. package/dist/web-mercator/web-mercator-viewport.d.ts.map +1 -0
  488. package/dist/web-mercator/web-mercator-viewport.js +276 -0
  489. package/dist/web-mercator/web-mercator-viewport.js.map +1 -0
  490. package/dist/web-mercator.d.ts +1 -1
  491. package/dist/web-mercator.d.ts.map +1 -1
  492. package/dist/web-mercator.js +1 -1
  493. package/dist/web-mercator.js.map +1 -1
  494. package/package.json +35 -462
  495. package/src/crs/crs-descriptor-types.ts +2 -1
  496. package/src/crs/index.ts +7 -0
  497. package/src/crs/spatial-reference-metadata.ts +118 -0
  498. package/src/ellipsoid-helpers/ellipsoid-transform.ts +3 -3
  499. package/src/ellipsoid-helpers/scale-to-geodetic-surface.ts +1 -1
  500. package/src/ellipsoid-helpers/tangent-plane-numerics.ts +1 -1
  501. package/src/ellipsoid-tangent-plane.ts +2 -2
  502. package/src/ellipsoid-transforms.ts +2 -2
  503. package/src/ellipsoid.ts +7 -3
  504. package/src/expressions.ts +2 -2
  505. package/src/geodesic-buffer.ts +1 -1
  506. package/src/geodesic-path.ts +1 -1
  507. package/src/geometry-constructors.ts +36 -0
  508. package/src/geometry-inspection.ts +66 -0
  509. package/src/index.ts +314 -4
  510. package/src/line-simplification.ts +97 -0
  511. package/src/linear-referencing.ts +94 -0
  512. package/src/lng-lat-rectangle.ts +1 -1
  513. package/src/local-reference-frame.ts +4 -4
  514. package/src/make-obb-from-region.ts +9 -1
  515. package/src/maps/air-ocean-mesh.ts +1 -1
  516. package/src/maps/myriahedral/unfold.ts +1 -1
  517. package/src/projection/experimental/crs/spatial-reference.ts +1 -6
  518. package/src/projection/experimental/crs/types.ts +2 -2
  519. package/src/projection/experimental/crs/wkt.ts +1 -1
  520. package/src/projection/experimental/crs-descriptor.ts +1 -1
  521. package/src/projection/experimental/crs-rendering-scale.ts +16 -4
  522. package/src/projection/experimental/datum.ts +1 -1
  523. package/src/projection/experimental/lazy-projections/aea.ts +4 -1
  524. package/src/projection/experimental/lazy-projections/bonne.ts +4 -1
  525. package/src/projection/experimental/lazy-projections/cass.ts +4 -1
  526. package/src/projection/experimental/lazy-projections/eck6.ts +4 -1
  527. package/src/projection/experimental/lazy-projections/eqdc.ts +4 -1
  528. package/src/projection/experimental/lazy-projections/eqearth.ts +4 -1
  529. package/src/projection/experimental/lazy-projections/equi.ts +4 -1
  530. package/src/projection/experimental/lazy-projections/geocent.ts +4 -1
  531. package/src/projection/experimental/lazy-projections/geos.ts +4 -1
  532. package/src/projection/experimental/lazy-projections/gnom.ts +4 -1
  533. package/src/projection/experimental/lazy-projections/krovak.ts +4 -1
  534. package/src/projection/experimental/lazy-projections/merc.ts +4 -1
  535. package/src/projection/experimental/lazy-projections/mill.ts +4 -1
  536. package/src/projection/experimental/lazy-projections/moll.ts +4 -1
  537. package/src/projection/experimental/lazy-projections/nzmg.ts +4 -1
  538. package/src/projection/experimental/lazy-projections/omerc.ts +4 -1
  539. package/src/projection/experimental/lazy-projections/ortho.ts +4 -1
  540. package/src/projection/experimental/lazy-projections/poly.ts +4 -1
  541. package/src/projection/experimental/lazy-projections/robin.ts +4 -1
  542. package/src/projection/experimental/lazy-projections/sinu.ts +4 -1
  543. package/src/projection/experimental/lazy-projections/stere.ts +4 -1
  544. package/src/projection/experimental/lazy-projections/tpers.ts +4 -1
  545. package/src/projection/experimental/lazy-projections/vandg.ts +4 -1
  546. package/src/projection/experimental/spatial-deformation.ts +1 -1
  547. package/src/projection/index.ts +1 -1
  548. package/src/projection/lib/projection.ts +1 -1
  549. package/src/rhumb-path.ts +1 -1
  550. package/src/spatial-planar-intersects.ts +134 -0
  551. package/src/spatial-planar.ts +266 -0
  552. package/src/spatial-sql.ts +276 -0
  553. package/src/st-functions.ts +852 -0
  554. package/src/subdivide-globe-mesh.ts +1 -1
  555. package/src/tasks/index.ts +34 -0
  556. package/src/tasks/terrain-coverage-worker.ts +6 -0
  557. package/src/tasks/terrain-coverage.ts +25 -0
  558. package/src/tasks/terrain-residency-worker.ts +6 -0
  559. package/src/tasks/terrain-residency.ts +250 -0
  560. package/src/terrain/breakline-mesh.ts +164 -0
  561. package/src/terrain/breakline-preprocess.ts +106 -0
  562. package/src/terrain/cdt2d.d.ts +10 -0
  563. package/src/terrain/continuous-mesh-error.ts +321 -0
  564. package/src/terrain/cutout-polygons.ts +202 -0
  565. package/src/terrain/cutout-region.ts +54 -0
  566. package/src/terrain/cutout-skirts.ts +52 -0
  567. package/src/terrain/depression-fill.ts +125 -0
  568. package/src/terrain/geographic-cutout.ts +154 -0
  569. package/src/terrain/geographic-lod-seams.ts +109 -0
  570. package/src/terrain/geographic-neighbor.ts +58 -0
  571. package/src/terrain/geographic-poles.ts +52 -0
  572. package/src/terrain/geographic-seam.ts +73 -0
  573. package/src/terrain/hydrology.ts +149 -0
  574. package/src/terrain/index.ts +160 -0
  575. package/src/terrain/lod-screen-error.ts +128 -0
  576. package/src/terrain/lod-select.ts +129 -0
  577. package/src/terrain/lod-stitch.ts +88 -0
  578. package/src/terrain/mesh-coverage.ts +215 -0
  579. package/src/terrain/mesh-cutout.ts +420 -0
  580. package/src/terrain/mesh-regions-data.ts +21 -13
  581. package/src/terrain/mesh-skirts.ts +10 -7
  582. package/src/terrain/mixed-halo-update.ts +147 -25
  583. package/src/terrain/mixed-vertex-halos.ts +125 -55
  584. package/src/terrain/regional-viewshed.ts +177 -0
  585. package/src/terrain/surface.ts +1 -1
  586. package/src/terrain/sweep-capsule.ts +148 -0
  587. package/src/terrain/sweep-cylinder.ts +64 -0
  588. package/src/terrain/sweep-plane.ts +61 -0
  589. package/src/terrain/sweep-polytope.ts +253 -0
  590. package/src/terrain/sweep-rotating-capsule.ts +139 -0
  591. package/src/terrain/sweep-rotation.ts +149 -0
  592. package/src/terrain/sweep-sphere.ts +100 -0
  593. package/src/terrain/tile-cutout-update.ts +293 -0
  594. package/src/terrain/tile-cutout.ts +123 -0
  595. package/src/terrain/valid-domain-mesh.ts +221 -0
  596. package/src/terrain/valid-domain-regions.ts +41 -0
  597. package/src/terrain/watershed-accumulation.ts +67 -0
  598. package/src/triaxial.ts +1 -1
  599. package/src/turf-expressions.ts +7 -0
  600. package/src/{turf/expressions.ts → turf-functions.ts} +121 -6
  601. package/src/turf.ts +3 -7
  602. package/src/type-utils.ts +2 -2
  603. package/src/web-mercator/assert.ts +11 -0
  604. package/src/web-mercator/fit-bounds.ts +132 -0
  605. package/src/web-mercator/fly-to-viewport.ts +157 -0
  606. package/src/web-mercator/get-bounds.ts +62 -0
  607. package/src/web-mercator/index.ts +49 -0
  608. package/src/web-mercator/math-utils.ts +35 -0
  609. package/src/web-mercator/mercator-meters.ts +83 -0
  610. package/src/web-mercator/normalize-viewport-props.ts +58 -0
  611. package/src/web-mercator/web-mercator-utils.ts +468 -0
  612. package/src/web-mercator/web-mercator-viewport.ts +406 -0
  613. package/src/web-mercator.ts +1 -1
  614. package/dist/projection/experimental/index.cjs +0 -11707
  615. package/dist/projection/experimental/index.cjs.map +0 -6
  616. package/dist/turf/expressions.cjs +0 -87
  617. package/dist/turf/expressions.cjs.map +0 -6
  618. package/dist/turf/expressions.d.ts +0 -24
  619. package/dist/turf/expressions.d.ts.map +0 -1
  620. package/dist/turf/expressions.js.map +0 -1
@@ -37,14 +37,23 @@ __export(index_exports, {
37
37
  TerrainContourBoundaryAxis: () => TerrainContourBoundaryAxis,
38
38
  TerrainMorphStatus: () => TerrainMorphStatus,
39
39
  TerrainProfileViewStatus: () => TerrainProfileViewStatus,
40
+ TerrainRegionalViewStatus: () => TerrainRegionalViewStatus,
40
41
  TerrainSampleStatus: () => TerrainSampleStatus,
41
42
  TerrainSurface: () => TerrainSurface,
42
43
  TerrainVertexHaloStatus: () => TerrainVertexHaloStatus,
43
44
  TiledHeightField: () => TiledHeightField,
45
+ accumulateTerrainWatersheds: () => accumulateTerrainWatersheds,
46
+ boundTerrainLodScreenError: () => boundTerrainLodScreenError,
47
+ boundTerrainMeshError: () => boundTerrainMeshError,
48
+ certifyTerrainMeshCoverage: () => certifyTerrainMeshCoverage,
44
49
  coordinateTerrainLodMorphs: () => coordinateTerrainLodMorphs,
50
+ createBreaklineTerrainMesh: () => createBreaklineTerrainMesh,
45
51
  createDelatinTerrainMesh: () => createDelatinTerrainMesh,
52
+ createGeographicTerrainCutoutFrame: () => createGeographicTerrainCutoutFrame,
46
53
  createMartiniTerrainMesh: () => createMartiniTerrainMesh,
47
54
  createTerrainContours: () => createTerrainContours,
55
+ createTerrainCutoutSkirts: () => createTerrainCutoutSkirts,
56
+ createTerrainDrainage: () => createTerrainDrainage,
48
57
  createTerrainFilteredPyramid: () => createTerrainFilteredPyramid,
49
58
  createTerrainGradientGrid: () => createTerrainGradientGrid,
50
59
  createTerrainGradientPyramid: () => createTerrainGradientPyramid,
@@ -53,12 +62,19 @@ __export(index_exports, {
53
62
  createTerrainMesh: () => createTerrainMesh,
54
63
  createTerrainMixedIsobands: () => createTerrainMixedIsobands,
55
64
  createTerrainMixedVertexTileHalos: () => createTerrainMixedVertexTileHalos,
65
+ createTerrainRegionalViewshed: () => createTerrainRegionalViewshed,
56
66
  createTerrainSkirt: () => createTerrainSkirt,
57
67
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
58
68
  createTerrainSurface: () => createTerrainSurface,
59
69
  createTerrainVertexTileHalos: () => createTerrainVertexTileHalos,
70
+ createValidDomainTerrainMesh: () => createValidDomainTerrainMesh,
60
71
  diagnoseTerrainContourBoundaries: () => diagnoseTerrainContourBoundaries,
72
+ discoverGeographicTerrainLodSeams: () => discoverGeographicTerrainLodSeams,
73
+ discoverGeographicTerrainPoles: () => discoverGeographicTerrainPoles,
61
74
  evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
75
+ fillTerrainDepressions: () => fillTerrainDepressions,
76
+ getGeographicTerrainNeighbor: () => getGeographicTerrainNeighbor,
77
+ getTerrainCellMetrics: () => getTerrainCellMetrics,
62
78
  getTerrainHierarchyNode: () => getTerrainHierarchyNode,
63
79
  getTerrainMeshEdge: () => getTerrainMeshEdge,
64
80
  getTerrainProfileHorizon: () => getTerrainProfileHorizon,
@@ -66,17 +82,38 @@ __export(index_exports, {
66
82
  getTerrainProfileVisibility: () => getTerrainProfileVisibility,
67
83
  getTerrainSlopeAspect: () => getTerrainSlopeAspect,
68
84
  getTerrainVertexHaloAffectedTiles: () => getTerrainVertexHaloAffectedTiles,
85
+ measureGeographicTerrainSeam: () => measureGeographicTerrainSeam,
69
86
  measureTerrainMeshError: () => measureTerrainMeshError,
70
87
  measureTerrainProfile: () => measureTerrainProfile,
71
88
  packTerrainHeightField: () => packTerrainHeightField,
89
+ prepareTerrainCutoutPolygons: () => prepareTerrainCutoutPolygons,
90
+ projectGeographicTerrainCutout: () => projectGeographicTerrainCutout,
72
91
  reconcileTerrainVertexTiles: () => reconcileTerrainVertexTiles,
73
92
  sampleTerrainProfile: () => sampleTerrainProfile,
93
+ selectTerrainLod: () => selectTerrainLod,
74
94
  simplifyTerrainContourPaths: () => simplifyTerrainContourPaths,
75
95
  simplifyTerrainContourPathsTopology: () => simplifyTerrainContourPathsTopology,
96
+ splitTerrainBreaklines: () => splitTerrainBreaklines,
97
+ splitTerrainMesh: () => splitTerrainMesh,
98
+ splitTerrainMeshTiles: () => splitTerrainMeshTiles,
76
99
  stitchTerrainContourTiles: () => stitchTerrainContourTiles,
77
100
  stitchTerrainContours: () => stitchTerrainContours,
101
+ stitchTerrainLodCut: () => stitchTerrainLodCut,
78
102
  stitchTerrainMeshEdges: () => stitchTerrainMeshEdges,
103
+ sweepTerrainBox: () => sweepTerrainBox,
104
+ sweepTerrainCapsule: () => sweepTerrainCapsule,
105
+ sweepTerrainCylinder: () => sweepTerrainCylinder,
106
+ sweepTerrainPlane: () => sweepTerrainPlane,
107
+ sweepTerrainPolytope: () => sweepTerrainPolytope,
108
+ sweepTerrainRotatingBox: () => sweepTerrainRotatingBox,
109
+ sweepTerrainRotatingCapsule: () => sweepTerrainRotatingCapsule,
110
+ sweepTerrainRotatingPolytope: () => sweepTerrainRotatingPolytope,
111
+ sweepTerrainRotatingSphere: () => sweepTerrainRotatingSphere,
112
+ sweepTerrainSphere: () => sweepTerrainSphere,
113
+ sweepTerrainTaperedCapsule: () => sweepTerrainTaperedCapsule,
114
+ sweepTerrainTriangleMesh: () => sweepTerrainTriangleMesh,
79
115
  unpackTerrainHeightField: () => unpackTerrainHeightField,
116
+ unprojectGeographicTerrainCutout: () => unprojectGeographicTerrainCutout,
80
117
  updateTerrainBounds: () => updateTerrainBounds,
81
118
  updateTerrainBoundsRegions: () => updateTerrainBoundsRegions,
82
119
  updateTerrainDelatinMeshRegions: () => updateTerrainDelatinMeshRegions,
@@ -89,9 +126,12 @@ __export(index_exports, {
89
126
  updateTerrainMixedVertexTileHalos: () => updateTerrainMixedVertexTileHalos,
90
127
  updateTerrainPersistentBounds: () => updateTerrainPersistentBounds,
91
128
  updateTerrainPersistentGradients: () => updateTerrainPersistentGradients,
129
+ updateTerrainTileCutouts: () => updateTerrainTileCutouts,
130
+ updateTerrainValidDomainMeshRegions: () => updateTerrainValidDomainMeshRegions,
92
131
  updateTerrainVertexTileHalos: () => updateTerrainVertexTileHalos,
93
132
  weldTerrainContourTiles: () => weldTerrainContourTiles,
94
- weldTerrainMixedContourTiles: () => weldTerrainMixedContourTiles
133
+ weldTerrainMixedContourTiles: () => weldTerrainMixedContourTiles,
134
+ wrapTerrainLongitude: () => wrapTerrainLongitude
95
135
  });
96
136
  module.exports = __toCommonJS(index_exports);
97
137
 
@@ -407,13 +447,13 @@ function validateBatch(positions, output) {
407
447
 
408
448
  // dist/terrain/mesh-skirts.js
409
449
  function createTerrainSkirt(mesh, options) {
410
- const { positions, indices } = mesh, { height, edges } = options;
450
+ const { positions, indices } = mesh, { height, baseZ, edges: edges2 } = options;
411
451
  const maxVertices = options.maxVertices ?? 2e6, maxTriangles = options.maxTriangles ?? 4e6;
412
- if (!Number.isFinite(height) || height <= 0 || !Number.isSafeInteger(maxVertices) || maxVertices < 0 || maxVertices > 4294967295 || !Number.isSafeInteger(maxTriangles) || maxTriangles < 0 || maxTriangles > 4294967295)
452
+ if ((baseZ === void 0 ? !(Number.isFinite(height) && height > 0) : height !== void 0 || !Number.isFinite(baseZ)) || !Number.isSafeInteger(maxVertices) || maxVertices < 0 || maxVertices > 4294967295 || !Number.isSafeInteger(maxTriangles) || maxTriangles < 0 || maxTriangles > 4294967295)
413
453
  throw new Error("Invalid terrain skirt height or capacity");
414
454
  if (!(positions instanceof Float32Array || positions instanceof Float64Array) || positions.length < 3 || positions.length % 3 || !positions.every(Number.isFinite) || !(indices instanceof Uint16Array || indices instanceof Uint32Array) || indices.length % 3 || positions.length / 3 > maxVertices || indices.length / 3 > maxTriangles)
415
455
  throw new Error("Invalid terrain skirt mesh or capacity");
416
- if (edges !== void 0 && (!(edges instanceof Uint16Array || edges instanceof Uint32Array) || edges.length % 2))
456
+ if (edges2 !== void 0 && (!(edges2 instanceof Uint16Array || edges2 instanceof Uint32Array) || edges2.length % 2))
417
457
  throw new Error("Invalid terrain skirt edge pairs");
418
458
  const vertexCount = positions.length / 3, triangleCount = indices.length / 3;
419
459
  const boundary = /* @__PURE__ */ new Map();
@@ -437,18 +477,18 @@ function createTerrainSkirt(mesh, options) {
437
477
  }
438
478
  }
439
479
  let selected;
440
- if (edges) {
480
+ if (edges2) {
441
481
  selected = [];
442
482
  const used = /* @__PURE__ */ new Set();
443
- for (let i = 0; i < edges.length; i += 2) {
444
- const key2 = edgeKey(edges[i], edges[i + 1]), edge = boundary.get(key2);
445
- if (!edge || edge.count !== 1 || used.has(key2))
483
+ for (let i = 0; i < edges2.length; i += 2) {
484
+ const key2 = edgeKey(edges2[i], edges2[i + 1]), edge2 = boundary.get(key2);
485
+ if (!edge2 || edge2.count !== 1 || used.has(key2))
446
486
  throw new Error("Terrain skirt selection must contain unique boundary edges");
447
487
  used.add(key2);
448
- selected.push(edge);
488
+ selected.push(edge2);
449
489
  }
450
490
  } else
451
- selected = [...boundary.values()].filter((edge) => edge.count === 1);
491
+ selected = [...boundary.values()].filter((edge2) => edge2.count === 1);
452
492
  const outputVertices = vertexCount + selected.length * 2, outputTriangles = triangleCount + selected.length * 2;
453
493
  if (!Number.isSafeInteger(outputVertices) || outputVertices > maxVertices || outputVertices > 4294967295 || !Number.isSafeInteger(outputTriangles) || outputTriangles > maxTriangles)
454
494
  throw new Error("Terrain skirt output capacity exceeded");
@@ -465,7 +505,7 @@ function createTerrainSkirt(mesh, options) {
465
505
  [b, lowerB]
466
506
  ]) {
467
507
  resultPositions.set(positions.subarray(3 * source, 3 * source + 3), 3 * target);
468
- resultPositions[3 * target + 2] = positions[3 * source + 2] - height;
508
+ resultPositions[3 * target + 2] = baseZ ?? positions[3 * source + 2] - height;
469
509
  if (!Number.isFinite(resultPositions[3 * target + 2]) || resultPositions[3 * target + 2] >= positions[3 * source + 2])
470
510
  throw new Error("Terrain skirt height cannot be represented in position precision");
471
511
  sourceVertexIndices[target - vertexCount] = source;
@@ -599,11 +639,11 @@ var ECCENTRICITY_SQUARED = 0.0066943799901413165;
599
639
  var MAX_MERCATOR_LATITUDE = Math.atan(Math.sinh(Math.PI)) / RADIANS;
600
640
  var GeographicHeightField = class {
601
641
  constructor(props) {
602
- const { bounds } = props;
642
+ const { bounds: bounds2 } = props;
603
643
  this.projection = props.projection ?? "geographic";
604
644
  this.heightReference = props.heightReference ?? "unknown";
605
645
  const limit = this.projection === "web-mercator" ? MAX_MERCATOR_LATITUDE : 90;
606
- if (bounds.length !== 4 || !bounds.every(Number.isFinite) || bounds[2] <= bounds[0] || bounds[2] - bounds[0] > 360 || bounds[3] <= bounds[1] || bounds[1] < -limit || bounds[3] > limit || this.projection === "geographic" && (bounds[1] === -90 || bounds[3] === 90)) {
646
+ if (bounds2.length !== 4 || !bounds2.every(Number.isFinite) || bounds2[2] <= bounds2[0] || bounds2[2] - bounds2[0] > 360 || bounds2[3] <= bounds2[1] || bounds2[1] < -limit || bounds2[3] > limit || this.projection === "geographic" && (bounds2[1] === -90 || bounds2[3] === 90)) {
607
647
  throw new Error("Terrain bounds must be increasing, span at most 360 degrees and exclude the projection limits");
608
648
  }
609
649
  if (this.projection !== "geographic" && this.projection !== "web-mercator")
@@ -611,11 +651,11 @@ var GeographicHeightField = class {
611
651
  const direction = props.rowDirection ?? "north-to-south";
612
652
  if (direction !== "north-to-south" && direction !== "south-to-north")
613
653
  throw new Error("Unknown terrain row direction");
614
- this.bounds = Object.freeze([...bounds]);
615
- const west = this.projectX(bounds[0]);
616
- const east = this.projectX(bounds[2]);
617
- const south = this.projectY(bounds[1]);
618
- const north = this.projectY(bounds[3]);
654
+ this.bounds = Object.freeze([...bounds2]);
655
+ const west = this.projectX(bounds2[0]);
656
+ const east = this.projectX(bounds2[2]);
657
+ const south = this.projectY(bounds2[1]);
658
+ const north = this.projectY(bounds2[3]);
619
659
  const cell = props.registration === "cell";
620
660
  const descending = direction === "north-to-south";
621
661
  this.field = new HeightField({
@@ -626,17 +666,17 @@ var GeographicHeightField = class {
626
666
  });
627
667
  }
628
668
  /** Longitude must use the bounds' unwrapped interval; no implicit wrapping or clamping. */
629
- sample(longitude, latitude, options, result) {
630
- const valid = Number.isFinite(longitude) && Number.isFinite(latitude);
631
- const inside = valid && longitude >= this.bounds[0] && longitude <= this.bounds[2] && latitude >= this.bounds[1] && latitude <= this.bounds[3];
632
- const sample = this.field.sample(inside ? this.projectX(longitude) : NaN, inside ? this.projectY(latitude) : NaN, options, result);
669
+ sample(longitude, latitude2, options, result) {
670
+ const valid = Number.isFinite(longitude) && Number.isFinite(latitude2);
671
+ const inside = valid && longitude >= this.bounds[0] && longitude <= this.bounds[2] && latitude2 >= this.bounds[1] && latitude2 <= this.bounds[3];
672
+ const sample = this.field.sample(inside ? this.projectX(longitude) : NaN, inside ? this.projectY(latitude2) : NaN, options, result);
633
673
  if (!inside) {
634
674
  sample.status = sample.gradientStatus = valid ? TerrainSampleStatus.OUTSIDE_DOMAIN : TerrainSampleStatus.INVALID_INPUT;
635
675
  return sample;
636
676
  }
637
677
  if (sample.gradientStatus !== TerrainSampleStatus.VALID)
638
678
  return sample;
639
- const phi = latitude * RADIANS;
679
+ const phi = latitude2 * RADIANS;
640
680
  const denominator = 1 - ECCENTRICITY_SQUARED * Math.sin(phi) ** 2;
641
681
  const n = RADIUS / Math.sqrt(denominator);
642
682
  const m = RADIUS * (1 - ECCENTRICITY_SQUARED) / denominator ** 1.5;
@@ -660,8 +700,8 @@ var GeographicHeightField = class {
660
700
  projectX(longitude) {
661
701
  return this.projection === "web-mercator" ? RADIUS * longitude * RADIANS : longitude;
662
702
  }
663
- projectY(latitude) {
664
- return this.projection === "web-mercator" ? RADIUS * Math.asinh(Math.tan(latitude * RADIANS)) : latitude;
703
+ projectY(latitude2) {
704
+ return this.projection === "web-mercator" ? RADIUS * Math.asinh(Math.tan(latitude2 * RADIANS)) : latitude2;
665
705
  }
666
706
  };
667
707
 
@@ -1133,7 +1173,7 @@ function createTransform(steps) {
1133
1173
  }
1134
1174
 
1135
1175
  // dist/terrain/surface.js
1136
- var import_geometry2 = require("@math.gl/geometry");
1176
+ var import_spatial_index = require("@math.gl/geometry/spatial-index");
1137
1177
 
1138
1178
  // dist/terrain/mesh-data.js
1139
1179
  function assembleTerrainMesh(field, gridCoordinates, indices, options) {
@@ -1196,7 +1236,7 @@ function createTerrainMesh(field, options = {}) {
1196
1236
  coordinates.set([column, row], (row * field.width + column) * 2);
1197
1237
  const output = new Uint32Array((field.width - 1) * (field.height - 1) * 6);
1198
1238
  let used = 0;
1199
- const add = (a, b, c) => {
1239
+ const add2 = (a, b, c) => {
1200
1240
  for (const i of [a, b, c])
1201
1241
  if (field.getHeight(i % field.width, Math.floor(i / field.width)) === void 0)
1202
1242
  return;
@@ -1208,11 +1248,11 @@ function createTerrainMesh(field, options = {}) {
1208
1248
  for (let column = 0; column < field.width - 1; column++) {
1209
1249
  const a = row * field.width + column, b = a + 1, c = a + field.width, d = c + 1;
1210
1250
  if (field.diagonal === "00-11") {
1211
- add(a, b, d);
1212
- add(a, d, c);
1251
+ add2(a, b, d);
1252
+ add2(a, d, c);
1213
1253
  } else {
1214
- add(a, b, c);
1215
- add(b, d, c);
1254
+ add2(a, b, c);
1255
+ add2(b, d, c);
1216
1256
  }
1217
1257
  }
1218
1258
  return assembleTerrainMesh(field, coordinates, used === output.length ? output : output.slice(0, used), options);
@@ -1245,11 +1285,11 @@ var TerrainSurface = class {
1245
1285
  throw new Error("Terrain vertex index out of bounds");
1246
1286
  this.gradients = new Float64Array(this.triangleCount * 2);
1247
1287
  this.normals = new Float64Array(this.triangleCount * 3);
1248
- const bounds = new Float64Array(this.triangleCount * 4);
1288
+ const bounds2 = new Float64Array(this.triangleCount * 4);
1249
1289
  let active = 0;
1250
1290
  for (let i = 0; i < this.triangleCount; i++) {
1251
1291
  const [a, b, c] = this.triangle(i);
1252
- bounds.set([
1292
+ bounds2.set([
1253
1293
  Math.min(a[0], b[0], c[0]),
1254
1294
  Math.min(a[1], b[1], c[1]),
1255
1295
  Math.max(a[0], b[0], c[0]),
@@ -1275,8 +1315,8 @@ var TerrainSurface = class {
1275
1315
  }
1276
1316
  this.activeTriangleCount = active;
1277
1317
  this.topology = buildTopology(this.indices, this.validity);
1278
- this.xyIndex = new import_geometry2.BoxIndex({ bounds, dimension: 2 });
1279
- this.bvh = new import_geometry2.TriangleBVH({ positions: this.positions, indices: this.indices });
1318
+ this.xyIndex = new import_spatial_index.BoxIndex({ bounds: bounds2, dimension: 2 });
1319
+ this.bvh = new import_spatial_index.TriangleBVH({ positions: this.positions, indices: this.indices });
1280
1320
  }
1281
1321
  /** Detached source data; changing these buffers never changes this surface. */
1282
1322
  copyData() {
@@ -1520,16 +1560,16 @@ var TerrainSurface = class {
1520
1560
  };
1521
1561
  function buildTopology(indices, validity) {
1522
1562
  const halfedges = new Int32Array(indices.length).fill(-1);
1523
- const edges = /* @__PURE__ */ new Map();
1563
+ const edges2 = /* @__PURE__ */ new Map();
1524
1564
  for (let i = 0; i < indices.length; i++) {
1525
1565
  const triangle = Math.floor(i / 3);
1526
1566
  if (!validity[triangle])
1527
1567
  continue;
1528
1568
  const a = indices[i], b = indices[triangle * 3 + (i % 3 + 1) % 3];
1529
1569
  const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
1530
- const opposite = edges.get(key2);
1570
+ const opposite = edges2.get(key2);
1531
1571
  if (opposite === void 0)
1532
- edges.set(key2, i);
1572
+ edges2.set(key2, i);
1533
1573
  else {
1534
1574
  if (halfedges[opposite] !== -1)
1535
1575
  throw new Error("Nonmanifold terrain edge");
@@ -1775,13 +1815,13 @@ function measureTerrainMeshError(field, mesh, options = {}) {
1775
1815
  }
1776
1816
 
1777
1817
  // dist/terrain/mesh-edges.js
1778
- function getTerrainMeshEdge(mesh, edge) {
1818
+ function getTerrainMeshEdge(mesh, edge2) {
1779
1819
  validateTerrainGridMesh(mesh);
1780
- if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge))
1820
+ if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge2))
1781
1821
  throw new Error("Unknown terrain mesh edge");
1782
- const column = edge === "minColumn" || edge === "maxColumn";
1822
+ const column = edge2 === "minColumn" || edge2 === "maxColumn";
1783
1823
  const axis = column ? 0 : 1;
1784
- const value = edge.startsWith("min") ? 0 : (column ? mesh.width : mesh.height) - 1;
1824
+ const value = edge2.startsWith("min") ? 0 : (column ? mesh.width : mesh.height) - 1;
1785
1825
  const vertices = /* @__PURE__ */ new Set();
1786
1826
  for (const index of mesh.indices)
1787
1827
  if (mesh.gridCoordinates[2 * index + axis] === value)
@@ -1805,19 +1845,19 @@ function createMartiniTerrainMesh(field, options) {
1805
1845
  throw new Error("Adaptive terrain sample capacity exceeded");
1806
1846
  if (field.validCount !== size * size)
1807
1847
  throw new Error("Adaptive terrain requires complete source data; use a regular mesh for holes");
1808
- const edges = options.fullEdges ?? [];
1809
- for (const edge of edges)
1810
- if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge))
1848
+ const edges2 = options.fullEdges ?? [];
1849
+ for (const edge2 of edges2)
1850
+ if (!["minColumn", "maxColumn", "minRow", "maxRow"].includes(edge2))
1811
1851
  throw new Error("Unknown adaptive terrain edge");
1812
1852
  const { heights } = field.copyData();
1813
1853
  const tile = new import_martini.default(size).createTile(heights);
1814
- for (const edge of edges)
1854
+ for (const edge2 of edges2)
1815
1855
  for (let i = 0; i < size; i++) {
1816
- const column = edge === "minColumn" ? 0 : edge === "maxColumn" ? cells : i;
1817
- const row = edge === "minRow" ? 0 : edge === "maxRow" ? cells : i;
1856
+ const column = edge2 === "minColumn" ? 0 : edge2 === "maxColumn" ? cells : i;
1857
+ const row = edge2 === "minRow" ? 0 : edge2 === "maxRow" ? cells : i;
1818
1858
  tile.errors[row * size + column] = Infinity;
1819
1859
  }
1820
- if (edges.length)
1860
+ if (edges2.length)
1821
1861
  tile.update();
1822
1862
  let threshold = options.maxError;
1823
1863
  for (let pass = 0; pass <= 8; pass++) {
@@ -2438,13 +2478,13 @@ function createTerrainContours(field, levels, options = {}) {
2438
2478
  const outputLevels = Float64Array.from(levels), positions = [], coordinates = [], segments = [], levelIndices = [];
2439
2479
  const shift = field.registration === "cell" ? 0.5 : 0;
2440
2480
  for (let levelIndex = 0; levelIndex < outputLevels.length; levelIndex++) {
2441
- const level = outputLevels[levelIndex], vertices = /* @__PURE__ */ new Map(), edges = /* @__PURE__ */ new Set();
2481
+ const level = outputLevels[levelIndex], vertices = /* @__PURE__ */ new Map(), edges2 = /* @__PURE__ */ new Set();
2442
2482
  const height = (i) => field.getHeight(i % field.width, Math.floor(i / field.width));
2443
2483
  const intersection = (a, b) => {
2444
2484
  if (a > b)
2445
2485
  [a, b] = [b, a];
2446
- const exact = height(a) === level ? a : height(b) === level ? b : void 0;
2447
- return exact === void 0 ? { a, b, key: `e${a}/${b}` } : { a: exact, b: exact, key: `v${exact}` };
2486
+ const exact2 = height(a) === level ? a : height(b) === level ? b : void 0;
2487
+ return exact2 === void 0 ? { a, b, key: `e${a}/${b}` } : { a: exact2, b: exact2, key: `v${exact2}` };
2448
2488
  };
2449
2489
  const vertex = ({ a, b, key: key2 }) => {
2450
2490
  const existing = vertices.get(key2);
@@ -2492,13 +2532,13 @@ function createTerrainContours(field, levels, options = {}) {
2492
2532
  return;
2493
2533
  const va = vertex(hits[0]), vb = vertex(hits[1]);
2494
2534
  const key2 = va < vb ? `${va}/${vb}` : `${vb}/${va}`;
2495
- if (edges.has(key2))
2535
+ if (edges2.has(key2))
2496
2536
  return;
2497
2537
  if (segments.length / 2 >= maxSegments)
2498
2538
  throw new Error("Terrain contour segment capacity exceeded");
2499
2539
  if (positions[3 * va] === positions[3 * vb] && positions[3 * va + 1] === positions[3 * vb + 1])
2500
2540
  throw new Error("Terrain contour segment collapses; use a local origin");
2501
- edges.add(key2);
2541
+ edges2.add(key2);
2502
2542
  segments.push(va, vb);
2503
2543
  levelIndices.push(levelIndex);
2504
2544
  };
@@ -2610,16 +2650,16 @@ function stitchTerrainContours(contours, options = {}) {
2610
2650
  throw new Error("Terrain contour path capacity exceeded");
2611
2651
  levels.push(assignments[start]);
2612
2652
  append(start);
2613
- let vertex = start, edge = firstEdge;
2614
- while (!visited[edge]) {
2615
- visited[edge] = 1;
2616
- const a = contours.segments[2 * edge], b = contours.segments[2 * edge + 1];
2653
+ let vertex = start, edge2 = firstEdge;
2654
+ while (!visited[edge2]) {
2655
+ visited[edge2] = 1;
2656
+ const a = contours.segments[2 * edge2], b = contours.segments[2 * edge2 + 1];
2617
2657
  vertex = vertex === a ? b : a;
2618
2658
  append(vertex);
2619
2659
  if (vertex === start || degrees[vertex] !== 2)
2620
2660
  break;
2621
2661
  const e0 = adjacency[starts[vertex]], e1 = adjacency[starts[vertex] + 1];
2622
- edge = visited[e0] ? e1 : e0;
2662
+ edge2 = visited[e0] ? e1 : e0;
2623
2663
  }
2624
2664
  closed.push(vertex === start ? 1 : 0);
2625
2665
  offsets.push(indices.length);
@@ -2657,7 +2697,7 @@ function weldTerrainContourTiles(tiles, options) {
2657
2697
  const levels = first.levels.slice();
2658
2698
  const positions = [], grid = [], segments = [], levelIndices = [];
2659
2699
  const vertices = /* @__PURE__ */ new Map();
2660
- const edges = /* @__PURE__ */ new Map();
2700
+ const edges2 = /* @__PURE__ */ new Map();
2661
2701
  const addresses = /* @__PURE__ */ new Set();
2662
2702
  let inputVertices = 0;
2663
2703
  let inputSegments = 0;
@@ -2733,8 +2773,8 @@ function weldTerrainContourTiles(tiles, options) {
2733
2773
  const level = data.levelIndices[i], a = mapVertex(data.segments[2 * i], level), b = mapVertex(data.segments[2 * i + 1], level);
2734
2774
  if (a === b || positions[3 * a] === positions[3 * b] && positions[3 * a + 1] === positions[3 * b + 1])
2735
2775
  throw new Error("Degenerate terrain contour segment after rebasing");
2736
- const edge = a < b ? `${a}/${b}` : `${b}/${a}`;
2737
- const previous = edges.get(edge);
2776
+ const edge2 = a < b ? `${a}/${b}` : `${b}/${a}`;
2777
+ const previous = edges2.get(edge2);
2738
2778
  if (previous !== void 0) {
2739
2779
  if (previous === tileIndex)
2740
2780
  throw new Error("Duplicate terrain contour segment");
@@ -2742,7 +2782,7 @@ function weldTerrainContourTiles(tiles, options) {
2742
2782
  }
2743
2783
  if (levelIndices.length >= limits.maxSegments)
2744
2784
  throw new Error("Terrain contour segment capacity exceeded");
2745
- edges.set(edge, tileIndex);
2785
+ edges2.set(edge2, tileIndex);
2746
2786
  segments.push(a, b);
2747
2787
  levelIndices.push(level);
2748
2788
  }
@@ -3024,7 +3064,7 @@ function measureTerrainProfile(profile, options = {}) {
3024
3064
  let validSampleCount = 0, minimum = Infinity, maximum = -Infinity, coveredSegmentCount = 0, missingSegmentCount = 0;
3025
3065
  let meanHeight = 0;
3026
3066
  const sums = new Float64Array(6), corrections = new Float64Array(6);
3027
- const add = (index, value) => {
3067
+ const add2 = (index, value) => {
3028
3068
  const y = value - corrections[index], next = sums[index] + y;
3029
3069
  if (!Number.isFinite(value) || !Number.isFinite(next))
3030
3070
  throw new Error("Terrain profile measurement arithmetic overflow");
@@ -3049,17 +3089,17 @@ function measureTerrainProfile(profile, options = {}) {
3049
3089
  const ds = distance - profile.distances[i - 1];
3050
3090
  if (status !== TerrainSampleStatus.VALID || profile.statuses[i - 1] !== TerrainSampleStatus.VALID) {
3051
3091
  missingSegmentCount++;
3052
- add(1, ds);
3092
+ add2(1, ds);
3053
3093
  continue;
3054
3094
  }
3055
3095
  coveredSegmentCount++;
3056
3096
  const previousCovered = sums[0];
3057
- add(0, ds);
3097
+ add2(0, ds);
3058
3098
  const previous = profile.heights[i - 1], dh = height - previous;
3059
- add(dh >= 0 ? 2 : 3, Math.abs(dh));
3060
- add(4, Math.hypot(ds, dh));
3099
+ add2(dh >= 0 ? 2 : 3, Math.abs(dh));
3100
+ add2(4, Math.hypot(ds, dh));
3061
3101
  const average = previous + dh / 2;
3062
- add(5, average * ds);
3102
+ add2(5, average * ds);
3063
3103
  if (previousCovered === 0)
3064
3104
  meanHeight = average;
3065
3105
  else {
@@ -3796,7 +3836,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3796
3836
  throw new Error("Mixed contour boundary-test budget exceeded");
3797
3837
  };
3798
3838
  const sorted = [...tiles].sort((a, b) => a.column - b.column || a.row - b.row || a.spacing - b.spacing);
3799
- const bounds = sorted.map((t) => {
3839
+ const bounds2 = sorted.map((t) => {
3800
3840
  if (![t.column, t.row, t.width, t.height, t.spacing].every(Number.isSafeInteger) || t.width < 2 || t.height < 2 || t.spacing < 1 || 2 ** Math.round(Math.log2(t.spacing)) !== t.spacing)
3801
3841
  throw new Error("Invalid mixed contour tile lattice");
3802
3842
  const x1 = t.column + (t.width - 1) * t.spacing, y1 = t.row + (t.height - 1) * t.spacing;
@@ -3804,10 +3844,10 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3804
3844
  throw new Error("Mixed contour lattice overflow");
3805
3845
  return [t.column, t.row, x1, y1];
3806
3846
  });
3807
- for (let i = 0; i < bounds.length; i++)
3847
+ for (let i = 0; i < bounds2.length; i++)
3808
3848
  for (let j = 0; j < i; j++) {
3809
3849
  charge();
3810
- const a = bounds[i], b = bounds[j];
3850
+ const a = bounds2[i], b = bounds2[j];
3811
3851
  if (Math.max(a[0], b[0]) < Math.min(a[2], b[2]) && Math.max(a[1], b[1]) < Math.min(a[3], b[3]))
3812
3852
  throw new Error("Mixed contour tile interiors overlap");
3813
3853
  }
@@ -3815,7 +3855,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3815
3855
  const positions = [], grid = [], vertexLevels = [];
3816
3856
  const roundedBoundary = /* @__PURE__ */ new Map();
3817
3857
  const boundary = /* @__PURE__ */ new Set(), shared = /* @__PURE__ */ new Map();
3818
- const edges = [];
3858
+ const edges2 = [];
3819
3859
  let inputVertices = 0, inputSegments = 0;
3820
3860
  for (let ti = 0; ti < sorted.length; ti++) {
3821
3861
  const tile = sorted[ti], data = tile.contours;
@@ -3890,18 +3930,18 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3890
3930
  if (localEdges.has(key2))
3891
3931
  throw new Error("Duplicate mixed contour segment");
3892
3932
  localEdges.add(key2);
3893
- const box = bounds[ti];
3933
+ const box = bounds2[ti];
3894
3934
  const seam = grid[2 * a] === grid[2 * b] && (grid[2 * a] === box[0] || grid[2 * a] === box[2]) || grid[2 * a + 1] === grid[2 * b + 1] && (grid[2 * a + 1] === box[1] || grid[2 * a + 1] === box[3]);
3895
- edges.push({ a, b, level, tile: ti, seam });
3935
+ edges2.push({ a, b, level, tile: ti, seam });
3896
3936
  }
3897
3937
  }
3898
3938
  const segments = [], levels = [], emitted = /* @__PURE__ */ new Map();
3899
- for (const edge of edges) {
3900
- const { a, b, level } = edge;
3939
+ for (const edge2 of edges2) {
3940
+ const { a, b, level } = edge2;
3901
3941
  const axis = grid[2 * a] === grid[2 * b] ? 1 : 0;
3902
3942
  const start = grid[2 * a + axis], end = grid[2 * b + axis];
3903
3943
  const cuts = [a, b];
3904
- if (edge.seam)
3944
+ if (edge2.seam)
3905
3945
  for (const v of boundary) {
3906
3946
  charge();
3907
3947
  const value = grid[2 * v + axis];
@@ -3919,13 +3959,13 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3919
3959
  const u = cuts[i - 1], v = cuts[i], key2 = u < v ? `${u}/${v}` : `${v}/${u}`;
3920
3960
  const prior = emitted.get(key2);
3921
3961
  if (prior !== void 0) {
3922
- if (prior === edge.tile)
3962
+ if (prior === edge2.tile)
3923
3963
  throw new Error("Overlapping mixed contour segments within tile");
3924
3964
  continue;
3925
3965
  }
3926
3966
  if (levels.length >= limits.maxSegments)
3927
3967
  throw new Error("Mixed contour output segment capacity exceeded");
3928
- emitted.set(key2, edge.tile);
3968
+ emitted.set(key2, edge2.tile);
3929
3969
  segments.push(u, v);
3930
3970
  levels.push(level);
3931
3971
  }
@@ -3941,6 +3981,46 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
3941
3981
  };
3942
3982
  }
3943
3983
 
3984
+ // dist/terrain/box-index.js
3985
+ var overlaps = (a, b) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
3986
+ function createTerrainBoxIndex(boxes) {
3987
+ const build = (ids) => {
3988
+ const box = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
3989
+ for (const id of ids) {
3990
+ const b = boxes[id];
3991
+ box.minX = Math.min(box.minX, b.minX);
3992
+ box.minY = Math.min(box.minY, b.minY);
3993
+ box.maxX = Math.max(box.maxX, b.maxX);
3994
+ box.maxY = Math.max(box.maxY, b.maxY);
3995
+ }
3996
+ if (ids.length <= 8)
3997
+ return { ...box, ids };
3998
+ const axis = box.maxX - box.minX >= box.maxY - box.minY ? "X" : "Y";
3999
+ 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);
4000
+ const mid = ids.length >>> 1;
4001
+ return { ...box, left: build(ids.slice(0, mid)), right: build(ids.slice(mid)) };
4002
+ };
4003
+ const root = build(boxes.map((_, i) => i));
4004
+ return (query, charge) => {
4005
+ const found = [], stack = [root];
4006
+ while (stack.length) {
4007
+ charge();
4008
+ const node = stack.pop();
4009
+ if (!overlaps(node, query))
4010
+ continue;
4011
+ if (node.ids) {
4012
+ for (const id of node.ids) {
4013
+ charge();
4014
+ if (overlaps(boxes[id], query))
4015
+ found.push(id);
4016
+ }
4017
+ } else
4018
+ stack.push(node.right, node.left);
4019
+ }
4020
+ return found.sort((a, b) => a - b);
4021
+ };
4022
+ }
4023
+
3944
4024
  // dist/terrain/sample-triangle-height.js
3945
4025
  function sampleTerrainTriangleHeight(field, x, y) {
3946
4026
  if (Number.isInteger(x) && Number.isInteger(y))
@@ -3988,63 +4068,83 @@ function sampleTerrainTriangleHeight(field, x, y) {
3988
4068
  function createTerrainMixedVertexTileHalos(tiles, options = {}) {
3989
4069
  return buildMixedVertexTileHalos(tiles, options);
3990
4070
  }
3991
- function buildMixedVertexTileHalos(tiles, options = {}, targets) {
4071
+ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
3992
4072
  const maxSamples = options.maxSamples ?? 4e6, maxTests = options.maxTileTests ?? 1e7;
3993
4073
  if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
3994
4074
  throw new Error("Invalid mixed halo capacity");
3995
4075
  let count = 0;
3996
- const addresses = /* @__PURE__ */ new Set();
4076
+ let previousKey;
3997
4077
  let frame;
3998
4078
  const sources = [...tiles].sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row).map((tile) => {
3999
- if (![tile.column, tile.row, tile.spacing].every(Number.isSafeInteger) || tile.spacing < 1 || 2 ** Math.round(Math.log2(tile.spacing)) !== tile.spacing)
4000
- throw new Error("Invalid mixed halo lattice");
4001
- const key2 = `${tile.spacing}/${tile.column}/${tile.row}`;
4002
- if (addresses.has(key2))
4003
- throw new Error("Duplicate mixed halo tile");
4004
- addresses.add(key2);
4005
4079
  count += (tile.field.width + 2) * (tile.field.height + 2);
4006
4080
  if (!Number.isSafeInteger(count) || count > maxSamples)
4007
4081
  throw new Error("Mixed halo sample capacity exceeded");
4008
- const field = new HeightField(tile.field);
4009
- if (field.registration !== "vertex")
4010
- throw new Error("Mixed halos require vertex registration");
4011
- const column = field.columnStep.map((v) => v / tile.spacing);
4012
- const row = field.rowStep.map((v) => v / tile.spacing);
4013
- const origin = field.origin.map((v, axis) => v - tile.column * column[axis] - tile.row * row[axis]);
4014
- 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])));
4015
- if (!origin.every(Number.isFinite))
4016
- throw new Error("Mixed halo coordinate overflow");
4017
- 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]))))))
4018
- throw new Error("Mixed halo frames or height references differ");
4082
+ let prepared = preparation == null ? void 0 : preparation.tiles.get(tile);
4083
+ if (!prepared) {
4084
+ prepared = prepareMixedHaloTile(tile);
4085
+ preparation == null ? void 0 : preparation.tiles.set(tile, prepared);
4086
+ }
4087
+ const { key: key2, source: field, columnStep: column, rowStep: row, frameOrigin: origin, scale } = prepared;
4088
+ if (previousKey === key2)
4089
+ throw new Error("Duplicate mixed halo tile");
4090
+ previousKey = key2;
4091
+ if (frame) {
4092
+ if (frame.reference !== field.heightReference)
4093
+ throw new Error("Mixed halo frames or height references differ");
4094
+ for (let i = 0; i < 2; i++) {
4095
+ if (column[i] !== frame.column[i] || row[i] !== frame.row[i] || origin[i] !== frame.origin[i] && Math.abs(origin[i] - 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]))))
4096
+ throw new Error("Mixed halo frames or height references differ");
4097
+ }
4098
+ }
4019
4099
  frame ?? (frame = { origin, column, row, reference: field.heightReference, scale });
4020
- return { ...tile, source: field };
4100
+ return prepared;
4021
4101
  });
4022
- for (const axis of ["column", "row"]) {
4023
- let min = Infinity, max = -Infinity;
4024
- for (const tile of sources) {
4025
- const size = axis === "column" ? tile.source.width : tile.source.height;
4026
- const low = tile[axis] - tile.spacing, high = tile[axis] + size * tile.spacing;
4027
- if (![low, high].every(Number.isSafeInteger))
4028
- throw new Error("Mixed halo lattice overflow");
4029
- min = Math.min(min, low);
4030
- max = Math.max(max, high);
4102
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
4103
+ for (let i = 0; i < sources.length; i++) {
4104
+ const { haloBounds } = sources[i];
4105
+ minX = Math.min(minX, haloBounds.minX);
4106
+ minY = Math.min(minY, haloBounds.minY);
4107
+ maxX = Math.max(maxX, haloBounds.maxX);
4108
+ maxY = Math.max(maxY, haloBounds.maxY);
4109
+ }
4110
+ if (sources.length && (!Number.isSafeInteger(maxX - minX) || !Number.isSafeInteger(maxY - minY)))
4111
+ throw new Error("Mixed halo lattice span overflow");
4112
+ if (targets && targets.size === 0)
4113
+ return { tiles: [] };
4114
+ let index;
4115
+ if (sources.length > 8) {
4116
+ const cached = preparation == null ? void 0 : preparation.layout;
4117
+ if (cached && sources.length === cached.keys.length && sources.every((tile, i) => tile.layoutKey === cached.keys[i])) {
4118
+ index = cached.query;
4119
+ } else {
4120
+ index = createTerrainBoxIndex(sources.map((tile) => ({
4121
+ minX: tile.column,
4122
+ minY: tile.row,
4123
+ maxX: tile.column + (tile.source.width - 1) * tile.spacing,
4124
+ maxY: tile.row + (tile.source.height - 1) * tile.spacing
4125
+ })));
4126
+ if (preparation)
4127
+ preparation.layout = { keys: sources.map((tile) => tile.layoutKey), query: index };
4031
4128
  }
4032
- if (sources.length && !Number.isSafeInteger(max - min))
4033
- throw new Error("Mixed halo lattice span overflow");
4034
4129
  }
4035
4130
  let tests = 0;
4131
+ const charge = () => {
4132
+ if (++tests > maxTests)
4133
+ throw new Error("Mixed halo tile-test budget exceeded");
4134
+ };
4036
4135
  return {
4037
- tiles: sources.filter((tile) => !targets || targets.has(`${tile.spacing}/${tile.column}/${tile.row}`)).map((tile) => {
4136
+ tiles: sources.filter((tile) => !targets || targets.has(tile.key)).map((tile) => {
4038
4137
  const source = tile.source, width = source.width + 2, height = source.height + 2;
4039
4138
  const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
4139
+ const candidates = (index == null ? void 0 : index(tile.haloBounds, charge).map((id) => sources[id])) ?? sources;
4040
4140
  for (let y = 0; y < height; y++)
4041
4141
  for (let x = 0; x < width; x++) {
4042
4142
  const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
4043
- if (![gx, gy].every(Number.isSafeInteger))
4143
+ if (!Number.isSafeInteger(gx) || !Number.isSafeInteger(gy))
4044
4144
  throw new Error("Mixed halo lattice overflow");
4045
- for (const candidate of sources) {
4046
- if (++tests > maxTests)
4047
- throw new Error("Mixed halo tile-test budget exceeded");
4145
+ for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
4146
+ const candidate = candidates[candidateIndex];
4147
+ charge();
4048
4148
  const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
4049
4149
  const f = candidate.source;
4050
4150
  if (cx < 0 || cy < 0 || cx > f.width - 1 || cy > f.height - 1)
@@ -4086,39 +4186,169 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets) {
4086
4186
  })
4087
4187
  };
4088
4188
  }
4189
+ function prepareMixedHaloTile(tile) {
4190
+ const { column, row, spacing } = tile;
4191
+ if (![column, row, spacing].every(Number.isSafeInteger) || spacing < 1 || 2 ** Math.round(Math.log2(spacing)) !== spacing)
4192
+ throw new Error("Invalid mixed halo lattice");
4193
+ const source = new HeightField(tile.field);
4194
+ if (source.registration !== "vertex")
4195
+ throw new Error("Mixed halos require vertex registration");
4196
+ const columnStep = source.columnStep.map((v) => v / spacing);
4197
+ const rowStep = source.rowStep.map((v) => v / spacing);
4198
+ const frameOrigin = source.origin.map((v, i) => v - column * columnStep[i] - row * rowStep[i]);
4199
+ const scale = source.origin.map((v, i) => Math.max(1, Math.abs(v), Math.abs(column * columnStep[i]), Math.abs(row * rowStep[i])));
4200
+ if (!frameOrigin.every(Number.isFinite))
4201
+ throw new Error("Mixed halo coordinate overflow");
4202
+ const minX = column - spacing, minY = row - spacing;
4203
+ const maxX = column + source.width * spacing, maxY = row + source.height * spacing;
4204
+ if (![minX, minY, maxX, maxY].every(Number.isSafeInteger))
4205
+ throw new Error("Mixed halo lattice overflow");
4206
+ const key2 = `${spacing}/${column}/${row}`;
4207
+ return {
4208
+ ...tile,
4209
+ source,
4210
+ columnStep,
4211
+ rowStep,
4212
+ frameOrigin,
4213
+ scale,
4214
+ key: key2,
4215
+ layoutKey: `${key2}/${source.width}/${source.height}`,
4216
+ haloBounds: { minX, minY, maxX, maxY }
4217
+ };
4218
+ }
4089
4219
 
4090
4220
  // dist/terrain/mixed-halo-update.js
4091
4221
  var key = (t) => `${t.spacing}/${t.column}/${t.row}`;
4222
+ var bounds = (tile, padding = 0) => ({
4223
+ minX: tile.column - padding,
4224
+ minY: tile.row - padding,
4225
+ maxX: tile.column + (tile.field.width - 1) * tile.spacing + padding,
4226
+ maxY: tile.row + (tile.field.height - 1) * tile.spacing + padding
4227
+ });
4228
+ var preparations = /* @__PURE__ */ new WeakMap();
4229
+ var targetIndexes = /* @__PURE__ */ new WeakMap();
4230
+ function editedBounds(old, next) {
4231
+ const a = old.field;
4232
+ const b = next.field;
4233
+ if (a.width !== b.width || a.height !== b.height || (a.diagonal ?? "00-11") !== (b.diagonal ?? "00-11"))
4234
+ return bounds(next);
4235
+ const sample = (field, x, y) => {
4236
+ const i = (field.offset ?? 0) + y * (field.stride ?? field.width) + x;
4237
+ const z = field.heights[i];
4238
+ return Number.isFinite(z) && (field.validity === void 0 || field.validity[i] !== 0) ? z : void 0;
4239
+ };
4240
+ let left = b.width, right = -1, top = b.height, bottom = -1;
4241
+ for (let y = 0; y < b.height; y++) {
4242
+ for (let x = 0; x < b.width; x++) {
4243
+ if (Object.is(sample(a, x, y), sample(b, x, y)))
4244
+ continue;
4245
+ left = Math.min(left, x);
4246
+ right = Math.max(right, x);
4247
+ top = Math.min(top, y);
4248
+ bottom = Math.max(bottom, y);
4249
+ }
4250
+ }
4251
+ if (right < 0)
4252
+ return null;
4253
+ return {
4254
+ minX: next.column + Math.max(0, left - 1) * next.spacing,
4255
+ maxX: next.column + Math.min(b.width - 1, right + 1) * next.spacing,
4256
+ minY: next.row + Math.max(0, top - 1) * next.spacing,
4257
+ maxY: next.row + Math.min(b.height - 1, bottom + 1) * next.spacing
4258
+ };
4259
+ }
4092
4260
  function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4093
4261
  const budget = options.maxDependencyTests ?? 1e7;
4094
4262
  if (!Number.isSafeInteger(budget) || budget < 0)
4095
4263
  throw new Error("Invalid mixed halo dependency budget");
4096
- const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4097
- const current = new Map(resident.map((t) => [key(t), t]));
4098
- const changed = [...old.values()].filter((t) => current.get(key(t)) !== t).concat(resident.filter((t) => old.get(key(t)) !== t));
4099
- const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key(t), t]));
4264
+ const unchangedLayout = (previous == null ? void 0 : previous.sources.length) === resident.length && resident.every((tile, i) => {
4265
+ const prior = previous.sources[i];
4266
+ return prior === tile || prior.column === tile.column && prior.row === tile.row && prior.spacing === tile.spacing && prior.field.width === tile.field.width && prior.field.height === tile.field.height;
4267
+ });
4268
+ const old = unchangedLayout ? void 0 : new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4100
4269
  const targets = /* @__PURE__ */ new Set();
4270
+ const initialized = previous !== null && preparations.has(previous);
4271
+ if (!initialized) {
4272
+ const cached = new Set(previous == null ? void 0 : previous.tiles.map(key));
4273
+ for (const tile of resident) {
4274
+ const address = key(tile);
4275
+ if (!cached.has(address))
4276
+ targets.add(address);
4277
+ }
4278
+ }
4279
+ let index = unchangedLayout && previous ? targetIndexes.get(previous) : void 0;
4101
4280
  let tests = 0;
4102
- for (const tile of resident) {
4103
- if (!cached.has(key(tile)))
4104
- targets.add(key(tile));
4105
- for (const source of changed) {
4106
- if (++tests > budget)
4107
- throw new Error("Mixed halo dependency budget exceeded");
4108
- if (tile.column - tile.spacing <= source.column + (source.field.width - 1) * source.spacing && tile.column + tile.field.width * tile.spacing >= source.column && tile.row - tile.spacing <= source.row + (source.field.height - 1) * source.spacing && tile.row + tile.field.height * tile.spacing >= source.row)
4109
- targets.add(key(tile));
4110
- }
4111
- }
4112
- const built = buildMixedVertexTileHalos(resident, options, targets).tiles;
4113
- for (const tile of built)
4114
- cached.set(key(tile), tile);
4115
- const tiles = resident.map((t) => cached.get(key(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
4116
- return {
4281
+ const charge = () => {
4282
+ if (++tests > budget)
4283
+ throw new Error("Mixed halo dependency budget exceeded");
4284
+ };
4285
+ function invalidate(box) {
4286
+ index ?? (index = createTerrainBoxIndex(resident.map((tile) => bounds(tile, tile.spacing))));
4287
+ for (const id of index(box, charge))
4288
+ targets.add(key(resident[id]));
4289
+ }
4290
+ for (let i = 0; i < resident.length; i++) {
4291
+ const tile = resident[i];
4292
+ const prior = unchangedLayout ? previous.sources[i] : old == null ? void 0 : old.get(key(tile));
4293
+ if (prior === tile)
4294
+ continue;
4295
+ targets.add(key(tile));
4296
+ if (!previous)
4297
+ continue;
4298
+ if (!prior) {
4299
+ invalidate(bounds(tile));
4300
+ } else if (prior.field.width !== tile.field.width || prior.field.height !== tile.field.height) {
4301
+ invalidate(bounds(prior));
4302
+ invalidate(bounds(tile));
4303
+ } else {
4304
+ const dirty = editedBounds(prior, tile);
4305
+ if (dirty)
4306
+ invalidate(dirty);
4307
+ }
4308
+ }
4309
+ const removed = [];
4310
+ if (old == null ? void 0 : old.size) {
4311
+ const current = new Set(resident.map(key));
4312
+ for (const [address, tile] of old) {
4313
+ if (current.has(address))
4314
+ continue;
4315
+ removed.push(address);
4316
+ if (resident.length)
4317
+ invalidate(bounds(tile));
4318
+ }
4319
+ }
4320
+ const priorPreparation = previous && preparations.get(previous);
4321
+ const preparation = {
4322
+ tiles: (priorPreparation == null ? void 0 : priorPreparation.tiles) ?? /* @__PURE__ */ new WeakMap(),
4323
+ layout: priorPreparation == null ? void 0 : priorPreparation.layout
4324
+ };
4325
+ const built = buildMixedVertexTileHalos(resident, options, targets, preparation).tiles;
4326
+ let tiles;
4327
+ if (unchangedLayout && initialized) {
4328
+ let cursor = 0;
4329
+ tiles = previous.tiles.map((tile) => {
4330
+ const replacement = built[cursor];
4331
+ if ((replacement == null ? void 0 : replacement.spacing) !== tile.spacing || replacement.column !== tile.column || replacement.row !== tile.row)
4332
+ return tile;
4333
+ cursor++;
4334
+ return replacement;
4335
+ });
4336
+ } else {
4337
+ const cached = new Map(previous == null ? void 0 : previous.tiles.map((tile) => [key(tile), tile]));
4338
+ for (const tile of built)
4339
+ cached.set(key(tile), tile);
4340
+ tiles = resident.map((tile) => cached.get(key(tile))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
4341
+ }
4342
+ const snapshot = {
4117
4343
  sources: resident.slice(),
4118
4344
  tiles,
4119
4345
  rebuilt: built.map(key),
4120
- removed: [...old.keys()].filter((k) => !current.has(k)).sort()
4346
+ removed: removed.sort()
4121
4347
  };
4348
+ preparations.set(snapshot, preparation);
4349
+ if (index)
4350
+ targetIndexes.set(snapshot, index);
4351
+ return snapshot;
4122
4352
  }
4123
4353
 
4124
4354
  // dist/terrain/mixed-gradient-update.js
@@ -4140,46 +4370,6 @@ function updateTerrainMixedGradientGrids(previous, halos, options = {}) {
4140
4370
  };
4141
4371
  }
4142
4372
 
4143
- // dist/terrain/box-index.js
4144
- var overlaps = (a, b) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
4145
- function createTerrainBoxIndex(boxes) {
4146
- const build = (ids) => {
4147
- const box = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
4148
- for (const id of ids) {
4149
- const b = boxes[id];
4150
- box.minX = Math.min(box.minX, b.minX);
4151
- box.minY = Math.min(box.minY, b.minY);
4152
- box.maxX = Math.max(box.maxX, b.maxX);
4153
- box.maxY = Math.max(box.maxY, b.maxY);
4154
- }
4155
- if (ids.length <= 8)
4156
- return { ...box, ids };
4157
- const axis = box.maxX - box.minX >= box.maxY - box.minY ? "X" : "Y";
4158
- ids.sort((a, b) => boxes[a][`min${axis}`] / 2 + boxes[a][`max${axis}`] / 2 - (boxes[b][`min${axis}`] / 2 + boxes[b][`max${axis}`] / 2) || a - b);
4159
- const mid = ids.length >>> 1;
4160
- return { ...box, left: build(ids.slice(0, mid)), right: build(ids.slice(mid)) };
4161
- };
4162
- const root = build(boxes.map((_, i) => i));
4163
- return (query, charge) => {
4164
- const found = [], stack = [root];
4165
- while (stack.length) {
4166
- charge();
4167
- const node = stack.pop();
4168
- if (!overlaps(node, query))
4169
- continue;
4170
- if (node.ids) {
4171
- for (const id of node.ids) {
4172
- charge();
4173
- if (overlaps(boxes[id], query))
4174
- found.push(id);
4175
- }
4176
- } else
4177
- stack.push(node.right, node.left);
4178
- }
4179
- return found.sort((a, b) => a - b);
4180
- };
4181
- }
4182
-
4183
4373
  // dist/terrain/contour-topology.js
4184
4374
  var bits = new DataView(new ArrayBuffer(8));
4185
4375
  function integer(x) {
@@ -4212,24 +4402,24 @@ function simplifyTerrainContourPathsTopology(paths, options) {
4212
4402
  const points = new Array(paths.positions.length / 3);
4213
4403
  for (const i of new Set(paths.indices))
4214
4404
  points[i] = { x: integer(paths.positions[3 * i]), y: integer(paths.positions[3 * i + 1]) };
4215
- const edges = [];
4405
+ const edges2 = [];
4216
4406
  for (let p = 0; p < paths.closed.length; p++)
4217
4407
  for (let i = paths.offsets[p]; i + 1 < paths.offsets[p + 1]; i++)
4218
- edges.push({ a: paths.indices[i], b: paths.indices[i + 1], p, i });
4408
+ edges2.push({ a: paths.indices[i], b: paths.indices[i + 1], p, i });
4219
4409
  const box = (a, b) => ({
4220
4410
  minX: Math.min(paths.positions[3 * a], paths.positions[3 * b]),
4221
4411
  maxX: Math.max(paths.positions[3 * a], paths.positions[3 * b]),
4222
4412
  minY: Math.min(paths.positions[3 * a + 1], paths.positions[3 * b + 1]),
4223
4413
  maxY: Math.max(paths.positions[3 * a + 1], paths.positions[3 * b + 1])
4224
4414
  });
4225
- const edgeBoxes = edges.map((e) => box(e.a, e.b)), edgeIndex = createTerrainBoxIndex(edgeBoxes);
4415
+ const edgeBoxes = edges2.map((e) => box(e.a, e.b)), edgeIndex = createTerrainBoxIndex(edgeBoxes);
4226
4416
  const vertexIds = [...new Set(paths.indices)], vertexIndex = createTerrainBoxIndex(vertexIds.map((v) => box(v, v)));
4227
- for (let i = 0; i < edges.length; i++)
4417
+ for (let i = 0; i < edges2.length; i++)
4228
4418
  for (const j of edgeIndex(edgeBoxes[i], charge)) {
4229
4419
  if (j <= i)
4230
4420
  continue;
4231
4421
  charge();
4232
- const a = edges[i], b = edges[j];
4422
+ const a = edges2[i], b = edges2[j];
4233
4423
  const common = [a.a, a.b].filter((v) => v === b.a || v === b.b);
4234
4424
  if (common.length === 1) {
4235
4425
  const v = common[0], x = a.a === v ? a.b : a.a, y = b.a === v ? b.b : b.a;
@@ -4262,19 +4452,19 @@ function simplifyTerrainContourPathsTopology(paths, options) {
4262
4452
  const interior = new Set(Array.from(paths.indices.subarray(start + 1, end)));
4263
4453
  let unsafe = false;
4264
4454
  for (const edgeId of edgeIndex(box(a, b), charge)) {
4265
- const edge = edges[edgeId];
4266
- if (edge.p === p && edge.i >= start && edge.i < end) {
4455
+ const edge2 = edges2[edgeId];
4456
+ if (edge2.p === p && edge2.i >= start && edge2.i < end) {
4267
4457
  if (straight)
4268
4458
  continue;
4269
4459
  charge();
4270
- const others2 = [edge.a, edge.b].filter((v) => v !== a && v !== b);
4271
- if (others2.some((v) => on(points[a], points[b], points[v])) || others2.length === 2 && intersects(points[a], points[b], points[edge.a], points[edge.b]))
4460
+ const others2 = [edge2.a, edge2.b].filter((v) => v !== a && v !== b);
4461
+ if (others2.some((v) => on(points[a], points[b], points[v])) || others2.length === 2 && intersects(points[a], points[b], points[edge2.a], points[edge2.b]))
4272
4462
  unsafe = true;
4273
4463
  continue;
4274
4464
  }
4275
4465
  charge();
4276
- const others = [edge.a, edge.b].filter((v) => v !== a && v !== b);
4277
- if (others.some((v) => on(points[a], points[b], points[v])) || others.length === 2 && intersects(points[a], points[b], points[edge.a], points[edge.b]))
4466
+ const others = [edge2.a, edge2.b].filter((v) => v !== a && v !== b);
4467
+ if (others.some((v) => on(points[a], points[b], points[v])) || others.length === 2 && intersects(points[a], points[b], points[edge2.a], points[edge2.b]))
4278
4468
  unsafe = true;
4279
4469
  }
4280
4470
  const swept = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
@@ -4502,7 +4692,7 @@ function createTerrainIsobands(fields, levels, options = {}) {
4502
4692
  return out.filter((v, i) => v.key !== out[(i + 1) % out.length].key);
4503
4693
  };
4504
4694
  for (let band = 0; band + 1 < levels.length; band++) {
4505
- const edges = /* @__PURE__ */ new Map();
4695
+ const edges2 = /* @__PURE__ */ new Map();
4506
4696
  for (const fieldId of rangeIndex({ minX: levels[band], maxX: levels[band + 1], minY: 0, maxY: 0 }, charge))
4507
4697
  for (let y = 0; y < fields[fieldId].height - 1; y++)
4508
4698
  for (let x = 0; x < fields[fieldId].width - 1; x++) {
@@ -4558,38 +4748,38 @@ function createTerrainIsobands(fields, levels, options = {}) {
4558
4748
  if (++edgeCount > maxEdges)
4559
4749
  throw new Error("Isoband edge capacity exceeded");
4560
4750
  const key2 = `${a.key}>${b.key}`, reverse = `${b.key}>${a.key}`;
4561
- if (edges.has(reverse))
4562
- edges.delete(reverse);
4751
+ if (edges2.has(reverse))
4752
+ edges2.delete(reverse);
4563
4753
  else {
4564
- if (edges.has(key2))
4754
+ if (edges2.has(key2))
4565
4755
  throw new Error("Overlapping isoband tiles");
4566
- edges.set(key2, { a, b });
4756
+ edges2.set(key2, { a, b });
4567
4757
  }
4568
4758
  }
4569
4759
  }
4570
4760
  }
4571
4761
  const outgoing = /* @__PURE__ */ new Map();
4572
- for (const [key2, e] of edges) {
4762
+ for (const [key2, e] of edges2) {
4573
4763
  if (!outgoing.has(e.a.key))
4574
4764
  outgoing.set(e.a.key, /* @__PURE__ */ new Set());
4575
4765
  outgoing.get(e.a.key).add(key2);
4576
4766
  }
4577
- while (edges.size) {
4578
- const first = edges.values().next().value, ring = [];
4579
- let edge = first;
4767
+ while (edges2.size) {
4768
+ const first = edges2.values().next().value, ring = [];
4769
+ let edge2 = first;
4580
4770
  for (; ; ) {
4581
4771
  charge();
4582
- ring.push(edge.a);
4583
- edges.delete(`${edge.a.key}>${edge.b.key}`);
4584
- outgoing.get(edge.a.key).delete(`${edge.a.key}>${edge.b.key}`);
4585
- if (edge.b.key === first.a.key)
4772
+ ring.push(edge2.a);
4773
+ edges2.delete(`${edge2.a.key}>${edge2.b.key}`);
4774
+ outgoing.get(edge2.a.key).delete(`${edge2.a.key}>${edge2.b.key}`);
4775
+ if (edge2.b.key === first.a.key)
4586
4776
  break;
4587
- const choices = [...outgoing.get(edge.b.key) ?? []].map((k) => edges.get(k));
4777
+ const choices = [...outgoing.get(edge2.b.key) ?? []].map((k) => edges2.get(k));
4588
4778
  if (!choices.length)
4589
4779
  throw new Error("Open isoband boundary");
4590
- const angle = (e) => Math.atan2((edge.b.x - edge.a.x) * (e.b.y - e.a.y) - (edge.b.y - edge.a.y) * (e.b.x - e.a.x), (edge.b.x - edge.a.x) * (e.b.x - e.a.x) + (edge.b.y - edge.a.y) * (e.b.y - e.a.y));
4780
+ const angle = (e) => Math.atan2((edge2.b.x - edge2.a.x) * (e.b.y - e.a.y) - (edge2.b.y - edge2.a.y) * (e.b.x - e.a.x), (edge2.b.x - edge2.a.x) * (e.b.x - e.a.x) + (edge2.b.y - edge2.a.y) * (e.b.y - e.a.y));
4591
4781
  choices.sort((a, b) => angle(b) - angle(a) || a.b.key.localeCompare(b.b.key));
4592
- edge = choices[0];
4782
+ edge2 = choices[0];
4593
4783
  }
4594
4784
  rings.push(ring);
4595
4785
  bands.push(band);
@@ -4726,6 +4916,24 @@ function updateMeshRegions(previous, field, dirty, options, configuration, creat
4726
4916
  let count = 0, tests = 0;
4727
4917
  const regions = [], rebuilt = [];
4728
4918
  const reusable = previous && sameTerrainFrame(previous.field, field) && previous.cellsPerRegion === cells && previous.configuration === configuration;
4919
+ const affectedRegions = /* @__PURE__ */ new Set();
4920
+ const columns = Math.ceil((field.width - 1) / cells);
4921
+ const rows = Math.ceil((field.height - 1) / cells);
4922
+ if (reusable) {
4923
+ for (const window of dirty) {
4924
+ const firstColumn = Math.max(0, Math.ceil(window.minColumn / cells) - 1);
4925
+ const firstRow = Math.max(0, Math.ceil(window.minRow / cells) - 1);
4926
+ const lastColumn = Math.min(columns - 1, Math.floor(window.maxColumn / cells));
4927
+ const lastRow = Math.min(rows - 1, Math.floor(window.maxRow / cells));
4928
+ for (let y = firstRow; y <= lastRow; y++) {
4929
+ for (let x = firstColumn; x <= lastColumn; x++) {
4930
+ if (++tests > budget)
4931
+ throw new Error("Terrain mesh region work budget exceeded");
4932
+ affectedRegions.add(y * columns + x);
4933
+ }
4934
+ }
4935
+ }
4936
+ }
4729
4937
  const cache = new Map(previous == null ? void 0 : previous.regions.map((r) => [`${r.column},${r.row}`, r]));
4730
4938
  for (let row = 0; row < field.height - 1; row += cells)
4731
4939
  for (let column = 0; column < field.width - 1; column += cells) {
@@ -4733,13 +4941,7 @@ function updateMeshRegions(previous, field, dirty, options, configuration, creat
4733
4941
  count += width * height;
4734
4942
  if (!Number.isSafeInteger(count) || count > limit)
4735
4943
  throw new Error("Terrain mesh region sample capacity exceeded");
4736
- let affected = !reusable;
4737
- for (const w of reusable ? dirty : []) {
4738
- if (++tests > budget)
4739
- throw new Error("Terrain mesh region work budget exceeded");
4740
- if (w.minColumn <= column + width - 1 && w.maxColumn >= column && w.minRow <= row + height - 1 && w.maxRow >= row)
4741
- affected = true;
4742
- }
4944
+ const affected = !reusable || affectedRegions.has(row / cells * columns + column / cells);
4743
4945
  const old = cache.get(`${column},${row}`);
4744
4946
  if (!affected && old) {
4745
4947
  regions.push(old);
@@ -4819,7 +5021,7 @@ function updateTerrainBoundsRegions(previous, field, dirty, options = {}) {
4819
5021
  throw new Error("Invalid bounds region capacity");
4820
5022
  validateTerrainDirtyWindows(dirty, field.width, field.height);
4821
5023
  if (!previous || !sameTerrainFrame(previous.field, field)) {
4822
- const bounds = new HeightFieldMinMax(field), levels2 = Array.from({ length: bounds.levelCount }, (_, i) => bounds.copyLevel(i));
5024
+ const bounds2 = new HeightFieldMinMax(field), levels2 = Array.from({ length: bounds2.levelCount }, (_, i) => bounds2.copyLevel(i));
4823
5025
  return { field, levels: levels2, updatedCounts: Uint32Array.from(levels2, (l) => l.width * l.height) };
4824
5026
  }
4825
5027
  let tests = 0;
@@ -5080,8 +5282,8 @@ function updateTerrainPersistentBounds(previous, field, dirty, options = {}) {
5080
5282
  const { nodesPerBlock, charge } = persistentHierarchyOptions(options, field.width * field.height);
5081
5283
  validateTerrainDirtyWindows(dirty, field.width, field.height);
5082
5284
  if (!previous || !sameTerrainFrame(previous.field, field) || previous.levels[0].nodesPerBlock !== nodesPerBlock) {
5083
- const bounds = new HeightFieldMinMax(field), levels = Array.from({ length: bounds.levelCount }, (_, i) => {
5084
- const l = bounds.copyLevel(i), values = new Float64Array(2 * l.width * l.height), counts = new Uint32Array(values.length);
5285
+ const bounds2 = new HeightFieldMinMax(field), levels = Array.from({ length: bounds2.levelCount }, (_, i) => {
5286
+ const l = bounds2.copyLevel(i), values = new Float64Array(2 * l.width * l.height), counts = new Uint32Array(values.length);
5085
5287
  for (let j = 0; j < l.width * l.height; j++) {
5086
5288
  values[2 * j] = l.minimums[j];
5087
5289
  values[2 * j + 1] = l.maximums[j];
@@ -5429,4 +5631,2747 @@ function createTerrainMixedIsobands(tiles, levels, options = {}) {
5429
5631
  sharedSamples: surface.sharedSamples
5430
5632
  };
5431
5633
  }
5634
+
5635
+ // dist/terrain/valid-domain-mesh.js
5636
+ var import_cdt2d = __toESM(require("cdt2d"), 1);
5637
+ function capacity(value) {
5638
+ if (!Number.isSafeInteger(value) || value < 1)
5639
+ throw new Error("Invalid mesh work limit");
5640
+ return value;
5641
+ }
5642
+ function createValidDomainTerrainMesh(field, options) {
5643
+ return meshValidDomain(field, options);
5644
+ }
5645
+ function meshValidDomain(field, options, constraints) {
5646
+ const { maxError } = options;
5647
+ const count = field.width * field.height;
5648
+ if (!Number.isFinite(maxError) || maxError < 0)
5649
+ throw new Error("Invalid maximum error");
5650
+ if (count > capacity(options.maxSamples ?? 11e5))
5651
+ throw new Error("Sample limit exceeded");
5652
+ const maxTriangles = capacity(options.maxTriangles ?? 22e5);
5653
+ const maxTests = capacity(options.maxSampleTests ?? 4e7);
5654
+ const regular = createTerrainMesh(field, options);
5655
+ const { width, height, origin, heightReference } = regular;
5656
+ const active = new Uint8Array(count);
5657
+ const boundary = /* @__PURE__ */ new Map();
5658
+ const edgeKey3 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
5659
+ for (let i = 0; i < regular.indices.length; i += 3) {
5660
+ for (let j = 0; j < 3; j++) {
5661
+ const a = regular.indices[i + j], b = regular.indices[i + (j + 1) % 3];
5662
+ active[a] = 1;
5663
+ const key2 = edgeKey3(a, b);
5664
+ if (!boundary.delete(key2))
5665
+ boundary.set(key2, [a, b]);
5666
+ }
5667
+ }
5668
+ const selected = new Int32Array(count).fill(-1);
5669
+ const points = [];
5670
+ const heights = [];
5671
+ const add2 = (i) => {
5672
+ if (selected[i] < 0) {
5673
+ selected[i] = points.length;
5674
+ points.push([i % width, Math.floor(i / width)]);
5675
+ heights.push(regular.positions[3 * i + 2]);
5676
+ }
5677
+ return selected[i];
5678
+ };
5679
+ const edges2 = Array.from(boundary.values(), ([a, b]) => [add2(a), add2(b)]);
5680
+ const extra = constraints == null ? void 0 : constraints(points, heights, edges2, selected, origin[2]);
5681
+ const inDomain = ([a, b, c]) => {
5682
+ const x = (points[a][0] + points[b][0] + points[c][0]) / 3;
5683
+ const y = (points[a][1] + points[b][1] + points[c][1]) / 3;
5684
+ const i = Math.floor(x), j = Math.floor(y);
5685
+ const u = x - i, v = y - j;
5686
+ const valid = (dx, dy) => field.getHeight(i + dx, j + dy) !== void 0;
5687
+ if (field.diagonal === "00-11") {
5688
+ return valid(0, 0) && valid(1, 1) && (u > v ? valid(1, 0) : valid(0, 1));
5689
+ }
5690
+ return valid(1, 0) && valid(0, 1) && (u + v < 1 ? valid(0, 0) : valid(1, 1));
5691
+ };
5692
+ const covered = new Uint8Array(count);
5693
+ let triangles = [];
5694
+ let maxSampleError = 0;
5695
+ let certifiedSamples = 0;
5696
+ let tests = 0;
5697
+ for (let pass = 0; points.length; pass++) {
5698
+ triangles = (0, import_cdt2d.default)(points, (extra == null ? void 0 : extra.edges) ?? edges2, {
5699
+ exterior: Boolean(extra),
5700
+ delaunay: false
5701
+ });
5702
+ if (extra)
5703
+ triangles = triangles.filter(inDomain);
5704
+ if (triangles.length > maxTriangles)
5705
+ throw new Error("Triangle limit exceeded");
5706
+ covered.fill(0);
5707
+ const refine = /* @__PURE__ */ new Set();
5708
+ maxSampleError = 0;
5709
+ certifiedSamples = 0;
5710
+ for (const [a, b, c] of triangles) {
5711
+ const [ax, ay] = points[a], [bx, by] = points[b], [cx, cy] = points[c];
5712
+ const det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
5713
+ if (det === 0)
5714
+ throw new Error("Degenerate triangulation");
5715
+ let worst = maxError;
5716
+ let candidate = -1;
5717
+ const sides = [
5718
+ [ax, ay, bx, by],
5719
+ [bx, by, cx, cy],
5720
+ [cx, cy, ax, ay]
5721
+ ];
5722
+ for (let y = Math.ceil(Math.min(ay, by, cy)); y <= Math.floor(Math.max(ay, by, cy)); y++) {
5723
+ let left = Infinity;
5724
+ let right = -Infinity;
5725
+ for (const [x0, y0, x1, y1] of sides) {
5726
+ if (y < Math.min(y0, y1) || y > Math.max(y0, y1))
5727
+ continue;
5728
+ const x = y0 === y1 ? x0 : x0 + (x1 - x0) * (y - y0) / (y1 - y0);
5729
+ left = Math.min(left, x);
5730
+ right = Math.max(right, y0 === y1 ? Math.max(x0, x1) : x);
5731
+ if (y0 === y1)
5732
+ left = Math.min(left, x1);
5733
+ }
5734
+ for (let x = Math.ceil(left - 1e-10); x <= Math.floor(right + 1e-10); x++) {
5735
+ if (++tests > maxTests)
5736
+ throw new Error("Sample test limit exceeded");
5737
+ const i = y * width + x;
5738
+ if (!active[i] || (extra == null ? void 0 : extra.excluded.has(i)))
5739
+ continue;
5740
+ const u = ((x - ax) * (cy - ay) - (y - ay) * (cx - ax)) / det;
5741
+ const v = ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) / det;
5742
+ const w = 1 - u - v;
5743
+ if (Math.min(u, v, w) < -1e-12)
5744
+ continue;
5745
+ if (!covered[i])
5746
+ certifiedSamples++;
5747
+ covered[i] = 1;
5748
+ const error = !extra && (selected[i] === a || selected[i] === b || selected[i] === c) ? 0 : Math.abs(w * heights[a] + u * heights[b] + v * heights[c] - regular.positions[3 * i + 2]);
5749
+ maxSampleError = Math.max(maxSampleError, error);
5750
+ if (error > worst && !(extra == null ? void 0 : extra.fixedSamples.has(i))) {
5751
+ worst = error;
5752
+ candidate = i;
5753
+ }
5754
+ }
5755
+ }
5756
+ if (candidate >= 0)
5757
+ refine.add(candidate);
5758
+ }
5759
+ if (active.some((value, i) => value && !covered[i] && !(extra == null ? void 0 : extra.excluded.has(i))))
5760
+ throw new Error("Incomplete domain triangulation");
5761
+ if (maxSampleError <= maxError)
5762
+ break;
5763
+ if (!Array.from(refine).some((i) => selected[i] < 0))
5764
+ throw new Error("Cannot certify mesh tolerance");
5765
+ if (pass === 63) {
5766
+ for (let i = 0; i < count; i++)
5767
+ if (active[i] && !(extra == null ? void 0 : extra.fixedSamples.has(i)))
5768
+ add2(i);
5769
+ } else {
5770
+ for (const i of refine)
5771
+ add2(i);
5772
+ }
5773
+ }
5774
+ const reverse = field.columnStep[0] * field.rowStep[1] - field.columnStep[1] * field.rowStep[0] < 0;
5775
+ const positions = new Float64Array(points.length * 3);
5776
+ const shift = field.registration === "cell" ? 0.5 : 0;
5777
+ for (let i = 0; i < points.length; i++) {
5778
+ const [x, y] = points[i];
5779
+ positions.set([
5780
+ field.origin[0] - origin[0] + (x + shift) * field.columnStep[0] + (y + shift) * field.rowStep[0],
5781
+ field.origin[1] - origin[1] + (x + shift) * field.columnStep[1] + (y + shift) * field.rowStep[1],
5782
+ heights[i]
5783
+ ], i * 3);
5784
+ }
5785
+ const indices = new Uint32Array(triangles.length * 3);
5786
+ for (let i = 0; i < triangles.length; i++) {
5787
+ const [a, b, c] = triangles[i];
5788
+ const [ax, ay] = points[a], [bx, by] = points[b], [cx, cy] = points[c];
5789
+ const clockwise = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) < 0;
5790
+ indices.set(reverse === clockwise ? [a, b, c] : [a, c, b], 3 * i);
5791
+ }
5792
+ return {
5793
+ positions,
5794
+ indices,
5795
+ gridCoordinates: Float64Array.from(points.flat()),
5796
+ origin,
5797
+ width,
5798
+ height,
5799
+ heightReference,
5800
+ maxSampleError,
5801
+ certifiedSamples
5802
+ };
5803
+ }
5804
+
5805
+ // dist/terrain/breakline-mesh.js
5806
+ var cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
5807
+ var onSegment = (a, b, p) => Math.abs(cross(a, b, p)) <= 8 * Number.EPSILON * (Math.abs((b[0] - a[0]) * (p[1] - a[1])) + Math.abs((b[1] - a[1]) * (p[0] - a[0]))) && p[0] >= Math.min(a[0], b[0]) && p[0] <= Math.max(a[0], b[0]) && p[1] >= Math.min(a[1], b[1]) && p[1] <= Math.max(a[1], b[1]);
5808
+ function createBreaklineTerrainMesh(field, options) {
5809
+ const breaklineEdges = [];
5810
+ let overriddenSamples = 0;
5811
+ const mesh = meshValidDomain(field, options, (points, heights, boundary, selected, originZ) => {
5812
+ const ids = new Map(points.map(([x, y], i) => [`${x},${y}`, i]));
5813
+ const fixed = /* @__PURE__ */ new Map();
5814
+ const excluded = /* @__PURE__ */ new Set();
5815
+ const fixedSamples = /* @__PURE__ */ new Set();
5816
+ const add2 = ([x, y, z]) => {
5817
+ if (![x, y, z, z - originZ].every(Number.isFinite) || x < 0 || y < 0 || x > field.width - 1 || y > field.height - 1) {
5818
+ throw new Error("Breakline endpoint is outside the sample rectangle or nonfinite");
5819
+ }
5820
+ const key2 = `${x},${y}`;
5821
+ const id = ids.get(key2) ?? points.length;
5822
+ if (fixed.has(id) && fixed.get(id) !== z)
5823
+ throw new Error("Conflicting breakline heights");
5824
+ if (!ids.has(key2)) {
5825
+ points.push([x, y]);
5826
+ ids.set(key2, id);
5827
+ }
5828
+ fixed.set(id, z);
5829
+ heights[id] = z - originZ;
5830
+ if (Number.isInteger(x) && Number.isInteger(y))
5831
+ selected[y * field.width + x] = id;
5832
+ return id;
5833
+ };
5834
+ if (options.breaklines.length > 2048)
5835
+ throw new Error("Breakline limit exceeded");
5836
+ for (const [a, b] of options.breaklines) {
5837
+ const p = add2(a), q = add2(b);
5838
+ if (p === q)
5839
+ throw new Error("Zero-length breakline");
5840
+ breaklineEdges.push([p, q]);
5841
+ }
5842
+ const edges3 = [];
5843
+ for (const [a, b] of boundary) {
5844
+ const split = [
5845
+ a,
5846
+ ...Array.from(fixed.keys()).filter((id) => id !== a && id !== b && onSegment(points[a], points[b], points[id])),
5847
+ b
5848
+ ];
5849
+ const [x, y] = points[a];
5850
+ split.sort((i, j) => Math.hypot(points[i][0] - x, points[i][1] - y) - Math.hypot(points[j][0] - x, points[j][1] - y));
5851
+ for (let i = 1; i < split.length; i++)
5852
+ edges3.push([split[i - 1], split[i]]);
5853
+ }
5854
+ const seen = /* @__PURE__ */ new Set();
5855
+ for (const [a, b] of breaklineEdges) {
5856
+ const key2 = `${Math.min(a, b)},${Math.max(a, b)}`;
5857
+ if (seen.has(key2))
5858
+ throw new Error("Duplicate breakline");
5859
+ seen.add(key2);
5860
+ const p = points[a], q = points[b];
5861
+ let coincident = false;
5862
+ for (const [c, d] of edges3) {
5863
+ if (a === c && b === d || a === d && b === c) {
5864
+ coincident = true;
5865
+ continue;
5866
+ }
5867
+ const r = points[c], s = points[d];
5868
+ const intersects3 = Math.sign(cross(p, q, r)) * Math.sign(cross(p, q, s)) < 0 && Math.sign(cross(r, s, p)) * Math.sign(cross(r, s, q)) < 0;
5869
+ if (intersects3 || c !== a && c !== b && onSegment(p, q, r) || d !== a && d !== b && onSegment(p, q, s) || a !== c && a !== d && onSegment(r, s, p) || b !== c && b !== d && onSegment(r, s, q)) {
5870
+ throw new Error("Breaklines and domain edges must meet only at shared endpoints");
5871
+ }
5872
+ }
5873
+ if (!coincident)
5874
+ edges3.push([a, b]);
5875
+ for (let y = Math.ceil(Math.min(p[1], q[1])); y <= Math.floor(Math.max(p[1], q[1])); y++) {
5876
+ for (let x = Math.ceil(Math.min(p[0], q[0])); x <= Math.floor(Math.max(p[0], q[0])); x++) {
5877
+ const source = field.getHeight(x, y);
5878
+ if (source === void 0 || !onSegment(p, q, [x, y]))
5879
+ continue;
5880
+ fixedSamples.add(y * field.width + x);
5881
+ const dx = q[0] - p[0], dy = q[1] - p[1];
5882
+ const f = Math.abs(dx) >= Math.abs(dy) ? (x - p[0]) / dx : (y - p[1]) / dy;
5883
+ const z = (1 - f) * heights[a] + f * heights[b] + originZ;
5884
+ if (Math.abs(source - z) <= options.maxError)
5885
+ continue;
5886
+ if (!options.breaklinesOverrideSamples)
5887
+ throw new Error("Breakline conflicts with source tolerance");
5888
+ excluded.add(y * field.width + x);
5889
+ }
5890
+ }
5891
+ }
5892
+ overriddenSamples = excluded.size;
5893
+ return { edges: edges3, excluded, fixedSamples };
5894
+ });
5895
+ const edges2 = /* @__PURE__ */ new Set();
5896
+ for (let i = 0; i < mesh.indices.length; i += 3) {
5897
+ for (let j = 0; j < 3; j++) {
5898
+ const a = mesh.indices[i + j], b = mesh.indices[i + (j + 1) % 3];
5899
+ edges2.add(`${Math.min(a, b)},${Math.max(a, b)}`);
5900
+ }
5901
+ }
5902
+ if (breaklineEdges.some(([a, b]) => !edges2.has(`${Math.min(a, b)},${Math.max(a, b)}`))) {
5903
+ throw new Error("Breakline was not preserved inside the valid terrain domain");
5904
+ }
5905
+ return { ...mesh, breaklineEdges: Uint32Array.from(breaklineEdges.flat()), overriddenSamples };
5906
+ }
5907
+
5908
+ // dist/terrain/continuous-mesh-error.js
5909
+ var exact = (x) => [x, x];
5910
+ function outward(lo, hi) {
5911
+ if (!Number.isFinite(lo) || !Number.isFinite(hi))
5912
+ throw new Error("Continuous error arithmetic overflow");
5913
+ const result = [
5914
+ lo - Math.max(Number.MIN_VALUE, Math.abs(lo) * Number.EPSILON),
5915
+ hi + Math.max(Number.MIN_VALUE, Math.abs(hi) * Number.EPSILON)
5916
+ ];
5917
+ if (!result.every(Number.isFinite))
5918
+ throw new Error("Continuous error arithmetic overflow");
5919
+ return result;
5920
+ }
5921
+ var add = (a, b) => outward(a[0] + b[0], a[1] + b[1]);
5922
+ var sub = (a, b) => outward(a[0] - b[1], a[1] - b[0]);
5923
+ function mul(a, b) {
5924
+ const values = [a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1]];
5925
+ return outward(Math.min(...values), Math.max(...values));
5926
+ }
5927
+ function div(a, b) {
5928
+ if (b[0] <= 0 && b[1] >= 0)
5929
+ throw new Error("Degenerate or numerically unresolved mesh triangle");
5930
+ return mul(a, outward(1 / b[1], 1 / b[0]));
5931
+ }
5932
+ var magnitude = (a) => Math.max(-a[0], a[1]);
5933
+ var minimumMagnitude = (a) => Math.max(0, a[0], -a[1]);
5934
+ var evaluate = (p, x, y) => add(p[0], add(mul(p[1], x), mul(p[2], y)));
5935
+ function edge(a, b, column, row) {
5936
+ const dx = sub(exact(b[0]), exact(a[0]));
5937
+ const dy = sub(exact(b[1]), exact(a[1]));
5938
+ return [
5939
+ sub(mul(dx, sub(exact(row), exact(a[1]))), mul(dy, sub(exact(column), exact(a[0])))),
5940
+ [-dy[1], -dy[0]],
5941
+ dx
5942
+ ];
5943
+ }
5944
+ function polygon(triangle, column, row) {
5945
+ const [a, b, c] = triangle;
5946
+ const first = edge(a, b, a[0], a[1]);
5947
+ const orientation2 = evaluate(first, sub(exact(c[0]), exact(a[0])), sub(exact(c[1]), exact(a[1])));
5948
+ if (orientation2[0] <= 0 && orientation2[1] >= 0)
5949
+ throw new Error("Degenerate or numerically unresolved mesh triangle");
5950
+ const sides = [edge(a, b, column, row), edge(b, c, column, row), edge(c, a, column, row)];
5951
+ return orientation2[0] > 0 ? sides : sides.map((p) => p.map(([lo, hi]) => [-hi, -lo]));
5952
+ }
5953
+ function boundTerrainMeshError(field, mesh, options = {}) {
5954
+ const { reference = "triangle", gap = 0.05, maxBoxes = 2e6, maxDepth = 12 } = options;
5955
+ const { gridCoordinates: xy, positions, indices, origin } = mesh;
5956
+ if (!["triangle", "bilinear"].includes(reference) || !Number.isFinite(gap) || gap < 0 || !Number.isSafeInteger(maxBoxes) || maxBoxes < 1 || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > 24)
5957
+ throw new Error("Invalid continuous error options");
5958
+ if (mesh.heightReference !== field.heightReference || !Number.isFinite(origin[2]) || positions.length % 3 || xy.length !== positions.length / 3 * 2 || indices.length % 3)
5959
+ throw new Error("Invalid continuous error mesh buffers or height reference");
5960
+ let upperBound = null;
5961
+ let lowerBound = 0;
5962
+ let witness = null;
5963
+ let boxes = 0;
5964
+ for (let i = 0; i < indices.length; i += 3) {
5965
+ const ids = [indices[i], indices[i + 1], indices[i + 2]];
5966
+ if (ids.some((id) => !Number.isSafeInteger(id) || id < 0 || id >= xy.length / 2)) {
5967
+ throw new Error("Invalid continuous error index");
5968
+ }
5969
+ const triangle = [
5970
+ [xy[2 * ids[0]], xy[2 * ids[0] + 1]],
5971
+ [xy[2 * ids[1]], xy[2 * ids[1] + 1]],
5972
+ [xy[2 * ids[2]], xy[2 * ids[2] + 1]]
5973
+ ];
5974
+ const [a, b, c] = triangle;
5975
+ const [za, zb, zc] = ids.map((id) => exact(positions[3 * id + 2]));
5976
+ if (triangle.some(([x, y]) => !Number.isFinite(x) || !Number.isFinite(y)) || [za, zb, zc].some((z) => !Number.isFinite(z[0])))
5977
+ throw new Error("Nonfinite continuous error vertex");
5978
+ if (reference === "triangle" && origin[2] === 0 && matchesReferenceHalf(field, triangle, [za[0], zb[0], zc[0]])) {
5979
+ if (++boxes > maxBoxes)
5980
+ throw new Error("Continuous error box limit exceeded");
5981
+ upperBound ?? (upperBound = 0);
5982
+ witness ?? (witness = a);
5983
+ continue;
5984
+ }
5985
+ const dx = sub(exact(b[0]), exact(a[0])), dy = sub(exact(b[1]), exact(a[1]));
5986
+ const ex = sub(exact(c[0]), exact(a[0])), ey = sub(exact(c[1]), exact(a[1]));
5987
+ const det = sub(mul(dx, ey), mul(dy, ex));
5988
+ const dz = sub(zb, za), ez = sub(zc, za);
5989
+ const sx = div(sub(mul(dz, ey), mul(ez, dy)), det);
5990
+ const sy = div(sub(mul(dx, ez), mul(ex, dz)), det);
5991
+ for (let row = Math.max(0, Math.ceil(Math.min(a[1], b[1], c[1])) - 1); row <= Math.min(field.height - 2, Math.floor(Math.max(a[1], b[1], c[1]))); row++) {
5992
+ for (let column = Math.max(0, Math.ceil(Math.min(a[0], b[0], c[0])) - 1); column <= Math.min(field.width - 2, Math.floor(Math.max(a[0], b[0], c[0]))); column++) {
5993
+ let visit = function(constraints, p, mixed, x, y, depth) {
5994
+ if (++boxes > maxBoxes)
5995
+ throw new Error("Continuous error box limit exceeded");
5996
+ if (constraints.some((side) => evaluate(side, x, y)[1] < 0))
5997
+ return;
5998
+ const error = (u2, v2) => add(evaluate(p, u2, v2), mul(mixed, mul(u2, v2)));
5999
+ const centerX = (x[0] + x[1]) / 2;
6000
+ const centerY = (y[0] + y[1]) / 2;
6001
+ const u = exact(centerX), v = exact(centerY);
6002
+ if (constraints.every((side) => evaluate(side, u, v)[0] >= 0)) {
6003
+ const lower = minimumMagnitude(error(u, v));
6004
+ if (!witness || lower > lowerBound) {
6005
+ lowerBound = lower;
6006
+ witness = [column + centerX, row + centerY];
6007
+ }
6008
+ }
6009
+ const upper = Math.max(...x.flatMap((u2) => y.map((v2) => magnitude(error(exact(u2), exact(v2))))));
6010
+ if (upper <= lowerBound + gap || depth === maxDepth) {
6011
+ upperBound = Math.max(upperBound ?? 0, upper);
6012
+ return;
6013
+ }
6014
+ if (x[1] - x[0] >= y[1] - y[0]) {
6015
+ visit(constraints, p, mixed, [x[0], centerX], y, depth + 1);
6016
+ visit(constraints, p, mixed, [centerX, x[1]], y, depth + 1);
6017
+ } else {
6018
+ visit(constraints, p, mixed, x, [y[0], centerY], depth + 1);
6019
+ visit(constraints, p, mixed, x, [centerY, y[1]], depth + 1);
6020
+ }
6021
+ };
6022
+ if (++boxes > maxBoxes)
6023
+ throw new Error("Continuous error box limit exceeded");
6024
+ const vertices = [
6025
+ [0, 0],
6026
+ [1, 0],
6027
+ [0, 1],
6028
+ [1, 1]
6029
+ ];
6030
+ const h = vertices.map(([x, y]) => field.getHeight(column + x, row + y));
6031
+ const sides = polygon(triangle, column, row);
6032
+ const base = add(za, add(mul(sx, sub(exact(column), exact(a[0]))), mul(sy, sub(exact(row), exact(a[1])))));
6033
+ const compare = (constant, x, y, mixed, constraints) => visit(constraints, [sub(base, sub(constant, exact(origin[2]))), sub(sx, x), sub(sy, y)], [-mixed[1], -mixed[0]], [0, 1], [0, 1], 0);
6034
+ if (reference === "bilinear") {
6035
+ const [h00, h10, h01, h11] = h;
6036
+ if (h00 === void 0 || h10 === void 0 || h01 === void 0 || h11 === void 0)
6037
+ continue;
6038
+ const x = sub(exact(h10), exact(h00)), y = sub(exact(h01), exact(h00));
6039
+ compare(exact(h00), x, y, sub(sub(exact(h11), exact(h01)), x), sides);
6040
+ } else {
6041
+ const halves = field.diagonal === "00-11" ? [
6042
+ [0, 1, 3],
6043
+ [0, 3, 2]
6044
+ ] : [
6045
+ [0, 1, 2],
6046
+ [1, 3, 2]
6047
+ ];
6048
+ for (const [j, k, l] of halves) {
6049
+ const z0 = h[j], z1 = h[k], z2 = h[l];
6050
+ if (z0 === void 0 || z1 === void 0 || z2 === void 0)
6051
+ continue;
6052
+ const p = vertices[j], q = vertices[k], r = vertices[l];
6053
+ const x = sub(mul(sub(exact(z1), exact(z0)), exact(r[1] - p[1])), mul(sub(exact(z2), exact(z0)), exact(q[1] - p[1])));
6054
+ const y = sub(mul(exact(q[0] - p[0]), sub(exact(z2), exact(z0))), mul(exact(r[0] - p[0]), sub(exact(z1), exact(z0))));
6055
+ compare(sub(exact(z0), add(mul(x, exact(p[0])), mul(y, exact(p[1])))), x, y, exact(0), [
6056
+ ...sides,
6057
+ ...polygon([p, q, r], 0, 0)
6058
+ ]);
6059
+ }
6060
+ }
6061
+ }
6062
+ }
6063
+ }
6064
+ return {
6065
+ upperBound,
6066
+ lowerBound,
6067
+ witness,
6068
+ boxes,
6069
+ converged: upperBound !== null && upperBound - lowerBound <= gap
6070
+ };
6071
+ }
6072
+ function matchesReferenceHalf(field, triangle, heights) {
6073
+ const column = Math.min(...triangle.map((p) => p[0]));
6074
+ const row = Math.min(...triangle.map((p) => p[1]));
6075
+ if (!Number.isInteger(column) || !Number.isInteger(row) || column < 0 || row < 0 || column >= field.width - 1 || row >= field.height - 1)
6076
+ return false;
6077
+ const corners = /* @__PURE__ */ new Set();
6078
+ for (let i = 0; i < 3; i++) {
6079
+ const [x, y] = triangle[i];
6080
+ const u = x - column, v = y - row;
6081
+ if (u !== 0 && u !== 1 || v !== 0 && v !== 1 || field.getHeight(x, y) !== heights[i])
6082
+ return false;
6083
+ corners.add(u + 2 * v);
6084
+ }
6085
+ return corners.size === 3 && (field.diagonal === "00-11" ? corners.has(0) && corners.has(3) : corners.has(1) && corners.has(2));
6086
+ }
6087
+
6088
+ // dist/terrain/geographic-seam.js
6089
+ function wrapTerrainLongitude(longitude, west, east) {
6090
+ if (![longitude, west, east].every(Number.isFinite) || east <= west || east - west > 360)
6091
+ throw new Error("Invalid terrain longitude interval or query");
6092
+ if (longitude >= west && longitude < east)
6093
+ return longitude;
6094
+ const delta = (longitude % 360 - west % 360) % 360;
6095
+ const offset = delta < 0 ? delta + 360 : delta;
6096
+ const mapped = west + offset;
6097
+ return mapped <= east ? mapped : void 0;
6098
+ }
6099
+ function measureGeographicTerrainSeam(a, b, probes, options = {}) {
6100
+ if (a && b && a.heightReference !== b.heightReference)
6101
+ throw new Error("Terrain seam height references differ");
6102
+ const sample = (field, longitude, latitude2) => {
6103
+ if (!field || !Number.isFinite(longitude))
6104
+ return field == null ? void 0 : field.sample(longitude, latitude2, options);
6105
+ const mapped = wrapTerrainLongitude(longitude, field.bounds[0], field.bounds[2]);
6106
+ return field.sample(mapped ?? longitude, latitude2, options);
6107
+ };
6108
+ return probes.map(([longitude, latitude2]) => {
6109
+ const left = sample(a, longitude, latitude2);
6110
+ const right = sample(b, longitude, latitude2);
6111
+ const valid = (left == null ? void 0 : left.status) === TerrainSampleStatus.VALID && (right == null ? void 0 : right.status) === TerrainSampleStatus.VALID;
6112
+ const derivatives = (left == null ? void 0 : left.gradientStatus) === TerrainSampleStatus.VALID && (right == null ? void 0 : right.gradientStatus) === TerrainSampleStatus.VALID;
6113
+ const normalAngle = derivatives ? Math.atan2(Math.hypot(left.normalY * right.normalZ - left.normalZ * right.normalY, left.normalZ * right.normalX - left.normalX * right.normalZ, left.normalX * right.normalY - left.normalY * right.normalX), left.normalX * right.normalX + left.normalY * right.normalY + left.normalZ * right.normalZ) : null;
6114
+ return {
6115
+ longitude,
6116
+ latitude: latitude2,
6117
+ statusA: (left == null ? void 0 : left.status) ?? TerrainSampleStatus.NOT_RESIDENT,
6118
+ statusB: (right == null ? void 0 : right.status) ?? TerrainSampleStatus.NOT_RESIDENT,
6119
+ gradientStatusA: (left == null ? void 0 : left.gradientStatus) ?? TerrainSampleStatus.NOT_RESIDENT,
6120
+ gradientStatusB: (right == null ? void 0 : right.gradientStatus) ?? TerrainSampleStatus.NOT_RESIDENT,
6121
+ heightJump: valid ? Math.abs(left.height - right.height) : null,
6122
+ normalAngle
6123
+ };
6124
+ });
6125
+ }
6126
+
6127
+ // dist/terrain/lod-screen-error.js
6128
+ function slack(value) {
6129
+ return Math.abs(value) * (2 * Number.EPSILON) + Number.MIN_VALUE;
6130
+ }
6131
+ function down(value) {
6132
+ return value - slack(value);
6133
+ }
6134
+ function up(value) {
6135
+ return value + slack(value);
6136
+ }
6137
+ function boundTerrainLodScreenError(bounds2, projection) {
6138
+ if (bounds2.min.length !== 3 || bounds2.max.length !== 3 || !bounds2.min.every((value, i) => Number.isFinite(value) && value <= bounds2.max[i]) || !bounds2.max.every(Number.isFinite) || !Number.isFinite(bounds2.geometricError) || bounds2.geometricError < 0)
6139
+ throw new RangeError("Invalid terrain LOD screen-error bounds");
6140
+ return prepareTerrainLodScreenError(projection)(bounds2);
6141
+ }
6142
+ function prepareTerrainLodScreenError(projection) {
6143
+ const { width, height, depthRange = "negative-one-to-one", reversedDepth = false } = projection;
6144
+ if (projection.matrix.length !== 16)
6145
+ throw new RangeError("Invalid terrain LOD clip matrix");
6146
+ const matrix = Array.from(projection.matrix);
6147
+ if (!matrix.every(Number.isFinite) || !Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0 || depthRange !== "negative-one-to-one" && depthRange !== "zero-to-one")
6148
+ throw new RangeError("Invalid terrain LOD projection");
6149
+ return ({ min, max, geometricError: error }) => {
6150
+ if (error === 0)
6151
+ return 0;
6152
+ function row(index) {
6153
+ let lower = matrix[12 + index];
6154
+ let upper = lower;
6155
+ let change = 0;
6156
+ for (let axis = 0; axis < 3; axis++) {
6157
+ const coefficient = matrix[4 * axis + index];
6158
+ const a = coefficient * min[axis];
6159
+ const b = coefficient * max[axis];
6160
+ lower = down(lower + down(Math.min(a, b)));
6161
+ upper = up(upper + up(Math.max(a, b)));
6162
+ change = up(change + up(Math.abs(coefficient) * error));
6163
+ }
6164
+ return { lower, upper, change };
6165
+ }
6166
+ const w = row(3);
6167
+ const z = row(2);
6168
+ const nearLow = reversedDepth ? down(w.lower - z.upper) : depthRange === "zero-to-one" ? z.lower : down(z.lower + w.lower);
6169
+ const nearHigh = reversedDepth ? up(w.upper - z.lower) : depthRange === "zero-to-one" ? z.upper : up(z.upper + w.upper);
6170
+ const nearChange = !reversedDepth && depthRange === "zero-to-one" ? z.change : up(z.change + w.change);
6171
+ if (up(nearHigh + nearChange) < 0)
6172
+ return 0;
6173
+ const denominator = down(w.lower - w.change);
6174
+ if (!(down(nearLow - nearChange) > 0 && denominator > 0))
6175
+ return Infinity;
6176
+ function pixelAxis(index, extent) {
6177
+ const coordinate = row(index);
6178
+ const magnitude2 = Math.max(Math.abs(coordinate.lower), Math.abs(coordinate.upper));
6179
+ const ndc = up(magnitude2 / denominator);
6180
+ const coupling = up(ndc * w.change);
6181
+ const numerator = up(coordinate.change + coupling);
6182
+ return up(up(numerator / denominator) * up(extent / 2));
6183
+ }
6184
+ const pixels = pixelAxis(0, width) + pixelAxis(1, height);
6185
+ return Number.isFinite(pixels) ? up(pixels) : Infinity;
6186
+ };
6187
+ }
6188
+
6189
+ // dist/terrain/lod-select.js
6190
+ function selectTerrainLod(roots, view) {
6191
+ var _a;
6192
+ const { targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
6193
+ if (!Number.isFinite(targetPixels) || targetPixels <= 0 || !(hysteresis >= 0 && hysteresis < 1) || !Number.isSafeInteger(maxVisited) || maxVisited < 1)
6194
+ throw new Error("Invalid terrain LOD view");
6195
+ const pixelError = "projection" in view ? prepareTerrainLodScreenError(view.projection) : createDistanceEstimator(view.position, view.verticalFov, view.viewportHeight);
6196
+ const selected = [];
6197
+ const refined = /* @__PURE__ */ new Set();
6198
+ const unavailable = [];
6199
+ const seen = /* @__PURE__ */ new Set();
6200
+ const pending = [...roots].reverse();
6201
+ while (pending.length) {
6202
+ const tile = pending.pop();
6203
+ if (seen.size >= maxVisited)
6204
+ throw new Error("Terrain LOD visit limit exceeded");
6205
+ if (seen.has(tile.id))
6206
+ throw new Error("Duplicate terrain LOD tile or cycle");
6207
+ seen.add(tile.id);
6208
+ if (tile.min.length !== 3 || tile.max.length !== 3 || ![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) || tile.geometricError < 0 || tile.min.some((n, i) => n > tile.max[i]))
6209
+ throw new Error("Invalid terrain LOD tile bounds or error");
6210
+ if (!tile.resident) {
6211
+ unavailable.push(tile.id);
6212
+ continue;
6213
+ }
6214
+ const pixels = pixelError(tile);
6215
+ const threshold = targetPixels * ((previouslyRefined == null ? void 0 : previouslyRefined.has(tile.id)) ? 1 - hysteresis : 1);
6216
+ if (pixels > threshold && ((_a = tile.children) == null ? void 0 : _a.length) && tile.children.every((child) => child.resident)) {
6217
+ if (pending.length + seen.size + tile.children.length > maxVisited)
6218
+ throw new Error("Terrain LOD visit limit exceeded");
6219
+ refined.add(tile.id);
6220
+ for (let i = tile.children.length - 1; i >= 0; i--)
6221
+ pending.push(tile.children[i]);
6222
+ } else {
6223
+ selected.push({ tile, pixels });
6224
+ }
6225
+ }
6226
+ return { selected, refined, unavailable };
6227
+ }
6228
+ function createDistanceEstimator(position, verticalFov, viewportHeight) {
6229
+ if (!position.every(Number.isFinite) || !Number.isFinite(verticalFov) || verticalFov <= 0 || verticalFov >= Math.PI || !Number.isFinite(viewportHeight) || viewportHeight <= 0)
6230
+ throw new Error("Invalid terrain LOD view");
6231
+ const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
6232
+ if (!Number.isFinite(scale))
6233
+ throw new Error("Terrain LOD projection scale overflow");
6234
+ return (tile) => {
6235
+ const distance = Math.hypot(...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
6236
+ return tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale;
6237
+ };
6238
+ }
6239
+
6240
+ // dist/terrain/lod-stitch.js
6241
+ function stitchTerrainLodCut(input, seams) {
6242
+ const meshes = input.slice();
6243
+ const paired = [];
6244
+ for (const { a, edgeA, b, edgeB, options, offsetBX = 0 } of seams) {
6245
+ if (a === b || !Number.isInteger(a) || !Number.isInteger(b) || !meshes[a] || !meshes[b])
6246
+ throw new Error("Invalid terrain LOD seam tile index");
6247
+ if (!Number.isFinite(offsetBX))
6248
+ throw new Error("Invalid terrain LOD seam offset");
6249
+ const meshB = meshes[b];
6250
+ const shiftedB = offsetBX === 0 ? meshB : {
6251
+ ...meshB,
6252
+ origin: [meshB.origin[0] + offsetBX, meshB.origin[1], meshB.origin[2]]
6253
+ };
6254
+ const result = stitchTerrainMeshEdges(meshes[a], edgeA, shiftedB, edgeB, options);
6255
+ meshes[a] = result.a;
6256
+ meshes[b] = offsetBX === 0 ? result.b : {
6257
+ ...result.b,
6258
+ origin: [result.b.origin[0] - offsetBX, result.b.origin[1], result.b.origin[2]]
6259
+ };
6260
+ paired.push({ a, b, idsA: result.seamA, idsB: result.seamB, offsetBX });
6261
+ }
6262
+ for (const { a, b, idsA, idsB, offsetBX } of paired) {
6263
+ const ma = meshes[a], mb = meshes[b];
6264
+ const path = (mesh, ids) => {
6265
+ const links = /* @__PURE__ */ new Set();
6266
+ for (let i = 1; i < ids.length; i++) {
6267
+ links.add(`${Math.min(ids[i - 1], ids[i])},${Math.max(ids[i - 1], ids[i])}`);
6268
+ }
6269
+ for (let i = 0; i < mesh.indices.length; i += 3) {
6270
+ for (let j = 0; j < 3; j++) {
6271
+ const p = mesh.indices[i + j], q = mesh.indices[i + (j + 1) % 3];
6272
+ links.delete(`${Math.min(p, q)},${Math.max(p, q)}`);
6273
+ }
6274
+ }
6275
+ return links.size === 0;
6276
+ };
6277
+ if (!path(ma, idsA) || !path(mb, idsB))
6278
+ throw new Error("Overlapping terrain LOD seam ranges require a common subdivision");
6279
+ for (let i = 0; i < idsA.length; i++) {
6280
+ for (let axis = 0; axis < 3; axis++) {
6281
+ const offset = mb.origin[axis] + (axis === 0 ? offsetBX : 0) - ma.origin[axis];
6282
+ const av = ma.positions[3 * idsA[i] + axis], bv = mb.positions[3 * idsB[i] + axis];
6283
+ const residual = av - bv - offset;
6284
+ const roundoff = 8 * Number.EPSILON * (Math.abs(av) + Math.abs(bv) + Math.abs(offset));
6285
+ if (!Number.isFinite(residual) || Math.abs(residual) > roundoff)
6286
+ throw new Error("Incompatible terrain LOD seam heights or shared corners");
6287
+ }
6288
+ }
6289
+ }
6290
+ return meshes;
6291
+ }
6292
+
6293
+ // dist/terrain/breakline-preprocess.js
6294
+ function splitTerrainBreaklines(input, options = {}) {
6295
+ const { heightTolerance = 1e-8, maxPairTests = 21e5, maxSegments = 2048 } = options;
6296
+ if (!Number.isFinite(heightTolerance) || heightTolerance < 0 || ![maxPairTests, maxSegments].every((n) => Number.isSafeInteger(n) && n >= 0 && n <= 4294967295))
6297
+ throw new Error("Invalid breakline split limits");
6298
+ if (input.length > maxSegments || input.length * (input.length - 1) / 2 > maxPairTests)
6299
+ throw new Error("Breakline preprocessing work limit exceeded");
6300
+ const vertices = /* @__PURE__ */ new Map();
6301
+ const canonical = (p) => {
6302
+ if (!p.every(Number.isFinite))
6303
+ throw new Error("Invalid breakline vertex");
6304
+ const key2 = `${p[0]},${p[1]}`;
6305
+ const prior = vertices.get(key2);
6306
+ if (prior) {
6307
+ if (Math.abs(prior[2] - p[2]) > heightTolerance)
6308
+ throw new Error("Conflicting breakline heights");
6309
+ return prior;
6310
+ }
6311
+ const point = [...p];
6312
+ vertices.set(key2, point);
6313
+ return point;
6314
+ };
6315
+ const lines = input.map(([a, b]) => {
6316
+ const p = canonical(a), q = canonical(b);
6317
+ if (p === q)
6318
+ throw new Error("Zero-length breakline");
6319
+ const knots = [
6320
+ { t: 0, point: p },
6321
+ { t: 1, point: q }
6322
+ ];
6323
+ return { p, q, dx: q[0] - p[0], dy: q[1] - p[1], knots };
6324
+ });
6325
+ let count = input.length;
6326
+ const add2 = (knots, t, point) => {
6327
+ if (knots.some((k) => k.point === point))
6328
+ return;
6329
+ if (knots.some((k) => k.t === t))
6330
+ throw new Error("Unresolved coincident breakline intersections");
6331
+ if (++count > maxSegments)
6332
+ throw new Error("Breakline output limit exceeded");
6333
+ knots.push({ t, point });
6334
+ };
6335
+ const cross4 = (ax, ay, bx, by) => ax * by - ay * bx;
6336
+ for (let i = 0; i < lines.length; i++) {
6337
+ const a = lines[i];
6338
+ for (let j = i + 1; j < lines.length; j++) {
6339
+ const b = lines[j];
6340
+ const x = b.p[0] - a.p[0], y = b.p[1] - a.p[1];
6341
+ const det = cross4(a.dx, a.dy, b.dx, b.dy);
6342
+ const u = cross4(x, y, a.dx, a.dy), t = cross4(x, y, b.dx, b.dy);
6343
+ if (![det, u, t].every(Number.isFinite))
6344
+ throw new Error("Breakline intersection overflow");
6345
+ if (det === 0) {
6346
+ if (u !== 0 || t !== 0)
6347
+ continue;
6348
+ const axis = Math.abs(a.dx) >= Math.abs(a.dy) ? 0 : 1;
6349
+ if (Math.max(Math.min(a.p[axis], a.q[axis]), Math.min(b.p[axis], b.q[axis])) < Math.min(Math.max(a.p[axis], a.q[axis]), Math.max(b.p[axis], b.q[axis])))
6350
+ throw new Error("Overlapping collinear breaklines");
6351
+ continue;
6352
+ }
6353
+ const fa = t / det, fb = u / det;
6354
+ if (fa < 0 || fa > 1 || fb < 0 || fb > 1)
6355
+ continue;
6356
+ const za = (1 - fa) * a.p[2] + fa * a.q[2], zb = (1 - fb) * b.p[2] + fb * b.q[2];
6357
+ if (!Number.isFinite(za) || !Number.isFinite(zb) || Math.abs(za - zb) > heightTolerance)
6358
+ throw new Error("Conflicting breakline heights at intersection");
6359
+ const point = canonical(fa === 0 ? a.p : fa === 1 ? a.q : fb === 0 ? b.p : fb === 1 ? b.q : [a.p[0] + fa * a.dx, a.p[1] + fa * a.dy, za]);
6360
+ add2(a.knots, fa, point);
6361
+ add2(b.knots, fb, point);
6362
+ }
6363
+ }
6364
+ const segments = [];
6365
+ const sourceSegments = new Uint32Array(count);
6366
+ for (let i = 0; i < lines.length; i++) {
6367
+ const knots = lines[i].knots.sort((a, b) => a.t - b.t);
6368
+ for (let j = 1; j < knots.length; j++) {
6369
+ sourceSegments[segments.length] = i;
6370
+ segments.push([knots[j - 1].point, knots[j].point]);
6371
+ }
6372
+ }
6373
+ return { segments, sourceSegments };
6374
+ }
6375
+
6376
+ // dist/terrain/valid-domain-regions.js
6377
+ function updateTerrainValidDomainMeshRegions(previous, field, dirty, options) {
6378
+ const { maxError, maxTrianglesPerRegion, maxSampleTestsPerRegion } = options;
6379
+ if (!Number.isFinite(maxError) || maxError < 0)
6380
+ throw new Error("Invalid regional mesh error");
6381
+ for (const limit of [maxTrianglesPerRegion, maxSampleTestsPerRegion]) {
6382
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 1))
6383
+ throw new Error("Invalid regional mesh work limit");
6384
+ }
6385
+ const configuration = `valid-domain:${maxError}:${maxTrianglesPerRegion ?? ""}:${maxSampleTestsPerRegion ?? ""}`;
6386
+ return updateMeshRegions(previous, field, dirty, options, configuration, (region) => createValidDomainTerrainMesh(region, {
6387
+ maxError,
6388
+ maxTriangles: maxTrianglesPerRegion,
6389
+ maxSampleTests: maxSampleTestsPerRegion
6390
+ }));
6391
+ }
6392
+
6393
+ // dist/terrain/mesh-coverage.js
6394
+ function gcd(a, b) {
6395
+ if (a < 0n)
6396
+ a = -a;
6397
+ if (b < 0n)
6398
+ b = -b;
6399
+ while (b !== 0n)
6400
+ [a, b] = [b, a % b];
6401
+ return a;
6402
+ }
6403
+ function certifyTerrainMeshCoverage(field, mesh, options = {}) {
6404
+ var _a, _b;
6405
+ const { reference = "triangle", maxTriangles = 2e6 } = options;
6406
+ const referenceMesh = typeof reference === "object" ? reference : null;
6407
+ const validShape = (input) => input.indices.length % 3 === 0 && input.gridCoordinates.length % 2 === 0;
6408
+ if (!Number.isSafeInteger(maxTriangles) || maxTriangles < 1 || !referenceMesh && reference !== "triangle" && reference !== "bilinear" || !validShape(mesh) || referenceMesh && !validShape(referenceMesh))
6409
+ throw new Error("Invalid terrain coverage input");
6410
+ const trianglesVisited = mesh.indices.length / 3 + (referenceMesh ? referenceMesh.indices.length / 3 : 2 * (field.width - 1) * (field.height - 1));
6411
+ if (trianglesVisited > maxTriangles) {
6412
+ return {
6413
+ status: "budget-exhausted",
6414
+ unmatchedSegments: 0,
6415
+ witness: null,
6416
+ trianglesVisited: 0,
6417
+ residualEdges: 0
6418
+ };
6419
+ }
6420
+ const bits2 = new DataView(new ArrayBuffer(8));
6421
+ function exact2(value) {
6422
+ bits2.setFloat64(0, value);
6423
+ const raw = bits2.getBigUint64(0);
6424
+ const exponent = Number(raw >> 52n & 2047n);
6425
+ const fraction = raw & (1n << 52n) - 1n;
6426
+ const integer2 = exponent === 0 ? fraction : (1n << 52n | fraction) << BigInt(exponent - 1);
6427
+ return value < 0 ? -integer2 : integer2;
6428
+ }
6429
+ const vertices = [];
6430
+ const vertexIds = /* @__PURE__ */ new Map();
6431
+ const edges2 = /* @__PURE__ */ new Map();
6432
+ function vertex(x, y) {
6433
+ if (!Number.isFinite(x) || !Number.isFinite(y))
6434
+ throw new Error("Nonfinite coverage coordinate");
6435
+ const key2 = `${x},${y}`;
6436
+ const previous = vertexIds.get(key2);
6437
+ if (previous !== void 0)
6438
+ return previous;
6439
+ const id = vertices.length;
6440
+ vertices.push([x, y]);
6441
+ vertexIds.set(key2, id);
6442
+ return id;
6443
+ }
6444
+ function edge2(a, b, weight) {
6445
+ var _a2;
6446
+ if (a > b) {
6447
+ [a, b] = [b, a];
6448
+ weight = -weight;
6449
+ }
6450
+ const key2 = b < 2 ** 26 ? a * 2 ** 26 + b : `${a},${b}`;
6451
+ const sum = (((_a2 = edges2.get(key2)) == null ? void 0 : _a2.weight) ?? 0) + weight;
6452
+ if (sum === 0)
6453
+ edges2.delete(key2);
6454
+ else
6455
+ edges2.set(key2, { a, b, weight: sum });
6456
+ }
6457
+ function triangle(a, b, c, weight) {
6458
+ edge2(a, b, weight);
6459
+ edge2(b, c, weight);
6460
+ edge2(c, a, weight);
6461
+ }
6462
+ function addMesh({ indices, gridCoordinates }, weight) {
6463
+ for (let i = 0; i < indices.length; i += 3) {
6464
+ const ids = [indices[i], indices[i + 1], indices[i + 2]].map((id) => {
6465
+ if (!Number.isSafeInteger(id) || id < 0 || id >= gridCoordinates.length / 2)
6466
+ throw new Error("Invalid coverage vertex index");
6467
+ return vertex(gridCoordinates[id * 2], gridCoordinates[id * 2 + 1]);
6468
+ });
6469
+ const [a, b, c] = ids.map((id) => vertices[id]);
6470
+ const left = (b[0] - a[0]) * (c[1] - a[1]);
6471
+ const right = (b[1] - a[1]) * (c[0] - a[0]);
6472
+ const det = left - right;
6473
+ const limit = 8 * Number.EPSILON * (Math.abs(left) + Math.abs(right)) + 8 * Number.MIN_VALUE;
6474
+ let sign2 = Math.sign(det);
6475
+ if (!Number.isFinite(det) || Math.abs(det) <= limit) {
6476
+ const [ax, ay] = a.map(exact2), [bx, by] = b.map(exact2), [cx, cy] = c.map(exact2);
6477
+ const determinant = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
6478
+ sign2 = determinant > 0n ? 1 : determinant < 0n ? -1 : 0;
6479
+ }
6480
+ if (!sign2)
6481
+ throw new Error("Degenerate coverage triangle");
6482
+ triangle(ids[0], ids[1], ids[2], weight * sign2);
6483
+ }
6484
+ }
6485
+ addMesh(mesh, 1);
6486
+ if (referenceMesh)
6487
+ addMesh(referenceMesh, -1);
6488
+ else
6489
+ for (let y = 0; y < field.height - 1; y++) {
6490
+ for (let x = 0; x < field.width - 1; x++) {
6491
+ const valid = [
6492
+ field.getHeight(x, y),
6493
+ field.getHeight(x + 1, y),
6494
+ field.getHeight(x, y + 1),
6495
+ field.getHeight(x + 1, y + 1)
6496
+ ].map((z) => z !== void 0);
6497
+ if (reference === "bilinear" && !valid.every(Boolean))
6498
+ continue;
6499
+ const corners = [
6500
+ [x, y],
6501
+ [x + 1, y],
6502
+ [x, y + 1],
6503
+ [x + 1, y + 1]
6504
+ ];
6505
+ const faces = field.diagonal === "00-11" ? [
6506
+ [0, 1, 3],
6507
+ [0, 3, 2]
6508
+ ] : [
6509
+ [0, 1, 2],
6510
+ [1, 3, 2]
6511
+ ];
6512
+ for (const [a, b, c] of faces) {
6513
+ if (!valid[a] || !valid[b] || !valid[c])
6514
+ continue;
6515
+ triangle(vertex(...corners[a]), vertex(...corners[b]), vertex(...corners[c]), -1);
6516
+ }
6517
+ }
6518
+ }
6519
+ const lines = /* @__PURE__ */ new Map();
6520
+ for (const { a, b, weight } of edges2.values()) {
6521
+ const p = vertices[a], q = vertices[b];
6522
+ const [x, y] = p.map(exact2), [u, v] = q.map(exact2);
6523
+ const divisor = gcd(u - x, v - y);
6524
+ let dx = (u - x) / divisor, dy = (v - y) / divisor;
6525
+ if (dx < 0n || dx === 0n && dy < 0n)
6526
+ [dx, dy] = [-dx, -dy];
6527
+ const key2 = `${dx},${dy},${dx * y - dy * x}`;
6528
+ let events = lines.get(key2);
6529
+ if (!events) {
6530
+ events = /* @__PURE__ */ new Map();
6531
+ lines.set(key2, events);
6532
+ }
6533
+ const axis = dx === 0n ? 1 : 0;
6534
+ const delta = weight;
6535
+ events.set(p[axis], { point: p, delta: (((_a = events.get(p[axis])) == null ? void 0 : _a.delta) ?? 0) + delta });
6536
+ events.set(q[axis], { point: q, delta: (((_b = events.get(q[axis])) == null ? void 0 : _b.delta) ?? 0) - delta });
6537
+ }
6538
+ let unmatchedSegments = 0;
6539
+ let witness = null;
6540
+ for (const events of lines.values()) {
6541
+ const sorted = [...events].sort(([a], [b]) => a - b);
6542
+ let jump = 0;
6543
+ for (let i = 0; i + 1 < sorted.length; i++) {
6544
+ jump += sorted[i][1].delta;
6545
+ if (!jump)
6546
+ continue;
6547
+ unmatchedSegments++;
6548
+ witness ?? (witness = { start: sorted[i][1].point, end: sorted[i + 1][1].point, multiplicityJump: jump });
6549
+ }
6550
+ }
6551
+ return {
6552
+ status: unmatchedSegments ? "mismatch" : "certified",
6553
+ unmatchedSegments,
6554
+ witness,
6555
+ trianglesVisited,
6556
+ residualEdges: edges2.size
6557
+ };
6558
+ }
6559
+
6560
+ // dist/geographic-tiles.js
6561
+ function getGeographicTileBounds(tile) {
6562
+ const size = gridSize(tile.level);
6563
+ if (![tile.x, tile.y].every((v) => Number.isInteger(v) && v >= 0 && v < size))
6564
+ throw new RangeError("Tile coordinates must be integers inside the level grid");
6565
+ return [
6566
+ -180 + 360 * tile.x / size,
6567
+ 90 - 180 * (tile.y + 1) / size,
6568
+ -180 + 360 * (tile.x + 1) / size,
6569
+ 90 - 180 * tile.y / size
6570
+ ];
6571
+ }
6572
+ function gridSize(level) {
6573
+ if (!Number.isInteger(level) || level < 0 || level > 30)
6574
+ throw new RangeError("Level must be an integer from 0 through 30");
6575
+ return 2 ** level;
6576
+ }
6577
+
6578
+ // dist/terrain/geographic-neighbor.js
6579
+ function getGeographicTerrainNeighbor(tile, edge2) {
6580
+ getGeographicTileBounds(tile);
6581
+ const { x, y, level } = tile;
6582
+ const size = 2 ** level;
6583
+ switch (edge2) {
6584
+ case "west":
6585
+ case "east": {
6586
+ const ownerX = edge2 === "west" ? x : (x + 1) % size;
6587
+ return {
6588
+ owner: { x: ownerX, y, level },
6589
+ ownerEdge: "west",
6590
+ other: { x: (ownerX + size - 1) % size, y, level },
6591
+ otherEdge: "east",
6592
+ crossesAntimeridian: ownerX === 0
6593
+ };
6594
+ }
6595
+ case "north":
6596
+ case "south": {
6597
+ const ownerY = edge2 === "north" ? y : y + 1;
6598
+ if (ownerY === 0 || ownerY === size)
6599
+ return null;
6600
+ return {
6601
+ owner: { x, y: ownerY, level },
6602
+ ownerEdge: "north",
6603
+ other: { x, y: ownerY - 1, level },
6604
+ otherEdge: "south",
6605
+ crossesAntimeridian: false
6606
+ };
6607
+ }
6608
+ default:
6609
+ throw new RangeError("Invalid geographic terrain edge");
6610
+ }
6611
+ }
6612
+
6613
+ // dist/terrain/sweep-sphere.js
6614
+ function sweepTerrainSphere(surface, start, end, radius, { fractionTolerance = 1e-6, maxWork = 1e5 } = {}) {
6615
+ if (!(fractionTolerance >= Number.EPSILON && fractionTolerance <= 1) || !Number.isSafeInteger(maxWork) || maxWork < 0)
6616
+ throw new RangeError("Invalid terrain sphere sweep limits");
6617
+ const delta = end.map((value, axis) => value - start[axis]);
6618
+ if (start.length !== 3 || end.length !== 3 || !start.every(Number.isFinite) || !end.every(Number.isFinite) || !delta.every(Number.isFinite) || !Number.isFinite(radius) || radius < 0)
6619
+ throw new RangeError("Invalid terrain sphere sweep motion or radius");
6620
+ let work = 0;
6621
+ let lower = 0;
6622
+ let upper = 1;
6623
+ const prefix = (fraction) => {
6624
+ const endPoint = fraction === 0 ? start : fraction === 1 ? end : [
6625
+ start[0] + delta[0] * fraction,
6626
+ start[1] + delta[1] * fraction,
6627
+ start[2] + delta[2] * fraction
6628
+ ];
6629
+ const query = surface.intersectCapsule(start, endPoint, radius, {
6630
+ maxWork: maxWork - work,
6631
+ maxContacts: 1
6632
+ });
6633
+ work += query.work;
6634
+ return query;
6635
+ };
6636
+ const initial = prefix(0);
6637
+ if (initial.result[0])
6638
+ return { status: "hit", fraction: 0, lowerFraction: 0, contact: initial.result[0], work };
6639
+ if (!initial.complete)
6640
+ return { status: "incomplete", work };
6641
+ const full = prefix(1);
6642
+ let contact = full.result[0];
6643
+ if (!contact)
6644
+ return { status: full.complete ? "miss" : "incomplete", work };
6645
+ while (upper - lower > fractionTolerance) {
6646
+ const middle = (lower + upper) / 2;
6647
+ const query = prefix(middle);
6648
+ if (query.result[0]) {
6649
+ upper = middle;
6650
+ contact = query.result[0];
6651
+ } else if (query.complete) {
6652
+ lower = middle;
6653
+ } else {
6654
+ return { status: "incomplete", work };
6655
+ }
6656
+ }
6657
+ return { status: "hit", fraction: upper, lowerFraction: lower, contact, work };
6658
+ }
6659
+
6660
+ // dist/terrain/sweep-capsule.js
6661
+ function sweepTerrainCapsule(surface, start, end, translation, radius, { fractionTolerance = 1e-6, maxWork = 1e5 } = {}) {
6662
+ var _a;
6663
+ const speed = Math.hypot(...translation);
6664
+ if (![start, end, translation].every((point) => point.length === 3 && point.every(Number.isFinite)) || !Number.isFinite(speed) || !Number.isFinite(radius) || radius < 0 || !(fractionTolerance >= Number.EPSILON && fractionTolerance <= 1) || !Number.isSafeInteger(maxWork) || maxWork < 0)
6665
+ throw new RangeError("Invalid terrain capsule sweep");
6666
+ let work = 0;
6667
+ const probe = (fraction) => {
6668
+ if (work >= maxWork)
6669
+ return null;
6670
+ work++;
6671
+ const move = (point) => [
6672
+ point[0] + translation[0] * fraction,
6673
+ point[1] + translation[1] * fraction,
6674
+ point[2] + translation[2] * fraction
6675
+ ];
6676
+ const query = surface.nearestSegmentQuery(move(start), move(end), { maxWork: maxWork - work });
6677
+ work += query.work;
6678
+ return query;
6679
+ };
6680
+ const initial = probe(0);
6681
+ if ((initial == null ? void 0 : initial.result) && initial.result.distance <= radius)
6682
+ return { status: "hit", work, fraction: 0, lowerFraction: 0, contact: initial.result };
6683
+ if (!(initial == null ? void 0 : initial.complete))
6684
+ return { status: "incomplete", work };
6685
+ if (!initial.result || speed === 0)
6686
+ return { status: "miss", work };
6687
+ let clearUntil = 0;
6688
+ let witness;
6689
+ const pending = [[0, 1]];
6690
+ while (pending.length) {
6691
+ const [lower, upper] = pending.pop();
6692
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
6693
+ return { status: "hit", work, lowerFraction: clearUntil, ...witness };
6694
+ const middle = lower + (upper - lower) / 2;
6695
+ const query = probe(middle);
6696
+ if (!query)
6697
+ return { status: "incomplete", work };
6698
+ const hit = query.result;
6699
+ if (hit && hit.distance <= radius) {
6700
+ witness = { fraction: middle, contact: hit };
6701
+ if (middle - clearUntil <= fractionTolerance)
6702
+ return { status: "hit", work, lowerFraction: clearUntil, ...witness };
6703
+ pending.push([lower, middle]);
6704
+ continue;
6705
+ }
6706
+ if (!query.complete)
6707
+ return { status: "incomplete", work };
6708
+ const travel = speed * Math.max(middle - lower, upper - middle);
6709
+ const allowance = 8 * Number.EPSILON * Math.max((hit == null ? void 0 : hit.distance) ?? 0, radius, travel);
6710
+ if (!hit || hit.distance - radius > travel + allowance) {
6711
+ clearUntil = upper;
6712
+ continue;
6713
+ }
6714
+ if (upper - lower <= fractionTolerance) {
6715
+ const final = (_a = probe(upper)) == null ? void 0 : _a.result;
6716
+ if (final && final.distance <= radius && upper - clearUntil <= fractionTolerance)
6717
+ return { status: "hit", work, fraction: upper, lowerFraction: clearUntil, contact: final };
6718
+ return { status: "incomplete", work };
6719
+ }
6720
+ pending.push([middle, upper], [lower, middle]);
6721
+ }
6722
+ return witness ? { status: "hit", work, lowerFraction: clearUntil, ...witness } : { status: "miss", work };
6723
+ }
6724
+ function sweepTerrainTaperedCapsule(surface, start, end, translation, radiusStart, radiusEnd, { maxWork = 1e5, fractionTolerance } = {}) {
6725
+ if (![radiusStart, radiusEnd].every((radius) => Number.isFinite(radius) && radius >= 0))
6726
+ throw new RangeError("Invalid terrain tapered capsule radii");
6727
+ const outer = sweepTerrainCapsule(surface, start, end, translation, Math.max(radiusStart, radiusEnd), {
6728
+ maxWork,
6729
+ fractionTolerance
6730
+ });
6731
+ if (outer.status !== "hit" || radiusStart === radiusEnd)
6732
+ return outer;
6733
+ const inner = sweepTerrainCapsule(surface, start, end, translation, Math.min(radiusStart, radiusEnd), {
6734
+ maxWork: maxWork - outer.work,
6735
+ fractionTolerance
6736
+ });
6737
+ const work = outer.work + inner.work;
6738
+ return inner.status === "hit" && outer.lowerFraction <= inner.fraction ? { ...inner, lowerFraction: outer.lowerFraction, work } : { status: "incomplete", work };
6739
+ }
6740
+
6741
+ // dist/terrain/sweep-polytope.js
6742
+ var sub2 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
6743
+ var cross2 = (a, b) => [
6744
+ a[1] * b[2] - a[2] * b[1],
6745
+ a[2] * b[0] - a[0] * b[2],
6746
+ a[0] * b[1] - a[1] * b[0]
6747
+ ];
6748
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
6749
+ var edges = ([a, b, c]) => [sub2(b, a), sub2(c, b), sub2(a, c)];
6750
+ function sweepTerrainPolytope(surface, collider, translation, { maxWork = 1e5 } = {}) {
6751
+ return queryTerrainPolytope(surface.copyData(), surface.origin, collider, translation, maxWork);
6752
+ }
6753
+ function queryTerrainPolytope(data, origin, collider, translation, maxWork, padding = 0) {
6754
+ if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite) || collider.vertices.length < 4 || collider.faces.length < 4 || collider.vertices.some((point) => point.length !== 3 || !point.every(Number.isFinite)))
6755
+ throw new RangeError("Invalid terrain polytope sweep");
6756
+ const vertices = collider.vertices.map((point) => sub2(point, origin));
6757
+ const normals = [];
6758
+ const directions = [];
6759
+ for (const face of collider.faces) {
6760
+ if (face.length !== 3 || face.some((i) => !Number.isSafeInteger(i) || !vertices[i]))
6761
+ throw new RangeError("Invalid terrain polytope face");
6762
+ const side = edges([vertices[face[0]], vertices[face[1]], vertices[face[2]]]);
6763
+ const normal = cross2(side[0], side[1]);
6764
+ if (!normal.every(Number.isFinite) || !normal.some(Boolean))
6765
+ throw new RangeError("Degenerate terrain polytope face");
6766
+ normals.push(normal);
6767
+ directions.push(...side);
6768
+ }
6769
+ return sweepTriangles(data, vertices, normals, directions, translation, maxWork, void 0, padding);
6770
+ }
6771
+ function sweepTerrainTriangleMesh(surface, collider, translation, { maxWork = 1e5 } = {}) {
6772
+ if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite))
6773
+ throw new RangeError("Invalid terrain triangle mesh sweep");
6774
+ const data = surface.copyData();
6775
+ let work = 0;
6776
+ let best;
6777
+ for (const face of collider.faces) {
6778
+ if (face.length !== 3)
6779
+ throw new RangeError("Invalid terrain sweep mesh face");
6780
+ const vertices = face.map((index) => {
6781
+ const point = collider.vertices[index];
6782
+ if (!Number.isSafeInteger(index) || !point || point.length !== 3 || !point.every(Number.isFinite))
6783
+ throw new RangeError("Invalid terrain sweep mesh vertex");
6784
+ return sub2(point, surface.origin);
6785
+ });
6786
+ const directions = edges(vertices);
6787
+ const normal = cross2(directions[0], directions[1]);
6788
+ if (!normal.every(Number.isFinite) || !normal.some(Boolean))
6789
+ throw new RangeError("Degenerate terrain sweep mesh face");
6790
+ const result = sweepTriangles(data, vertices, [normal], directions, translation, maxWork - work, normal);
6791
+ work += result.work;
6792
+ if (result.status === "incomplete")
6793
+ return { status: "incomplete", work };
6794
+ if (result.status === "hit" && (!best || result.fraction < best.fraction))
6795
+ best = result;
6796
+ }
6797
+ return best ? { ...best, work } : { status: "miss", work };
6798
+ }
6799
+ function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal, padding = 0) {
6800
+ let work = 0;
6801
+ let best;
6802
+ const vertex = (index) => {
6803
+ const i = 3 * data.indices[index];
6804
+ return [data.positions[i], data.positions[i + 1], data.positions[i + 2]];
6805
+ };
6806
+ for (let i = 0; i < data.triangleValidity.length; i++) {
6807
+ if (!data.triangleValidity[i])
6808
+ continue;
6809
+ const triangle = [vertex(3 * i), vertex(3 * i + 1), vertex(3 * i + 2)];
6810
+ const sides = edges(triangle);
6811
+ let enter = 0;
6812
+ let exit = (best == null ? void 0 : best.fraction) ?? 1;
6813
+ let normal = null;
6814
+ function* axes() {
6815
+ const terrainNormal = cross2(sides[0], sides[1]);
6816
+ yield terrainNormal;
6817
+ if (movingTriangleNormal) {
6818
+ for (const side of sides)
6819
+ yield cross2(terrainNormal, side);
6820
+ for (const direction of directions)
6821
+ yield cross2(movingTriangleNormal, direction);
6822
+ }
6823
+ yield* normals;
6824
+ for (const side of sides)
6825
+ for (const direction of directions)
6826
+ yield cross2(side, direction);
6827
+ }
6828
+ for (const axis of axes()) {
6829
+ if (work >= maxWork)
6830
+ return { status: "incomplete", work };
6831
+ work++;
6832
+ const length = Math.hypot(...axis);
6833
+ if (length === 0)
6834
+ continue;
6835
+ const unit = [axis[0] / length, axis[1] / length, axis[2] / length];
6836
+ const low = Math.min(...triangle.map((point) => dot(point, unit)));
6837
+ const high = Math.max(...triangle.map((point) => dot(point, unit)));
6838
+ let min = Infinity;
6839
+ let max = -Infinity;
6840
+ for (const point of vertices) {
6841
+ const projection = dot(point, unit);
6842
+ min = Math.min(min, projection);
6843
+ max = Math.max(max, projection);
6844
+ }
6845
+ min -= padding;
6846
+ max += padding;
6847
+ const speed = dot(translation, unit);
6848
+ if (![low, high, min, max, speed, length].every(Number.isFinite))
6849
+ throw new RangeError("Terrain polytope projection overflow");
6850
+ if (speed === 0) {
6851
+ if (min > high || max < low)
6852
+ exit = -1;
6853
+ } else {
6854
+ const first = (low - max) / speed;
6855
+ const last = (high - min) / speed;
6856
+ const entry = Math.min(first, last);
6857
+ if (entry > enter) {
6858
+ enter = entry;
6859
+ normal = speed < 0 ? unit : [-unit[0], -unit[1], -unit[2]];
6860
+ }
6861
+ exit = Math.min(exit, Math.max(first, last));
6862
+ }
6863
+ if (enter > exit)
6864
+ break;
6865
+ }
6866
+ if (enter <= exit && (!best || enter < best.fraction)) {
6867
+ best = { status: "hit", fraction: enter, triangleIndex: i, normal, work };
6868
+ if (enter === 0)
6869
+ break;
6870
+ }
6871
+ }
6872
+ return best ? { ...best, work } : { status: "miss", work };
6873
+ }
6874
+ function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6875
+ return sweepTerrainPolytope(surface, createSweepBox(center, halfExtents), translation, options);
6876
+ }
6877
+ function createSweepBox(center, halfExtents) {
6878
+ if (halfExtents.length !== 3 || halfExtents.some((value) => !(value > 0)))
6879
+ throw new RangeError("Terrain box half extents must be positive");
6880
+ const vertices = Array.from({ length: 8 }, (_, i) => [
6881
+ center[0] + (i & 1 ? 1 : -1) * halfExtents[0],
6882
+ center[1] + (i & 2 ? 1 : -1) * halfExtents[1],
6883
+ center[2] + (i & 4 ? 1 : -1) * halfExtents[2]
6884
+ ]);
6885
+ return {
6886
+ vertices,
6887
+ faces: [
6888
+ [0, 1, 3],
6889
+ [0, 3, 2],
6890
+ [4, 6, 7],
6891
+ [4, 7, 5],
6892
+ [0, 4, 5],
6893
+ [0, 5, 1],
6894
+ [2, 3, 7],
6895
+ [2, 7, 6],
6896
+ [0, 2, 6],
6897
+ [0, 6, 4],
6898
+ [1, 5, 7],
6899
+ [1, 7, 3]
6900
+ ]
6901
+ };
6902
+ }
6903
+
6904
+ // dist/terrain/sweep-rotating-capsule.js
6905
+ function sweepTerrainRotatingCapsule(surface, start, end, radius, { pivot, translation, rotation }, { maxWork = 1e5, fractionTolerance = 1e-5 } = {}) {
6906
+ var _a;
6907
+ const norm = Math.hypot(...rotation);
6908
+ if (![start, end, pivot, translation].every((p) => p.length === 3 && p.every(Number.isFinite)) || rotation.length !== 4 || !(norm > 0 && Number.isFinite(norm)) || !Number.isFinite(radius) || radius < 0 || !Number.isSafeInteger(maxWork) || maxWork < 0 || !(fractionTolerance >= Number.EPSILON && fractionTolerance <= 1))
6909
+ throw new RangeError("Invalid terrain capsule rigid motion");
6910
+ const sign2 = rotation[3] < 0 ? -1 : 1;
6911
+ const axisLength = Math.hypot(rotation[0], rotation[1], rotation[2]);
6912
+ const angle = 2 * Math.atan2(axisLength, Math.abs(rotation[3]));
6913
+ if (angle === 0) {
6914
+ return sweepTerrainCapsule(surface, start, end, translation, radius, {
6915
+ maxWork,
6916
+ fractionTolerance
6917
+ });
6918
+ }
6919
+ const x = rotation[0] / axisLength * sign2;
6920
+ const y = rotation[1] / axisLength * sign2;
6921
+ const z = rotation[2] / axisLength * sign2;
6922
+ const offsets = [start, end].map((p) => p.map((v, i) => v - pivot[i]));
6923
+ const reach = Math.max(...offsets.map((p) => Math.hypot(...p)));
6924
+ const speed = Math.hypot(...translation) + angle * reach;
6925
+ const scale = Math.max(Math.hypot(...pivot), reach, speed, radius);
6926
+ if (!Number.isFinite(scale))
6927
+ throw new RangeError("Terrain capsule rigid motion overflow");
6928
+ let work = 0;
6929
+ function probe(t) {
6930
+ if (work >= maxWork)
6931
+ return null;
6932
+ work++;
6933
+ const sin = Math.sin(angle * t);
6934
+ const cos = Math.cos(angle * t);
6935
+ const [a, b] = t === 0 ? [start, end] : offsets.map(([u, v, w]) => {
6936
+ const d = (x * u + y * v + z * w) * (1 - cos);
6937
+ const pos = [
6938
+ pivot[0] + (translation[0] * t + u * cos + (y * w - z * v) * sin + x * d),
6939
+ pivot[1] + (translation[1] * t + v * cos + (z * u - x * w) * sin + y * d),
6940
+ pivot[2] + (translation[2] * t + w * cos + (x * v - y * u) * sin + z * d)
6941
+ ];
6942
+ if (!pos.every(Number.isFinite))
6943
+ throw new RangeError("Terrain capsule pose overflow");
6944
+ return pos;
6945
+ });
6946
+ const query = surface.nearestSegmentQuery(a, b, { maxWork: maxWork - work });
6947
+ work += query.work;
6948
+ return query;
6949
+ }
6950
+ const initial = probe(0);
6951
+ if ((initial == null ? void 0 : initial.result) && initial.result.distance <= radius)
6952
+ return { status: "hit", fraction: 0, lowerFraction: 0, work, contact: initial.result };
6953
+ if (!(initial == null ? void 0 : initial.complete))
6954
+ return { status: "incomplete", work };
6955
+ if (!initial.result || speed === 0)
6956
+ return { status: "miss", work };
6957
+ let clearUntil = 0;
6958
+ let witness;
6959
+ const pending = [[0, 1]];
6960
+ while (pending.length) {
6961
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
6962
+ return { status: "hit", lowerFraction: clearUntil, work, ...witness };
6963
+ const [lo, hi] = pending.pop();
6964
+ const mid = lo + (hi - lo) / 2;
6965
+ const query = probe(mid);
6966
+ const contact = query == null ? void 0 : query.result;
6967
+ if (contact && contact.distance <= radius) {
6968
+ witness = { fraction: mid, contact };
6969
+ if (mid - clearUntil <= fractionTolerance)
6970
+ return { status: "hit", lowerFraction: clearUntil, work, ...witness };
6971
+ if (mid === lo || mid === hi)
6972
+ return { status: "incomplete", work };
6973
+ pending.push([lo, mid]);
6974
+ continue;
6975
+ }
6976
+ if (!(query == null ? void 0 : query.complete))
6977
+ return { status: "incomplete", work };
6978
+ const travel = speed * Math.max(mid - lo, hi - mid);
6979
+ const allowance = 16 * Number.EPSILON * Math.max(scale, (contact == null ? void 0 : contact.distance) ?? 0);
6980
+ if (!contact || contact.distance - radius > travel + allowance) {
6981
+ clearUntil = hi;
6982
+ continue;
6983
+ }
6984
+ if (hi - clearUntil <= fractionTolerance) {
6985
+ const final = (witness == null ? void 0 : witness.fraction) === hi ? witness.contact : (_a = probe(hi)) == null ? void 0 : _a.result;
6986
+ if (final && final.distance <= radius)
6987
+ return { status: "hit", fraction: hi, lowerFraction: clearUntil, work, contact: final };
6988
+ }
6989
+ if (mid === lo || mid === hi || hi - lo <= fractionTolerance / 4)
6990
+ return { status: "incomplete", work };
6991
+ pending.push([mid, hi], [lo, mid]);
6992
+ }
6993
+ return witness ? { status: "hit", lowerFraction: clearUntil, work, ...witness } : { status: "miss", work };
6994
+ }
6995
+ function sweepTerrainRotatingSphere(surface, center, radius, motion, options) {
6996
+ return sweepTerrainRotatingCapsule(surface, center, center, radius, motion, options);
6997
+ }
6998
+
6999
+ // dist/terrain/sweep-cylinder.js
7000
+ function sweepTerrainCylinder(surface, center, height, radiusBottom, radiusTop, translation, { sides = 16, maxWork = 1e5 } = {}) {
7001
+ if (center.length !== 3 || !center.every(Number.isFinite) || ![height, radiusBottom, radiusTop].every((value) => Number.isFinite(value) && value > 0) || !Number.isInteger(sides) || sides < 3 || sides > 128)
7002
+ throw new RangeError("Invalid terrain cylinder sweep");
7003
+ const faces = [];
7004
+ for (let i = 0; i < sides; i++) {
7005
+ const next = (i + 1) % sides;
7006
+ faces.push([i, next, next + sides], [i, next + sides, i + sides]);
7007
+ if (i > 0 && i < sides - 1)
7008
+ faces.push([0, i + 1, i], [sides, sides + i, sides + i + 1]);
7009
+ }
7010
+ const hull = (scale) => ({
7011
+ faces,
7012
+ vertices: Array.from({ length: 2 * sides }, (_, i) => {
7013
+ const top = i >= sides;
7014
+ const angle = 2 * Math.PI * (i % sides) / sides;
7015
+ const radius = (top ? radiusTop : radiusBottom) * scale;
7016
+ return [
7017
+ center[0] + radius * Math.cos(angle),
7018
+ center[1] + radius * Math.sin(angle),
7019
+ center[2] + (top ? height : -height) / 2
7020
+ ];
7021
+ })
7022
+ });
7023
+ const outer = sweepTerrainPolytope(surface, hull(1 / Math.cos(Math.PI / sides)), translation, {
7024
+ maxWork
7025
+ });
7026
+ if (outer.status !== "hit")
7027
+ return outer;
7028
+ const inner = sweepTerrainPolytope(surface, hull(1), translation, {
7029
+ maxWork: maxWork - outer.work
7030
+ });
7031
+ const work = outer.work + inner.work;
7032
+ if (inner.status !== "hit" || inner.fraction < outer.fraction)
7033
+ return { status: "incomplete", work };
7034
+ return { ...inner, normal: null, lowerFraction: outer.fraction, work };
7035
+ }
7036
+
7037
+ // dist/terrain/sweep-plane.js
7038
+ function sweepTerrainPlane(surface, point, normal, translation, { maxWork = 1e5 } = {}) {
7039
+ const length = Math.hypot(...normal);
7040
+ if (![point, normal, translation].every((v) => v.length === 3 && v.every(Number.isFinite)) || !(length > 0 && Number.isFinite(length)) || !Number.isSafeInteger(maxWork) || maxWork < 0)
7041
+ throw new RangeError("Invalid terrain plane sweep");
7042
+ const unit = [normal[0] / length, normal[1] / length, normal[2] / length];
7043
+ const velocity = translation[0] * unit[0] + translation[1] * unit[1] + translation[2] * unit[2];
7044
+ if (!Number.isFinite(velocity))
7045
+ throw new RangeError("Terrain plane velocity overflow");
7046
+ const { positions, indices, triangleValidity } = surface.copyData();
7047
+ const local = point.map((value, axis) => value - surface.origin[axis]);
7048
+ let work = 0;
7049
+ let fraction = Infinity;
7050
+ let triangleIndex = -1;
7051
+ for (let i = 0; i < triangleValidity.length; i++) {
7052
+ if (!triangleValidity[i])
7053
+ continue;
7054
+ if (work >= maxWork)
7055
+ return { status: "incomplete", work };
7056
+ work++;
7057
+ let min = Infinity;
7058
+ let max = -Infinity;
7059
+ for (let j = 0; j < 3; j++) {
7060
+ const k = indices[3 * i + j] * 3;
7061
+ const distance = (positions[k] - local[0]) * unit[0] + (positions[k + 1] - local[1]) * unit[1] + (positions[k + 2] - local[2]) * unit[2];
7062
+ if (!Number.isFinite(distance))
7063
+ throw new RangeError("Terrain plane projection overflow");
7064
+ min = Math.min(min, distance);
7065
+ max = Math.max(max, distance);
7066
+ }
7067
+ if (min <= 0 && max >= 0)
7068
+ return { status: "hit", fraction: 0, triangleIndex: i, normal: null, work };
7069
+ const entry = velocity > 0 ? min / velocity : max / velocity;
7070
+ if (velocity !== 0 && entry > 0 && entry <= 1 && entry < fraction) {
7071
+ triangleIndex = i;
7072
+ fraction = entry;
7073
+ }
7074
+ }
7075
+ if (triangleIndex < 0)
7076
+ return { status: "miss", work };
7077
+ const entryNormal = velocity < 0 ? unit : [-unit[0], -unit[1], -unit[2]];
7078
+ return { status: "hit", fraction, triangleIndex, normal: entryNormal, work };
7079
+ }
7080
+
7081
+ // dist/terrain/geographic-lod-seams.js
7082
+ function discoverGeographicTerrainLodSeams(cut) {
7083
+ const vertical = /* @__PURE__ */ new Map();
7084
+ const horizontal = /* @__PURE__ */ new Map();
7085
+ const world = 2 ** 30;
7086
+ const addresses = /* @__PURE__ */ new Set();
7087
+ const key2 = (level, x, y) => `${level}/${x}/${y}`;
7088
+ for (const tile of cut) {
7089
+ getGeographicTileBounds(tile);
7090
+ const address = key2(tile.level, tile.x, tile.y);
7091
+ if (addresses.has(address))
7092
+ throw new Error("Duplicate geographic terrain tile");
7093
+ addresses.add(address);
7094
+ }
7095
+ function add2(lines, line, side, span) {
7096
+ let group = lines.get(line);
7097
+ if (!group) {
7098
+ group = { before: [], after: [] };
7099
+ lines.set(line, group);
7100
+ }
7101
+ group[side].push(span);
7102
+ }
7103
+ cut.forEach(({ level, x, y }, tile) => {
7104
+ for (let parent = level - 1; parent >= 0; parent--) {
7105
+ const scale = 2 ** (level - parent);
7106
+ if (addresses.has(key2(parent, Math.floor(x / scale), Math.floor(y / scale))))
7107
+ throw new Error("Overlapping geographic terrain tiles");
7108
+ }
7109
+ const size = 2 ** (30 - level);
7110
+ const west = x * size;
7111
+ const north = y * size;
7112
+ const east = west + size;
7113
+ const south = north + size;
7114
+ add2(vertical, west, "after", { tile, start: north, end: south });
7115
+ add2(vertical, east % world, "before", { tile, start: north, end: south });
7116
+ if (north !== 0)
7117
+ add2(horizontal, north, "after", { tile, start: west, end: east });
7118
+ if (south !== world)
7119
+ add2(horizontal, south, "before", { tile, start: west, end: east });
7120
+ });
7121
+ const seams = [];
7122
+ function match(lines, column) {
7123
+ const beforeEdge = column ? "maxColumn" : "maxRow";
7124
+ const afterEdge = column ? "minColumn" : "minRow";
7125
+ const byStart = (a, b) => a.start - b.start;
7126
+ for (const [line, { before, after }] of lines) {
7127
+ before.sort(byStart);
7128
+ after.sort(byStart);
7129
+ let i = 0;
7130
+ let j = 0;
7131
+ while (i < before.length && j < after.length) {
7132
+ const left = before[i];
7133
+ const right = after[j];
7134
+ const start = Math.max(left.start, right.start);
7135
+ const end = Math.min(left.end, right.end);
7136
+ const leftLevel = cut[left.tile].level;
7137
+ const rightLevel = cut[right.tile].level;
7138
+ if (end > start && leftLevel !== rightLevel) {
7139
+ const leftOwns = leftLevel < rightLevel;
7140
+ const coarse = leftOwns ? left : right;
7141
+ seams.push({
7142
+ a: coarse.tile,
7143
+ edgeA: leftOwns ? beforeEdge : afterEdge,
7144
+ b: leftOwns ? right.tile : left.tile,
7145
+ edgeB: leftOwns ? afterEdge : beforeEdge,
7146
+ ...column && line === 0 ? { offsetBX: leftOwns ? 360 : -360 } : {},
7147
+ options: {
7148
+ rangeA: [
7149
+ (start - coarse.start) / (coarse.end - coarse.start),
7150
+ (end - coarse.start) / (coarse.end - coarse.start)
7151
+ ]
7152
+ }
7153
+ });
7154
+ }
7155
+ if (left.end <= right.end)
7156
+ i++;
7157
+ if (right.end <= left.end)
7158
+ j++;
7159
+ }
7160
+ }
7161
+ }
7162
+ match(vertical, true);
7163
+ match(horizontal, false);
7164
+ const edges2 = ["minColumn", "maxColumn", "minRow", "maxRow"];
7165
+ return seams.sort((a, b) => cut[a.a].level - cut[b.a].level || cut[a.a].y - cut[b.a].y || cut[a.a].x - cut[b.a].x || edges2.indexOf(a.edgeA) - edges2.indexOf(b.edgeA) || a.options.rangeA[0] - b.options.rangeA[0]);
7166
+ }
7167
+
7168
+ // dist/terrain/geographic-poles.js
7169
+ function discoverGeographicTerrainPoles(cut) {
7170
+ function collect(latitude2, edge2) {
7171
+ const incident = [];
7172
+ for (let tile = 0; tile < cut.length; tile++) {
7173
+ const [west, south, east, north] = getGeographicTileBounds(cut[tile]);
7174
+ if ((edge2 === "north" ? north : south) === latitude2)
7175
+ incident.push({ tile, edge: edge2, longitude: [west, east] });
7176
+ }
7177
+ incident.sort((a, b) => a.longitude[0] - b.longitude[0]);
7178
+ const gaps = [];
7179
+ let cursor = -180;
7180
+ for (const { longitude: [west, east] } of incident) {
7181
+ if (west < cursor)
7182
+ throw new Error("Overlapping geographic terrain pole sectors");
7183
+ if (west > cursor)
7184
+ gaps.push([cursor, west]);
7185
+ cursor = east;
7186
+ }
7187
+ if (cursor < 180)
7188
+ gaps.push([cursor, 180]);
7189
+ return { latitude: latitude2, incident, gaps };
7190
+ }
7191
+ return { north: collect(90, "north"), south: collect(-90, "south") };
7192
+ }
7193
+
7194
+ // dist/terrain/sweep-rotation.js
7195
+ function sweepTerrainRotatingPolytope(surface, collider, { pivot, translation, rotation }, { maxWork = 1e5, fractionTolerance = 1e-5 } = {}) {
7196
+ const norm = Math.hypot(...rotation);
7197
+ if (pivot.length !== 3 || translation.length !== 3 || rotation.length !== 4 || !pivot.every(Number.isFinite) || !translation.every(Number.isFinite) || !(norm > 0 && Number.isFinite(norm)) || !Number.isSafeInteger(maxWork) || maxWork < 0 || !(fractionTolerance >= Number.EPSILON && fractionTolerance <= 1))
7198
+ throw new RangeError("Invalid terrain rigid motion");
7199
+ const localPivot = pivot.map((v, i) => v - surface.origin[i]);
7200
+ const offsets = collider.vertices.map((v) => v.map((x2, i) => x2 - pivot[i]));
7201
+ const radius = offsets.reduce((r, v) => Math.max(r, Math.hypot(...v)), 0);
7202
+ const sign2 = rotation[3] < 0 ? -1 : 1;
7203
+ const vectorNorm = Math.hypot(rotation[0], rotation[1], rotation[2]);
7204
+ const angle = 2 * Math.atan2(vectorNorm, Math.abs(rotation[3]));
7205
+ const speed = Math.hypot(...translation) + angle * radius;
7206
+ if (!Number.isFinite(speed))
7207
+ throw new RangeError("Terrain rigid motion overflow");
7208
+ const data = surface.copyData();
7209
+ if (angle === 0) {
7210
+ const result = queryTerrainPolytope(data, surface.origin, collider, translation, maxWork);
7211
+ return result.status === "hit" ? { ...result, lowerFraction: result.fraction } : result;
7212
+ }
7213
+ const [x, y, z] = rotation.slice(0, 3).map((v) => v / vectorNorm * sign2);
7214
+ const zero = [0, 0, 0];
7215
+ let work = 0;
7216
+ const pose = (t) => {
7217
+ const sin = Math.sin(angle * t);
7218
+ const cos = Math.cos(angle * t);
7219
+ return {
7220
+ faces: collider.faces,
7221
+ vertices: offsets.map(([a, b, c]) => {
7222
+ const projection = (x * a + y * b + z * c) * (1 - cos);
7223
+ return [
7224
+ localPivot[0] + translation[0] * t + a * cos + (y * c - z * b) * sin + x * projection,
7225
+ localPivot[1] + translation[1] * t + b * cos + (z * a - x * c) * sin + y * projection,
7226
+ localPivot[2] + translation[2] * t + c * cos + (x * b - y * a) * sin + z * projection
7227
+ ];
7228
+ })
7229
+ };
7230
+ };
7231
+ const probe = (shape, padding = 0) => {
7232
+ if (work >= maxWork)
7233
+ return { status: "incomplete", work: 0 };
7234
+ work++;
7235
+ const result = queryTerrainPolytope(data, zero, shape, zero, maxWork - work, padding);
7236
+ work += result.work;
7237
+ return result;
7238
+ };
7239
+ const initial = probe(pose(0));
7240
+ if (initial.status === "hit")
7241
+ return { ...initial, lowerFraction: 0, work };
7242
+ if (initial.status === "incomplete")
7243
+ return { status: "incomplete", work };
7244
+ let clearUntil = 0;
7245
+ let witness;
7246
+ const pending = [[0, 1]];
7247
+ while (pending.length) {
7248
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
7249
+ return { ...witness, lowerFraction: clearUntil, work };
7250
+ const [lo, hi] = pending.pop();
7251
+ const mid = lo + (hi - lo) / 2;
7252
+ const shape = pose(mid);
7253
+ const padding = speed * Math.max(mid - lo, hi - mid);
7254
+ const expanded = probe(shape, padding + 8 * Number.EPSILON * (radius + padding));
7255
+ if (expanded.status === "miss") {
7256
+ clearUntil = hi;
7257
+ continue;
7258
+ }
7259
+ if (expanded.status === "incomplete")
7260
+ return { status: "incomplete", work };
7261
+ const hit = probe(shape);
7262
+ if (hit.status === "incomplete")
7263
+ return { status: "incomplete", work };
7264
+ if (hit.status === "hit") {
7265
+ witness = { ...hit, fraction: mid };
7266
+ if (mid - clearUntil <= fractionTolerance)
7267
+ return { ...witness, lowerFraction: clearUntil, work };
7268
+ pending.push([lo, mid]);
7269
+ } else if (hi - clearUntil <= fractionTolerance) {
7270
+ const end = (witness == null ? void 0 : witness.fraction) === hi ? witness : probe(pose(hi));
7271
+ if ((end == null ? void 0 : end.status) === "hit")
7272
+ return { ...end, fraction: hi, lowerFraction: clearUntil, work };
7273
+ if (hi - lo <= fractionTolerance / 4)
7274
+ return { status: "incomplete", work };
7275
+ pending.push([mid, hi], [lo, mid]);
7276
+ } else {
7277
+ if (mid === lo || mid === hi || hi - lo <= fractionTolerance / 4)
7278
+ return { status: "incomplete", work };
7279
+ pending.push([mid, hi], [lo, mid]);
7280
+ }
7281
+ }
7282
+ return witness ? { ...witness, lowerFraction: clearUntil, work } : { status: "miss", work };
7283
+ }
7284
+ function sweepTerrainRotatingBox(surface, center, halfExtents, motion, options) {
7285
+ return sweepTerrainRotatingPolytope(surface, createSweepBox(center, halfExtents), motion, options);
7286
+ }
7287
+
7288
+ // dist/terrain/regional-viewshed.js
7289
+ var TerrainRegionalViewStatus = {
7290
+ VISIBLE: 0,
7291
+ BLOCKED: 1,
7292
+ UNKNOWN: 2,
7293
+ MISSING_TARGET: 3,
7294
+ OBSERVER: 4
7295
+ };
7296
+ function createTerrainRegionalViewshed(grid, sample, options) {
7297
+ const { width, height, origin, spacing } = grid;
7298
+ const { observer, sampleStep, radius, targetOffset = 0, maxTargets = 1e5, maxSamples = 4e6 } = options;
7299
+ const count = width * height;
7300
+ if (![width, height, count, maxTargets, maxSamples].every(Number.isSafeInteger) || width < 1 || height < 1 || count > maxTargets || maxSamples < 1 || origin.length !== 2 || spacing.length !== 2 || observer.length !== 3 || ![...origin, ...spacing, ...observer, sampleStep, targetOffset].every(Number.isFinite) || spacing.some((value) => value <= 0) || sampleStep <= 0 || targetOffset < 0 || radius !== void 0 && (!Number.isFinite(radius) || radius <= 0 || observer[2] <= -radius))
7301
+ throw new RangeError("Invalid regional viewshed grid or options");
7302
+ const statuses = new Uint8Array(count);
7303
+ const targetStatuses = new Uint8Array(count);
7304
+ const sampledCoverage = new Uint8Array(count);
7305
+ let samples = 0;
7306
+ function read(x, y) {
7307
+ if (samples >= maxSamples)
7308
+ throw new RangeError("Regional viewshed sample budget exceeded");
7309
+ samples++;
7310
+ const result = sample(x, y);
7311
+ if (!Number.isInteger(result.status) || result.status < 0 || result.status > TerrainSampleStatus.NOT_RESIDENT || result.status === TerrainSampleStatus.VALID && (!Number.isFinite(result.height) || radius !== void 0 && result.height <= -radius))
7312
+ throw new RangeError("Invalid regional viewshed sample");
7313
+ return result;
7314
+ }
7315
+ function sight(distance, elevation) {
7316
+ let rise = elevation - observer[2];
7317
+ let run = distance;
7318
+ if (radius !== void 0) {
7319
+ const theta = distance / radius;
7320
+ const radial = radius + elevation;
7321
+ const halfSine = Math.sin(theta / 2);
7322
+ rise -= radial * (2 * halfSine * halfSine);
7323
+ run = radial * Math.sin(theta);
7324
+ }
7325
+ if (!Number.isFinite(rise) || !Number.isFinite(run) || run <= 0)
7326
+ throw new RangeError("Regional viewshed sight calculation overflow");
7327
+ return [rise, run];
7328
+ }
7329
+ const observerSample = { ...read(observer[0], observer[1]) };
7330
+ const observerValid = observerSample.status === TerrainSampleStatus.VALID;
7331
+ for (let i = 0; i < count; i++) {
7332
+ const x = origin[0] + i % width * spacing[0];
7333
+ const y = origin[1] + Math.floor(i / width) * spacing[1];
7334
+ const dx = x - observer[0];
7335
+ const dy = y - observer[1];
7336
+ const distance = Math.hypot(dx, dy);
7337
+ if (!Number.isFinite(distance) || radius !== void 0 && distance / radius >= Math.PI)
7338
+ throw new RangeError("Regional viewshed distance outside supported range");
7339
+ const target = distance === 0 ? observerSample : read(x, y);
7340
+ targetStatuses[i] = target.status;
7341
+ if (target.status !== TerrainSampleStatus.VALID) {
7342
+ statuses[i] = TerrainRegionalViewStatus.MISSING_TARGET;
7343
+ continue;
7344
+ }
7345
+ if (distance === 0) {
7346
+ statuses[i] = TerrainRegionalViewStatus.OBSERVER;
7347
+ sampledCoverage[i] = 1;
7348
+ continue;
7349
+ }
7350
+ const [targetRise, targetRun] = sight(distance, target.height + targetOffset);
7351
+ const segments = Math.max(1, Math.ceil(distance / sampleStep));
7352
+ if (!Number.isSafeInteger(segments) || segments - 1 > maxSamples - samples)
7353
+ throw new RangeError("Regional viewshed sample budget exceeded");
7354
+ let complete = observerValid;
7355
+ let blocked = observerValid && observerSample.height > observer[2];
7356
+ for (let j = 1; j < segments; j++) {
7357
+ const fraction = j / segments;
7358
+ const station = read(observer[0] + dx * fraction, observer[1] + dy * fraction);
7359
+ if (station.status !== TerrainSampleStatus.VALID) {
7360
+ complete = false;
7361
+ } else if (!blocked) {
7362
+ const [rise, run] = sight(distance * fraction, station.height);
7363
+ blocked = compareTerrainSlopes(rise, run, targetRise, targetRun) >= 0;
7364
+ }
7365
+ }
7366
+ sampledCoverage[i] = complete ? 1 : 0;
7367
+ statuses[i] = blocked ? TerrainRegionalViewStatus.BLOCKED : complete ? TerrainRegionalViewStatus.VISIBLE : TerrainRegionalViewStatus.UNKNOWN;
7368
+ }
7369
+ return { statuses, targetStatuses, sampledCoverage, samples };
7370
+ }
7371
+
7372
+ // dist/terrain/hydrology.js
7373
+ function getTerrainCellMetrics(field) {
7374
+ if (field.registration !== "cell")
7375
+ throw new Error("Terrain cell metrics require cell registration");
7376
+ const [cx, cy] = field.columnStep;
7377
+ const [rx, ry] = field.rowStep;
7378
+ const determinant = cx * ry - cy * rx;
7379
+ const columnLength = Math.hypot(cx, cy);
7380
+ const rowLength = Math.hypot(rx, ry);
7381
+ const area = Math.abs(determinant);
7382
+ if (!(area > 0 && Number.isFinite(area) && Number.isFinite(columnLength + rowLength)))
7383
+ throw new RangeError("Invalid terrain cell geometry");
7384
+ const sign2 = Math.sign(determinant);
7385
+ const east = [sign2 * ry / rowLength, -sign2 * rx / rowLength];
7386
+ const south = [-sign2 * cy / columnLength, sign2 * cx / columnLength];
7387
+ return {
7388
+ area,
7389
+ faceLengths: [rowLength, rowLength, columnLength, columnLength],
7390
+ faceNormals: [[-east[0], -east[1]], east, [-south[0], -south[1]], south]
7391
+ };
7392
+ }
7393
+ function createTerrainDrainage(field, { outlets = [], maxCells = 4194304 } = {}) {
7394
+ const { width, height, columnStep, rowStep } = field;
7395
+ const count = width * height;
7396
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
7397
+ throw new RangeError("Terrain drainage exceeds its cell budget");
7398
+ const { area: cellArea } = getTerrainCellMetrics(field);
7399
+ for (const i of outlets) {
7400
+ if (!Number.isInteger(i) || i < 0 || i >= count || field.getHeight(i % width, Math.floor(i / width)) === void 0)
7401
+ throw new RangeError("Terrain outlet must identify a valid cell");
7402
+ }
7403
+ const { heights, validity } = field.copyData();
7404
+ const receiver = new Int32Array(count).fill(-1);
7405
+ const terminal = new Int32Array(count).fill(-1);
7406
+ const contributingCells = new Uint32Array(count);
7407
+ const incoming = new Uint8Array(count);
7408
+ const queue = new Int32Array(count);
7409
+ const outletSet = new Set(outlets);
7410
+ const offsets = [];
7411
+ for (let dy = -1; dy <= 1; dy++) {
7412
+ for (let dx = -1; dx <= 1; dx++) {
7413
+ if (!dx && !dy)
7414
+ continue;
7415
+ const distance = Math.hypot(dx * columnStep[0] + dy * rowStep[0], dx * columnStep[1] + dy * rowStep[1]);
7416
+ if (!(distance > 0 && Number.isFinite(distance)))
7417
+ throw new RangeError("Invalid terrain neighbor distance");
7418
+ offsets.push({ dx, dy, distance });
7419
+ }
7420
+ }
7421
+ for (let i = 0; i < count; i++) {
7422
+ if (!validity[i])
7423
+ continue;
7424
+ contributingCells[i] = 1;
7425
+ if (outletSet.has(i))
7426
+ continue;
7427
+ const col = i % width;
7428
+ const row = Math.floor(i / width);
7429
+ let steepest = 0;
7430
+ for (const { dx, dy, distance } of offsets) {
7431
+ if (col + dx < 0 || col + dx >= width || row + dy < 0 || row + dy >= height)
7432
+ continue;
7433
+ const j = i + dx + dy * width;
7434
+ if (!validity[j] || heights[j] >= heights[i])
7435
+ continue;
7436
+ if (dx && dy && (!validity[i + dx] || !validity[i + dy * width]))
7437
+ continue;
7438
+ const slope = (heights[i] - heights[j]) / distance;
7439
+ if (!Number.isFinite(slope) || slope === 0)
7440
+ throw new RangeError("Terrain drainage slope is outside the representable range");
7441
+ if (slope > steepest) {
7442
+ steepest = slope;
7443
+ receiver[i] = j;
7444
+ }
7445
+ }
7446
+ if (receiver[i] >= 0)
7447
+ incoming[receiver[i]]++;
7448
+ }
7449
+ let end = 0;
7450
+ for (let i = 0; i < count; i++)
7451
+ if (validity[i] && !incoming[i])
7452
+ queue[end++] = i;
7453
+ for (let cursor = 0; cursor < end; cursor++) {
7454
+ const i = queue[cursor];
7455
+ const next = receiver[i];
7456
+ if (next < 0)
7457
+ continue;
7458
+ contributingCells[next] += contributingCells[i];
7459
+ if (--incoming[next] === 0)
7460
+ queue[end++] = next;
7461
+ }
7462
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
7463
+ const i = queue[cursor];
7464
+ const next = receiver[i];
7465
+ terminal[i] = next < 0 ? i : terminal[next];
7466
+ }
7467
+ return { receiver, terminal, contributingCells, cellArea };
7468
+ }
7469
+
7470
+ // dist/terrain/depression-fill.js
7471
+ function fillTerrainDepressions(field, { outlets, maxCells = 4194304 }) {
7472
+ if (field.registration !== "cell")
7473
+ throw new Error("Terrain depression fill requires cell registration");
7474
+ const { width, height } = field;
7475
+ const count = width * height;
7476
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
7477
+ throw new RangeError("Terrain depression fill exceeds its cell budget");
7478
+ if (!outlets.length)
7479
+ throw new RangeError("Terrain depression fill requires an outlet");
7480
+ for (const i of outlets) {
7481
+ if (!Number.isInteger(i) || i < 0 || i >= count || field.getHeight(i % width, Math.floor(i / width)) === void 0)
7482
+ throw new RangeError("Terrain outlet must identify a valid cell");
7483
+ }
7484
+ const { heights, validity } = field.copyData();
7485
+ const receiver = new Int32Array(count).fill(-2);
7486
+ const heap = new Int32Array(count);
7487
+ let size = 0;
7488
+ let disconnectedCells = field.validCount;
7489
+ const before = (a, b) => heights[a] < heights[b] || heights[a] === heights[b] && a < b;
7490
+ function push(cell) {
7491
+ let slot = size++;
7492
+ while (slot > 0) {
7493
+ const parent = Math.floor((slot - 1) / 2);
7494
+ if (!before(cell, heap[parent]))
7495
+ break;
7496
+ heap[slot] = heap[parent];
7497
+ slot = parent;
7498
+ }
7499
+ heap[slot] = cell;
7500
+ }
7501
+ function pop() {
7502
+ const first = heap[0];
7503
+ const tail = heap[--size];
7504
+ let slot = 0;
7505
+ let child = 1;
7506
+ while (child < size) {
7507
+ if (child + 1 < size && before(heap[child + 1], heap[child]))
7508
+ child++;
7509
+ if (!before(heap[child], tail))
7510
+ break;
7511
+ heap[slot] = heap[child];
7512
+ slot = child;
7513
+ child = slot * 2 + 1;
7514
+ }
7515
+ if (size)
7516
+ heap[slot] = tail;
7517
+ return first;
7518
+ }
7519
+ function visit(cell, parent) {
7520
+ if (!validity[cell] || receiver[cell] !== -2)
7521
+ return;
7522
+ receiver[cell] = parent;
7523
+ disconnectedCells--;
7524
+ if (parent >= 0)
7525
+ heights[cell] = Math.max(heights[cell], heights[parent]);
7526
+ push(cell);
7527
+ }
7528
+ for (const outlet of outlets)
7529
+ visit(outlet, -1);
7530
+ while (size) {
7531
+ const cell = pop();
7532
+ const column = cell % width;
7533
+ if (column > 0)
7534
+ visit(cell - 1, cell);
7535
+ if (column + 1 < width)
7536
+ visit(cell + 1, cell);
7537
+ if (cell >= width)
7538
+ visit(cell - width, cell);
7539
+ if (cell < count - width)
7540
+ visit(cell + width, cell);
7541
+ }
7542
+ return {
7543
+ field: new HeightField({
7544
+ width,
7545
+ height,
7546
+ heights,
7547
+ validity,
7548
+ origin: field.origin,
7549
+ columnStep: field.columnStep,
7550
+ rowStep: field.rowStep,
7551
+ registration: field.registration,
7552
+ diagonal: field.diagonal,
7553
+ heightReference: field.heightReference
7554
+ }),
7555
+ receiver,
7556
+ disconnectedCells
7557
+ };
7558
+ }
7559
+
7560
+ // dist/terrain/cutout-region.js
7561
+ var PLAN = /* @__PURE__ */ Symbol.for("@math.gl/geospatial/terrain-cutout-polygons/v1");
7562
+ function createTerrainCutoutPlan(plan) {
7563
+ return Object.freeze({ [PLAN]: Object.freeze(plan) });
7564
+ }
7565
+ function getTerrainCutoutPlan(region) {
7566
+ if (Array.isArray(region))
7567
+ return void 0;
7568
+ const plan = region == null ? void 0 : region[PLAN];
7569
+ if (!plan)
7570
+ throw new RangeError("Invalid prepared terrain cutout polygons");
7571
+ return plan;
7572
+ }
7573
+ function copyTerrainCutoutRegion(region) {
7574
+ return getTerrainCutoutPlan(region) ? region : region.map((p) => [p[0], p[1]]);
7575
+ }
7576
+ function sameTerrainCutoutRegion(a, b) {
7577
+ if (getTerrainCutoutPlan(a) || getTerrainCutoutPlan(b))
7578
+ return a === b;
7579
+ const aa = a, bb = b;
7580
+ return aa.length === bb.length && aa.every((p, i) => bb[i].length === 2 && p[0] === bb[i][0] && p[1] === bb[i][1]);
7581
+ }
7582
+
7583
+ // dist/terrain/mesh-cutout.js
7584
+ function splitTerrainMesh(mesh, polygon2, { maxWork = 4e6, maxVertices = 5e5, maxTriangles = 5e5 } = {}) {
7585
+ if (![maxWork, maxVertices, maxTriangles].every((n) => Number.isSafeInteger(n) && n >= 0) || maxVertices > 4294967295 || maxTriangles > 4294967295 || !(mesh.positions instanceof Float32Array || mesh.positions instanceof Float64Array) || !(mesh.indices instanceof Uint16Array || mesh.indices instanceof Uint32Array) || mesh.positions.length % 3 || mesh.indices.length % 3 || mesh.positions.length / 3 > maxVertices || mesh.indices.length / 3 > maxTriangles || !mesh.positions.every(Number.isFinite))
7586
+ throw new RangeError("Invalid terrain cutout mesh or capacity");
7587
+ let work = 0;
7588
+ function charge(amount) {
7589
+ work += amount;
7590
+ if (work > maxWork)
7591
+ throw new RangeError("Terrain cutout work budget exceeded");
7592
+ }
7593
+ const prepared = getTerrainCutoutPlan(polygon2);
7594
+ const ring = prepared ? void 0 : validatePolygon(polygon2, charge);
7595
+ const lines = (prepared == null ? void 0 : prepared.lines) ?? ring.map((p, i) => [p, ring[(i + 1) % ring.length]]);
7596
+ const vertices = [];
7597
+ for (let i = 0; i < mesh.positions.length; i += 3)
7598
+ vertices.push([mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2]]);
7599
+ const faces = [];
7600
+ for (let i = 0; i < mesh.indices.length; i += 3) {
7601
+ const face = [mesh.indices[i], mesh.indices[i + 1], mesh.indices[i + 2]];
7602
+ if (face.some((id) => id >= vertices.length))
7603
+ throw new RangeError("Invalid terrain cutout index");
7604
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
7605
+ faces.push(face);
7606
+ }
7607
+ validateTopology(vertices, faces, charge);
7608
+ const patch = createPiece();
7609
+ const remainder = createPiece();
7610
+ const intersections = lines.map(() => /* @__PURE__ */ new Map());
7611
+ let fragmentCount = 0;
7612
+ function addVertex(vertex) {
7613
+ if (vertices.length >= maxVertices || !vertex.every(Number.isFinite))
7614
+ throw new RangeError("Terrain cutout vertex budget or coordinate range exceeded");
7615
+ return vertices.push(vertex) - 1;
7616
+ }
7617
+ function intersection(a, b, da, db, line) {
7618
+ const key2 = edgeKey2(a, b);
7619
+ const cache = intersections[line];
7620
+ const saved = cache.get(key2);
7621
+ if (saved !== void 0)
7622
+ return saved;
7623
+ const pa = vertices[a], pb = vertices[b];
7624
+ if (pa[0] > pb[0] || pa[0] === pb[0] && (pa[1] > pb[1] || pa[1] === pb[1] && pa[2] > pb[2])) {
7625
+ [a, b] = [b, a];
7626
+ [da, db] = [db, da];
7627
+ }
7628
+ const t = Math.abs(da) / (Math.abs(da) + Math.abs(db));
7629
+ if (!(t > 0 && t < 1))
7630
+ throw new RangeError("Unrepresentable terrain cut intersection");
7631
+ const u = vertices[a];
7632
+ const v = vertices[b];
7633
+ const id = addVertex([
7634
+ u[0] + t * (v[0] - u[0]),
7635
+ u[1] + t * (v[1] - u[1]),
7636
+ u[2] + t * (v[2] - u[2])
7637
+ ]);
7638
+ cache.set(key2, id);
7639
+ return id;
7640
+ }
7641
+ for (let source = 0; source < faces.length; source++) {
7642
+ let fragments = [{ ids: faces[source], inside: true }];
7643
+ for (let line = 0; line < lines.length; line++) {
7644
+ const next = [];
7645
+ const [a, b] = lines[line];
7646
+ for (const fragment of fragments) {
7647
+ const { ids } = fragment;
7648
+ charge(ids.length);
7649
+ const distances = ids.map((id) => cross3(a, b, vertices[id]));
7650
+ if (distances.some((d) => !Number.isFinite(d)))
7651
+ throw new RangeError("Invalid terrain cut coordinates");
7652
+ if (!distances.some((d) => d < 0))
7653
+ next.push(fragment);
7654
+ else if (!distances.some((d) => d > 0))
7655
+ next.push({ ...fragment, inside: false });
7656
+ else {
7657
+ const positive = [];
7658
+ const negative = [];
7659
+ for (let i = 0; i < ids.length; i++) {
7660
+ const j = (i + 1) % ids.length;
7661
+ const d = distances[i];
7662
+ const e = distances[j];
7663
+ if (d >= 0)
7664
+ positive.push(ids[i]);
7665
+ if (d <= 0)
7666
+ negative.push(ids[i]);
7667
+ if (d < 0 && e > 0 || d > 0 && e < 0) {
7668
+ const id = intersection(ids[i], ids[j], d, e, line);
7669
+ positive.push(id);
7670
+ negative.push(id);
7671
+ }
7672
+ }
7673
+ next.push({ ids: positive, inside: fragment.inside }, { ids: negative, inside: false });
7674
+ }
7675
+ if (fragmentCount + next.length > maxTriangles)
7676
+ throw new RangeError("Terrain cutout fragment budget exceeded");
7677
+ }
7678
+ fragments = next;
7679
+ }
7680
+ fragmentCount += fragments.length;
7681
+ for (const { ids, inside } of fragments) {
7682
+ let center;
7683
+ if (prepared || ids.length > 3) {
7684
+ center = [...vertices[ids[0]]];
7685
+ for (const id of ids) {
7686
+ for (let k = 0; k < 3; k++)
7687
+ center[k] += (vertices[id][k] - vertices[ids[0]][k]) / ids.length;
7688
+ }
7689
+ }
7690
+ const polygonIndex = prepared ? prepared.classify([center[0], center[1]], charge) : inside ? 0 : -1;
7691
+ const piece = polygonIndex >= 0 ? patch : remainder;
7692
+ if (ids.length === 3)
7693
+ emit(piece, ids, source, polygonIndex);
7694
+ else {
7695
+ const hub = addVertex(center);
7696
+ for (let i = 0; i < ids.length; i++)
7697
+ emit(piece, [ids[i], ids[(i + 1) % ids.length], hub], source, polygonIndex);
7698
+ }
7699
+ }
7700
+ }
7701
+ function emit(piece, face, source, polygonIndex) {
7702
+ if (patch.sourceFaces.length + remainder.sourceFaces.length >= maxTriangles)
7703
+ throw new RangeError("Terrain cutout triangle budget exceeded");
7704
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
7705
+ const [a, b, c] = faces[source].map((id) => vertices[id]);
7706
+ const area = cross3(a, b, c);
7707
+ for (let i = 0; i < 3; i++) {
7708
+ const id = face[i];
7709
+ if (!piece.ids.has(id)) {
7710
+ if (patch.ids.size + remainder.ids.size >= maxVertices)
7711
+ throw new RangeError("Terrain cutout output vertex budget exceeded");
7712
+ piece.ids.set(id, piece.ids.size);
7713
+ const p = vertices[id];
7714
+ piece.positions.push(...p);
7715
+ piece.sourceTriangles.push(source);
7716
+ piece.sourceWeights.push(cross3(b, c, p) / area, cross3(c, a, p) / area, cross3(a, b, p) / area);
7717
+ }
7718
+ piece.indices.push(piece.ids.get(id));
7719
+ addEdge(piece.boundary, id, face[(i + 1) % 3], polygonIndex);
7720
+ }
7721
+ piece.sourceFaces.push(source);
7722
+ piece.polygonIndices.push(polygonIndex);
7723
+ }
7724
+ for (const [key2, inside] of patch.boundary) {
7725
+ const outside = remainder.boundary.get(key2);
7726
+ if (!outside)
7727
+ continue;
7728
+ const [a, b] = inside.edge;
7729
+ if (inside.count !== 1 || outside.count !== 1 || outside.edge[0] !== b)
7730
+ throw new Error("Nonconforming terrain cut boundary");
7731
+ patch.cutEdges.push(patch.ids.get(a), patch.ids.get(b));
7732
+ remainder.cutEdges.push(remainder.ids.get(b), remainder.ids.get(a));
7733
+ patch.cutPolygonIndices.push(inside.polygon);
7734
+ remainder.cutPolygonIndices.push(inside.polygon);
7735
+ }
7736
+ return { patch: finish(patch), remainder: finish(remainder) };
7737
+ }
7738
+ function validatePolygon(polygon2, charge) {
7739
+ if (polygon2.length < 3 || polygon2.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
7740
+ throw new RangeError("Invalid terrain cut polygon");
7741
+ const ring = [...polygon2];
7742
+ const orientation2 = cross3(ring[0], ring[1], ring[2]);
7743
+ if (orientation2 < 0)
7744
+ ring.reverse();
7745
+ for (let i = 0; i < ring.length; i++) {
7746
+ charge(ring.length);
7747
+ const j = (i + 1) % ring.length;
7748
+ for (let k = 0; k < ring.length; k++) {
7749
+ if (k === i || k === j)
7750
+ continue;
7751
+ const area = cross3(ring[i], ring[j], ring[k]);
7752
+ if (!(area > 0 && Number.isFinite(area)))
7753
+ throw new RangeError("Terrain cut polygon must be strictly convex");
7754
+ }
7755
+ }
7756
+ return ring;
7757
+ }
7758
+ function checkTriangle(a, b, c) {
7759
+ const area = cross3(a, b, c);
7760
+ const scale = Math.hypot(b[0] - a[0], b[1] - a[1]) * Math.hypot(c[0] - a[0], c[1] - a[1]);
7761
+ if (!(area > Number.EPSILON * scale && Number.isFinite(area)))
7762
+ throw new RangeError("Terrain cut requires upward nondegenerate XY triangles");
7763
+ }
7764
+ function validateTopology(vertices, faces, charge) {
7765
+ const edges2 = /* @__PURE__ */ new Map();
7766
+ const boxes = faces.map((face) => {
7767
+ for (let i = 0; i < 3; i++)
7768
+ addEdge(edges2, face[i], face[(i + 1) % 3]);
7769
+ const points = face.map((id) => vertices[id]);
7770
+ return {
7771
+ face,
7772
+ points,
7773
+ low: Math.min(...points.map((p) => p[0])),
7774
+ high: Math.max(...points.map((p) => p[0])),
7775
+ minY: Math.min(...points.map((p) => p[1])),
7776
+ maxY: Math.max(...points.map((p) => p[1]))
7777
+ };
7778
+ }).sort((a, b) => a.low - b.low);
7779
+ for (let i = 0; i < boxes.length; i++) {
7780
+ const a = boxes[i];
7781
+ for (let j = i + 1; j < boxes.length && boxes[j].low <= a.high; j++) {
7782
+ charge(1);
7783
+ const b = boxes[j];
7784
+ if (a.maxY < b.minY || b.maxY < a.minY)
7785
+ continue;
7786
+ if (!separates(a.points, b.points) && !separates(b.points, a.points))
7787
+ throw new RangeError("Terrain cut input has overlapping XY triangles");
7788
+ checkJunctions(a.face, b.face, vertices);
7789
+ checkJunctions(b.face, a.face, vertices);
7790
+ }
7791
+ }
7792
+ }
7793
+ function separates(a, b) {
7794
+ return a.some((p, i) => b.every((q) => cross3(p, a[(i + 1) % 3], q) <= 0));
7795
+ }
7796
+ function checkJunctions(a, b, vertices) {
7797
+ for (let i = 0; i < 3; i++) {
7798
+ const u = vertices[a[i]];
7799
+ const v = vertices[a[(i + 1) % 3]];
7800
+ const overlaps2 = b.filter((id) => {
7801
+ const p = vertices[id];
7802
+ if (cross3(u, v, p) !== 0)
7803
+ return false;
7804
+ const axis = Math.abs(v[0] - u[0]) >= Math.abs(v[1] - u[1]) ? 0 : 1;
7805
+ const low = Math.min(u[axis], v[axis]);
7806
+ const high = Math.max(u[axis], v[axis]);
7807
+ if (p[axis] > low && p[axis] < high)
7808
+ throw new RangeError("Terrain cut input has a T-junction");
7809
+ return p[axis] >= low && p[axis] <= high;
7810
+ });
7811
+ if (overlaps2.length >= 2 && (!overlaps2.includes(a[i]) || !overlaps2.includes(a[(i + 1) % 3])))
7812
+ throw new RangeError("Terrain cut input has an unwelded shared edge");
7813
+ }
7814
+ }
7815
+ function addEdge(edges2, a, b, polygon2 = -1) {
7816
+ const key2 = edgeKey2(a, b);
7817
+ const entry = edges2.get(key2);
7818
+ if (!entry)
7819
+ edges2.set(key2, { edge: [a, b], count: 1, polygon: polygon2 });
7820
+ else {
7821
+ if (entry.count !== 1 || entry.edge[0] !== b)
7822
+ throw new RangeError("Terrain cut mesh has inconsistent or nonmanifold edges");
7823
+ entry.count++;
7824
+ }
7825
+ }
7826
+ function edgeKey2(a, b) {
7827
+ return a < b ? a + "," + b : b + "," + a;
7828
+ }
7829
+ function cross3(a, b, c) {
7830
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
7831
+ }
7832
+ function createPiece() {
7833
+ return {
7834
+ ids: /* @__PURE__ */ new Map(),
7835
+ positions: [],
7836
+ indices: [],
7837
+ sourceTriangles: [],
7838
+ sourceWeights: [],
7839
+ sourceFaces: [],
7840
+ boundary: /* @__PURE__ */ new Map(),
7841
+ cutEdges: [],
7842
+ polygonIndices: [],
7843
+ cutPolygonIndices: []
7844
+ };
7845
+ }
7846
+ function finish(piece) {
7847
+ return {
7848
+ positions: Float64Array.from(piece.positions),
7849
+ indices: Uint32Array.from(piece.indices),
7850
+ sourceTriangles: Uint32Array.from(piece.sourceTriangles),
7851
+ sourceWeights: Float64Array.from(piece.sourceWeights),
7852
+ sourceFaces: Uint32Array.from(piece.sourceFaces),
7853
+ cutEdges: Uint32Array.from(piece.cutEdges),
7854
+ polygonIndices: Uint32Array.from(piece.polygonIndices),
7855
+ cutPolygonIndices: Uint32Array.from(piece.cutPolygonIndices)
7856
+ };
7857
+ }
7858
+ function validateTerrainCutoutTopology(mesh, maxWork) {
7859
+ const vertices = [];
7860
+ const faces = [];
7861
+ for (let i = 0; i < mesh.positions.length; i += 3)
7862
+ vertices.push([mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2]]);
7863
+ for (let i = 0; i < mesh.indices.length; i += 3)
7864
+ faces.push([mesh.indices[i], mesh.indices[i + 1], mesh.indices[i + 2]]);
7865
+ let work = 0;
7866
+ validateTopology(vertices, faces, (amount) => {
7867
+ work += amount;
7868
+ if (work > maxWork)
7869
+ throw new RangeError("Terrain cutout topology work budget exceeded");
7870
+ });
7871
+ }
7872
+
7873
+ // dist/terrain/cutout-skirts.js
7874
+ function createTerrainCutoutSkirts(cutout, { lift = 0, patch, remainder }) {
7875
+ if (!Number.isFinite(lift))
7876
+ throw new RangeError("Invalid terrain cutout lift");
7877
+ const positions = cutout.patch.positions.slice();
7878
+ for (let i = 2; i < positions.length; i += 3) {
7879
+ positions[i] += lift;
7880
+ if (!Number.isFinite(positions[i]))
7881
+ throw new RangeError("Terrain cutout lift overflow");
7882
+ }
7883
+ return {
7884
+ patch: skirtPiece({ ...cutout.patch, positions }, patch),
7885
+ remainder: skirtPiece(cutout.remainder, remainder)
7886
+ };
7887
+ }
7888
+ function skirtPiece(surface, options) {
7889
+ if (!surface.cutEdges.length)
7890
+ return { surface };
7891
+ return {
7892
+ surface,
7893
+ skirt: createTerrainSkirt(surface, { ...options, edges: surface.cutEdges })
7894
+ };
7895
+ }
7896
+
7897
+ // dist/terrain/watershed-accumulation.js
7898
+ function accumulateTerrainWatersheds(receiver, { maxCells = 4194304 } = {}) {
7899
+ const count = receiver.length;
7900
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
7901
+ throw new RangeError("Terrain watershed accumulation exceeds its cell budget");
7902
+ const incoming = new Uint32Array(count);
7903
+ const contributingCells = new Uint32Array(count);
7904
+ const terminal = new Int32Array(count).fill(-1);
7905
+ const queue = new Int32Array(count);
7906
+ let active = 0;
7907
+ for (let i = 0; i < count; i++) {
7908
+ const next = receiver[i];
7909
+ if (next === -2)
7910
+ continue;
7911
+ if (next < -1 || next >= count || next >= 0 && receiver[next] === -2)
7912
+ throw new RangeError("Invalid terrain watershed receiver");
7913
+ active++;
7914
+ contributingCells[i] = 1;
7915
+ if (next >= 0)
7916
+ incoming[next]++;
7917
+ }
7918
+ let end = 0;
7919
+ for (let i = 0; i < count; i++) {
7920
+ if (contributingCells[i] && !incoming[i])
7921
+ queue[end++] = i;
7922
+ }
7923
+ for (let cursor = 0; cursor < end; cursor++) {
7924
+ const i = queue[cursor];
7925
+ const next = receiver[i];
7926
+ if (next < 0)
7927
+ continue;
7928
+ contributingCells[next] += contributingCells[i];
7929
+ if (--incoming[next] === 0)
7930
+ queue[end++] = next;
7931
+ }
7932
+ if (end !== active)
7933
+ throw new RangeError("Terrain watershed receiver graph contains a cycle");
7934
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
7935
+ const i = queue[cursor];
7936
+ const next = receiver[i];
7937
+ terminal[i] = next < 0 ? i : terminal[next];
7938
+ }
7939
+ return { terminal, contributingCells };
7940
+ }
7941
+
7942
+ // dist/terrain/tile-cutout.js
7943
+ function splitTerrainMeshTiles(tiles, polygon2, options = {}) {
7944
+ const assembled = assembleTerrainCutoutTiles(tiles, options);
7945
+ return {
7946
+ ...splitTerrainMesh(assembled.mesh, polygon2, { ...options, maxWork: assembled.remainingWork }),
7947
+ sourceTiles: assembled.sourceTiles,
7948
+ sourceTileFaces: assembled.sourceTileFaces
7949
+ };
7950
+ }
7951
+ function assembleTerrainCutoutTiles(tiles, options = {}) {
7952
+ const maxVertices = options.maxVertices ?? 5e5;
7953
+ const maxTriangles = options.maxTriangles ?? 5e5;
7954
+ const maxWork = options.maxWork ?? 4e6;
7955
+ if (![maxVertices, maxTriangles, maxWork].every((n) => Number.isSafeInteger(n) && n >= 0) || maxVertices > 4294967295 || maxTriangles > 4294967295)
7956
+ throw new RangeError("Invalid terrain tile cutout limits");
7957
+ let vertexCount = 0;
7958
+ let faceCount = 0;
7959
+ let work = 0;
7960
+ for (const tile of tiles) {
7961
+ if (!(tile.positions instanceof Float32Array || tile.positions instanceof Float64Array) || !(tile.indices instanceof Uint16Array || tile.indices instanceof Uint32Array) || tile.positions.length % 3 || tile.indices.length % 3)
7962
+ throw new RangeError("Invalid terrain tile cutout mesh");
7963
+ vertexCount += tile.positions.length / 3;
7964
+ faceCount += tile.indices.length / 3;
7965
+ work += 1 + tile.positions.length / 3 + tile.indices.length;
7966
+ if (vertexCount > maxVertices || faceCount > maxTriangles || work > maxWork)
7967
+ throw new RangeError("Terrain tile cutout input budget exceeded");
7968
+ }
7969
+ const positions = new Float64Array(vertexCount * 3);
7970
+ const indices = new Uint32Array(faceCount * 3);
7971
+ const sourceTiles = new Uint32Array(faceCount);
7972
+ const sourceTileFaces = new Uint32Array(faceCount);
7973
+ const vertices = /* @__PURE__ */ new Map();
7974
+ let vertexOffset = 0;
7975
+ let faceOffset = 0;
7976
+ for (let tileIndex = 0; tileIndex < tiles.length; tileIndex++) {
7977
+ const tile = tiles[tileIndex];
7978
+ const remap = new Uint32Array(tile.positions.length / 3);
7979
+ for (let i = 0; i < remap.length; i++) {
7980
+ const x = tile.positions[i * 3];
7981
+ const y = tile.positions[i * 3 + 1];
7982
+ const z = tile.positions[i * 3 + 2];
7983
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z))
7984
+ throw new RangeError("Invalid terrain tile cutout coordinate");
7985
+ const key2 = `${x},${y},${z}`;
7986
+ let id = vertices.get(key2);
7987
+ if (id === void 0) {
7988
+ id = vertexOffset++;
7989
+ vertices.set(key2, id);
7990
+ positions[id * 3] = x;
7991
+ positions[id * 3 + 1] = y;
7992
+ positions[id * 3 + 2] = z;
7993
+ }
7994
+ remap[i] = id;
7995
+ }
7996
+ for (let i = 0; i < tile.indices.length; i++) {
7997
+ const id = tile.indices[i];
7998
+ if (id >= remap.length)
7999
+ throw new RangeError("Invalid terrain tile cutout index");
8000
+ indices[faceOffset * 3 + i] = remap[id];
8001
+ }
8002
+ for (let i = 0; i < tile.indices.length / 3; i++) {
8003
+ sourceTiles[faceOffset + i] = tileIndex;
8004
+ sourceTileFaces[faceOffset + i] = i;
8005
+ }
8006
+ faceOffset += tile.indices.length / 3;
8007
+ }
8008
+ return {
8009
+ mesh: { positions: positions.subarray(0, vertexOffset * 3), indices },
8010
+ sourceTiles,
8011
+ sourceTileFaces,
8012
+ remainingWork: maxWork - work
8013
+ };
8014
+ }
8015
+
8016
+ // dist/terrain/tile-cutout-update.js
8017
+ var CACHE = /* @__PURE__ */ Symbol("terrain-cutout-cache");
8018
+ function updateTerrainTileCutouts(residents, polygon2, previous, options = {}) {
8019
+ const limits = {
8020
+ maxTiles: options.maxTiles ?? 512,
8021
+ maxPairChecks: options.maxPairChecks ?? 131072,
8022
+ maxBoundaryEdges: options.maxBoundaryEdges ?? 1e6,
8023
+ maxWork: options.maxWork ?? 4e6,
8024
+ maxVertices: options.maxVertices ?? 5e5,
8025
+ maxTriangles: options.maxTriangles ?? 5e5
8026
+ };
8027
+ if (Object.values(limits).some((n) => !Number.isSafeInteger(n) || n < 0) || limits.maxVertices > 4294967295 || limits.maxTriangles > 4294967295 || residents.length > limits.maxTiles)
8028
+ throw new RangeError("Invalid terrain cutout update limits");
8029
+ const prior = previous == null ? void 0 : previous[CACHE];
8030
+ const compatible = prior && sameTerrainCutoutRegion(prior.polygon, polygon2) && Object.keys(limits).every((key2) => prior.options[key2] === limits[key2]);
8031
+ if (!compatible)
8032
+ splitTerrainMesh({ positions: new Float64Array(), indices: new Uint32Array() }, polygon2, limits);
8033
+ const entries = /* @__PURE__ */ new Map();
8034
+ const rebuilt = [];
8035
+ let boundaryCount = 0;
8036
+ for (const resident of residents) {
8037
+ if (!resident.id || typeof resident.id !== "string" || entries.has(resident.id) || !Number.isSafeInteger(resident.revision) || resident.revision < 0)
8038
+ throw new RangeError("Invalid or duplicate terrain cutout resident");
8039
+ const old = compatible ? prior.entries.get(resident.id) : void 0;
8040
+ let entry;
8041
+ if (old && old.resident.mesh === resident.mesh && old.resident.revision === resident.revision)
8042
+ entry = old;
8043
+ else {
8044
+ const split = splitTerrainMesh(resident.mesh, polygon2, limits);
8045
+ const edges2 = [...boundaryEdges(split.patch, 0), ...boundaryEdges(split.remainder, 1)];
8046
+ const bounds2 = [Infinity, Infinity, -Infinity, -Infinity];
8047
+ for (const id of resident.mesh.indices) {
8048
+ const x = resident.mesh.positions[id * 3], y = resident.mesh.positions[id * 3 + 1];
8049
+ bounds2[0] = Math.min(bounds2[0], x);
8050
+ bounds2[1] = Math.min(bounds2[1], y);
8051
+ bounds2[2] = Math.max(bounds2[2], x);
8052
+ bounds2[3] = Math.max(bounds2[3], y);
8053
+ }
8054
+ entry = { resident: { ...resident }, split, displayed: split, bounds: bounds2, edges: edges2 };
8055
+ rebuilt.push(resident.id);
8056
+ }
8057
+ boundaryCount += entry.edges.length;
8058
+ if (boundaryCount > limits.maxBoundaryEdges)
8059
+ throw new RangeError("Terrain cutout boundary budget exceeded");
8060
+ entries.set(resident.id, entry);
8061
+ }
8062
+ const values = [...entries.values()];
8063
+ let pairs = 0;
8064
+ for (let i = 0; i < values.length; i++)
8065
+ for (let j = i + 1; j < values.length; j++) {
8066
+ if (++pairs > limits.maxPairChecks)
8067
+ throw new RangeError("Terrain cutout pair budget exceeded");
8068
+ const a = values[i], b = values[j];
8069
+ if (a.bounds[2] < b.bounds[0] || b.bounds[2] < a.bounds[0] || a.bounds[3] < b.bounds[1] || b.bounds[3] < a.bounds[1])
8070
+ continue;
8071
+ if (compatible && prior.entries.get(a.resident.id) === a && prior.entries.get(b.resident.id) === b)
8072
+ continue;
8073
+ const combined = assembleTerrainCutoutTiles([a.resident.mesh, b.resident.mesh], limits);
8074
+ validateTerrainCutoutTopology(combined.mesh, combined.remainingWork);
8075
+ }
8076
+ const boundaries = /* @__PURE__ */ new Map();
8077
+ const cutKeys = /* @__PURE__ */ new Map();
8078
+ for (let tile = 0; tile < values.length; tile++)
8079
+ for (const edge2 of values[tile].edges) {
8080
+ const other = boundaries.get(edge2.key);
8081
+ if (!other) {
8082
+ boundaries.set(edge2.key, { edge: edge2, paired: false });
8083
+ continue;
8084
+ }
8085
+ if (other.paired || other.edge.start !== edge2.end || other.edge.end !== edge2.start)
8086
+ throw new RangeError("Nonconforming terrain cutout tile boundary");
8087
+ other.paired = true;
8088
+ if (other.edge.side !== edge2.side) {
8089
+ cutKeys.set(edge2.key, edge2.side === 0 ? edge2.polygon : other.edge.polygon);
8090
+ }
8091
+ }
8092
+ const tiles = /* @__PURE__ */ new Map();
8093
+ const changed = [];
8094
+ for (let i = 0; i < values.length; i++) {
8095
+ const entry = values[i];
8096
+ const old = prior == null ? void 0 : prior.entries.get(entry.resident.id);
8097
+ const cuts = [[], []];
8098
+ const polygons = [[], []];
8099
+ for (const edge2 of entry.edges) {
8100
+ const polygonIndex = cutKeys.get(edge2.key);
8101
+ if (polygonIndex !== void 0) {
8102
+ cuts[edge2.side].push(edge2.a, edge2.b);
8103
+ polygons[edge2.side].push(polygonIndex);
8104
+ }
8105
+ }
8106
+ const patch = withEdges(entry.split.patch, cuts[0], polygons[0], old == null ? void 0 : old.displayed.patch);
8107
+ const remainder = withEdges(entry.split.remainder, cuts[1], polygons[1], old == null ? void 0 : old.displayed.remainder);
8108
+ const displayed = old && patch === old.displayed.patch && remainder === old.displayed.remainder ? old.displayed : { patch, remainder };
8109
+ if (displayed !== (old == null ? void 0 : old.displayed))
8110
+ changed.push(entry.resident.id);
8111
+ entries.set(entry.resident.id, displayed === entry.displayed ? entry : { ...entry, displayed });
8112
+ tiles.set(entry.resident.id, displayed);
8113
+ }
8114
+ return {
8115
+ cache: { [CACHE]: { polygon: copyTerrainCutoutRegion(polygon2), options: limits, entries } },
8116
+ tiles,
8117
+ changed,
8118
+ rebuilt,
8119
+ removed: prior ? [...prior.entries.keys()].filter((id) => !entries.has(id)) : []
8120
+ };
8121
+ }
8122
+ function withEdges(piece, edges2, polygons, old) {
8123
+ const same = old && old.positions === piece.positions && old.cutEdges.length === edges2.length && old.cutEdges.every((id, i) => id === edges2[i]) && old.cutPolygonIndices.every((id, i) => id === polygons[i]);
8124
+ return same ? old : { ...piece, cutEdges: Uint32Array.from(edges2), cutPolygonIndices: Uint32Array.from(polygons) };
8125
+ }
8126
+ function boundaryEdges(piece, side) {
8127
+ const edges2 = /* @__PURE__ */ new Map();
8128
+ for (let i = 0; i < piece.indices.length; i += 3)
8129
+ for (let j = 0; j < 3; j++) {
8130
+ const a = piece.indices[i + j], b = piece.indices[i + (j + 1) % 3];
8131
+ const key2 = a < b ? `${a},${b}` : `${b},${a}`;
8132
+ const old = edges2.get(key2);
8133
+ if (old)
8134
+ old.count++;
8135
+ else
8136
+ edges2.set(key2, { a, b, count: 1, polygon: piece.polygonIndices[i / 3] });
8137
+ }
8138
+ const result = [];
8139
+ const point = (id) => `${piece.positions[id * 3]},${piece.positions[id * 3 + 1]},${piece.positions[id * 3 + 2]}`;
8140
+ for (const { a, b, count, polygon: polygon2 } of edges2.values())
8141
+ if (count === 1) {
8142
+ const start = point(a), end = point(b);
8143
+ result.push({
8144
+ polygon: polygon2,
8145
+ a,
8146
+ b,
8147
+ side,
8148
+ start,
8149
+ end,
8150
+ key: start < end ? `${start}/${end}` : `${end}/${start}`
8151
+ });
8152
+ }
8153
+ return result;
8154
+ }
8155
+
8156
+ // dist/terrain/geographic-cutout.js
8157
+ var RAD = Math.PI / 180;
8158
+ function createGeographicTerrainCutoutFrame(options) {
8159
+ if (options.center.length !== 2)
8160
+ throw new RangeError("Invalid geographic terrain cutout center");
8161
+ const frame = {
8162
+ center: [wrap(options.center[0]), options.center[1]],
8163
+ radius: options.radius ?? 6378137,
8164
+ maxAngularRadius: options.maxAngularRadius ?? 30
8165
+ };
8166
+ validateFrame(frame);
8167
+ return Object.freeze({ ...frame, center: Object.freeze(frame.center) });
8168
+ }
8169
+ function projectGeographicTerrainCutout(positions, frame) {
8170
+ var _a;
8171
+ validateFrame(frame);
8172
+ validatePositions(positions);
8173
+ const result = new Float64Array(positions.length);
8174
+ const [sin0, cos0] = latitude(frame.center[1]);
8175
+ const maximum = chartLimit(frame);
8176
+ for (let i = 0; i < positions.length; i += 3) {
8177
+ const lon = positions[i], lat = positions[i + 1];
8178
+ if (lat < -90 || lat > 90)
8179
+ throw new RangeError("Invalid geographic terrain latitude");
8180
+ const sin = Math.sin(lat * RAD);
8181
+ const cos = Math.abs(lat) === 90 ? 0 : Math.cos(lat * RAD);
8182
+ const delta = wrap(wrap(lon) - frame.center[0]) * RAD;
8183
+ const dot2 = sin0 * sin + cos0 * cos * Math.cos(delta);
8184
+ const x = cos * Math.sin(delta) / dot2;
8185
+ const y = (cos0 * sin - sin0 * cos * Math.cos(delta)) / dot2;
8186
+ if (!(dot2 > 0) || Math.hypot(x, y) > maximum)
8187
+ throw new RangeError("Terrain coordinate exceeds geographic cutout chart");
8188
+ result[i] = frame.radius * x;
8189
+ result[i + 1] = frame.radius * y;
8190
+ result[i] || (result[i] = 0);
8191
+ result[_a = i + 1] || (result[_a] = 0);
8192
+ result[i + 2] = positions[i + 2];
8193
+ }
8194
+ if (!result.every(Number.isFinite))
8195
+ throw new RangeError("Geographic terrain projection overflow");
8196
+ return result;
8197
+ }
8198
+ function unprojectGeographicTerrainCutout(positions, frame) {
8199
+ validateFrame(frame);
8200
+ validatePositions(positions);
8201
+ const result = new Float64Array(positions.length);
8202
+ const [sin0, cos0] = latitude(frame.center[1]);
8203
+ const maximum = chartLimit(frame);
8204
+ for (let i = 0; i < positions.length; i += 3) {
8205
+ const x = positions[i] / frame.radius, y = positions[i + 1] / frame.radius;
8206
+ const distance = Math.hypot(x, y);
8207
+ if (!Number.isFinite(distance) || distance > maximum)
8208
+ throw new RangeError("Terrain coordinate exceeds geographic cutout chart");
8209
+ const horizontal = cos0 - y * sin0;
8210
+ const vertical = sin0 + y * cos0;
8211
+ const lat = Math.atan2(vertical, Math.hypot(horizontal, x)) / RAD;
8212
+ result[i] = Math.abs(lat) === 90 ? frame.center[0] : wrap(frame.center[0] + Math.atan2(x, horizontal) / RAD);
8213
+ result[i + 1] = lat;
8214
+ result[i + 2] = positions[i + 2];
8215
+ }
8216
+ return result;
8217
+ }
8218
+ function wrap(longitude) {
8219
+ const result = longitude % 360;
8220
+ return result >= 180 ? result - 360 : result < -180 ? result + 360 : result;
8221
+ }
8222
+ function latitude(degrees) {
8223
+ return [Math.sin(degrees * RAD), Math.abs(degrees) === 90 ? 0 : Math.cos(degrees * RAD)];
8224
+ }
8225
+ function validateFrame(frame) {
8226
+ if (frame.center.length !== 2 || !frame.center.every(Number.isFinite) || frame.center[0] < -180 || frame.center[0] >= 180 || Math.abs(frame.center[1]) > 90 || !Number.isFinite(frame.radius) || frame.radius <= 0 || !Number.isFinite(frame.maxAngularRadius) || frame.maxAngularRadius <= 0 || frame.maxAngularRadius > 80)
8227
+ throw new RangeError("Invalid geographic terrain cutout frame");
8228
+ }
8229
+ function validatePositions(positions) {
8230
+ if (!(positions instanceof Float32Array || positions instanceof Float64Array) || positions.length % 3 || !positions.every(Number.isFinite))
8231
+ throw new RangeError("Invalid geographic terrain cutout positions");
8232
+ }
8233
+ function chartLimit(frame) {
8234
+ const distance = Math.tan(frame.maxAngularRadius * RAD);
8235
+ return distance + 16 * Number.EPSILON * (1 + distance);
8236
+ }
8237
+
8238
+ // dist/terrain/cutout-polygons.js
8239
+ function prepareTerrainCutoutPolygons(polygons, { maxEdges = 2048, maxWork = 4e6 } = {}) {
8240
+ if (![maxEdges, maxWork].every((n) => Number.isSafeInteger(n) && n >= 0) || !polygons.length)
8241
+ throw new RangeError("Invalid terrain cutout polygon limits or empty set");
8242
+ let work = 0, edgeCount = 0;
8243
+ const charge = (amount) => {
8244
+ work += amount;
8245
+ if (work > maxWork)
8246
+ throw new RangeError("Terrain cutout polygon work budget exceeded");
8247
+ };
8248
+ if (polygons.length > Math.floor(maxEdges / 3))
8249
+ throw new RangeError("Terrain cutout polygon edge budget exceeded");
8250
+ const regions = polygons.map((p) => {
8251
+ var _a;
8252
+ if (1 + (((_a = p.holes) == null ? void 0 : _a.length) ?? 0) > Math.floor((maxEdges - edgeCount) / 3))
8253
+ throw new RangeError("Terrain cutout polygon edge budget exceeded");
8254
+ return [p.outer, ...p.holes ?? []].map((ring) => {
8255
+ edgeCount += ring.length;
8256
+ if (edgeCount > maxEdges)
8257
+ throw new RangeError("Terrain cutout polygon edge budget exceeded");
8258
+ charge(ring.length);
8259
+ if (ring.length < 3 || ring.some((p2) => p2.length !== 2 || !p2.every(Number.isFinite)))
8260
+ throw new RangeError("Invalid terrain cutout polygon ring");
8261
+ return ring.map((p2) => Object.freeze([p2[0], p2[1]]));
8262
+ });
8263
+ });
8264
+ const rings = regions.flat();
8265
+ for (const ring of rings) {
8266
+ let area = 0;
8267
+ for (let i = 0; i < ring.length; i++) {
8268
+ charge(1);
8269
+ const a = ring[i], b = ring[(i + 1) % ring.length], c = ring[(i + 2) % ring.length];
8270
+ if (equal(a, b))
8271
+ throw new RangeError("Duplicate terrain cutout ring vertex");
8272
+ area += orient2(ring[0], a, b);
8273
+ if (orient2(a, b, c) === 0 && (a[0] - b[0]) * (c[0] - b[0]) + (a[1] - b[1]) * (c[1] - b[1]) >= 0)
8274
+ throw new RangeError("Backtracking terrain cutout ring edge");
8275
+ for (let j = i + 1; j < ring.length; j++) {
8276
+ if (j === i + 1 || i === 0 && j === ring.length - 1)
8277
+ continue;
8278
+ charge(1);
8279
+ if (intersects2(a, b, ring[j], ring[(j + 1) % ring.length]))
8280
+ throw new RangeError("Self-intersecting terrain cutout ring");
8281
+ }
8282
+ }
8283
+ if (!Number.isFinite(area) || area === 0)
8284
+ throw new RangeError("Degenerate terrain cutout ring");
8285
+ }
8286
+ for (let i = 0; i < rings.length; i++)
8287
+ for (let j = i + 1; j < rings.length; j++) {
8288
+ const a = rings[i], b = rings[j];
8289
+ for (let x = 0; x < a.length; x++)
8290
+ for (let y = 0; y < b.length; y++) {
8291
+ charge(1);
8292
+ if (intersects2(a[x], a[(x + 1) % a.length], b[y], b[(y + 1) % b.length]))
8293
+ throw new RangeError("Terrain cutout rings must not touch or intersect");
8294
+ }
8295
+ }
8296
+ for (const region of regions)
8297
+ for (let i = 1; i < region.length; i++) {
8298
+ if (contains(region[0], region[i][0], charge) !== 1)
8299
+ throw new RangeError("Terrain cutout hole must be strictly inside its outer ring");
8300
+ for (let j = 1; j < i; j++)
8301
+ if (contains(region[j], region[i][0], charge) === 1 || contains(region[i], region[j][0], charge) === 1)
8302
+ throw new RangeError("Nested terrain cutout holes are not supported");
8303
+ }
8304
+ function inRegion(region, point, budget) {
8305
+ const outer = contains(region[0], point, budget);
8306
+ if (outer !== 1)
8307
+ return outer;
8308
+ for (let i = 1; i < region.length; i++) {
8309
+ const hole = contains(region[i], point, budget);
8310
+ if (hole === 0)
8311
+ return 0;
8312
+ if (hole === 1)
8313
+ return -1;
8314
+ }
8315
+ return 1;
8316
+ }
8317
+ for (let i = 0; i < regions.length; i++)
8318
+ for (let j = i + 1; j < regions.length; j++) {
8319
+ if (inRegion(regions[i], regions[j][0][0], charge) === 1 || inRegion(regions[j], regions[i][0][0], charge) === 1)
8320
+ throw new RangeError("Overlapping terrain cutout polygon domains");
8321
+ }
8322
+ const lines = [];
8323
+ for (const ring of rings)
8324
+ for (let i = 0; i < ring.length; i++) {
8325
+ const a = ring[i], b = ring[(i + 1) % ring.length];
8326
+ if (lines.some(([u, v]) => {
8327
+ charge(1);
8328
+ return orient2(u, v, a) === 0 && orient2(u, v, b) === 0;
8329
+ }))
8330
+ continue;
8331
+ lines.push(a[0] < b[0] || a[0] === b[0] && a[1] < b[1] ? [a, b] : [b, a]);
8332
+ }
8333
+ return createTerrainCutoutPlan({
8334
+ lines: Object.freeze(lines.map((line) => Object.freeze(line))),
8335
+ classify(point, budget) {
8336
+ for (let i = 0; i < regions.length; i++) {
8337
+ const result = inRegion(regions[i], point, budget);
8338
+ if (result === 0)
8339
+ throw new RangeError("Unrepresentable terrain cutout fragment interior");
8340
+ if (result === 1)
8341
+ return i;
8342
+ }
8343
+ return -1;
8344
+ }
8345
+ });
8346
+ }
8347
+ function equal(a, b) {
8348
+ return a[0] === b[0] && a[1] === b[1];
8349
+ }
8350
+ function orient2(a, b, c) {
8351
+ const value = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
8352
+ if (!Number.isFinite(value))
8353
+ throw new RangeError("Terrain cutout polygon coordinate overflow");
8354
+ return value;
8355
+ }
8356
+ function onSegment2(a, b, p) {
8357
+ return p[0] >= Math.min(a[0], b[0]) && p[0] <= Math.max(a[0], b[0]) && p[1] >= Math.min(a[1], b[1]) && p[1] <= Math.max(a[1], b[1]);
8358
+ }
8359
+ function intersects2(a, b, c, d) {
8360
+ const abC = orient2(a, b, c), abD = orient2(a, b, d), cdA = orient2(c, d, a), cdB = orient2(c, d, b);
8361
+ return abC === 0 && onSegment2(a, b, c) || abD === 0 && onSegment2(a, b, d) || cdA === 0 && onSegment2(c, d, a) || cdB === 0 && onSegment2(c, d, b) || (abC > 0 && abD < 0 || abC < 0 && abD > 0) && (cdA > 0 && cdB < 0 || cdA < 0 && cdB > 0);
8362
+ }
8363
+ function contains(ring, p, charge) {
8364
+ let winding = 0;
8365
+ for (let i = 0; i < ring.length; i++) {
8366
+ charge(1);
8367
+ const a = ring[i], b = ring[(i + 1) % ring.length], cross4 = orient2(a, b, p);
8368
+ if (cross4 === 0 && onSegment2(a, b, p))
8369
+ return 0;
8370
+ if (a[1] <= p[1] && b[1] > p[1] && cross4 > 0)
8371
+ winding++;
8372
+ if (a[1] > p[1] && b[1] <= p[1] && cross4 < 0)
8373
+ winding--;
8374
+ }
8375
+ return winding === 0 ? -1 : 1;
8376
+ }
5432
8377
  //# sourceMappingURL=index.cjs.map