@math.gl/geospatial 5.0.0-beta.10 → 5.0.0-beta.12

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 (360) hide show
  1. package/README.md +3 -3
  2. package/dist/crs/index.cjs +54 -0
  3. package/dist/crs/index.cjs.map +2 -2
  4. package/dist/crs/index.d.ts +1 -0
  5. package/dist/crs/index.d.ts.map +1 -1
  6. package/dist/crs/index.js +1 -0
  7. package/dist/crs/index.js.map +1 -1
  8. package/dist/crs/spatial-reference-metadata.d.ts +20 -0
  9. package/dist/crs/spatial-reference-metadata.d.ts.map +1 -0
  10. package/dist/crs/spatial-reference-metadata.js +86 -0
  11. package/dist/crs/spatial-reference-metadata.js.map +1 -0
  12. package/dist/expressions.d.ts +1 -1
  13. package/dist/expressions.d.ts.map +1 -1
  14. package/dist/index.cjs +1738 -316
  15. package/dist/index.cjs.map +3 -3
  16. package/dist/index.d.ts +14 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +12 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/projection/experimental/core.cjs.map +1 -1
  21. package/dist/projection/experimental/crs/spatial-reference.d.ts.map +1 -1
  22. package/dist/projection/experimental/crs/spatial-reference.js.map +1 -1
  23. package/dist/projection/experimental/crs/types.d.ts.map +1 -1
  24. package/dist/projection/experimental/lazy-projections/aea.cjs +4 -1
  25. package/dist/projection/experimental/lazy-projections/aea.cjs.map +1 -1
  26. package/dist/projection/experimental/lazy-projections/aea.d.ts.map +1 -1
  27. package/dist/projection/experimental/lazy-projections/aea.js +4 -1
  28. package/dist/projection/experimental/lazy-projections/aea.js.map +1 -1
  29. package/dist/projection/experimental/lazy-projections/bonne.cjs +4 -1
  30. package/dist/projection/experimental/lazy-projections/bonne.cjs.map +1 -1
  31. package/dist/projection/experimental/lazy-projections/bonne.d.ts.map +1 -1
  32. package/dist/projection/experimental/lazy-projections/bonne.js +4 -1
  33. package/dist/projection/experimental/lazy-projections/bonne.js.map +1 -1
  34. package/dist/projection/experimental/lazy-projections/cass.cjs +4 -1
  35. package/dist/projection/experimental/lazy-projections/cass.cjs.map +1 -1
  36. package/dist/projection/experimental/lazy-projections/cass.d.ts.map +1 -1
  37. package/dist/projection/experimental/lazy-projections/cass.js +4 -1
  38. package/dist/projection/experimental/lazy-projections/cass.js.map +1 -1
  39. package/dist/projection/experimental/lazy-projections/eck6.cjs +4 -1
  40. package/dist/projection/experimental/lazy-projections/eck6.cjs.map +1 -1
  41. package/dist/projection/experimental/lazy-projections/eck6.d.ts.map +1 -1
  42. package/dist/projection/experimental/lazy-projections/eck6.js +4 -1
  43. package/dist/projection/experimental/lazy-projections/eck6.js.map +1 -1
  44. package/dist/projection/experimental/lazy-projections/eqdc.cjs +4 -1
  45. package/dist/projection/experimental/lazy-projections/eqdc.cjs.map +1 -1
  46. package/dist/projection/experimental/lazy-projections/eqdc.d.ts.map +1 -1
  47. package/dist/projection/experimental/lazy-projections/eqdc.js +4 -1
  48. package/dist/projection/experimental/lazy-projections/eqdc.js.map +1 -1
  49. package/dist/projection/experimental/lazy-projections/eqearth.cjs +4 -1
  50. package/dist/projection/experimental/lazy-projections/eqearth.cjs.map +1 -1
  51. package/dist/projection/experimental/lazy-projections/eqearth.d.ts.map +1 -1
  52. package/dist/projection/experimental/lazy-projections/eqearth.js +4 -1
  53. package/dist/projection/experimental/lazy-projections/eqearth.js.map +1 -1
  54. package/dist/projection/experimental/lazy-projections/equi.cjs +4 -1
  55. package/dist/projection/experimental/lazy-projections/equi.cjs.map +1 -1
  56. package/dist/projection/experimental/lazy-projections/equi.d.ts.map +1 -1
  57. package/dist/projection/experimental/lazy-projections/equi.js +4 -1
  58. package/dist/projection/experimental/lazy-projections/equi.js.map +1 -1
  59. package/dist/projection/experimental/lazy-projections/geocent.cjs +4 -1
  60. package/dist/projection/experimental/lazy-projections/geocent.cjs.map +1 -1
  61. package/dist/projection/experimental/lazy-projections/geocent.d.ts.map +1 -1
  62. package/dist/projection/experimental/lazy-projections/geocent.js +4 -1
  63. package/dist/projection/experimental/lazy-projections/geocent.js.map +1 -1
  64. package/dist/projection/experimental/lazy-projections/geos.cjs +4 -1
  65. package/dist/projection/experimental/lazy-projections/geos.cjs.map +1 -1
  66. package/dist/projection/experimental/lazy-projections/geos.d.ts.map +1 -1
  67. package/dist/projection/experimental/lazy-projections/geos.js +4 -1
  68. package/dist/projection/experimental/lazy-projections/geos.js.map +1 -1
  69. package/dist/projection/experimental/lazy-projections/gnom.cjs +4 -1
  70. package/dist/projection/experimental/lazy-projections/gnom.cjs.map +1 -1
  71. package/dist/projection/experimental/lazy-projections/gnom.d.ts.map +1 -1
  72. package/dist/projection/experimental/lazy-projections/gnom.js +4 -1
  73. package/dist/projection/experimental/lazy-projections/gnom.js.map +1 -1
  74. package/dist/projection/experimental/lazy-projections/index.cjs +92 -23
  75. package/dist/projection/experimental/lazy-projections/index.cjs.map +1 -1
  76. package/dist/projection/experimental/lazy-projections/krovak.cjs +4 -1
  77. package/dist/projection/experimental/lazy-projections/krovak.cjs.map +1 -1
  78. package/dist/projection/experimental/lazy-projections/krovak.d.ts.map +1 -1
  79. package/dist/projection/experimental/lazy-projections/krovak.js +4 -1
  80. package/dist/projection/experimental/lazy-projections/krovak.js.map +1 -1
  81. package/dist/projection/experimental/lazy-projections/merc.cjs +4 -1
  82. package/dist/projection/experimental/lazy-projections/merc.cjs.map +1 -1
  83. package/dist/projection/experimental/lazy-projections/merc.d.ts.map +1 -1
  84. package/dist/projection/experimental/lazy-projections/merc.js +4 -1
  85. package/dist/projection/experimental/lazy-projections/merc.js.map +1 -1
  86. package/dist/projection/experimental/lazy-projections/mill.cjs +4 -1
  87. package/dist/projection/experimental/lazy-projections/mill.cjs.map +1 -1
  88. package/dist/projection/experimental/lazy-projections/mill.d.ts.map +1 -1
  89. package/dist/projection/experimental/lazy-projections/mill.js +4 -1
  90. package/dist/projection/experimental/lazy-projections/mill.js.map +1 -1
  91. package/dist/projection/experimental/lazy-projections/moll.cjs +4 -1
  92. package/dist/projection/experimental/lazy-projections/moll.cjs.map +1 -1
  93. package/dist/projection/experimental/lazy-projections/moll.d.ts.map +1 -1
  94. package/dist/projection/experimental/lazy-projections/moll.js +4 -1
  95. package/dist/projection/experimental/lazy-projections/moll.js.map +1 -1
  96. package/dist/projection/experimental/lazy-projections/nzmg.cjs +4 -1
  97. package/dist/projection/experimental/lazy-projections/nzmg.cjs.map +1 -1
  98. package/dist/projection/experimental/lazy-projections/nzmg.d.ts.map +1 -1
  99. package/dist/projection/experimental/lazy-projections/nzmg.js +4 -1
  100. package/dist/projection/experimental/lazy-projections/nzmg.js.map +1 -1
  101. package/dist/projection/experimental/lazy-projections/omerc.cjs +4 -1
  102. package/dist/projection/experimental/lazy-projections/omerc.cjs.map +1 -1
  103. package/dist/projection/experimental/lazy-projections/omerc.d.ts.map +1 -1
  104. package/dist/projection/experimental/lazy-projections/omerc.js +4 -1
  105. package/dist/projection/experimental/lazy-projections/omerc.js.map +1 -1
  106. package/dist/projection/experimental/lazy-projections/ortho.cjs +4 -1
  107. package/dist/projection/experimental/lazy-projections/ortho.cjs.map +1 -1
  108. package/dist/projection/experimental/lazy-projections/ortho.d.ts.map +1 -1
  109. package/dist/projection/experimental/lazy-projections/ortho.js +4 -1
  110. package/dist/projection/experimental/lazy-projections/ortho.js.map +1 -1
  111. package/dist/projection/experimental/lazy-projections/poly.cjs +4 -1
  112. package/dist/projection/experimental/lazy-projections/poly.cjs.map +1 -1
  113. package/dist/projection/experimental/lazy-projections/poly.d.ts.map +1 -1
  114. package/dist/projection/experimental/lazy-projections/poly.js +4 -1
  115. package/dist/projection/experimental/lazy-projections/poly.js.map +1 -1
  116. package/dist/projection/experimental/lazy-projections/robin.cjs +4 -1
  117. package/dist/projection/experimental/lazy-projections/robin.cjs.map +1 -1
  118. package/dist/projection/experimental/lazy-projections/robin.d.ts.map +1 -1
  119. package/dist/projection/experimental/lazy-projections/robin.js +4 -1
  120. package/dist/projection/experimental/lazy-projections/robin.js.map +1 -1
  121. package/dist/projection/experimental/lazy-projections/sinu.cjs +4 -1
  122. package/dist/projection/experimental/lazy-projections/sinu.cjs.map +1 -1
  123. package/dist/projection/experimental/lazy-projections/sinu.d.ts.map +1 -1
  124. package/dist/projection/experimental/lazy-projections/sinu.js +4 -1
  125. package/dist/projection/experimental/lazy-projections/sinu.js.map +1 -1
  126. package/dist/projection/experimental/lazy-projections/stere.cjs +4 -1
  127. package/dist/projection/experimental/lazy-projections/stere.cjs.map +1 -1
  128. package/dist/projection/experimental/lazy-projections/stere.d.ts.map +1 -1
  129. package/dist/projection/experimental/lazy-projections/stere.js +4 -1
  130. package/dist/projection/experimental/lazy-projections/stere.js.map +1 -1
  131. package/dist/projection/experimental/lazy-projections/tpers.cjs +4 -1
  132. package/dist/projection/experimental/lazy-projections/tpers.cjs.map +1 -1
  133. package/dist/projection/experimental/lazy-projections/tpers.d.ts.map +1 -1
  134. package/dist/projection/experimental/lazy-projections/tpers.js +4 -1
  135. package/dist/projection/experimental/lazy-projections/tpers.js.map +1 -1
  136. package/dist/projection/experimental/lazy-projections/vandg.cjs +4 -1
  137. package/dist/projection/experimental/lazy-projections/vandg.cjs.map +1 -1
  138. package/dist/projection/experimental/lazy-projections/vandg.d.ts.map +1 -1
  139. package/dist/projection/experimental/lazy-projections/vandg.js +4 -1
  140. package/dist/projection/experimental/lazy-projections/vandg.js.map +1 -1
  141. package/dist/projection/index.cjs.map +1 -1
  142. package/dist/projection/index.d.ts.map +1 -1
  143. package/dist/projection/index.js.map +1 -1
  144. package/dist/projection/lib/projection.js.map +1 -1
  145. package/dist/projection/pipeline.cjs.map +1 -1
  146. package/dist/projection/transform-analysis.cjs.map +1 -1
  147. package/dist/tasks/index.cjs +181 -84
  148. package/dist/tasks/index.cjs.map +2 -2
  149. package/dist/tasks/terrain-residency.d.ts.map +1 -1
  150. package/dist/tasks/terrain-residency.js +80 -18
  151. package/dist/tasks/terrain-residency.js.map +1 -1
  152. package/dist/terrain/cutout-polygons.d.ts +21 -0
  153. package/dist/terrain/cutout-polygons.d.ts.map +1 -0
  154. package/dist/terrain/cutout-polygons.js +172 -0
  155. package/dist/terrain/cutout-polygons.js.map +1 -0
  156. package/dist/terrain/cutout-region.d.ts +34 -0
  157. package/dist/terrain/cutout-region.d.ts.map +1 -0
  158. package/dist/terrain/cutout-region.js +33 -0
  159. package/dist/terrain/cutout-region.js.map +1 -0
  160. package/dist/terrain/cutout-skirts.d.ts +34 -0
  161. package/dist/terrain/cutout-skirts.d.ts.map +1 -0
  162. package/dist/terrain/cutout-skirts.js +29 -0
  163. package/dist/terrain/cutout-skirts.js.map +1 -0
  164. package/dist/terrain/depression-fill.d.ts +25 -0
  165. package/dist/terrain/depression-fill.d.ts.map +1 -0
  166. package/dist/terrain/depression-fill.js +106 -0
  167. package/dist/terrain/depression-fill.js.map +1 -0
  168. package/dist/terrain/geographic-cutout.d.ts +38 -0
  169. package/dist/terrain/geographic-cutout.d.ts.map +1 -0
  170. package/dist/terrain/geographic-cutout.js +120 -0
  171. package/dist/terrain/geographic-cutout.js.map +1 -0
  172. package/dist/terrain/hydrology.d.ts +42 -0
  173. package/dist/terrain/hydrology.d.ts.map +1 -0
  174. package/dist/terrain/hydrology.js +112 -0
  175. package/dist/terrain/hydrology.js.map +1 -0
  176. package/dist/terrain/index.cjs +1529 -107
  177. package/dist/terrain/index.cjs.map +3 -3
  178. package/dist/terrain/index.d.ts +15 -1
  179. package/dist/terrain/index.d.ts.map +1 -1
  180. package/dist/terrain/index.js +13 -0
  181. package/dist/terrain/index.js.map +1 -1
  182. package/dist/terrain/lod-screen-error.d.ts +28 -0
  183. package/dist/terrain/lod-screen-error.d.ts.map +1 -0
  184. package/dist/terrain/lod-screen-error.js +95 -0
  185. package/dist/terrain/lod-screen-error.js.map +1 -0
  186. package/dist/terrain/lod-select.d.ts +26 -10
  187. package/dist/terrain/lod-select.d.ts.map +1 -1
  188. package/dist/terrain/lod-select.js +27 -14
  189. package/dist/terrain/lod-select.js.map +1 -1
  190. package/dist/terrain/mesh-cutout.d.ts +45 -0
  191. package/dist/terrain/mesh-cutout.d.ts.map +1 -0
  192. package/dist/terrain/mesh-cutout.js +336 -0
  193. package/dist/terrain/mesh-cutout.js.map +1 -0
  194. package/dist/terrain/mesh-skirts.d.ts +8 -2
  195. package/dist/terrain/mesh-skirts.d.ts.map +1 -1
  196. package/dist/terrain/mesh-skirts.js +5 -4
  197. package/dist/terrain/mesh-skirts.js.map +1 -1
  198. package/dist/terrain/mixed-halo-update.d.ts.map +1 -1
  199. package/dist/terrain/mixed-halo-update.js +58 -23
  200. package/dist/terrain/mixed-halo-update.js.map +1 -1
  201. package/dist/terrain/mixed-vertex-halos.d.ts +24 -1
  202. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -1
  203. package/dist/terrain/mixed-vertex-halos.js +75 -58
  204. package/dist/terrain/mixed-vertex-halos.js.map +1 -1
  205. package/dist/terrain/regional-viewshed.d.ts +55 -0
  206. package/dist/terrain/regional-viewshed.d.ts.map +1 -0
  207. package/dist/terrain/regional-viewshed.js +119 -0
  208. package/dist/terrain/regional-viewshed.js.map +1 -0
  209. package/dist/terrain/sweep-polytope.d.ts +4 -0
  210. package/dist/terrain/sweep-polytope.d.ts.map +1 -1
  211. package/dist/terrain/sweep-polytope.js +15 -5
  212. package/dist/terrain/sweep-polytope.js.map +1 -1
  213. package/dist/terrain/sweep-rotating-capsule.d.ts +17 -0
  214. package/dist/terrain/sweep-rotating-capsule.d.ts.map +1 -0
  215. package/dist/terrain/sweep-rotating-capsule.js +118 -0
  216. package/dist/terrain/sweep-rotating-capsule.js.map +1 -0
  217. package/dist/terrain/sweep-rotation.d.ts +35 -0
  218. package/dist/terrain/sweep-rotation.d.ts.map +1 -0
  219. package/dist/terrain/sweep-rotation.js +114 -0
  220. package/dist/terrain/sweep-rotation.js.map +1 -0
  221. package/dist/terrain/tile-cutout-update.d.ts +73 -0
  222. package/dist/terrain/tile-cutout-update.d.ts.map +1 -0
  223. package/dist/terrain/tile-cutout-update.js +181 -0
  224. package/dist/terrain/tile-cutout-update.js.map +1 -0
  225. package/dist/terrain/tile-cutout.d.ts +33 -0
  226. package/dist/terrain/tile-cutout.d.ts.map +1 -0
  227. package/dist/terrain/tile-cutout.js +93 -0
  228. package/dist/terrain/tile-cutout.js.map +1 -0
  229. package/dist/terrain/watershed-accumulation.d.ts +20 -0
  230. package/dist/terrain/watershed-accumulation.d.ts.map +1 -0
  231. package/dist/terrain/watershed-accumulation.js +53 -0
  232. package/dist/terrain/watershed-accumulation.js.map +1 -0
  233. package/dist/turf/expressions.cjs +4 -4
  234. package/dist/turf/expressions.cjs.map +2 -2
  235. package/dist/turf/expressions.d.ts +2 -2
  236. package/dist/turf/expressions.d.ts.map +1 -1
  237. package/dist/turf/expressions.js +2 -2
  238. package/dist/turf/expressions.js.map +1 -1
  239. package/dist/turf.cjs +25 -25
  240. package/dist/turf.cjs.map +2 -2
  241. package/dist/turf.d.ts +1 -1
  242. package/dist/turf.d.ts.map +1 -1
  243. package/dist/turf.js +2 -2
  244. package/dist/turf.js.map +1 -1
  245. package/dist/web-mercator/assert.d.ts +2 -0
  246. package/dist/web-mercator/assert.d.ts.map +1 -0
  247. package/dist/web-mercator/assert.js +12 -0
  248. package/dist/web-mercator/assert.js.map +1 -0
  249. package/dist/web-mercator/fit-bounds.d.ts +52 -0
  250. package/dist/web-mercator/fit-bounds.d.ts.map +1 -0
  251. package/dist/web-mercator/fit-bounds.js +70 -0
  252. package/dist/web-mercator/fit-bounds.js.map +1 -0
  253. package/dist/web-mercator/fly-to-viewport.d.ts +19 -0
  254. package/dist/web-mercator/fly-to-viewport.d.ts.map +1 -0
  255. package/dist/web-mercator/fly-to-viewport.js +94 -0
  256. package/dist/web-mercator/fly-to-viewport.js.map +1 -0
  257. package/dist/web-mercator/get-bounds.d.ts +3 -0
  258. package/dist/web-mercator/get-bounds.d.ts.map +1 -0
  259. package/dist/web-mercator/get-bounds.js +56 -0
  260. package/dist/web-mercator/get-bounds.js.map +1 -0
  261. package/dist/web-mercator/index.cjs +705 -0
  262. package/dist/web-mercator/index.cjs.map +6 -0
  263. package/dist/web-mercator/index.d.ts +14 -0
  264. package/dist/web-mercator/index.d.ts.map +1 -0
  265. package/dist/web-mercator/index.js +14 -0
  266. package/dist/web-mercator/index.js.map +1 -0
  267. package/dist/web-mercator/math-utils.d.ts +7 -0
  268. package/dist/web-mercator/math-utils.d.ts.map +1 -0
  269. package/dist/web-mercator/math-utils.js +30 -0
  270. package/dist/web-mercator/math-utils.js.map +1 -0
  271. package/dist/web-mercator/mercator-meters.d.ts +29 -0
  272. package/dist/web-mercator/mercator-meters.d.ts.map +1 -0
  273. package/dist/web-mercator/mercator-meters.js +61 -0
  274. package/dist/web-mercator/mercator-meters.js.map +1 -0
  275. package/dist/web-mercator/normalize-viewport-props.d.ts +16 -0
  276. package/dist/web-mercator/normalize-viewport-props.d.ts.map +1 -0
  277. package/dist/web-mercator/normalize-viewport-props.js +45 -0
  278. package/dist/web-mercator/normalize-viewport-props.js.map +1 -0
  279. package/dist/web-mercator/web-mercator-utils.d.ts +192 -0
  280. package/dist/web-mercator/web-mercator-utils.d.ts.map +1 -0
  281. package/dist/web-mercator/web-mercator-utils.js +321 -0
  282. package/dist/web-mercator/web-mercator-utils.js.map +1 -0
  283. package/dist/web-mercator/web-mercator-viewport.d.ts +177 -0
  284. package/dist/web-mercator/web-mercator-viewport.d.ts.map +1 -0
  285. package/dist/web-mercator/web-mercator-viewport.js +276 -0
  286. package/dist/web-mercator/web-mercator-viewport.js.map +1 -0
  287. package/dist/web-mercator.d.ts +1 -1
  288. package/dist/web-mercator.d.ts.map +1 -1
  289. package/dist/web-mercator.js +1 -1
  290. package/dist/web-mercator.js.map +1 -1
  291. package/package.json +19 -458
  292. package/src/crs/index.ts +7 -0
  293. package/src/crs/spatial-reference-metadata.ts +118 -0
  294. package/src/expressions.ts +1 -1
  295. package/src/index.ts +92 -4
  296. package/src/projection/experimental/crs/spatial-reference.ts +1 -6
  297. package/src/projection/experimental/crs/types.ts +1 -1
  298. package/src/projection/experimental/crs/wkt.ts +1 -1
  299. package/src/projection/experimental/crs-descriptor.ts +1 -1
  300. package/src/projection/experimental/lazy-projections/aea.ts +4 -1
  301. package/src/projection/experimental/lazy-projections/bonne.ts +4 -1
  302. package/src/projection/experimental/lazy-projections/cass.ts +4 -1
  303. package/src/projection/experimental/lazy-projections/eck6.ts +4 -1
  304. package/src/projection/experimental/lazy-projections/eqdc.ts +4 -1
  305. package/src/projection/experimental/lazy-projections/eqearth.ts +4 -1
  306. package/src/projection/experimental/lazy-projections/equi.ts +4 -1
  307. package/src/projection/experimental/lazy-projections/geocent.ts +4 -1
  308. package/src/projection/experimental/lazy-projections/geos.ts +4 -1
  309. package/src/projection/experimental/lazy-projections/gnom.ts +4 -1
  310. package/src/projection/experimental/lazy-projections/krovak.ts +4 -1
  311. package/src/projection/experimental/lazy-projections/merc.ts +4 -1
  312. package/src/projection/experimental/lazy-projections/mill.ts +4 -1
  313. package/src/projection/experimental/lazy-projections/moll.ts +4 -1
  314. package/src/projection/experimental/lazy-projections/nzmg.ts +4 -1
  315. package/src/projection/experimental/lazy-projections/omerc.ts +4 -1
  316. package/src/projection/experimental/lazy-projections/ortho.ts +4 -1
  317. package/src/projection/experimental/lazy-projections/poly.ts +4 -1
  318. package/src/projection/experimental/lazy-projections/robin.ts +4 -1
  319. package/src/projection/experimental/lazy-projections/sinu.ts +4 -1
  320. package/src/projection/experimental/lazy-projections/stere.ts +4 -1
  321. package/src/projection/experimental/lazy-projections/tpers.ts +4 -1
  322. package/src/projection/experimental/lazy-projections/vandg.ts +4 -1
  323. package/src/projection/index.ts +1 -1
  324. package/src/projection/lib/projection.ts +1 -1
  325. package/src/tasks/terrain-residency.ts +86 -21
  326. package/src/terrain/cutout-polygons.ts +202 -0
  327. package/src/terrain/cutout-region.ts +54 -0
  328. package/src/terrain/cutout-skirts.ts +52 -0
  329. package/src/terrain/depression-fill.ts +125 -0
  330. package/src/terrain/geographic-cutout.ts +154 -0
  331. package/src/terrain/hydrology.ts +149 -0
  332. package/src/terrain/index.ts +85 -1
  333. package/src/terrain/lod-screen-error.ts +128 -0
  334. package/src/terrain/lod-select.ts +65 -31
  335. package/src/terrain/mesh-cutout.ts +420 -0
  336. package/src/terrain/mesh-skirts.ts +10 -7
  337. package/src/terrain/mixed-halo-update.ts +54 -20
  338. package/src/terrain/mixed-vertex-halos.ts +94 -78
  339. package/src/terrain/regional-viewshed.ts +177 -0
  340. package/src/terrain/sweep-polytope.ts +49 -25
  341. package/src/terrain/sweep-rotating-capsule.ts +139 -0
  342. package/src/terrain/sweep-rotation.ts +149 -0
  343. package/src/terrain/tile-cutout-update.ts +293 -0
  344. package/src/terrain/tile-cutout.ts +123 -0
  345. package/src/terrain/watershed-accumulation.ts +67 -0
  346. package/src/turf/expressions.ts +3 -3
  347. package/src/turf.ts +3 -7
  348. package/src/web-mercator/assert.ts +11 -0
  349. package/src/web-mercator/fit-bounds.ts +132 -0
  350. package/src/web-mercator/fly-to-viewport.ts +157 -0
  351. package/src/web-mercator/get-bounds.ts +62 -0
  352. package/src/web-mercator/index.ts +49 -0
  353. package/src/web-mercator/math-utils.ts +35 -0
  354. package/src/web-mercator/mercator-meters.ts +83 -0
  355. package/src/web-mercator/normalize-viewport-props.ts +58 -0
  356. package/src/web-mercator/web-mercator-utils.ts +468 -0
  357. package/src/web-mercator/web-mercator-viewport.ts +406 -0
  358. package/src/web-mercator.ts +1 -1
  359. package/dist/projection/experimental/index.cjs +0 -11707
  360. package/dist/projection/experimental/index.cjs.map +0 -6
@@ -37,17 +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,
44
47
  boundTerrainMeshError: () => boundTerrainMeshError,
45
48
  certifyTerrainMeshCoverage: () => certifyTerrainMeshCoverage,
46
49
  coordinateTerrainLodMorphs: () => coordinateTerrainLodMorphs,
47
50
  createBreaklineTerrainMesh: () => createBreaklineTerrainMesh,
48
51
  createDelatinTerrainMesh: () => createDelatinTerrainMesh,
52
+ createGeographicTerrainCutoutFrame: () => createGeographicTerrainCutoutFrame,
49
53
  createMartiniTerrainMesh: () => createMartiniTerrainMesh,
50
54
  createTerrainContours: () => createTerrainContours,
55
+ createTerrainCutoutSkirts: () => createTerrainCutoutSkirts,
56
+ createTerrainDrainage: () => createTerrainDrainage,
51
57
  createTerrainFilteredPyramid: () => createTerrainFilteredPyramid,
52
58
  createTerrainGradientGrid: () => createTerrainGradientGrid,
53
59
  createTerrainGradientPyramid: () => createTerrainGradientPyramid,
@@ -56,6 +62,7 @@ __export(index_exports, {
56
62
  createTerrainMesh: () => createTerrainMesh,
57
63
  createTerrainMixedIsobands: () => createTerrainMixedIsobands,
58
64
  createTerrainMixedVertexTileHalos: () => createTerrainMixedVertexTileHalos,
65
+ createTerrainRegionalViewshed: () => createTerrainRegionalViewshed,
59
66
  createTerrainSkirt: () => createTerrainSkirt,
60
67
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
61
68
  createTerrainSurface: () => createTerrainSurface,
@@ -65,7 +72,9 @@ __export(index_exports, {
65
72
  discoverGeographicTerrainLodSeams: () => discoverGeographicTerrainLodSeams,
66
73
  discoverGeographicTerrainPoles: () => discoverGeographicTerrainPoles,
67
74
  evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
75
+ fillTerrainDepressions: () => fillTerrainDepressions,
68
76
  getGeographicTerrainNeighbor: () => getGeographicTerrainNeighbor,
77
+ getTerrainCellMetrics: () => getTerrainCellMetrics,
69
78
  getTerrainHierarchyNode: () => getTerrainHierarchyNode,
70
79
  getTerrainMeshEdge: () => getTerrainMeshEdge,
71
80
  getTerrainProfileHorizon: () => getTerrainProfileHorizon,
@@ -77,12 +86,16 @@ __export(index_exports, {
77
86
  measureTerrainMeshError: () => measureTerrainMeshError,
78
87
  measureTerrainProfile: () => measureTerrainProfile,
79
88
  packTerrainHeightField: () => packTerrainHeightField,
89
+ prepareTerrainCutoutPolygons: () => prepareTerrainCutoutPolygons,
90
+ projectGeographicTerrainCutout: () => projectGeographicTerrainCutout,
80
91
  reconcileTerrainVertexTiles: () => reconcileTerrainVertexTiles,
81
92
  sampleTerrainProfile: () => sampleTerrainProfile,
82
93
  selectTerrainLod: () => selectTerrainLod,
83
94
  simplifyTerrainContourPaths: () => simplifyTerrainContourPaths,
84
95
  simplifyTerrainContourPathsTopology: () => simplifyTerrainContourPathsTopology,
85
96
  splitTerrainBreaklines: () => splitTerrainBreaklines,
97
+ splitTerrainMesh: () => splitTerrainMesh,
98
+ splitTerrainMeshTiles: () => splitTerrainMeshTiles,
86
99
  stitchTerrainContourTiles: () => stitchTerrainContourTiles,
87
100
  stitchTerrainContours: () => stitchTerrainContours,
88
101
  stitchTerrainLodCut: () => stitchTerrainLodCut,
@@ -92,10 +105,15 @@ __export(index_exports, {
92
105
  sweepTerrainCylinder: () => sweepTerrainCylinder,
93
106
  sweepTerrainPlane: () => sweepTerrainPlane,
94
107
  sweepTerrainPolytope: () => sweepTerrainPolytope,
108
+ sweepTerrainRotatingBox: () => sweepTerrainRotatingBox,
109
+ sweepTerrainRotatingCapsule: () => sweepTerrainRotatingCapsule,
110
+ sweepTerrainRotatingPolytope: () => sweepTerrainRotatingPolytope,
111
+ sweepTerrainRotatingSphere: () => sweepTerrainRotatingSphere,
95
112
  sweepTerrainSphere: () => sweepTerrainSphere,
96
113
  sweepTerrainTaperedCapsule: () => sweepTerrainTaperedCapsule,
97
114
  sweepTerrainTriangleMesh: () => sweepTerrainTriangleMesh,
98
115
  unpackTerrainHeightField: () => unpackTerrainHeightField,
116
+ unprojectGeographicTerrainCutout: () => unprojectGeographicTerrainCutout,
99
117
  updateTerrainBounds: () => updateTerrainBounds,
100
118
  updateTerrainBoundsRegions: () => updateTerrainBoundsRegions,
101
119
  updateTerrainDelatinMeshRegions: () => updateTerrainDelatinMeshRegions,
@@ -108,6 +126,7 @@ __export(index_exports, {
108
126
  updateTerrainMixedVertexTileHalos: () => updateTerrainMixedVertexTileHalos,
109
127
  updateTerrainPersistentBounds: () => updateTerrainPersistentBounds,
110
128
  updateTerrainPersistentGradients: () => updateTerrainPersistentGradients,
129
+ updateTerrainTileCutouts: () => updateTerrainTileCutouts,
111
130
  updateTerrainValidDomainMeshRegions: () => updateTerrainValidDomainMeshRegions,
112
131
  updateTerrainVertexTileHalos: () => updateTerrainVertexTileHalos,
113
132
  weldTerrainContourTiles: () => weldTerrainContourTiles,
@@ -428,9 +447,9 @@ function validateBatch(positions, output) {
428
447
 
429
448
  // dist/terrain/mesh-skirts.js
430
449
  function createTerrainSkirt(mesh, options) {
431
- const { positions, indices } = mesh, { height, edges: edges2 } = options;
450
+ const { positions, indices } = mesh, { height, baseZ, edges: edges2 } = options;
432
451
  const maxVertices = options.maxVertices ?? 2e6, maxTriangles = options.maxTriangles ?? 4e6;
433
- 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)
434
453
  throw new Error("Invalid terrain skirt height or capacity");
435
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)
436
455
  throw new Error("Invalid terrain skirt mesh or capacity");
@@ -486,7 +505,7 @@ function createTerrainSkirt(mesh, options) {
486
505
  [b, lowerB]
487
506
  ]) {
488
507
  resultPositions.set(positions.subarray(3 * source, 3 * source + 3), 3 * target);
489
- resultPositions[3 * target + 2] = positions[3 * source + 2] - height;
508
+ resultPositions[3 * target + 2] = baseZ ?? positions[3 * source + 2] - height;
490
509
  if (!Number.isFinite(resultPositions[3 * target + 2]) || resultPositions[3 * target + 2] >= positions[3 * source + 2])
491
510
  throw new Error("Terrain skirt height cannot be represented in position precision");
492
511
  sourceVertexIndices[target - vertexCount] = source;
@@ -647,17 +666,17 @@ var GeographicHeightField = class {
647
666
  });
648
667
  }
649
668
  /** Longitude must use the bounds' unwrapped interval; no implicit wrapping or clamping. */
650
- sample(longitude, latitude, options, result) {
651
- const valid = Number.isFinite(longitude) && Number.isFinite(latitude);
652
- const inside = valid && longitude >= this.bounds[0] && longitude <= this.bounds[2] && latitude >= this.bounds[1] && latitude <= this.bounds[3];
653
- 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);
654
673
  if (!inside) {
655
674
  sample.status = sample.gradientStatus = valid ? TerrainSampleStatus.OUTSIDE_DOMAIN : TerrainSampleStatus.INVALID_INPUT;
656
675
  return sample;
657
676
  }
658
677
  if (sample.gradientStatus !== TerrainSampleStatus.VALID)
659
678
  return sample;
660
- const phi = latitude * RADIANS;
679
+ const phi = latitude2 * RADIANS;
661
680
  const denominator = 1 - ECCENTRICITY_SQUARED * Math.sin(phi) ** 2;
662
681
  const n = RADIUS / Math.sqrt(denominator);
663
682
  const m = RADIUS * (1 - ECCENTRICITY_SQUARED) / denominator ** 1.5;
@@ -681,8 +700,8 @@ var GeographicHeightField = class {
681
700
  projectX(longitude) {
682
701
  return this.projection === "web-mercator" ? RADIUS * longitude * RADIANS : longitude;
683
702
  }
684
- projectY(latitude) {
685
- 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;
686
705
  }
687
706
  };
688
707
 
@@ -4054,56 +4073,48 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4054
4073
  if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
4055
4074
  throw new Error("Invalid mixed halo capacity");
4056
4075
  let count = 0;
4057
- const addresses = /* @__PURE__ */ new Set();
4076
+ let previousKey;
4058
4077
  let frame;
4059
4078
  const sources = [...tiles].sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row).map((tile) => {
4060
- if (![tile.column, tile.row, tile.spacing].every(Number.isSafeInteger) || tile.spacing < 1 || 2 ** Math.round(Math.log2(tile.spacing)) !== tile.spacing)
4061
- throw new Error("Invalid mixed halo lattice");
4062
- const key2 = `${tile.spacing}/${tile.column}/${tile.row}`;
4063
- if (addresses.has(key2))
4064
- throw new Error("Duplicate mixed halo tile");
4065
- addresses.add(key2);
4066
4079
  count += (tile.field.width + 2) * (tile.field.height + 2);
4067
4080
  if (!Number.isSafeInteger(count) || count > maxSamples)
4068
4081
  throw new Error("Mixed halo sample capacity exceeded");
4069
- let field = preparation == null ? void 0 : preparation.fields.get(tile);
4070
- if (!field) {
4071
- field = new HeightField(tile.field);
4072
- preparation == null ? void 0 : preparation.fields.set(tile, field);
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
+ }
4073
4098
  }
4074
- if (field.registration !== "vertex")
4075
- throw new Error("Mixed halos require vertex registration");
4076
- const column = field.columnStep.map((v) => v / tile.spacing);
4077
- const row = field.rowStep.map((v) => v / tile.spacing);
4078
- const origin = field.origin.map((v, axis) => v - tile.column * column[axis] - tile.row * row[axis]);
4079
- 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])));
4080
- if (!origin.every(Number.isFinite))
4081
- throw new Error("Mixed halo coordinate overflow");
4082
- 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]))))))
4083
- throw new Error("Mixed halo frames or height references differ");
4084
4099
  frame ?? (frame = { origin, column, row, reference: field.heightReference, scale });
4085
- return { ...tile, source: field };
4100
+ return prepared;
4086
4101
  });
4087
- for (const axis of ["column", "row"]) {
4088
- let min = Infinity, max = -Infinity;
4089
- for (const tile of sources) {
4090
- const size = axis === "column" ? tile.source.width : tile.source.height;
4091
- const low = tile[axis] - tile.spacing, high = tile[axis] + size * tile.spacing;
4092
- if (![low, high].every(Number.isSafeInteger))
4093
- throw new Error("Mixed halo lattice overflow");
4094
- min = Math.min(min, low);
4095
- max = Math.max(max, high);
4096
- }
4097
- if (sources.length && !Number.isSafeInteger(max - min))
4098
- throw new Error("Mixed halo lattice span overflow");
4099
- }
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");
4100
4112
  if (targets && targets.size === 0)
4101
4113
  return { tiles: [] };
4102
4114
  let index;
4103
4115
  if (sources.length > 8) {
4104
- const keys = preparation && sources.map((tile) => `${tile.spacing}/${tile.column}/${tile.row}/${tile.source.width}/${tile.source.height}`);
4105
4116
  const cached = preparation == null ? void 0 : preparation.layout;
4106
- if (keys && cached && keys.length === cached.keys.length && keys.every((key2, i) => key2 === cached.keys[i])) {
4117
+ if (cached && sources.length === cached.keys.length && sources.every((tile, i) => tile.layoutKey === cached.keys[i])) {
4107
4118
  index = cached.query;
4108
4119
  } else {
4109
4120
  index = createTerrainBoxIndex(sources.map((tile) => ({
@@ -4112,8 +4123,8 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4112
4123
  maxX: tile.column + (tile.source.width - 1) * tile.spacing,
4113
4124
  maxY: tile.row + (tile.source.height - 1) * tile.spacing
4114
4125
  })));
4115
- if (preparation && keys)
4116
- preparation.layout = { keys, query: index };
4126
+ if (preparation)
4127
+ preparation.layout = { keys: sources.map((tile) => tile.layoutKey), query: index };
4117
4128
  }
4118
4129
  }
4119
4130
  let tests = 0;
@@ -4122,21 +4133,17 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4122
4133
  throw new Error("Mixed halo tile-test budget exceeded");
4123
4134
  };
4124
4135
  return {
4125
- 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) => {
4126
4137
  const source = tile.source, width = source.width + 2, height = source.height + 2;
4127
4138
  const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
4128
- const candidates = (index == null ? void 0 : index({
4129
- minX: tile.column - tile.spacing,
4130
- minY: tile.row - tile.spacing,
4131
- maxX: tile.column + source.width * tile.spacing,
4132
- maxY: tile.row + source.height * tile.spacing
4133
- }, charge).map((id) => sources[id])) ?? sources;
4139
+ const candidates = (index == null ? void 0 : index(tile.haloBounds, charge).map((id) => sources[id])) ?? sources;
4134
4140
  for (let y = 0; y < height; y++)
4135
4141
  for (let x = 0; x < width; x++) {
4136
4142
  const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
4137
- if (![gx, gy].every(Number.isSafeInteger))
4143
+ if (!Number.isSafeInteger(gx) || !Number.isSafeInteger(gy))
4138
4144
  throw new Error("Mixed halo lattice overflow");
4139
- for (const candidate of candidates) {
4145
+ for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
4146
+ const candidate = candidates[candidateIndex];
4140
4147
  charge();
4141
4148
  const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
4142
4149
  const f = candidate.source;
@@ -4179,6 +4186,36 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4179
4186
  })
4180
4187
  };
4181
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
+ }
4182
4219
 
4183
4220
  // dist/terrain/mixed-halo-update.js
4184
4221
  var key = (t) => `${t.spacing}/${t.column}/${t.row}`;
@@ -4224,14 +4261,21 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4224
4261
  const budget = options.maxDependencyTests ?? 1e7;
4225
4262
  if (!Number.isSafeInteger(budget) || budget < 0)
4226
4263
  throw new Error("Invalid mixed halo dependency budget");
4227
- const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4228
- const current = new Map(resident.map((t) => [key(t), t]));
4229
- const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key(t), t]));
4230
- const targets = /* @__PURE__ */ new Set();
4231
4264
  const unchangedLayout = (previous == null ? void 0 : previous.sources.length) === resident.length && resident.every((tile, i) => {
4232
4265
  const prior = previous.sources[i];
4233
- return key(prior) === key(tile) && prior.field.width === tile.field.width && prior.field.height === tile.field.height;
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;
4234
4267
  });
4268
+ const old = unchangedLayout ? void 0 : new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
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
+ }
4235
4279
  let index = unchangedLayout && previous ? targetIndexes.get(previous) : void 0;
4236
4280
  let tests = 0;
4237
4281
  const charge = () => {
@@ -4243,12 +4287,13 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4243
4287
  for (const id of index(box, charge))
4244
4288
  targets.add(key(resident[id]));
4245
4289
  }
4246
- for (const tile of resident) {
4247
- const address = key(tile);
4248
- const prior = old.get(address);
4249
- if (!cached.has(address) || prior !== tile)
4250
- targets.add(address);
4251
- if (prior === tile || !previous)
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)
4252
4297
  continue;
4253
4298
  if (!prior) {
4254
4299
  invalidate(bounds(tile));
@@ -4261,24 +4306,44 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4261
4306
  invalidate(dirty);
4262
4307
  }
4263
4308
  }
4264
- for (const [address, tile] of old) {
4265
- if (!current.has(address) && resident.length)
4266
- invalidate(bounds(tile));
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
+ }
4267
4319
  }
4268
4320
  const priorPreparation = previous && preparations.get(previous);
4269
4321
  const preparation = {
4270
- fields: (priorPreparation == null ? void 0 : priorPreparation.fields) ?? /* @__PURE__ */ new WeakMap(),
4322
+ tiles: (priorPreparation == null ? void 0 : priorPreparation.tiles) ?? /* @__PURE__ */ new WeakMap(),
4271
4323
  layout: priorPreparation == null ? void 0 : priorPreparation.layout
4272
4324
  };
4273
4325
  const built = buildMixedVertexTileHalos(resident, options, targets, preparation).tiles;
4274
- for (const tile of built)
4275
- cached.set(key(tile), tile);
4276
- const tiles = resident.map((t) => cached.get(key(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
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
+ }
4277
4342
  const snapshot = {
4278
4343
  sources: resident.slice(),
4279
4344
  tiles,
4280
4345
  rebuilt: built.map(key),
4281
- removed: [...old.keys()].filter((k) => !current.has(k)).sort()
4346
+ removed: removed.sort()
4282
4347
  };
4283
4348
  preparations.set(snapshot, preparation);
4284
4349
  if (index)
@@ -5590,12 +5655,12 @@ function meshValidDomain(field, options, constraints) {
5590
5655
  const { width, height, origin, heightReference } = regular;
5591
5656
  const active = new Uint8Array(count);
5592
5657
  const boundary = /* @__PURE__ */ new Map();
5593
- const edgeKey2 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
5658
+ const edgeKey3 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
5594
5659
  for (let i = 0; i < regular.indices.length; i += 3) {
5595
5660
  for (let j = 0; j < 3; j++) {
5596
5661
  const a = regular.indices[i + j], b = regular.indices[i + (j + 1) % 3];
5597
5662
  active[a] = 1;
5598
- const key2 = edgeKey2(a, b);
5663
+ const key2 = edgeKey3(a, b);
5599
5664
  if (!boundary.delete(key2))
5600
5665
  boundary.set(key2, [a, b]);
5601
5666
  }
@@ -5800,8 +5865,8 @@ function createBreaklineTerrainMesh(field, options) {
5800
5865
  continue;
5801
5866
  }
5802
5867
  const r = points[c], s = points[d];
5803
- const intersects2 = Math.sign(cross(p, q, r)) * Math.sign(cross(p, q, s)) < 0 && Math.sign(cross(r, s, p)) * Math.sign(cross(r, s, q)) < 0;
5804
- if (intersects2 || c !== a && c !== b && onSegment(p, q, r) || d !== a && d !== b && onSegment(p, q, s) || a !== c && a !== d && onSegment(r, s, p) || b !== c && b !== d && onSegment(r, s, q)) {
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)) {
5805
5870
  throw new Error("Breaklines and domain edges must meet only at shared endpoints");
5806
5871
  }
5807
5872
  }
@@ -6034,21 +6099,21 @@ function wrapTerrainLongitude(longitude, west, east) {
6034
6099
  function measureGeographicTerrainSeam(a, b, probes, options = {}) {
6035
6100
  if (a && b && a.heightReference !== b.heightReference)
6036
6101
  throw new Error("Terrain seam height references differ");
6037
- const sample = (field, longitude, latitude) => {
6102
+ const sample = (field, longitude, latitude2) => {
6038
6103
  if (!field || !Number.isFinite(longitude))
6039
- return field == null ? void 0 : field.sample(longitude, latitude, options);
6104
+ return field == null ? void 0 : field.sample(longitude, latitude2, options);
6040
6105
  const mapped = wrapTerrainLongitude(longitude, field.bounds[0], field.bounds[2]);
6041
- return field.sample(mapped ?? longitude, latitude, options);
6106
+ return field.sample(mapped ?? longitude, latitude2, options);
6042
6107
  };
6043
- return probes.map(([longitude, latitude]) => {
6044
- const left = sample(a, longitude, latitude);
6045
- const right = sample(b, longitude, latitude);
6108
+ return probes.map(([longitude, latitude2]) => {
6109
+ const left = sample(a, longitude, latitude2);
6110
+ const right = sample(b, longitude, latitude2);
6046
6111
  const valid = (left == null ? void 0 : left.status) === TerrainSampleStatus.VALID && (right == null ? void 0 : right.status) === TerrainSampleStatus.VALID;
6047
6112
  const derivatives = (left == null ? void 0 : left.gradientStatus) === TerrainSampleStatus.VALID && (right == null ? void 0 : right.gradientStatus) === TerrainSampleStatus.VALID;
6048
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;
6049
6114
  return {
6050
6115
  longitude,
6051
- latitude,
6116
+ latitude: latitude2,
6052
6117
  statusA: (left == null ? void 0 : left.status) ?? TerrainSampleStatus.NOT_RESIDENT,
6053
6118
  statusB: (right == null ? void 0 : right.status) ?? TerrainSampleStatus.NOT_RESIDENT,
6054
6119
  gradientStatusA: (left == null ? void 0 : left.gradientStatus) ?? TerrainSampleStatus.NOT_RESIDENT,
@@ -6059,15 +6124,75 @@ function measureGeographicTerrainSeam(a, b, probes, options = {}) {
6059
6124
  });
6060
6125
  }
6061
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
+
6062
6189
  // dist/terrain/lod-select.js
6063
6190
  function selectTerrainLod(roots, view) {
6064
6191
  var _a;
6065
- const { position, verticalFov, viewportHeight, targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
6066
- if (!position.every(Number.isFinite) || !Number.isFinite(verticalFov) || verticalFov <= 0 || verticalFov >= Math.PI || !Number.isFinite(viewportHeight) || viewportHeight <= 0 || !Number.isFinite(targetPixels) || targetPixels <= 0 || !(hysteresis >= 0 && hysteresis < 1) || !Number.isSafeInteger(maxVisited) || maxVisited < 1)
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)
6067
6194
  throw new Error("Invalid terrain LOD view");
6068
- const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
6069
- if (!Number.isFinite(scale))
6070
- throw new Error("Terrain LOD projection scale overflow");
6195
+ const pixelError = "projection" in view ? prepareTerrainLodScreenError(view.projection) : createDistanceEstimator(view.position, view.verticalFov, view.viewportHeight);
6071
6196
  const selected = [];
6072
6197
  const refined = /* @__PURE__ */ new Set();
6073
6198
  const unavailable = [];
@@ -6080,14 +6205,13 @@ function selectTerrainLod(roots, view) {
6080
6205
  if (seen.has(tile.id))
6081
6206
  throw new Error("Duplicate terrain LOD tile or cycle");
6082
6207
  seen.add(tile.id);
6083
- if (![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) || tile.geometricError < 0 || tile.min.some((n, i) => n > tile.max[i]))
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]))
6084
6209
  throw new Error("Invalid terrain LOD tile bounds or error");
6085
6210
  if (!tile.resident) {
6086
6211
  unavailable.push(tile.id);
6087
6212
  continue;
6088
6213
  }
6089
- const distance = Math.hypot(...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
6090
- const pixels = tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale;
6214
+ const pixels = pixelError(tile);
6091
6215
  const threshold = targetPixels * ((previouslyRefined == null ? void 0 : previouslyRefined.has(tile.id)) ? 1 - hysteresis : 1);
6092
6216
  if (pixels > threshold && ((_a = tile.children) == null ? void 0 : _a.length) && tile.children.every((child) => child.resident)) {
6093
6217
  if (pending.length + seen.size + tile.children.length > maxVisited)
@@ -6101,6 +6225,17 @@ function selectTerrainLod(roots, view) {
6101
6225
  }
6102
6226
  return { selected, refined, unavailable };
6103
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
+ }
6104
6239
 
6105
6240
  // dist/terrain/lod-stitch.js
6106
6241
  function stitchTerrainLodCut(input, seams) {
@@ -6197,14 +6332,14 @@ function splitTerrainBreaklines(input, options = {}) {
6197
6332
  throw new Error("Breakline output limit exceeded");
6198
6333
  knots.push({ t, point });
6199
6334
  };
6200
- const cross3 = (ax, ay, bx, by) => ax * by - ay * bx;
6335
+ const cross4 = (ax, ay, bx, by) => ax * by - ay * bx;
6201
6336
  for (let i = 0; i < lines.length; i++) {
6202
6337
  const a = lines[i];
6203
6338
  for (let j = i + 1; j < lines.length; j++) {
6204
6339
  const b = lines[j];
6205
6340
  const x = b.p[0] - a.p[0], y = b.p[1] - a.p[1];
6206
- const det = cross3(a.dx, a.dy, b.dx, b.dy);
6207
- const u = cross3(x, y, a.dx, a.dy), t = cross3(x, y, b.dx, b.dy);
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);
6208
6343
  if (![det, u, t].every(Number.isFinite))
6209
6344
  throw new Error("Breakline intersection overflow");
6210
6345
  if (det === 0) {
@@ -6613,9 +6748,12 @@ var cross2 = (a, b) => [
6613
6748
  var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
6614
6749
  var edges = ([a, b, c]) => [sub2(b, a), sub2(c, b), sub2(a, c)];
6615
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) {
6616
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)))
6617
6755
  throw new RangeError("Invalid terrain polytope sweep");
6618
- const vertices = collider.vertices.map((point) => sub2(point, surface.origin));
6756
+ const vertices = collider.vertices.map((point) => sub2(point, origin));
6619
6757
  const normals = [];
6620
6758
  const directions = [];
6621
6759
  for (const face of collider.faces) {
@@ -6628,7 +6766,7 @@ function sweepTerrainPolytope(surface, collider, translation, { maxWork = 1e5 }
6628
6766
  normals.push(normal);
6629
6767
  directions.push(...side);
6630
6768
  }
6631
- return sweepTriangles(surface.copyData(), vertices, normals, directions, translation, maxWork);
6769
+ return sweepTriangles(data, vertices, normals, directions, translation, maxWork, void 0, padding);
6632
6770
  }
6633
6771
  function sweepTerrainTriangleMesh(surface, collider, translation, { maxWork = 1e5 } = {}) {
6634
6772
  if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite))
@@ -6658,7 +6796,7 @@ function sweepTerrainTriangleMesh(surface, collider, translation, { maxWork = 1e
6658
6796
  }
6659
6797
  return best ? { ...best, work } : { status: "miss", work };
6660
6798
  }
6661
- function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal) {
6799
+ function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal, padding = 0) {
6662
6800
  let work = 0;
6663
6801
  let best;
6664
6802
  const vertex = (index) => {
@@ -6704,6 +6842,8 @@ function sweepTriangles(data, vertices, normals, directions, translation, maxWor
6704
6842
  min = Math.min(min, projection);
6705
6843
  max = Math.max(max, projection);
6706
6844
  }
6845
+ min -= padding;
6846
+ max += padding;
6707
6847
  const speed = dot(translation, unit);
6708
6848
  if (![low, high, min, max, speed, length].every(Number.isFinite))
6709
6849
  throw new RangeError("Terrain polytope projection overflow");
@@ -6732,6 +6872,9 @@ function sweepTriangles(data, vertices, normals, directions, translation, maxWor
6732
6872
  return best ? { ...best, work } : { status: "miss", work };
6733
6873
  }
6734
6874
  function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6875
+ return sweepTerrainPolytope(surface, createSweepBox(center, halfExtents), translation, options);
6876
+ }
6877
+ function createSweepBox(center, halfExtents) {
6735
6878
  if (halfExtents.length !== 3 || halfExtents.some((value) => !(value > 0)))
6736
6879
  throw new RangeError("Terrain box half extents must be positive");
6737
6880
  const vertices = Array.from({ length: 8 }, (_, i) => [
@@ -6739,7 +6882,7 @@ function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6739
6882
  center[1] + (i & 2 ? 1 : -1) * halfExtents[1],
6740
6883
  center[2] + (i & 4 ? 1 : -1) * halfExtents[2]
6741
6884
  ]);
6742
- return sweepTerrainPolytope(surface, {
6885
+ return {
6743
6886
  vertices,
6744
6887
  faces: [
6745
6888
  [0, 1, 3],
@@ -6755,7 +6898,102 @@ function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6755
6898
  [1, 5, 7],
6756
6899
  [1, 7, 3]
6757
6900
  ]
6758
- }, translation, options);
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);
6759
6997
  }
6760
6998
 
6761
6999
  // dist/terrain/sweep-cylinder.js
@@ -6929,11 +7167,11 @@ function discoverGeographicTerrainLodSeams(cut) {
6929
7167
 
6930
7168
  // dist/terrain/geographic-poles.js
6931
7169
  function discoverGeographicTerrainPoles(cut) {
6932
- function collect(latitude, edge2) {
7170
+ function collect(latitude2, edge2) {
6933
7171
  const incident = [];
6934
7172
  for (let tile = 0; tile < cut.length; tile++) {
6935
7173
  const [west, south, east, north] = getGeographicTileBounds(cut[tile]);
6936
- if ((edge2 === "north" ? north : south) === latitude)
7174
+ if ((edge2 === "north" ? north : south) === latitude2)
6937
7175
  incident.push({ tile, edge: edge2, longitude: [west, east] });
6938
7176
  }
6939
7177
  incident.sort((a, b) => a.longitude[0] - b.longitude[0]);
@@ -6948,8 +7186,1192 @@ function discoverGeographicTerrainPoles(cut) {
6948
7186
  }
6949
7187
  if (cursor < 180)
6950
7188
  gaps.push([cursor, 180]);
6951
- return { latitude, incident, gaps };
7189
+ return { latitude: latitude2, incident, gaps };
6952
7190
  }
6953
7191
  return { north: collect(90, "north"), south: collect(-90, "south") };
6954
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
+ }
6955
8377
  //# sourceMappingURL=index.cjs.map