@loaders.gl/tiles 5.0.0-alpha.12 → 5.0.0-alpha.13

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 (716) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +18 -72
  3. package/dist/dist.dev.js +6979 -42928
  4. package/dist/dist.min.js +3 -22
  5. package/dist/image-set.d.ts +1 -1
  6. package/dist/image-set.d.ts.map +1 -1
  7. package/dist/index.cjs +2847 -8781
  8. package/dist/index.cjs.map +3 -4
  9. package/dist/index.d.ts +4 -45
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +3 -27
  12. package/dist/index.js.map +1 -1
  13. package/dist/mlt/bundled.d.ts +3 -0
  14. package/dist/mlt/bundled.d.ts.map +1 -0
  15. package/dist/mlt/bundled.js +5 -0
  16. package/dist/mlt/bundled.js.map +1 -0
  17. package/dist/mlt/index.cjs +3701 -0
  18. package/dist/mlt/index.cjs.map +6 -0
  19. package/dist/mlt/index.d.ts +10 -0
  20. package/dist/mlt/index.d.ts.map +1 -0
  21. package/dist/mlt/index.js +12 -0
  22. package/dist/mlt/index.js.map +1 -0
  23. package/dist/mlt/lib/encode-mlt-geometry.d.ts +6 -0
  24. package/dist/mlt/lib/encode-mlt-geometry.d.ts.map +1 -0
  25. package/dist/mlt/lib/encode-mlt-geometry.js +150 -0
  26. package/dist/mlt/lib/encode-mlt-geometry.js.map +1 -0
  27. package/dist/mlt/lib/encode-mlt-streams.d.ts +13 -0
  28. package/dist/mlt/lib/encode-mlt-streams.d.ts.map +1 -0
  29. package/dist/mlt/lib/encode-mlt-streams.js +57 -0
  30. package/dist/mlt/lib/encode-mlt-streams.js.map +1 -0
  31. package/dist/mlt/lib/encode-mlt.d.ts +6 -0
  32. package/dist/mlt/lib/encode-mlt.d.ts.map +1 -0
  33. package/dist/mlt/lib/encode-mlt.js +174 -0
  34. package/dist/mlt/lib/encode-mlt.js.map +1 -0
  35. package/dist/mlt/lib/parse-mlt.d.ts +11 -0
  36. package/dist/mlt/lib/parse-mlt.d.ts.map +1 -0
  37. package/dist/mlt/lib/parse-mlt.js +675 -0
  38. package/dist/mlt/lib/parse-mlt.js.map +1 -0
  39. package/dist/mlt/mlt-format.d.ts +14 -0
  40. package/dist/mlt/mlt-format.d.ts.map +1 -0
  41. package/dist/mlt/mlt-format.js +17 -0
  42. package/dist/mlt/mlt-format.js.map +1 -0
  43. package/dist/mlt/mlt-loader-with-parser.d.ts +91 -0
  44. package/dist/mlt/mlt-loader-with-parser.d.ts.map +1 -0
  45. package/dist/mlt/mlt-loader-with-parser.js +29 -0
  46. package/dist/mlt/mlt-loader-with-parser.js.map +1 -0
  47. package/dist/mlt/mlt-loader.d.ts +115 -0
  48. package/dist/mlt/mlt-loader.d.ts.map +1 -0
  49. package/dist/mlt/mlt-loader.js +38 -0
  50. package/dist/mlt/mlt-loader.js.map +1 -0
  51. package/dist/mlt/mlt-source-loader.d.ts +82 -0
  52. package/dist/mlt/mlt-source-loader.d.ts.map +1 -0
  53. package/dist/mlt/mlt-source-loader.js +179 -0
  54. package/dist/mlt/mlt-source-loader.js.map +1 -0
  55. package/dist/mlt/mlt-writer.d.ts +45 -0
  56. package/dist/mlt/mlt-writer.d.ts.map +1 -0
  57. package/dist/mlt/mlt-writer.js +21 -0
  58. package/dist/mlt/mlt-writer.js.map +1 -0
  59. package/dist/mlt/unbundled.d.ts +3 -0
  60. package/dist/mlt/unbundled.d.ts.map +1 -0
  61. package/dist/mlt/unbundled.js +5 -0
  62. package/dist/mlt/unbundled.js.map +1 -0
  63. package/dist/mvt/arrow-table-tile-source-loader-types.d.ts +36 -0
  64. package/dist/mvt/arrow-table-tile-source-loader-types.d.ts.map +1 -0
  65. package/dist/mvt/arrow-table-tile-source-loader-types.js +36 -0
  66. package/dist/mvt/arrow-table-tile-source-loader-types.js.map +1 -0
  67. package/dist/mvt/arrow-table-tile-source-loader.cjs +6343 -0
  68. package/dist/mvt/arrow-table-tile-source-loader.cjs.map +6 -0
  69. package/dist/mvt/arrow-table-tile-source-loader.d.ts +69 -0
  70. package/dist/mvt/arrow-table-tile-source-loader.d.ts.map +1 -0
  71. package/dist/mvt/arrow-table-tile-source-loader.js +216 -0
  72. package/dist/mvt/arrow-table-tile-source-loader.js.map +1 -0
  73. package/dist/mvt/arrow-table-tile-source-types.d.ts +21 -0
  74. package/dist/mvt/arrow-table-tile-source-types.d.ts.map +1 -0
  75. package/dist/mvt/arrow-table-tile-source-types.js +6 -0
  76. package/dist/mvt/arrow-table-tile-source-types.js.map +1 -0
  77. package/dist/mvt/bundled.d.ts +6 -0
  78. package/dist/mvt/bundled.d.ts.map +1 -0
  79. package/dist/mvt/bundled.js +7 -0
  80. package/dist/mvt/bundled.js.map +1 -0
  81. package/dist/mvt/dist.dev.js +46689 -0
  82. package/dist/mvt/dist.min.js +94 -0
  83. package/dist/mvt/index.cjs +10095 -0
  84. package/dist/mvt/index.cjs.map +6 -0
  85. package/dist/mvt/index.d.ts +28 -0
  86. package/dist/mvt/index.d.ts.map +1 -0
  87. package/dist/mvt/index.js +27 -0
  88. package/dist/mvt/index.js.map +1 -0
  89. package/dist/mvt/lib/encode-mvt-arrow.d.ts +6 -0
  90. package/dist/mvt/lib/encode-mvt-arrow.d.ts.map +1 -0
  91. package/dist/mvt/lib/encode-mvt-arrow.js +225 -0
  92. package/dist/mvt/lib/encode-mvt-arrow.js.map +1 -0
  93. package/dist/mvt/lib/encode-mvt.d.ts +30 -0
  94. package/dist/mvt/lib/encode-mvt.d.ts.map +1 -0
  95. package/dist/mvt/lib/encode-mvt.js +20 -0
  96. package/dist/mvt/lib/encode-mvt.js.map +1 -0
  97. package/dist/mvt/lib/get-schemas-from-tilejson.d.ts +4 -0
  98. package/dist/mvt/lib/get-schemas-from-tilejson.d.ts.map +1 -0
  99. package/dist/mvt/lib/get-schemas-from-tilejson.js +56 -0
  100. package/dist/mvt/lib/get-schemas-from-tilejson.js.map +1 -0
  101. package/dist/mvt/lib/is-longitude-latitude-crs.d.ts +3 -0
  102. package/dist/mvt/lib/is-longitude-latitude-crs.d.ts.map +1 -0
  103. package/dist/mvt/lib/is-longitude-latitude-crs.js +13 -0
  104. package/dist/mvt/lib/is-longitude-latitude-crs.js.map +1 -0
  105. package/dist/mvt/lib/mapbox-vt-pbf/geojson-wrapper.d.ts +25 -0
  106. package/dist/mvt/lib/mapbox-vt-pbf/geojson-wrapper.d.ts.map +1 -0
  107. package/dist/mvt/lib/mapbox-vt-pbf/geojson-wrapper.js +73 -0
  108. package/dist/mvt/lib/mapbox-vt-pbf/geojson-wrapper.js.map +1 -0
  109. package/dist/mvt/lib/mapbox-vt-pbf/to-vector-tile.d.ts +52 -0
  110. package/dist/mvt/lib/mapbox-vt-pbf/to-vector-tile.d.ts.map +1 -0
  111. package/dist/mvt/lib/mapbox-vt-pbf/to-vector-tile.js +165 -0
  112. package/dist/mvt/lib/mapbox-vt-pbf/to-vector-tile.js.map +1 -0
  113. package/dist/mvt/lib/mvt-pbf/mvt-constants.d.ts +116 -0
  114. package/dist/mvt/lib/mvt-pbf/mvt-constants.d.ts.map +1 -0
  115. package/dist/mvt/lib/mvt-pbf/mvt-constants.js +127 -0
  116. package/dist/mvt/lib/mvt-pbf/mvt-constants.js.map +1 -0
  117. package/dist/mvt/lib/mvt-pbf/mvt-types.d.ts +17 -0
  118. package/dist/mvt/lib/mvt-pbf/mvt-types.d.ts.map +1 -0
  119. package/dist/mvt/lib/mvt-pbf/mvt-types.js +5 -0
  120. package/dist/mvt/lib/mvt-pbf/mvt-types.js.map +1 -0
  121. package/dist/mvt/lib/mvt-pbf/parse-geometry-from-pbf.d.ts +77 -0
  122. package/dist/mvt/lib/mvt-pbf/parse-geometry-from-pbf.d.ts.map +1 -0
  123. package/dist/mvt/lib/mvt-pbf/parse-geometry-from-pbf.js +235 -0
  124. package/dist/mvt/lib/mvt-pbf/parse-geometry-from-pbf.js.map +1 -0
  125. package/dist/mvt/lib/mvt-pbf/parse-mvt-from-pbf.d.ts +25 -0
  126. package/dist/mvt/lib/mvt-pbf/parse-mvt-from-pbf.d.ts.map +1 -0
  127. package/dist/mvt/lib/mvt-pbf/parse-mvt-from-pbf.js +263 -0
  128. package/dist/mvt/lib/mvt-pbf/parse-mvt-from-pbf.js.map +1 -0
  129. package/dist/mvt/lib/mvt-pbf/write-mvt-to-pbf.d.ts +4 -0
  130. package/dist/mvt/lib/mvt-pbf/write-mvt-to-pbf.d.ts.map +1 -0
  131. package/dist/mvt/lib/mvt-pbf/write-mvt-to-pbf.js +134 -0
  132. package/dist/mvt/lib/mvt-pbf/write-mvt-to-pbf.js.map +1 -0
  133. package/dist/mvt/lib/mvt-worker-transport.d.ts +15 -0
  134. package/dist/mvt/lib/mvt-worker-transport.d.ts.map +1 -0
  135. package/dist/mvt/lib/mvt-worker-transport.js +54 -0
  136. package/dist/mvt/lib/mvt-worker-transport.js.map +1 -0
  137. package/dist/mvt/lib/parse-mvt-geojson.d.ts +6 -0
  138. package/dist/mvt/lib/parse-mvt-geojson.d.ts.map +1 -0
  139. package/dist/mvt/lib/parse-mvt-geojson.js +48 -0
  140. package/dist/mvt/lib/parse-mvt-geojson.js.map +1 -0
  141. package/dist/mvt/lib/parse-mvt.d.ts +14 -0
  142. package/dist/mvt/lib/parse-mvt.d.ts.map +1 -0
  143. package/dist/mvt/lib/parse-mvt.js +105 -0
  144. package/dist/mvt/lib/parse-mvt.js.map +1 -0
  145. package/dist/mvt/lib/parse-tilejson.d.ts +74 -0
  146. package/dist/mvt/lib/parse-tilejson.d.ts.map +1 -0
  147. package/dist/mvt/lib/parse-tilejson.js +267 -0
  148. package/dist/mvt/lib/parse-tilejson.js.map +1 -0
  149. package/dist/mvt/lib/resolve-table-tile-parameters.d.ts +4 -0
  150. package/dist/mvt/lib/resolve-table-tile-parameters.d.ts.map +1 -0
  151. package/dist/mvt/lib/resolve-table-tile-parameters.js +16 -0
  152. package/dist/mvt/lib/resolve-table-tile-parameters.js.map +1 -0
  153. package/dist/mvt/lib/types.d.ts +88 -0
  154. package/dist/mvt/lib/types.d.ts.map +1 -0
  155. package/dist/mvt/lib/types.js.map +1 -0
  156. package/dist/mvt/lib/utils/geometry-utils.d.ts +83 -0
  157. package/dist/mvt/lib/utils/geometry-utils.d.ts.map +1 -0
  158. package/dist/mvt/lib/utils/geometry-utils.js +211 -0
  159. package/dist/mvt/lib/utils/geometry-utils.js.map +1 -0
  160. package/dist/mvt/lib/vector-tile/vector-tile-feature.d.ts +72 -0
  161. package/dist/mvt/lib/vector-tile/vector-tile-feature.d.ts.map +1 -0
  162. package/dist/mvt/lib/vector-tile/vector-tile-feature.js +350 -0
  163. package/dist/mvt/lib/vector-tile/vector-tile-feature.js.map +1 -0
  164. package/dist/mvt/lib/vector-tile/vector-tile-layer.d.ts +29 -0
  165. package/dist/mvt/lib/vector-tile/vector-tile-layer.d.ts.map +1 -0
  166. package/dist/mvt/lib/vector-tile/vector-tile-layer.js +108 -0
  167. package/dist/mvt/lib/vector-tile/vector-tile-layer.js.map +1 -0
  168. package/dist/mvt/lib/vector-tile/vector-tile.d.ts +9 -0
  169. package/dist/mvt/lib/vector-tile/vector-tile.d.ts.map +1 -0
  170. package/dist/mvt/lib/vector-tile/vector-tile.js +28 -0
  171. package/dist/mvt/lib/vector-tile/vector-tile.js.map +1 -0
  172. package/dist/mvt/lib/vector-tiler/arrow-tile.d.ts +6 -0
  173. package/dist/mvt/lib/vector-tiler/arrow-tile.d.ts.map +1 -0
  174. package/dist/mvt/lib/vector-tiler/arrow-tile.js +84 -0
  175. package/dist/mvt/lib/vector-tiler/arrow-tile.js.map +1 -0
  176. package/dist/mvt/lib/vector-tiler/features/clip-features.d.ts +16 -0
  177. package/dist/mvt/lib/vector-tiler/features/clip-features.d.ts.map +1 -0
  178. package/dist/mvt/lib/vector-tiler/features/clip-features.js +211 -0
  179. package/dist/mvt/lib/vector-tiler/features/clip-features.js.map +1 -0
  180. package/dist/mvt/lib/vector-tiler/features/convert-feature.d.ts +18 -0
  181. package/dist/mvt/lib/vector-tiler/features/convert-feature.d.ts.map +1 -0
  182. package/dist/mvt/lib/vector-tiler/features/convert-feature.js +161 -0
  183. package/dist/mvt/lib/vector-tiler/features/convert-feature.js.map +1 -0
  184. package/dist/mvt/lib/vector-tiler/features/proto-feature.d.ts +30 -0
  185. package/dist/mvt/lib/vector-tiler/features/proto-feature.d.ts.map +1 -0
  186. package/dist/mvt/lib/vector-tiler/features/proto-feature.js +53 -0
  187. package/dist/mvt/lib/vector-tiler/features/proto-feature.js.map +1 -0
  188. package/dist/mvt/lib/vector-tiler/features/simplify-path.d.ts +10 -0
  189. package/dist/mvt/lib/vector-tiler/features/simplify-path.d.ts.map +1 -0
  190. package/dist/mvt/lib/vector-tiler/features/simplify-path.js +67 -0
  191. package/dist/mvt/lib/vector-tiler/features/simplify-path.js.map +1 -0
  192. package/dist/mvt/lib/vector-tiler/features/wrap-features.d.ts +17 -0
  193. package/dist/mvt/lib/vector-tiler/features/wrap-features.d.ts.map +1 -0
  194. package/dist/mvt/lib/vector-tiler/features/wrap-features.js +95 -0
  195. package/dist/mvt/lib/vector-tiler/features/wrap-features.js.map +1 -0
  196. package/dist/mvt/lib/vector-tiler/proto-tile.d.ts +40 -0
  197. package/dist/mvt/lib/vector-tiler/proto-tile.d.ts.map +1 -0
  198. package/dist/mvt/lib/vector-tiler/proto-tile.js +139 -0
  199. package/dist/mvt/lib/vector-tiler/proto-tile.js.map +1 -0
  200. package/dist/mvt/lib/vector-tiler/tile-to-geojson.d.ts +12 -0
  201. package/dist/mvt/lib/vector-tiler/tile-to-geojson.d.ts.map +1 -0
  202. package/dist/mvt/lib/vector-tiler/tile-to-geojson.js +81 -0
  203. package/dist/mvt/lib/vector-tiler/tile-to-geojson.js.map +1 -0
  204. package/dist/mvt/lib/vector-tiler/transform-tile.d.ts +7 -0
  205. package/dist/mvt/lib/vector-tiler/transform-tile.d.ts.map +1 -0
  206. package/dist/mvt/lib/vector-tiler/transform-tile.js +42 -0
  207. package/dist/mvt/lib/vector-tiler/transform-tile.js.map +1 -0
  208. package/dist/mvt/map-style-format.d.ts +13 -0
  209. package/dist/mvt/map-style-format.d.ts.map +1 -0
  210. package/dist/mvt/map-style-format.js +16 -0
  211. package/dist/mvt/map-style-format.js.map +1 -0
  212. package/dist/mvt/map-style-loader-with-parser.d.ts +26 -0
  213. package/dist/mvt/map-style-loader-with-parser.d.ts.map +1 -0
  214. package/dist/mvt/map-style-loader-with-parser.js +38 -0
  215. package/dist/mvt/map-style-loader-with-parser.js.map +1 -0
  216. package/dist/mvt/map-style-loader.d.ts +44 -0
  217. package/dist/mvt/map-style-loader.d.ts.map +1 -0
  218. package/dist/mvt/map-style-loader.js +25 -0
  219. package/dist/mvt/map-style-loader.js.map +1 -0
  220. package/dist/mvt/map-style-schema.d.ts +58 -0
  221. package/dist/mvt/map-style-schema.d.ts.map +1 -0
  222. package/dist/mvt/map-style-schema.js +47 -0
  223. package/dist/mvt/map-style-schema.js.map +1 -0
  224. package/dist/mvt/map-style.d.ts +110 -0
  225. package/dist/mvt/map-style.d.ts.map +1 -0
  226. package/dist/mvt/map-style.js +90 -0
  227. package/dist/mvt/map-style.js.map +1 -0
  228. package/dist/mvt/mvt-format.d.ts +14 -0
  229. package/dist/mvt/mvt-format.d.ts.map +1 -0
  230. package/dist/mvt/mvt-format.js +23 -0
  231. package/dist/mvt/mvt-format.js.map +1 -0
  232. package/dist/mvt/mvt-geojson-loader-types.d.ts +82 -0
  233. package/dist/mvt/mvt-geojson-loader-types.d.ts.map +1 -0
  234. package/dist/mvt/mvt-geojson-loader-types.js +34 -0
  235. package/dist/mvt/mvt-geojson-loader-types.js.map +1 -0
  236. package/dist/mvt/mvt-geojson-loader.cjs +1366 -0
  237. package/dist/mvt/mvt-geojson-loader.cjs.map +6 -0
  238. package/dist/mvt/mvt-geojson-loader.d.ts +32 -0
  239. package/dist/mvt/mvt-geojson-loader.d.ts.map +1 -0
  240. package/dist/mvt/mvt-geojson-loader.js +13 -0
  241. package/dist/mvt/mvt-geojson-loader.js.map +1 -0
  242. package/dist/mvt/mvt-loader-with-parser.d.ts +105 -0
  243. package/dist/mvt/mvt-loader-with-parser.d.ts.map +1 -0
  244. package/dist/mvt/mvt-loader-with-parser.js +21 -0
  245. package/dist/mvt/mvt-loader-with-parser.js.map +1 -0
  246. package/dist/mvt/mvt-loader.d.ts +129 -0
  247. package/dist/mvt/mvt-loader.d.ts.map +1 -0
  248. package/dist/mvt/mvt-loader.js +40 -0
  249. package/dist/mvt/mvt-loader.js.map +1 -0
  250. package/dist/mvt/mvt-source-loader.d.ts +102 -0
  251. package/dist/mvt/mvt-source-loader.d.ts.map +1 -0
  252. package/dist/mvt/mvt-source-loader.js +275 -0
  253. package/dist/mvt/mvt-source-loader.js.map +1 -0
  254. package/dist/mvt/mvt-writer.d.ts +28 -0
  255. package/dist/mvt/mvt-writer.d.ts.map +1 -0
  256. package/dist/mvt/mvt-writer.js +32 -0
  257. package/dist/mvt/mvt-writer.js.map +1 -0
  258. package/dist/mvt/table-tile-source-loader.d.ts +169 -0
  259. package/dist/mvt/table-tile-source-loader.d.ts.map +1 -0
  260. package/dist/mvt/table-tile-source-loader.js +478 -0
  261. package/dist/mvt/table-tile-source-loader.js.map +1 -0
  262. package/dist/mvt/tilejson-format.d.ts +13 -0
  263. package/dist/mvt/tilejson-format.d.ts.map +1 -0
  264. package/dist/mvt/tilejson-format.js +16 -0
  265. package/dist/mvt/tilejson-format.js.map +1 -0
  266. package/dist/mvt/tilejson-loader-with-parser.d.ts +13 -0
  267. package/dist/mvt/tilejson-loader-with-parser.d.ts.map +1 -0
  268. package/dist/mvt/tilejson-loader-with-parser.js +25 -0
  269. package/dist/mvt/tilejson-loader-with-parser.js.map +1 -0
  270. package/dist/mvt/tilejson-loader.d.ts +56 -0
  271. package/dist/mvt/tilejson-loader.d.ts.map +1 -0
  272. package/dist/mvt/tilejson-loader.js +28 -0
  273. package/dist/mvt/tilejson-loader.js.map +1 -0
  274. package/dist/mvt/tilejson-zod-schema.cjs +79 -0
  275. package/dist/mvt/tilejson-zod-schema.cjs.map +6 -0
  276. package/dist/mvt/tilejson-zod-schema.d.ts +218 -0
  277. package/dist/mvt/tilejson-zod-schema.d.ts.map +1 -0
  278. package/dist/mvt/tilejson-zod-schema.js +68 -0
  279. package/dist/mvt/tilejson-zod-schema.js.map +1 -0
  280. package/dist/mvt/tilejson.schema.json +197 -0
  281. package/dist/mvt/unbundled.d.ts +8 -0
  282. package/dist/mvt/unbundled.d.ts.map +1 -0
  283. package/dist/mvt/unbundled.js +8 -0
  284. package/dist/mvt/unbundled.js.map +1 -0
  285. package/dist/mvt/workers/mvt-worker-node.d.ts +2 -0
  286. package/dist/mvt/workers/mvt-worker-node.d.ts.map +1 -0
  287. package/dist/mvt/workers/mvt-worker-node.js +8 -0
  288. package/dist/mvt/workers/mvt-worker-node.js.map +1 -0
  289. package/dist/mvt/workers/mvt-worker.d.ts +2 -0
  290. package/dist/mvt/workers/mvt-worker.d.ts.map +1 -0
  291. package/dist/mvt/workers/mvt-worker.js +7 -0
  292. package/dist/mvt/workers/mvt-worker.js.map +1 -0
  293. package/dist/mvt-worker-node.js +72460 -0
  294. package/dist/mvt-worker-node.js.map +7 -0
  295. package/dist/mvt-worker.js +21239 -0
  296. package/dist/pmtiles/bundled.d.ts +3 -0
  297. package/dist/pmtiles/bundled.d.ts.map +1 -0
  298. package/dist/pmtiles/bundled.js +5 -0
  299. package/dist/pmtiles/bundled.js.map +1 -0
  300. package/dist/pmtiles/dist.dev.js +50530 -0
  301. package/dist/pmtiles/dist.min.js +94 -0
  302. package/dist/pmtiles/geoarrow.cjs +6718 -0
  303. package/dist/pmtiles/geoarrow.cjs.map +6 -0
  304. package/dist/pmtiles/geoarrow.d.ts +30 -0
  305. package/dist/pmtiles/geoarrow.d.ts.map +1 -0
  306. package/dist/pmtiles/geoarrow.js +143 -0
  307. package/dist/pmtiles/geoarrow.js.map +1 -0
  308. package/dist/pmtiles/index.cjs +8011 -0
  309. package/dist/pmtiles/index.cjs.map +6 -0
  310. package/dist/pmtiles/index.d.ts +14 -0
  311. package/dist/pmtiles/index.d.ts.map +1 -0
  312. package/dist/pmtiles/index.js +10 -0
  313. package/dist/pmtiles/index.js.map +1 -0
  314. package/dist/pmtiles/lib/blob-source.d.ts +14 -0
  315. package/dist/pmtiles/lib/blob-source.d.ts.map +1 -0
  316. package/dist/pmtiles/lib/blob-source.js +32 -0
  317. package/dist/pmtiles/lib/blob-source.js.map +1 -0
  318. package/dist/pmtiles/lib/encode-pmtiles.d.ts +8 -0
  319. package/dist/pmtiles/lib/encode-pmtiles.d.ts.map +1 -0
  320. package/dist/pmtiles/lib/encode-pmtiles.js +268 -0
  321. package/dist/pmtiles/lib/encode-pmtiles.js.map +1 -0
  322. package/dist/pmtiles/lib/parse-pmtiles.d.ts +52 -0
  323. package/dist/pmtiles/lib/parse-pmtiles.d.ts.map +1 -0
  324. package/dist/pmtiles/lib/parse-pmtiles.js +95 -0
  325. package/dist/pmtiles/lib/parse-pmtiles.js.map +1 -0
  326. package/dist/pmtiles/lib/range-request-source.d.ts +24 -0
  327. package/dist/pmtiles/lib/range-request-source.d.ts.map +1 -0
  328. package/dist/pmtiles/lib/range-request-source.js +45 -0
  329. package/dist/pmtiles/lib/range-request-source.js.map +1 -0
  330. package/dist/pmtiles/lib/version.d.ts +2 -0
  331. package/dist/pmtiles/lib/version.d.ts.map +1 -0
  332. package/dist/pmtiles/lib/version.js +8 -0
  333. package/dist/pmtiles/lib/version.js.map +1 -0
  334. package/dist/pmtiles/pmtiles-format.d.ts +14 -0
  335. package/dist/pmtiles/pmtiles-format.d.ts.map +1 -0
  336. package/dist/pmtiles/pmtiles-format.js +17 -0
  337. package/dist/pmtiles/pmtiles-format.js.map +1 -0
  338. package/dist/pmtiles/pmtiles-loader-with-parser.d.ts +30 -0
  339. package/dist/pmtiles/pmtiles-loader-with-parser.d.ts.map +1 -0
  340. package/dist/pmtiles/pmtiles-loader-with-parser.js +41 -0
  341. package/dist/pmtiles/pmtiles-loader-with-parser.js.map +1 -0
  342. package/dist/pmtiles/pmtiles-loader.d.ts +41 -0
  343. package/dist/pmtiles/pmtiles-loader.d.ts.map +1 -0
  344. package/dist/pmtiles/pmtiles-loader.js +20 -0
  345. package/dist/pmtiles/pmtiles-loader.js.map +1 -0
  346. package/dist/pmtiles/pmtiles-source-loader.d.ts +85 -0
  347. package/dist/pmtiles/pmtiles-source-loader.d.ts.map +1 -0
  348. package/dist/pmtiles/pmtiles-source-loader.js +239 -0
  349. package/dist/pmtiles/pmtiles-source-loader.js.map +1 -0
  350. package/dist/pmtiles/pmtiles-writer-types.d.ts +39 -0
  351. package/dist/pmtiles/pmtiles-writer-types.d.ts.map +1 -0
  352. package/dist/{point-cloud-tile-source-types.js → pmtiles/pmtiles-writer-types.js} +1 -1
  353. package/dist/pmtiles/pmtiles-writer-types.js.map +1 -0
  354. package/dist/pmtiles/pmtiles-writer.d.ts +22 -0
  355. package/dist/pmtiles/pmtiles-writer.d.ts.map +1 -0
  356. package/dist/pmtiles/pmtiles-writer.js +15 -0
  357. package/dist/pmtiles/pmtiles-writer.js.map +1 -0
  358. package/dist/pmtiles/raster.cjs +1183 -0
  359. package/dist/pmtiles/raster.cjs.map +6 -0
  360. package/dist/pmtiles/raster.d.ts +30 -0
  361. package/dist/pmtiles/raster.d.ts.map +1 -0
  362. package/dist/pmtiles/raster.js +212 -0
  363. package/dist/pmtiles/raster.js.map +1 -0
  364. package/dist/pmtiles/source-info.d.ts +25 -0
  365. package/dist/pmtiles/source-info.d.ts.map +1 -0
  366. package/dist/{types.js → pmtiles/source-info.js} +1 -1
  367. package/dist/pmtiles/source-info.js.map +1 -0
  368. package/dist/pmtiles/unbundled.d.ts +3 -0
  369. package/dist/pmtiles/unbundled.d.ts.map +1 -0
  370. package/dist/pmtiles/unbundled.js +5 -0
  371. package/dist/pmtiles/unbundled.js.map +1 -0
  372. package/dist/raster-set.d.ts +1 -1
  373. package/dist/raster-set.d.ts.map +1 -1
  374. package/dist/raster-set.js +1 -1
  375. package/dist/raster-set.js.map +1 -1
  376. package/dist/tile-matrix.cjs +81 -0
  377. package/dist/tile-matrix.cjs.map +6 -0
  378. package/dist/tile-matrix.d.ts +52 -0
  379. package/dist/tile-matrix.d.ts.map +1 -0
  380. package/dist/tile-matrix.js +75 -0
  381. package/dist/tile-matrix.js.map +1 -0
  382. package/dist/tileset-2d/tile-2d-header.d.ts +2 -2
  383. package/dist/tileset-2d/tile-2d-header.d.ts.map +1 -1
  384. package/dist/tileset-2d/tile-2d-header.js +11 -11
  385. package/dist/tileset-2d/tile-2d-header.js.map +1 -1
  386. package/dist/tileset-2d/tileset-2d.d.ts +19 -10
  387. package/dist/tileset-2d/tileset-2d.d.ts.map +1 -1
  388. package/dist/tileset-2d/tileset-2d.js +69 -15
  389. package/dist/tileset-2d/tileset-2d.js.map +1 -1
  390. package/package.json +101 -25
  391. package/src/image-set.ts +1 -1
  392. package/src/index.ts +8 -128
  393. package/src/mlt/bundled.ts +9 -0
  394. package/src/mlt/index.ts +18 -0
  395. package/src/mlt/lib/encode-mlt-geometry.ts +162 -0
  396. package/src/mlt/lib/encode-mlt-streams.ts +66 -0
  397. package/src/mlt/lib/encode-mlt.ts +215 -0
  398. package/src/mlt/lib/parse-mlt.ts +906 -0
  399. package/src/mlt/libs/mlt-decoder.cjs +4552 -0
  400. package/src/mlt/mlt-format.ts +19 -0
  401. package/src/mlt/mlt-loader-with-parser.ts +57 -0
  402. package/src/mlt/mlt-loader.ts +64 -0
  403. package/src/mlt/mlt-source-loader.ts +266 -0
  404. package/src/mlt/mlt-writer.ts +47 -0
  405. package/src/mlt/unbundled.ts +6 -0
  406. package/src/mvt/arrow-table-tile-source-loader-types.ts +55 -0
  407. package/src/mvt/arrow-table-tile-source-loader.ts +307 -0
  408. package/src/mvt/arrow-table-tile-source-types.ts +32 -0
  409. package/src/mvt/bundled.ts +14 -0
  410. package/src/mvt/index.ts +67 -0
  411. package/src/mvt/lib/encode-mvt-arrow.ts +273 -0
  412. package/src/mvt/lib/encode-mvt.ts +46 -0
  413. package/src/mvt/lib/get-schemas-from-tilejson.ts +64 -0
  414. package/src/mvt/lib/is-longitude-latitude-crs.ts +15 -0
  415. package/src/mvt/lib/mapbox-vt-pbf/geojson-to-vt.ts.disabled +76 -0
  416. package/src/mvt/lib/mapbox-vt-pbf/geojson-wrapper.ts +89 -0
  417. package/src/mvt/lib/mapbox-vt-pbf/to-vector-tile.ts +230 -0
  418. package/src/mvt/lib/mvt-pbf/mvt-constants.ts +135 -0
  419. package/src/mvt/lib/mvt-pbf/mvt-types.ts +22 -0
  420. package/src/mvt/lib/mvt-pbf/parse-geometry-from-pbf.ts +285 -0
  421. package/src/mvt/lib/mvt-pbf/parse-mvt-from-pbf.ts +310 -0
  422. package/src/mvt/lib/mvt-pbf/write-mvt-to-pbf.ts +162 -0
  423. package/src/mvt/lib/mvt-worker-transport.ts +74 -0
  424. package/src/mvt/lib/parse-mvt-geojson.ts +65 -0
  425. package/src/mvt/lib/parse-mvt.ts +145 -0
  426. package/src/mvt/lib/parse-tilejson.ts +397 -0
  427. package/src/mvt/lib/resolve-table-tile-parameters.ts +23 -0
  428. package/src/mvt/lib/types.ts +90 -0
  429. package/src/mvt/lib/utils/geometry-utils.ts +238 -0
  430. package/src/mvt/lib/vector-tile/LICENSE.txt +31 -0
  431. package/src/mvt/lib/vector-tile/vector-tile-feature.ts +430 -0
  432. package/src/mvt/lib/vector-tile/vector-tile-layer.ts +130 -0
  433. package/src/mvt/lib/vector-tile/vector-tile.ts +32 -0
  434. package/src/mvt/lib/vector-tiler/LICENSE +19 -0
  435. package/src/mvt/lib/vector-tiler/arrow-tile.ts +93 -0
  436. package/src/mvt/lib/vector-tiler/features/clip-features.ts +250 -0
  437. package/src/mvt/lib/vector-tiler/features/convert-feature.ts +213 -0
  438. package/src/mvt/lib/vector-tiler/features/proto-feature.ts +104 -0
  439. package/src/mvt/lib/vector-tiler/features/simplify-path.ts +84 -0
  440. package/src/mvt/lib/vector-tiler/features/wrap-features.ts +125 -0
  441. package/src/mvt/lib/vector-tiler/proto-tile.ts +217 -0
  442. package/src/mvt/lib/vector-tiler/tile-to-geojson.ts +104 -0
  443. package/src/mvt/lib/vector-tiler/transform-tile.ts +57 -0
  444. package/src/mvt/map-style-format.ts +18 -0
  445. package/src/mvt/map-style-loader-with-parser.ts +62 -0
  446. package/src/mvt/map-style-loader.ts +31 -0
  447. package/src/mvt/map-style-schema.ts +53 -0
  448. package/src/mvt/map-style.ts +218 -0
  449. package/src/mvt/mvt-format.ts +25 -0
  450. package/src/mvt/mvt-geojson-loader-types.ts +60 -0
  451. package/src/mvt/mvt-geojson-loader.ts +20 -0
  452. package/src/mvt/mvt-loader-with-parser.ts +53 -0
  453. package/src/mvt/mvt-loader.ts +73 -0
  454. package/src/mvt/mvt-source-loader.ts +410 -0
  455. package/src/mvt/mvt-writer.ts +35 -0
  456. package/src/mvt/table-tile-source-loader.ts +672 -0
  457. package/src/mvt/tilejson-format.ts +18 -0
  458. package/src/mvt/tilejson-loader-with-parser.ts +38 -0
  459. package/src/mvt/tilejson-loader.ts +42 -0
  460. package/src/mvt/tilejson-zod-schema.ts +199 -0
  461. package/src/mvt/unbundled.ts +13 -0
  462. package/src/mvt/workers/mvt-worker-node.ts +9 -0
  463. package/src/mvt/workers/mvt-worker.ts +8 -0
  464. package/src/pmtiles/bundled.ts +6 -0
  465. package/src/pmtiles/geoarrow.ts +188 -0
  466. package/src/pmtiles/index.ts +27 -0
  467. package/src/pmtiles/lib/blob-source.ts +41 -0
  468. package/src/pmtiles/lib/encode-pmtiles.ts +322 -0
  469. package/src/pmtiles/lib/parse-pmtiles.ts +180 -0
  470. package/src/pmtiles/lib/range-request-source.ts +60 -0
  471. package/src/pmtiles/lib/version.ts +8 -0
  472. package/src/pmtiles/pmtiles-format.ts +19 -0
  473. package/src/pmtiles/pmtiles-loader-with-parser.ts +60 -0
  474. package/src/pmtiles/pmtiles-loader.ts +30 -0
  475. package/src/pmtiles/pmtiles-source-loader.ts +346 -0
  476. package/src/pmtiles/pmtiles-writer-types.ts +45 -0
  477. package/src/pmtiles/pmtiles-writer.ts +26 -0
  478. package/src/pmtiles/raster.ts +289 -0
  479. package/src/pmtiles/source-info.ts +25 -0
  480. package/src/pmtiles/unbundled.ts +6 -0
  481. package/src/raster-set.ts +2 -2
  482. package/src/tile-matrix.ts +138 -0
  483. package/src/tileset-2d/tile-2d-header.ts +14 -13
  484. package/src/tileset-2d/tileset-2d.ts +81 -19
  485. package/dist/constants.d.ts +0 -38
  486. package/dist/constants.d.ts.map +0 -1
  487. package/dist/constants.js +0 -39
  488. package/dist/constants.js.map +0 -1
  489. package/dist/point-cloud/point-cloud-tile.d.ts +0 -47
  490. package/dist/point-cloud/point-cloud-tile.d.ts.map +0 -1
  491. package/dist/point-cloud/point-cloud-tile.js +0 -70
  492. package/dist/point-cloud/point-cloud-tile.js.map +0 -1
  493. package/dist/point-cloud/point-cloud-tileset.d.ts +0 -135
  494. package/dist/point-cloud/point-cloud-tileset.d.ts.map +0 -1
  495. package/dist/point-cloud/point-cloud-tileset.js +0 -549
  496. package/dist/point-cloud/point-cloud-tileset.js.map +0 -1
  497. package/dist/point-cloud/types.d.ts +0 -81
  498. package/dist/point-cloud/types.d.ts.map +0 -1
  499. package/dist/point-cloud/types.js.map +0 -1
  500. package/dist/point-cloud-tile-source-loader-types.d.ts +0 -31
  501. package/dist/point-cloud-tile-source-loader-types.d.ts.map +0 -1
  502. package/dist/point-cloud-tile-source-loader-types.js +0 -34
  503. package/dist/point-cloud-tile-source-loader-types.js.map +0 -1
  504. package/dist/point-cloud-tile-source-loader.cjs +0 -81
  505. package/dist/point-cloud-tile-source-loader.cjs.map +0 -7
  506. package/dist/point-cloud-tile-source-loader.d.ts +0 -27
  507. package/dist/point-cloud-tile-source-loader.d.ts.map +0 -1
  508. package/dist/point-cloud-tile-source-loader.js +0 -17
  509. package/dist/point-cloud-tile-source-loader.js.map +0 -1
  510. package/dist/point-cloud-tile-source-types.d.ts +0 -15
  511. package/dist/point-cloud-tile-source-types.d.ts.map +0 -1
  512. package/dist/point-cloud-tile-source-types.js.map +0 -1
  513. package/dist/point-cloud-tile-source.cjs +0 -105
  514. package/dist/point-cloud-tile-source.cjs.map +0 -7
  515. package/dist/point-cloud-tile-source.d.ts +0 -36
  516. package/dist/point-cloud-tile-source.d.ts.map +0 -1
  517. package/dist/point-cloud-tile-source.js +0 -84
  518. package/dist/point-cloud-tile-source.js.map +0 -1
  519. package/dist/spatial/format-spatial-reference.d.ts +0 -68
  520. package/dist/spatial/format-spatial-reference.d.ts.map +0 -1
  521. package/dist/spatial/format-spatial-reference.js +0 -291
  522. package/dist/spatial/format-spatial-reference.js.map +0 -1
  523. package/dist/spatial/get-spatial-coordinate-frame.d.ts +0 -20
  524. package/dist/spatial/get-spatial-coordinate-frame.d.ts.map +0 -1
  525. package/dist/spatial/get-spatial-coordinate-frame.js +0 -139
  526. package/dist/spatial/get-spatial-coordinate-frame.js.map +0 -1
  527. package/dist/spatial/i3s-elevation.d.ts +0 -20
  528. package/dist/spatial/i3s-elevation.d.ts.map +0 -1
  529. package/dist/spatial/i3s-elevation.js +0 -90
  530. package/dist/spatial/i3s-elevation.js.map +0 -1
  531. package/dist/spatial/i3s-spatial-transformer.d.ts +0 -205
  532. package/dist/spatial/i3s-spatial-transformer.d.ts.map +0 -1
  533. package/dist/spatial/i3s-spatial-transformer.js +0 -731
  534. package/dist/spatial/i3s-spatial-transformer.js.map +0 -1
  535. package/dist/spatial/normalize-crs-identifier.d.ts +0 -15
  536. package/dist/spatial/normalize-crs-identifier.d.ts.map +0 -1
  537. package/dist/spatial/normalize-crs-identifier.js +0 -22
  538. package/dist/spatial/normalize-crs-identifier.js.map +0 -1
  539. package/dist/spatial/spatial-coordinate-transformer.d.ts +0 -54
  540. package/dist/spatial/spatial-coordinate-transformer.d.ts.map +0 -1
  541. package/dist/spatial/spatial-coordinate-transformer.js +0 -311
  542. package/dist/spatial/spatial-coordinate-transformer.js.map +0 -1
  543. package/dist/spatial/spatial-resource-registry.d.ts +0 -47
  544. package/dist/spatial/spatial-resource-registry.d.ts.map +0 -1
  545. package/dist/spatial/spatial-resource-registry.js +0 -76
  546. package/dist/spatial/spatial-resource-registry.js.map +0 -1
  547. package/dist/spatial/spatial-types.d.ts +0 -190
  548. package/dist/spatial/spatial-types.d.ts.map +0 -1
  549. package/dist/spatial/spatial-types.js +0 -192
  550. package/dist/spatial/spatial-types.js.map +0 -1
  551. package/dist/spatial/tiles-3d-spatial-transformer.d.ts +0 -32
  552. package/dist/spatial/tiles-3d-spatial-transformer.d.ts.map +0 -1
  553. package/dist/spatial/tiles-3d-spatial-transformer.js +0 -163
  554. package/dist/spatial/tiles-3d-spatial-transformer.js.map +0 -1
  555. package/dist/tileset-3d/common/indexed-archive-tileset-source.d.ts +0 -60
  556. package/dist/tileset-3d/common/indexed-archive-tileset-source.d.ts.map +0 -1
  557. package/dist/tileset-3d/common/indexed-archive-tileset-source.js +0 -130
  558. package/dist/tileset-3d/common/indexed-archive-tileset-source.js.map +0 -1
  559. package/dist/tileset-3d/common/tile-3d-contracts.d.ts +0 -63
  560. package/dist/tileset-3d/common/tile-3d-contracts.d.ts.map +0 -1
  561. package/dist/tileset-3d/common/tile-3d-contracts.js +0 -51
  562. package/dist/tileset-3d/common/tile-3d-contracts.js.map +0 -1
  563. package/dist/tileset-3d/common/tile-3d.d.ts +0 -410
  564. package/dist/tileset-3d/common/tile-3d.d.ts.map +0 -1
  565. package/dist/tileset-3d/common/tile-3d.js +0 -1056
  566. package/dist/tileset-3d/common/tile-3d.js.map +0 -1
  567. package/dist/tileset-3d/common/tileset-3d.d.ts +0 -369
  568. package/dist/tileset-3d/common/tileset-3d.d.ts.map +0 -1
  569. package/dist/tileset-3d/common/tileset-3d.js +0 -879
  570. package/dist/tileset-3d/common/tileset-3d.js.map +0 -1
  571. package/dist/tileset-3d/common/tileset-cache.d.ts +0 -29
  572. package/dist/tileset-3d/common/tileset-cache.d.ts.map +0 -1
  573. package/dist/tileset-3d/common/tileset-cache.js +0 -82
  574. package/dist/tileset-3d/common/tileset-cache.js.map +0 -1
  575. package/dist/tileset-3d/common/tileset-content-traversal.d.ts +0 -37
  576. package/dist/tileset-3d/common/tileset-content-traversal.d.ts.map +0 -1
  577. package/dist/tileset-3d/common/tileset-content-traversal.js +0 -80
  578. package/dist/tileset-3d/common/tileset-content-traversal.js.map +0 -1
  579. package/dist/tileset-3d/common/tileset-observability.d.ts +0 -60
  580. package/dist/tileset-3d/common/tileset-observability.d.ts.map +0 -1
  581. package/dist/tileset-3d/common/tileset-observability.js +0 -39
  582. package/dist/tileset-3d/common/tileset-observability.js.map +0 -1
  583. package/dist/tileset-3d/common/tileset-source.d.ts +0 -228
  584. package/dist/tileset-3d/common/tileset-source.d.ts.map +0 -1
  585. package/dist/tileset-3d/common/tileset-source.js +0 -17
  586. package/dist/tileset-3d/common/tileset-source.js.map +0 -1
  587. package/dist/tileset-3d/common/tileset-traverser.d.ts +0 -88
  588. package/dist/tileset-3d/common/tileset-traverser.d.ts.map +0 -1
  589. package/dist/tileset-3d/common/tileset-traverser.js +0 -341
  590. package/dist/tileset-3d/common/tileset-traverser.js.map +0 -1
  591. package/dist/tileset-3d/format-3d-tiles/implicit-tiling.d.ts +0 -182
  592. package/dist/tileset-3d/format-3d-tiles/implicit-tiling.d.ts.map +0 -1
  593. package/dist/tileset-3d/format-3d-tiles/implicit-tiling.js +0 -678
  594. package/dist/tileset-3d/format-3d-tiles/implicit-tiling.js.map +0 -1
  595. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.d.ts +0 -221
  596. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.d.ts.map +0 -1
  597. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.js +0 -770
  598. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.js.map +0 -1
  599. package/dist/tileset-3d/format-3d-tiles/tileset-3d-traverser.d.ts +0 -111
  600. package/dist/tileset-3d/format-3d-tiles/tileset-3d-traverser.d.ts.map +0 -1
  601. package/dist/tileset-3d/format-3d-tiles/tileset-3d-traverser.js +0 -339
  602. package/dist/tileset-3d/format-3d-tiles/tileset-3d-traverser.js.map +0 -1
  603. package/dist/tileset-3d/format-i3s/i3s-pending-tiles-register.d.ts +0 -27
  604. package/dist/tileset-3d/format-i3s/i3s-pending-tiles-register.d.ts.map +0 -1
  605. package/dist/tileset-3d/format-i3s/i3s-pending-tiles-register.js +0 -45
  606. package/dist/tileset-3d/format-i3s/i3s-pending-tiles-register.js.map +0 -1
  607. package/dist/tileset-3d/format-i3s/i3s-source.d.ts +0 -116
  608. package/dist/tileset-3d/format-i3s/i3s-source.d.ts.map +0 -1
  609. package/dist/tileset-3d/format-i3s/i3s-source.js +0 -450
  610. package/dist/tileset-3d/format-i3s/i3s-source.js.map +0 -1
  611. package/dist/tileset-3d/format-i3s/i3s-tile-manager.d.ts +0 -34
  612. package/dist/tileset-3d/format-i3s/i3s-tile-manager.d.ts.map +0 -1
  613. package/dist/tileset-3d/format-i3s/i3s-tile-manager.js +0 -81
  614. package/dist/tileset-3d/format-i3s/i3s-tile-manager.js.map +0 -1
  615. package/dist/tileset-3d/format-i3s/i3s-tileset-traverser.d.ts +0 -25
  616. package/dist/tileset-3d/format-i3s/i3s-tileset-traverser.d.ts.map +0 -1
  617. package/dist/tileset-3d/format-i3s/i3s-tileset-traverser.js +0 -84
  618. package/dist/tileset-3d/format-i3s/i3s-tileset-traverser.js.map +0 -1
  619. package/dist/tileset-3d/helpers/3d-tiles-options.d.ts +0 -5
  620. package/dist/tileset-3d/helpers/3d-tiles-options.d.ts.map +0 -1
  621. package/dist/tileset-3d/helpers/3d-tiles-options.js +0 -9
  622. package/dist/tileset-3d/helpers/3d-tiles-options.js.map +0 -1
  623. package/dist/tileset-3d/helpers/bounding-volume.d.ts +0 -23
  624. package/dist/tileset-3d/helpers/bounding-volume.d.ts.map +0 -1
  625. package/dist/tileset-3d/helpers/bounding-volume.js +0 -236
  626. package/dist/tileset-3d/helpers/bounding-volume.js.map +0 -1
  627. package/dist/tileset-3d/helpers/frame-state.d.ts +0 -93
  628. package/dist/tileset-3d/helpers/frame-state.d.ts.map +0 -1
  629. package/dist/tileset-3d/helpers/frame-state.js +0 -211
  630. package/dist/tileset-3d/helpers/frame-state.js.map +0 -1
  631. package/dist/tileset-3d/helpers/i3s-lod.d.ts +0 -20
  632. package/dist/tileset-3d/helpers/i3s-lod.d.ts.map +0 -1
  633. package/dist/tileset-3d/helpers/i3s-lod.js +0 -95
  634. package/dist/tileset-3d/helpers/i3s-lod.js.map +0 -1
  635. package/dist/tileset-3d/helpers/s2-bounding-volume.d.ts +0 -17
  636. package/dist/tileset-3d/helpers/s2-bounding-volume.d.ts.map +0 -1
  637. package/dist/tileset-3d/helpers/s2-bounding-volume.js +0 -17
  638. package/dist/tileset-3d/helpers/s2-bounding-volume.js.map +0 -1
  639. package/dist/tileset-3d/helpers/tiles-3d-lod.d.ts +0 -72
  640. package/dist/tileset-3d/helpers/tiles-3d-lod.d.ts.map +0 -1
  641. package/dist/tileset-3d/helpers/tiles-3d-lod.js +0 -257
  642. package/dist/tileset-3d/helpers/tiles-3d-lod.js.map +0 -1
  643. package/dist/tileset-3d/helpers/tiles-3d-request-priority.d.ts +0 -134
  644. package/dist/tileset-3d/helpers/tiles-3d-request-priority.d.ts.map +0 -1
  645. package/dist/tileset-3d/helpers/tiles-3d-request-priority.js +0 -179
  646. package/dist/tileset-3d/helpers/tiles-3d-request-priority.js.map +0 -1
  647. package/dist/tileset-3d/helpers/transform-utils.d.ts +0 -3
  648. package/dist/tileset-3d/helpers/transform-utils.d.ts.map +0 -1
  649. package/dist/tileset-3d/helpers/transform-utils.js +0 -86
  650. package/dist/tileset-3d/helpers/transform-utils.js.map +0 -1
  651. package/dist/tileset-3d/helpers/zoom.d.ts +0 -46
  652. package/dist/tileset-3d/helpers/zoom.d.ts.map +0 -1
  653. package/dist/tileset-3d/helpers/zoom.js +0 -86
  654. package/dist/tileset-3d/helpers/zoom.js.map +0 -1
  655. package/dist/types.d.ts +0 -48
  656. package/dist/types.d.ts.map +0 -1
  657. package/dist/types.js.map +0 -1
  658. package/dist/utils/doubly-linked-list-node.d.ts +0 -11
  659. package/dist/utils/doubly-linked-list-node.d.ts.map +0 -1
  660. package/dist/utils/doubly-linked-list-node.js +0 -20
  661. package/dist/utils/doubly-linked-list-node.js.map +0 -1
  662. package/dist/utils/doubly-linked-list.d.ts +0 -30
  663. package/dist/utils/doubly-linked-list.d.ts.map +0 -1
  664. package/dist/utils/doubly-linked-list.js +0 -93
  665. package/dist/utils/doubly-linked-list.js.map +0 -1
  666. package/dist/utils/managed-array.d.ts +0 -85
  667. package/dist/utils/managed-array.d.ts.map +0 -1
  668. package/dist/utils/managed-array.js +0 -152
  669. package/dist/utils/managed-array.js.map +0 -1
  670. package/src/constants.ts +0 -59
  671. package/src/point-cloud/point-cloud-tile.ts +0 -80
  672. package/src/point-cloud/point-cloud-tileset.ts +0 -767
  673. package/src/point-cloud/types.ts +0 -99
  674. package/src/point-cloud-tile-source-loader-types.ts +0 -53
  675. package/src/point-cloud-tile-source-loader.ts +0 -32
  676. package/src/point-cloud-tile-source-types.ts +0 -20
  677. package/src/point-cloud-tile-source.ts +0 -112
  678. package/src/spatial/format-spatial-reference.ts +0 -385
  679. package/src/spatial/get-spatial-coordinate-frame.ts +0 -169
  680. package/src/spatial/i3s-elevation.ts +0 -96
  681. package/src/spatial/i3s-spatial-transformer.ts +0 -1021
  682. package/src/spatial/normalize-crs-identifier.ts +0 -26
  683. package/src/spatial/spatial-coordinate-transformer.ts +0 -397
  684. package/src/spatial/spatial-resource-registry.ts +0 -90
  685. package/src/spatial/spatial-types.ts +0 -422
  686. package/src/spatial/tiles-3d-spatial-transformer.ts +0 -194
  687. package/src/tileset-3d/common/indexed-archive-tileset-source.ts +0 -205
  688. package/src/tileset-3d/common/tile-3d-contracts.ts +0 -115
  689. package/src/tileset-3d/common/tile-3d.ts +0 -1310
  690. package/src/tileset-3d/common/tileset-3d.ts +0 -1210
  691. package/src/tileset-3d/common/tileset-cache.ts +0 -111
  692. package/src/tileset-3d/common/tileset-content-traversal.ts +0 -114
  693. package/src/tileset-3d/common/tileset-observability.ts +0 -100
  694. package/src/tileset-3d/common/tileset-source.ts +0 -284
  695. package/src/tileset-3d/common/tileset-traverser.ts +0 -416
  696. package/src/tileset-3d/format-3d-tiles/implicit-tiling.ts +0 -1056
  697. package/src/tileset-3d/format-3d-tiles/tiles-3d-source.ts +0 -1025
  698. package/src/tileset-3d/format-3d-tiles/tileset-3d-traverser.ts +0 -391
  699. package/src/tileset-3d/format-i3s/i3s-pending-tiles-register.ts +0 -48
  700. package/src/tileset-3d/format-i3s/i3s-source.ts +0 -557
  701. package/src/tileset-3d/format-i3s/i3s-tile-manager.ts +0 -105
  702. package/src/tileset-3d/format-i3s/i3s-tileset-traverser.ts +0 -102
  703. package/src/tileset-3d/helpers/3d-tiles-options.ts +0 -11
  704. package/src/tileset-3d/helpers/bounding-volume.ts +0 -281
  705. package/src/tileset-3d/helpers/frame-state.ts +0 -322
  706. package/src/tileset-3d/helpers/i3s-lod.ts +0 -109
  707. package/src/tileset-3d/helpers/s2-bounding-volume.ts +0 -32
  708. package/src/tileset-3d/helpers/tiles-3d-lod.ts +0 -370
  709. package/src/tileset-3d/helpers/tiles-3d-request-priority.ts +0 -301
  710. package/src/tileset-3d/helpers/transform-utils.ts +0 -109
  711. package/src/tileset-3d/helpers/zoom.ts +0 -120
  712. package/src/types.ts +0 -54
  713. package/src/utils/doubly-linked-list-node.ts +0 -22
  714. package/src/utils/doubly-linked-list.ts +0 -105
  715. package/src/utils/managed-array.ts +0 -174
  716. /package/dist/{point-cloud → mvt/lib}/types.js +0 -0
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/tileset-3d/common/tileset-3d.ts", "../../../node_modules/@probe.gl/stats/src/utils/hi-res-timestamp.ts", "../../../node_modules/@probe.gl/stats/src/lib/stat.ts", "../../../node_modules/@probe.gl/stats/src/lib/stats.ts", "../src/utils/doubly-linked-list-node.ts", "../src/utils/doubly-linked-list.ts", "../src/tileset-3d/common/tileset-cache.ts", "../src/tileset-3d/helpers/transform-utils.ts", "../src/tileset-3d/helpers/frame-state.ts", "../src/tileset-3d/helpers/tiles-3d-lod.ts", "../src/tileset-3d/helpers/tiles-3d-request-priority.ts", "../src/constants.ts", "../src/spatial/spatial-types.ts", "../src/spatial/get-spatial-coordinate-frame.ts", "../src/spatial/normalize-crs-identifier.ts", "../src/tileset-3d/common/tileset-source.ts", "../src/tileset-3d/common/tileset-observability.ts", "../src/tileset-3d/common/tileset-content-traversal.ts", "../src/tileset-3d/common/indexed-archive-tileset-source.ts", "../src/tileset-3d/common/tile-3d.ts", "../src/tileset-3d/common/tile-3d-contracts.ts", "../src/tileset-3d/helpers/bounding-volume.ts", "../src/tileset-3d/helpers/i3s-lod.ts", "../src/utils/managed-array.ts", "../src/tileset-3d/common/tileset-traverser.ts", "../src/tileset-3d/format-3d-tiles/tiles-3d-source.ts", "../src/tileset-3d/format-3d-tiles/tileset-3d-traverser.ts", "../src/tileset-3d/helpers/zoom.ts", "../src/spatial/i3s-elevation.ts", "../src/spatial/format-spatial-reference.ts", "../src/spatial/spatial-coordinate-transformer.ts", "../src/spatial/spatial-resource-registry.ts", "../src/spatial/tiles-3d-spatial-transformer.ts", "../src/tileset-3d/format-3d-tiles/implicit-tiling.ts", "../src/tileset-3d/helpers/s2-bounding-volume.ts", "../src/tileset-3d/format-i3s/i3s-source.ts", "../src/tileset-3d/format-i3s/i3s-pending-tiles-register.ts", "../src/tileset-3d/format-i3s/i3s-tile-manager.ts", "../src/tileset-3d/format-i3s/i3s-tileset-traverser.ts", "../src/spatial/i3s-spatial-transformer.ts", "../src/tileset-2d/tile-2d-header.ts", "../src/tileset-2d/tileset-2d.ts", "../src/image-set.ts", "../src/raster-set.ts", "../src/point-cloud/point-cloud-tileset.ts", "../src/point-cloud/point-cloud-tile.ts", "../src/point-cloud-tile-source-loader-types.ts"],
4
- "sourcesContent": ["// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {Tileset3DProps} from './tileset-3d/common/tileset-3d';\nexport type {FoveatedInterpolationCallback} from './tileset-3d/helpers/tiles-3d-request-priority';\nexport {Tileset3D} from './tileset-3d/common/tileset-3d';\nexport {getTileset3DTraversalSnapshot} from './tileset-3d/common/tileset-observability';\nexport type {Tileset3DTraversalSnapshot} from './tileset-3d/common/tileset-observability';\nexport {traverseTilesetContents} from './tileset-3d/common/tileset-content-traversal';\nexport type {\n TilesetContentTraversalItem,\n TraverseTilesetContentsOptions\n} from './tileset-3d/common/tileset-content-traversal';\nexport type {\n TileContentLoadResult,\n TileChildrenLoadResult,\n TilesetContentFormats,\n TilesetJSON,\n TilesetSourceInput,\n TilesetSourceMetadata,\n TilesetSourceRequest,\n TilesetSourceResolver,\n Tileset3DSource,\n TilesetSourceViewState\n} from './tileset-3d/common/tileset-source';\nexport {isTileset3DSource} from './tileset-3d/common/tileset-source';\nexport type {IndexedArchiveTilesetSourceOptions} from './tileset-3d/common/indexed-archive-tileset-source';\nexport {IndexedArchiveTilesetSource} from './tileset-3d/common/indexed-archive-tileset-source';\nexport {Tile3D} from './tileset-3d/common/tile-3d';\nexport type {\n Tile3DContent,\n Tile3DFeatureIdSet,\n Tile3DMetadataContext,\n Tile3DBoundingVolume\n} from './tileset-3d/common/tile-3d-contracts';\nexport type {TileChildrenState} from './tileset-3d/common/tile-3d';\nexport {Tiles3DSource} from './tileset-3d/format-3d-tiles/tiles-3d-source';\nexport type {ImplicitTilingStats} from './tileset-3d/format-3d-tiles/tiles-3d-source';\nexport type {\n ImplicitAvailability,\n ImplicitSubtreeReference,\n ImplicitTileCoordinates,\n ImplicitTileHeader,\n ImplicitTilingDescriptor,\n MaterializedImplicitSubtree,\n ParsedImplicitSubtree\n} from './tileset-3d/format-3d-tiles/implicit-tiling';\nexport {\n createImplicitSubtreeReference,\n materializeImplicitSubtree,\n replaceImplicitUrlTemplate\n} from './tileset-3d/format-3d-tiles/implicit-tiling';\nexport {I3SSource} from './tileset-3d/format-i3s/i3s-source';\n\nexport {TilesetTraverser} from './tileset-3d/common/tileset-traverser';\nexport {TilesetCache} from './tileset-3d/common/tileset-cache';\n\nexport type {\n Bounds,\n GeoBoundingBox,\n NonGeoBoundingBox,\n TileBoundingBox,\n TileIndex,\n TileLoadProps,\n ZRange\n} from './tileset-2d';\nexport type {\n Tileset2DAdapter,\n Tileset2DTileContext,\n Tileset2DTraversalContext\n} from './tileset-2d';\nexport type {\n RefinementStrategy,\n RefinementStrategyFunction,\n Tileset2DBaseProps,\n Tileset2DProps,\n Tile2DListener,\n Tile2DLoadDataProps\n} from './tileset-2d';\nexport {\n SharedTile2DHeader,\n Tileset2D,\n STRATEGY_DEFAULT,\n STRATEGY_NEVER,\n STRATEGY_REPLACE\n} from './tileset-2d';\nexport type {\n ImageSetBaseProps,\n ImageSetListener,\n ImageSetProps,\n ImageSetRequest\n} from './image-set';\nexport {ImageSet} from './image-set';\nexport type {\n RasterSetBaseProps,\n RasterSetListener,\n RasterSetProps,\n RasterSetRequest,\n RasterSetShouldRefetchArgs\n} from './raster-set';\nexport {RasterSet} from './raster-set';\nexport type {\n PointCloudAttribute,\n PointCloudBoundingVolume,\n PointCloudTileContent,\n PointCloudTileHeader,\n PointCloudTilesetSource,\n PointCloudTilesetViewState,\n PointCloudCoordinateSystem\n} from './point-cloud/types';\nexport type {PointCloudTilesetOptions} from './point-cloud/point-cloud-tileset';\nexport {PointCloudTileset} from './point-cloud/point-cloud-tileset';\nexport {PointCloudTile} from './point-cloud/point-cloud-tile';\nexport {createBoundingVolume} from './tileset-3d/helpers/bounding-volume';\nexport {calculateTransformProps} from './tileset-3d/helpers/transform-utils';\nexport {convertS2BoundingVolumeToOBB} from './tileset-3d/helpers/s2-bounding-volume';\nexport type {S2VolumeInfo} from './tileset-3d/helpers/s2-bounding-volume';\n\nexport type {\n CreateTilesetSpatialReferenceOptions,\n TilesetCoordinateFrame,\n TilesetElevationBounds,\n TilesetElevationMode,\n TilesetElevationProvider,\n TilesetElevationRange,\n TilesetElevationSample,\n TilesetHeightReference,\n TilesetOutputCoordinates,\n TilesetSpatialOptions,\n TilesetSpatialReference,\n TilesetSpatialReferenceProvenance,\n TilesetTargetHeightReference\n} from './spatial/spatial-types';\nexport {\n applyTilesetSpatialOptions,\n createTilesetSpatialReference,\n markTilesetSpatialReferenceTransformed\n} from './spatial/spatial-types';\nexport {\n get3DTilesSpatialReference,\n getI3SSpatialReference\n} from './spatial/format-spatial-reference';\nexport {SpatialCoordinateTransformer} from './spatial/spatial-coordinate-transformer';\nexport {getSpatialCoordinateFrame} from './spatial/spatial-coordinate-transformer';\nexport {Tiles3DSpatialTransformer} from './spatial/tiles-3d-spatial-transformer';\nexport type {Tiles3DSpatialBoundingVolume} from './spatial/tiles-3d-spatial-transformer';\nexport type {\n I3SSpatialBounds,\n I3SSpatialObb,\n I3STransformedPositions,\n I3STransformedGeometry\n} from './spatial/i3s-spatial-transformer';\nexport {I3SSpatialTransformer} from './spatial/i3s-spatial-transformer';\nexport {\n getGeoidModel,\n registerGeoidModel,\n registerGeoidModelFromPgm,\n registerSpatialCrs,\n registerSpatialDatumGrid\n} from './spatial/spatial-resource-registry';\n\nexport {getFrameState} from './tileset-3d/helpers/frame-state';\nexport type {FrameState, GetFrameStateOptions} from './tileset-3d/helpers/frame-state';\nexport {getLodStatus} from './tileset-3d/helpers/i3s-lod';\n\nexport {\n TILE_CONTENT_STATE,\n TILE_REFINEMENT,\n TILE_TYPE,\n TILESET_TYPE,\n LOD_METRIC_TYPE\n} from './constants';\n\nexport {PointCloudTileSourceLoader} from './point-cloud-tile-source-loader-types';\nexport type {\n PointCloudTileSourceInput,\n PointCloudTileSourceOptions\n} from './point-cloud-tile-source-types';\n", "// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Stats} from '@probe.gl/stats';\nimport {RequestScheduler, Loader, LoaderOptions} from '@loaders.gl/loader-utils';\nimport {TilesetCache} from './tileset-cache';\nimport {calculateTransformProps} from '../helpers/transform-utils';\nimport {getFrameState, limitSelectedTiles, updateCameraMotionState} from '../helpers/frame-state';\nimport type {CameraMotionState, FrameState} from '../helpers/frame-state';\nimport {\n calculateDynamicScreenSpaceErrorDensity,\n updateRootTransformForDynamicScreenSpaceError\n} from '../helpers/tiles-3d-lod';\nimport {interpolateLinearly} from '../helpers/tiles-3d-request-priority';\nimport type {FoveatedInterpolationCallback} from '../helpers/tiles-3d-request-priority';\n\nimport type {GeospatialViewport, Viewport} from '../../types';\nimport {Tile3D} from './tile-3d';\nimport {TILESET_TYPE} from '../../constants';\nimport type {TilesetSpatialOptions, TilesetSpatialReference} from '../../spatial/spatial-types';\nimport {\n applyTilesetSpatialOptions,\n createTilesetSpatialReference\n} from '../../spatial/spatial-types';\n\nimport {TilesetTraverser} from './tileset-traverser';\nimport {\n isTileset3DSource,\n TileContentLoadResult,\n TilesetContentFormats,\n TilesetJSON,\n Tileset3DSource,\n TilesetSourceMetadata\n} from './tileset-source';\n\nexport type {TilesetJSON} from './tileset-source';\n\nexport type Tileset3DProps = {\n /** Format options forwarded to I3S content requests, including source-coordinate decoding. */\n i3s?: Record<string, unknown>;\n throttleRequests?: boolean;\n maxRequests?: number;\n loadOptions?: LoaderOptions;\n loadTiles?: boolean;\n basePath?: string;\n /**\n * Soft target, in bytes, for cached tile content that is not required by the current frame.\n * The listed default applies to 3D Tiles; I3S retains its existing 32 MiB default.\n * @default 536870912\n */\n cacheBytes?: number;\n /**\n * Additional bytes that the current-frame working set may use before memory-adjusted SSE rises.\n * The listed default applies to 3D Tiles; I3S retains its existing 1 MiB default.\n * @default 536870912\n */\n maximumCacheOverflowBytes?: number;\n maximumTilesSelected?: number;\n debounceTime?: number;\n\n description?: string;\n attributions?: string[];\n\n ellipsoid?: object;\n modelMatrix?: Matrix4;\n /** Automatic CRS output options and expert source-metadata recovery overrides. */\n spatial?: TilesetSpatialOptions;\n\n maximumScreenSpaceError?: number;\n /**\n * Enables replacement traversal that may skip hierarchy levels while retaining ready ancestors\n * as coverage. This trades temporary overdraw for faster refinement on deep trees.\n * Defaults to `true` for 3D Tiles and `false` for I3S. Set to `false` to request every level.\n */\n skipLevelOfDetail?: boolean;\n /**\n * SSE above which tiles remain part of the non-skipping base traversal.\n * @default 1024\n */\n baseScreenSpaceError?: number;\n /**\n * Required SSE reduction from the nearest requested or loaded ancestor before loading a tile.\n * @default 16\n */\n skipScreenSpaceErrorFactor?: number;\n /**\n * Minimum hierarchy levels between requested tiles during skip-LOD traversal.\n * @default 1\n */\n skipLevels?: number;\n /**\n * Requests only final tiles that meet the active SSE target when skip-LOD is enabled.\n * @default false\n */\n immediatelyLoadDesiredLevelOfDetail?: boolean;\n /** Enables perspective dynamic SSE to reduce distant, horizon-facing refinement. */\n dynamicScreenSpaceError?: boolean;\n /** Base dynamic SSE fog density in inverse meters. */\n dynamicScreenSpaceErrorDensity?: number;\n /** Maximum dynamic SSE reduction in logical/CSS pixels. */\n dynamicScreenSpaceErrorFactor?: number;\n /** Fraction of tileset height at which dynamic SSE begins to fade, clamped to `[0, 1]`. */\n dynamicScreenSpaceErrorHeightFalloff?: number;\n /**\n * Enables adaptive LOD reduction when estimated tile memory exceeds the overflow ceiling.\n * Defaults to `true` for 3D Tiles and retains the existing `false` default for I3S.\n */\n memoryAdjustedScreenSpaceError?: boolean;\n viewportTraversersMap?: any;\n updateTransforms?: boolean;\n viewDistanceScale?: number;\n /** Reduced viewport-height fraction used to prioritize coarse initial coverage; `0` disables it. */\n progressiveResolutionHeightFraction?: number;\n /** Whether requests nearer the center of a perspective viewport receive higher priority. */\n foveatedScreenSpaceError?: boolean;\n /** Fraction of the perspective field of view that receives no foveated SSE relaxation. */\n foveatedConeSize?: number;\n /** Minimum logical-pixel SSE relaxation immediately outside the foveated cone. */\n foveatedMinimumScreenSpaceErrorRelaxation?: number;\n /** Function that increases SSE relaxation from the foveated cone toward the viewport edge. */\n foveatedInterpolationCallback?: FoveatedInterpolationCallback;\n /** Seconds peripheral requests may wait after the camera moves. */\n foveatedTimeDelay?: number;\n\n onTileLoad?: (tile: Tile3D) => any;\n onTileUnload?: (tile: Tile3D) => any;\n onTileError?: (tile: Tile3D, message: string, url: string) => any;\n /** Called when a format-specific source operation fails. */\n onSourceError?: (error: Error, source: Tileset3DSource, tile?: Tile3D | null) => any;\n /** Called when tileset initialization fails before traversal can begin. */\n onTilesetError?: (error: Error, tileset: Tileset3D) => any;\n contentLoader?: (tile: Tile3D) => Promise<void>;\n onTraversalComplete?: (selectedTiles: Tile3D[]) => Tile3D[];\n onUpdate?: () => void;\n};\n\ntype Props = {\n description: string;\n ellipsoid: object;\n modelMatrix: Matrix4;\n throttleRequests: boolean;\n maxRequests: number;\n /** Soft target, in bytes, for evictable cached tile content. */\n cacheBytes: number;\n /** Current-frame headroom, in bytes, before memory-adjusted SSE rises. */\n maximumCacheOverflowBytes: number;\n maximumTilesSelected: number;\n debounceTime: number;\n onTileLoad: (tile: Tile3D) => void;\n onTileUnload: (tile: Tile3D) => void;\n onTileError: (tile: Tile3D, message: string, url: string) => void;\n onSourceError: (error: Error, source: Tileset3DSource, tile?: Tile3D | null) => void;\n onTilesetError: (error: Error, tileset: Tileset3D) => void;\n onTraversalComplete: (selectedTiles: Tile3D[]) => Tile3D[];\n onUpdate: () => void;\n maximumScreenSpaceError: number;\n /** Whether replacement traversal may skip levels while retaining ancestor coverage. */\n skipLevelOfDetail: boolean;\n /** SSE above which tiles remain part of the non-skipping base traversal. */\n baseScreenSpaceError: number;\n /** Required SSE reduction between requested skip-LOD tiles. */\n skipScreenSpaceErrorFactor: number;\n /** Minimum hierarchy levels between requested skip-LOD tiles. */\n skipLevels: number;\n /** Whether skip-LOD requests only the final desired tiles. */\n immediatelyLoadDesiredLevelOfDetail: boolean;\n /** Whether perspective dynamic SSE is enabled. */\n dynamicScreenSpaceError: boolean;\n /** Base dynamic SSE fog density in inverse meters. */\n dynamicScreenSpaceErrorDensity: number;\n /** Maximum dynamic SSE reduction in logical/CSS pixels. */\n dynamicScreenSpaceErrorFactor: number;\n /** Fraction of tileset height at which dynamic SSE begins to fade. */\n dynamicScreenSpaceErrorHeightFalloff: number;\n /** Whether cache pressure may adapt the active SSE threshold. */\n memoryAdjustedScreenSpaceError: boolean;\n viewportTraversersMap: Record<string, any> | null;\n attributions: string[];\n loadTiles: boolean;\n loadOptions: LoaderOptions;\n updateTransforms: boolean;\n viewDistanceScale: number;\n /** Reduced viewport-height fraction used to prioritize coarse initial coverage. */\n progressiveResolutionHeightFraction: number;\n /** Whether perspective requests are prioritized around the viewport center. */\n foveatedScreenSpaceError: boolean;\n /** Fraction of the perspective field of view with no foveated SSE relaxation. */\n foveatedConeSize: number;\n /** Minimum logical-pixel SSE relaxation outside the foveated cone. */\n foveatedMinimumScreenSpaceErrorRelaxation: number;\n /** Function used to interpolate foveated SSE relaxation. */\n foveatedInterpolationCallback: FoveatedInterpolationCallback;\n /** Seconds eligible peripheral requests wait after camera movement. */\n foveatedTimeDelay: number;\n basePath: string;\n contentLoader?: (tile: Tile3D) => Promise<void>;\n i3s: Record<string, any>;\n /** Automatic CRS output options and expert source-metadata recovery overrides. */\n spatial: TilesetSpatialOptions;\n};\n\nconst BYTES_PER_MEBIBYTE = 1024 * 1024;\nconst DEFAULT_CACHE_BYTES = 512 * BYTES_PER_MEBIBYTE;\nconst DEFAULT_MAXIMUM_CACHE_OVERFLOW_BYTES = 512 * BYTES_PER_MEBIBYTE;\nconst DEFAULT_I3S_CACHE_BYTES = 32 * BYTES_PER_MEBIBYTE;\nconst DEFAULT_I3S_MAXIMUM_CACHE_OVERFLOW_BYTES = BYTES_PER_MEBIBYTE;\n\n/**\n * Validates a byte-based tile-cache budget.\n *\n * Fractions are accepted because JavaScript memory estimates are numbers, but negative, infinite,\n * and `NaN` values cannot define a stable cache threshold.\n *\n * @param value - Proposed cache budget in bytes.\n * @param optionName - Public option name used in an actionable error message.\n * @returns The validated byte budget.\n */\nfunction validateCacheByteLength(value: number, optionName: string): number {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${optionName} must be a finite number greater than or equal to 0`);\n }\n return value;\n}\n\n/**\n * Resolves the base cache target from the byte-native option or its fallback.\n *\n * @param options - Options that may contain a byte-native cache value.\n * @param fallbackCacheBytes - Existing or default cache target in bytes.\n * @returns The resolved and validated cache target in bytes.\n */\nfunction resolveCacheBytes(options: Tileset3DProps, fallbackCacheBytes: number): number {\n const cacheBytes = options.cacheBytes ?? fallbackCacheBytes;\n return validateCacheByteLength(cacheBytes, 'cacheBytes');\n}\n\n/**\n * Resolves cache overflow headroom from the byte-native option or its fallback.\n *\n * @param options - Options that may contain a byte-native overflow value.\n * @param fallbackOverflowBytes - Existing or default overflow headroom in bytes.\n * @returns The resolved and validated overflow headroom in bytes.\n */\nfunction resolveMaximumCacheOverflowBytes(\n options: Tileset3DProps,\n fallbackOverflowBytes: number\n): number {\n const maximumCacheOverflowBytes = options.maximumCacheOverflowBytes ?? fallbackOverflowBytes;\n return validateCacheByteLength(maximumCacheOverflowBytes, 'maximumCacheOverflowBytes');\n}\n\nconst DEFAULT_PROPS: Props = {\n description: '',\n ellipsoid: Ellipsoid.WGS84,\n modelMatrix: new Matrix4(),\n throttleRequests: true,\n maxRequests: 64,\n cacheBytes: DEFAULT_CACHE_BYTES,\n maximumCacheOverflowBytes: DEFAULT_MAXIMUM_CACHE_OVERFLOW_BYTES,\n maximumTilesSelected: 0,\n debounceTime: 0,\n onTileLoad: () => {},\n onTileUnload: () => {},\n onTileError: () => {},\n onSourceError: () => {},\n onTilesetError: () => {},\n onTraversalComplete: (selectedTiles: Tile3D[]) => selectedTiles,\n onUpdate: () => {},\n contentLoader: undefined,\n viewDistanceScale: 1.0,\n progressiveResolutionHeightFraction: 0.3,\n foveatedScreenSpaceError: true,\n foveatedConeSize: 0.1,\n foveatedMinimumScreenSpaceErrorRelaxation: 0,\n foveatedInterpolationCallback: interpolateLinearly,\n foveatedTimeDelay: 0.2,\n maximumScreenSpaceError: 8,\n skipLevelOfDetail: false,\n baseScreenSpaceError: 1024,\n skipScreenSpaceErrorFactor: 16,\n skipLevels: 1,\n immediatelyLoadDesiredLevelOfDetail: false,\n dynamicScreenSpaceError: true,\n dynamicScreenSpaceErrorDensity: 2.0e-4,\n dynamicScreenSpaceErrorFactor: 24,\n dynamicScreenSpaceErrorHeightFalloff: 0.25,\n memoryAdjustedScreenSpaceError: true,\n loadTiles: true,\n updateTransforms: true,\n viewportTraversersMap: null,\n loadOptions: {fetch: {}},\n attributions: [],\n basePath: '',\n i3s: {},\n spatial: {}\n};\n\nconst TILES_TOTAL = 'Tiles In Tileset(s)';\nconst TILES_IN_MEMORY = 'Tiles In Memory';\nconst TILES_IN_VIEW = 'Tiles In View';\nconst TILES_RENDERABLE = 'Tiles To Render';\nconst TILES_LOADED = 'Tiles Loaded';\nconst TILES_LOADING = 'Tiles Loading';\nconst TILES_UNLOADED = 'Tiles Unloaded';\nconst TILES_LOAD_FAILED = 'Failed Tile Loads';\nconst POINTS_COUNT = 'Points/Vertices';\nconst TILES_GPU_MEMORY = 'Tile Memory Use';\nconst MAXIMUM_SSE = 'Maximum Screen Space Error';\n\n/**\n * Shared runtime for tile traversal, selection, cache management, and request scheduling.\n *\n * Format-specific loading behavior is delegated to a {@link Tileset3DSource} implementation.\n */\nexport class Tileset3D {\n options: Props;\n loadOptions: LoaderOptions;\n /** Source implementation responsible for format-specific initialization and loading. */\n source: Tileset3DSource;\n\n type: TILESET_TYPE;\n tileset: TilesetJSON | null;\n loader: Loader;\n url: string;\n basePath: string;\n modelMatrix: Matrix4;\n ellipsoid: any;\n lodMetricType: string;\n lodMetricValue: number;\n refine: string;\n root: Tile3D | null = null;\n roots: Record<string, Tile3D> = {};\n asset: Record<string, any> = {};\n /** Inline metadata schema declared by the source tileset, when present. */\n schema: Record<string, any> | null = null;\n /** External metadata schema URI declared by the source tileset, when present. */\n schemaUri: string | null = null;\n /** Metadata groups declared by the source tileset, in source order. */\n groups: Array<Record<string, any>> = [];\n /** Tileset-wide metadata entity, preserved without property-table decoding. */\n metadata: Record<string, any> | null = null;\n /** Tileset statistics metadata, preserved for application-level inspection. */\n statistics: unknown = null;\n /** Normalized source and target coordinate reference system metadata. */\n spatialReference: TilesetSpatialReference = createTilesetSpatialReference({});\n\n description = '';\n properties: any;\n extras: any = null;\n attributions: any = {};\n credits: any = {};\n\n stats: Stats;\n contentFormats: TilesetContentFormats;\n\n cartographicCenter: Vector3 | null = null;\n cartesianCenter: Vector3 | null = null;\n zoom = 1;\n boundingVolume: any = null;\n\n /** Effective dynamic SSE density calculated for the most recently traversed viewport. */\n dynamicScreenSpaceErrorComputedDensity = 0;\n\n /** Estimated bytes currently retained by loaded tile content. */\n gpuMemoryUsageInBytes = 0;\n /** Active SSE threshold after optional cache-pressure adjustment, in logical/CSS pixels. */\n memoryAdjustedScreenSpaceError = 0.0;\n\n private _cacheBytes = DEFAULT_CACHE_BYTES;\n private _maximumCacheOverflowBytes = DEFAULT_MAXIMUM_CACHE_OVERFLOW_BYTES;\n\n _frameNumber = 0;\n private _tiles: Record<string, Tile3D> = {};\n private _pendingCount = 0;\n\n selectedTiles: Tile3D[] = [];\n\n traverseCounter = 0;\n geometricError = 0;\n private lastUpdatedVieports: Viewport[] | Viewport | null = null;\n private _requestedTiles: Tile3D[] = [];\n private _emptyTiles: Tile3D[] = [];\n private frameStateData: any = {};\n /** Last camera pose retained independently for each viewport. */\n private _cameraMotionStates: Record<string, CameraMotionState> = {};\n /** Pending traversal that releases requests after camera motion settles. */\n private _deferredTraversalTimeout: ReturnType<typeof setTimeout> | null = null;\n\n _traverser: TilesetTraverser;\n _cache = new TilesetCache();\n _requestScheduler: RequestScheduler;\n\n /** Drawn fallback instances retained independently for each viewport tree. */\n private _heldTiles: Set<Tile3D> = new Set();\n private updatePromise: Promise<number> | null = null;\n tilesetInitializationPromise: Promise<void>;\n\n /**\n * Creates a tileset runtime from an explicit source implementation.\n * @param source Source-backed tileset implementation.\n * @param options Traversal and runtime options.\n */\n constructor(source: Tileset3DSource, options?: Tileset3DProps) {\n if (!isTileset3DSource(source)) {\n throw new Error('Tileset3D requires a Tileset3DSource instance');\n }\n\n const suppliedOptions = options || {};\n const usesTiles3DCacheDefaults = source.type === TILESET_TYPE.TILES3D;\n const defaultCacheBytes = usesTiles3DCacheDefaults\n ? DEFAULT_PROPS.cacheBytes\n : DEFAULT_I3S_CACHE_BYTES;\n const defaultMaximumCacheOverflowBytes = usesTiles3DCacheDefaults\n ? DEFAULT_PROPS.maximumCacheOverflowBytes\n : DEFAULT_I3S_MAXIMUM_CACHE_OVERFLOW_BYTES;\n const cacheBytes = resolveCacheBytes(suppliedOptions, defaultCacheBytes);\n const maximumCacheOverflowBytes = resolveMaximumCacheOverflowBytes(\n suppliedOptions,\n defaultMaximumCacheOverflowBytes\n );\n this.options = {\n ...DEFAULT_PROPS,\n ...suppliedOptions,\n cacheBytes,\n maximumCacheOverflowBytes,\n skipLevelOfDetail: suppliedOptions.skipLevelOfDetail ?? source.type === TILESET_TYPE.TILES3D,\n memoryAdjustedScreenSpaceError:\n suppliedOptions.memoryAdjustedScreenSpaceError ?? usesTiles3DCacheDefaults\n };\n this.loadOptions = this.options.loadOptions || {};\n this.source = source;\n\n this.tileset = null;\n this.loader = this.source.loader;\n this.type = this.source.type;\n this.url = this.source.url;\n this.basePath = this.source.basePath;\n this.modelMatrix = this.options.modelMatrix;\n this.ellipsoid = this.options.ellipsoid;\n this.lodMetricType = '';\n this.lodMetricValue = 0;\n this.refine = '';\n this.contentFormats = this.source.contentFormats;\n\n this._traverser = this._initializeTraverser();\n this._requestScheduler = new RequestScheduler({\n throttleRequests: this.options.throttleRequests,\n maxRequests: this.options.maxRequests\n });\n\n this.memoryAdjustedScreenSpaceError = this.options.maximumScreenSpaceError;\n this._cacheBytes = cacheBytes;\n this._maximumCacheOverflowBytes = maximumCacheOverflowBytes;\n const metadata = this._getSourceMetadata();\n if (metadata) {\n this.spatialReference = applyTilesetSpatialOptions(\n metadata.spatialReference,\n this.options.spatial\n );\n }\n\n this.stats = new Stats({id: this.url});\n this._initializeStats();\n\n this.tilesetInitializationPromise = this._initializeTileSet();\n }\n\n destroy(): void {\n this._clearDeferredTraversal();\n this.source.destroy?.();\n this._destroy();\n }\n\n isLoaded(): boolean {\n return this._pendingCount === 0 && this._frameNumber !== 0 && this._requestedTiles.length === 0;\n }\n\n get tiles(): object[] {\n return Object.values(this._tiles);\n }\n\n get frameNumber(): number {\n return this._frameNumber;\n }\n\n /**\n * Returns the tiles requested during the most recent completed traversal.\n *\n * A defensive copy makes request ordering deterministic for diagnostics and prevents callers\n * from mutating the scheduler's working set.\n */\n get requestedTiles(): readonly Tile3D[] {\n return this._requestedTiles.slice();\n }\n\n /**\n * Returns empty tiles considered during the most recent completed traversal.\n *\n * Empty tiles can still be useful hierarchy placeholders, but their IDs are included in\n * observability snapshots so applications can distinguish traversal work from render content.\n */\n get emptyTiles(): readonly Tile3D[] {\n return this._emptyTiles.slice();\n }\n\n /**\n * Gets or sets the soft target, in bytes, for cached tile content not needed this frame.\n *\n * Current-frame tiles remain protected even when their estimated memory exceeds this target.\n * Reducing the value makes unused least-recently-used tiles eligible for eviction on the next\n * traversal.\n * @default 536870912 for 3D Tiles; 33554432 for I3S\n */\n get cacheBytes(): number {\n return this._cacheBytes;\n }\n\n set cacheBytes(value: number) {\n this._cacheBytes = validateCacheByteLength(value, 'cacheBytes');\n this.options.cacheBytes = this._cacheBytes;\n }\n\n /**\n * Gets or sets the additional current-frame headroom, in bytes, before memory-adjusted SSE rises.\n *\n * The pressure ceiling is `cacheBytes + maximumCacheOverflowBytes`. This value does not change\n * the base target used to evict tiles that were not touched in the current frame.\n * @default 536870912 for 3D Tiles; 1048576 for I3S\n */\n get maximumCacheOverflowBytes(): number {\n return this._maximumCacheOverflowBytes;\n }\n\n set maximumCacheOverflowBytes(value: number) {\n this._maximumCacheOverflowBytes = validateCacheByteLength(value, 'maximumCacheOverflowBytes');\n this.options.maximumCacheOverflowBytes = this._maximumCacheOverflowBytes;\n }\n\n get queryParams(): string {\n const rootUrl = this.source.getTileUrl(this.url);\n const queryIndex = rootUrl.indexOf('?');\n return queryIndex >= 0 ? rootUrl.slice(queryIndex + 1) : '';\n }\n\n /**\n * Updates traversal and runtime options while retaining unspecified byte budgets.\n *\n * @param props - Partial runtime options to apply.\n */\n setProps(props: Tileset3DProps): void {\n const cacheBytes = resolveCacheBytes(props, this.cacheBytes);\n const maximumCacheOverflowBytes = resolveMaximumCacheOverflowBytes(\n props,\n this.maximumCacheOverflowBytes\n );\n this.options = {\n ...this.options,\n ...props,\n cacheBytes,\n maximumCacheOverflowBytes\n };\n this._cacheBytes = cacheBytes;\n this._maximumCacheOverflowBytes = maximumCacheOverflowBytes;\n }\n\n getTileUrl(tilePath: string): string {\n return this.source.getTileUrl(tilePath);\n }\n\n hasExtension(extensionName: string): boolean {\n return Boolean(this.source.hasExtension?.(extensionName));\n }\n\n update(viewports: Viewport[] | Viewport | null = null): void {\n this.tilesetInitializationPromise.then(() => {\n if (!viewports && this.lastUpdatedVieports) {\n viewports = this.lastUpdatedVieports;\n } else {\n this.lastUpdatedVieports = viewports;\n }\n if (viewports) {\n this.doUpdate(viewports);\n }\n });\n }\n\n async selectTiles(viewports: Viewport[] | Viewport | null = null): Promise<number> {\n await this.tilesetInitializationPromise;\n if (viewports) {\n this.lastUpdatedVieports = viewports;\n }\n if (!this.updatePromise) {\n this.updatePromise = new Promise<number>(resolve => {\n setTimeout(() => {\n if (this.lastUpdatedVieports) {\n this.doUpdate(this.lastUpdatedVieports);\n }\n resolve(this._frameNumber);\n this.updatePromise = null;\n }, this.options.debounceTime);\n });\n }\n return this.updatePromise;\n }\n\n /**\n * Moves the active LOD threshold toward the configured SSE or away from cache pressure.\n *\n * Usage below {@link Tileset3D.cacheBytes} restores quality in two-percent steps. Usage above\n * `cacheBytes + maximumCacheOverflowBytes` reduces refinement in two-percent steps. Values in\n * the overflow window leave the threshold unchanged, preventing rapid load/evict oscillation.\n */\n adjustScreenSpaceError(): void {\n if (this.gpuMemoryUsageInBytes < this.cacheBytes) {\n this.memoryAdjustedScreenSpaceError = Math.max(\n this.memoryAdjustedScreenSpaceError / 1.02,\n this.options.maximumScreenSpaceError\n );\n } else if (this.gpuMemoryUsageInBytes > this.cacheBytes + this.maximumCacheOverflowBytes) {\n this.memoryAdjustedScreenSpaceError *= 1.02;\n }\n }\n\n private doUpdate(viewports: Viewport[] | Viewport): void {\n if ('loadTiles' in this.options && !this.options.loadTiles) {\n return;\n }\n if (this.traverseCounter > 0) {\n return;\n }\n const preparedViewports = viewports instanceof Array ? viewports : [viewports];\n const activeViewportIds = new Set(preparedViewports.map(viewport => viewport.id));\n // A viewport may be removed between frames. Discard its completed state before aggregating\n // requested and selected tiles so observability reflects only the current traversal inputs.\n for (const frameStateId of Object.keys(this.frameStateData)) {\n if (!activeViewportIds.has(frameStateId)) {\n delete this.frameStateData[frameStateId];\n }\n }\n\n this._cache.reset();\n this._frameNumber++;\n this.traverseCounter = preparedViewports.length;\n const currentTime = Date.now();\n let minimumDeferredTraversalDelay = Number.POSITIVE_INFINITY;\n const viewportsToTraverse: string[] = [];\n for (const viewport of preparedViewports) {\n const id = viewport.id;\n if (this._needTraverse(id)) {\n viewportsToTraverse.push(id);\n } else {\n this.traverseCounter--;\n }\n }\n\n for (const viewport of preparedViewports) {\n const id = viewport.id;\n if (!this.roots[id]) {\n this.roots[id] = this._initializeTileHeaders(this.tileset, null);\n }\n\n if (!viewportsToTraverse.includes(id)) {\n continue;\n }\n const frameState = getFrameState(viewport as GeospatialViewport, this._frameNumber);\n const root = this.roots[id];\n const cameraMotionUpdate = updateCameraMotionState(\n this._cameraMotionStates[id],\n frameState.camera.position,\n frameState.camera.direction,\n currentTime\n );\n this._cameraMotionStates[id] = cameraMotionUpdate.state;\n frameState.camera.timeSinceMovement = cameraMotionUpdate.timeSinceMovement;\n // Dynamic SSE reads the root's inverse computed transform before traversal updates tile\n // visibility. Refresh it from the current tileset model matrix here so animated local\n // box/sphere tilesets never calculate their height falloff one transform behind the frame.\n updateRootTransformForDynamicScreenSpaceError(root, this.modelMatrix);\n frameState.dynamicScreenSpaceErrorDensity =\n this.type === TILESET_TYPE.TILES3D &&\n this.options.dynamicScreenSpaceError &&\n !frameState.viewport.orthographic\n ? calculateDynamicScreenSpaceErrorDensity(root, frameState, this.options)\n : 0;\n // Keep the legacy diagnostic field, but traversal reads the per-viewport frame value above.\n this.dynamicScreenSpaceErrorComputedDensity = frameState.dynamicScreenSpaceErrorDensity;\n this._traverser.traverse(root, frameState, this.options);\n if (Object.keys(this._traverser.deferredTiles).length > 0) {\n minimumDeferredTraversalDelay = Math.min(\n minimumDeferredTraversalDelay,\n Math.max(this.options.foveatedTimeDelay - cameraMotionUpdate.timeSinceMovement, 0)\n );\n }\n }\n\n if (Number.isFinite(minimumDeferredTraversalDelay)) {\n this._scheduleDeferredTraversal(minimumDeferredTraversalDelay);\n } else {\n this._clearDeferredTraversal();\n }\n }\n\n /**\n * Schedules one follow-up traversal when the moving-camera deferral window expires.\n *\n * Replacing an existing timer ensures continuing camera movement pushes the retry window forward\n * instead of creating a queue of redundant traversals.\n *\n * @param delayInSeconds - Remaining stationary delay before deferred requests become eligible.\n */\n private _scheduleDeferredTraversal(delayInSeconds: number): void {\n this._clearDeferredTraversal();\n this._deferredTraversalTimeout = setTimeout(\n () => {\n this._deferredTraversalTimeout = null;\n this.selectTiles().catch((error: unknown) => {\n const traversalError = error instanceof Error ? error : new Error(String(error));\n this._onTilesetError(traversalError);\n });\n },\n Math.max(delayInSeconds * 1000, 0)\n );\n }\n\n /** Clears a pending moving-camera follow-up traversal. */\n private _clearDeferredTraversal(): void {\n if (this._deferredTraversalTimeout !== null) {\n clearTimeout(this._deferredTraversalTimeout);\n this._deferredTraversalTimeout = null;\n }\n }\n\n _needTraverse(viewportId: string): boolean {\n let traverserId = viewportId;\n if (this.options.viewportTraversersMap) {\n traverserId = this.options.viewportTraversersMap[viewportId];\n }\n return traverserId === viewportId;\n }\n\n _onTraversalEnd(frameState: FrameState): void {\n const id = frameState.viewport.id;\n if (!this.frameStateData[id]) {\n this.frameStateData[id] = {selectedTiles: [], _requestedTiles: [], _emptyTiles: []};\n }\n const currentFrameStateData = this.frameStateData[id];\n const selectedTiles = Object.values(this._traverser.selectedTiles);\n const [filteredSelectedTiles, unselectedTiles] = limitSelectedTiles(\n selectedTiles,\n frameState,\n this.options.maximumTilesSelected\n );\n currentFrameStateData.selectedTiles = filteredSelectedTiles;\n for (const tile of unselectedTiles) {\n tile.unselect();\n }\n\n currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);\n currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);\n\n this.traverseCounter--;\n if (this.traverseCounter > 0) {\n return;\n }\n\n this._updateTiles();\n }\n\n _updateTiles(): void {\n const previousSelectedTiles = this.selectedTiles;\n this.selectedTiles = [];\n this._requestedTiles = [];\n this._emptyTiles = [];\n\n for (const frameStateKey in this.frameStateData) {\n const frameStateDataValue = this.frameStateData[frameStateKey];\n this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);\n this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);\n this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);\n }\n\n this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);\n\n const selectedTiles = new Set(this.selectedTiles);\n const hasUndrawnTiles = this.selectedTiles.some(tile => !tile.tileDrawn);\n\n let heldBackCount = 0;\n if (hasUndrawnTiles) {\n const activeRoots = new Set(\n Object.keys(this.frameStateData).map(viewportId => this.roots[viewportId])\n );\n const descendantReadiness = new Map<Tile3D, boolean>();\n for (const tile of this.selectedTiles) {\n for (let ancestor = tile.parent; ancestor; ancestor = ancestor.parent) {\n descendantReadiness.set(\n ancestor,\n (descendantReadiness.get(ancestor) ?? true) && tile.tileDrawn\n );\n }\n }\n // Drawing can finish between traversals. Promote only previously selected\n // geometry that actually drew; pending tiles cannot provide visible fallback.\n for (const tile of previousSelectedTiles) {\n if (tile.tileDrawn) this._heldTiles.add(tile);\n }\n for (const tile of this._heldTiles) {\n let root = tile;\n while (root.parent) root = root.parent;\n // Removed viewport trees cannot contribute fallback to the remaining views.\n if (!activeRoots.has(root)) {\n this._heldTiles.delete(tile);\n continue;\n }\n if (selectedTiles.has(tile)) continue;\n if (\n tile.contentAvailable &&\n !this._hasDrawnReplacement(tile, selectedTiles, descendantReadiness)\n ) {\n tile._selectedFrame = this._frameNumber;\n this.selectedTiles.push(tile);\n heldBackCount++;\n } else {\n this._heldTiles.delete(tile);\n }\n }\n } else {\n this._heldTiles = selectedTiles;\n }\n\n if (heldBackCount > 0) {\n setTimeout(() => {\n this.selectTiles();\n }, 0);\n }\n\n for (const tile of this.selectedTiles) {\n this._tiles[tile.id] = tile;\n }\n\n this._loadTiles();\n this._unloadTiles();\n this._updateStats();\n\n if (this._tilesChanged(previousSelectedTiles, this.selectedTiles)) {\n this.options.onUpdate();\n }\n }\n\n /**\n * Releases fallback geometry once its own selected replacement has drawn.\n * Unrelated pending branches must not delay this region's handoff. When no related\n * replacement is selected, retain the fallback until the complete selection has drawn.\n */\n private _hasDrawnReplacement(\n tile: Tile3D,\n selectedTiles: Set<Tile3D>,\n descendantReadiness: Map<Tile3D, boolean>\n ): boolean {\n for (let ancestor = tile.parent; ancestor; ancestor = ancestor.parent) {\n if (selectedTiles.has(ancestor)) {\n return ancestor.tileDrawn;\n }\n }\n return descendantReadiness.get(tile) === true;\n }\n\n _tilesChanged(oldSelectedTiles: Tile3D[], selectedTiles: Tile3D[]): boolean {\n if (oldSelectedTiles.length !== selectedTiles.length) {\n return true;\n }\n const oldSet = new Set(oldSelectedTiles.map(tile => tile.id));\n const newSet = new Set(selectedTiles.map(tile => tile.id));\n let changed = oldSelectedTiles.some(tile => !newSet.has(tile.id));\n changed = changed || selectedTiles.some(tile => !oldSet.has(tile.id));\n return changed;\n }\n\n _loadTiles(): void {\n this._requestedTiles.sort((tileA, tileB) => tileA._priority - tileB._priority);\n for (const tile of this._requestedTiles) {\n if (tile.contentUnloaded) {\n this._loadTile(tile);\n }\n }\n }\n\n _unloadTiles(): void {\n this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));\n if (this.options.memoryAdjustedScreenSpaceError) {\n this.adjustScreenSpaceError();\n }\n }\n\n _updateStats(): void {\n let tilesRenderable = 0;\n let pointsRenderable = 0;\n for (const tile of this.selectedTiles) {\n if (tile.contentAvailable && tile.content) {\n tilesRenderable++;\n const contents = tile.contents.length ? tile.contents : [tile.content];\n for (const content of contents) {\n if (content.pointCount) {\n pointsRenderable += content.pointCount;\n } else {\n pointsRenderable += content.vertexCount || 0;\n }\n }\n }\n }\n\n this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;\n this.stats.get(TILES_RENDERABLE).count = tilesRenderable;\n this.stats.get(POINTS_COUNT).count = pointsRenderable;\n this.stats.get(MAXIMUM_SSE).count = this.memoryAdjustedScreenSpaceError;\n }\n\n async _initializeTileSet(): Promise<void> {\n try {\n const initializePromise = this.source.initialize();\n const initialMetadata = this._getSourceMetadata();\n if (initialMetadata) {\n this._syncSourceState(initialMetadata);\n }\n if (\n initialMetadata?.tileset?.root &&\n typeof initialMetadata.tileset.root.then !== 'function' &&\n (!this.source.prepareTileset || this.spatialReference?.status === 'native')\n ) {\n this.root = this._initializeTileHeaders(initialMetadata.tileset, null);\n this._applyViewState();\n }\n\n await initializePromise;\n const metadata = this.source.getMetadata();\n this._syncSourceState(metadata);\n await this.source.prepareTileset?.(this);\n if (!this.root) {\n this.root = this._initializeTileHeaders(metadata.tileset, null);\n }\n this._applyViewState();\n } catch (error: unknown) {\n const sourceError = error instanceof Error ? error : new Error(String(error));\n this._onSourceError(sourceError, this.root);\n this._onTilesetError(sourceError);\n throw sourceError;\n }\n }\n\n _initializeStats(): void {\n this.stats.get(TILES_TOTAL);\n this.stats.get(TILES_LOADING);\n this.stats.get(TILES_IN_MEMORY);\n this.stats.get(TILES_IN_VIEW);\n this.stats.get(TILES_RENDERABLE);\n this.stats.get(TILES_LOADED);\n this.stats.get(TILES_UNLOADED);\n this.stats.get(TILES_LOAD_FAILED);\n this.stats.get(POINTS_COUNT);\n this.stats.get(TILES_GPU_MEMORY, 'memory');\n this.stats.get(MAXIMUM_SSE);\n }\n\n _initializeTileHeaders(tilesetJson: TilesetJSON, parentTileHeader?: Tile3D | null): Tile3D {\n return this.source.initializeTileHeaders(this, tilesetJson, parentTileHeader);\n }\n\n _initializeTraverser(): TilesetTraverser {\n return this.source.createTraverser({\n basePath: this.basePath,\n onTraversalEnd: this._onTraversalEnd.bind(this)\n });\n }\n\n _destroyTileHeaders(parentTile: Tile3D): void {\n this._destroySubtree(parentTile);\n }\n\n async _loadTile(tile: Tile3D): Promise<void> {\n let loadResult: TileContentLoadResult | null = null;\n try {\n this._onStartTileLoading();\n loadResult = await tile.loadContent();\n } catch (error: unknown) {\n const tileError = error instanceof Error ? error : new Error('load failed');\n this._onSourceError(tileError, tile);\n this._onTileLoadError(tile, tileError);\n } finally {\n this._onEndTileLoading();\n this._onTileLoad(tile, loadResult);\n }\n }\n\n /**\n * Loads a source-managed lazy child-header group and reports failures through tile callbacks.\n *\n * Subtree metadata shares the normal loading counters but is not reported as render content and\n * is not added to the GPU cache. Traversal is notified separately after the promise settles.\n *\n * @param tile - Runtime tile that owns the lazy subtree reference.\n * @param frameState - View state that made the subtree eligible for refinement.\n */\n async _loadTileChildren(tile: Tile3D, frameState: FrameState): Promise<void> {\n try {\n this._onStartTileLoading();\n await tile.loadChildren(frameState);\n } catch (error: unknown) {\n const tileError = error instanceof Error ? error : new Error('subtree load failed');\n this._onSourceError(tileError, tile);\n this._onTileLoadError(tile, tileError);\n } finally {\n this._onEndTileLoading();\n }\n }\n\n _onTileLoadError(tile: Tile3D, error: Error): void {\n this.stats.get(TILES_LOAD_FAILED).incrementCount();\n\n const message = error.message || error.toString();\n const url = tile.url;\n console.error(`A 3D tile failed to load: ${tile.url} ${message}`);\n this.options.onTileError(tile, message, url);\n }\n\n _onSourceError(error: Error, tile: Tile3D | null = null): void {\n this.options.onSourceError(error, this.source, tile);\n }\n\n _onTilesetError(error: Error): void {\n this.options.onTilesetError(error, this);\n }\n\n _onTileLoad(tile: Tile3D, loadResult: TileContentLoadResult | null): void {\n if (!loadResult?.loaded) {\n return;\n }\n\n if (tile.content) {\n calculateTransformProps(tile, tile.content);\n }\n\n this.source.onTileLoaded?.(this, tile, loadResult);\n this._syncSourceState(this.source.getMetadata());\n\n const totalTiles = this.source.getTilesTotalCount?.();\n if (totalTiles) {\n this.stats.get(TILES_TOTAL).reset();\n this.stats.get(TILES_TOTAL).addCount(totalTiles);\n }\n\n this._addTileToCache(tile);\n this.options.onTileLoad(tile);\n }\n\n _onStartTileLoading(): void {\n this._pendingCount++;\n this.stats.get(TILES_LOADING).incrementCount();\n }\n\n _onEndTileLoading(): void {\n this._pendingCount--;\n this.stats.get(TILES_LOADING).decrementCount();\n }\n\n _addTileToCache(tile: Tile3D): void {\n this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));\n }\n\n _updateCacheStats(tile: Tile3D): void {\n this.stats.get(TILES_LOADED).incrementCount();\n this.stats.get(TILES_IN_MEMORY).incrementCount();\n\n this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;\n this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;\n\n if (this.options.memoryAdjustedScreenSpaceError) {\n this.adjustScreenSpaceError();\n }\n }\n\n _unloadTile(tile: Tile3D): void {\n this.gpuMemoryUsageInBytes -= tile.gpuMemoryUsageInBytes || 0;\n\n this.stats.get(TILES_IN_MEMORY).decrementCount();\n this.stats.get(TILES_UNLOADED).incrementCount();\n this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;\n\n this.options.onTileUnload(tile);\n tile.unloadContent();\n }\n\n _destroy(): void {\n const stack: Tile3D[] = [];\n\n if (this.root) {\n stack.push(this.root);\n }\n\n while (stack.length > 0) {\n const tile = stack.pop() as Tile3D;\n\n for (const child of tile.children) {\n stack.push(child);\n }\n\n this._destroyTile(tile);\n }\n this.root = null;\n }\n\n _destroySubtree(tile: Tile3D): void {\n const rootTile = tile;\n const stack: Tile3D[] = [rootTile];\n while (stack.length > 0) {\n tile = stack.pop() as Tile3D;\n for (const child of tile.children) {\n stack.push(child);\n }\n if (tile !== rootTile) {\n this._destroyTile(tile);\n }\n }\n rootTile.children = [];\n }\n\n _destroyTile(tile: Tile3D): void {\n this._cache.unloadTile(this, tile);\n this._unloadTile(tile);\n tile.destroy();\n }\n\n private _syncSourceState(metadata: TilesetSourceMetadata): void {\n this.tileset = metadata.tileset;\n this.loader = metadata.loader;\n this.type = metadata.type;\n this.url = metadata.url;\n this.basePath = metadata.basePath;\n this.lodMetricType = metadata.lodMetricType;\n this.lodMetricValue = metadata.lodMetricValue;\n this.refine = metadata.refine;\n this.contentFormats = this.source.contentFormats;\n this.asset = this.source.asset || this.asset;\n const tileset = metadata.tileset as Record<string, any>;\n this.schema = tileset.schema || null;\n this.schemaUri = tileset.schemaUri || null;\n this.groups = tileset.groups || [];\n this.metadata = tileset.metadata || null;\n this.statistics = tileset.statistics ?? null;\n const spatialReference = applyTilesetSpatialOptions(\n metadata.spatialReference,\n this.options.spatial\n );\n this.spatialReference = preserveTransformedSpatialReference(\n this.spatialReference,\n spatialReference\n );\n this.properties = this.source.properties ?? this.properties;\n this.extras = this.source.extras ?? this.extras;\n if (this.options.attributions?.length) {\n this.credits = {attributions: this.options.attributions};\n } else {\n this.credits = this.source.credits || this.credits;\n }\n }\n\n private _applyViewState(): void {\n const viewState = this.source.getViewState(this.root);\n this.asset = viewState.asset || this.source.asset || {};\n this.properties = viewState.properties ?? this.source.properties;\n this.extras = viewState.extras ?? this.source.extras ?? null;\n this.credits = viewState.credits ||\n this.source.credits ||\n this.credits || {attributions: this.options.attributions || []};\n this.description = viewState.description || this.options.description || '';\n this.boundingVolume = viewState.boundingVolume || this.root?.boundingVolume || null;\n this.cartographicCenter = viewState.cartographicCenter || new Vector3();\n this.cartesianCenter = viewState.cartesianCenter || null;\n this.zoom = viewState.zoom || 1;\n this.geometricError = this.tileset?.geometricError || 0;\n }\n\n /**\n * Returns normalized source metadata when initialization has already populated it.\n */\n private _getSourceMetadata(): TilesetSourceMetadata | null {\n try {\n return this.source.getMetadata();\n } catch {\n return null;\n }\n }\n}\n\n/** Preserve a completed runtime operation when asynchronous source metadata describes the same request. */\nfunction preserveTransformedSpatialReference(\n current: TilesetSpatialReference,\n next: TilesetSpatialReference\n): TilesetSpatialReference {\n return current?.status === 'transformed' &&\n current.sourceCrs === next.sourceCrs &&\n current.targetCrs === next.targetCrs &&\n current.targetHeightReference === next.targetHeightReference &&\n current.outputCoordinates === next.outputCoordinates\n ? current\n : next;\n}\n", "// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default function getHiResTimestamp(): number {\n let timestamp;\n // Get best timer available.\n if (typeof window !== 'undefined' && window.performance) {\n timestamp = window.performance.now();\n } else if (typeof process !== 'undefined' && process.hrtime) {\n const timeParts = process.hrtime();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n", "import getHiResTimestamp from '../utils/hi-res-timestamp';\n\nexport default class Stat {\n readonly name: string;\n readonly type: string | undefined;\n sampleSize: number = 1;\n time: number = 0;\n count: number = 0;\n samples: number = 0;\n lastTiming: number = 0;\n lastSampleTime: number = 0;\n lastSampleCount: number = 0;\n\n _count: number = 0;\n _time: number = 0;\n _samples: number = 0;\n _startTime: number = 0;\n _timerPending: boolean = false;\n\n constructor(name: string, type?: string) {\n this.name = name;\n this.type = type;\n this.reset();\n }\n\n reset(): this {\n this.time = 0;\n this.count = 0;\n this.samples = 0;\n this.lastTiming = 0;\n this.lastSampleTime = 0;\n this.lastSampleCount = 0;\n this._count = 0;\n this._time = 0;\n this._samples = 0;\n this._startTime = 0;\n this._timerPending = false;\n\n return this;\n }\n\n setSampleSize(samples: number): this {\n this.sampleSize = samples;\n return this;\n }\n\n /** Call to increment count (+1) */\n incrementCount(): this {\n this.addCount(1);\n\n return this;\n }\n\n /** Call to decrement count (-1) */\n decrementCount(): this {\n this.subtractCount(1);\n\n return this;\n }\n\n /** Increase count */\n addCount(value: number): this {\n this._count += value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Decrease count */\n subtractCount(value: number): this {\n this._count -= value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Add an arbitrary timing and bump the count */\n addTime(time: number): this {\n this._time += time;\n this.lastTiming = time;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n /** Start a timer */\n timeStart(): this {\n this._startTime = getHiResTimestamp();\n this._timerPending = true;\n\n return this;\n }\n\n /** End a timer. Adds to time and bumps the timing count. */\n timeEnd(): this {\n if (!this._timerPending) {\n return this;\n }\n this.addTime(getHiResTimestamp() - this._startTime);\n this._timerPending = false;\n this._checkSampling();\n\n return this;\n }\n\n getSampleAverageCount(): number {\n return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;\n }\n\n /** Calculate average time / count for the previous window */\n getSampleAverageTime(): number {\n return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;\n }\n\n /** Calculate counts per second for the previous window */\n getSampleHz(): number {\n return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;\n }\n\n getAverageCount(): number {\n return this.samples > 0 ? this.count / this.samples : 0;\n }\n\n /** Calculate average time / count */\n getAverageTime(): number {\n return this.samples > 0 ? this.time / this.samples : 0;\n }\n\n /** Calculate counts per second */\n getHz(): number {\n return this.time > 0 ? this.samples / (this.time / 1000) : 0;\n }\n\n _checkSampling(): void {\n if (this._samples === this.sampleSize) {\n this.lastSampleTime = this._time;\n this.lastSampleCount = this._count;\n this.count += this._count;\n this.time += this._time;\n this.samples += this._samples;\n this._time = 0;\n this._count = 0;\n this._samples = 0;\n }\n }\n}\n", "// probe.gl, MIT license\n\nimport Stat from './stat';\n\ntype TableEntry = {\n time: number;\n count: number;\n average: number;\n hz: number;\n};\n\n/** A \"bag\" of `Stat` objects, can be visualized using `StatsWidget` */\nexport default class Stats {\n readonly id: string;\n readonly stats: Record<string, Stat> = {};\n\n constructor(options: {id: string; stats?: Stats | Stat[] | {name: string; type?: string}[]}) {\n this.id = options.id;\n this.stats = {};\n\n this._initializeStats(options.stats);\n\n Object.seal(this);\n }\n\n /** Acquire a stat. Create if it doesn't exist. */\n get(name: string, type: string = 'count'): Stat {\n return this._getOrCreate({name, type});\n }\n\n get size(): number {\n return Object.keys(this.stats).length;\n }\n\n /** Reset all stats */\n reset(): this {\n for (const stat of Object.values(this.stats)) {\n stat.reset();\n }\n\n return this;\n }\n\n forEach(fn: (stat: Stat) => void): void {\n for (const stat of Object.values(this.stats)) {\n fn(stat);\n }\n }\n\n getTable(): Record<string, TableEntry> {\n const table: Record<string, TableEntry> = {};\n this.forEach(stat => {\n table[stat.name] = {\n time: stat.time || 0,\n count: stat.count || 0,\n average: stat.getAverageTime() || 0,\n hz: stat.getHz() || 0\n };\n });\n\n return table;\n }\n\n _initializeStats(stats: Stats | Stat[] | {name: string; type?: string}[] = []): void {\n stats.forEach(stat => this._getOrCreate(stat));\n }\n\n _getOrCreate(stat: Stat | {name: string, type?: string}): Stat {\n const {name, type} = stat;\n let result = this.stats[name];\n if (!result) {\n if (stat instanceof Stat) {\n result = stat;\n } else {\n result = new Stat(name, type);\n }\n this.stats[name] = result;\n }\n return result;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\n/**\n * Doubly linked list node\n * @private\n */\nexport class DoublyLinkedListNode {\n item;\n previous;\n next;\n\n constructor(item, previous, next) {\n this.item = item;\n this.previous = previous;\n this.next = next;\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {DoublyLinkedListNode} from './doubly-linked-list-node';\n\n/**\n * Doubly linked list\n * @private\n */\nexport class DoublyLinkedList {\n head: DoublyLinkedListNode | null = null;\n tail: DoublyLinkedListNode | null = null;\n _length = 0;\n\n get length() {\n return this._length;\n }\n\n /**\n * Adds the item to the end of the list\n * @param {*} [item]\n * @return {DoublyLinkedListNode}\n */\n add(item) {\n const node = new DoublyLinkedListNode(item, this.tail, null);\n\n if (this.tail) {\n this.tail.next = node;\n this.tail = node;\n } else {\n this.head = node;\n this.tail = node;\n }\n\n ++this._length;\n\n return node;\n }\n\n /**\n * Removes the given node from the list\n * @param {DoublyLinkedListNode} node\n */\n remove(node) {\n if (!node) {\n return;\n }\n\n if (node.previous && node.next) {\n node.previous.next = node.next;\n node.next.previous = node.previous;\n } else if (node.previous) {\n // Remove last node\n node.previous.next = null;\n this.tail = node.previous;\n } else if (node.next) {\n // Remove first node\n node.next.previous = null;\n this.head = node.next;\n } else {\n // Remove last node in the linked list\n this.head = null;\n this.tail = null;\n }\n\n node.next = null;\n node.previous = null;\n\n --this._length;\n }\n\n /**\n * Moves nextNode after node\n * @param {DoublyLinkedListNode} node\n * @param {DoublyLinkedListNode} nextNode\n */\n splice(node, nextNode) {\n if (node === nextNode) {\n return;\n }\n\n // Remove nextNode, then insert after node\n this.remove(nextNode);\n this._insert(node, nextNode);\n }\n\n _insert(node, nextNode) {\n const oldNodeNext = node.next;\n node.next = nextNode;\n\n // nextNode is the new tail\n if (this.tail === node) {\n this.tail = nextNode;\n } else {\n oldNodeNext.previous = nextNode;\n }\n\n nextNode.next = oldNodeNext;\n nextNode.previous = node;\n\n ++this._length;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport type {Tileset3D} from './tileset-3d';\nimport type {Tile3D} from './tile-3d';\nimport {DoublyLinkedList} from '../../utils/doubly-linked-list';\n\n/**\n * Stores tiles with content loaded.\n * @private\n */\nexport class TilesetCache {\n private _list: DoublyLinkedList;\n private _sentinel: any;\n private _trimTiles: boolean;\n\n constructor() {\n // [head, sentinel) -> tiles that weren't selected this frame and may be removed from the cache\n // (sentinel, tail] -> tiles that were selected this frame\n this._list = new DoublyLinkedList();\n this._sentinel = this._list.add('sentinel');\n this._trimTiles = false;\n }\n\n reset(): void {\n // Move sentinel node to the tail so, at the start of the frame, all tiles\n // may be potentially replaced. Tiles are moved to the right of the sentinel\n // when they are selected so they will not be replaced.\n this._list.splice(this._list.tail, this._sentinel);\n }\n\n touch(tile: Tile3D): void {\n const node = tile._cacheNode;\n if (node) {\n this._list.splice(this._sentinel, node);\n }\n }\n\n add(\n tileset: Tileset3D,\n tile: Tile3D,\n addCallback?: (tileset: Tileset3D, tile: Tile3D) => void\n ): void {\n if (!tile._cacheNode) {\n tile._cacheNode = this._list.add(tile);\n\n if (addCallback) {\n addCallback(tileset, tile);\n }\n }\n }\n\n unloadTile(\n tileset: Tileset3D,\n tile: Tile3D,\n unloadCallback?: (tileset: Tileset3D, tile: Tile3D) => void\n ): void {\n const node = tile._cacheNode;\n if (!node) {\n return;\n }\n\n this._list.remove(node);\n tile._cacheNode = null;\n if (unloadCallback) {\n unloadCallback(tileset, tile);\n }\n }\n\n /**\n * Unloads least-recently-used tiles until the byte-native cache target is met.\n *\n * Tiles touched after the frame sentinel remain protected, so {@link Tileset3D.cacheBytes} is a\n * soft target rather than a hard cap on the visible working set. Overflow headroom affects\n * memory-adjusted SSE, not eviction of unused tiles.\n *\n * @param tileset - Tileset that owns the cache and reports estimated content memory.\n * @param unloadCallback - Callback that releases content and decrements the memory estimate.\n */\n unloadTiles(\n tileset: Tileset3D,\n unloadCallback?: (tileset: Tileset3D, tile: Tile3D) => void\n ): void {\n const trimTiles = this._trimTiles;\n this._trimTiles = false;\n\n const list = this._list;\n\n // Traverse the list only to the sentinel since tiles/nodes to the\n // right of the sentinel were used this frame.\n // The sub-list to the left of the sentinel is ordered from LRU to MRU.\n const sentinel = this._sentinel;\n let node = list.head;\n\n while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > tileset.cacheBytes || trimTiles)) {\n // @ts-expect-error\n const tile = node.item;\n // @ts-expect-error\n node = node.next;\n this.unloadTile(tileset, tile, unloadCallback);\n }\n }\n\n trim(): void {\n this._trimTiles = true;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport {assert} from '@loaders.gl/loader-utils';\n\nimport {Tile3D} from '../common/tile-3d';\n\nexport function calculateTransformProps(tileHeader: Tile3D, tile: Tile3D['content']) {\n assert(tileHeader);\n assert(tile);\n\n const {rtcCenter, gltfUpAxis} = tile;\n const {\n computedTransform,\n boundingVolume: {center}\n } = tileHeader;\n\n let modelMatrix = new Matrix4(computedTransform);\n\n // Translate if appropriate\n if (rtcCenter) {\n modelMatrix.translate(rtcCenter);\n }\n\n // glTF models need to be rotated from Y to Z up\n // https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification#y-up-to-z-up\n switch (gltfUpAxis) {\n case 'Z':\n break;\n case 'Y':\n const rotationY = new Matrix4().rotateX(Math.PI / 2);\n modelMatrix = modelMatrix.multiplyRight(rotationY);\n break;\n case 'X':\n const rotationX = new Matrix4().rotateY(-Math.PI / 2);\n modelMatrix = modelMatrix.multiplyRight(rotationX);\n break;\n default:\n break;\n }\n\n // Scale/offset positions if normalized integers\n if (tile.isQuantized) {\n modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);\n }\n\n // Option 1: Cartesian matrix and origin\n const cartesianOrigin = new Vector3(center);\n\n tile.cartesianModelMatrix = modelMatrix;\n tile.cartesianOrigin = cartesianOrigin;\n\n // Option 2: Cartographic matrix and origin\n const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(\n cartesianOrigin,\n new Vector3()\n );\n const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);\n const toFixedFrameMatrix = fromFixedFrameMatrix.invert();\n\n tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);\n tile.cartographicOrigin = cartographicOrigin;\n\n // Absorb glTF root node matrix into model matrices for Float32 precision.\n // The glTF root node matrix (applied as sceneModelMatrix in the shader) may contain\n // ECEF-scale translations (~millions of meters). When both cartographicModelMatrix\n // and sceneModelMatrix are applied in the Float32 GPU shader, catastrophic cancellation\n // occurs causing visible seams between adjacent tiles. By combining them here in Float64,\n // the result has small ENU-scale values that preserve precision.\n const rootNode = _getRootNode(tile);\n if (rootNode) {\n tile.cartesianModelMatrix = new Matrix4(modelMatrix).multiplyRight(rootNode.matrix);\n tile.cartographicModelMatrix.multiplyRight(rootNode.matrix);\n rootNode.matrix = Matrix4.IDENTITY;\n }\n\n // Deprecated, drop\n if (!tile.coordinateSystem) {\n tile.modelMatrix = tile.cartographicModelMatrix;\n }\n}\n\nconst TRANSLATION_LIMIT_SQUARED = 10e5 ** 2; // 100km\n\n/**\n * Returns the glTF root node if it has a matrix with earth-scale translations (> 100km).\n * These large translations cause Float32 precision issues when applied in the GPU shader.\n */\nfunction _getRootNode(tile: Tile3D['content']): {matrix: number[]} | null {\n const gltf = tile.gltf;\n if (!gltf) {\n return null;\n }\n\n const sceneIndex = typeof gltf.scene === 'number' ? gltf.scene : 0;\n const scene = gltf.scenes?.[sceneIndex];\n const rootNode = scene?.nodes?.[0];\n if (!rootNode?.matrix) return null;\n\n // Extract translation and compare magnitude (meters) to limit\n const m = rootNode.matrix;\n const translationMagnitude = m[12] * m[12] + m[13] * m[13] + m[14] * m[14];\n if (translationMagnitude <= TRANSLATION_LIMIT_SQUARED) return null;\n\n return rootNode;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Tile3D} from '../common/tile-3d';\nimport {Vector3} from '@math.gl/core';\nimport {CullingVolume, Plane} from '@math.gl/culling';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {GeospatialViewport, Viewport} from '../../types';\n\nexport type FrameState = {\n camera: {\n /** Camera position in WGS84 Cartesian meters. */\n position: number[];\n /** Normalized camera direction in WGS84 Cartesian coordinates. */\n direction: number[];\n /** Normalized camera up direction in WGS84 Cartesian coordinates. */\n up: number[];\n /** Camera position as `[longitude, latitude, height]`, with height in meters. */\n cartographicPosition: [number, number, number];\n /** Perspective vertical field of view in radians. */\n verticalFieldOfView: number;\n /** Elapsed seconds since camera position or direction last changed. */\n timeSinceMovement: number;\n };\n viewport: GeospatialViewport;\n topDownViewport: GeospatialViewport; // Use it to calculate projected radius for a tile\n height: number;\n cullingVolume: CullingVolume;\n /** Optional world-space clipping planes applied to render-content culling. */\n clippingPlanes?: Plane[];\n frameNumber: number; // TODO: This can be the same between updates, what number is unique for between updates?\n /** Perspective projection factor: twice the tangent of half the vertical field of view. */\n sseDenominator: number;\n /** View-dependent density used by perspective dynamic screen-space error for this traversal. */\n dynamicScreenSpaceErrorDensity: number;\n};\n\n/** Optional camera and projection measurements supplied when constructing a frame state. */\nexport type GetFrameStateOptions = {\n /** Elapsed seconds since camera position or direction last changed. */\n timeSinceCameraMovement?: number;\n};\n\n/** Camera pose and timestamp retained between traversal frames. */\nexport type CameraMotionState = {\n /** Last observed Earth-centered, Earth-fixed camera position. */\n position: number[];\n /** Last observed normalized Earth-centered, Earth-fixed camera direction. */\n direction: number[];\n /** Timestamp in milliseconds of the last observed pose change. */\n lastMovementTime: number;\n};\n\n/** Updated camera state and elapsed stationary time for a traversal frame. */\nexport type CameraMotionUpdate = {\n /** Camera pose to retain for the next traversal. */\n state: CameraMotionState;\n /** Elapsed seconds since the camera pose last changed. */\n timeSinceMovement: number;\n};\n\nconst scratchVector = new Vector3();\nconst scratchPosition = new Vector3();\nconst CAMERA_POSITION_EPSILON = 1e-5;\nconst CAMERA_DIRECTION_EPSILON = 1e-7;\nconst cullingVolume = new CullingVolume([\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane()\n]);\n\n/**\n * Extracts a frame state appropriate for tile culling from a structural deck.gl viewport.\n *\n * The viewport must describe the render camera, including its elevation. Geographic heights\n * returned by `unprojectPosition` are used directly; adding a terrain offset only to traversal\n * would make visibility, camera distances, and screen-space error disagree with rendering.\n *\n * `options.timeSinceCameraMovement` can be supplied by a caller that retains camera pose across\n * calls. It defaults to a stationary camera so standalone callers do not defer requests.\n *\n * @param viewport - Geospatial viewport supplying camera and projection measurements.\n * @param frameNumber - Current tileset traversal frame number.\n * @param options - Additional camera and projection measurements for traversal.\n * @returns Frame state used for visibility, SSE, and request-priority calculations.\n */\nexport function getFrameState(\n viewport: GeospatialViewport,\n frameNumber: number,\n options: GetFrameStateOptions = {}\n): FrameState {\n // Traverse and and request. Update _selectedTiles so that we know what to render.\n // Traverse and and request. Update _selectedTiles so that we know what to render.\n const {cameraUp, height} = viewport;\n const cameraDirection = viewport.cameraDirection as number[] | undefined;\n const {metersPerUnit} = viewport.distanceScales;\n\n // TODO - Ellipsoid.eastNorthUpToFixedFrame() breaks on raw array, create a Vector.\n // TODO - Ellipsoid.eastNorthUpToFixedFrame() takes a cartesian, is that intuitive?\n const viewportCenterCartesian = worldToCartesian(viewport, viewport.center);\n const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);\n\n const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);\n const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(\n cameraPositionCartographic,\n new Vector3()\n );\n\n // These should still be normalized as the transform has scale 1 (goes from meters to meters)\n let cameraDirectionCartesian: Vector3;\n if (cameraDirection) {\n cameraDirectionCartesian = new Vector3(\n // @ts-ignore\n enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))\n ).normalize();\n } else {\n // Concrete deck.gl viewports do not expose the legacy structural cameraDirection field.\n // The near-plane center is on the view axis, so its world-space direction is equivalent and\n // works for perspective foveation without coupling loaders.gl to deck.gl internals.\n // getFrustumPlanes is required by traversal but omitted from the minimal structural Viewport\n // type for compatibility with existing application-side declarations.\n // @ts-expect-error Runtime geospatial viewports provide getFrustumPlanes.\n const nearPlane = viewport.getFrustumPlanes().near;\n const nearCenterCommon = closestPointOnPlane(nearPlane, viewport.cameraPosition);\n const nearCenterCartesian = worldToCartesian(viewport, nearCenterCommon);\n cameraDirectionCartesian = new Vector3(nearCenterCartesian)\n .subtract(cameraPositionCartesian)\n .normalize();\n }\n const cameraUpCartesian = new Vector3(\n // @ts-ignore\n enuToFixedTransform.transformAsVector(new Vector3(cameraUp).scale(metersPerUnit))\n ).normalize();\n\n commonSpacePlanesToWGS84(viewport);\n\n const ViewportClass = viewport.constructor;\n const {longitude, latitude, width, bearing, zoom, position} = viewport;\n // @ts-ignore\n const topDownViewport = new ViewportClass({\n longitude,\n latitude,\n height,\n width,\n bearing,\n zoom,\n position,\n pitch: 0\n });\n\n const verticalFieldOfView =\n Number.isFinite(viewport.fovy) && Number(viewport.fovy) > 0 && Number(viewport.fovy) < 180\n ? (Number(viewport.fovy) * Math.PI) / 180\n : Math.PI / 3;\n\n // TODO: make a file/class for frameState and document what needs to be attached to this so that traversal can function\n return {\n camera: {\n position: cameraPositionCartesian,\n direction: cameraDirectionCartesian,\n up: cameraUpCartesian,\n cartographicPosition: cameraPositionCartographic,\n verticalFieldOfView,\n timeSinceMovement: options.timeSinceCameraMovement ?? Number.POSITIVE_INFINITY\n },\n viewport,\n topDownViewport,\n height,\n cullingVolume,\n clippingPlanes: viewport.clippingPlanes,\n frameNumber, // TODO: This can be the same between updates, what number is unique for between updates?\n sseDenominator: 2 * Math.tan(verticalFieldOfView / 2),\n // Tileset3D fills this immediately before traversal because it depends on the root volume.\n dynamicScreenSpaceErrorDensity: 0\n };\n}\n\n/**\n * Updates retained camera motion state and calculates how long the current pose has been stable.\n *\n * The first observation is treated as stationary so initial tileset loading is never delayed.\n * Position and direction are both compared because orbiting in place changes request relevance\n * without necessarily changing the viewport's camera position.\n *\n * @param previousState - Pose retained from the preceding traversal for this viewport.\n * @param position - Current Earth-centered, Earth-fixed camera position.\n * @param direction - Current normalized Earth-centered, Earth-fixed camera direction.\n * @param currentTime - Current monotonic-enough wall-clock time in milliseconds.\n * @returns Updated pose and elapsed stationary time.\n */\nexport function updateCameraMotionState(\n previousState: CameraMotionState | undefined,\n position: number[] | Vector3,\n direction: number[] | Vector3,\n currentTime: number\n): CameraMotionUpdate {\n const positionArray = Array.from(position);\n const directionArray = Array.from(direction);\n const positionChanged = previousState\n ? positionArray.length !== previousState.position.length ||\n positionArray.some(\n (value, index) => Math.abs(value - previousState.position[index]) > CAMERA_POSITION_EPSILON\n )\n : false;\n const directionChanged = previousState\n ? directionArray.length !== previousState.direction.length ||\n directionArray.some(\n (value, index) =>\n Math.abs(value - previousState.direction[index]) > CAMERA_DIRECTION_EPSILON\n )\n : false;\n const lastMovementTime =\n positionChanged || directionChanged\n ? currentTime\n : (previousState?.lastMovementTime ?? Number.NEGATIVE_INFINITY);\n\n return {\n state: {\n position: positionArray,\n direction: directionArray,\n lastMovementTime\n },\n timeSinceMovement: Math.max((currentTime - lastMovementTime) / 1000, 0)\n };\n}\n\n/**\n * Limit `tiles` array length with `maximumTilesSelected` number.\n * The criteria for this filtering is distance of a tile center\n * to the `frameState.viewport`'s longitude and latitude\n * @param tiles - tiles array to filter\n * @param frameState - frameState to calculate distances\n * @param maximumTilesSelected - maximal amount of tiles in the output array\n * @returns new tiles array\n */\nexport function limitSelectedTiles(\n tiles: Tile3D[],\n frameState: FrameState,\n maximumTilesSelected: number\n): [Tile3D[], Tile3D[]] {\n if (maximumTilesSelected === 0 || tiles.length <= maximumTilesSelected) {\n return [tiles, []];\n }\n // Accumulate distances in couples array: [tileIndex: number, distanceToViewport: number]\n const tuples: [number, number][] = [];\n const {longitude: viewportLongitude, latitude: viewportLatitude} = frameState.viewport;\n for (const [index, tile] of tiles.entries()) {\n const [longitude, latitude] = tile.header.mbs;\n const deltaLon = Math.abs(viewportLongitude - longitude);\n const deltaLat = Math.abs(viewportLatitude - latitude);\n const distance = Math.sqrt(deltaLat * deltaLat + deltaLon * deltaLon);\n tuples.push([index, distance]);\n }\n const tuplesSorted = tuples.sort((a, b) => a[1] - b[1]);\n const selectedTiles: Tile3D[] = [];\n for (let i = 0; i < maximumTilesSelected; i++) {\n selectedTiles.push(tiles[tuplesSorted[i][0]]);\n }\n const unselectedTiles: Tile3D[] = [];\n for (let i = maximumTilesSelected; i < tuplesSorted.length; i++) {\n unselectedTiles.push(tiles[tuplesSorted[i][0]]);\n }\n\n return [selectedTiles, unselectedTiles];\n}\n\nfunction commonSpacePlanesToWGS84(viewport) {\n // Extract frustum planes based on current view.\n const frustumPlanes = viewport.getFrustumPlanes();\n\n // Get the near/far plane centers\n const nearCenterCommon = closestPointOnPlane(frustumPlanes.near, viewport.cameraPosition);\n const nearCenterCartesian = worldToCartesian(viewport, nearCenterCommon);\n const cameraCartesian = worldToCartesian(viewport, viewport.cameraPosition, scratchPosition);\n\n let i = 0;\n cullingVolume.planes[i++].fromPointNormal(\n nearCenterCartesian,\n scratchVector.copy(nearCenterCartesian).subtract(cameraCartesian)\n );\n\n for (const dir in frustumPlanes) {\n if (dir === 'near') {\n continue; // eslint-disable-line no-continue\n }\n const plane = frustumPlanes[dir];\n const posCommon = closestPointOnPlane(plane, nearCenterCommon, scratchPosition);\n const cartesianPos = worldToCartesian(viewport, posCommon, scratchPosition);\n\n cullingVolume.planes[i++].fromPointNormal(\n cartesianPos,\n // Want the normal to point into the frustum since that's what culling expects\n scratchVector.copy(nearCenterCartesian).subtract(cartesianPos)\n );\n }\n}\n\nfunction closestPointOnPlane(\n plane: {distance: number; normal: Vector3},\n refPoint: number[] | Vector3,\n out: Vector3 = new Vector3()\n): Vector3 {\n const distanceToRef = plane.normal.dot(refPoint);\n out\n .copy(plane.normal)\n .scale(plane.distance - distanceToRef)\n .add(refPoint);\n return out;\n}\n\nfunction worldToCartesian(\n viewport: Viewport,\n point: number[] | Vector3,\n out: Vector3 = new Vector3()\n): Vector3 {\n const cartographicPos = viewport.unprojectPosition(point);\n return Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, out);\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Matrix4, Quaternion, Vector3, clamp} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport type {Tile3D} from '../common/tile-3d';\nimport type {FrameState} from './frame-state';\n\n/** Options that control the perspective dynamic screen-space error optimization. */\nexport type DynamicScreenSpaceErrorOptions = {\n /** Base fog density used to reduce distant, horizon-facing screen-space error. */\n dynamicScreenSpaceErrorDensity: number;\n /** Maximum number of logical pixels subtracted from perspective screen-space error. */\n dynamicScreenSpaceErrorFactor: number;\n /** Fraction of the tileset height at which the optimization begins to fade. */\n dynamicScreenSpaceErrorHeightFalloff: number;\n};\n\ntype TileBoundingVolumeHeader = {\n box?: number[];\n region?: number[];\n sphere?: number[];\n};\n\ntype TilesetHeightRange = {\n cameraHeight: number;\n minimumHeight: number;\n maximumHeight: number;\n cameraDirection: Vector3;\n upDirection: Vector3;\n};\n\nconst scratchPositionNormal = new Vector3();\nconst scratchCartographic = new Vector3();\nconst scratchCenter = new Vector3();\nconst scratchPosition = new Vector3();\nconst scratchDirection = new Vector3();\nconst scratchBoxXAxis = new Vector3();\nconst scratchBoxYAxis = new Vector3();\nconst scratchBoxZAxis = new Vector3();\nconst scratchBoxQuaternion = new Quaternion();\nconst unitZDirection = new Vector3(0, 0, 1);\n\n/**\n * Refreshes the root transform before calculating transform-dependent dynamic SSE density.\n *\n * Traversal normally updates transforms while visiting tile visibility, but density is calculated\n * immediately before traversal. Performing the root update at that earlier boundary keeps local\n * box and sphere height falloff synchronized with an animated tileset model matrix in the same\n * frame. {@link Tile3D._updateTransform} also recalculates world-space geometric error from its raw\n * source value, so repeated calls do not compound scale.\n *\n * @param root - Root tile whose computed transform feeds dynamic SSE height calculations.\n * @param modelMatrix - Current tileset-to-world transform for this frame.\n */\nexport function updateRootTransformForDynamicScreenSpaceError(\n root: Tile3D,\n modelMatrix: Matrix4\n): void {\n root._updateTransform(modelMatrix);\n}\n\n/**\n * Calculates the effective dynamic screen-space error density for one viewport and frame.\n *\n * Dynamic SSE is a perspective-only optimization for street-level views. It reduces refinement\n * for distant tiles near the horizon, where loading every geometric detail is expensive and has\n * limited visual benefit. Density fades to zero as the camera rises above the tileset or points\n * vertically. The returned value belongs to the supplied frame state; callers must not reuse it\n * for another viewport because camera height and direction are view dependent.\n *\n * @param root - Root tile whose transform and source bounding volume define the tileset space.\n * @param frameState - Current camera measurements in WGS84 and logical viewport space.\n * @param options - Dynamic SSE density and height-falloff controls.\n * @returns Effective fog density for this viewport, or zero when it cannot be calculated.\n */\nexport function calculateDynamicScreenSpaceErrorDensity(\n root: Tile3D,\n frameState: FrameState,\n options: DynamicScreenSpaceErrorOptions\n): number {\n if (\n !Number.isFinite(options.dynamicScreenSpaceErrorDensity) ||\n options.dynamicScreenSpaceErrorDensity <= 0\n ) {\n return 0;\n }\n\n const boundingVolumeHeader = getContentBoundingVolumeHeader(root);\n const heightRange = boundingVolumeHeader.region\n ? getRegionHeightRange(boundingVolumeHeader.region, frameState)\n : getCartesianHeightRange(root, boundingVolumeHeader, frameState);\n\n if (!heightRange) {\n return 0;\n }\n\n const heightFalloff = clamp(options.dynamicScreenSpaceErrorHeightFalloff, 0, 1);\n const heightClose =\n heightRange.minimumHeight +\n (heightRange.maximumHeight - heightRange.minimumHeight) * heightFalloff;\n const heightSpan = heightRange.maximumHeight - heightClose;\n const heightPercentage =\n heightSpan > 0\n ? clamp((heightRange.cameraHeight - heightClose) / heightSpan, 0, 1)\n : heightRange.cameraHeight >= heightRange.maximumHeight\n ? 1\n : 0;\n\n // A horizontal view has a dot product near zero and receives the strongest optimization.\n // A vertical view has a dot product near one and keeps the unmodified perspective SSE.\n const verticalAlignment = clamp(\n Math.abs(heightRange.cameraDirection.dot(heightRange.upDirection)),\n 0,\n 1\n );\n const horizonFactor = (1 - verticalAlignment) * (1 - heightPercentage);\n\n return options.dynamicScreenSpaceErrorDensity * horizonFactor;\n}\n\n/**\n * Calculates exponential fog strength for a camera distance and density.\n * @param distanceToCamera - Distance from the camera to the tile bounding volume in meters.\n * @param density - Effective dynamic SSE density in inverse meters.\n * @returns Unitless strength in the inclusive range from zero to one.\n */\nexport function getDynamicScreenSpaceErrorFog(distanceToCamera: number, density: number): number {\n const scalar = distanceToCamera * density;\n return 1 - Math.exp(-(scalar * scalar));\n}\n\n/**\n * Calculates the perspective SSE reduction for a tile.\n * @param distanceToCamera - Distance from the camera to the tile bounding volume in meters.\n * @param density - View-dependent fog density calculated for the current frame.\n * @param factor - Maximum reduction in logical/CSS pixels.\n * @returns Number of logical pixels to subtract from perspective SSE.\n */\nexport function getDynamicScreenSpaceError(\n distanceToCamera: number,\n density: number,\n factor: number\n): number {\n if (density <= 0 || factor <= 0 || !Number.isFinite(density) || !Number.isFinite(factor)) {\n return 0;\n }\n\n return getDynamicScreenSpaceErrorFog(distanceToCamera, density) * factor;\n}\n\n/**\n * Calculates 3D Tiles screen-space error (SSE) for the current projection.\n *\n * Perspective SSE projects the tile's world-space geometric error through the existing viewport\n * height and frustum denominator. Dynamic SSE may then reduce distant horizon refinement using\n * the density calculated specifically for this frame and viewport. Orthographic projection has\n * no perspective distance falloff, so its error is divided directly by the viewport's world-space\n * meters per logical pixel and is never adjusted by perspective dynamic SSE.\n *\n * @param tile - Tile containing the transform-scaled geometric error and camera distance.\n * @param frameState - Current camera and viewport measurements.\n * @param useParentLodMetric - Whether request prioritization should use the parent's error.\n * @param viewportHeightFraction - Fraction of viewport height represented by the priority pass.\n * @returns Estimated error in logical/CSS pixels.\n */\nexport function getTiles3DScreenSpaceError(\n tile: Tile3D,\n frameState: FrameState,\n useParentLodMetric: boolean,\n viewportHeightFraction = 1\n): number {\n const tileset = tile.tileset;\n const parentLodMetricValue = (tile.parent && tile.parent.lodMetricValue) || tile.lodMetricValue;\n const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;\n\n // Leaf tiles do not have any error so save the computation.\n if (lodMetricValue === 0) {\n return 0;\n }\n\n const {viewDistanceScale} = tileset.options;\n const lodScale = viewDistanceScale || 1;\n const heightFraction = Number.isFinite(viewportHeightFraction)\n ? Math.max(viewportHeightFraction, 0)\n : 1;\n const orthographicError = getOrthographicScreenSpaceError(\n lodMetricValue,\n frameState,\n lodScale,\n heightFraction\n );\n if (orthographicError !== null) {\n return orthographicError;\n }\n\n // Avoid divide by zero when viewer is inside the tile.\n const distanceToCamera = Math.max(tile._distanceToCamera, 1e-7);\n const {height, sseDenominator} = frameState;\n let screenSpaceError =\n (lodMetricValue * height * heightFraction * lodScale) / (distanceToCamera * sseDenominator);\n\n if (tileset.options.dynamicScreenSpaceError && !frameState.viewport.orthographic) {\n screenSpaceError -= getDynamicScreenSpaceError(\n distanceToCamera,\n frameState.dynamicScreenSpaceErrorDensity,\n tileset.options.dynamicScreenSpaceErrorFactor\n );\n }\n\n return screenSpaceError;\n}\n\n/**\n * Calculates orthographic SSE when the viewport provides a valid logical-pixel scale.\n *\n * deck.gl viewport dimensions and `metersPerPixel` use logical/CSS pixels. Applying the browser's\n * device pixel ratio again would therefore double-correct the result and select different LODs on\n * otherwise identical displays. If a structural third-party viewport does not expose a usable\n * scale, `null` tells the caller to retain the established perspective-compatible fallback.\n *\n * @param lodMetricValue - Transform-scaled geometric error in world-space meters.\n * @param frameState - Current frame state containing the viewport.\n * @param lodScale - Application refinement scale from `viewDistanceScale`.\n * @param viewportHeightFraction - Fraction of logical viewport height represented by the pass.\n * @returns SSE in logical pixels, or `null` when orthographic SSE cannot be calculated.\n */\nfunction getOrthographicScreenSpaceError(\n lodMetricValue: number,\n frameState: FrameState,\n lodScale: number,\n viewportHeightFraction: number\n): number | null {\n const viewport = frameState.viewport;\n if (!viewport?.orthographic) {\n return null;\n }\n\n const metersPerPixel = viewport.metersPerPixel;\n if (!Number.isFinite(metersPerPixel) || !metersPerPixel || metersPerPixel <= 0) {\n return null;\n }\n\n return (lodMetricValue * lodScale * viewportHeightFraction) / metersPerPixel;\n}\n\n/** Returns the content bounding volume header, falling back to the traversal volume. */\nfunction getContentBoundingVolumeHeader(root: Tile3D): TileBoundingVolumeHeader {\n return root.header.content?.boundingVolume || root.header.boundingVolume;\n}\n\n/** Calculates camera and tileset heights for a geodetic region bounding volume. */\nfunction getRegionHeightRange(region: number[], frameState: FrameState): TilesetHeightRange {\n const upDirection = scratchPositionNormal.copy(frameState.camera.position).normalize();\n const cameraDirection = scratchDirection.copy(frameState.camera.direction).normalize();\n\n return {\n cameraHeight: frameState.camera.cartographicPosition[2],\n minimumHeight: region[4],\n maximumHeight: region[5],\n cameraDirection,\n upDirection\n };\n}\n\n/**\n * Calculates camera and tileset heights for box and sphere volumes.\n *\n * The root transform is inverted so that both camera height and source volume dimensions use the\n * same coordinate system. Small coordinates are treated as local z-up. Earth-scale coordinates\n * are treated as WGS84 and use cartographic height, matching Cesium's conservative approximation.\n */\nfunction getCartesianHeightRange(\n root: Tile3D,\n boundingVolumeHeader: TileBoundingVolumeHeader,\n frameState: FrameState\n): TilesetHeightRange | null {\n const halfHeight = getBoundingVolumeCenterAndHalfHeight(boundingVolumeHeader, scratchCenter);\n if (halfHeight === null) {\n return null;\n }\n\n const localTransform = new Matrix4(root.computedTransform).invert();\n const ellipsoid = root.tileset.ellipsoid as Ellipsoid;\n const centerMagnitude = Math.hypot(scratchCenter[0], scratchCenter[1], scratchCenter[2]);\n\n if (centerMagnitude > ellipsoid.minimumRadius) {\n const centerCartographic = ellipsoid.cartesianToCartographic(\n scratchCenter,\n scratchCartographic\n );\n const upDirection = scratchPositionNormal.copy(frameState.camera.position).normalize();\n const cameraDirection = scratchDirection.copy(frameState.camera.direction).normalize();\n\n return {\n cameraHeight: frameState.camera.cartographicPosition[2],\n minimumHeight: 0,\n maximumHeight: centerCartographic[2] * 2,\n cameraDirection,\n upDirection\n };\n }\n\n localTransform.transformAsPoint(frameState.camera.position, scratchPosition);\n localTransform.transformAsVector(frameState.camera.direction, scratchDirection);\n scratchDirection.normalize();\n\n return {\n cameraHeight: scratchPosition[2],\n minimumHeight: scratchCenter[2] - halfHeight,\n maximumHeight: scratchCenter[2] + halfHeight,\n cameraDirection: scratchDirection,\n upDirection: unitZDirection\n };\n}\n\n/**\n * Copies the source volume center and returns its conservative z-up half-height.\n * @param boundingVolumeHeader - Root content or traversal volume from tileset JSON.\n * @param result - Scratch vector that receives the source-space center.\n * @returns Half-height in source-space meters, or `null` for an unsupported volume.\n */\nfunction getBoundingVolumeCenterAndHalfHeight(\n boundingVolumeHeader: TileBoundingVolumeHeader,\n result: Vector3\n): number | null {\n if (boundingVolumeHeader.box) {\n const box = boundingVolumeHeader.box;\n result.set(box[0], box[1], box[2]);\n return getBoxHalfHeight(box);\n }\n\n if (boundingVolumeHeader.sphere) {\n const sphere = boundingVolumeHeader.sphere;\n result.set(sphere[0], sphere[1], sphere[2]);\n return sphere[3];\n }\n\n return null;\n}\n\n/**\n * Returns the conservative source-z extent of an oriented box.\n *\n * A 12-component 3D Tiles box stores three half-axis vectors, so every vector can contribute to\n * vertical height after rotation. The alternate 10-component representation stores half sizes and\n * a quaternion; rotating its three scaled basis vectors produces the same sum of absolute z\n * projections. Using only the nominal z axis would underestimate tilted volumes and fade dynamic\n * SSE too early while the camera is still within the tileset's height range.\n *\n * @param box - Source-space oriented box in half-axis or half-size/quaternion form.\n * @returns Conservative source-z half-height in the box coordinate system's distance units.\n */\nfunction getBoxHalfHeight(box: number[]): number {\n if (box.length === 10) {\n scratchBoxQuaternion.fromArray(box, 6);\n scratchBoxXAxis.set(box[3], 0, 0).transformByQuaternion(scratchBoxQuaternion);\n scratchBoxYAxis.set(0, box[4], 0).transformByQuaternion(scratchBoxQuaternion);\n scratchBoxZAxis.set(0, 0, box[5]).transformByQuaternion(scratchBoxQuaternion);\n return (\n Math.abs(scratchBoxXAxis[2]) + Math.abs(scratchBoxYAxis[2]) + Math.abs(scratchBoxZAxis[2])\n );\n }\n\n return Math.abs(box[5]) + Math.abs(box[8]) + Math.abs(box[11]);\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT AND Apache-2.0\n// Copyright vis.gl contributors\n\n// This file contains behavior derived from the Cesium code base under Apache 2 license.\n\nimport {Vector3} from '@math.gl/core';\nimport {BoundingSphere, OrientedBoundingBox} from '@math.gl/culling';\nimport {TILE_REFINEMENT} from '../../constants';\n\nconst PREFERRED_SORTING_DIGITS = 10_000;\nconst FOVEATED_SORTING_SCALE = 10_000;\nconst PROGRESSIVE_RESOLUTION_PENALTY = 100_000_000;\n\nconst scratchBoundingSphere = new BoundingSphere();\nconst scratchCenterOffset = new Vector3();\nconst scratchClosestPointOnLine = new Vector3();\nconst scratchVectorToLine = new Vector3();\nconst scratchClosestPointOnSphere = new Vector3();\n\n/**\n * Interpolates the logical-pixel SSE relaxation used outside the foveated center cone.\n *\n * @param minimumValue - Relaxation at the edge of the center cone, in logical pixels.\n * @param maximumValue - Maximum relaxation at the edge of the perspective field of view, in\n * logical pixels.\n * @param interpolationAmount - Normalized distance from the cone edge toward the field-of-view\n * edge, clamped to `[0, 1]` by the caller.\n * @returns Interpolated SSE relaxation in logical pixels. Non-finite results are treated as zero.\n */\nexport type FoveatedInterpolationCallback = (\n minimumValue: number,\n maximumValue: number,\n interpolationAmount: number\n) => number;\n\n/** Camera measurements required to calculate a tile's foveated priority. */\nexport type FoveatedPriorityCamera = {\n /** Camera position in the same world-space coordinate system as the tile bounding volume. */\n position: number[];\n /** Normalized world-space camera direction. */\n direction: number[];\n};\n\n/** Inputs that determine whether a peripheral tile request may be deferred. */\nexport type FoveatedDeferralParameters = {\n /** Tile refinement mode. */\n refinement: TILE_REFINEMENT;\n /** Whether replacement traversal may skip hierarchy levels while retaining ancestors. */\n skipLevelOfDetail: boolean;\n /** Whether foveated prioritization is enabled. */\n foveatedScreenSpaceError: boolean;\n /** Fraction of the field of view that loads without foveated SSE relaxation. */\n foveatedConeSize: number;\n /** Minimum logical-pixel relaxation at the edge of the foveated cone. */\n minimumScreenSpaceErrorRelaxation: number;\n /** Interpolation function used to increase relaxation toward the viewport edge. */\n interpolationCallback: FoveatedInterpolationCallback;\n /** Tile distance from the camera view axis, represented as an angular factor. */\n foveatedFactor: number;\n /** Camera vertical field of view in radians. */\n verticalFieldOfView: number;\n /** Tile SSE in logical pixels. */\n screenSpaceError: number;\n /** Parent SSE in logical pixels, when a parent exists. */\n parentScreenSpaceError?: number;\n /** Current traversal SSE threshold in logical pixels. */\n maximumScreenSpaceError: number;\n /** Whether the tile contributes coarse progressive-resolution coverage. */\n priorityProgressiveResolution: boolean;\n};\n\n/** Inputs used to encode a stable, lexicographically ordered request priority. */\nexport type TileRequestPriorityParameters = {\n /** Whether the tile contributes coarse progressive-resolution coverage. */\n priorityProgressiveResolution: boolean;\n /** Tile distance from the camera view axis, represented as an angular factor. */\n foveatedFactor: number;\n /** Existing reverse-SSE ordering value; smaller values are more urgent. */\n reverseScreenSpaceError: number;\n /** Root SSE used to normalize reverse-SSE ordering without changing its order. */\n rootScreenSpaceError: number;\n};\n\n/**\n * Linearly interpolates between two values.\n *\n * @param minimumValue - Value returned when `interpolationAmount` is zero.\n * @param maximumValue - Value returned when `interpolationAmount` is one.\n * @param interpolationAmount - Normalized interpolation position.\n * @returns Linearly interpolated value.\n */\nexport function interpolateLinearly(\n minimumValue: number,\n maximumValue: number,\n interpolationAmount: number\n): number {\n return minimumValue + (maximumValue - minimumValue) * interpolationAmount;\n}\n\n/**\n * Calculates how far a tile lies from the camera's forward center ray.\n *\n * The tile's bounding sphere, rather than only its center, is used so large tiles that intersect\n * the view axis retain center priority. Clamping the nearest point to the forward ray prevents\n * volumes behind the camera from receiving the same priority as centered visible content. The\n * returned angular factor is zero on the view axis and increases toward the edge of a perspective\n * frustum, reaching one for volumes entirely behind the camera.\n *\n * @param boundingVolume - Tile volume used to find the point nearest the camera view axis.\n * @param camera - World-space camera position and normalized view direction.\n * @returns Unitless angular factor, where zero intersects the view axis and larger values are more\n * peripheral.\n */\nexport function calculateFoveatedFactor(\n boundingVolume: BoundingSphere | OrientedBoundingBox,\n camera: FoveatedPriorityCamera\n): number {\n const boundingSphere =\n boundingVolume instanceof BoundingSphere\n ? boundingVolume\n : boundingVolume.getBoundingSphere(scratchBoundingSphere);\n const {center, radius} = boundingSphere;\n\n scratchCenterOffset.copy(center).subtract(camera.position);\n const centerZDepth = Math.max(scratchCenterOffset.dot(camera.direction), 0);\n scratchClosestPointOnLine.copy(camera.direction).scale(centerZDepth).add(camera.position);\n scratchVectorToLine.copy(scratchClosestPointOnLine).subtract(center);\n\n const distanceToCenterLine = scratchVectorToLine.magnitude();\n if (distanceToCenterLine <= radius) {\n return 0;\n }\n\n scratchClosestPointOnSphere\n .copy(scratchVectorToLine)\n .normalize()\n .scale(radius)\n .add(center)\n .subtract(camera.position);\n if (scratchClosestPointOnSphere.magnitude() === 0) {\n return 0;\n }\n\n scratchClosestPointOnSphere.normalize();\n return Math.min(Math.max(1 - scratchClosestPointOnSphere.dot(camera.direction), 0), 1);\n}\n\n/**\n * Returns whether a tile supplies the coarse coverage targeted by progressive resolution.\n *\n * In addition to tiles whose reduced-height SSE exceeds the normal threshold, the first child\n * that crosses below the threshold is promoted. Promoting that SSE leaf prevents gaps between\n * coarse hierarchy levels in the initial coverage pass.\n *\n * @param screenSpaceError - Tile SSE calculated at the reduced logical viewport height.\n * @param parentScreenSpaceError - Parent SSE at the same reduced height, when available.\n * @param maximumScreenSpaceError - Normal traversal threshold in logical pixels.\n * @param progressiveResolutionHeightFraction - Reduced-height fraction; values outside `(0, 0.5]`\n * disable progressive priority.\n * @returns `true` when the tile belongs to the initial coarse-coverage priority band.\n */\nexport function isProgressiveResolutionPriority(\n screenSpaceError: number,\n parentScreenSpaceError: number | undefined,\n maximumScreenSpaceError: number,\n progressiveResolutionHeightFraction: number\n): boolean {\n if (\n !Number.isFinite(progressiveResolutionHeightFraction) ||\n progressiveResolutionHeightFraction <= 0 ||\n progressiveResolutionHeightFraction > 0.5\n ) {\n return false;\n }\n\n if (screenSpaceError > maximumScreenSpaceError) {\n return true;\n }\n\n return parentScreenSpaceError !== undefined && parentScreenSpaceError > maximumScreenSpaceError;\n}\n\n/**\n * Returns whether a peripheral request can wait briefly after camera motion.\n *\n * Traditional `REPLACE` traversal is never deferred because every required child must be ready\n * before its parent disappears. `ADD` traversal and skip-LOD replacement traversal can safely keep\n * already available ancestors while peripheral descendants wait.\n *\n * @param parameters - Refinement, projection, SSE, and foveation measurements for the tile.\n * @returns `true` when the request may wait during the camera-motion delay.\n */\nexport function isFoveatedRequestDeferred(parameters: FoveatedDeferralParameters): boolean {\n const coneSize = Number.isFinite(parameters.foveatedConeSize)\n ? Math.min(Math.max(parameters.foveatedConeSize, 0), 1)\n : 1;\n const replacementRefinement = parameters.refinement === TILE_REFINEMENT.REPLACE;\n if (\n (replacementRefinement && !parameters.skipLevelOfDetail) ||\n !parameters.foveatedScreenSpaceError ||\n coneSize >= 1 ||\n (replacementRefinement &&\n parameters.skipLevelOfDetail &&\n parameters.priorityProgressiveResolution)\n ) {\n return false;\n }\n\n const verticalFieldOfView =\n Number.isFinite(parameters.verticalFieldOfView) && parameters.verticalFieldOfView > 0\n ? parameters.verticalFieldOfView\n : Math.PI / 3;\n const maximumFoveatedFactor = 1 - Math.cos(verticalFieldOfView * 0.5);\n const coneFactor = coneSize * maximumFoveatedFactor;\n if (parameters.foveatedFactor <= coneFactor || maximumFoveatedFactor <= coneFactor) {\n return false;\n }\n\n const interpolationAmount = Math.min(\n Math.max((parameters.foveatedFactor - coneFactor) / (maximumFoveatedFactor - coneFactor), 0),\n 1\n );\n const interpolationCallback =\n typeof parameters.interpolationCallback === 'function'\n ? parameters.interpolationCallback\n : interpolateLinearly;\n const interpolatedRelaxation = interpolationCallback(\n parameters.minimumScreenSpaceErrorRelaxation,\n parameters.maximumScreenSpaceError,\n interpolationAmount\n );\n const screenSpaceErrorRelaxation = Number.isFinite(interpolatedRelaxation)\n ? Math.min(Math.max(interpolatedRelaxation, 0), parameters.maximumScreenSpaceError)\n : 0;\n const screenSpaceError =\n parameters.screenSpaceError === 0 && parameters.parentScreenSpaceError !== undefined\n ? parameters.parentScreenSpaceError * 0.5\n : parameters.screenSpaceError;\n\n return parameters.maximumScreenSpaceError - screenSpaceErrorRelaxation <= screenSpaceError;\n}\n\n/**\n * Returns whether an eligible foveated request is inside the current camera-motion delay.\n *\n * Eligibility describes geometry and refinement safety; this function adds time. Keeping the\n * active state separate ensures the scheduler removes the temporary hold as soon as the configured\n * delay expires, while invalid timing inputs safely disable the hold.\n *\n * @param deferralEligible - Whether refinement and foveation permit this request to wait.\n * @param timeSinceMovement - Seconds since the current viewport last changed pose.\n * @param foveatedTimeDelay - Maximum delay after motion, in seconds.\n * @returns `true` only while an eligible request remains inside a positive finite delay.\n */\nexport function isFoveatedRequestDelayActive(\n deferralEligible: boolean,\n timeSinceMovement: number,\n foveatedTimeDelay: number\n): boolean {\n return (\n deferralEligible &&\n Number.isFinite(timeSinceMovement) &&\n Number.isFinite(foveatedTimeDelay) &&\n foveatedTimeDelay > 0 &&\n timeSinceMovement < foveatedTimeDelay\n );\n}\n\n/**\n * Encodes request priority into independent decimal bands.\n *\n * Smaller values load first. Requests inside the moving-camera delay are kept out of this queue;\n * eligible requests are ordered by the progressive-coverage flag, distance from the view center,\n * and finally the established reverse-SSE order. Normalizing reverse SSE preserves its relative\n * ordering while preventing one metric from spilling into the next priority band.\n *\n * @param parameters - Independent request-priority measurements for a tile.\n * @returns Numeric priority for `RequestScheduler`; smaller values start first.\n */\nexport function calculateTileRequestPriority(parameters: TileRequestPriorityParameters): number {\n const normalizedReverseScreenSpaceError =\n parameters.rootScreenSpaceError > 0\n ? Math.min(\n Math.max(parameters.reverseScreenSpaceError / parameters.rootScreenSpaceError, 0),\n 1\n )\n : 0;\n const preferredSortingDigits = Math.floor(\n normalizedReverseScreenSpaceError * (PREFERRED_SORTING_DIGITS - 1)\n );\n const normalizedFoveatedFactor = Number.isFinite(parameters.foveatedFactor)\n ? Math.min(Math.max(parameters.foveatedFactor, 0), 1)\n : 0;\n const foveatedSortingDigits =\n Math.floor(normalizedFoveatedFactor * (PREFERRED_SORTING_DIGITS - 1)) * FOVEATED_SORTING_SCALE;\n const progressiveResolutionDigits = parameters.priorityProgressiveResolution\n ? 0\n : PROGRESSIVE_RESOLUTION_PENALTY;\n return progressiveResolutionDigits + foveatedSortingDigits + preferredSortingDigits;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type TileContentState =\n | 'unloaded' // Has never been requested\n | 'loading' // Is waiting on a pending request\n | 'processing' // Request received. Contents are being processed for rendering. Depending on the content, it might make its own requests for external data.\n | 'ready' // Ready to render.\n | 'expired' // Is expired and will be unloaded once new content is loaded.\n | 'failed'; // Request failed.\n\nexport const TILE_CONTENT_STATE = {\n UNLOADED: 0, // Has never been requested\n LOADING: 1, // Is waiting on a pending request\n PROCESSING: 2, // Request received. Contents are being processed for rendering. Depending on the content, it might make its own requests for external data.\n READY: 3, // Ready to render.\n EXPIRED: 4, // Is expired and will be unloaded once new content is loaded.\n FAILED: 5 // Request failed.\n};\n\nexport type TileRefinement = 'add' | 'replace';\n\nexport enum TILE_REFINEMENT {\n ADD = 1, // Render tile and, if screen space error exceeded, also refine to its children.\n REPLACE = 2 // Render tile or, if screen space error exceeded, refine to its descendants instead.\n}\n\nexport type TileType = 'empty' | 'scenegraph' | 'pointcloud' | 'mesh';\n\nexport enum TILE_TYPE {\n EMPTY = 'empty',\n SCENEGRAPH = 'scenegraph',\n POINTCLOUD = 'pointcloud',\n MESH = 'mesh'\n}\n\nexport type TilesetType = 'I3S' | 'TILES3D';\n\nexport enum TILESET_TYPE {\n I3S = 'I3S',\n TILES3D = 'TILES3D'\n}\n\nexport type LODMetricType = 'geometricError' | 'maxScreenThreshold';\n\nexport enum LOD_METRIC_TYPE {\n GEOMETRIC_ERROR = 'geometricError',\n MAX_SCREEN_THRESHOLD = 'maxScreenThreshold'\n}\n\n// Cesium 3D Tiles Specific\nexport type Tile3DOptimizationHint = 'NOT_COMPUTED' | 'USE_OPTIMIZATION' | 'SKIP_OPTIMIZATION';\n\nexport const TILE3D_OPTIMIZATION_HINT = {\n NOT_COMPUTED: -1,\n USE_OPTIMIZATION: 1,\n SKIP_OPTIMIZATION: 0\n};\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n createSpatialReference,\n inferCRSRepresentation,\n type ReadonlyCRSDefinition,\n type SpatialReference,\n type SpatialReferenceAlternative,\n type SpatialReferenceCoordinateFrame,\n type SpatialReferenceProvenance,\n type SpatialReferenceRepresentation,\n type SpatialReferenceState\n} from '@math.gl/crs';\nimport type {Geoid} from '@math.gl/geoid';\nimport {getSpatialCoordinateFrame} from './get-spatial-coordinate-frame';\n\n/** How height values in a 3D dataset relate to the earth. */\nexport type TilesetHeightReference = 'native' | 'ellipsoidal' | 'orthometric' | 'unknown';\n\n/** Height reference that an application may request for transformed output. */\nexport type TilesetTargetHeightReference = 'native' | 'ellipsoidal' | 'orthometric';\n\n/** I3S placement rule applied after source-height interpretation. */\nexport type TilesetElevationMode =\n | 'absoluteHeight'\n | 'onTheGround'\n | 'relativeToGround'\n | 'relativeToScene';\n\n/** One WGS84 longitude/latitude location requested from an elevation provider. */\nexport type TilesetElevationSample = readonly [longitude: number, latitude: number];\n\n/** WGS84 geographic footprint passed to an elevation provider. */\nexport type TilesetElevationBounds = {\n /** Western longitude in degrees. Greater than `east` when crossing the antimeridian. */\n readonly west: number;\n /** Southern latitude in degrees. */\n readonly south: number;\n /** Eastern longitude in degrees. Less than `west` when crossing the antimeridian. */\n readonly east: number;\n /** Northern latitude in degrees. */\n readonly north: number;\n};\n\n/** Conservative elevation extrema over one geographic footprint. */\nexport type TilesetElevationRange = {\n /** Minimum elevation anywhere inside the footprint. */\n readonly minimum: number;\n /** Maximum elevation anywhere inside the footprint. */\n readonly maximum: number;\n};\n\n/**\n * Application-owned source of terrain or scene-surface heights.\n *\n * Providers receive WGS84 longitude/latitude locations and may batch asynchronous requests. They\n * never need to transform horizontal coordinates. Returned heights default to meters in the\n * layer's source height reference unless `unit` or `heightReference` says otherwise.\n */\nexport type TilesetElevationProvider = {\n /** Height reference used by sampled values. Omit to use the layer's source height reference. */\n readonly heightReference?: Exclude<TilesetHeightReference, 'native' | 'unknown'>;\n /** Linear unit used by sampled values. Defaults to `meter`. */\n readonly unit?: string;\n /**\n * Samples one height for every supplied location, preserving input order.\n * @param positions - WGS84 longitude/latitude locations.\n * @returns Finite heights with the same length and order as `positions`.\n */\n sampleElevations(\n positions: readonly TilesetElevationSample[]\n ): readonly number[] | Promise<readonly number[]>;\n /**\n * Returns conservative elevation extrema over an entire geographic footprint.\n *\n * Bounds preparation requires this operation because point samples cannot detect an interior\n * peak or depression and therefore cannot produce a culling-safe traversal volume.\n *\n * @param bounds - WGS84 geographic footprint in degrees.\n * @returns Minimum and maximum elevations in this provider's declared unit and height reference.\n */\n getElevationRange(\n bounds: TilesetElevationBounds\n ): TilesetElevationRange | Promise<TilesetElevationRange>;\n};\n\n/** Coordinate representation requested from a 3D tileset. */\nexport type TilesetOutputCoordinates = 'auto' | 'ecef' | 'local-enu' | 'target-crs';\n\n/** Broad coordinate frame used by a 3D dataset. */\nexport type TilesetCoordinateFrame = SpatialReferenceCoordinateFrame;\n\n/** Origin of a normalized spatial-reference value. */\nexport type TilesetSpatialReferenceProvenance = SpatialReferenceProvenance;\n\n/**\n * Simple application-facing spatial options shared by 3D Tiles and I3S.\n *\n * Source CRS details are normally discovered from dataset metadata. The source overrides are\n * expert recovery controls for incomplete or non-standard datasets.\n */\nexport type TilesetSpatialOptions = {\n /** CRS of transformed output coordinates. Omit to retain the format's natural world frame. */\n targetCrs?: ReadonlyCRSDefinition;\n /** Height reference of transformed output coordinates. Defaults to `native`. */\n targetHeightReference?: TilesetTargetHeightReference;\n /** Output coordinate representation. Defaults to `auto`. */\n outputCoordinates?: TilesetOutputCoordinates;\n /** Expert override used when source metadata is absent or incorrect. */\n sourceCrs?: ReadonlyCRSDefinition;\n /** Expert override for a dynamic coordinate reference epoch. */\n coordinateEpoch?: number;\n /** Registered geoid model name or an already parsed geoid model. */\n geoidModel?: string | Geoid;\n /** Terrain heights used by I3S `onTheGround` and `relativeToGround` placement. */\n terrainElevationProvider?: TilesetElevationProvider;\n /** Scene-surface heights used by I3S `relativeToScene` placement. */\n sceneElevationProvider?: TilesetElevationProvider;\n};\n\n/**\n * Normalized, readonly spatial metadata discovered for a 3D tileset.\n *\n * This is diagnostic output. Applications normally do not construct it.\n */\nexport type TilesetSpatialReference = SpatialReference & {\n /** Source horizontal or compound CRS, when it can be identified. */\n readonly sourceCrs?: ReadonlyCRSDefinition;\n /** Source vertical CRS, when independently identified. */\n readonly verticalCrs?: ReadonlyCRSDefinition;\n /** Number of meters represented by one source Z unit. */\n readonly verticalUnitScale: number;\n /** Coordinate epoch attached to the source coordinates. */\n readonly coordinateEpoch?: number;\n /** Source height interpretation. */\n readonly heightReference: TilesetHeightReference;\n /** I3S placement rule, when the source layer declares one. */\n readonly elevationMode?: TilesetElevationMode;\n /** Declared I3S elevation offset before unit normalization. */\n readonly elevationOffset?: number;\n /** Unit of the I3S elevation offset. Defaults to `meter` when a mode is declared. */\n readonly elevationUnit?: string;\n /** Number of meters represented by one elevation-offset unit. */\n readonly elevationUnitScale: number;\n /** Broad frame in which source coordinates are encoded. */\n readonly coordinateFrame: TilesetCoordinateFrame;\n /** Coordinate component order used by the format wire representation. */\n readonly axisOrder: 'xy' | 'yx' | 'xyz' | 'unknown';\n /** How the source CRS was established. */\n readonly provenance: TilesetSpatialReferenceProvenance;\n /** Target CRS selected by application options, if any. */\n readonly targetCrs?: ReadonlyCRSDefinition;\n /** Target height interpretation selected by application options. */\n readonly targetHeightReference: TilesetTargetHeightReference;\n /** Output representation selected by application options. */\n readonly outputCoordinates: TilesetOutputCoordinates;\n /** Whether coordinates are native, ready to transform, transformed, or unresolved. */\n readonly status: 'native' | 'transformable' | 'transformed' | 'unresolved';\n /** Non-fatal qualifications retained for diagnostics and user interfaces. */\n readonly warnings: readonly string[];\n};\n\n/** Input used by format adapters to create normalized spatial metadata. */\nexport type CreateTilesetSpatialReferenceOptions = {\n /** Discovered source CRS. */\n sourceCrs?: ReadonlyCRSDefinition;\n /** Whether the source CRS was explicit, defaulted, unknown, or absent. */\n sourceCrsState?: SpatialReferenceState;\n /** Serialization or naming form used by the source CRS. */\n sourceCrsRepresentation?: SpatialReferenceRepresentation;\n /** Additional source CRS representations retained by the format. */\n sourceCrsAlternatives?: readonly SpatialReferenceAlternative[];\n /** Discovered vertical CRS. */\n verticalCrs?: ReadonlyCRSDefinition;\n /** Per-component source units, aligned with the stored coordinate order. */\n units?: readonly string[];\n /** Number of meters represented by one discovered source Z unit. */\n verticalUnitScale?: number;\n /** Discovered coordinate epoch. */\n coordinateEpoch?: number;\n /** Discovered height interpretation. */\n heightReference?: TilesetHeightReference;\n /** Format-specific elevation placement rule. */\n elevationMode?: TilesetElevationMode;\n /** Format-specific elevation offset before unit normalization. */\n elevationOffset?: number;\n /** Unit of the format-specific elevation offset. */\n elevationUnit?: string;\n /** Number of meters represented by one elevation-offset unit. */\n elevationUnitScale?: number;\n /** Discovered broad coordinate frame. */\n coordinateFrame?: TilesetCoordinateFrame;\n /** Format wire-axis order. */\n axisOrder?: 'xy' | 'yx' | 'xyz' | 'unknown';\n /** Metadata provenance. */\n provenance?: TilesetSpatialReferenceProvenance;\n /** Non-fatal discovery qualifications. */\n warnings?: readonly string[];\n};\n\n/**\n * Combines format discovery with the intentionally small application option surface.\n *\n * @param discovered - Values derived from dataset metadata and format defaults.\n * @param options - Application target options and expert recovery overrides.\n * @returns Normalized immutable spatial metadata.\n */\nexport function createTilesetSpatialReference(\n discovered: CreateTilesetSpatialReferenceOptions,\n options: TilesetSpatialOptions = {}\n): TilesetSpatialReference {\n const hasSourceCrsOverride = options.sourceCrs !== undefined;\n const sourceCrs = options.sourceCrs || discovered.sourceCrs;\n const outputCoordinates = options.outputCoordinates || 'auto';\n const targetCrs = options.targetCrs || (outputCoordinates === 'ecef' ? 'EPSG:4978' : undefined);\n const targetHeightReference = options.targetHeightReference || 'native';\n const verticalUnitScale = discovered.verticalUnitScale ?? 1;\n const elevationUnitScale = discovered.elevationUnitScale ?? 1;\n const elevationOffset = discovered.elevationOffset || 0;\n const requiresSurface =\n discovered.elevationMode === 'onTheGround' ||\n discovered.elevationMode === 'relativeToGround' ||\n discovered.elevationMode === 'relativeToScene';\n const hasElevationProvider =\n discovered.elevationMode === 'relativeToScene'\n ? Boolean(options.sceneElevationProvider)\n : !requiresSurface || Boolean(options.terrainElevationProvider);\n const hasFormatVerticalOperation =\n verticalUnitScale !== 1 ||\n elevationUnitScale !== 1 ||\n (discovered.elevationMode !== undefined &&\n (requiresSurface ||\n (discovered.elevationMode === 'absoluteHeight' && elevationOffset !== 0)));\n const needsHeightTransform =\n targetHeightReference !== 'native' && targetHeightReference !== discovered.heightReference;\n const hasRequestedTransform =\n Boolean(targetCrs) ||\n targetHeightReference !== 'native' ||\n outputCoordinates !== 'auto' ||\n hasFormatVerticalOperation;\n const hasRequiredTarget = outputCoordinates !== 'target-crs' || Boolean(targetCrs);\n const hasHeightMetadata =\n !needsHeightTransform || (discovered.heightReference || 'unknown') !== 'unknown';\n const hasVerticalUnits =\n Number.isFinite(verticalUnitScale) &&\n verticalUnitScale > 0 &&\n Number.isFinite(elevationUnitScale) &&\n elevationUnitScale > 0;\n const canTransform =\n Boolean(sourceCrs) &&\n hasRequestedTransform &&\n hasRequiredTarget &&\n hasHeightMetadata &&\n hasVerticalUnits &&\n hasElevationProvider &&\n outputCoordinates !== 'local-enu';\n\n const provenance = hasSourceCrsOverride ? 'caller-override' : discovered.provenance || 'unknown';\n const coordinateFrame =\n hasSourceCrsOverride && sourceCrs\n ? getSpatialCoordinateFrame(sourceCrs)\n : discovered.coordinateFrame;\n const sourceCrsState = hasSourceCrsOverride\n ? 'explicit'\n : discovered.sourceCrsState ||\n (sourceCrs ? (provenance === 'format-default' ? 'default' : 'explicit') : 'absent');\n const spatialReference = createSpatialReference({\n crs: sourceCrs\n ? {\n state: sourceCrsState === 'default' ? 'default' : 'explicit',\n definition: sourceCrs,\n representation:\n (!hasSourceCrsOverride && discovered.sourceCrsRepresentation) ||\n inferCRSRepresentation(sourceCrs),\n provenance,\n alternatives: hasSourceCrsOverride ? undefined : discovered.sourceCrsAlternatives\n }\n : {\n state: sourceCrsState === 'unknown' ? 'unknown' : 'absent',\n provenance\n },\n vertical: discovered.verticalCrs\n ? {\n state: 'explicit',\n definition: discovered.verticalCrs,\n representation: inferCRSRepresentation(discovered.verticalCrs),\n provenance: discovered.provenance || 'metadata'\n }\n : undefined,\n coordinateEpoch: options.coordinateEpoch ?? discovered.coordinateEpoch,\n coordinateFrame,\n coordinateOrder: getCoordinateOrder(discovered.axisOrder),\n units: hasSourceCrsOverride ? undefined : discovered.units\n });\n const normalizedSourceCrs = getKnownCRSDefinition(spatialReference.crs);\n const normalizedVerticalCrs = spatialReference.vertical\n ? getKnownCRSDefinition(spatialReference.vertical)\n : undefined;\n const normalizedTargetCrs = targetCrs ? cloneReadonlyCRSDefinition(targetCrs) : undefined;\n\n return Object.freeze({\n ...spatialReference,\n sourceCrs: normalizedSourceCrs,\n verticalCrs: normalizedVerticalCrs,\n verticalUnitScale,\n coordinateEpoch: options.coordinateEpoch ?? discovered.coordinateEpoch,\n heightReference: discovered.heightReference || 'unknown',\n elevationMode: discovered.elevationMode,\n elevationOffset: discovered.elevationOffset,\n elevationUnit: discovered.elevationUnit,\n elevationUnitScale,\n coordinateFrame: coordinateFrame || 'unknown',\n axisOrder: discovered.axisOrder || 'unknown',\n provenance,\n targetCrs: normalizedTargetCrs,\n targetHeightReference,\n outputCoordinates,\n status: hasRequestedTransform ? (canTransform ? 'transformable' : 'unresolved') : 'native',\n warnings: Object.freeze([...(discovered.warnings || [])])\n });\n}\n\n/**\n * Applies application target and recovery options to format-discovered spatial metadata.\n *\n * @param discovered - Readonly metadata returned by a format adapter.\n * @param options - Application target options and expert recovery overrides.\n * @returns A new normalized immutable descriptor.\n */\nexport function applyTilesetSpatialOptions(\n discovered: TilesetSpatialReference | undefined,\n options: TilesetSpatialOptions = {}\n): TilesetSpatialReference {\n return createTilesetSpatialReference(\n {\n sourceCrs: discovered?.sourceCrs,\n sourceCrsState: discovered?.crs.state,\n sourceCrsRepresentation:\n discovered?.crs.state === 'explicit' || discovered?.crs.state === 'default'\n ? discovered.crs.representation\n : undefined,\n sourceCrsAlternatives:\n discovered?.crs.state === 'explicit' || discovered?.crs.state === 'default'\n ? discovered.crs.alternatives\n : undefined,\n verticalCrs: discovered?.verticalCrs,\n units: discovered?.units,\n verticalUnitScale: discovered?.verticalUnitScale,\n coordinateEpoch: discovered?.coordinateEpoch,\n heightReference: discovered?.heightReference,\n elevationMode: discovered?.elevationMode,\n elevationOffset: discovered?.elevationOffset,\n elevationUnit: discovered?.elevationUnit,\n elevationUnitScale: discovered?.elevationUnitScale,\n coordinateFrame: discovered?.coordinateFrame,\n axisOrder: discovered?.axisOrder,\n provenance: discovered?.provenance,\n warnings: discovered?.warnings\n },\n options\n );\n}\n\n/** Return a known definition from a canonical CRS reference. */\nfunction getKnownCRSDefinition(\n reference: SpatialReference['crs']\n): ReadonlyCRSDefinition | undefined {\n return reference.state === 'explicit' || reference.state === 'default'\n ? reference.definition\n : undefined;\n}\n\n/** Clone and deeply freeze a target CRS through the canonical math.gl constructor. */\nfunction cloneReadonlyCRSDefinition(definition: ReadonlyCRSDefinition): ReadonlyCRSDefinition {\n const spatialReference = createSpatialReference({\n crs: {\n state: 'explicit',\n definition,\n representation: inferCRSRepresentation(definition),\n provenance: 'caller-override'\n }\n });\n const clonedDefinition = getKnownCRSDefinition(spatialReference.crs);\n if (!clonedDefinition) {\n throw new Error('Failed to normalize a known target CRS definition');\n }\n return clonedDefinition;\n}\n\n/** Convert the legacy tileset axis label to the common stored-coordinate order. */\nfunction getCoordinateOrder(\n axisOrder: CreateTilesetSpatialReferenceOptions['axisOrder']\n): readonly string[] {\n switch (axisOrder) {\n case 'xy':\n return ['x', 'y'];\n case 'yx':\n return ['y', 'x'];\n case 'xyz':\n return ['x', 'y', 'z'];\n default:\n return [];\n }\n}\n\n/**\n * Marks a normalized descriptor after every returned coordinate and bound has entered its target\n * frame.\n *\n * @param spatialReference - Transformable spatial descriptor.\n * @returns An immutable descriptor with `status: 'transformed'`.\n */\nexport function markTilesetSpatialReferenceTransformed(\n spatialReference: TilesetSpatialReference\n): TilesetSpatialReference {\n if (spatialReference.status !== 'transformable' && spatialReference.status !== 'transformed') {\n throw new Error('Only a transformable spatial reference can be marked as transformed');\n }\n return Object.freeze({...spatialReference, status: 'transformed'});\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n inferCRSRepresentation,\n parsePROJString,\n parseWKTCRS,\n type ReadonlyCRSDefinition,\n type SpatialReferenceCoordinateFrame,\n type WKTCRSNode\n} from '@math.gl/crs';\nimport {\n normalizeCrsIdentifier,\n WGS84_GEOCENTRIC_CRS,\n WGS84_GEOGRAPHIC_CRS\n} from './normalize-crs-identifier';\n\n/**\n * Classify a CRS definition into the broad coordinate frame used by 3D format adapters.\n *\n * @param definition - CRS definition to classify.\n * @returns The broad geographic, geocentric, projected, local, or unknown frame.\n */\nexport function getSpatialCoordinateFrame(\n definition: ReadonlyCRSDefinition\n): SpatialReferenceCoordinateFrame {\n if (typeof definition === 'string') {\n const representation = inferCRSRepresentation(definition);\n if (representation === 'wkt') {\n return getWktCoordinateFrame(definition);\n }\n if (representation === 'proj-string') {\n return getProjStringCoordinateFrame(definition);\n }\n return getKnownCrsIdentifierCoordinateFrame(definition) || 'projected';\n }\n\n const projJsonDefinition = definition as {\n type?: string;\n source_crs?: ReadonlyCRSDefinition;\n components?: readonly ReadonlyCRSDefinition[];\n coordinate_system?: {subtype?: string};\n };\n if (projJsonDefinition.type === 'BoundCRS' && projJsonDefinition.source_crs) {\n return getSpatialCoordinateFrame(projJsonDefinition.source_crs);\n }\n if (projJsonDefinition.type === 'CompoundCRS' && projJsonDefinition.components?.[0]) {\n return getSpatialCoordinateFrame(projJsonDefinition.components[0]);\n }\n if (String(projJsonDefinition.type).includes('Projected')) {\n return 'projected';\n }\n if (String(projJsonDefinition.type).includes('Geographic')) {\n return 'geographic';\n }\n if (String(projJsonDefinition.type).includes('Geodetic')) {\n return projJsonDefinition.coordinate_system?.subtype === 'Cartesian'\n ? 'geocentric'\n : 'geographic';\n }\n return 'unknown';\n}\n\n/**\n * Classifies authority identifiers for which the tiles runtime has explicit frame knowledge.\n *\n * Unlike {@link getSpatialCoordinateFrame}, this function does not assume that an unrecognized\n * authority identifier is projected. Draft formats use this strict result to avoid inventing\n * semantics for unknown authorities or registry codes.\n *\n * @param definition - Serialized CRS identifier.\n * @returns A known frame, or `undefined` when registry semantics are unavailable.\n */\nexport function getKnownCrsIdentifierCoordinateFrame(\n definition: ReadonlyCRSDefinition | undefined\n): SpatialReferenceCoordinateFrame | undefined {\n if (typeof definition !== 'string') {\n return undefined;\n }\n const normalized = normalizeCrsIdentifier(definition);\n if (normalized === WGS84_GEOCENTRIC_CRS) {\n return 'geocentric';\n }\n if (normalized === WGS84_GEOGRAPHIC_CRS || normalized === 'OGC:CRS84') {\n return 'geographic';\n }\n const epsgMatch = /^EPSG:(\\d+)$/.exec(normalized);\n if (!epsgMatch) {\n return undefined;\n }\n const identifier = Number(epsgMatch[1]);\n if (identifier === 7789) {\n return 'geocentric';\n }\n if (identifier === 4490 || identifier === 4979) {\n return 'geographic';\n }\n if (\n identifier === 3857 ||\n (identifier >= 32601 && identifier <= 32660) ||\n (identifier >= 32701 && identifier <= 32760)\n ) {\n return 'projected';\n }\n return undefined;\n}\n\n/** Classifies a WKT definition using the syntax tree parsed by `@math.gl/crs`. */\nfunction getWktCoordinateFrame(definition: string): SpatialReferenceCoordinateFrame {\n let root: WKTCRSNode;\n try {\n root = parseWKTCRS(definition).root;\n } catch {\n return 'unknown';\n }\n switch (root.keyword.toUpperCase()) {\n case 'GEOCCS':\n return 'geocentric';\n case 'GEOGCS':\n case 'GEOGCRS':\n case 'GEOGRAPHICCRS':\n case 'GEOGRAPHIC2DCRS':\n case 'GEOGRAPHIC3DCRS':\n return 'geographic';\n case 'PROJCS':\n case 'PROJCRS':\n case 'PROJECTEDCRS':\n return 'projected';\n case 'GEODCRS':\n case 'GEODETICCRS': {\n const coordinateSystem = root.values.find(\n (value): value is WKTCRSNode =>\n value.type === 'node' && value.keyword.toUpperCase() === 'CS'\n );\n const subtype = coordinateSystem?.values[0];\n if (subtype?.type !== 'enumeration' && subtype?.type !== 'string') {\n return 'unknown';\n }\n return subtype.value.toUpperCase() === 'CARTESIAN'\n ? 'geocentric'\n : subtype.value.toUpperCase() === 'ELLIPSOIDAL'\n ? 'geographic'\n : 'unknown';\n }\n default:\n return 'unknown';\n }\n}\n\n/** Classifies a PROJ string using the syntax tree parsed by `@math.gl/crs`. */\nfunction getProjStringCoordinateFrame(definition: string): SpatialReferenceCoordinateFrame {\n try {\n const projection = parsePROJString(definition).parameters.find(\n parameter => parameter.name.toLowerCase() === 'proj'\n )?.value;\n switch (projection?.toLowerCase()) {\n case 'longlat':\n case 'latlong':\n return 'geographic';\n case 'geocent':\n return 'geocentric';\n default:\n return projection ? 'projected' : 'unknown';\n }\n } catch {\n return 'unknown';\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Compact identifier for conventional WGS84 longitude/latitude coordinates. */\nexport const WGS84_GEOGRAPHIC_CRS = 'EPSG:4326';\n\n/** Compact identifier for WGS84 Earth-centered, Earth-fixed coordinates. */\nexport const WGS84_GEOCENTRIC_CRS = 'EPSG:4978';\n\n/**\n * Normalizes common OGC URL and URN CRS spellings to compact authority identifiers.\n *\n * This intentionally performs syntax normalization only. Authority lookup and semantic\n * equivalence remain outside the scope of `@math.gl/crs` and the tiles runtime.\n *\n * @param identifier - Serialized CRS identifier.\n * @returns Uppercase compact identifier when an OGC spelling is recognized.\n */\nexport function normalizeCrsIdentifier(identifier: string): string {\n const normalizedIdentifier = identifier.trim().toUpperCase();\n const ogcMatch = normalizedIdentifier.match(\n /(?:\\/DEF\\/CRS\\/|URN:OGC:DEF:CRS:)([A-Z0-9_-]+)(?:\\/|::)(?:[^/:]*[/:])?([A-Z0-9_.-]+)$/\n );\n return ogcMatch ? `${ogcMatch[1]}:${ogcMatch[2]}` : normalizedIdentifier;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CoreAPI, Loader, LoaderOptions} from '@loaders.gl/loader-utils';\nimport type {Vector3} from '@math.gl/core';\nimport type {TilesetTraverser, TilesetTraverserProps} from './tileset-traverser';\nimport type {Tile3D} from './tile-3d';\nimport type {Tileset3D} from './tileset-3d';\nimport type {FrameState} from '../helpers/frame-state';\nimport type {TILESET_TYPE} from '../../constants';\nimport type {TilesetSpatialReference} from '../../spatial/spatial-types';\nimport type {Tile3DContent} from './tile-3d-contracts';\n\n/**\n * Parsed top-level tileset payload consumed by {@link Tileset3D} or a {@link Tileset3DSource}.\n */\nexport type TilesetJSON = any;\n\n/**\n * Resource-loading strategy used by source implementations to fetch and parse root metadata\n * and tile resources.\n */\nexport type TilesetSourceResolver = {\n /**\n * Loads and parses the root metadata resource for a source.\n */\n loadRoot<DataT>(url: string, loader: Loader<DataT>, loadOptions: LoaderOptions): Promise<DataT>;\n\n /**\n * Loads and parses an arbitrary source-relative resource.\n */\n loadResource<DataT>(\n url: string,\n loader: Loader<DataT>,\n loadOptions: LoaderOptions\n ): Promise<DataT>;\n};\n\n/**\n * URL-based source input used when a source is responsible for fetching root metadata.\n */\nexport type TilesetSourceRequest = {\n /** Absolute root metadata URL. */\n url: string;\n /** Loader used to fetch and parse the root metadata. */\n loader: Loader;\n /** Optional base path override for relative resources. */\n basePath?: string;\n /** Optional resource-loading strategy used for archive-backed datasets. */\n resolver?: TilesetSourceResolver;\n /** Optional core API implementation used for nested source loading. */\n coreApi?: CoreAPI;\n};\n\n/**\n * Constructor input accepted by explicit source implementations.\n *\n * Request descriptors are the public path. Preloaded metadata remains useful for tests and\n * internal call sites that already own parsed root metadata.\n */\nexport type TilesetSourceInput = TilesetJSON | TilesetSourceRequest;\n\n/**\n * Result of a source-managed tile content request.\n */\nexport type TileContentLoadResult = {\n /** Whether the tile content request produced usable content. */\n loaded: boolean;\n /** All payloads loaded for a tile, in source order. */\n contents?: any[];\n /** Optional normalized renderer-neutral descriptors for each content entry. */\n contentEntries?: Tile3DContent[];\n /** Nested tileset metadata to install below the loaded tile, if any. */\n nestedTileset?: TilesetJSON;\n /** Nested tilesets found among multiple content payloads. */\n nestedTilesets?: TilesetJSON[];\n};\n\n/** Result of a source-managed lazy child-header request. */\nexport type TileChildrenLoadResult = {\n /** Whether a subtree resource was loaded and installed. */\n loaded: boolean;\n /** Number of available tiles described by the subtree, including its existing root placeholder. */\n tileCount: number;\n /** Number of lazy child-subtree references installed at the new boundary. */\n childSubtreeCount: number;\n};\n\n/**\n * Flags describing compression and texture formats observed while streaming tile content.\n */\nexport type TilesetContentFormats = {\n draco: boolean;\n meshopt: boolean;\n dds: boolean;\n ktx2: boolean;\n};\n\n/**\n * Optional view-state metadata exposed by a {@link Tileset3DSource} after initialization.\n */\nexport type TilesetSourceViewState = {\n cartographicCenter?: Vector3 | null;\n cartesianCenter?: Vector3 | null;\n zoom?: number;\n boundingVolume?: any;\n description?: string;\n properties?: any;\n extras?: any;\n credits?: any;\n asset?: Record<string, any>;\n};\n\n/**\n * Normalized source metadata consumed by {@link Tileset3D}.\n */\nexport type TilesetSourceMetadata = {\n /** Format discriminator. */\n type: TILESET_TYPE;\n /** Primary format loader used for metadata and default content requests. */\n loader: Loader;\n /** Absolute root metadata URL. */\n url: string;\n /** Base path used for relative resource resolution. */\n basePath: string;\n /** Parsed and normalized source payload. */\n tileset: TilesetJSON;\n /** Root lod metric type used as fallback by runtime tiles. */\n lodMetricType: string;\n /** Root lod metric value used as fallback by runtime tiles. */\n lodMetricValue: number;\n /** Root refinement mode used as fallback by runtime tiles. */\n refine: string;\n /** Format-discovered coordinate reference system metadata. */\n spatialReference?: TilesetSpatialReference;\n};\n\n/**\n * Format-specific adapter used by {@link Tileset3D} for initialization, loading, and metadata access.\n */\nexport interface Tileset3DSource {\n /** Tileset format discriminator. */\n readonly type: TILESET_TYPE;\n /** Primary format loader used for metadata and default content requests. */\n readonly loader: Loader;\n /** Absolute URL of the root tileset resource. */\n readonly url: string;\n /** Base directory used for relative resource resolution. */\n readonly basePath: string;\n /** Source-specific root tileset payload, when available. */\n readonly tileset?: TilesetJSON | null;\n /** Loader options forwarded to metadata and content requests. */\n readonly loadOptions: LoaderOptions;\n /** Core API used for source-managed loads, when injected by the caller. */\n coreApi?: CoreAPI;\n /** Accumulated content-format flags for the tileset. */\n readonly contentFormats: TilesetContentFormats;\n /** Format-specific asset metadata, if any. */\n asset?: Record<string, any>;\n /** Per-feature property schema, if any. */\n properties?: any;\n /** Application-specific root metadata, if any. */\n extras?: any;\n /** Attribution and credit metadata, if any. */\n credits?: any;\n\n /** Normalized source metadata after initialization. */\n metadata?: TilesetSourceMetadata;\n\n /**\n * Initializes source state before traversal begins.\n */\n initialize(): Promise<void>;\n\n /**\n * Prepares option-dependent asynchronous source state before runtime headers are constructed.\n *\n * I3S uses this hook to sample elevation surfaces for its root bound after `Tileset3D` has\n * applied spatial options. Sources without asynchronous header preparation omit the hook.\n */\n prepareTileset?(tileset: Tileset3D): Promise<void>;\n\n /** Releases source-local caches and prevents late asynchronous work from mutating runtime tiles. */\n destroy?(): void;\n\n /**\n * Returns normalized source metadata after initialization completes.\n */\n getMetadata(): TilesetSourceMetadata;\n\n /**\n * Returns the root tileset payload after source initialization completes.\n */\n getRootTileset(): Promise<TilesetJSON>;\n\n /**\n * Creates the runtime tile tree for a tileset payload or nested subtree.\n */\n initializeTileHeaders(\n tileset: Tileset3D,\n tilesetJson: TilesetJSON,\n parentTile?: Tile3D | null\n ): Tile3D;\n\n /**\n * Creates the traverser implementation appropriate for this source.\n */\n createTraverser(options: TilesetTraverserProps): TilesetTraverser;\n\n /**\n * Loads renderable content for a tile.\n */\n loadTileContent(tile: Tile3D): Promise<TileContentLoadResult>;\n\n /**\n * Loads and installs a complete lazy child-header group for a runtime tile.\n *\n * Sources that implement this hook retain ownership of resource parsing, caching, query\n * inheritance, and archive resolution. Traversal calls it only after visibility and LOD checks.\n */\n loadTileChildren?(tile: Tile3D, frameState: FrameState): Promise<TileChildrenLoadResult>;\n\n /**\n * Loads all source-managed child headers without requiring camera or visibility state.\n *\n * This hook is used by complete dataset operations such as conversion. Implementations retain\n * ownership of implicit subtrees, node pages, archive resolution, and query inheritance.\n */\n loadTileChildrenForTraversal?(\n tile: Tile3D,\n signal?: AbortSignal\n ): Promise<TileChildrenLoadResult>;\n\n /**\n * Resolves a tile-relative path to the final request URL.\n */\n getTileUrl(tilePath: string): string;\n\n /**\n * Returns tileset-level view metadata derived from the loaded source.\n */\n getViewState(rootTile: Tile3D | null): TilesetSourceViewState;\n\n /**\n * Checks whether the source declares a specific extension.\n */\n hasExtension?(extensionName: string): boolean;\n\n /**\n * Loads child tile metadata on demand for formats that do not expose the full tree up front.\n */\n loadChildTileHeader?(\n parentTile: Tile3D,\n childId: string,\n frameState: FrameState | null\n ): Promise<any>;\n\n /**\n * Updates source-managed bookkeeping after a tile finishes loading.\n */\n onTileLoaded?(tileset: Tileset3D, tile: Tile3D, loadResult: TileContentLoadResult): void;\n\n /**\n * Returns the total known tile count for stats, if available.\n */\n getTilesTotalCount?(): number | null;\n}\n\n/**\n * Type guard for distinguishing a source-backed constructor input from other runtime values.\n * @param value Value to test.\n * @returns `true` when the value implements the {@link Tileset3DSource} contract.\n */\nexport function isTileset3DSource(value: unknown): value is Tileset3DSource {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'initialize' in value &&\n 'getRootTileset' in value &&\n 'initializeTileHeaders' in value &&\n 'loadTileContent' in value\n );\n}\n", "// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Tileset3D} from './tileset-3d';\nimport type {Tile3D} from './tile-3d';\n\n/**\n * A deterministic, renderer-neutral snapshot of one {@link Tileset3D} traversal.\n *\n * Tile IDs are sorted so snapshots can be compared across runs even when child requests complete\n * in a different order. Counts are reported for the completed traversal frame and cache values are\n * expressed in bytes. This is an inspection contract; it does not alter traversal or request policy.\n */\nexport type Tileset3DTraversalSnapshot = {\n /** Monotonically increasing traversal frame number. */\n frameNumber: number;\n /** IDs selected for rendering, sorted for stable comparisons. */\n selectedTileIds: string[];\n /** IDs whose content was requested, sorted for stable comparisons. */\n requestedTileIds: string[];\n /** IDs visited as hierarchy-only or empty tiles, sorted for stable comparisons. */\n emptyTileIds: string[];\n /** Number of selected tiles in the completed frame. */\n visibleTileCount: number;\n /** Number of selected tiles with renderable content. */\n renderableTileCount: number;\n /** Number of tile or subtree loads currently in flight. */\n loadingTileCount: number;\n /** Cumulative number of tiles loaded into the runtime cache. */\n loadedTileCount: number;\n /** Cumulative number of failed tile loads. */\n failedTileCount: number;\n /** Number of tiles currently retained in the runtime cache. */\n cachedTileCount: number;\n /** Estimated cached content bytes. */\n cacheBytes: number;\n /** Active memory-adjusted maximum SSE in logical/CSS pixels. */\n maximumScreenSpaceError: number;\n /** Source-specific implicit subtree counters, when the source exposes them. */\n implicitTiling?: {\n /** Number of subtree resources requested from the source. */\n requestedSubtrees: number;\n /** Number of subtree resources successfully materialized. */\n loadedSubtrees: number;\n /** Number of requests served by the parsed-subtree cache. */\n cacheHits: number;\n /** Number of parsed subtrees currently retained for reuse. */\n cachedSubtrees: number;\n /** Number of subtree requests currently in flight. */\n pendingSubtrees: number;\n /** Number of runtime tile headers created from materialized subtrees. */\n materializedTiles: number;\n };\n};\n\n/**\n * Creates a stable observability snapshot from public {@link Tileset3D} state.\n *\n * The helper intentionally reads only public runtime fields and source diagnostics. It is safe to\n * call from an instrumentation loop and does not retain tile or content references.\n *\n * @param tileset - Runtime whose most recent traversal should be inspected.\n * @returns A serializable snapshot suitable for logs, regression fixtures, and benchmark output.\n */\nexport function getTileset3DTraversalSnapshot(tileset: Tileset3D): Tileset3DTraversalSnapshot {\n const selectedTiles = tileset.selectedTiles.slice();\n const requestedTiles = tileset.requestedTiles.slice();\n const emptyTiles = tileset.emptyTiles.slice();\n\n const getTileIds = (tiles: readonly Tile3D[]): string[] =>\n tiles.map(tile => String(tile.id)).sort();\n\n const getStatCount = (name: string): number => {\n const count = tileset.stats.get(name).count;\n return typeof count === 'number' && Number.isFinite(count) ? count : 0;\n };\n\n const implicitTilingSource = tileset.source as Tileset3D['source'] & {\n getImplicitTilingStats?: () => Tileset3DTraversalSnapshot['implicitTiling'];\n };\n const implicitTiling = implicitTilingSource.getImplicitTilingStats?.();\n\n return {\n frameNumber: tileset.frameNumber,\n selectedTileIds: getTileIds(selectedTiles),\n requestedTileIds: getTileIds(requestedTiles),\n emptyTileIds: getTileIds(emptyTiles),\n visibleTileCount: selectedTiles.length,\n renderableTileCount: selectedTiles.filter(\n tile => tile.contentAvailable && Boolean(tile.content)\n ).length,\n loadingTileCount: getStatCount('Tiles Loading'),\n loadedTileCount: getStatCount('Tiles Loaded'),\n failedTileCount: getStatCount('Failed Tile Loads'),\n cachedTileCount: getStatCount('Tiles In Memory'),\n cacheBytes: tileset.gpuMemoryUsageInBytes,\n maximumScreenSpaceError: tileset.memoryAdjustedScreenSpaceError,\n ...(implicitTiling ? {implicitTiling} : {})\n };\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Tile3D} from './tile-3d';\nimport type {Tileset3D} from './tileset-3d';\nimport type {TileContentLoadResult} from './tileset-source';\nimport type {Tile3DContent} from './tile-3d-contracts';\nimport {TILESET_TYPE} from '../../constants';\n\n/** Options for complete camera-independent tileset content traversal. */\nexport interface TraverseTilesetContentsOptions {\n /** Cancel traversal and stop issuing further source requests. */\n readonly signal?: AbortSignal;\n /**\n * Unload content loaded by this traversal when iteration advances or closes, including on error.\n * Defaults to false. Preloaded content is retained. Use a runtime dedicated to this traversal;\n * consume payloads before advancing and do not retain them or update the runtime concurrently.\n */\n readonly unloadContent?: boolean;\n}\n\n/** One tile placement and its ordered content entries from a completed source read. */\nexport interface TilesetContentTraversalItem {\n /** Runtime tile placement. Shared content resources are yielded once per placement. */\n readonly tile: Tile3D;\n /** Ordered content entries, including multiple contents declared by a single tile. */\n readonly contents: readonly Tile3DContent[];\n}\n\n/**\n * Walks every declared tile placement and its loaded content without a camera or visibility test.\n *\n * Source implementations remain responsible for lazy subtree and node-page resolution. Children\n * are visited in declaration order, nested tilesets are installed by the source before descent,\n * and repeated resource URLs are not deduplicated because each placement can have a distinct\n * transform. Content stays attached unless `unloadContent` is enabled. In that mode, newly loaded\n * payloads are valid until iteration advances or closes. Tile placements and children remain\n * available; callers still own the tileset, source, and archive lifetime.\n *\n * @param tileset - Initialized or initializing source-backed tileset runtime.\n * @param options - Cancellation and decoded-content lifetime options.\n * @returns One item for each visited tile placement in deterministic depth-first order.\n */\nexport async function* traverseTilesetContents(\n tileset: Tileset3D,\n options: TraverseTilesetContentsOptions = {}\n): AsyncGenerator<TilesetContentTraversalItem> {\n await tileset.tilesetInitializationPromise;\n throwIfAborted(options.signal);\n if (!tileset.root) {\n throw new Error('Tileset initialization completed without a root tile');\n }\n\n const stack: Tile3D[] = [tileset.root];\n const visitedTiles = new Set<Tile3D>();\n while (stack.length > 0) {\n throwIfAborted(options.signal);\n const tile = stack.pop() as Tile3D;\n if (visitedTiles.has(tile)) {\n continue;\n }\n visitedTiles.add(tile);\n\n if (tile.header.implicitSubtree && tile.childrenState !== 'ready') {\n const loadChildren = tileset.source.loadTileChildrenForTraversal;\n if (!loadChildren) {\n throw new Error('Tileset source does not support camera-independent subtree loading');\n }\n const result = await loadChildren.call(tileset.source, tile, options.signal);\n if (!result.loaded) {\n throw new Error(`Unable to load implicit subtree for tile ${tile.id}`);\n }\n tile.childrenState = 'ready';\n }\n\n if (tileset.type === TILESET_TYPE.I3S && tileset.source.loadTileChildrenForTraversal) {\n const result = await tileset.source.loadTileChildrenForTraversal(tile, options.signal);\n if (!result.loaded) {\n throw new Error(`Unable to load I3S child nodes for tile ${tile.id}`);\n }\n }\n\n throwIfAborted(options.signal);\n const loadsContent = tile.contentUrls.length > 0 && !tile.content;\n try {\n if (loadsContent) {\n const loadResult: TileContentLoadResult = await tile.loadContentForTraversal();\n throwIfAborted(options.signal);\n if (!loadResult.loaded) {\n throw new Error(`Unable to load tile content for tile ${tile.id}`);\n }\n tileset.source.onTileLoaded?.(tileset, tile, loadResult);\n }\n\n yield {tile, contents: tile.contentEntries};\n } finally {\n if (options.unloadContent && loadsContent) {\n tile.unloadContent();\n }\n }\n\n for (let childIndex = tile.children.length - 1; childIndex >= 0; childIndex--) {\n stack.push(tile.children[childIndex]);\n }\n }\n}\n\n/** Throws the signal reason when traversal is cancelled. */\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The operation was aborted', 'AbortError');\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {BlobFile, HttpFile, path} from '@loaders.gl/loader-utils';\nimport type {CoreAPI, Loader, LoaderOptions, ReadableFile} from '@loaders.gl/loader-utils';\nimport type {TilesetSourceResolver} from './tileset-source';\n\n/** Options for {@link IndexedArchiveTilesetSource}. */\nexport type IndexedArchiveTilesetSourceOptions<ArchiveT> = {\n /** Archive URL or Blob. */\n data: string | Blob;\n /** Filename to expose for Blob inputs that do not provide a name. */\n fallbackFilename: string;\n /** Archive file extension used as the URL path marker. */\n archiveExtension: string;\n /** Path to the root metadata resource inside the archive. */\n rootPath: string;\n /** Optional mode passed when loading the root metadata resource. */\n rootMode?: string;\n /** Parses an opened readable file into an indexed archive object. */\n parseArchive: (file: ReadableFile) => Promise<ArchiveT>;\n /** Loads one resource from the parsed archive. */\n getFile: (archive: ArchiveT, pathInArchive: string, mode?: string) => Promise<ArrayBuffer>;\n /** Returns the core API used for local file loading and nested resource parsing. */\n getCoreApi: () => CoreAPI | undefined;\n /** Error message to throw when the core API is required but unavailable. */\n missingCoreApiMessage: string;\n};\n\n/**\n * Tileset source resolver backed by an indexed archive such as 3TZ or SLPK.\n *\n * The source owns archive opening, archive caching, path resolution, and archive-backed `fetch`\n * injection. Format-specific parsing and file lookup stay in the owning format module.\n */\nexport class IndexedArchiveTilesetSource<ArchiveT> implements TilesetSourceResolver {\n /** URL exposed to the tileset source that owns this archive source. */\n readonly sourceUrl: string;\n\n private readonly options: IndexedArchiveTilesetSourceOptions<ArchiveT>;\n private archivePromise?: Promise<ArchiveT>;\n\n /**\n * Creates an indexed archive tileset source.\n * @param options Archive source options\n */\n constructor(options: IndexedArchiveTilesetSourceOptions<ArchiveT>) {\n this.options = options;\n this.sourceUrl = getArchiveSourceUrl(options.data, options.fallbackFilename);\n }\n\n /**\n * Loads and parses the archive root metadata resource.\n * @param url Root URL, ignored because the archive root path is configured explicitly\n * @param loader Loader used to parse the root metadata\n * @param loadOptions Loader options forwarded to parsing\n */\n async loadRoot<DataT>(\n url: string,\n loader: Loader<DataT>,\n loadOptions: LoaderOptions\n ): Promise<DataT> {\n // Resolve root-relative URIs inside the archive rather than beside its download URL.\n const resourceUrl = this.options.rootPath\n ? `${stripQueryString(this.sourceUrl)}/${this.options.rootPath}`\n : url;\n return await this.parseArchiveResource(\n resourceUrl,\n this.options.rootPath,\n loader,\n loadOptions,\n this.options.rootMode\n );\n }\n\n /**\n * Loads and parses an archive resource relative to a requesting resource URL.\n * @param url Resource URL\n * @param loader Loader used to parse the resource\n * @param loadOptions Loader options forwarded to parsing\n */\n async loadResource<DataT>(\n url: string,\n loader: Loader<DataT>,\n loadOptions: LoaderOptions\n ): Promise<DataT> {\n const pathInArchive = this.resolveArchivePath(url, url);\n return await this.parseArchiveResource(url, pathInArchive, loader, loadOptions);\n }\n\n private async parseArchiveResource<DataT>(\n resourceUrl: string,\n pathInArchive: string,\n loader: Loader<DataT>,\n loadOptions: LoaderOptions,\n mode?: string\n ): Promise<DataT> {\n const coreApi = this.options.getCoreApi();\n if (!coreApi) {\n throw new Error(this.options.missingCoreApiMessage);\n }\n\n const data = await this.loadFile(pathInArchive, mode);\n const archiveFetch = this.createArchiveFetch(resourceUrl);\n return (await coreApi.parse(\n data,\n loader,\n {\n ...loadOptions,\n fetch: archiveFetch\n },\n {\n url: resourceUrl,\n fetch: archiveFetch,\n _parse: coreApi.parse,\n loaders: [loader],\n coreApi\n } as any\n )) as DataT;\n }\n\n private createArchiveFetch(contextUrl: string): typeof fetch {\n return async (input: RequestInfo | URL): Promise<Response> => {\n const requestUrl =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;\n const pathInArchive = this.resolveArchivePath(requestUrl, contextUrl);\n const data = await this.loadFile(pathInArchive);\n return new Response(data, {status: 200});\n };\n }\n\n private async loadFile(pathInArchive: string, mode?: string): Promise<ArrayBuffer> {\n this.archivePromise ||= this.openArchiveReadableFile().then(file =>\n this.options.parseArchive(file)\n );\n const archive = await this.archivePromise;\n return await this.options.getFile(archive, pathInArchive, mode);\n }\n\n private async openArchiveReadableFile(): Promise<ReadableFile> {\n const {data} = this.options;\n if (typeof data !== 'string') {\n return new BlobFile(data);\n }\n\n if (/^https?:\\/\\//i.test(data)) {\n return new HttpFile(data);\n }\n\n const coreApi = this.options.getCoreApi();\n if (!coreApi) {\n throw new Error(this.options.missingCoreApiMessage);\n }\n const response = await coreApi.fetchFile(data);\n return new BlobFile(await response.arrayBuffer());\n }\n\n private resolveArchivePath(request: string, baseUrl: string): string {\n const requestWithoutQuery = stripQueryString(request);\n const archiveRoot = stripQueryString(this.sourceUrl);\n const baseWithoutQuery = stripQueryString(baseUrl);\n const basePath =\n baseWithoutQuery === archiveRoot ? archiveRoot : path.dirname(baseWithoutQuery);\n const markerExpression = new RegExp(`\\\\.${this.options.archiveExtension}/(.*)$`, 'i');\n const markerMatch = requestWithoutQuery.match(markerExpression);\n if (markerMatch?.[1]) {\n return markerMatch[1];\n }\n\n const isAbsoluteRequest =\n /^[a-z][a-z0-9+.-]*:/i.test(requestWithoutQuery) || requestWithoutQuery.startsWith('/');\n const absoluteRequest = requestWithoutQuery.startsWith(archiveRoot)\n ? requestWithoutQuery\n : baseWithoutQuery === archiveRoot && !isAbsoluteRequest\n ? `${archiveRoot}/${requestWithoutQuery}`\n : /^[a-z][a-z0-9+.-]*:\\/\\//i.test(baseWithoutQuery)\n ? new URL(requestWithoutQuery, baseWithoutQuery).href\n : path.resolve(basePath, requestWithoutQuery);\n\n if (absoluteRequest === archiveRoot) {\n return '';\n }\n\n if (absoluteRequest.startsWith(`${archiveRoot}/`)) {\n return absoluteRequest.slice(archiveRoot.length + 1);\n }\n\n return absoluteRequest.replace(/^\\/+/, '');\n }\n}\n\nfunction getArchiveSourceUrl(data: string | Blob, fallbackFilename: string): string {\n if (typeof data === 'string') {\n return data;\n }\n\n const fileName =\n 'name' in data && typeof data.name === 'string' && data.name ? data.name : fallbackFilename;\n return `memory://${fileName}`;\n}\n\nfunction stripQueryString(url: string): string {\n return url.split(/[?#]/, 1)[0];\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Vector3, Matrix4} from '@math.gl/core';\nimport {CullingVolume} from '@math.gl/culling';\nimport type {CullingResult} from '@math.gl/culling';\nimport {getTile3DFeatureIdSets} from './tile-3d-contracts';\nimport type {Tile3DContent, Tile3DFeatureIdSet, Tile3DMetadataContext} from './tile-3d-contracts';\n\n// Note: circular dependency\nimport type {Tileset3D} from './tileset-3d';\nimport type {DoublyLinkedListNode} from '../../utils/doubly-linked-list-node';\nimport {LOD_METRIC_TYPE, TILE_REFINEMENT, TILE_CONTENT_STATE, TILESET_TYPE} from '../../constants';\nimport type {TileChildrenLoadResult, TileContentLoadResult} from './tileset-source';\n\nimport {FrameState} from '../helpers/frame-state';\nimport {\n createBoundingVolume,\n getCartographicBounds,\n CartographicBounds\n} from '../helpers/bounding-volume';\nimport {getTiles3DScreenSpaceError} from '../helpers/tiles-3d-lod';\nimport {getProjectedRadius} from '../helpers/i3s-lod';\nimport {TilesetTraverser} from './tileset-traverser';\nimport {\n calculateFoveatedFactor,\n calculateTileRequestPriority,\n isFoveatedRequestDelayActive,\n isFoveatedRequestDeferred,\n isProgressiveResolutionPriority\n} from '../helpers/tiles-3d-request-priority';\n\nconst scratchVector = new Vector3();\n\n/**\n * Classifies render-content visibility across all content volumes owned by a tile.\n *\n * Content volumes form a union: one visible content entry keeps the tile renderable even when\n * another entry is outside the frustum or clipping planes. The traversal volume is intentionally\n * not used here except as a fallback when a tile has no content-specific volume. This separation\n * keeps clipping render-only and prevents a tight content volume from pruning descendants.\n *\n * @param contentVolumes - Transformed content volumes in source order.\n * @param fallbackVolume - Tile volume used when content does not declare its own volume.\n * @param cullingVolume - Current view frustum.\n * @param visibilityPlaneMask - Parent visibility mask optimization.\n * @param clippingPlanes - Optional world-space planes applied to render content only.\n * @returns Union visibility classification for the renderable content.\n */\nexport function getContentVisibility(\n contentVolumes: any[],\n fallbackVolume: any,\n cullingVolume: CullingVolume,\n visibilityPlaneMask: number | undefined,\n clippingPlanes: any[] = []\n): CullingResult {\n const volumes = contentVolumes.length ? contentVolumes : [fallbackVolume];\n let visibleVolume = false;\n let intersectingVolume = false;\n for (const contentVolume of volumes) {\n let visibility: CullingResult = 'inside';\n if (visibilityPlaneMask !== CullingVolume.MASK_INSIDE) {\n visibility = cullingVolume.computeVisibility(contentVolume);\n if (visibility === 'outside') {\n continue;\n }\n }\n let clipped = false;\n for (const clippingPlane of clippingPlanes) {\n if (contentVolume.intersectPlane(clippingPlane) === 'outside') {\n clipped = true;\n break;\n }\n }\n if (!clipped) {\n visibleVolume = true;\n intersectingVolume = intersectingVolume || visibility === 'intersecting';\n }\n }\n if (!visibleVolume) {\n return 'outside';\n }\n return intersectingVolume ? 'intersecting' : 'inside';\n}\n\nfunction isNestedTilesetPayload(payload: unknown): boolean {\n if (!payload || typeof payload !== 'object') {\n return false;\n }\n const record = payload as Record<string, any>;\n return record.shape === 'tileset3d' || record.type === 'tileset3d' || Boolean(record.tileset);\n}\n\nfunction defined(x) {\n return x !== undefined && x !== null;\n}\n\n/**\n * @param tileset - Tileset3D instance\n * @param header - tile header - JSON loaded from a dataset\n * @param parentHeader - parent Tile3D instance\n * @param extendedId - optional ID to separate copies of a tile for different viewports.\n * const extendedId = `${tile.id}-${frameState.viewport.id}`;\n */\nexport type Tile3DProps = {\n tileset: Tileset3D;\n header: Object;\n parentHeader: Tile3D;\n extendedId: string;\n};\n\n/** Lifecycle of a source-managed lazy child-header group. */\nexport type TileChildrenState = 'unloaded' | 'loading' | 'ready' | 'failed';\n\n/**\n * A Tile3DHeader represents a tile as Tileset3D. When a tile is first created, its content is not loaded;\n * the content is loaded on-demand when needed based on the view.\n * Do not construct this directly, instead access tiles through {@link Tileset3D#tileVisible}.\n */\nexport class Tile3D {\n tileset: Tileset3D;\n header: any;\n id: string;\n url: string;\n parent: Tile3D;\n /* Specifies the type of refine that is used when traversing this tile for rendering. */\n refine: TILE_REFINEMENT;\n type: string;\n contentUrl: string;\n /** Resolved render-content URLs in source order; empty for contentless tiles. */\n contentUrls: string[] = [];\n /** Different refinement algorithms used by I3S and 3D tiles */\n lodMetricType = 'geometricError';\n /**\n * The world-space geometric error, in meters, introduced if this tile is rendered and its\n * children are not. For I3S this stores the format's unscaled screen-threshold metric instead.\n */\n lodMetricValue: number = 0;\n\n /**\n * The source LOD metric before applying the tile's computed transform. Keeping the source value\n * separate ensures transform updates never compound an already-scaled geometric error.\n */\n private _unscaledLodMetricValue: number = 0;\n\n /** Whether the source format defines geometric error in transform-local units. */\n private _scaleGeometricError: boolean = true;\n\n /** @todo math.gl is not exporting BoundingVolume base type? */\n boundingVolume: any = null;\n\n /**\n * The tile's content. This represents the actual tile's payload,\n * not the content's metadata in the tileset JSON file.\n */\n content: any = null;\n /** Loaded payloads in the same order as {@link contentUrls}; `content` remains the primary payload. */\n contents: any[] = [];\n /** Ordered renderer-neutral descriptors for each source content entry. */\n contentEntries: Tile3DContent[] = [];\n /** Raw metadata references inherited by this tile and its content. */\n metadataContext: Tile3DMetadataContext = {};\n /** Feature-id declarations normalized from supported content extensions. */\n featureIdSets: Tile3DFeatureIdSet[] = [];\n /** Decoded 3D Tiles vector topology for the primary loaded content, when present. */\n vectorContent: unknown = null;\n /**\n * Metadata entity attached to this tile in the source tileset, if present.\n *\n * This is the raw 3D Tiles metadata reference. The generic tiles runtime preserves it without\n * decoding schema classes or binary property tables.\n */\n metadata: Record<string, any> | null = null;\n /** Raw metadata entities attached to tile contents, in content source order. */\n contentMetadata: Array<Record<string, any> | null> = [];\n contentState: number = TILE_CONTENT_STATE.UNLOADED;\n gpuMemoryUsageInBytes: number = 0;\n\n /** The tile's children - an array of Tile3D objects. */\n children: Tile3D[] = [];\n /** Current lifecycle state for a lazy implicit subtree rooted at this tile. */\n childrenState: TileChildrenState = 'ready';\n depth: number = 0;\n viewportIds: any[] = [];\n transform = new Matrix4();\n extensions: any = null;\n /** TODO Cesium 3d tiles specific */\n implicitTiling?: any = null;\n\n /** Container to store application specific data */\n userData: Record<string, any> = {};\n\n computedTransform: any;\n hasEmptyContent: boolean = false;\n hasTilesetContent: boolean = false;\n\n traverser = new TilesetTraverser({});\n\n /** Used by TilesetCache */\n _cacheNode: DoublyLinkedListNode | null = null;\n\n private _frameNumber: any = null;\n\n // TODO Cesium 3d tiles specific\n private _expireDate: any = null;\n private _expiredContent: any = null;\n\n /** In-flight source request shared by repeated traversal frames. */\n private _childrenPromise: Promise<TileChildrenLoadResult> | null = null;\n\n private _boundingBox?: CartographicBounds = undefined;\n\n /** updated every frame for tree traversal and rendering optimizations: */\n public _distanceToCamera: number = 0;\n _screenSpaceError: number = 0;\n /** SSE calculated at the reduced viewport height used to prioritize coarse coverage. */\n _screenSpaceErrorProgressiveResolution: number = 0;\n /** Whether this tile should be promoted into the progressive-resolution request pass. */\n _priorityProgressiveResolution: boolean = false;\n /** Angular distance from the camera view axis used to prioritize center tiles. */\n _foveatedFactor: number = 0;\n /** Whether this peripheral request is currently inside the camera-motion deferral window. */\n priorityDeferred: boolean = false;\n private _visibilityPlaneMask: any;\n private _visible: boolean | undefined = undefined;\n\n private _contentBoundingVolume: any;\n private _contentBoundingVolumes: any[] = [];\n /** Source content-volume headers retained after render content is unloaded. */\n private _contentBoundingVolumeHeaders: any[] = [];\n private _viewerRequestVolume: any;\n\n /** Bounding volume used to cull the tile's first renderable content entry. */\n get contentBoundingVolume(): any {\n return this._contentBoundingVolume;\n }\n\n /** All transformed render-content bounding volumes, including tile-volume fallbacks. */\n get contentBoundingVolumes(): any[] {\n return this._contentBoundingVolumes;\n }\n\n /** Bounding volume that limits when this tile may be requested, when declared. */\n get viewerRequestVolume(): any {\n return this._viewerRequestVolume;\n }\n\n /** Accumulated tile transforms from the source JSON, excluding the tileset model matrix. */\n _initialTransform: Matrix4 = new Matrix4();\n\n // Used by traverser, cannot be marked private\n _priority: number = 0;\n _selectedFrame: number = 0;\n _requestedFrame: number = 0;\n _selectionDepth: number = 0;\n _touchedFrame: number = 0;\n _centerZDepth: number = 0;\n _shouldRefine: boolean = false;\n _stackLength: number = 0;\n _visitedFrame: number = 0;\n _inRequestVolume: boolean = false;\n _lodJudge: any = null; // TODO i3s specific, needs to remove\n\n /**\n * Indicates whether the tile has been drawn by the renderer.\n * Defaults to true for backwards compatibility \u2014 renderers that support\n * transition hold (e.g. deck.gl 9.3+) should set this to false on tile load,\n * then back to true after first draw to avoid flashes (see deck.gl #7914).\n */\n tileDrawn: boolean = true;\n\n /**\n * @constructs\n * Create a Tile3D instance\n * @param tileset - Tileset3D instance\n * @param header - tile header - JSON loaded from a dataset\n * @param parentHeader - parent Tile3D instance\n * @param extendedId - optional ID to separate copies of a tile for different viewports.\n * const extendedId = `${tile.id}-${frameState.viewport.id}`;\n */\n // eslint-disable-next-line max-statements\n constructor(\n tileset: Tileset3D,\n header: {[key: string]: any},\n parentHeader?: Tile3D,\n extendedId = ''\n ) {\n // PUBLIC MEMBERS\n // original tile data\n this.header = header;\n\n // The tileset containing this tile.\n this.tileset = tileset;\n this.id = extendedId || header.id;\n this.url = header.url;\n\n // This tile's parent or `undefined` if this tile is the root.\n // @ts-ignore\n this.parent = parentHeader;\n this.refine = this._getRefine(header.refine);\n this.type = header.type;\n this.contentUrl = header.contentUrl;\n this.contentUrls = header.contentUrls || (header.contentUrl ? [header.contentUrl] : []);\n this._initializeMetadata(header);\n this.childrenState = header.implicitSubtree ? 'unloaded' : 'ready';\n\n this._initializeLodMetric(header);\n this._initializeTransforms(header);\n this._updateLodMetricScale();\n this._initializeBoundingVolumes(header);\n this._initializeContent(header);\n this._initializeContentEntries(header);\n this._initializeRenderingState(header);\n\n Object.seal(this);\n }\n\n destroy() {\n this.header = null;\n }\n\n isDestroyed() {\n return this.header === null;\n }\n\n get selected() {\n return this._selectedFrame === this.tileset._frameNumber;\n }\n\n get isVisible() {\n return this._visible;\n }\n\n get isVisibleAndInRequestVolume() {\n return this._visible && this._inRequestVolume;\n }\n\n /** Returns true if tile is not an empty tile and not an external tileset */\n get hasRenderContent() {\n return !this.hasEmptyContent && !this.hasTilesetContent;\n }\n\n /** Returns true if tile has children */\n get hasChildren() {\n return (\n this.children.length > 0 ||\n (this.header.children && this.header.children.length > 0) ||\n Boolean(this.header.implicitSubtree && this.childrenState !== 'ready')\n );\n }\n\n /** Returns whether traversal may request an unresolved lazy child-header group. */\n get hasUnloadedChildren(): boolean {\n return Boolean(\n this.header.implicitSubtree &&\n (this.childrenState === 'unloaded' || this.childrenState === 'failed')\n );\n }\n\n /** Returns whether a lazy child-header request is currently in flight. */\n get childrenLoading(): boolean {\n return this.childrenState === 'loading';\n }\n\n /**\n * Determines if the tile's content is ready. This is automatically `true` for\n * tiles with empty content.\n */\n get contentReady() {\n return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;\n }\n\n /**\n * Determines if the tile has available content to render. `true` if the tile's\n * content is ready or if it has expired content this renders while new content loads; otherwise,\n */\n get contentAvailable() {\n return Boolean(\n (this.contentReady && this.hasRenderContent) || (this._expiredContent && !this.contentFailed)\n );\n }\n\n /** Returns true if tile has renderable content but it's unloaded */\n get hasUnloadedContent() {\n return this.hasRenderContent && this.contentUnloaded;\n }\n\n /**\n * Determines if the tile's content has not be requested. `true` if tile's\n * content has not be requested; otherwise, `false`.\n */\n get contentUnloaded() {\n return this.contentState === TILE_CONTENT_STATE.UNLOADED;\n }\n\n /**\n * Determines if the tile's content is expired. `true` if tile's\n * content is expired; otherwise, `false`.\n */\n get contentExpired() {\n return this.contentState === TILE_CONTENT_STATE.EXPIRED;\n }\n\n // Determines if the tile's content failed to load. `true` if the tile's\n // content failed to load; otherwise, `false`.\n get contentFailed() {\n return this.contentState === TILE_CONTENT_STATE.FAILED;\n }\n\n /**\n * Distance from the tile's bounding volume center to the camera\n */\n get distanceToCamera(): number {\n return this._distanceToCamera;\n }\n\n /**\n * Screen space error for LOD selection\n */\n get screenSpaceError(): number {\n return this._screenSpaceError;\n }\n\n /**\n * Get the current world-space bounding volume in cartographic coordinates.\n * @returns [min, max] each in [longitude, latitude, altitude]\n */\n get boundingBox(): CartographicBounds {\n if (!this._boundingBox) {\n this._boundingBox = getCartographicBounds(\n this.header.boundingVolume,\n this.boundingVolume,\n !this.computedTransform.equals(this._initialTransform)\n );\n }\n return this._boundingBox;\n }\n\n /**\n * Gets the tile's screen-space error for normal refinement or a reduced-height priority pass.\n *\n * I3S already supplies a screen-oriented LOD metric and intentionally ignores the optional 3D\n * Tiles progressive-resolution height fraction.\n *\n * @param frameState - Current camera and viewport measurements.\n * @param useParentLodMetric - Whether to substitute the parent LOD metric.\n * @param viewportHeightFraction - Fraction of viewport height represented by the priority pass.\n * @returns Screen-space LOD error for the current tileset format.\n */\n getScreenSpaceError(frameState, useParentLodMetric, viewportHeightFraction = 1) {\n switch (this.tileset.type) {\n case TILESET_TYPE.I3S:\n return getProjectedRadius(this, frameState);\n case TILESET_TYPE.TILES3D:\n return getTiles3DScreenSpaceError(\n this,\n frameState,\n useParentLodMetric,\n viewportHeightFraction\n );\n default:\n // eslint-disable-next-line\n throw new Error('Unsupported tileset type');\n }\n }\n\n /**\n * Make tile unselected than means it won't be shown\n * but it can be still loaded in memory\n */\n unselect(): void {\n this._selectedFrame = 0;\n }\n\n /**\n * Memory usage of tile on GPU\n */\n _getGpuMemoryUsageInBytes(): number {\n const contents = this.contents.length ? this.contents : [this.content];\n return contents.reduce(\n (total, content) => total + (content?.gpuMemoryUsageInBytes || content?.byteLength || 0),\n 0\n );\n }\n\n /**\n * Returns scheduler priority for render-content requests.\n *\n * @returns Numeric priority, or a negative value when the queued request should be cancelled.\n */\n _getPriority(): number {\n return this._calculateRequestPriority(false);\n }\n\n /**\n * Returns scheduler priority for lazy child-header requests.\n *\n * Contentless implicit placeholders intentionally retain `UNLOADED` content state, so metadata\n * scheduling skips only that render-content cancellation check and preserves every visibility,\n * recency, progressive, foveated, and motion-deferral rule.\n *\n * @returns Numeric priority, or a negative value when the queued request should be cancelled.\n */\n private _getChildrenPriority(): number {\n return this._calculateRequestPriority(true);\n }\n\n /**\n * Calculates the common scheduler priority for content or hierarchy metadata.\n *\n * @param allowUnloadedContent - Whether an empty placeholder may request child metadata.\n * @returns Numeric priority, or a negative value when the queued request should be cancelled.\n */\n // eslint-disable-next-line complexity\n private _calculateRequestPriority(allowUnloadedContent: boolean): number {\n const traverser = this.tileset._traverser;\n const skipLevelOfDetail =\n traverser.options.skipLevelOfDetail && !traverser.disableSkipLevelOfDetail;\n\n /*\n * Tiles that are outside of the camera's frustum could be skipped if we are in 'ADD' mode\n * or if we are using 'Skip Traversal' in 'REPLACE' mode.\n * Otherewise, all 'touched' child tiles have to be loaded and displayed,\n * this may include tiles that are outide of the camera frustum (so that we can hide the parent tile).\n */\n const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;\n\n // Check if any reason to abort\n if (maySkipTile && !this.isVisible && this._visible !== undefined) {\n return -1;\n }\n // Condition used in `cancelOutOfViewRequests` function in CesiumJS/Cesium3DTileset.js\n if (this.tileset._frameNumber - this._touchedFrame >= 1) {\n return -1;\n }\n // RequestScheduler re-evaluates this callback before a queued request receives a slot. A\n // negative priority cancels work that became deferred after it was queued; the scheduled\n // follow-up traversal submits it again after the motion delay expires.\n if (this.priorityDeferred) {\n return -1;\n }\n if (!allowUnloadedContent && this.contentState === TILE_CONTENT_STATE.UNLOADED) {\n return -1;\n }\n\n // Based on the priority function `getPriorityReverseScreenSpaceError` in CesiumJS. Scheduling priority is based on the parent's screen space error when possible.\n const parent = this.parent;\n const useParentScreenSpaceError =\n parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);\n const screenSpaceError = useParentScreenSpaceError\n ? parent._screenSpaceError\n : this._screenSpaceError;\n\n const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;\n\n // Map higher SSE to lower values (e.g. root tile is highest priority), then combine the\n // existing order with independent progressive and foveated priority bands.\n const reverseScreenSpaceError = Math.max(rootScreenSpaceError - screenSpaceError, 0);\n return calculateTileRequestPriority({\n priorityProgressiveResolution: this._priorityProgressiveResolution,\n foveatedFactor: this._foveatedFactor,\n reverseScreenSpaceError,\n rootScreenSpaceError\n });\n }\n\n /**\n * Requests the tile's content.\n * The request may not be made if the Request Scheduler can't prioritize it.\n */\n // eslint-disable-next-line max-statements, complexity\n async loadContent(): Promise<TileContentLoadResult> {\n if (this.hasEmptyContent) {\n return {loaded: false};\n }\n\n if (this.content) {\n return {loaded: true};\n }\n\n const expired = this.contentExpired;\n\n if (expired) {\n this._expireDate = null;\n }\n\n this.contentState = TILE_CONTENT_STATE.LOADING;\n\n const requestToken = await this.tileset._requestScheduler.scheduleRequest(\n this.id,\n this._getPriority.bind(this)\n );\n\n if (!requestToken) {\n // cancelled\n this.contentState = TILE_CONTENT_STATE.UNLOADED;\n return {loaded: false};\n }\n\n try {\n return await this._loadContentFromSource();\n } catch (error) {\n // Tile is unloaded before the content finishes loading\n this.contentState = TILE_CONTENT_STATE.FAILED;\n throw error;\n } finally {\n requestToken.done();\n }\n }\n\n /** Loads content for complete dataset operations without viewport-based request priority. */\n async loadContentForTraversal(): Promise<TileContentLoadResult> {\n if (this.hasEmptyContent) {\n return {loaded: false};\n }\n if (this.content) {\n return {loaded: true, contents: this.contents};\n }\n\n this.contentState = TILE_CONTENT_STATE.LOADING;\n try {\n return await this._loadContentFromSource();\n } catch (error) {\n this.contentState = TILE_CONTENT_STATE.FAILED;\n throw error;\n }\n }\n\n /** Loads source content and updates the tile's renderer-neutral payload state. */\n private async _loadContentFromSource(): Promise<TileContentLoadResult> {\n const loadResult = await this.tileset.source.loadTileContent(this);\n if (loadResult.contents) {\n this.contents = loadResult.contents;\n this.content = this.contents[0] || null;\n }\n this.vectorContent =\n this.contents.find(content => Boolean(content?.vectorContent))?.vectorContent || null;\n\n if (this.tileset.options.contentLoader) {\n await this.tileset.options.contentLoader(this);\n }\n\n this.contentState = TILE_CONTENT_STATE.READY;\n this._onContentLoaded();\n this._updateContentEntriesAfterLoad(loadResult);\n return loadResult;\n }\n\n /**\n * Requests and installs this tile's lazy child-header group through its source.\n *\n * The same request scheduler and SSE/foveated priority value used for render content are reused\n * for subtree metadata. Repeated traversal frames share one promise, and scheduler cancellation\n * restores the unloaded state so a later frame can retry.\n *\n * @param frameState - View state that made the subtree eligible for refinement.\n * @returns Source load result, or an unloaded result if scheduling was cancelled.\n */\n async loadChildren(frameState: FrameState): Promise<TileChildrenLoadResult> {\n if (!this.header.implicitSubtree || this.childrenState === 'ready') {\n return {loaded: false, tileCount: 0, childSubtreeCount: 0};\n }\n if (this._childrenPromise) {\n return await this._childrenPromise;\n }\n if (!this.tileset.source.loadTileChildren) {\n throw new Error('Tileset source does not support lazy tile children');\n }\n\n this.childrenState = 'loading';\n this._childrenPromise = this._loadChildrenWithScheduler(frameState);\n try {\n return await this._childrenPromise;\n } finally {\n this._childrenPromise = null;\n }\n }\n\n /**\n * Runs one lazy child-header load after obtaining a scheduler token.\n *\n * @param frameState - View state forwarded to the source implementation.\n * @returns Source load result.\n */\n private async _loadChildrenWithScheduler(\n frameState: FrameState\n ): Promise<TileChildrenLoadResult> {\n const requestToken = await this.tileset._requestScheduler.scheduleRequest(\n `${this.id}:implicit-subtree`,\n this._getChildrenPriority.bind(this)\n );\n if (!requestToken) {\n this.childrenState = 'unloaded';\n return {loaded: false, tileCount: 0, childSubtreeCount: 0};\n }\n\n try {\n const loadResult = await this.tileset.source.loadTileChildren!(this, frameState);\n this.childrenState = loadResult.loaded ? 'ready' : 'unloaded';\n return loadResult;\n } catch (error) {\n this.childrenState = 'failed';\n throw error;\n } finally {\n requestToken.done();\n }\n }\n\n /**\n * Replaces a contentless implicit placeholder with its materialized subtree-root header.\n *\n * The placeholder transform is preserved when the subtree omits a root transform. An explicit\n * subtree-root transform replaces it and is recomposed against the runtime parent. Content,\n * metadata, bounds, and raw geometric error are reinitialized from the available header.\n *\n * @param materializedHeader - Available root header produced from one subtree resource.\n */\n applyImplicitSubtreeHeader(materializedHeader: Record<string, any>): void {\n const existingTransform = this.header.transform;\n const existingTransformMatrix = this.header.transformMatrix;\n const hasMaterializedTransform = materializedHeader.transform !== undefined;\n this.header = {\n ...this.header,\n ...materializedHeader,\n transform: hasMaterializedTransform ? materializedHeader.transform : existingTransform,\n transformMatrix: hasMaterializedTransform\n ? materializedHeader.transformMatrix\n : existingTransformMatrix,\n implicitSubtree: undefined\n };\n if (hasMaterializedTransform) {\n this._initializeTransforms(this.header);\n }\n this.refine = this._getRefine(materializedHeader.refine);\n this.type = materializedHeader.type;\n this.contentUrl = materializedHeader.contentUrl;\n this.contentUrls =\n materializedHeader.contentUrls ||\n (materializedHeader.contentUrl ? [materializedHeader.contentUrl] : []);\n this._initializeMetadata(this.header);\n this._initializeLodMetric(materializedHeader);\n this._updateLodMetricScale();\n this._initializeBoundingVolumes(this.header);\n this._boundingBox = undefined;\n // Use the merged header so inherited viewer-request-volume metadata remains available when a\n // materialized implicit tile has no render content of its own.\n this._initializeContent(this.header);\n this._initializeContentEntries(this.header);\n }\n\n /** Refreshes tile and content metadata from a source or materialized tile header. */\n private _initializeMetadata(header: Record<string, any>): void {\n this.metadata = header.metadata || null;\n const contentHeaders = Array.isArray(header.content) ? header.content : [header.content];\n this.contentMetadata = contentHeaders\n .filter(Boolean)\n .map(contentHeader => contentHeader.metadata || null);\n const firstContentHeader = contentHeaders.find(Boolean) || {};\n const groupReference = firstContentHeader.group;\n const group =\n typeof groupReference === 'number'\n ? this.tileset.groups?.[groupReference] || null\n : groupReference || null;\n const metadataContext: Tile3DMetadataContext = {\n tileset: this.tileset.metadata || null,\n group,\n tile: this.metadata,\n content: this.contentMetadata[0] || null,\n subtree: header.implicitMetadata || null\n };\n if (this.tileset.groups) {\n metadataContext.groups = this.tileset.groups;\n }\n this.metadataContext = metadataContext;\n }\n\n /** Updates payload and renderability while retaining immutable metadata descriptors. */\n private _updateContentEntriesAfterLoad(loadResult: TileContentLoadResult): void {\n if (loadResult.contentEntries) {\n this.contentEntries = loadResult.contentEntries.map((entry, index) => ({\n ...entry,\n index,\n boundingVolume:\n entry.boundingVolume || this._contentBoundingVolumes[index] || this.boundingVolume,\n payload: entry.payload ?? this.contents[index] ?? null,\n featureIds: entry.featureIds?.length\n ? entry.featureIds\n : getTile3DFeatureIdSets(entry.payload ?? this.contents[index]),\n renderable: Boolean(\n entry.renderable !== false &&\n (entry.payload ?? this.contents[index]) &&\n !isNestedTilesetPayload(entry.payload ?? this.contents[index])\n )\n }));\n this.featureIdSets = this.contentEntries.flatMap(entry => entry.featureIds);\n return;\n }\n this.contentEntries = this.contentEntries.map((entry, index) => ({\n ...entry,\n payload: this.contents[index] ?? null,\n featureIds: getTile3DFeatureIdSets(this.contents[index]),\n renderable: Boolean(this.contents[index]) && !isNestedTilesetPayload(this.contents[index])\n }));\n this.featureIdSets = this.contentEntries.flatMap(entry => entry.featureIds);\n }\n\n /** Returns one ordered content descriptor, or null when the index is out of range. */\n getContentEntry(index: number): Tile3DContent | null {\n return this.contentEntries[index] || null;\n }\n\n /** Returns whether an ordered content entry currently has renderable payload. */\n isContentRenderable(index: number): boolean {\n return Boolean(this.contentEntries[index]?.renderable);\n }\n\n /** Initializes additive renderer-neutral descriptors from a normalized tile header. */\n private _initializeContentEntries(tileHeader: Record<string, any>): void {\n const headers = Array.isArray(tileHeader.content)\n ? tileHeader.content\n : tileHeader.content\n ? [tileHeader.content]\n : [];\n this.contentEntries = headers.map((contentHeader, index) => {\n const normalizedContentHeader = contentHeader || {};\n return {\n index,\n uri: this.contentUrls[index] || normalizedContentHeader.uri || normalizedContentHeader.url,\n group: normalizedContentHeader.group,\n type: normalizedContentHeader.type,\n payload: null,\n metadata: normalizedContentHeader.metadata || null,\n boundingVolume: this._contentBoundingVolumes[index] || this.boundingVolume,\n featureIds: this._getFeatureIdSets(normalizedContentHeader),\n renderable: false\n };\n });\n }\n\n /** Extracts renderer-neutral feature-id declarations without decoding property values. */\n private _getFeatureIdSets(contentHeader: Record<string, any>): Tile3DFeatureIdSet[] {\n return getTile3DFeatureIdSets(contentHeader);\n }\n\n // Unloads the tile's content.\n unloadContent() {\n for (const content of this.contents.length ? this.contents : [this.content]) {\n if (content && content.destroy) {\n content.destroy();\n }\n }\n this.contents = [];\n this.content = null;\n this.vectorContent = null;\n this.contentEntries = this.contentEntries.map(entry => ({\n ...entry,\n payload: null,\n renderable: false\n }));\n this.featureIdSets = this.contentEntries.flatMap(entry => entry.featureIds);\n if (this.header.content && this.header.content.destroy) {\n this.header.content.destroy();\n }\n this.header.content = null;\n this.contentState = TILE_CONTENT_STATE.UNLOADED;\n this.tileDrawn = true;\n return true;\n }\n\n /**\n * Update the tile's visibility\n * @param {Object} frameState - frame state for tile culling\n * @param {string[]} viewportIds - a list of viewport ids that show this tile\n * @return {void}\n */\n updateVisibility(frameState, viewportIds) {\n if (this._frameNumber === frameState.frameNumber) {\n // Return early if visibility has already been checked during the traversal.\n // The visibility may have already been checked if the cullWithChildrenBounds optimization is used.\n return;\n }\n\n const parent = this.parent;\n const parentVisibilityPlaneMask = parent\n ? parent._visibilityPlaneMask\n : CullingVolume.MASK_INDETERMINATE;\n\n if (this.tileset._traverser.options.updateTransforms) {\n const parentTransform = parent ? parent.computedTransform : this.tileset.modelMatrix;\n this._updateTransform(parentTransform);\n }\n\n this._distanceToCamera = this.distanceToTile(frameState);\n this._screenSpaceError = this.getScreenSpaceError(frameState, false);\n this._updateRequestPriorityMetrics(frameState);\n this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask); // Use parent's plane mask to speed up visibility test\n this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;\n this._inRequestVolume = this.insideViewerRequestVolume(frameState);\n\n this._frameNumber = frameState.frameNumber;\n this.viewportIds = viewportIds;\n }\n\n /**\n * Updates progressive-resolution and foveated request metrics for a 3D Tiles traversal frame.\n *\n * I3S retains its format-specific screen-threshold ordering and is explicitly isolated from\n * geometric-error scheduling. Orthographic viewports still receive progressive coverage, but\n * angular foveation is disabled because an orthographic frustum has no perspective field of view.\n *\n * @param frameState - Current camera and viewport measurements.\n */\n _updateRequestPriorityMetrics(frameState: FrameState): void {\n if (this.tileset.type !== TILESET_TYPE.TILES3D) {\n this._screenSpaceErrorProgressiveResolution = this._screenSpaceError;\n this._priorityProgressiveResolution = false;\n this._foveatedFactor = 0;\n this.priorityDeferred = false;\n return;\n }\n\n const options = this.tileset.options;\n const progressiveResolutionHeightFraction = options.progressiveResolutionHeightFraction;\n this._screenSpaceErrorProgressiveResolution = this.getScreenSpaceError(\n frameState,\n false,\n progressiveResolutionHeightFraction\n );\n this._priorityProgressiveResolution = isProgressiveResolutionPriority(\n this._screenSpaceErrorProgressiveResolution,\n this.parent?._screenSpaceErrorProgressiveResolution,\n this.tileset.memoryAdjustedScreenSpaceError,\n progressiveResolutionHeightFraction\n );\n\n if (\n !options.foveatedScreenSpaceError ||\n frameState.viewport?.orthographic ||\n !frameState.camera?.position ||\n !frameState.camera?.direction\n ) {\n this._foveatedFactor = 0;\n this.priorityDeferred = false;\n return;\n }\n\n this._foveatedFactor = calculateFoveatedFactor(this.boundingVolume, frameState.camera);\n const traverser = this.tileset._traverser;\n const skipLevelOfDetail =\n traverser.options.skipLevelOfDetail && !traverser.disableSkipLevelOfDetail;\n const deferralEligible = isFoveatedRequestDeferred({\n refinement: this.refine,\n skipLevelOfDetail,\n foveatedScreenSpaceError: options.foveatedScreenSpaceError,\n foveatedConeSize: options.foveatedConeSize,\n minimumScreenSpaceErrorRelaxation: options.foveatedMinimumScreenSpaceErrorRelaxation,\n interpolationCallback: options.foveatedInterpolationCallback,\n foveatedFactor: this._foveatedFactor,\n verticalFieldOfView: frameState.camera.verticalFieldOfView,\n screenSpaceError: this._screenSpaceError,\n parentScreenSpaceError: this.parent?._screenSpaceError,\n maximumScreenSpaceError: this.tileset.memoryAdjustedScreenSpaceError,\n priorityProgressiveResolution: this._priorityProgressiveResolution\n });\n this.priorityDeferred = isFoveatedRequestDelayActive(\n deferralEligible,\n frameState.camera.timeSinceMovement,\n options.foveatedTimeDelay\n );\n }\n\n // Determines whether the tile's bounding volume intersects the culling volume.\n // @param {FrameState} frameState The frame state.\n // @param {Number} parentVisibilityPlaneMask The parent's plane mask to speed up the visibility check.\n // @returns {Number} A plane mask as described above in {@link CullingVolume#computeVisibilityWithPlaneMask}.\n visibility(frameState, parentVisibilityPlaneMask) {\n const {cullingVolume} = frameState;\n const {boundingVolume} = this;\n\n // TODO Cesium specific - restore clippingPlanes\n // const {clippingPlanes, clippingPlanesOriginMatrix} = tileset;\n // if (clippingPlanes && clippingPlanes.enabled) {\n // const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(\n // boundingVolume,\n // clippingPlanesOriginMatrix\n // );\n // this._isClipped = intersection !== Intersect.INSIDE;\n // if (intersection === Intersect.OUTSIDE) {\n // return CullingVolume.MASK_OUTSIDE;\n // }\n // }\n\n // return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);\n return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);\n }\n\n /**\n * Determines whether renderable content intersects the view and configured clipping planes.\n *\n * Clipping planes are render-only constraints; traversal continues to use the tile volume.\n *\n * @param frameState Current camera, culling, and optional clipping-plane state.\n * @returns The content visibility classification.\n */\n contentVisibility(frameState: FrameState, contentIndex?: number): CullingResult {\n const contentVolumes =\n contentIndex === undefined\n ? this._contentBoundingVolumes\n : this._contentBoundingVolumes[contentIndex]\n ? [this._contentBoundingVolumes[contentIndex]]\n : [];\n return getContentVisibility(\n contentVolumes,\n this.boundingVolume,\n frameState.cullingVolume,\n this._visibilityPlaneMask,\n frameState.clippingPlanes\n );\n }\n\n /**\n * Computes the (potentially approximate) distance from the closest point of the tile's bounding volume to the camera.\n * @param frameState The frame state.\n * @returns {Number} The distance, in meters, or zero if the camera is inside the bounding volume.\n */\n distanceToTile(frameState: FrameState): number {\n const boundingVolume = this.boundingVolume;\n return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));\n }\n\n /**\n * Computes the tile's camera-space z-depth.\n * @param frameState The frame state.\n * @returns The distance, in meters.\n */\n cameraSpaceZDepth({camera}): number {\n const boundingVolume = this.boundingVolume; // Gets the underlying OrientedBoundingBox or BoundingSphere\n scratchVector.subVectors(boundingVolume.center, camera.position);\n return camera.direction.dot(scratchVector);\n }\n\n /**\n * Checks if the camera is inside the viewer request volume.\n * @param {FrameState} frameState The frame state.\n * @returns {Boolean} Whether the camera is inside the volume.\n */\n insideViewerRequestVolume(frameState: FrameState) {\n const viewerRequestVolume = this._viewerRequestVolume;\n return (\n !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0\n );\n }\n\n // TODO Cesium specific\n\n // Update whether the tile has expired.\n updateExpiration() {\n if (defined(this._expireDate) && this.contentReady && !this.hasEmptyContent) {\n const now = Date.now();\n // @ts-ignore Date.lessThan - replace with ms compare?\n if (Date.lessThan(this._expireDate, now)) {\n this.contentState = TILE_CONTENT_STATE.EXPIRED;\n this._expiredContent = this.content;\n }\n }\n }\n\n get extras() {\n return this.header.extras;\n }\n\n // INTERNAL METHODS\n\n /** Initializes the tile's LOD metric from its header or its nearest available ancestor. */\n _initializeLodMetric(header: {[key: string]: any}): void {\n this._scaleGeometricError =\n typeof header._scaleGeometricError === 'boolean'\n ? header._scaleGeometricError\n : (this.parent?._scaleGeometricError ?? true);\n if ('lodMetricType' in header) {\n this.lodMetricType = header.lodMetricType;\n } else {\n this.lodMetricType = (this.parent && this.parent.lodMetricType) || this.tileset.lodMetricType;\n // eslint-disable-next-line\n console.warn(`3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType`);\n }\n\n // This is used to compute screen space error, i.e., the error measured in pixels.\n if ('lodMetricValue' in header) {\n this._unscaledLodMetricValue = header.lodMetricValue;\n } else {\n // Inherit the source value, not the parent's world-space value. The child's complete\n // transform will be applied after transform initialization below.\n this._unscaledLodMetricValue = this.parent\n ? this.parent._unscaledLodMetricValue\n : this.tileset.lodMetricValue;\n // eslint-disable-next-line\n console.warn(\n '3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue'\n );\n }\n\n this.lodMetricValue = this._unscaledLodMetricValue;\n }\n\n _initializeTransforms(tileHeader) {\n // The local transform of this tile.\n this.transform = tileHeader.transform ? new Matrix4(tileHeader.transform) : new Matrix4();\n\n const parent = this.parent;\n const tileset = this.tileset;\n\n const parentTransform =\n parent && parent.computedTransform\n ? parent.computedTransform.clone()\n : tileset.modelMatrix.clone();\n this.computedTransform = new Matrix4(parentTransform).multiplyRight(this.transform);\n\n const parentInitialTransform =\n parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4();\n this._initialTransform = new Matrix4(parentInitialTransform).multiplyRight(this.transform);\n }\n\n /**\n * Updates the world-space LOD metric from the source metric and the complete tile transform.\n *\n * 3D Tiles geometric error is a distance in the tile's local meters. Screen-space error (SSE)\n * compares that distance with a world-space camera distance, so both quantities must use the\n * same scale. For non-uniform transforms the largest axis scale is deliberately used: this is\n * conservative and prevents refinement from stopping while any transformed dimension can still\n * exceed the requested visual error. Rotation and translation do not affect the scale.\n *\n * I3S `maxScreenThreshold` is already a screen-space metric and must not be transform-scaled.\n */\n _updateLodMetricScale(): void {\n if (this.lodMetricType !== LOD_METRIC_TYPE.GEOMETRIC_ERROR || !this._scaleGeometricError) {\n this.lodMetricValue = this._unscaledLodMetricValue;\n return;\n }\n\n const transformScale = this.computedTransform.getScale(scratchVector);\n const maximumScale = Math.max(transformScale[0], transformScale[1], transformScale[2]);\n this.lodMetricValue = this._unscaledLodMetricValue * maximumScale;\n }\n\n _initializeBoundingVolumes(tileHeader) {\n this._contentBoundingVolume = null;\n this._contentBoundingVolumeHeaders = [];\n this._viewerRequestVolume = null;\n\n this._updateBoundingVolume(tileHeader);\n }\n\n _initializeContent(tileHeader) {\n // Empty tile by default\n this.content = {_tileset: this.tileset, _tile: this};\n this.contents = [];\n this.hasEmptyContent = true;\n this.contentState = TILE_CONTENT_STATE.UNLOADED;\n\n // When `true`, the tile's content points to an external tileset.\n // This is `false` until the tile's content is loaded.\n this.hasTilesetContent = false;\n\n if (tileHeader.contentUrl || tileHeader.contentUrls?.length) {\n this.content = null;\n this.hasEmptyContent = false;\n }\n }\n\n // TODO - remove anything not related to basic visibility detection\n _initializeRenderingState(header) {\n this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);\n this._shouldRefine = false;\n\n // Members this are updated every frame for tree traversal and rendering optimizations:\n this._distanceToCamera = 0;\n this._centerZDepth = 0;\n this._screenSpaceError = 0;\n this._screenSpaceErrorProgressiveResolution = 0;\n this._priorityProgressiveResolution = false;\n this._foveatedFactor = 0;\n this.priorityDeferred = false;\n this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;\n this._visible = undefined;\n this._inRequestVolume = false;\n\n this._stackLength = 0;\n this._selectionDepth = 0;\n\n this._frameNumber = 0;\n this._touchedFrame = 0;\n this._visitedFrame = 0;\n this._selectedFrame = 0;\n this._requestedFrame = 0;\n\n this._priority = 0.0;\n }\n\n _getRefine(refine) {\n // Inherit from parent tile if omitted.\n return refine || (this.parent && this.parent.refine) || TILE_REFINEMENT.REPLACE;\n }\n\n /**\n * Returns whether loaded content is an external tileset.\n *\n * Parsed shape is authoritative because valid external resources may be extensionless, signed,\n * or use a misleading filename. This method is called only after source loading has populated\n * `content`.\n */\n _isTileset(): boolean {\n return (this.contents.length ? this.contents : [this.content]).some(\n content => content?.shape === 'tileset3d'\n );\n }\n\n _onContentLoaded() {\n // Vector and Geometry tile rendering do not support the skip LOD optimization.\n const contents = this.contents.length ? this.contents : [this.content];\n for (const content of contents) {\n switch (content && content.type) {\n case 'vctr':\n case 'geom':\n // @ts-ignore\n this.tileset._traverser.disableSkipLevelOfDetail = true;\n break;\n default:\n }\n }\n\n // The content may be tileset json\n if (this._isTileset()) {\n this.hasTilesetContent = true;\n } else {\n this.gpuMemoryUsageInBytes = this._getGpuMemoryUsageInBytes();\n }\n }\n\n _updateBoundingVolume(header) {\n this._boundingBox = undefined;\n // Update the bounding volumes\n this.boundingVolume = createBoundingVolume(\n header.boundingVolume,\n this.computedTransform,\n this.boundingVolume,\n this._initialTransform\n );\n\n // Viewer request volumes constrain traversal, not just render content. A contentless implicit\n // connector can still own an inherited request volume, so initialize it before the\n // content-specific early return below.\n if (header.viewerRequestVolume) {\n this._viewerRequestVolume = createBoundingVolume(\n header.viewerRequestVolume,\n this.computedTransform,\n this._viewerRequestVolume,\n this._initialTransform\n );\n }\n\n const content = header.content;\n if (content) {\n this._contentBoundingVolumeHeaders = Array.isArray(content) ? content : [content];\n }\n const contentHeaders = content\n ? Array.isArray(content)\n ? content\n : [content]\n : this._contentBoundingVolumeHeaders;\n // Preserve source order: an unbounded content entry uses the tile volume at its\n // corresponding index rather than being appended after bounded sibling entries.\n this._contentBoundingVolumes = contentHeaders.length\n ? contentHeaders.map(headerEntry =>\n headerEntry?.boundingVolume\n ? createBoundingVolume(\n headerEntry.boundingVolume,\n this.computedTransform,\n undefined,\n this._initialTransform\n )\n : this.boundingVolume\n )\n : [this.boundingVolume];\n this._contentBoundingVolume = this._contentBoundingVolumes[0] || null;\n }\n\n /**\n * Updates the tile's computed transform, world-space geometric error, and bounding volumes.\n * @param parentTransform - Current computed transform of the parent tile or tileset.\n */\n _updateTransform(parentTransform = new Matrix4()): void {\n const computedTransform = parentTransform.clone().multiplyRight(this.transform);\n const didTransformChange = !computedTransform.equals(this.computedTransform);\n\n if (!didTransformChange) {\n return;\n }\n\n this.computedTransform = computedTransform;\n\n // Recalculate from the unscaled source metric so repeated model-matrix changes never compound.\n this._updateLodMetricScale();\n this._updateBoundingVolume(this.header);\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Structural subset implemented by math.gl bounding volumes used by tile renderers. */\nexport type Tile3DBoundingVolume = {\n distanceSquaredTo?(point: unknown): number;\n intersectPlane?(plane: unknown): number;\n};\n\n/** Renderer-neutral description of one ordered tile content entry. */\nexport type Tile3DContent = {\n /** Zero-based source order, stable across loading and unloading. */\n index: number;\n /** Resolved content URI when declared by the tileset. */\n uri?: string;\n /** Tileset group index declared by this content entry. */\n group?: number;\n /** Normalized tile content kind, when detected. */\n type?: string;\n /** Decoded payload, or null while unloaded/failed. */\n payload: unknown;\n /** Raw content metadata reference. */\n metadata: Record<string, unknown> | null;\n /** Transformed content volume, with tile-volume fallback. */\n boundingVolume: Tile3DBoundingVolume | null;\n /** Normalized feature-id declarations for this content. */\n featureIds: Tile3DFeatureIdSet[];\n /** Whether the payload can currently be rendered. */\n renderable: boolean;\n};\n\n/** Renderer-neutral feature-id declaration from a tile content payload. */\nexport type Tile3DFeatureIdSet = {\n /** Source of the feature identifiers. */\n source: 'attribute' | 'property-table' | 'constant' | 'texture' | 'implicit';\n /** glTF attribute name for attribute-backed identifiers. */\n attribute?: string;\n /** Structural-metadata property-table index. */\n propertyTable?: number;\n /** Constant feature identifier. */\n constant?: number;\n /** Texture-backed identifier declaration, when present. */\n texture?: Record<string, unknown>;\n /** Implicit identifier declaration, when present. */\n implicit?: Record<string, unknown>;\n /** Decoded identifier values, when supplied by a content loader. */\n values?: Uint32Array | Uint16Array | Uint8Array;\n /** Unrecognized source fields preserved for forward compatibility. */\n details?: Record<string, unknown>;\n};\n\n/** Raw metadata references inherited by a tile and its contents. */\nexport type Tile3DMetadataContext = {\n /** Tileset-level metadata entity. */\n tileset?: Record<string, unknown> | null;\n /** Group metadata entity selected for the tile's primary content. */\n group?: Record<string, unknown> | null;\n /** All tileset groups, used to resolve a selected content entry's group. */\n groups?: readonly (Record<string, unknown> | null)[];\n /** Tile metadata entity. */\n tile?: Record<string, unknown> | null;\n /** Content metadata entity. */\n content?: Record<string, unknown> | null;\n /** Implicit-subtree metadata entity. */\n subtree?: Record<string, unknown> | null;\n};\n\n/** Extracts mesh-feature declarations from a decoded glTF-like payload. */\nexport function getTile3DFeatureIdSets(payload: unknown): Tile3DFeatureIdSet[] {\n const featureIdSets: Tile3DFeatureIdSet[] = [];\n const visited = new Set<object>();\n const visit = (value: unknown): void => {\n if (!value || typeof value !== 'object') {\n return;\n }\n if (visited.has(value as object)) {\n return;\n }\n visited.add(value as object);\n const record = value as Record<string, any>;\n const declarations = record.extensions?.EXT_mesh_features?.featureIds;\n if (Array.isArray(declarations)) {\n for (const declaration of declarations) {\n if (!declaration || typeof declaration !== 'object') {\n continue;\n }\n const source = declaration.texture\n ? 'texture'\n : declaration.implicit\n ? 'implicit'\n : declaration.attribute !== undefined\n ? 'attribute'\n : declaration.propertyTable !== undefined\n ? 'property-table'\n : 'constant';\n featureIdSets.push({\n source,\n attribute: declaration.attribute,\n propertyTable: declaration.propertyTable,\n constant: declaration.constant,\n texture: declaration.texture,\n implicit: declaration.implicit,\n values: declaration.values,\n details: declaration\n });\n }\n }\n for (const child of Object.values(record)) {\n visit(child);\n }\n };\n visit(payload);\n return featureIdSets;\n}\n", "// SPDX-License-Identifier: Apache-2.0\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\n/* eslint-disable */\nimport {Quaternion, Vector3, Matrix3, Matrix4, degrees} from '@math.gl/core';\nimport {BoundingSphere, OrientedBoundingBox} from '@math.gl/culling';\nimport {Ellipsoid, makeOBBFromRegion} from '@math.gl/geospatial';\nimport {assert} from '@loaders.gl/loader-utils';\n\n// const scratchProjectedBoundingSphere = new BoundingSphere();\n\nfunction defined(x) {\n return x !== undefined && x !== null;\n}\n\n// const scratchMatrix = new Matrix3();\nconst scratchPoint = new Vector3();\nconst scratchScale = new Vector3();\nconst identityTransform = new Matrix4();\n// const scratchRectangle = new Rectangle();\n// const scratchOrientedBoundingBox = new OrientedBoundingBox();\n// const scratchTransform = new Matrix4();\n\n/**\n * Create a bounding volume from the tile's bounding volume header.\n * @param {Object} boundingVolumeHeader The tile's bounding volume header.\n * @param {Matrix4} transform The current computed tile transform, including application transforms.\n * @param [result] The object onto which to store the result.\n * @param initialTransform The accumulated JSON tile transform, excluded from region transforms.\n * Defaults to transform so callers without application transforms keep geospatial regions fixed.\n * @returns The modified result parameter or a new TileBoundingVolume instance if none was provided.\n */\nexport function createBoundingVolume(\n boundingVolumeHeader,\n transform: Matrix4,\n result?,\n initialTransform: Matrix4 = transform\n) {\n assert(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');\n\n // boundingVolume schema:\n // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/schema/boundingVolume.schema.json\n if (boundingVolumeHeader.box) {\n // S2 cells and regions are geospatially anchored. Their conservative ECEF boxes are already\n // world-space volumes and must not receive the tile/node transform a second time.\n const boxTransform = boundingVolumeHeader.s2VolumeInfo ? identityTransform : transform;\n return createBox(boundingVolumeHeader.box, boxTransform, result);\n }\n if (boundingVolumeHeader.region) {\n const boundingVolume = makeOBBFromRegion(boundingVolumeHeader.region);\n // Regions are already in world coordinates. Apply only the change from the JSON transform.\n const regionTransform = transform.equals(initialTransform)\n ? identityTransform\n : transform.clone().multiplyRight(initialTransform.clone().invert());\n return createBox(\n [...boundingVolume.center, ...boundingVolume.halfAxes],\n regionTransform,\n result\n );\n }\n\n if (boundingVolumeHeader.sphere) {\n return createSphere(boundingVolumeHeader.sphere, transform, result);\n }\n\n throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');\n}\n\n/** [min, max] each in [longitude, latitude, altitude] */\nexport type CartographicBounds = [min: number[], max: number[]];\n\n/**\n * Calculate the cartographic bounding box the tile's bounding volume.\n * @param {Object} boundingVolumeHeader The tile's bounding volume header.\n * @param {BoundingVolume} boundingVolume The bounding volume.\n * @param isRegionTransformed Whether application transforms moved the region from its JSON bounds.\n * @returns {CartographicBounds}\n */\nexport function getCartographicBounds(\n boundingVolumeHeader,\n boundingVolume: OrientedBoundingBox | BoundingSphere,\n isRegionTransformed = false\n): CartographicBounds {\n // boundingVolume schema:\n // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/schema/boundingVolume.schema.json\n if (boundingVolumeHeader.box || (boundingVolumeHeader.region && isRegionTransformed)) {\n return orientedBoundingBoxToCartographicBounds(boundingVolume as OrientedBoundingBox);\n }\n if (boundingVolumeHeader.region) {\n // [west, south, east, north, minimum height, maximum height]\n // Latitudes and longitudes are in the WGS 84 datum as defined in EPSG 4979 and are in radians.\n // Heights are in meters above (or below) the WGS 84 ellipsoid.\n const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;\n\n return [\n [degrees(west), degrees(south), minHeight],\n [degrees(east), degrees(north), maxHeight]\n ];\n }\n\n if (boundingVolumeHeader.sphere) {\n return boundingSphereToCartographicBounds(boundingVolume as BoundingSphere);\n }\n\n throw new Error('Unkown boundingVolume type');\n}\n\nfunction createBox(box, transform, result?) {\n // https://math.gl/modules/culling/docs/api-reference/oriented-bounding-box\n // 1. A half-axes based representation.\n // box: An array of 12 numbers that define an oriented bounding box.\n // The first three elements define the x, y, and z values for the center of the box.\n // The next three elements (with indices 3, 4, and 5) define the x axis direction and half-length.\n // The next three elements (indices 6, 7, and 8) define the y axis direction and half-length.\n // The last three elements (indices 9, 10, and 11) define the z axis direction and half-length.\n // 2. A half-size-quaternion based representation.\n // box: An array of 10 numbers that define an oriented bounding box.\n // The first three elements define the x, y, and z values for the center of the box in a right-handed 3-axis (x, y, z) Cartesian coordinate system where the z-axis is up.\n // The next three elements (with indices 3, 4, and 5) define the halfSize.\n // The last four elements (indices 6, 7, 8 and 10) define the quaternion.\n const center = new Vector3(box[0], box[1], box[2]);\n transform.transform(center, center);\n let origin: number[] = [];\n if (box.length === 10) {\n const halfSize = box.slice(3, 6);\n const quaternion = new Quaternion();\n quaternion.fromArray(box, 6);\n const x = new Vector3([1, 0, 0]);\n const y = new Vector3([0, 1, 0]);\n const z = new Vector3([0, 0, 1]);\n x.transformByQuaternion(quaternion);\n x.scale(halfSize[0]);\n y.transformByQuaternion(quaternion);\n y.scale(halfSize[1]);\n z.transformByQuaternion(quaternion);\n z.scale(halfSize[2]);\n origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];\n } else {\n origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];\n }\n const xAxis = transform.transformAsVector(origin.slice(0, 3));\n const yAxis = transform.transformAsVector(origin.slice(3, 6));\n const zAxis = transform.transformAsVector(origin.slice(6, 9));\n const halfAxes = new Matrix3([\n xAxis[0],\n xAxis[1],\n xAxis[2],\n yAxis[0],\n yAxis[1],\n yAxis[2],\n zAxis[0],\n zAxis[1],\n zAxis[2]\n ]);\n\n if (defined(result)) {\n result.center = center;\n result.halfAxes = halfAxes;\n return result;\n }\n\n return new OrientedBoundingBox(center, halfAxes);\n}\n\nfunction createSphere(sphere, transform, result?) {\n // Find the transformed center\n const center = new Vector3(sphere[0], sphere[1], sphere[2]);\n transform.transform(center, center);\n const scale = transform.getScale(scratchScale);\n\n const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);\n const radius = sphere[3] * uniformScale;\n\n if (defined(result)) {\n result.center = center;\n result.radius = radius;\n return result;\n }\n\n return new BoundingSphere(center, radius);\n}\n\n/**\n * Convert a bounding volume defined by OrientedBoundingBox to cartographic bounds\n * @returns {CartographicBounds}\n */\nfunction orientedBoundingBoxToCartographicBounds(\n boundingVolume: OrientedBoundingBox\n): CartographicBounds {\n const result = emptyCartographicBounds();\n\n const {halfAxes} = boundingVolume as OrientedBoundingBox;\n const xAxis = new Vector3(halfAxes.getColumn(0));\n const yAxis = new Vector3(halfAxes.getColumn(1));\n const zAxis = new Vector3(halfAxes.getColumn(2));\n\n // Test all 8 corners of the box\n for (let x = 0; x < 2; x++) {\n for (let y = 0; y < 2; y++) {\n for (let z = 0; z < 2; z++) {\n scratchPoint.copy(boundingVolume.center);\n scratchPoint.add(xAxis);\n scratchPoint.add(yAxis);\n scratchPoint.add(zAxis);\n\n addToCartographicBounds(result, scratchPoint);\n zAxis.negate();\n }\n yAxis.negate();\n }\n xAxis.negate();\n }\n return result;\n}\n\n/**\n * Convert a bounding volume defined by BoundingSphere to cartographic bounds\n * @returns {CartographicBounds}\n */\nfunction boundingSphereToCartographicBounds(boundingVolume: BoundingSphere): CartographicBounds {\n const result = emptyCartographicBounds();\n\n const {center, radius} = boundingVolume as BoundingSphere;\n const point = Ellipsoid.WGS84.scaleToGeodeticSurface(center, scratchPoint);\n\n let zAxis: Vector3;\n if (point) {\n zAxis = Ellipsoid.WGS84.geodeticSurfaceNormal(point) as Vector3;\n } else {\n zAxis = new Vector3(0, 0, 1);\n }\n let xAxis = new Vector3(zAxis[2], -zAxis[1], 0);\n if (xAxis.len() > 0) {\n xAxis.normalize();\n } else {\n xAxis = new Vector3(0, 1, 0);\n }\n const yAxis = xAxis.clone().cross(zAxis);\n\n // Test 6 end points of the 3 axes\n for (const axis of [xAxis, yAxis, zAxis]) {\n scratchScale.copy(axis).scale(radius);\n for (let dir = 0; dir < 2; dir++) {\n scratchPoint.copy(center);\n scratchPoint.add(scratchScale);\n addToCartographicBounds(result, scratchPoint);\n // Flip the axis\n scratchScale.negate();\n }\n }\n return result;\n}\n\n/**\n * Create a new cartographic bounds that contains no points\n * @returns {CartographicBounds}\n */\nfunction emptyCartographicBounds(): CartographicBounds {\n return [\n [Infinity, Infinity, Infinity],\n [-Infinity, -Infinity, -Infinity]\n ];\n}\n\n/**\n * Add a point to the target cartographic bounds\n * @param {CartographicBounds} target\n * @param {Vector3} cartesian coordinates of the point to add\n */\nfunction addToCartographicBounds(target: CartographicBounds, cartesian: Readonly<Vector3>) {\n Ellipsoid.WGS84.cartesianToCartographic(cartesian, scratchPoint);\n target[0][0] = Math.min(target[0][0], scratchPoint[0]);\n target[0][1] = Math.min(target[0][1], scratchPoint[1]);\n target[0][2] = Math.min(target[0][2], scratchPoint[2]);\n\n target[1][0] = Math.max(target[1][0], scratchPoint[0]);\n target[1][1] = Math.max(target[1][1], scratchPoint[1]);\n target[1][2] = Math.max(target[1][2], scratchPoint[2]);\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Tile3D} from '../common/tile-3d';\nimport {FrameState} from './frame-state';\n\nconst cameraPositionCartesian = new Vector3();\nconst toEye = new Vector3();\nconst cameraPositionEnu = new Vector3();\nconst extraVertexEnu = new Vector3();\nconst projectedOriginVector = new Vector3();\nconst enuToCartesianMatrix = new Matrix4();\nconst cartesianToEnuMatrix = new Matrix4();\n\n/**\n * For the maxScreenThreshold error metric, maxError means that you should replace the node with it's children\n as soon as the nodes bounding sphere has a screen radius larger than maxError pixels.\n In this sense a value of 0 means you should always load it's children,\n or if it's a leaf node, you should always display it.\n * @param tile \n * @param frameState \n * @returns \n */\nexport function getLodStatus(tile: Tile3D, frameState: FrameState): 'DIG' | 'OUT' | 'DRAW' {\n if (tile.lodMetricValue === 0 || Number.isNaN(tile.lodMetricValue)) {\n return 'DIG';\n }\n const screenSize = 2 * getProjectedRadius(tile, frameState);\n if (screenSize < 2) {\n return 'OUT';\n }\n if (!tile.header.children) {\n return 'DRAW';\n }\n\n switch (tile.lodMetricType) {\n case 'screenSpaceRelative': {\n const viewportHeight = frameState.topDownViewport.height || 1;\n return screenSize / viewportHeight <= tile.lodMetricValue ? 'DRAW' : 'DIG';\n }\n case 'distanceRangeFromDefaultCamera':\n return tile.distanceToTile(frameState) >= tile.lodMetricValue ? 'DRAW' : 'DIG';\n case 'maxScreenThresholdSQ': {\n const diameterThreshold = Math.sqrt(tile.lodMetricValue / (Math.PI * 0.25));\n return screenSize <= diameterThreshold ? 'DRAW' : 'DIG';\n }\n case 'maxScreenThreshold':\n default:\n return screenSize <= tile.lodMetricValue ? 'DRAW' : 'DIG';\n }\n}\n\n/**\n * Calculate size of MBS radius projected on the screen plane\n * @param tile\n * @param frameState\n * @returns\n */\n// eslint-disable-next-line max-statements\nexport function getProjectedRadius(tile: Tile3D, frameState: FrameState): number {\n const {topDownViewport: viewport} = frameState;\n const mbs = tile.header.i3sLodMbs || tile.header.mbs;\n const mbsLat = mbs[1];\n const mbsLon = mbs[0];\n const mbsZ = mbs[2];\n const mbsR = mbs[3];\n const mbsCenterCartesian = [...tile.boundingVolume.center];\n const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);\n Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, cameraPositionCartesian);\n\n // ---------------------------\n // Calculate mbs border vertex\n // ---------------------------\n toEye.copy(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();\n // Add extra vector to form plane\n Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);\n cartesianToEnuMatrix.copy(enuToCartesianMatrix).invert();\n cameraPositionEnu.copy(cameraPositionCartesian).transform(cartesianToEnuMatrix);\n // Mean Proportionals in Right Triangles - Altitude rule\n // https://mathbitsnotebook.com/Geometry/RightTriangles/RTmeanRight.html\n const projection = Math.sqrt(\n cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]\n );\n const extraZ = (projection * projection) / cameraPositionEnu[2];\n extraVertexEnu.copy([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);\n const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);\n const extraVectorCartesian = extraVertexCartesian.subtract(mbsCenterCartesian).normalize();\n // We need radius vector orthogonal to toEye vector\n const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);\n const sphereMbsBorderVertexCartesian = radiusVector.add(mbsCenterCartesian);\n const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(\n sphereMbsBorderVertexCartesian\n );\n // ---------------------------\n\n // Project center vertex and border vertex and calculate projected radius of MBS\n const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);\n const projectedMbsBorderVertex = viewport.project(\n sphereMbsBorderVertexCartographic as [number, number, number]\n );\n const projectedRadius = projectedOriginVector\n .copy(projectedOrigin)\n .subtract(projectedMbsBorderVertex)\n .magnitude();\n return projectedRadius;\n}\n", "// SPDX-License-Identifier: Apache-2.0\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {assert} from '@loaders.gl/loader-utils';\n\n/**\n * A wrapper around arrays so that the internal length of the array can be manually managed.\n *\n * @alias ManagedArray\n * @constructor\n * @private\n *\n * @param {Number} [length=0] The initial length of the array.\n */\nexport class ManagedArray {\n _map = new Map();\n _array: any[];\n _length: number;\n\n constructor(length = 0) {\n this._array = new Array(length);\n this._length = length;\n }\n\n /**\n * Gets or sets the length of the array.\n * If the set length is greater than the length of the internal array, the internal array is resized.\n *\n * @memberof ManagedArray.prototype\n * @type Number\n */\n get length() {\n return this._length;\n }\n\n set length(length) {\n this._length = length;\n if (length > this._array.length) {\n this._array.length = length;\n }\n }\n\n /**\n * Gets the internal array.\n *\n * @memberof ManagedArray.prototype\n * @type Array\n * @readonly\n */\n get values() {\n return this._array;\n }\n\n /**\n * Gets the element at an index.\n *\n * @param {Number} index The index to get.\n */\n get(index) {\n assert(index < this._array.length);\n return this._array[index];\n }\n\n /**\n * Sets the element at an index. Resizes the array if index is greater than the length of the array.\n *\n * @param {Number} index The index to set.\n * @param {*} element The element to set at index.\n */\n set(index, element) {\n assert(index >= 0);\n\n if (index >= this.length) {\n this.length = index + 1;\n }\n\n if (this._map.has(this._array[index])) {\n this._map.delete(this._array[index]);\n }\n\n this._array[index] = element;\n this._map.set(element, index);\n }\n\n delete(element) {\n const index = this._map.get(element);\n if (index >= 0) {\n this._array.splice(index, 1);\n this._map.delete(element);\n this.length--;\n }\n }\n\n /**\n * Returns the last element in the array without modifying the array.\n *\n * @returns {*} The last element in the array.\n */\n peek() {\n return this._array[this._length - 1];\n }\n\n /**\n * Push an element into the array.\n *\n * @param {*} element The element to push.\n */\n push(element) {\n if (!this._map.has(element)) {\n const index = this.length++;\n this._array[index] = element;\n this._map.set(element, index);\n }\n }\n\n /**\n * Pop an element from the array.\n *\n * @returns {*} The last element in the array.\n */\n pop() {\n const element = this._array[--this.length];\n this._map.delete(element);\n return element;\n }\n\n /**\n * Resize the internal array if length > _array.length.\n *\n * @param {Number} length The length.\n */\n reserve(length) {\n assert(length >= 0);\n\n if (length > this._array.length) {\n this._array.length = length;\n }\n }\n\n /**\n * Resize the array.\n *\n * @param {Number} length The length.\n */\n resize(length) {\n assert(length >= 0);\n\n this.length = length;\n }\n\n /**\n * Trim the internal array to the specified length. Defaults to the current length.\n *\n * @param {Number} [length] The length.\n */\n trim(length) {\n if (length === null || length === undefined) {\n length = this.length;\n }\n this._array.length = length;\n }\n\n reset() {\n this._array = [];\n this._map = new Map();\n this._length = 0;\n }\n\n find(target) {\n return this._map.has(target);\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Tile3D} from './tile-3d';\nimport {ManagedArray} from '../../utils/managed-array';\nimport {TILE_REFINEMENT} from '../../constants';\nimport {FrameState} from '../helpers/frame-state';\n\nexport type TilesetTraverserProps = {\n loadSiblings?: boolean;\n skipLevelOfDetail?: boolean;\n /** SSE above which tiles remain part of the non-skipping base traversal. */\n baseScreenSpaceError?: number;\n /** Required SSE reduction from the nearest requested or loaded ancestor before loading a tile. */\n skipScreenSpaceErrorFactor?: number;\n /** Minimum hierarchy levels between requested tiles during skip-LOD traversal. */\n skipLevels?: number;\n /** Requests only final tiles that meet the active SSE target when skip-LOD is enabled. */\n immediatelyLoadDesiredLevelOfDetail?: boolean;\n updateTransforms?: boolean;\n onTraversalEnd?: (frameState) => any;\n viewportTraversersMap?: Record<string, any>;\n basePath?: string;\n};\n\nexport const DEFAULT_PROPS: Required<TilesetTraverserProps> = {\n loadSiblings: false,\n skipLevelOfDetail: false,\n baseScreenSpaceError: 1024,\n skipScreenSpaceErrorFactor: 16,\n skipLevels: 1,\n immediatelyLoadDesiredLevelOfDetail: false,\n updateTransforms: true,\n onTraversalEnd: () => {},\n viewportTraversersMap: {},\n basePath: ''\n};\n\nexport class TilesetTraverser {\n options: Required<TilesetTraverserProps>;\n\n /** Whether loaded content has disabled skip-LOD traversal for this tileset. */\n disableSkipLevelOfDetail: boolean = false;\n\n // fulfill in traverse call\n root: any = null;\n\n // tiles should be rendered\n selectedTiles: Record<string, Tile3D> = {};\n // tiles should be loaded from server\n requestedTiles: Record<string, Tile3D> = {};\n /** Tiles intentionally held until the camera has remained still for the configured delay. */\n deferredTiles: Record<string, Tile3D> = {};\n // tiles does not have render content\n emptyTiles: Record<string, Tile3D> = {};\n\n protected lastUpdate: number = new Date().getTime();\n protected readonly updateDebounceTime = 1000;\n /** temporary storage to hold the traversed tiles during a traversal */\n protected _traversalStack = new ManagedArray();\n protected _emptyTraversalStack = new ManagedArray();\n /** set in every traverse cycle */\n protected _frameNumber: number | null = null;\n\n // RESULT\n protected traversalFinished(frameState: FrameState): boolean {\n return true;\n }\n\n // TODO nested props\n constructor(options: TilesetTraverserProps) {\n this.options = {...DEFAULT_PROPS, ...options};\n }\n\n /** Returns whether skip-LOD traversal is enabled and supported by the loaded content. */\n isSkipLevelOfDetailEnabled(): boolean {\n return this.options.skipLevelOfDetail && !this.disableSkipLevelOfDetail;\n }\n\n // tiles should be visible\n traverse(root, frameState, options) {\n this.root = root; // for root screen space error\n this.options = {...this.options, ...options};\n\n // reset result\n this.reset();\n\n // update tile (visibility and expiration)\n this.updateTile(root, frameState);\n\n this._frameNumber = frameState.frameNumber;\n this.executeTraversal(root, frameState);\n }\n\n reset() {\n this.requestedTiles = {};\n this.deferredTiles = {};\n this.selectedTiles = {};\n this.emptyTiles = {};\n this._traversalStack.reset();\n this._emptyTraversalStack.reset();\n }\n\n /**\n * Execute traverse\n * Depth-first traversal that traverses all visible tiles and marks tiles for selection.\n * If skipLevelOfDetail is off then a tile does not refine until all children are loaded.\n * This is the traditional replacement refinement approach and is called the base traversal.\n * Tiles that have a greater screen space error than the base screen space error are part of the base traversal,\n * all other tiles are part of the skip traversal. The skip traversal allows for skipping levels of the tree\n * and rendering children and parent tiles simultaneously.\n */\n /* eslint-disable-next-line complexity, max-statements */\n executeTraversal(root, frameState: FrameState): void {\n // stack to store traversed tiles, only visible tiles should be added to stack\n // visible: visible in the current view frustum\n const stack = this._traversalStack;\n root._selectionDepth = 1;\n\n stack.push(root);\n while (stack.length > 0) {\n // 1. pop tile\n const tile = stack.pop();\n\n // 2. check if tile needs to be refine, needs refine if a tile's LoD is not sufficient and tile has available children (available content)\n let shouldRefine = false;\n if (this.canTraverse(tile, frameState)) {\n this.updateChildTiles(tile, frameState);\n shouldRefine = this.updateAndPushChildren(\n tile,\n frameState,\n stack,\n tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth\n );\n }\n\n // 3. decide if should render (select) this tile\n // - tile does not have render content\n // - tile has render content and tile is `add` type (pointcloud)\n // - tile has render content and tile is `replace` type (photogrammetry) and can't refine any further\n const parent = tile.parent;\n const parentRefines = Boolean(!parent || parent._shouldRefine);\n const stoppedRefining = !shouldRefine;\n\n if (!tile.hasRenderContent) {\n this.emptyTiles[tile.id] = tile;\n this.loadTile(tile, frameState);\n if (stoppedRefining) {\n this.selectTile(tile, frameState);\n }\n // additive tiles\n } else if (tile.refine === TILE_REFINEMENT.ADD) {\n // Additive tiles are always loaded and selected\n this.loadTile(tile, frameState);\n this.selectTile(tile, frameState);\n\n // replace tiles\n } else if (tile.refine === TILE_REFINEMENT.REPLACE) {\n // Always load tiles in the base traversal\n // Select tiles that can't refine further\n this.loadTile(tile, frameState);\n // Skip-LOD keeps a ready ancestor selected while descendants stream in. This prevents\n // replacement holes when traversal jumps over one or more hierarchy levels.\n if (stoppedRefining || this.isSkipLevelOfDetailEnabled()) {\n this.selectTile(tile, frameState);\n }\n }\n\n // 3. update cache, most recent touched tiles have higher priority to be fetched from server\n this.touchTile(tile, frameState);\n\n // 4. update tile refine prop and parent refinement status to trickle down to the descendants\n tile._shouldRefine = shouldRefine && parentRefines;\n }\n\n this.completeTraversal(frameState);\n }\n\n /** Notifies the owning tileset when traversal is complete or its debounce interval expires. */\n protected completeTraversal(frameState: FrameState): void {\n const newTime = new Date().getTime();\n if (this.traversalFinished(frameState) || newTime - this.lastUpdate > this.updateDebounceTime) {\n this.lastUpdate = newTime;\n this.options.onTraversalEnd(frameState);\n }\n }\n\n updateChildTiles(tile: Tile3D, frameState: FrameState): void {\n const children = tile.children;\n for (const child of children) {\n this.updateTile(child, frameState);\n }\n }\n\n /* eslint-disable complexity, max-statements */\n updateAndPushChildren(tile: Tile3D, frameState: FrameState, stack, depth): boolean {\n const {loadSiblings} = this.options;\n const skipLevelOfDetail = this.isSkipLevelOfDetailEnabled();\n\n const children = tile.children;\n\n // sort children tiles\n children.sort(this.compareDistanceToCamera.bind(this));\n\n // For traditional replacement refinement only refine if all children are loaded.\n // Empty tiles are exempt since it looks better if children stream in as they are loaded to fill the empty space.\n const checkRefines =\n tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;\n\n let hasVisibleChild = false;\n let refines = true;\n\n for (const child of children) {\n child._selectionDepth = depth;\n if (child.isVisibleAndInRequestVolume) {\n if (stack.find(child)) {\n stack.delete(child);\n }\n stack.push(child);\n hasVisibleChild = true;\n } else if ((checkRefines || loadSiblings) && child._inRequestVolume) {\n // Keep non-visible children loaded when they are inside their viewer request volume;\n // they may still be needed before a replacement parent can refine. The request-volume\n // check intentionally applies to sibling loading as well, preventing off-volume work.\n this.loadTile(child, frameState);\n this.touchTile(child, frameState);\n }\n\n if (checkRefines) {\n let childRefines;\n if (!child._inRequestVolume) {\n childRefines = false;\n } else if (!child.hasRenderContent) {\n childRefines = this.executeEmptyTraversal(child, frameState);\n } else {\n childRefines = child.contentAvailable;\n }\n // Readiness controls replacement, not discovery. Visit every sibling so\n // one unavailable child cannot serialize requests or hide ready siblings.\n refines = refines && childRefines;\n }\n }\n\n if (!hasVisibleChild) {\n refines = false;\n }\n return refines;\n }\n /* eslint-enable complexity, max-statements */\n\n updateTile(tile: Tile3D, frameState: FrameState): void {\n this.updateTileVisibility(tile, frameState);\n }\n\n // tile to render in the browser\n selectTile(tile: Tile3D, frameState: FrameState): void {\n if (this.shouldSelectTile(tile, frameState)) {\n // The tile can be selected right away and does not require traverseAndSelect\n tile._selectedFrame = frameState.frameNumber;\n this.selectedTiles[tile.id] = tile;\n }\n }\n\n // tile to load from server\n loadTile(tile: Tile3D, frameState: FrameState): void {\n if (this.shouldLoadTile(tile)) {\n if (this.shouldDeferTileRequest(tile)) {\n this.deferredTiles[tile.id] = tile;\n return;\n }\n tile._requestedFrame = frameState.frameNumber;\n tile._priority = tile._getPriority();\n this.requestedTiles[tile.id] = tile;\n }\n }\n\n /**\n * Returns whether an eligible peripheral request should wait for camera motion to settle.\n *\n * Eligibility and the current time window are calculated together when tile visibility updates.\n * Keeping the active state on the tile also lets a queued scheduler callback cancel work that\n * became deferred after its original traversal.\n *\n * @param tile - Tile considered for loading.\n * @returns `true` when the request should be retried after the remaining delay.\n */\n shouldDeferTileRequest(tile: Tile3D): boolean {\n return tile.priorityDeferred;\n }\n\n // cache tile\n touchTile(tile: Tile3D, frameState: FrameState): void {\n tile.tileset._cache.touch(tile);\n tile._touchedFrame = frameState.frameNumber;\n }\n\n // tile should be visible\n // tile should have children\n // tile LoD (level of detail) is not sufficient under current viewport\n canTraverse(tile: Tile3D, frameState: FrameState): boolean {\n if (!tile.hasChildren) {\n return false;\n }\n\n // cesium specific\n if (tile.hasTilesetContent) {\n // Traverse external this to visit its root tile\n // Don't traverse if the subtree is expired because it will be destroyed\n return !tile.contentExpired;\n }\n\n return this.shouldRefine(tile, frameState);\n }\n\n shouldLoadTile(tile: Tile3D): boolean {\n // if request tile is in current frame\n // and has unexpired render content\n return tile.hasUnloadedContent || tile.contentExpired;\n }\n\n /**\n * Returns whether a tile's content is available and visible for rendering.\n * @param tile Tile considered for rendering.\n * @param frameState Current culling state.\n */\n shouldSelectTile(tile: Tile3D, frameState: FrameState): boolean {\n return tile.contentAvailable && tile.contentVisibility(frameState) !== 'outside';\n }\n\n /** Decide if tile LoD (level of detail) is not sufficient under current viewport */\n shouldRefine(tile: Tile3D, frameState: FrameState, useParentMetric: boolean = false): boolean {\n let screenSpaceError = tile._screenSpaceError;\n if (useParentMetric) {\n screenSpaceError = tile.getScreenSpaceError(frameState, true);\n }\n\n return screenSpaceError > tile.tileset.memoryAdjustedScreenSpaceError;\n }\n\n updateTileVisibility(tile: Tile3D, frameState: FrameState): void {\n const viewportIds: string[] = [];\n if (this.options.viewportTraversersMap) {\n for (const key in this.options.viewportTraversersMap) {\n const value = this.options.viewportTraversersMap[key];\n if (value === frameState.viewport.id) {\n viewportIds.push(key);\n }\n }\n } else {\n viewportIds.push(frameState.viewport.id);\n }\n tile.updateVisibility(frameState, viewportIds);\n }\n\n // UTILITIES\n\n compareDistanceToCamera(b: Tile3D, a: Tile3D): number {\n return b._distanceToCamera - a._distanceToCamera;\n }\n\n anyChildrenVisible(tile: Tile3D, frameState: FrameState): boolean {\n let anyVisible = false;\n for (const child of tile.children) {\n // @ts-expect-error\n child.updateVisibility(frameState);\n // @ts-expect-error\n anyVisible = anyVisible || child.isVisibleAndInRequestVolume;\n }\n return anyVisible;\n }\n\n // Depth-first traversal that checks if all nearest descendants with content are loaded.\n // Ignores visibility.\n executeEmptyTraversal(root: Tile3D, frameState: FrameState): boolean {\n let allDescendantsLoaded = true;\n let hasPendingLazyChildren = false;\n const stack = this._emptyTraversalStack;\n stack.push(root);\n\n while (stack.length > 0) {\n const tile = stack.pop();\n\n const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState);\n const emptyLeaf = !tile.hasRenderContent && tile.children.length === 0;\n if (tile.header.implicitSubtree) {\n // An unresolved implicit boundary is not a proven empty leaf. Treating it as loaded would\n // allow REPLACE traversal to drop its ancestor before availability and content are known.\n hasPendingLazyChildren = true;\n allDescendantsLoaded = false;\n }\n\n // Traversal stops but the tile does not have content yet\n // There will be holes if the parent tries to refine to its children, so don't refine\n // One exception: a parent may refine even if one of its descendants is an empty leaf\n if (!traverse && !tile.contentAvailable && !emptyLeaf) {\n allDescendantsLoaded = false;\n }\n\n this.updateTile(tile, frameState);\n\n if (!tile.isVisibleAndInRequestVolume) {\n this.loadTile(tile, frameState);\n this.touchTile(tile, frameState);\n }\n\n if (traverse) {\n const children = tile.children;\n for (const child of children) {\n stack.push(child);\n }\n }\n }\n return (root.hasEmptyContent && !hasPendingLazyChildren) || allDescendantsLoaded;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {path, RequestCache, sliceArrayBuffer} from '@loaders.gl/loader-utils';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Matrix4, Vector3} from '@math.gl/core';\nimport type {CoreAPI, Loader, LoaderContext, LoaderOptions} from '@loaders.gl/loader-utils';\nimport type {Tile3D} from '../common/tile-3d';\nimport {Tileset3DTraverser} from './tileset-3d-traverser';\nimport type {Tileset3D} from '../common/tileset-3d';\nimport type {\n TileChildrenLoadResult,\n TileContentLoadResult,\n TilesetContentFormats,\n TilesetJSON,\n Tileset3DSource,\n TilesetSourceInput,\n TilesetSourceMetadata,\n TilesetSourceRequest,\n TilesetSourceResolver,\n TilesetSourceViewState\n} from '../common/tileset-source';\nimport {Tile3D as Tile3DNode} from '../common/tile-3d';\nimport {getZoomFromBoundingVolume} from '../helpers/zoom';\nimport {TILESET_TYPE} from '../../constants';\nimport type {TilesetTraverser, TilesetTraverserProps} from '../common/tileset-traverser';\nimport type {FrameState} from '../helpers/frame-state';\nimport {get3DTilesSpatialReference} from '../../spatial/format-spatial-reference';\nimport {Tiles3DSpatialTransformer} from '../../spatial/tiles-3d-spatial-transformer';\nimport {\n applyTilesetSpatialOptions,\n markTilesetSpatialReferenceTransformed\n} from '../../spatial/spatial-types';\nimport type {TilesetSpatialReference} from '../../spatial/spatial-types';\nimport {\n materializeImplicitSubtree,\n type ImplicitSubtreeReference,\n type ParsedImplicitSubtree\n} from './implicit-tiling';\n\nconst EMPTY_CONTENT_FORMATS: TilesetContentFormats = {\n draco: false,\n meshopt: false,\n dds: false,\n ktx2: false\n};\n\nconst DEFAULT_MAXIMUM_CACHED_SUBTREES = 32;\n\ntype PackageFile = {\n name?: string;\n mimeType: string;\n uri?: string;\n originalUri?: string;\n data?: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n bufferUri?: string;\n};\n\ntype PackageResource = {fileIndex: number; files: PackageFile[]};\n\ntype Tiles3DPackageLoaderContext = LoaderContext & {\n /** Parent package records available while parsing an embedded tileset or subtree. */\n _tiles3dPackageFiles: PackageFile[];\n};\n\n/** Diagnostics for source-managed implicit subtree loading. */\nexport type ImplicitTilingStats = {\n /** Subtree resources requested from the resolver or core API. */\n requestedSubtrees: number;\n /** Successful subtree materializations, including parsed-cache hits. */\n loadedSubtrees: number;\n /** Requests served by the source's parsed-subtree cache. */\n cacheHits: number;\n /** Parsed subtree resources currently retained for reuse. */\n cachedSubtrees: number;\n /** Subtree resource requests currently in flight. */\n pendingSubtrees: number;\n /** Runtime headers created below already-existing subtree-root placeholders. */\n materializedTiles: number;\n};\n\n/**\n * {@link Tileset3DSource} implementation for 3D Tiles datasets.\n */\nexport class Tiles3DSource implements Tileset3DSource {\n /** 3D Tiles format discriminator. */\n readonly type = TILESET_TYPE.TILES3D;\n /** Loader used for tile content requests. */\n readonly loader: Loader;\n /** Root tileset URL. */\n readonly url: string;\n /** Base path used for relative tile resource resolution. */\n readonly basePath: string;\n /** Parsed root tileset payload. */\n tileset: TilesetJSON | null = null;\n /** Loader options forwarded to content requests. */\n readonly loadOptions: LoaderOptions;\n /** Core API used for root and tile-content loads when injected by the caller. */\n coreApi?: CoreAPI;\n /** Aggregate content-format flags discovered during streaming. */\n readonly contentFormats: TilesetContentFormats = {...EMPTY_CONTENT_FORMATS};\n\n /** Top-level 3D Tiles asset metadata. */\n asset?: Record<string, any>;\n /** Top-level per-feature properties metadata. */\n properties?: any;\n /** Top-level application-specific metadata. */\n extras?: any;\n /** Source-provided attribution metadata. */\n credits?: any;\n /** Normalized source metadata after initialization. */\n metadata?: TilesetSourceMetadata;\n\n private readonly queryParams: Record<string, string> = {};\n /** Final request URLs cached by unmodified tile content URL. */\n private readonly tileUrlCache: Map<string, string> = new Map();\n /** Original content descriptors retained across {@link Tile3D.unloadContent} calls. */\n private readonly tileContentHeaders = new WeakMap<Tile3D, Record<string, any>[]>();\n /** Installed nested roots by parent placement and ordered nested-content slot, across reloads. */\n private readonly nestedTilesetRoots = new WeakMap<Tile3D, Tile3D[]>();\n /** Source-local namespaces assigned to distinct embedded glTF package file collections. */\n private readonly packageNamespaces = new WeakMap<PackageFile[], number>();\n /** Next source-local package namespace. */\n private nextPackageNamespace = 0;\n /** Parsed subtree requests keyed by final source URL for deduplication and LRU reuse. */\n private readonly implicitSubtreeCache: RequestCache<ParsedImplicitSubtree>;\n /** Mutable counters exposed as a defensive snapshot through {@link getImplicitTilingStats}. */\n private readonly implicitTilingStats: Omit<\n ImplicitTilingStats,\n 'cachedSubtrees' | 'pendingSubtrees'\n > = {\n requestedSubtrees: 0,\n loadedSubtrees: 0,\n cacheHits: 0,\n materializedTiles: 0\n };\n /** Whether the owning tileset has released this source. */\n private destroyed = false;\n private readonly extensionsUsed: string[] = [];\n private readonly resolver?: TilesetSourceResolver;\n private rootTileset: TilesetJSON;\n /** CRS transformer shared by this source's headers and decoded glTF content. */\n private spatialTransformer?: Tiles3DSpatialTransformer;\n /** Root header after composing source-frame transforms and rebuilding target bounds. */\n private preparedRootHeader?: Record<string, any>;\n\n /**\n * Creates a 3D Tiles source.\n * @param input Root metadata request, or preloaded root metadata for tests and internal callers.\n * @param loadOptions Loader options forwarded to tile requests.\n */\n constructor(input: TilesetSourceInput, loadOptions: LoaderOptions = {}) {\n const request = normalizeTiles3DRequest(input);\n this.rootTileset = isTilesetRequest(input) ? null : input;\n this.tileset = this.rootTileset;\n this.loader = request.loader;\n this.url = request.url;\n this.basePath = request.basePath || path.dirname(request.url);\n this.resolver = request.resolver;\n this.coreApi = request.coreApi;\n this.loadOptions = loadOptions;\n const maximumCachedSubtrees = Number(\n (loadOptions['3d-tiles'] as Record<string, unknown> | undefined)?.maximumCachedSubtrees\n );\n const maximumCacheEntries = Number.isFinite(maximumCachedSubtrees)\n ? Math.max(0, Math.floor(maximumCachedSubtrees))\n : DEFAULT_MAXIMUM_CACHED_SUBTREES;\n this.implicitSubtreeCache = new RequestCache({maxEntries: maximumCacheEntries});\n }\n\n /**\n * Releases URL and parsed-subtree caches and blocks late subtree installation.\n *\n * The injected resolver or core API remains responsible for transport-level abort signals. A\n * request that cannot be aborted may finish parsing, but it will not mutate destroyed tiles.\n */\n destroy(): void {\n this.destroyed = true;\n this.tileUrlCache.clear();\n this.implicitSubtreeCache.clear();\n }\n\n /**\n * Fetches and validates top-level metadata, then normalizes common fields used by {@link Tileset3D}.\n */\n async initialize(): Promise<void> {\n if (!this.rootTileset) {\n const loaderOptions = (this.loadOptions[this.loader.id] as Record<string, unknown>) || {};\n this.rootTileset = await this.loadRootData(this.url, {\n ...this.loadOptions,\n [this.loader.id]: {\n ...loaderOptions,\n isTileset: true\n }\n });\n }\n this.tileset = this.rootTileset;\n\n if (this.rootTileset.queryString) {\n const searchParams = new URLSearchParams(this.rootTileset.queryString);\n for (const [parameterName, parameterValue] of searchParams.entries()) {\n this.setQueryParameter(parameterName, parameterValue);\n }\n }\n\n this.asset = this.rootTileset.asset;\n if (!this.asset) {\n throw new Error('Tileset must have an asset property.');\n }\n if (\n this.rootTileset.formatVersion !== '2.0-draft' &&\n this.asset.version !== '0.0' &&\n this.asset.version !== '1.0' &&\n this.asset.version !== '1.1'\n ) {\n throw new Error('The tileset must be 3D Tiles version 0.0, 1.0, 1.1, or 2.0-draft.');\n }\n\n if ('tilesetVersion' in this.asset) {\n this.setQueryParameter('v', this.asset.tilesetVersion);\n }\n\n this.properties = this.rootTileset.properties;\n this.extras = this.rootTileset.extras;\n this.credits = {attributions: []};\n this.extensionsUsed.splice(\n 0,\n this.extensionsUsed.length,\n ...(this.rootTileset.extensionsUsed || [])\n );\n this.metadata = {\n type: this.type,\n loader: this.loader,\n url: this.url,\n basePath: this.basePath,\n tileset: this.rootTileset,\n lodMetricType: this.rootTileset.lodMetricType,\n lodMetricValue: this.rootTileset.lodMetricValue,\n refine: this.rootTileset.root?.refine,\n spatialReference: get3DTilesSpatialReference(this.rootTileset)\n };\n }\n\n /**\n * Returns normalized source metadata after initialization.\n */\n getMetadata(): TilesetSourceMetadata {\n if (!this.metadata) {\n throw new Error('Tiles3DSource has not been initialized');\n }\n return this.metadata;\n }\n\n /**\n * Returns the root 3D Tiles payload.\n */\n async getRootTileset(): Promise<TilesetJSON> {\n return this.getMetadata().tileset;\n }\n\n /** Prepare nonlinear CRS state before runtime headers are materialized. */\n async prepareTileset(tileset: Tileset3D): Promise<void> {\n const spatialReference = tileset.spatialReference;\n if (spatialReference.status === 'unresolved') {\n throw new Error(\n spatialReference.warnings[0] ||\n '3D Tiles spatial operations cannot be resolved from the supplied metadata and options'\n );\n }\n if (spatialReference.status !== 'transformable' && spatialReference.status !== 'transformed') {\n return;\n }\n this.spatialTransformer ||= new Tiles3DSpatialTransformer(\n spatialReference,\n tileset.options.spatial\n );\n tileset.spatialReference = markTilesetSpatialReferenceTransformed(spatialReference);\n this.preparedRootHeader = this.transformTileHeader(\n this.getMetadata().tileset.root,\n new Matrix4()\n );\n }\n\n /**\n * Builds explicit runtime headers while leaving implicit subtree references lazy.\n */\n initializeTileHeaders(\n tileset: Tileset3D,\n tilesetJson: TilesetJSON,\n parentTile?: Tile3D | null\n ): Tile3D {\n const rootHeader = parentTile ? tilesetJson.root : this.preparedRootHeader || tilesetJson.root;\n const rootTile = new Tile3DNode(tileset, rootHeader, parentTile || undefined);\n\n if (parentTile) {\n parentTile.children.push(rootTile);\n rootTile.depth = parentTile.depth + 1;\n }\n\n const stack: Tile3D[] = [rootTile];\n while (stack.length > 0) {\n const tile = stack.pop() as Tile3D;\n tileset.stats.get('Tiles In Tileset(s)').incrementCount();\n const children = tile.header.children || [];\n for (const childHeader of children) {\n const childTile = new Tile3DNode(tileset, childHeader, tile);\n if (childTile.contentUrl?.includes('?session=')) {\n const url = new URL(childTile.contentUrl);\n const session = url.searchParams.get('session');\n if (session) {\n this.setQueryParameter('session', session);\n }\n }\n tile.children.push(childTile);\n childTile.depth = tile.depth + 1;\n stack.push(childTile);\n }\n }\n\n return rootTile;\n }\n\n /**\n * Creates the standard 3D Tiles traverser.\n */\n createTraverser(options: TilesetTraverserProps): TilesetTraverser {\n return new Tileset3DTraverser(options);\n }\n\n /**\n * Loads binary content or nested tileset JSON for a runtime tile.\n */\n async loadTileContent(tile: Tile3D): Promise<TileContentLoadResult> {\n const contentUrls = (tile.contentUrls || [tile.contentUrl]).filter(Boolean);\n const cachedContentHeaders = this.tileContentHeaders.get(tile);\n const contentHeaders: Record<string, any>[] =\n cachedContentHeaders ||\n (Array.isArray(tile.header?.content)\n ? tile.header.content\n : tile.header?.content\n ? [tile.header.content]\n : []);\n if (!cachedContentHeaders) {\n this.tileContentHeaders.set(tile, contentHeaders);\n }\n const tilesetLoaderOptions =\n (this.loadOptions[this.loader.id] as Record<string, unknown>) || {};\n const options = {\n ...this.loadOptions,\n [this.loader.id]: {\n ...tilesetLoaderOptions,\n // Content bytes, rather than URL suffixes, distinguish external tilesets from renderable\n // payloads. This is required for signed and extensionless resources.\n isTileset: 'auto',\n assetGltfUpAxis: (this.asset && this.asset.gltfUpAxis) || 'Y',\n _tilesetOptions: {\n spatialReference: tile.header?._spatialReference || tile.tileset?.spatialReference,\n spatialOptions: tile.tileset?.options.spatial,\n spatialTransform: tile.header?._spatialTransform\n }\n }\n };\n\n const contents = await Promise.all(\n contentUrls.map((contentUrl, contentIndex) => {\n const contentHeader = contentHeaders[contentIndex] || {};\n const vectorExtension = contentHeader.extensions?.['3DTILES_content_gltf_vector'];\n const vectorContent =\n contentHeader._vectorContent ||\n (vectorExtension?.vector === true ? {clip: vectorExtension.clip === true} : undefined);\n const contentOptions = vectorContent\n ? {\n ...options,\n [this.loader.id]: {\n ...(options[this.loader.id] as Record<string, unknown>),\n vectorContent\n }\n }\n : options;\n return this.loadContentResource(\n this.getTileUrl(contentUrl),\n contentHeader._resource,\n contentOptions\n );\n })\n );\n tile.contents = contents;\n tile.content = contents[0] || null;\n const nestedTilesets = contents.filter(content => content?.shape === 'tileset3d');\n\n return {\n loaded: true,\n contents,\n nestedTileset: nestedTilesets[0],\n nestedTilesets\n };\n }\n\n /** Transform a tile header and its eagerly declared descendants. */\n private transformTileHeader(\n header: Record<string, any>,\n parentTransform: Matrix4 = new Matrix4()\n ): Record<string, any> {\n if (!this.spatialTransformer) {\n return header;\n }\n return this.transformTileHeaderWithTransformer(\n header,\n this.spatialTransformer,\n parentTransform\n );\n }\n\n /** Rebuilds one header subtree using an explicitly selected CRS transformer. */\n private transformTileHeaderWithTransformer(\n header: Record<string, any>,\n transformer: Tiles3DSpatialTransformer,\n parentTransform: Matrix4,\n spatialReference?: TilesetSpatialReference\n ): Record<string, any> {\n const localTransform = header.transform ? new Matrix4(header.transform) : new Matrix4();\n const composedTransform = new Matrix4(parentTransform).multiplyRight(localTransform);\n const content = Array.isArray(header.content)\n ? header.content.map((entry: Record<string, any>) =>\n this.transformContentHeader(entry, composedTransform, transformer)\n )\n : header.content\n ? this.transformContentHeader(header.content, composedTransform, transformer)\n : header.content;\n return {\n ...header,\n transform: undefined,\n boundingVolume: header.boundingVolume\n ? transformer.transformBoundingVolume(header.boundingVolume, composedTransform)\n : header.boundingVolume,\n _spatialReference: spatialReference,\n _spatialTransform: composedTransform.toArray(),\n content,\n children: Array.isArray(header.children)\n ? header.children.map((child: Record<string, any>) =>\n this.transformTileHeaderWithTransformer(\n child,\n transformer,\n composedTransform,\n spatialReference\n )\n )\n : header.children\n };\n }\n\n private transformContentHeader(\n content: Record<string, any>,\n composedTransform: Matrix4,\n transformer: Tiles3DSpatialTransformer\n ): Record<string, any> {\n return {\n ...content,\n boundingVolume: content.boundingVolume\n ? transformer.transformBoundingVolume(content.boundingVolume, composedTransform)\n : content.boundingVolume\n };\n }\n\n /**\n * Loads, materializes, and installs exactly one implicit subtree.\n *\n * Final URLs pass through the same query inheritance and archive/custom resolver path as render\n * content. Parsed resources are deduplicated by final URL, while the pure materializer creates\n * lazy placeholders for every available child subtree instead of recursively fetching them.\n *\n * @param tile - Existing contentless subtree-root placeholder.\n * @param frameState - View state that made this request eligible; priority is consumed earlier.\n * @returns Counts describing the installed subtree.\n */\n async loadTileChildren(tile: Tile3D, frameState: FrameState): Promise<TileChildrenLoadResult> {\n void frameState;\n const reference = tile.header.implicitSubtree as ImplicitSubtreeReference | undefined;\n if (!reference) {\n return {loaded: false, tileCount: 0, childSubtreeCount: 0};\n }\n\n const subtreeUrl = this.getTileUrl(reference.subtreeUrl);\n const subtree = await this.loadImplicitSubtreeResource(subtreeUrl, reference.resource);\n if (this.destroyed || tile.isDestroyed()) {\n return {loaded: false, tileCount: 0, childSubtreeCount: 0};\n }\n const materializedSubtree = materializeImplicitSubtree(subtree, {\n ...reference,\n subtreeUrl\n });\n\n const nestedSpatialReference = tile.header._spatialReference as\n | TilesetSpatialReference\n | undefined;\n const subtreeTransformer = nestedSpatialReference\n ? new Tiles3DSpatialTransformer(nestedSpatialReference, tile.tileset.options.spatial)\n : this.spatialTransformer;\n const materializedRoot = subtreeTransformer\n ? this.transformTileHeaderWithTransformer(\n materializedSubtree.root,\n subtreeTransformer,\n new Matrix4(),\n nestedSpatialReference\n )\n : materializedSubtree.root;\n tile.applyImplicitSubtreeHeader(materializedRoot);\n const materializedTileCount = this.initializeMaterializedChildren(\n tile.tileset,\n tile,\n materializedRoot.children\n );\n this.implicitTilingStats.loadedSubtrees++;\n this.implicitTilingStats.materializedTiles += materializedTileCount;\n\n return {\n loaded: true,\n tileCount: materializedSubtree.tileCount,\n childSubtreeCount: materializedSubtree.childSubtreeCount\n };\n }\n\n /** Loads an implicit subtree for dataset traversal without camera state. */\n async loadTileChildrenForTraversal(\n tile: Tile3D,\n signal?: AbortSignal\n ): Promise<TileChildrenLoadResult> {\n throwIfTraversalAborted(signal);\n const result = await this.loadTileChildren(tile, {} as FrameState);\n throwIfTraversalAborted(signal);\n return result;\n }\n\n /**\n * Returns a snapshot of implicit-subtree request, cache, and materialization counters.\n *\n * @returns Immutable-by-convention diagnostic values for runtime inspection.\n */\n getImplicitTilingStats(): ImplicitTilingStats {\n return {\n ...this.implicitTilingStats,\n cachedSubtrees: this.implicitSubtreeCache.size - this.implicitSubtreeCache.pendingSize,\n pendingSubtrees: this.implicitSubtreeCache.pendingSize\n };\n }\n\n /**\n * Resolves a tile content URL with source-managed query parameters.\n *\n * Existing per-resource parameters take precedence over inherited root, version, and session\n * values. Completed URLs are cached by the original tile path; {@link setQueryParameter}\n * invalidates the cache before changed source state can be observed.\n *\n * @param tilePath - Unmodified absolute content URL or data URL from the tile header.\n * @returns Content URL with any missing source parameters appended.\n */\n getTileUrl(tilePath: string): string {\n if (tilePath.startsWith('data:')) {\n return tilePath;\n }\n\n const cachedTileUrl = this.tileUrlCache.get(tilePath);\n if (cachedTileUrl) {\n return cachedTileUrl;\n }\n\n if (!Object.keys(this.queryParams).length) {\n this.tileUrlCache.set(tilePath, tilePath);\n return tilePath;\n }\n\n const [pathWithoutQuery, existingQuery = ''] = tilePath.split('?');\n const mergedQueryParams = new URLSearchParams(existingQuery);\n\n for (const [key, value] of Object.entries(this.queryParams)) {\n if (!mergedQueryParams.has(key)) {\n mergedQueryParams.set(key, value);\n }\n }\n\n const queryParams = mergedQueryParams.toString();\n const tileUrl = queryParams ? `${pathWithoutQuery}?${queryParams}` : pathWithoutQuery;\n this.tileUrlCache.set(tilePath, tileUrl);\n return tileUrl;\n }\n\n /**\n * Updates an inherited source query parameter and invalidates derived request URLs.\n *\n * Root tokens and tileset versions normally settle during initialization. Some providers expose\n * a session parameter on a child URL, so invalidation is required to prevent URLs cached earlier\n * in header construction from retaining stale authentication state.\n *\n * @param parameterName - Query parameter name.\n * @param parameterValue - Query parameter value.\n */\n private setQueryParameter(parameterName: string, parameterValue: string): void {\n if (this.queryParams[parameterName] === parameterValue) {\n return;\n }\n this.queryParams[parameterName] = parameterValue;\n this.tileUrlCache.clear();\n }\n\n /**\n * Derives the default view state from the root bounding volume.\n */\n getViewState(rootTile: Tile3D | null): TilesetSourceViewState {\n if (!rootTile) {\n return {\n asset: this.asset,\n properties: this.properties,\n extras: this.extras,\n credits: this.credits\n };\n }\n\n const {center} = rootTile.boundingVolume;\n let cartographicCenter: Vector3;\n if (center && (center[0] !== 0 || center[1] !== 0 || center[2] !== 0)) {\n cartographicCenter = new Vector3();\n Ellipsoid.WGS84.cartesianToCartographic(center, cartographicCenter);\n } else {\n cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);\n }\n\n return {\n asset: this.asset,\n properties: this.properties,\n extras: this.extras,\n credits: this.credits,\n boundingVolume: rootTile.boundingVolume,\n cartographicCenter,\n cartesianCenter: center,\n zoom: getZoomFromBoundingVolume(rootTile.boundingVolume, cartographicCenter)\n };\n }\n\n /**\n * Checks whether the root tileset declares the given extension.\n */\n hasExtension(extensionName: string): boolean {\n return this.extensionsUsed.includes(extensionName);\n }\n\n /**\n * Updates content-format flags and installs nested tileset subtrees once per content slot.\n * Reloading payloads retains attached roots and their descendants, including duplicate URLs\n * declared in separate slots or parent placements. Detached roots are reinstalled in declaration order.\n */\n onTileLoaded(tileset: Tileset3D, tile: Tile3D, loadResult: TileContentLoadResult): void {\n const contents = tile.contents.length ? tile.contents : [tile.content];\n const extensionsRemoved = contents.flatMap(content => content?.gltf?.extensionsRemoved || []);\n if (extensionsRemoved.includes('KHR_draco_mesh_compression')) {\n this.contentFormats.draco = true;\n }\n if (extensionsRemoved.includes('EXT_meshopt_compression')) {\n this.contentFormats.meshopt = true;\n }\n if (extensionsRemoved.includes('KHR_texture_basisu')) {\n this.contentFormats.ktx2 = true;\n }\n\n const nestedTilesets =\n loadResult.nestedTilesets || (loadResult.nestedTileset ? [loadResult.nestedTileset] : []);\n const installedRoots = this.nestedTilesetRoots.get(tile) || [];\n for (const [nestedIndex, nestedTileset] of nestedTilesets.entries()) {\n const installedRoot = installedRoots[nestedIndex];\n if (installedRoot && tile.children.includes(installedRoot)) {\n continue;\n }\n const nextRoot = installedRoots\n .slice(nestedIndex + 1)\n .find(root => tile.children.includes(root));\n const nestedRoot = tileset._initializeTileHeaders(\n this.prepareNestedTileset(tileset, nestedTileset),\n tile\n );\n // Header installation appends roots; restore declaration order before any later retained slot.\n if (nextRoot) {\n tile.children.splice(tile.children.indexOf(nestedRoot), 1);\n tile.children.splice(tile.children.indexOf(nextRoot), 0, nestedRoot);\n }\n installedRoots[nestedIndex] = nestedRoot;\n this.nestedTilesetRoots.set(tile, installedRoots);\n }\n }\n\n /**\n * Resolves a nested tileset's CRS independently and adapts it to the owning tileset output frame.\n *\n * Nested resources may use a different source CRS from their parent. Their headers and glTF\n * payloads must therefore use a transformer built from the nested descriptor, while the parent\n * runtime continues to expose one requested output frame to traversal and rendering.\n */\n private prepareNestedTileset(tileset: Tileset3D, nestedTileset: TilesetJSON): TilesetJSON {\n const nestedSpatialReference = nestedTileset.spatialMetadata;\n const parentSpatialReference = tileset.spatialReference;\n\n if (\n nestedSpatialReference?.status === 'unresolved' ||\n nestedSpatialReference?.crs.state === 'unknown'\n ) {\n throw new Error(\n nestedSpatialReference.warnings[0] ||\n 'Nested 3D Tiles CRS is explicitly unresolved and cannot be placed in the parent frame'\n );\n }\n\n if (!nestedSpatialReference || !nestedSpatialReference.sourceCrs) {\n if (\n this.spatialTransformer &&\n (parentSpatialReference.status === 'transformable' ||\n parentSpatialReference.status === 'transformed')\n ) {\n return {\n ...nestedTileset,\n spatialMetadata: parentSpatialReference,\n root: this.transformTileHeaderWithTransformer(\n nestedTileset.root,\n this.spatialTransformer,\n new Matrix4(),\n parentSpatialReference\n )\n };\n }\n return addNestedSpatialReference(nestedTileset, parentSpatialReference);\n }\n\n const parentCoordinateEpoch = parentSpatialReference.coordinateEpoch;\n const nestedCoordinateEpoch = nestedSpatialReference.coordinateEpoch;\n if (\n parentCoordinateEpoch !== undefined &&\n nestedCoordinateEpoch !== undefined &&\n parentCoordinateEpoch !== nestedCoordinateEpoch\n ) {\n throw new Error(\n `Nested 3D Tiles coordinate epoch ${nestedCoordinateEpoch} differs from parent epoch ${parentCoordinateEpoch}; epoch-aware transformation is unavailable`\n );\n }\n\n const outputCrs = parentSpatialReference.targetCrs || parentSpatialReference.sourceCrs;\n if (!outputCrs) {\n return addNestedSpatialReference(nestedTileset, nestedSpatialReference);\n }\n\n const nestedOutputReference = applyTilesetSpatialOptions(nestedSpatialReference, {\n ...tileset.options.spatial,\n outputCoordinates: 'target-crs',\n targetCrs: outputCrs\n });\n if (nestedOutputReference.status === 'unresolved') {\n throw new Error(\n nestedOutputReference.warnings[0] ||\n 'Nested 3D Tiles CRS cannot be resolved in the parent output frame'\n );\n }\n if (nestedOutputReference.status === 'native') {\n return addNestedSpatialReference(nestedTileset, nestedOutputReference);\n }\n\n const nestedTransformer = new Tiles3DSpatialTransformer(\n nestedOutputReference,\n tileset.options.spatial\n );\n return {\n ...nestedTileset,\n spatialMetadata: nestedOutputReference,\n root: this.transformTileHeaderWithTransformer(\n nestedTileset.root,\n nestedTransformer,\n new Matrix4(),\n nestedOutputReference\n )\n };\n }\n\n /**\n * Loads data through injected core APIs so this module stays independent from `@loaders.gl/core`.\n */\n private async loadWithCoreApi(\n url: string,\n options: LoaderOptions,\n loader: Loader = this.loader\n ): Promise<any> {\n if (!this.coreApi) {\n throw new Error('Tiles3DSource requires an injected coreApi to load tileset data');\n }\n\n return await this.coreApi.load(url, loader, options);\n }\n\n /**\n * Loads data through an injected resolver when present, otherwise through the injected core API.\n */\n private async loadRootData(url: string, options: LoaderOptions): Promise<any> {\n if (this.resolver) {\n return await this.resolver.loadRoot(url, this.loader, options);\n }\n\n return await this.loadWithCoreApi(url, options);\n }\n\n /**\n * Loads an arbitrary source resource through an injected resolver or core API.\n */\n private async loadResourceData(\n url: string,\n options: LoaderOptions,\n loader: Loader = this.loader\n ): Promise<any> {\n if (this.resolver) {\n return await this.resolver.loadResource(url, loader, options);\n }\n\n return await this.loadWithCoreApi(url, options, loader);\n }\n\n /** Loads a URL content reference or parses a buffer-view file retained from a glTF package. */\n private async loadContentResource(\n url: string,\n packageResource: PackageResource | undefined,\n options: LoaderOptions\n ): Promise<any> {\n if (!packageResource) {\n return await this.loadResourceData(url, options);\n }\n const file = packageResource.files[packageResource.fileIndex];\n if (!file) {\n throw new Error(`3D Tiles package references missing file ${packageResource.fileIndex}`);\n }\n if (file.uri) {\n return await this.loadResourceData(this.getTileUrl(file.uri), options);\n }\n if (!this.coreApi) {\n throw new Error('Tiles3DSource requires an injected coreApi to parse embedded package data');\n }\n\n const data = await this.getPackageFileData(file);\n const packageNamespace = this.getPackageNamespace(packageResource.files);\n const packageRootUrl = `gltf-package://${packageNamespace}/${packageResource.fileIndex}`;\n const fileName = file.name || 'content';\n const directorySeparatorIndex = fileName.lastIndexOf('/');\n const packageBaseUrl =\n directorySeparatorIndex >= 0\n ? `${packageRootUrl}/${fileName.slice(0, directorySeparatorIndex)}`\n : packageRootUrl;\n return await this.coreApi.parse(data, this.loader, options, {\n url: `${packageRootUrl}/${fileName}`,\n filename: fileName,\n baseUrl: packageBaseUrl,\n loaders: [this.loader],\n coreApi: this.coreApi,\n _parse: this.coreApi.parse,\n _tiles3dPackageFiles: packageResource.files,\n fetch: async (resource: string, init?: RequestInit) => {\n const reference = resource.startsWith(`${packageRootUrl}/`)\n ? resource.slice(packageRootUrl.length + 1)\n : resource;\n const referencedFile = packageResource.files.find(\n packageFile => packageFile.name === reference || packageFile.originalUri === reference\n );\n if (!referencedFile) {\n throw new Error(`3D Tiles glTF package does not contain file ${reference}`);\n }\n if (referencedFile.uri) {\n return await this.coreApi!.fetchFile(this.getTileUrl(referencedFile.uri), init);\n }\n const referencedData = await this.getPackageFileData(referencedFile);\n return new Response(referencedData, {\n headers: {'content-type': referencedFile.mimeType}\n });\n }\n } as Tiles3DPackageLoaderContext);\n }\n\n /** Returns a stable source-local namespace for one embedded glTF package file collection. */\n private getPackageNamespace(files: PackageFile[]): number {\n const existingNamespace = this.packageNamespaces.get(files);\n if (existingNamespace !== undefined) {\n return existingNamespace;\n }\n const packageNamespace = this.nextPackageNamespace++;\n this.packageNamespaces.set(files, packageNamespace);\n return packageNamespace;\n }\n\n /** Resolves a retained package-file byte range without eagerly copying other package files. */\n private async getPackageFileData(file: PackageFile): Promise<ArrayBuffer> {\n if (file.data) {\n return sliceArrayBuffer(file.data, file.byteOffset, file.byteLength);\n }\n if (file.bufferUri && this.coreApi) {\n const response = await this.coreApi.fetchFile(this.getTileUrl(file.bufferUri));\n if (!response.ok) {\n throw new Error(`Failed to fetch 3D Tiles package buffer: HTTP ${response.status}`);\n }\n const buffer = await response.arrayBuffer();\n return sliceArrayBuffer(buffer, file.byteOffset, file.byteLength);\n }\n throw new Error('3D Tiles package file has no available byte source');\n }\n\n /**\n * Returns a parsed subtree from the LRU cache or starts one source-managed request.\n *\n * @param subtreeUrl - Final subtree URL after query inheritance.\n * @param packageResource - Optional glTF package file satisfying the subtree reference.\n * @returns Parsed subtree availability data.\n */\n private async loadImplicitSubtreeResource(\n subtreeUrl: string,\n packageResource?: PackageResource\n ): Promise<ParsedImplicitSubtree> {\n const cachedSubtree = this.implicitSubtreeCache.get(subtreeUrl);\n if (cachedSubtree) {\n this.implicitTilingStats.cacheHits++;\n return await cachedSubtree;\n }\n\n this.implicitTilingStats.requestedSubtrees++;\n const loaderOptions = (this.loadOptions[this.loader.id] as Record<string, unknown>) || {};\n return await this.implicitSubtreeCache.getOrLoad(subtreeUrl, async () => {\n const options = {\n ...this.loadOptions,\n [this.loader.id]: {\n ...loaderOptions,\n isTileset: false,\n isSubtree: true\n }\n };\n return (await (packageResource\n ? this.loadContentResource(subtreeUrl, packageResource, options)\n : this.loadResourceData(subtreeUrl, options))) as ParsedImplicitSubtree;\n });\n }\n\n /**\n * Instantiates every header represented by one materialized subtree.\n *\n * @param tileset - Owning runtime tileset.\n * @param parentTile - Existing materialized parent.\n * @param childHeaders - Headers to install below the parent.\n * @returns Number of newly allocated runtime tile nodes.\n */\n private initializeMaterializedChildren(\n tileset: Tileset3D,\n parentTile: Tile3D,\n childHeaders: Record<string, any>[]\n ): number {\n let materializedTileCount = 0;\n const stack: Array<{parentTile: Tile3D; childHeaders: Record<string, any>[]}> = [\n {parentTile, childHeaders}\n ];\n while (stack.length > 0) {\n const entry = stack.pop()!;\n for (const childHeader of entry.childHeaders) {\n const childTile = new Tile3DNode(tileset, childHeader, entry.parentTile);\n entry.parentTile.children.push(childTile);\n childTile.depth = entry.parentTile.depth + 1;\n tileset.stats.get('Tiles In Tileset(s)').incrementCount();\n materializedTileCount++;\n if (childHeader.children?.length) {\n stack.push({parentTile: childTile, childHeaders: childHeader.children});\n }\n }\n }\n return materializedTileCount;\n }\n}\n\n/** Throws a cancellation reason before or after source-managed traversal work. */\nfunction throwIfTraversalAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The operation was aborted', 'AbortError');\n }\n}\n\nfunction isTilesetRequest(input: TilesetSourceInput): input is TilesetSourceRequest {\n return Boolean(\n input && typeof input === 'object' && 'url' in input && 'loader' in input && !('type' in input)\n );\n}\n\n/**\n * Normalizes constructor input into a URL request descriptor.\n * @param input Constructor input for {@link Tiles3DSource}.\n * @returns A normalized request with a resolved base path.\n */\nfunction normalizeTiles3DRequest(input: TilesetSourceInput): TilesetSourceRequest {\n if (isTilesetRequest(input)) {\n return {\n ...input,\n basePath: input.basePath || path.dirname(input.url)\n };\n }\n\n return {\n url: input.url,\n loader: input.loader,\n basePath: input.basePath || path.dirname(input.url),\n resolver: (input as TilesetSourceRequest).resolver,\n coreApi: (input as TilesetSourceRequest).coreApi\n };\n}\n\n/** Adds a nested CRS descriptor to each header without changing its native placement. */\nfunction addNestedSpatialReference(\n nestedTileset: TilesetJSON,\n spatialReference: TilesetSpatialReference\n): TilesetJSON {\n const addToHeader = (header: Record<string, any>): Record<string, any> => ({\n ...header,\n _spatialReference: spatialReference,\n children: Array.isArray(header.children) ? header.children.map(addToHeader) : header.children\n });\n return {\n ...nestedTileset,\n spatialMetadata: spatialReference,\n root: addToHeader(nestedTileset.root)\n };\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// This file is derived from the Cesium code base under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {TILE3D_OPTIMIZATION_HINT, TILE_REFINEMENT} from '../../constants';\nimport {TilesetTraverser} from '../common/tileset-traverser';\nimport type {Tile3D} from '../common/tile-3d';\nimport type {FrameState} from '../helpers/frame-state';\n\nexport class Tileset3DTraverser extends TilesetTraverser {\n /** Pending implicit subtree requests keyed by viewport and tile identity. */\n private readonly pendingImplicitSubtrees: Map<string, number> = new Map();\n\n /**\n * Reports whether every implicit subtree request started by this viewport traversal has settled.\n *\n * @param frameState - Traversal frame whose completion callback is being considered.\n * @returns `true` when no matching subtree metadata request remains pending.\n */\n protected traversalFinished(frameState: FrameState): boolean {\n const viewportPrefix = `${frameState.viewport.id}:`;\n for (const [requestKey, frameNumber] of this.pendingImplicitSubtrees) {\n if (requestKey.startsWith(viewportPrefix) && frameNumber === frameState.frameNumber) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Runs normal replacement traversal or the dedicated skip-LOD traversal selected by options.\n *\n * @param root - Root of the runtime subtree to traverse.\n * @param frameState - Current culling and LOD state.\n */\n executeTraversal(root: Tile3D, frameState: FrameState): void {\n if (!this.isSkipLevelOfDetailEnabled()) {\n super.executeTraversal(root, frameState);\n return;\n }\n this.executeSkipTraversal(root, frameState);\n }\n\n /**\n * Traverses visible replacement branches without requesting skipped intermediate content.\n *\n * Base-traversal tiles establish coarse coverage. Below that base, only final desired tiles and\n * tiles that cross the configured depth/SSE thresholds are requested. Already available\n * ancestors remain selectable while those requests stream in.\n *\n * @param root - Root of the runtime subtree to traverse.\n * @param frameState - Current culling and LOD state.\n */\n private executeSkipTraversal(root: Tile3D, frameState: FrameState): void {\n const stack: Tile3D[] = [root];\n root._selectionDepth = root.parent ? root.parent._selectionDepth : 1;\n\n while (stack.length > 0) {\n const tile = stack.pop() as Tile3D;\n const parentRefines = !tile.parent || tile.parent._shouldRefine;\n const shouldRefine =\n this.canTraverse(tile, frameState) &&\n this.updateAndPushSkipChildren(tile, frameState, stack) &&\n parentRefines;\n const stoppedRefining = !shouldRefine && parentRefines;\n\n if (!tile.hasRenderContent) {\n this.emptyTiles[tile.id] = tile;\n this.loadTile(tile, frameState);\n // A known empty terminal branch needs no fallback geometry. Lazy child groups still\n // report hasChildren while unresolved, so they retain coverage until materialized.\n if (stoppedRefining && (!tile.hasEmptyContent || tile.hasChildren)) {\n this.selectDesiredTile(tile, frameState);\n }\n } else if (tile.refine === TILE_REFINEMENT.ADD) {\n this.loadTile(tile, frameState);\n this.selectDesiredTile(tile, frameState);\n } else if (tile.refine === TILE_REFINEMENT.REPLACE) {\n if (this.isInBaseTraversal(tile, frameState)) {\n this.loadTile(tile, frameState);\n if (stoppedRefining) {\n this.selectDesiredTile(tile, frameState);\n }\n } else if (stoppedRefining) {\n this.loadTile(tile, frameState);\n this.selectDesiredTile(tile, frameState);\n } else if (this.hasReachedSkippingThreshold(tile, frameState)) {\n this.loadTile(tile, frameState);\n }\n }\n\n this.touchTile(tile, frameState);\n tile._shouldRefine = shouldRefine;\n }\n\n this.completeTraversal(frameState);\n }\n\n /**\n * Updates and pushes visible children for skip traversal without requiring sibling readiness.\n *\n * @param tile - Parent whose children are considered.\n * @param frameState - Current culling and LOD state.\n * @param stack - Depth-first traversal stack.\n * @returns `true` when at least one visible child continues refinement.\n */\n private updateAndPushSkipChildren(\n tile: Tile3D,\n frameState: FrameState,\n stack: Tile3D[]\n ): boolean {\n this.updateChildTiles(tile, frameState);\n tile.children.sort(this.compareDistanceToCamera.bind(this));\n\n let hasVisibleChild = false;\n for (const child of tile.children) {\n child._selectionDepth = tile.hasRenderContent\n ? tile._selectionDepth + 1\n : tile._selectionDepth;\n if (child.isVisibleAndInRequestVolume) {\n stack.push(child);\n hasVisibleChild = true;\n } else if (this.options.loadSiblings && child._inRequestVolume) {\n this.loadTile(child, frameState);\n this.touchTile(child, frameState);\n }\n }\n return hasVisibleChild;\n }\n\n /**\n * Determines whether a tile belongs to the coarse non-skipping portion of the traversal.\n *\n * @param tile - Tile considered for loading.\n * @param frameState - Current traversal frame.\n * @returns `true` when the tile should always be requested for fallback coverage.\n */\n private isInBaseTraversal(tile: Tile3D, frameState: FrameState): boolean {\n if (this.options.immediatelyLoadDesiredLevelOfDetail) {\n return false;\n }\n if (!this.findNearestRequestedOrLoadedAncestor(tile, frameState)) {\n return true;\n }\n\n const configuredBaseScreenSpaceError = Number.isFinite(this.options.baseScreenSpaceError)\n ? Math.max(this.options.baseScreenSpaceError, 0)\n : 1024;\n const baseScreenSpaceError = Math.max(\n configuredBaseScreenSpaceError,\n tile.tileset.memoryAdjustedScreenSpaceError\n );\n if (tile._screenSpaceError === 0 && tile.parent) {\n return tile.parent._screenSpaceError > baseScreenSpaceError;\n }\n return tile._screenSpaceError > baseScreenSpaceError;\n }\n\n /**\n * Determines whether a skipped branch has crossed its configured request threshold.\n *\n * @param tile - Tile considered for loading.\n * @param frameState - Current traversal frame.\n * @returns `true` when the tile must be requested instead of skipped.\n */\n private hasReachedSkippingThreshold(tile: Tile3D, frameState: FrameState): boolean {\n if (this.options.immediatelyLoadDesiredLevelOfDetail) {\n return false;\n }\n const progressiveResolutionLeaf =\n tile._priorityProgressiveResolution &&\n tile._screenSpaceErrorProgressiveResolution <= tile.tileset.memoryAdjustedScreenSpaceError &&\n Boolean(\n tile.parent &&\n tile.parent._screenSpaceErrorProgressiveResolution >\n tile.tileset.memoryAdjustedScreenSpaceError\n );\n if (progressiveResolutionLeaf) {\n return true;\n }\n\n const ancestor = this.findNearestRequestedOrLoadedAncestor(tile, frameState);\n if (!ancestor) {\n return false;\n }\n const skipScreenSpaceErrorFactor =\n Number.isFinite(this.options.skipScreenSpaceErrorFactor) &&\n this.options.skipScreenSpaceErrorFactor > 0\n ? this.options.skipScreenSpaceErrorFactor\n : 16;\n const skipLevels = Number.isFinite(this.options.skipLevels)\n ? Math.max(Math.floor(this.options.skipLevels), 0)\n : 1;\n return (\n tile._screenSpaceError < ancestor._screenSpaceError / skipScreenSpaceErrorFactor &&\n tile.depth > ancestor.depth + skipLevels\n );\n }\n\n /**\n * Finds the nearest ancestor whose render content is loaded, loading, or requested this frame.\n *\n * @param tile - Descendant whose request threshold needs an anchor.\n * @param frameState - Current traversal frame.\n * @returns The nearest request anchor, or `null` when none exists.\n */\n private findNearestRequestedOrLoadedAncestor(\n tile: Tile3D,\n frameState: FrameState\n ): Tile3D | null {\n let ancestor = tile.parent;\n while (ancestor) {\n const contentIsUsableAnchor =\n ancestor.hasRenderContent &&\n !ancestor.contentFailed &&\n (!ancestor.hasUnloadedContent || ancestor._requestedFrame === frameState.frameNumber);\n if (contentIsUsableAnchor) {\n return ancestor;\n }\n ancestor = ancestor.parent;\n }\n return null;\n }\n\n /**\n * Selects the desired tile, its nearest ready ancestor, or nearby ready descendants.\n *\n * @param tile - Tile that ended the desired refinement branch.\n * @param frameState - Current culling state.\n */\n private selectDesiredTile(tile: Tile3D, frameState: FrameState): void {\n let fallbackTile: Tile3D | null = tile;\n while (fallbackTile) {\n if (this.shouldSelectTile(fallbackTile, frameState)) {\n this.selectTile(fallbackTile, frameState);\n if (fallbackTile !== tile) {\n // On zoom-out the desired coarse level may still be unavailable. Preserve\n // nearby detail that already drew while the ancestor fills uncovered pixels.\n this.selectLoadedDescendants(tile, frameState, true);\n }\n return;\n }\n fallbackTile = fallbackTile.parent;\n }\n this.selectLoadedDescendants(tile, frameState);\n }\n\n /**\n * Selects ready descendants near an unavailable desired tile to reduce temporary empty regions.\n *\n * @param root - Unavailable tile whose descendants are searched.\n * @param frameState - Current culling state.\n * @param drawnOnly - Reuse drawn detail without starting obsolete GPU work.\n */\n private selectLoadedDescendants(\n root: Tile3D,\n frameState: FrameState,\n drawnOnly: boolean = false\n ): void {\n const stack: Array<{tile: Tile3D; depth: number}> = [{tile: root, depth: 0}];\n while (stack.length > 0) {\n const {tile, depth} = stack.pop() as {tile: Tile3D; depth: number};\n for (const child of tile.children) {\n this.updateTile(child, frameState);\n if (!child.isVisibleAndInRequestVolume) {\n continue;\n }\n if (this.shouldSelectTile(child, frameState) && (!drawnOnly || child.tileDrawn)) {\n this.selectTile(child, frameState);\n this.touchTile(child, frameState);\n } else if (depth < 1) {\n stack.push({tile: child, depth: depth + 1});\n }\n }\n }\n }\n\n compareDistanceToCamera(a, b) {\n // Sort by farthest child first since this is going on a stack\n return b._distanceToCamera === 0 && a._distanceToCamera === 0\n ? b._centerZDepth - a._centerZDepth\n : b._distanceToCamera - a._distanceToCamera;\n }\n\n /**\n * Starts an implicit subtree request after culling and request-volume eligibility.\n *\n * The first subtree of an implicit hierarchy materializes independently of SSE because its\n * placeholder has no render content. Deeper subtree boundaries remain SSE-gated. The current\n * parent remains the traversal boundary while metadata is loading, which preserves REPLACE\n * coverage and ADD accumulation. Request scheduling reads the tile's existing\n * progressive-resolution and foveated metrics, so subtree metadata follows the same priority\n * policy as render content. A completion notification lets the owning tileset publish the newly\n * materialized traversal result on the next update.\n *\n * @param tile - Tile whose existing or lazy children should be updated.\n * @param frameState - Current culling and LOD state.\n */\n updateChildTiles(tile: Tile3D, frameState: FrameState): void {\n const isImplicitHierarchyRoot = tile.header.implicitSubtree?.coordinates.level === 0;\n if (\n tile.hasUnloadedChildren &&\n tile.isVisibleAndInRequestVolume &&\n (isImplicitHierarchyRoot || this.shouldRefine(tile, frameState))\n ) {\n const requestKey = `${frameState.viewport.id}:${tile.id}`;\n if (!this.pendingImplicitSubtrees.has(requestKey)) {\n this.pendingImplicitSubtrees.set(requestKey, frameState.frameNumber);\n void tile.tileset._loadTileChildren(tile, frameState).finally(() => {\n this.handleImplicitSubtreeLoad(tile, frameState, requestKey);\n });\n }\n }\n super.updateChildTiles(tile, frameState);\n }\n\n /**\n * Resumes the same traversal frame after one lazy subtree request settles.\n *\n * Successful materialization traverses the new headers immediately. Failed or scheduler-cancelled\n * requests finish the current traversal without retrying in a tight loop; a later application\n * update may retry them.\n *\n * @param tile - Subtree-root tile whose request settled.\n * @param frameState - Frame that started the request.\n * @param requestKey - Viewport-scoped pending-request identity.\n */\n private handleImplicitSubtreeLoad(\n tile: Tile3D,\n frameState: FrameState,\n requestKey: string\n ): void {\n this.pendingImplicitSubtrees.delete(requestKey);\n if (this._frameNumber !== frameState.frameNumber) {\n return;\n }\n if (tile.childrenState === 'ready') {\n this.executeTraversal(tile, frameState);\n } else if (this.traversalFinished(frameState)) {\n this.options.onTraversalEnd(frameState);\n }\n }\n\n updateTileVisibility(tile, frameState) {\n super.updateTileVisibility(tile, frameState);\n\n // Optimization - if none of the tile's children are visible then this tile isn't visible\n if (!tile.isVisibleAndInRequestVolume) {\n return;\n }\n\n const hasChildren = tile.children.length > 0;\n if (tile.hasTilesetContent && hasChildren) {\n // Use the root tile's visibility instead of this tile's visibility.\n // The root tile may be culled by the children bounds optimization in which\n // case this tile should also be culled.\n const firstChild = tile.children[0];\n this.updateTileVisibility(firstChild, frameState);\n tile._visible = firstChild._visible;\n return;\n }\n\n if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {\n tile._visible = false;\n return;\n }\n\n const replace = tile.refine === TILE_REFINEMENT.REPLACE;\n const useOptimization =\n tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;\n if (replace && useOptimization && hasChildren) {\n if (!this.anyChildrenVisible(tile, frameState)) {\n tile._visible = false;\n return;\n }\n }\n }\n\n meetsScreenSpaceErrorEarly(tile, frameState) {\n const {parent} = tile;\n if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {\n return false;\n }\n\n // Use parent's geometric error with child's box to see if the tile already meet the SSE\n return !this.shouldRefine(tile, frameState, true);\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3} from '@math.gl/core';\nimport {BoundingSphere, OrientedBoundingBox} from '@math.gl/culling';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {BoundingRectangle} from '../../types';\n\nconst WGS84_RADIUS_X = 6378137.0;\nconst WGS84_RADIUS_Y = 6378137.0;\nconst WGS84_RADIUS_Z = 6356752.3142451793;\n\nconst scratchVector = new Vector3();\n\n/**\n * Calculate appropriate zoom value for a particular boundingVolume\n * @param boundingVolume - the instance of bounding volume\n * @param cartorgraphicCenter - cartographic center of the bounding volume\n * @returns {number} - zoom value\n */\nexport function getZoomFromBoundingVolume(\n boundingVolume: BoundingSphere | OrientedBoundingBox | BoundingRectangle,\n cartorgraphicCenter: Vector3\n) {\n if (boundingVolume instanceof OrientedBoundingBox) {\n // OrientedBoundingBox\n const {halfAxes} = boundingVolume;\n const obbSize = getObbSize(halfAxes);\n // Use WGS84_RADIUS_Z to allign with BoundingSphere algorithm\n // Add the tile elevation value for correct zooming to elevated tiles\n return Math.log2(WGS84_RADIUS_Z / (obbSize + cartorgraphicCenter[2]));\n } else if (boundingVolume instanceof BoundingSphere) {\n // BoundingSphere\n const {radius} = boundingVolume;\n // Add the tile elevation value for correct zooming to elevated tiles\n return Math.log2(WGS84_RADIUS_Z / (radius + cartorgraphicCenter[2]));\n } else if (boundingVolume.width && boundingVolume.height) {\n // BoundingRectangle\n const {width, height} = boundingVolume;\n const zoomX = Math.log2(WGS84_RADIUS_X / width);\n const zoomY = Math.log2(WGS84_RADIUS_Y / height);\n\n return (zoomX + zoomY) / 2;\n }\n\n return 1;\n}\n\n/**\n * Calculate initial zoom for the tileset from 3D `fullExtent` defined in\n * the tileset metadata\n * @param fullExtent - 3D extent of the tileset\n * @param fullExtent.xmin - minimal longitude in decimal degrees\n * @param fullExtent.xmax - maximal longitude in decimal degrees\n * @param fullExtent.ymin - minimal latitude in decimal degrees\n * @param fullExtent.ymax - maximal latitude in decimal degrees\n * @param fullExtent.zmin - minimal elevation in meters\n * @param fullExtent.zmax - maximal elevation in meters\n * @param cartorgraphicCenter - tileset center in cartographic coordinate system\n * @param cartesianCenter - tileset center in cartesian coordinate system\n * @returns - initial zoom for the tileset\n */\nexport function getZoomFromFullExtent(\n fullExtent: {\n xmin: number;\n xmax: number;\n ymin: number;\n ymax: number;\n zmin: number;\n zmax: number;\n },\n cartorgraphicCenter: Vector3,\n cartesianCenter: Vector3\n) {\n Ellipsoid.WGS84.cartographicToCartesian(\n [fullExtent.xmax, fullExtent.ymax, fullExtent.zmax],\n scratchVector\n );\n const extentSize = Math.sqrt(\n Math.pow(scratchVector[0] - cartesianCenter[0], 2) +\n Math.pow(scratchVector[1] - cartesianCenter[1], 2) +\n Math.pow(scratchVector[2] - cartesianCenter[2], 2)\n );\n return Math.log2(WGS84_RADIUS_Z / (extentSize + cartorgraphicCenter[2]));\n}\n\n/**\n * Calculate initial zoom for the tileset from 2D `extent` defined in\n * the tileset metadata\n * @param extent - 2D extent of the tileset. It is array of 4 elements [xmin, ymin, xmax, ymax]\n * @param extent[0] - minimal longitude in decimal degrees\n * @param extent[1] - minimal latitude in decimal degrees\n * @param extent[2] - maximal longitude in decimal degrees\n * @param extent[3] - maximal latitude in decimal degrees\n * @param cartorgraphicCenter - tileset center in cartographic coordinate system\n * @param cartesianCenter - tileset center in cartesian coordinate system\n * @returns - initial zoom for the tileset\n */\nexport function getZoomFromExtent(\n extent: [number, number, number, number],\n cartorgraphicCenter: Vector3,\n cartesianCenter: Vector3\n) {\n const [xmin, ymin, xmax, ymax] = extent;\n return getZoomFromFullExtent(\n {xmin, xmax, ymin, ymax, zmin: 0, zmax: 0},\n cartorgraphicCenter,\n cartesianCenter\n );\n}\n\nfunction getObbSize(halfAxes) {\n halfAxes.getColumn(0, scratchVector);\n const axeY = halfAxes.getColumn(1);\n const axeZ = halfAxes.getColumn(2);\n const farthestVertex = scratchVector.add(axeY).add(axeZ);\n const size = farthestVertex.len();\n return size;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst LINEAR_UNIT_TO_METERS: Readonly<Record<string, number>> = Object.freeze({\n meter: 1,\n millimeter: 0.001,\n centimeter: 0.01,\n decimeter: 0.1,\n kilometer: 1000,\n foot: 0.3048,\n yard: 0.9144,\n mile: 1609.344,\n 'us-foot': 1200 / 3937,\n 'us-inch': 0.0254000508001016,\n 'us-yard': 3600 / 3937,\n 'us-mile': 6336000 / 3937,\n 'clarke-foot': 0.3047972654,\n 'clarke-yard': 0.9143917962,\n 'clarke-link': 0.201166195164,\n 'sears-yard': 0.914398414616,\n 'sears-foot': 0.304799471539,\n 'sears-chain': 20.1167651216,\n 'sears-1922-truncated-chain': 20.116756,\n 'benoit-1895-b-chain': 20.1167824944,\n 'indian-yard': 0.914398530744,\n 'indian-1937-yard': 0.91439523,\n 'gold-coast-foot': 0.304799710181\n});\n\nconst LINEAR_UNIT_ALIASES: Readonly<Record<string, string>> = Object.freeze({\n m: 'meter',\n metre: 'meter',\n meters: 'meter',\n metres: 'meter',\n mm: 'millimeter',\n millimetre: 'millimeter',\n millimeters: 'millimeter',\n millimetres: 'millimeter',\n cm: 'centimeter',\n centimetre: 'centimeter',\n centimeters: 'centimeter',\n centimetres: 'centimeter',\n dm: 'decimeter',\n decimetre: 'decimeter',\n decimeters: 'decimeter',\n decimetres: 'decimeter',\n km: 'kilometer',\n kilometre: 'kilometer',\n kilometers: 'kilometer',\n kilometres: 'kilometer',\n ft: 'foot',\n feet: 'foot',\n 'us-survey-foot': 'us-foot',\n 'us-survey-feet': 'us-foot',\n yd: 'yard',\n yards: 'yard',\n mi: 'mile',\n miles: 'mile'\n});\n\n/**\n * Resolves an ArcGIS/I3S linear unit to meters.\n *\n * @param unit - I3S `heightUnit`, `elevationInfo.unit`, or provider unit.\n * @returns Meters per unit, or `undefined` when the declaration is unsupported.\n */\nexport function getI3SLinearUnitScale(unit: string | undefined): number | undefined {\n if (!unit) {\n return undefined;\n }\n const normalized = unit.trim().toLowerCase().replaceAll('_', '-');\n const canonical = LINEAR_UNIT_ALIASES[normalized] || normalized;\n return LINEAR_UNIT_TO_METERS[canonical];\n}\n\n/**\n * Resolves the source-Z conversion declared by an I3S layer.\n *\n * Legacy `ZFactor` is an explicit conversion to meters and takes precedence over the descriptive\n * `heightUnit`. This avoids applying the same feet-to-meters conversion twice on layers that\n * publish both fields.\n *\n * @param heightUnit - Unit declared by `heightModelInfo.heightUnit`.\n * @param zFactor - Legacy layer conversion factor.\n * @returns Meters per stored Z unit, or `undefined` for an invalid declaration.\n */\nexport function getI3SVerticalUnitScale(\n heightUnit: string | undefined,\n zFactor: number | undefined\n): number | undefined {\n if (zFactor !== undefined) {\n return Number.isFinite(zFactor) && zFactor > 0 ? zFactor : undefined;\n }\n return heightUnit ? getI3SLinearUnitScale(heightUnit) : 1;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {ReadonlyCRSDefinition} from '@math.gl/crs';\nimport {getI3SLinearUnitScale, getI3SVerticalUnitScale} from './i3s-elevation';\nimport {\n getKnownCrsIdentifierCoordinateFrame,\n getSpatialCoordinateFrame\n} from './get-spatial-coordinate-frame';\nimport {createTilesetSpatialReference} from './spatial-types';\nimport type {TilesetElevationMode, TilesetSpatialReference} from './spatial-types';\n\n/** ArcGIS/I3S spatial reference fields used without depending on the I3S package. */\ntype I3SSpatialReferenceLike = {\n wkid?: number;\n latestWkid?: number;\n vcsWkid?: number;\n latestVcsWkid?: number;\n wkt?: string;\n};\n\n/** I3S layer fields needed for spatial metadata discovery. */\ntype I3SLayerLike = {\n spatialReference?: I3SSpatialReferenceLike;\n fullExtent?: {spatialReference?: I3SSpatialReferenceLike};\n heightModelInfo?: {\n heightModel?: string;\n vertCRS?: ReadonlyCRSDefinition;\n heightUnit?: string;\n };\n ZFactor?: number;\n elevationInfo?: {mode?: string; offset?: number; unit?: string};\n};\n\n/** 3D Tiles metadata schema property used for semantic lookup. */\ntype Tiles3DMetadataProperty = {semantic?: string};\n\n/** 3D Tiles document fields needed for CRS semantic discovery. */\ntype Tiles3DLike = {\n schema?: {\n classes?: Record<string, unknown>;\n };\n schemaUri?: string;\n metadata?: {class?: string; properties?: Record<string, unknown>};\n root?: {boundingVolume?: {region?: unknown}};\n extensions?: Record<string, unknown>;\n};\n\n/**\n * Discovers normalized spatial metadata from an I3S scene-layer document.\n *\n * I3S encodes geographic coordinates in longitude/latitude wire order even for authority\n * definitions whose formal axis order differs.\n *\n * @param layer - Parsed I3S layer document.\n * @returns Normalized source spatial metadata.\n */\nexport function getI3SSpatialReference(layer: I3SLayerLike): TilesetSpatialReference {\n const spatialReference = layer.spatialReference || layer.fullExtent?.spatialReference;\n const sourceCrs = getI3SCrsDefinition(spatialReference);\n const verticalCrs =\n layer.heightModelInfo?.vertCRS || getI3SVerticalCrsDefinition(spatialReference);\n const heightModel = layer.heightModelInfo?.heightModel;\n const verticalUnit = layer.heightModelInfo?.heightUnit;\n const verticalUnitScale = getI3SVerticalUnitScale(verticalUnit, layer.ZFactor);\n const heightReference =\n heightModel === 'ellipsoidal'\n ? 'ellipsoidal'\n : heightModel === 'gravity_related_height'\n ? 'orthometric'\n : 'unknown';\n const sourceIdentifier = getCrsIdentifier(spatialReference);\n const coordinateFrame =\n sourceIdentifier === undefined\n ? sourceCrs\n ? getSpatialCoordinateFrame(sourceCrs)\n : 'unknown'\n : getSpatialCoordinateFrame(`EPSG:${sourceIdentifier}`);\n const units = getI3SCoordinateUnits(coordinateFrame, verticalUnit, layer.ZFactor);\n const warnings: string[] = [];\n const elevationMode = getI3SElevationMode(layer.elevationInfo?.mode);\n const elevationUnit = layer.elevationInfo ? layer.elevationInfo.unit || 'meter' : undefined;\n const elevationUnitScale = getI3SLinearUnitScale(elevationUnit);\n if (verticalUnitScale === undefined) {\n warnings.push(\n layer.ZFactor !== undefined\n ? `I3S ZFactor ${layer.ZFactor} is not a positive finite conversion factor`\n : `Unsupported I3S vertical unit ${verticalUnit}`\n );\n }\n if (layer.elevationInfo && elevationUnitScale === undefined) {\n warnings.push(`Unsupported I3S elevation unit ${elevationUnit}`);\n }\n if (layer.elevationInfo?.mode && !elevationMode) {\n warnings.push(`Unsupported I3S elevation mode ${layer.elevationInfo.mode}`);\n }\n if (elevationMode && elevationMode !== 'absoluteHeight') {\n warnings.push(\n `I3S elevation mode ${elevationMode} requires a terrain or scene elevation provider`\n );\n }\n\n return createTilesetSpatialReference({\n sourceCrs,\n sourceCrsRepresentation:\n sourceIdentifier !== undefined ? 'identifier' : sourceCrs ? 'wkt' : undefined,\n sourceCrsAlternatives:\n sourceIdentifier !== undefined && spatialReference?.wkt\n ? [{definition: spatialReference.wkt, representation: 'wkt'}]\n : undefined,\n verticalCrs,\n units,\n verticalUnitScale: verticalUnitScale ?? Number.NaN,\n heightReference,\n elevationMode,\n elevationOffset: layer.elevationInfo?.offset,\n elevationUnit,\n elevationUnitScale:\n layer.elevationInfo?.mode && !elevationMode\n ? Number.NaN\n : (elevationUnitScale ?? (layer.elevationInfo ? Number.NaN : 1)),\n coordinateFrame,\n axisOrder: sourceCrs ? 'xyz' : 'unknown',\n provenance: sourceCrs ? 'metadata' : 'unknown',\n warnings\n });\n}\n\n/** Return per-component I3S units only when their coordinate association is unambiguous. */\nfunction getI3SCoordinateUnits(\n coordinateFrame: TilesetSpatialReference['coordinateFrame'],\n verticalUnit: string | undefined,\n zFactor: number | undefined\n): readonly string[] | undefined {\n if (coordinateFrame === 'geocentric') {\n return ['meter', 'meter', 'meter'];\n }\n if (coordinateFrame === 'geographic' && (verticalUnit || zFactor === undefined)) {\n return ['degree', 'degree', verticalUnit || 'meter'];\n }\n return undefined;\n}\n\n/** Return a supported I3S elevation mode without widening the public descriptor. */\nfunction getI3SElevationMode(mode: string | undefined): TilesetElevationMode | undefined {\n switch (mode) {\n case 'absoluteHeight':\n case 'onTheGround':\n case 'relativeToGround':\n case 'relativeToScene':\n return mode;\n default:\n return undefined;\n }\n}\n\n/**\n * Discovers the 3D Tiles geocentric CRS and coordinate epoch from structured metadata semantics.\n *\n * The method intentionally does not infer ECEF from coordinate magnitude. A root `region`\n * establishes the format's global ellipsoidal frame, while local tilesets without an explicit\n * semantic remain unknown.\n *\n * @param tileset - Parsed 3D Tiles tileset document.\n * @returns Normalized source spatial metadata.\n */\nexport function get3DTilesSpatialReference(tileset: Tiles3DLike): TilesetSpatialReference {\n const draftSpatialReference = getDraft3DTilesSpatialReference(tileset);\n if (draftSpatialReference) {\n return draftSpatialReference;\n }\n const geocentricCrs = getTilesetSemanticValue(tileset, 'TILESET_CRS_GEOCENTRIC');\n const coordinateEpoch = getTilesetSemanticValue(tileset, 'TILESET_CRS_COORDINATE_EPOCH');\n const warnings: string[] = [];\n\n let sourceCrs: ReadonlyCRSDefinition | undefined;\n let provenance: TilesetSpatialReference['provenance'] = 'unknown';\n let sourceCrsState: 'explicit' | 'default' | 'unknown' | 'absent' | undefined;\n if (typeof geocentricCrs === 'string' && geocentricCrs.toUpperCase() !== 'UNKNOWN') {\n sourceCrs = geocentricCrs;\n provenance = 'metadata';\n sourceCrsState = 'explicit';\n } else if (geocentricCrs !== undefined) {\n warnings.push('3D Tiles geocentric CRS is explicitly unknown');\n provenance = 'metadata';\n sourceCrsState = 'unknown';\n } else if (tileset.root?.boundingVolume?.region) {\n sourceCrs = 'EPSG:4978';\n provenance = 'format-default';\n sourceCrsState = 'default';\n } else if (tileset.schemaUri && !tileset.schema) {\n warnings.push(\n 'External 3D Tiles metadata schema must be loaded before CRS semantics can resolve'\n );\n }\n\n const epoch = parseCoordinateEpoch(coordinateEpoch);\n if (coordinateEpoch !== undefined && epoch === undefined) {\n warnings.push('3D Tiles coordinate epoch is not a finite decimal year');\n }\n\n return createTilesetSpatialReference({\n sourceCrs,\n sourceCrsState,\n sourceCrsRepresentation: sourceCrs ? 'identifier' : undefined,\n coordinateEpoch: epoch,\n heightReference: sourceCrs ? 'ellipsoidal' : 'unknown',\n coordinateFrame: sourceCrs ? 'geocentric' : 'unknown',\n axisOrder: sourceCrs ? 'xyz' : 'unknown',\n provenance,\n warnings\n });\n}\n\n/** Resolves the draft glTF EXT_geospatial_crs WKID or WKT2 declaration. */\nfunction getDraft3DTilesSpatialReference(\n tileset: Tiles3DLike\n): TilesetSpatialReference | undefined {\n const extension = tileset.extensions?.EXT_geospatial_crs as\n | {format?: unknown; extensions?: Record<string, unknown>}\n | undefined;\n if (!extension) {\n return undefined;\n }\n const warnings: string[] = [];\n let sourceCrs: ReadonlyCRSDefinition | undefined;\n let verticalCrs: ReadonlyCRSDefinition | undefined;\n let epoch: number | undefined;\n let representation: 'identifier' | 'wkt' | undefined;\n if (extension.format === 'wkid') {\n const wkidExtension = extension.extensions?.EXT_geospatial_crs_wkid as\n | {authority?: unknown; wkid?: unknown; vcsWkid?: unknown; epoch?: unknown}\n | undefined;\n if (typeof wkidExtension?.authority === 'string' && Number.isInteger(wkidExtension.wkid)) {\n sourceCrs = `${wkidExtension.authority}:${wkidExtension.wkid}`;\n representation = 'identifier';\n if (Number.isInteger(wkidExtension.vcsWkid)) {\n verticalCrs = `${wkidExtension.authority}:${wkidExtension.vcsWkid}`;\n }\n epoch = parseCoordinateEpoch(wkidExtension.epoch);\n if (wkidExtension.epoch !== undefined && epoch === undefined) {\n warnings.push('EXT_geospatial_crs_wkid epoch is not a finite decimal year');\n }\n } else {\n warnings.push('EXT_geospatial_crs_wkid requires string authority and integer wkid');\n }\n } else if (extension.format === 'wkt2') {\n const wktExtension = extension.extensions?.EXT_geospatial_crs_wkt2 as\n | {wkt2?: unknown}\n | undefined;\n if (typeof wktExtension?.wkt2 === 'string' && wktExtension.wkt2.trim()) {\n sourceCrs = wktExtension.wkt2;\n representation = 'wkt';\n } else {\n warnings.push('EXT_geospatial_crs_wkt2 requires a nonempty wkt2 string');\n }\n } else {\n warnings.push(`Unsupported EXT_geospatial_crs format ${String(extension.format)}`);\n }\n const coordinateFrame =\n representation === 'wkt'\n ? getSpatialCoordinateFrame(sourceCrs as string)\n : getKnownCrsIdentifierCoordinateFrame(sourceCrs) || 'unknown';\n const verticalSemantics = getDraftVerticalCrsSemantics(verticalCrs);\n if (verticalCrs && !verticalSemantics) {\n warnings.push(\n `Unsupported vertical CRS ${String(verticalCrs)}; vertical unit and height reference are unknown`\n );\n }\n const verticalUnit = verticalCrs ? verticalSemantics?.unit : 'meter';\n return createTilesetSpatialReference({\n sourceCrs,\n sourceCrsState: sourceCrs ? 'explicit' : 'unknown',\n sourceCrsRepresentation: representation,\n verticalCrs,\n coordinateEpoch: epoch,\n units:\n coordinateFrame === 'geocentric'\n ? ['meter', 'meter', 'meter']\n : coordinateFrame === 'geographic' && verticalUnit\n ? ['degree', 'degree', verticalUnit]\n : undefined,\n verticalUnitScale: verticalCrs ? (verticalSemantics?.verticalUnitScale ?? Number.NaN) : 1,\n heightReference: verticalCrs\n ? (verticalSemantics?.heightReference ?? 'unknown')\n : sourceCrs\n ? 'ellipsoidal'\n : 'unknown',\n coordinateFrame,\n axisOrder: sourceCrs ? 'xyz' : 'unknown',\n provenance: 'metadata',\n warnings\n });\n}\n\n/** Known vertical CRS semantics needed to interpret draft 3D Tiles height values. */\ntype DraftVerticalCrsSemantics = {\n unit: string;\n verticalUnitScale: number;\n heightReference: 'orthometric';\n};\n\n/** Resolves vertical units and height interpretation for known EPSG vertical CRSs. */\nfunction getDraftVerticalCrsSemantics(\n verticalCrs: ReadonlyCRSDefinition | undefined\n): DraftVerticalCrsSemantics | undefined {\n if (typeof verticalCrs !== 'string') {\n return undefined;\n }\n const epsgMatch = /^EPSG:(\\d+)$/i.exec(verticalCrs);\n if (!epsgMatch) {\n return undefined;\n }\n switch (Number(epsgMatch[1])) {\n case 5702: // NGVD29 height (ftUS)\n case 6360: // NAVD88 height (ftUS)\n return {\n unit: 'us-foot',\n verticalUnitScale: 1200 / 3937,\n heightReference: 'orthometric'\n };\n case 5703: // NAVD88 height\n return {unit: 'meter', verticalUnitScale: 1, heightReference: 'orthometric'};\n default:\n return undefined;\n }\n}\n\n/** Parse the 3D Tiles decimal-year string while tolerating legacy numeric producer output. */\nfunction parseCoordinateEpoch(value: unknown): number | undefined {\n if (typeof value !== 'string' && typeof value !== 'number') {\n return undefined;\n }\n if (typeof value === 'string' && !value.trim()) {\n return undefined;\n }\n const epoch = Number(value);\n return Number.isFinite(epoch) ? epoch : undefined;\n}\n\n/** Return an I3S horizontal CRS definition, preferring current WKID aliases over legacy values. */\nfunction getI3SCrsDefinition(\n spatialReference?: I3SSpatialReferenceLike\n): ReadonlyCRSDefinition | undefined {\n const identifier = getCrsIdentifier(spatialReference);\n if (identifier !== undefined) {\n return `EPSG:${identifier}`;\n }\n return spatialReference?.wkt;\n}\n\n/** Return an I3S vertical CRS definition. */\nfunction getI3SVerticalCrsDefinition(\n spatialReference?: I3SSpatialReferenceLike\n): ReadonlyCRSDefinition | undefined {\n const identifier = spatialReference?.latestVcsWkid ?? spatialReference?.vcsWkid;\n return identifier === undefined ? undefined : `EPSG:${identifier}`;\n}\n\n/** Return the preferred horizontal WKID. */\nfunction getCrsIdentifier(spatialReference?: I3SSpatialReferenceLike): number | undefined {\n return spatialReference?.latestWkid ?? spatialReference?.wkid;\n}\n\n/** Resolve a tileset-wide structured metadata property by its standard semantic. */\nfunction getTilesetSemanticValue(tileset: Tiles3DLike, semantic: string): unknown {\n const classIdentifier = tileset.metadata?.class;\n if (!classIdentifier) {\n return undefined;\n }\n const classDefinition = tileset.schema?.classes?.[classIdentifier] as\n | {properties?: Record<string, Tiles3DMetadataProperty>}\n | undefined;\n const propertyDefinitions = classDefinition?.properties;\n const propertyValues = tileset.metadata?.properties;\n for (const [propertyIdentifier, propertyDefinition] of Object.entries(\n propertyDefinitions || {}\n )) {\n if (propertyDefinition.semantic === semantic) {\n return propertyValues?.[propertyIdentifier];\n }\n }\n return undefined;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Geoid} from '@math.gl/geoid';\nimport {Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport type {ReadonlyCRSDefinition} from '@math.gl/crs';\nimport type {Projection} from '@math.gl/projection';\nimport {ProjectionBuffer} from '@math.gl/projection/bulk';\nimport {getGeoidModel, getSpatialProjectionEngine} from './spatial-resource-registry';\nimport {\n normalizeCrsIdentifier,\n WGS84_GEOCENTRIC_CRS,\n WGS84_GEOGRAPHIC_CRS\n} from './normalize-crs-identifier';\nimport type {\n TilesetHeightReference,\n TilesetSpatialOptions,\n TilesetSpatialReference,\n TilesetTargetHeightReference\n} from './spatial-types';\nexport {getSpatialCoordinateFrame} from './get-spatial-coordinate-frame';\n\n/**\n * Deterministic coordinate transformer used by 3D tile format adapters.\n *\n * The transformer uses conventional `[x, y, z]` array order at its boundary. Format adapters are\n * responsible for mapping authority-axis order into their documented wire order. Requested\n * transformations fail when required definitions or geoid resources are unavailable.\n */\nexport class SpatialCoordinateTransformer {\n /** Normalized spatial metadata describing this transformation. */\n readonly spatialReference: TilesetSpatialReference;\n\n /** Projection from the source CRS directly to the requested horizontal target CRS. */\n private readonly horizontalProjection?: Projection;\n\n /** Reusable packed xyz projection for horizontal-only coordinate batches. */\n private readonly horizontalProjectionBuffer?: ProjectionBuffer;\n\n /** Projection from the source CRS to geographic longitude, latitude, and ellipsoidal height. */\n private readonly geographicProjection?: Projection;\n\n /** Projection from adjusted geographic coordinates to the requested output CRS. */\n private readonly heightOutputProjection?: Projection;\n\n /** Whether source coordinates use the WGS84 geocentric frame handled by math.gl. */\n private readonly sourceIsGeocentric: boolean;\n\n /** Whether output coordinates use the WGS84 geocentric frame handled by math.gl. */\n private readonly outputIsGeocentric: boolean;\n\n /** Whether source coordinates already use conventional WGS84 longitude/latitude order. */\n private readonly sourceIsGeographic: boolean;\n\n /** Whether output coordinates use conventional WGS84 longitude/latitude order. */\n private readonly outputIsGeographic: boolean;\n\n /** Geoid model used to convert between ellipsoidal and orthometric heights. */\n private readonly geoid?: Geoid;\n\n /**\n * Creates a coordinate transformer.\n *\n * @param spatialReference - Format-discovered and option-normalized spatial metadata.\n * @param options - Application options containing an optional geoid model.\n */\n constructor(spatialReference: TilesetSpatialReference, options: TilesetSpatialOptions = {}) {\n this.spatialReference = spatialReference;\n const projectionEngine = getSpatialProjectionEngine();\n validateTransformRequest(spatialReference);\n const outputCrs = spatialReference.targetCrs || spatialReference.sourceCrs;\n this.sourceIsGeocentric = isWgs84Geocentric(spatialReference.sourceCrs);\n this.outputIsGeocentric = isWgs84Geocentric(outputCrs);\n this.sourceIsGeographic = isWgs84Geographic(spatialReference.sourceCrs);\n this.outputIsGeographic = isWgs84Geographic(outputCrs);\n\n if (\n spatialReference.sourceCrs &&\n spatialReference.targetCrs &&\n !this.sourceIsGeocentric &&\n !this.outputIsGeocentric\n ) {\n this.horizontalProjection = projectionEngine.createProjection({\n from: getHorizontalProjectionDefinition(spatialReference.sourceCrs),\n to: getHorizontalProjectionDefinition(spatialReference.targetCrs),\n enforceAxis: false\n });\n if (!requiresHeightTransformation(spatialReference)) {\n this.horizontalProjectionBuffer = new ProjectionBuffer({\n projection: this.horizontalProjection,\n dimension: 3\n });\n }\n }\n\n if (\n requiresHeightTransformation(spatialReference) ||\n this.sourceIsGeocentric ||\n this.outputIsGeocentric\n ) {\n if (!this.sourceIsGeographic && !this.sourceIsGeocentric) {\n this.geographicProjection = projectionEngine.createProjection({\n from: getHorizontalProjectionDefinition(spatialReference.sourceCrs),\n to: WGS84_GEOGRAPHIC_CRS,\n enforceAxis: false\n });\n }\n if (!this.outputIsGeographic && !this.outputIsGeocentric) {\n this.heightOutputProjection = projectionEngine.createProjection({\n from: WGS84_GEOGRAPHIC_CRS,\n to: getHorizontalProjectionDefinition(outputCrs),\n enforceAxis: false\n });\n }\n }\n\n if (requiresHeightTransformation(spatialReference)) {\n this.geoid = resolveGeoid(options.geoidModel);\n if (!this.geoid) {\n const modelName = typeof options.geoidModel === 'string' ? ` \"${options.geoidModel}\"` : '';\n throw new Error(\n `Height conversion requires a registered geoid model${modelName}; ` +\n 'call registerGeoidModel() or pass a parsed Geoid instance'\n );\n }\n }\n }\n\n /**\n * Transforms one `[x, y, z?]` coordinate while retaining additional components.\n *\n * @param coordinate - Source coordinate in the format adapter's normalized `x/y/z` order.\n * @returns A new transformed coordinate array.\n */\n transformPosition(coordinate: readonly number[]): number[] {\n if (coordinate.length < 2) {\n throw new Error('A spatial coordinate must contain at least x and y components');\n }\n\n const result = [...coordinate];\n if (\n requiresHeightTransformation(this.spatialReference) ||\n this.sourceIsGeocentric ||\n this.outputIsGeocentric\n ) {\n if (result.length < 3 || !Number.isFinite(result[2])) {\n throw new Error('Three-dimensional CRS conversion requires a finite z coordinate');\n }\n const geographic = this.toGeographic(result);\n if (requiresHeightTransformation(this.spatialReference)) {\n const geoidUndulation = this.geoid!.getHeight(geographic[1], geographic[0]);\n geographic[2] = transformHeight(\n geographic[2],\n geoidUndulation,\n this.spatialReference.heightReference,\n this.spatialReference.targetHeightReference\n );\n }\n const projected = this.fromGeographic(geographic);\n result.splice(0, projected.length, ...projected);\n return result;\n }\n\n if (this.horizontalProjection) {\n const projected = this.horizontalProjection.projectSync(result.slice(0, 3));\n result.splice(0, projected.length, ...projected);\n }\n return result;\n }\n\n /** Transform packed xyz positions into owned Float64 storage, batching finite horizontal transforms. */\n transformPositions(positions: ArrayLike<number>): Float64Array {\n if (positions.length % 3 !== 0) {\n throw new Error('Packed spatial positions must contain a multiple of three components');\n }\n const transformedPositions = new Float64Array(positions.length);\n if (this.horizontalProjectionBuffer) {\n transformedPositions.set(positions);\n // The bulk API rejects nonfinite ordinates; preserve scalar behavior for those inputs.\n if (transformedPositions.every(Number.isFinite)) {\n return this.horizontalProjectionBuffer.projectFlatTo(\n transformedPositions,\n transformedPositions\n );\n }\n }\n for (let index = 0; index < positions.length; index += 3) {\n const transformed = this.transformPosition([\n Number(positions[index]),\n Number(positions[index + 1]),\n Number(positions[index + 2])\n ]);\n transformedPositions[index] = transformed[0];\n transformedPositions[index + 1] = transformed[1];\n transformedPositions[index + 2] = transformed[2];\n }\n return transformedPositions;\n }\n\n /** Transform packed xyz normals using a local finite-difference tangent approximation. */\n transformNormals(normals: ArrayLike<number>, positions: ArrayLike<number>): Float32Array {\n if (normals.length !== positions.length || normals.length % 3 !== 0) {\n throw new Error('Spatial normals and positions must have matching xyz component counts');\n }\n const transformedNormals = new Float32Array(normals.length);\n const epsilon = 1e-5;\n for (let index = 0; index < normals.length; index += 3) {\n const position = [\n Number(positions[index]),\n Number(positions[index + 1]),\n Number(positions[index + 2])\n ];\n const normal = [\n Number(normals[index]),\n Number(normals[index + 1]),\n Number(normals[index + 2])\n ];\n const jacobian = getFiniteDifferenceJacobian(this, position, epsilon);\n const transformedNormal = inverseTransposeMultiply(jacobian, normal);\n const length = Math.hypot(...transformedNormal);\n if (length > 0 && Number.isFinite(length)) {\n transformedNormals[index] = transformedNormal[0] / length;\n transformedNormals[index + 1] = transformedNormal[1] / length;\n transformedNormals[index + 2] = transformedNormal[2] / length;\n } else {\n transformedNormals[index] = normal[0];\n transformedNormals[index + 1] = normal[1];\n transformedNormals[index + 2] = normal[2];\n }\n }\n return transformedNormals;\n }\n\n /** Convert one source coordinate to conventional WGS84 longitude, latitude, and height. */\n private toGeographic(coordinate: number[]): number[] {\n if (this.sourceIsGeocentric) {\n return Array.from(Ellipsoid.WGS84.cartesianToCartographic(new Vector3(coordinate)));\n }\n if (this.sourceIsGeographic) {\n return coordinate.slice(0, 3);\n }\n return this.geographicProjection!.projectSync(coordinate.slice(0, 3));\n }\n\n /** Convert one conventional WGS84 geographic coordinate to the selected output CRS. */\n private fromGeographic(coordinate: number[]): number[] {\n if (this.outputIsGeocentric) {\n return Array.from(Ellipsoid.WGS84.cartographicToCartesian(new Vector3(coordinate)));\n }\n if (this.outputIsGeographic) {\n return coordinate.slice(0, 3);\n }\n return this.heightOutputProjection!.projectSync(coordinate.slice(0, 3));\n }\n}\n\nfunction getFiniteDifferenceJacobian(\n transformer: SpatialCoordinateTransformer,\n position: number[],\n epsilon: number\n): number[][] {\n const columns: number[][] = [];\n for (let axis = 0; axis < 3; axis++) {\n const plus = position.slice();\n const minus = position.slice();\n plus[axis] += epsilon;\n minus[axis] -= epsilon;\n const plusPosition = transformer.transformPosition(plus);\n const minusPosition = transformer.transformPosition(minus);\n columns.push([\n (plusPosition[0] - minusPosition[0]) / (2 * epsilon),\n (plusPosition[1] - minusPosition[1]) / (2 * epsilon),\n (plusPosition[2] - minusPosition[2]) / (2 * epsilon)\n ]);\n }\n return columns;\n}\n\nfunction inverseTransposeMultiply(jacobianColumns: number[][], vector: number[]): number[] {\n const [a, b, c] = jacobianColumns;\n const determinant =\n a[0] * (b[1] * c[2] - b[2] * c[1]) -\n b[0] * (a[1] * c[2] - a[2] * c[1]) +\n c[0] * (a[1] * b[2] - a[2] * b[1]);\n if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-15) {\n return vector;\n }\n const inverseTranspose = [\n [b[1] * c[2] - b[2] * c[1], a[2] * c[1] - a[1] * c[2], a[1] * b[2] - a[2] * b[1]],\n [b[2] * c[0] - b[0] * c[2], a[0] * c[2] - a[2] * c[0], a[2] * b[0] - a[0] * b[2]],\n [b[0] * c[1] - b[1] * c[0], a[1] * c[0] - a[0] * c[1], a[0] * b[1] - a[1] * b[0]]\n ];\n return inverseTranspose.map(\n row => (row[0] * vector[0] + row[1] * vector[1] + row[2] * vector[2]) / determinant\n );\n}\n\n/** Select the horizontal CRS while height conversion is handled separately. */\nfunction getHorizontalProjectionDefinition(\n definition: ReadonlyCRSDefinition | undefined\n): ReadonlyCRSDefinition {\n if (!definition) {\n throw new Error('Cannot construct a projection because the CRS is unknown');\n }\n if (typeof definition !== 'string' && definition.type === 'CompoundCRS') {\n const horizontalComponents = definition.components.filter(\n component => component.type !== 'VerticalCRS'\n );\n if (horizontalComponents.length !== 1) {\n throw new Error('CompoundCRS requires exactly one horizontal component');\n }\n return getHorizontalProjectionDefinition(horizontalComponents[0]);\n }\n return definition as ReadonlyCRSDefinition;\n}\n\n/** Validate that all requested operations can be represented by the current runtime. */\nfunction validateTransformRequest(spatialReference: TilesetSpatialReference): void {\n if (spatialReference.outputCoordinates === 'local-enu') {\n throw new Error(\n 'local-enu output requires a dataset-derived local origin and must be created by a tileset source'\n );\n }\n if (spatialReference.outputCoordinates === 'target-crs' && !spatialReference.targetCrs) {\n throw new Error('target-crs output requires targetCrs');\n }\n if (!spatialReference.sourceCrs && spatialReference.status === 'unresolved') {\n throw new Error('Cannot transform coordinates because the source CRS is unknown');\n }\n if (\n requiresHeightTransformation(spatialReference) &&\n spatialReference.heightReference === 'unknown'\n ) {\n throw new Error('Cannot convert heights because the source height reference is unknown');\n }\n if (\n spatialReference.coordinateFrame === 'geocentric' &&\n !isWgs84Geocentric(spatialReference.sourceCrs)\n ) {\n throw new Error(\n 'Only EPSG:4978 geocentric coordinates are supported by the current spatial transformer'\n );\n }\n if (spatialReference.status === 'unresolved') {\n throw new Error('The requested spatial output cannot be resolved from the available metadata');\n }\n}\n\n/** Return whether a CRS definition identifies the WGS84 geocentric frame. */\nfunction isWgs84Geocentric(definition: unknown): boolean {\n return (\n typeof definition === 'string' && normalizeCrsIdentifier(definition) === WGS84_GEOCENTRIC_CRS\n );\n}\n\n/** Return whether a CRS definition uses conventional WGS84 longitude/latitude coordinates. */\nfunction isWgs84Geographic(definition: unknown): boolean {\n if (typeof definition !== 'string') {\n return false;\n }\n const identifier = normalizeCrsIdentifier(definition);\n return (\n identifier === WGS84_GEOGRAPHIC_CRS || identifier === 'EPSG:4979' || identifier === 'OGC:CRS84'\n );\n}\n\n/** Return whether source and target height interpretations differ. */\nfunction requiresHeightTransformation(spatialReference: TilesetSpatialReference): boolean {\n const target = spatialReference.targetHeightReference;\n return target !== 'native' && target !== spatialReference.heightReference;\n}\n\n/** Resolve an inline or registered geoid model. */\nfunction resolveGeoid(model: string | Geoid | undefined): Geoid | undefined {\n return typeof model === 'string' ? getGeoidModel(model) : model;\n}\n\n/** Apply the GeographicLib geoid undulation convention, h = H + N. */\nfunction transformHeight(\n height: number,\n geoidUndulation: number,\n source: TilesetHeightReference,\n target: TilesetTargetHeightReference\n): number {\n if (source === target || target === 'native') {\n return height;\n }\n if (source === 'orthometric' && target === 'ellipsoidal') {\n return height + geoidUndulation;\n }\n if (source === 'ellipsoidal' && target === 'orthometric') {\n return height - geoidUndulation;\n }\n throw new Error(`Unsupported height conversion from ${source} to ${target}`);\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Geoid, parsePGM} from '@math.gl/geoid';\nimport {FullProjectionEngine, parseNTv2Grid} from '@math.gl/projection';\nimport type {DatumGrid, ProjectionEngine} from '@math.gl/projection';\nimport type {ReadonlyCRSDefinition} from '@math.gl/crs';\n\nconst geoidModels = new Map<string, Geoid>();\nconst projectionAliases: Record<string, ReadonlyCRSDefinition> = {};\nconst datumGrids: Record<string, DatumGrid> = {};\nlet spatialProjectionEngine: ProjectionEngine = new FullProjectionEngine();\n\n/** Returns the projection engine containing application-registered spatial resources. */\nexport function getSpatialProjectionEngine(): ProjectionEngine {\n return spatialProjectionEngine;\n}\n\n/**\n * Registers an application-supplied CRS alias for deterministic coordinate transformations.\n *\n * loaders.gl never downloads registry definitions implicitly.\n *\n * @param name - Identifier used by dataset metadata or application options.\n * @param definition - CRS definition understood by `@math.gl/projection`.\n */\nexport function registerSpatialCrs(name: string, definition: ReadonlyCRSDefinition): void {\n validateResourceName(name, 'CRS');\n projectionAliases[name] = definition;\n spatialProjectionEngine = new FullProjectionEngine({aliases: projectionAliases, datumGrids});\n}\n\n/**\n * Registers an NTv2 datum grid used by a previously or subsequently registered CRS definition.\n *\n * @param name - Grid name referenced by the Proj4 definition.\n * @param data - Complete NTv2 grid bytes.\n */\nexport function registerSpatialDatumGrid(name: string, data: ArrayBuffer): void {\n validateResourceName(name, 'datum grid');\n datumGrids[name] = parseNTv2Grid(data);\n spatialProjectionEngine = new FullProjectionEngine({aliases: projectionAliases, datumGrids});\n}\n\n/**\n * Registers an already parsed geoid model.\n *\n * @param name - Stable application-local model name.\n * @param geoid - Parsed `@math.gl/geoid` model.\n */\nexport function registerGeoidModel(name: string, geoid: Geoid): void {\n validateResourceName(name, 'geoid model');\n geoidModels.set(name, geoid);\n}\n\n/**\n * Parses and registers a GeographicLib PGM geoid model.\n *\n * @param name - Stable application-local model name.\n * @param data - Complete PGM model bytes.\n * @param options - Interpolation options forwarded to `@math.gl/geoid`.\n * @returns The parsed and registered geoid model.\n */\nexport function registerGeoidModelFromPgm(\n name: string,\n data: Uint8Array,\n options: {cubic?: boolean} = {}\n): Geoid {\n const geoid = parsePGM(data, options);\n registerGeoidModel(name, geoid);\n return geoid;\n}\n\n/**\n * Returns a registered geoid model without initiating network access.\n *\n * @param name - Application-local model name.\n * @returns Registered model, or `undefined` when the application has not supplied it.\n */\nexport function getGeoidModel(name: string): Geoid | undefined {\n return geoidModels.get(name);\n}\n\n/** Validate a caller-controlled spatial resource name. */\nfunction validateResourceName(name: string, resourceType: string): void {\n if (!name.trim()) {\n throw new Error(`${resourceType} name must not be empty`);\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {SpatialCoordinateTransformer} from './spatial-coordinate-transformer';\nimport {Matrix4} from '@math.gl/core';\nimport type {TilesetSpatialOptions, TilesetSpatialReference} from './spatial-types';\n\n/** Structural 3D Tiles volume shape used by the source adapter. */\nexport type Tiles3DSpatialBoundingVolume = {\n box?: number[];\n sphere?: number[];\n region?: number[];\n [key: string]: unknown;\n};\n\n/**\n * Applies nonlinear CRS operations to 3D Tiles geometry bounds.\n *\n * Bounds are rebuilt from conservative samples. This intentionally produces an axis-aligned box\n * in the target frame; it is safe for culling and screen-space-error calculations even when the\n * source volume is rotated or the projection is nonlinear.\n */\nexport class Tiles3DSpatialTransformer {\n /** Normalized reference describing the completed operation. */\n readonly spatialReference: TilesetSpatialReference;\n private readonly coordinateTransformer: SpatialCoordinateTransformer;\n private readonly geographicCoordinateTransformer: SpatialCoordinateTransformer;\n\n /** Creates a 3D Tiles transformer for a requested target CRS. */\n constructor(spatialReference: TilesetSpatialReference, options: TilesetSpatialOptions = {}) {\n this.coordinateTransformer = new SpatialCoordinateTransformer(spatialReference, options);\n // 3D Tiles regions are always encoded as WGS84 longitude/latitude radians, independently\n // of the tileset's local CRS. Build a second pipeline for that fixed source frame.\n const geographicSpatialReference = {\n ...spatialReference,\n sourceCrs: 'EPSG:4326' as const,\n targetCrs: spatialReference.targetCrs || spatialReference.sourceCrs,\n coordinateFrame: 'geographic' as const,\n axisOrder: 'xy' as const\n };\n this.geographicCoordinateTransformer = new SpatialCoordinateTransformer(\n geographicSpatialReference,\n options\n );\n this.spatialReference = spatialReference;\n }\n\n /** Transform packed POSITION values into the target CRS. */\n transformPositions(positions: ArrayLike<number>): Float64Array {\n return this.coordinateTransformer.transformPositions(positions);\n }\n\n /** Transform packed NORMAL values using the corresponding source positions. */\n transformNormals(normals: ArrayLike<number>, positions: ArrayLike<number>): Float32Array {\n return this.coordinateTransformer.transformNormals(normals, positions);\n }\n\n /** Rebuild a conservative target-frame volume from a source volume. */\n transformBoundingVolume(\n volume: Tiles3DSpatialBoundingVolume,\n sourceTransform?: ArrayLike<number>\n ): Tiles3DSpatialBoundingVolume {\n const transform = sourceTransform ? new Matrix4(Array.from(sourceTransform)) : undefined;\n const samples = volume.region\n ? getRegionSamples(volume.region)\n : getVolumeSamples(volume).map(sample =>\n transform ? Array.from(transform.transformAsPoint(sample)) : sample\n );\n if (!samples.length) {\n return volume;\n }\n const transformed = volume.region\n ? samples.map(sample => this.transformRegionSample(sample))\n : samples.map(sample => this.coordinateTransformer.transformPosition(sample));\n return {box: createAxisAlignedBox(transformed)};\n }\n\n /** Transforms one WGS84 region sample into the selected output frame. */\n private transformRegionSample(sample: number[]): number[] {\n return this.geographicCoordinateTransformer.transformPosition(sample);\n }\n}\n\n/** Samples region corners, center lines, and both height planes in degrees/meters. */\nfunction getRegionSamples(region: number[]): number[][] {\n if (region.length < 6 || region.some(value => !Number.isFinite(value))) {\n return [];\n }\n const [west, south, east, north, minimumHeight, maximumHeight] = region;\n const longitudeEnd = east < west ? east + Math.PI * 2 : east;\n const longitudes = getIntervalSamples(west, longitudeEnd);\n const latitudes = getIntervalSamples(south, north);\n const samples: number[][] = [];\n for (const longitude of longitudes) {\n for (const latitude of latitudes) {\n for (const height of [minimumHeight, maximumHeight]) {\n samples.push([(longitude * 180) / Math.PI, (latitude * 180) / Math.PI, height]);\n }\n }\n }\n return samples;\n}\n\n/** Includes interval endpoints and every quarter-turn where ECEF axes reach an extremum. */\nfunction getIntervalSamples(start: number, end: number): number[] {\n const samples = [start, (start + end) / 2, end];\n const angularStep = Math.PI / 2;\n const firstCriticalIndex = Math.ceil(start / angularStep);\n const lastCriticalIndex = Math.floor(end / angularStep);\n for (\n let criticalIndex = firstCriticalIndex;\n criticalIndex <= lastCriticalIndex;\n criticalIndex++\n ) {\n samples.push(criticalIndex * angularStep);\n }\n return samples;\n}\n\nfunction getVolumeSamples(volume: Tiles3DSpatialBoundingVolume): number[][] {\n if (volume.box && volume.box.length >= 12) {\n const center = volume.box.slice(0, 3);\n const axes = [volume.box.slice(3, 6), volume.box.slice(6, 9), volume.box.slice(9, 12)];\n const samples: number[][] = [];\n for (let firstIndex = 0; firstIndex <= 4; firstIndex++) {\n for (let secondIndex = 0; secondIndex <= 4; secondIndex++) {\n for (let thirdIndex = 0; thirdIndex <= 4; thirdIndex++) {\n const first = firstIndex / 2 - 1;\n const second = secondIndex / 2 - 1;\n const third = thirdIndex / 2 - 1;\n samples.push([\n center[0] + first * axes[0][0] + second * axes[1][0] + third * axes[2][0],\n center[1] + first * axes[0][1] + second * axes[1][1] + third * axes[2][1],\n center[2] + first * axes[0][2] + second * axes[1][2] + third * axes[2][2]\n ]);\n }\n }\n }\n return samples;\n }\n if (volume.sphere && volume.sphere.length >= 4) {\n const [x, y, z, radius] = volume.sphere;\n const samples = [\n [x - radius, y, z],\n [x + radius, y, z],\n [x, y - radius, z],\n [x, y + radius, z],\n [x, y, z - radius],\n [x, y, z + radius]\n ];\n for (let longitudeIndex = 0; longitudeIndex < 16; longitudeIndex++) {\n const longitude = (longitudeIndex * Math.PI * 2) / 16;\n samples.push([x + radius * Math.cos(longitude), y + radius * Math.sin(longitude), z]);\n }\n return samples;\n }\n // Regions are already WGS84 geographic volumes. Keep them unchanged until a dedicated\n // geographic-region adapter can account for longitude wrapping and datum semantics.\n return [];\n}\n\nfunction createAxisAlignedBox(samples: number[][]): number[] {\n const minimum = [Infinity, Infinity, Infinity];\n const maximum = [-Infinity, -Infinity, -Infinity];\n for (const sample of samples) {\n for (let axis = 0; axis < 3; axis++) {\n minimum[axis] = Math.min(minimum[axis], sample[axis]);\n maximum[axis] = Math.max(maximum[axis], sample[axis]);\n }\n }\n const padding = [\n Math.max((maximum[0] - minimum[0]) * 0.01, 1e-9),\n Math.max((maximum[1] - minimum[1]) * 0.01, 1e-9),\n Math.max((maximum[2] - minimum[2]) * 0.01, 1e-9)\n ];\n const center = [\n (minimum[0] + maximum[0]) / 2,\n (minimum[1] + maximum[1]) / 2,\n (minimum[2] + maximum[2]) / 2\n ];\n return [\n ...center,\n (maximum[0] - minimum[0]) / 2 + padding[0],\n 0,\n 0,\n 0,\n (maximum[1] - minimum[1]) / 2 + padding[1],\n 0,\n 0,\n 0,\n (maximum[2] - minimum[2]) / 2 + padding[2]\n ];\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright vis.gl contributors\n\nimport {LOD_METRIC_TYPE, TILE_REFINEMENT, TILE_TYPE} from '../../constants';\nimport {getS2DescendantIndex, getS2IndexFromToken, getS2TokenFromIndex} from '@math.gl/dggs/s2';\nimport {convertS2BoundingVolumeToOBB, type S2VolumeInfo} from '../helpers/s2-bounding-volume';\n\nconst QUADTREE_CHILD_COUNT = 4;\nconst OCTREE_CHILD_COUNT = 8;\nconst AVAILABILITY_RANK_CACHE = new WeakMap<ImplicitAvailability, Uint32Array>();\n\n/** Global coordinates of a tile in an implicit quadtree or octree. */\nexport type ImplicitTileCoordinates = {\n /** Zero-based level relative to the implicit-tile root. */\n level: number;\n /** Zero-based horizontal coordinate at {@link level}. */\n x: number;\n /** Zero-based vertical coordinate at {@link level}. */\n y: number;\n /** Zero-based height coordinate at {@link level}; always zero for quadtrees. */\n z: number;\n};\n\n/** Serializable information shared by every subtree in one implicit-tile hierarchy. */\nexport type ImplicitTilingDescriptor = {\n /** Absolute template URL for render content, or an empty string for a contentless hierarchy. */\n contentUrlTemplate: string;\n /** Absolute templates for every implicit content stream, in source order. */\n contentUrlTemplates?: string[];\n /** Non-URI content metadata inherited by each available implicit content resource. */\n contentHeader?: Record<string, any>;\n /** Metadata inherited by every implicit content stream, in source order. */\n contentHeaders?: Array<Record<string, any>>;\n /** Whether generated headers preserve the standard `contents` source representation. */\n useCanonicalContents?: boolean;\n /** Absolute template URL for subtree availability files. */\n subtreesUrlTemplate: string;\n /** Spatial subdivision used by the hierarchy. */\n subdivisionScheme: 'QUADTREE' | 'OCTREE';\n /** Number of tile levels represented inside each subtree file. */\n subtreeLevels: number;\n /** Last valid global tile level, where the implicit root is level zero. */\n maximumLevel: number;\n /** Refinement mode inherited by generated tiles. */\n refine: TILE_REFINEMENT | string;\n /** LOD metric used by generated tiles. */\n lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR;\n /** Source geometric error of the implicit root, in local meters. */\n rootLodMetricValue: number;\n /** Bounding volume of the complete implicit hierarchy. */\n rootBoundingVolume: Record<string, any>;\n /** Whether runtime transforms scale geometric error; false for draft 2.0. */\n scaleGeometricError?: boolean;\n /** Package files that may satisfy concrete content and subtree template references. */\n resourceFiles?: ImplicitPackageFile[];\n};\n\n/** Structured-cloneable file retained from a draft glTF package. */\nexport type ImplicitPackageFile = {\n name?: string;\n mimeType: string;\n uri?: string;\n originalUri?: string;\n data?: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n bufferUri?: string;\n};\n\n/** Package reference attached to a generated content or subtree URL. */\nexport type ImplicitPackageResource = {\n fileIndex: number;\n files: ImplicitPackageFile[];\n};\n\n/** Lazy pointer from a runtime tile to the subtree that defines it and its descendants. */\nexport type ImplicitSubtreeReference = {\n /** Global coordinates of the referenced subtree root. */\n coordinates: ImplicitTileCoordinates;\n /** Absolute subtree URL before source-level query inheritance is applied. */\n subtreeUrl: string;\n /** Serializable hierarchy description used to materialize the subtree. */\n descriptor: ImplicitTilingDescriptor;\n /** Embedded package resource matching {@link subtreeUrl}, when available. */\n resource?: ImplicitPackageResource;\n};\n\n/** Constant or bitstream-backed availability declaration from a parsed subtree. */\nexport type ImplicitAvailability = {\n /** Constant availability value applied to every addressed element. */\n constant?: number;\n /** Expanded least-significant-bit-first availability buffer. */\n explicitBitstream?: Uint8Array;\n};\n\n/** Parsed subset of the 3D Tiles subtree schema needed for hierarchy materialization. */\nexport type ParsedImplicitSubtree = {\n /** Availability of tiles inside this subtree. */\n tileAvailability: ImplicitAvailability;\n /**\n * Availability of tile content. Array entries correspond to content templates in source order.\n * Omitted availability denotes a metadata-only subtree with no render content.\n */\n contentAvailability?: ImplicitAvailability | ImplicitAvailability[];\n /** Availability of subtree roots immediately below this subtree. */\n childSubtreeAvailability: ImplicitAvailability;\n /** Property-table payloads referenced by subtree metadata declarations. */\n propertyTables?: unknown;\n /** Property-table reference for metadata attached to each available tile. */\n tileMetadata?: unknown;\n /** Property-table references for metadata attached to each content stream. */\n contentMetadata?: unknown;\n /** Metadata entity attached to the subtree itself. */\n subtreeMetadata?: unknown;\n /** Decoded standard attribute accessors keyed by tile semantic. */\n tileAttributes?: Record<string, ArrayLike<number>>;\n /** Decoded standard attribute accessors keyed by content semantic. */\n contentAttributes?: Record<string, ArrayLike<number>>;\n /** Index of the property table assigned to available tiles. */\n tileProperties?: unknown;\n /** Index of the property table assigned to available contents. */\n contentProperties?: unknown;\n /** Fully decoded property rows for available tiles, in availability order. */\n tilePropertyRows?: Array<Record<string, unknown>>;\n /** Fully decoded property rows for available contents, in availability order. */\n contentPropertyRows?: Array<Record<string, unknown>>;\n /** Tile property rows filtered to values permitted in URI templates. */\n tileTemplatePropertyRows?: Array<Record<string, unknown>>;\n /** Content property rows filtered to values permitted in URI templates. */\n contentTemplatePropertyRows?: Array<Record<string, unknown>>;\n /** Files retained by a glTF subtree package for later content/subtree resolution. */\n resourceFiles?: ImplicitPackageFile[];\n};\n\n/** Runtime header produced for an available implicit tile. */\nexport type ImplicitTileHeader = Record<string, any> & {\n /** Stable source identity, including global implicit coordinates. */\n id: string;\n /** Materialized children that are represented by the same subtree file. */\n children: ImplicitTileHeader[];\n /** Optional lazy reference when this tile begins a child subtree. */\n implicitSubtree?: ImplicitSubtreeReference;\n /** Raw subtree metadata references preserved for application-level interpretation. */\n implicitMetadata?: ImplicitSubtreeMetadata;\n};\n\n/** Metadata references inherited by generated implicit tile headers. */\nexport type ImplicitSubtreeMetadata = {\n /** Property tables declared by the subtree. */\n propertyTables?: unknown;\n /** Tile-level metadata property-table reference. */\n tileMetadata?: unknown;\n /** Content-level metadata property-table references in content order. */\n contentMetadata?: unknown;\n /** Subtree-level metadata entity. */\n subtreeMetadata?: unknown;\n /** Decoded property-table row for this tile. */\n tileProperties?: Record<string, unknown>;\n /** Decoded property-table row for this tile's available content. */\n contentProperties?: Record<string, unknown>;\n};\n\n/** Result of materializing exactly one subtree resource. */\nexport type MaterializedImplicitSubtree = {\n /** Header for the subtree root, including its in-subtree descendants. */\n root: ImplicitTileHeader;\n /** Number of available headers materialized from this subtree. */\n tileCount: number;\n /** Number of lazy child-subtree references created at the subtree boundary. */\n childSubtreeCount: number;\n};\n\n/**\n * Creates the lazy reference stored on an implicit subtree-root header.\n *\n * @param descriptor - Shared implicit hierarchy description.\n * @param coordinates - Global coordinates of the subtree root.\n * @returns Serializable reference with its concrete subtree URL.\n */\nexport function createImplicitSubtreeReference(\n descriptor: ImplicitTilingDescriptor,\n coordinates: ImplicitTileCoordinates\n): ImplicitSubtreeReference {\n return {\n coordinates,\n subtreeUrl: replaceImplicitUrlTemplate(descriptor.subtreesUrlTemplate, coordinates),\n descriptor,\n resource: findImplicitPackageResource(\n descriptor.resourceFiles,\n replaceImplicitUrlTemplate(descriptor.subtreesUrlTemplate, coordinates)\n )\n };\n}\n\n/**\n * Materializes the available tiles described by one subtree file without performing I/O.\n *\n * The function deliberately stops at the subtree boundary. Available child subtrees become lazy\n * references so traversal, SSE, request-volume checks, and the request scheduler decide when the\n * next network request is useful.\n *\n * @param subtree - Parsed availability data for one subtree resource.\n * @param reference - Coordinates and hierarchy description for the subtree root.\n * @returns Materialized root and diagnostic counts.\n * @throws If the subtree root is unavailable or the descriptor is invalid.\n */\nexport function materializeImplicitSubtree(\n subtree: ParsedImplicitSubtree,\n reference: ImplicitSubtreeReference\n): MaterializedImplicitSubtree {\n const {descriptor} = reference;\n validateImplicitDescriptor(descriptor);\n validateImplicitSubtree(subtree, descriptor);\n\n const counters = {tileCount: 0, childSubtreeCount: 0};\n const root = materializeAvailableTile(\n subtree,\n reference,\n {localLevel: 0, mortonIndex: 0},\n reference.coordinates,\n counters\n );\n\n if (!root) {\n throw new Error(\n `Invalid 3D Tiles subtree: root tile is unavailable at ${reference.subtreeUrl}`\n );\n }\n\n return {root, ...counters};\n}\n\n/** Validates availability lengths and tightly packed draft attribute/property row counts. */\nfunction validateImplicitSubtree(\n subtree: ParsedImplicitSubtree,\n descriptor: ImplicitTilingDescriptor\n): void {\n const childCount = getImplicitChildCount(descriptor.subdivisionScheme);\n const tileElementCount = (childCount ** descriptor.subtreeLevels - 1) / (childCount - 1);\n const childSubtreeElementCount = childCount ** descriptor.subtreeLevels;\n validateAvailabilityLength(subtree.tileAvailability, tileElementCount, 'tile');\n const contentAvailabilityStreams = Array.isArray(subtree.contentAvailability)\n ? subtree.contentAvailability\n : subtree.contentAvailability\n ? [subtree.contentAvailability]\n : [];\n for (const contentAvailability of contentAvailabilityStreams) {\n validateAvailabilityLength(contentAvailability, tileElementCount, 'content');\n }\n validateAvailabilityLength(\n subtree.childSubtreeAvailability,\n childSubtreeElementCount,\n 'child subtree'\n );\n const availableTileCount = countAvailableElements(subtree.tileAvailability, tileElementCount);\n const availableContentCount = contentAvailabilityStreams[0]\n ? countAvailableElements(contentAvailabilityStreams[0], tileElementCount)\n : 0;\n validateAttributeLengths(subtree.tileAttributes, availableTileCount, 'tile');\n validateAttributeLengths(subtree.contentAttributes, availableContentCount, 'content');\n if (subtree.tilePropertyRows && subtree.tilePropertyRows.length !== availableTileCount) {\n throw new Error('3DTILES_subtree: tile property-table count does not match availability');\n }\n if (subtree.contentPropertyRows && subtree.contentPropertyRows.length !== availableContentCount) {\n throw new Error('3DTILES_subtree: content property-table count does not match availability');\n }\n}\n\n/** Verifies that a bitstream contains every bit required by its implicit subtree. */\nfunction validateAvailabilityLength(\n availability: ImplicitAvailability,\n elementCount: number,\n label: string\n): void {\n if (availability.constant === 0 || availability.constant === 1) {\n return;\n }\n if (\n !availability.explicitBitstream ||\n availability.explicitBitstream.byteLength * 8 < elementCount\n ) {\n throw new Error(`3DTILES_subtree: ${label} availability bitstream is too short`);\n }\n}\n\n/** Counts available elements within the meaningful, unpadded part of an availability stream. */\nfunction countAvailableElements(availability: ImplicitAvailability, elementCount: number): number {\n if (availability.constant === 1) {\n return elementCount;\n }\n if (availability.constant === 0) {\n return 0;\n }\n let availableCount = 0;\n for (let index = 0; index < elementCount; index++) {\n if (getAvailabilityValue(availability, index)) {\n availableCount++;\n }\n }\n return availableCount;\n}\n\n/** Validates standard subtree attribute accessor counts after availability expansion. */\nfunction validateAttributeLengths(\n attributes: Record<string, ArrayLike<number>> | undefined,\n availableCount: number,\n label: string\n): void {\n const componentCounts: Record<string, number> = {\n TILE_BOUNDING_BOX: 16,\n TILE_BOUNDING_SPHERE: 4,\n TILE_GEOMETRIC_ERROR: 1,\n TILE_REFINE: 1,\n TILE_TRANSFORM: 16,\n CONTENT_BOUNDING_BOX: 16,\n CONTENT_BOUNDING_SPHERE: 4\n };\n for (const [semantic, values] of Object.entries(attributes || {})) {\n const componentCount = componentCounts[semantic];\n if (componentCount && values.length !== availableCount * componentCount) {\n throw new Error(\n `3DTILES_subtree: ${label} attribute ${semantic} count does not match availability`\n );\n }\n }\n}\n\n/**\n * Replaces implicit coordinate placeholders in a content or subtree URL.\n *\n * @param templateUrl - URL containing level/x/y/z placeholders.\n * @param coordinates - Global coordinates to insert.\n * @returns URL with all coordinate placeholders replaced.\n */\nexport function replaceImplicitUrlTemplate(\n templateUrl: string,\n coordinates: ImplicitTileCoordinates,\n properties: Record<string, unknown> = {}\n): string {\n const values: Record<string, unknown> = {\n level: coordinates.level,\n x: coordinates.x,\n y: coordinates.y,\n z: coordinates.z,\n ...properties\n };\n return templateUrl.replace(/{([^{}]+)}/g, (match, propertyName: string) => {\n const value = Object.hasOwn(values, propertyName)\n ? values[propertyName]\n : values[propertyName.toLowerCase()];\n return value === undefined ? match : String(value);\n });\n}\n\n/**\n * Builds one available tile and recursively materializes descendants in the same subtree.\n *\n * @param subtree - Parsed availability declarations.\n * @param reference - Current subtree reference.\n * @param localCoordinates - Level and Morton index relative to the current subtree.\n * @param globalCoordinates - Coordinates relative to the complete implicit hierarchy.\n * @param counters - Mutable diagnostic counters owned by the public materializer call.\n * @returns Header for an available tile, or `null` for a sparse unavailable position.\n */\nfunction materializeAvailableTile(\n subtree: ParsedImplicitSubtree,\n reference: ImplicitSubtreeReference,\n localCoordinates: {localLevel: number; mortonIndex: number},\n globalCoordinates: ImplicitTileCoordinates,\n counters: {tileCount: number; childSubtreeCount: number}\n): ImplicitTileHeader | null {\n const {descriptor} = reference;\n const childCount = getImplicitChildCount(descriptor.subdivisionScheme);\n const availabilityIndex =\n getLevelOffset(childCount, localCoordinates.localLevel) + localCoordinates.mortonIndex;\n\n if (!getAvailabilityValue(subtree.tileAvailability, availabilityIndex)) {\n return null;\n }\n\n counters.tileCount++;\n const contentAvailability = getContentAvailability(\n subtree.contentAvailability,\n availabilityIndex\n );\n const children: ImplicitTileHeader[] = [];\n\n if (globalCoordinates.level < descriptor.maximumLevel) {\n if (localCoordinates.localLevel + 1 < descriptor.subtreeLevels) {\n for (let childIndex = 0; childIndex < childCount; childIndex++) {\n const childCoordinates = getChildCoordinates(\n globalCoordinates,\n childIndex,\n descriptor.subdivisionScheme\n );\n const childHeader = materializeAvailableTile(\n subtree,\n reference,\n {\n localLevel: localCoordinates.localLevel + 1,\n mortonIndex: localCoordinates.mortonIndex * childCount + childIndex\n },\n childCoordinates,\n counters\n );\n if (childHeader) {\n children.push(childHeader);\n }\n }\n } else {\n for (let childIndex = 0; childIndex < childCount; childIndex++) {\n const childSubtreeIndex = localCoordinates.mortonIndex * childCount + childIndex;\n if (getAvailabilityValue(subtree.childSubtreeAvailability, childSubtreeIndex)) {\n const childCoordinates = getChildCoordinates(\n globalCoordinates,\n childIndex,\n descriptor.subdivisionScheme\n );\n children.push(createLazyImplicitTileHeader(subtree, descriptor, childCoordinates));\n counters.childSubtreeCount++;\n }\n }\n }\n }\n\n return formatImplicitTileHeader(\n subtree,\n descriptor,\n reference,\n globalCoordinates,\n availabilityIndex,\n contentAvailability,\n children\n );\n}\n\n/**\n * Creates a contentless placeholder for an available child subtree.\n *\n * @param descriptor - Shared implicit hierarchy description.\n * @param coordinates - Global coordinates of the child subtree root.\n * @returns Header that participates in culling and SSE before its subtree is requested.\n */\nfunction createLazyImplicitTileHeader(\n subtree: ParsedImplicitSubtree,\n descriptor: ImplicitTilingDescriptor,\n coordinates: ImplicitTileCoordinates\n): ImplicitTileHeader {\n const resourceFiles = mergeImplicitPackageFiles(descriptor.resourceFiles, subtree.resourceFiles);\n const childDescriptor = resourceFiles ? {...descriptor, resourceFiles} : descriptor;\n const reference = createImplicitSubtreeReference(childDescriptor, coordinates);\n return {\n id: getImplicitTileId(reference, coordinates),\n children: [],\n implicitSubtree: reference,\n boundingVolume: calculateImplicitBoundingVolume(\n descriptor.rootBoundingVolume,\n coordinates,\n descriptor.subdivisionScheme\n ),\n geometricError: descriptor.rootLodMetricValue / 2 ** coordinates.level,\n lodMetricType: descriptor.lodMetricType,\n lodMetricValue: descriptor.rootLodMetricValue / 2 ** coordinates.level,\n refine: descriptor.refine,\n type: TILE_TYPE.EMPTY,\n implicitMetadata: getImplicitSubtreeMetadata(subtree),\n _scaleGeometricError: descriptor.scaleGeometricError !== false\n };\n}\n\ntype ImplicitAttributeOverrides = {\n boundingVolume?: Record<string, any>;\n geometricError?: number;\n refine?: TILE_REFINEMENT;\n transform?: number[];\n};\n\n/** Decodes supported standard subtree attributes for one tightly packed available row. */\nfunction getSubtreeAttributeOverrides(\n attributes: Record<string, ArrayLike<number>> | undefined,\n rowIndex: number,\n scope: 'tile' | 'content'\n): ImplicitAttributeOverrides {\n if (!attributes || rowIndex < 0) {\n return {};\n }\n const box = getAttributeComponents(\n attributes[scope === 'tile' ? 'TILE_BOUNDING_BOX' : 'CONTENT_BOUNDING_BOX'],\n rowIndex,\n 16\n );\n const sphere = getAttributeComponents(\n attributes[scope === 'tile' ? 'TILE_BOUNDING_SPHERE' : 'CONTENT_BOUNDING_SPHERE'],\n rowIndex,\n 4\n );\n const boundingVolume = box\n ? {\n box: [\n box[12],\n box[13],\n box[14],\n box[0] / 2,\n box[1] / 2,\n box[2] / 2,\n box[4] / 2,\n box[5] / 2,\n box[6] / 2,\n box[8] / 2,\n box[9] / 2,\n box[10] / 2\n ]\n }\n : sphere\n ? {sphere}\n : undefined;\n if (scope === 'content') {\n return {boundingVolume};\n }\n const geometricError = getAttributeComponents(attributes.TILE_GEOMETRIC_ERROR, rowIndex, 1)?.[0];\n if (geometricError !== undefined && (!Number.isFinite(geometricError) || geometricError < 0)) {\n throw new Error('3DTILES_subtree: TILE_GEOMETRIC_ERROR must be nonnegative');\n }\n const refineValue = getAttributeComponents(attributes.TILE_REFINE, rowIndex, 1)?.[0];\n if (refineValue !== undefined && refineValue !== 0 && refineValue !== 1) {\n throw new Error('3DTILES_subtree: TILE_REFINE must be 0 or 1');\n }\n return {\n boundingVolume,\n geometricError,\n refine:\n refineValue === undefined\n ? undefined\n : refineValue === 0\n ? TILE_REFINEMENT.ADD\n : TILE_REFINEMENT.REPLACE,\n transform: getAttributeComponents(attributes.TILE_TRANSFORM, rowIndex, 16)\n };\n}\n\n/** Copies one logical accessor element and validates its available-row count. */\nfunction getAttributeComponents(\n values: ArrayLike<number> | undefined,\n rowIndex: number,\n componentCount: number\n): number[] | undefined {\n if (!values) {\n return undefined;\n }\n const offset = rowIndex * componentCount;\n if (offset + componentCount > values.length) {\n throw new Error('3DTILES_subtree: attribute accessor is shorter than availability');\n }\n return Array.from({length: componentCount}, (_unused, componentIndex) =>\n Number(values[offset + componentIndex])\n );\n}\n\n/** Returns the tightly packed property/attribute row index for an available element. */\nfunction getAvailabilityRank(availability: ImplicitAvailability, index: number): number {\n if (availability.constant === 1) {\n return index;\n }\n if (availability.constant === 0) {\n return 0;\n }\n let ranks = AVAILABILITY_RANK_CACHE.get(availability);\n if (!ranks) {\n const bitCount = (availability.explicitBitstream?.byteLength || 0) * 8;\n ranks = new Uint32Array(bitCount + 1);\n for (let candidateIndex = 0; candidateIndex < bitCount; candidateIndex++) {\n ranks[candidateIndex + 1] =\n ranks[candidateIndex] + Number(getAvailabilityValue(availability, candidateIndex));\n }\n AVAILABILITY_RANK_CACHE.set(availability, ranks);\n }\n return ranks[index];\n}\n\n/** Locates a concrete generated URI in a retained glTF package. */\nfunction findImplicitPackageResource(\n files: ImplicitPackageFile[] | undefined,\n resourceUrl: string\n): ImplicitPackageResource | undefined {\n if (!files?.length) {\n return undefined;\n }\n const urlWithoutQuery = resourceUrl.split('?')[0];\n const packageRelativePath = /^gltf-package:\\/\\/[^/]+\\/(.*)$/.exec(urlWithoutQuery)?.[1];\n const exactFileIndex = files.findIndex(file => {\n const reference = file.originalUri || file.name;\n return (\n file.uri === urlWithoutQuery ||\n Boolean(reference && (urlWithoutQuery === reference || packageRelativePath === reference))\n );\n });\n if (exactFileIndex >= 0) {\n return {fileIndex: exactFileIndex, files};\n }\n const fileIndex = files.findIndex(file => {\n const reference = file.originalUri || file.name;\n return Boolean(\n reference &&\n (urlWithoutQuery.endsWith(`/${reference}`) || urlWithoutQuery.endsWith(`:${reference}`))\n );\n });\n return fileIndex < 0 ? undefined : {fileIndex, files};\n}\n\n/** Layers files declared by a child package over inherited parent-package files. */\nfunction mergeImplicitPackageFiles(\n parentFiles: ImplicitPackageFile[] | undefined,\n childFiles: ImplicitPackageFile[] | undefined\n): ImplicitPackageFile[] | undefined {\n if (!childFiles?.length) {\n return parentFiles;\n }\n if (!parentFiles?.length) {\n return childFiles;\n }\n const childReferences = new Set(\n childFiles.flatMap(file => [file.uri, file.originalUri, file.name].filter(Boolean) as string[])\n );\n return [\n ...childFiles,\n ...parentFiles.filter(\n file =>\n ![file.uri, file.originalUri, file.name].some(\n reference => reference && childReferences.has(reference)\n )\n )\n ];\n}\n\n/**\n * Formats an available implicit tile as a runtime header.\n *\n * @param descriptor - Shared implicit hierarchy description.\n * @param reference - Current subtree reference used to build stable IDs.\n * @param coordinates - Global tile coordinates.\n * @param contentAvailability - Availability for each content stream in source order.\n * @param children - Materialized or lazy child headers.\n * @returns Runtime tile header.\n */\nfunction formatImplicitTileHeader(\n subtree: ParsedImplicitSubtree,\n descriptor: ImplicitTilingDescriptor,\n reference: ImplicitSubtreeReference,\n coordinates: ImplicitTileCoordinates,\n availabilityIndex: number,\n contentAvailability: boolean[],\n children: ImplicitTileHeader[]\n): ImplicitTileHeader {\n const tilePropertyIndex = getAvailabilityRank(subtree.tileAvailability, availabilityIndex);\n const tileProperties = subtree.tilePropertyRows?.[tilePropertyIndex];\n const primaryContentAvailability = Array.isArray(subtree.contentAvailability)\n ? subtree.contentAvailability[0]\n : subtree.contentAvailability;\n const contentPropertyIndex =\n primaryContentAvailability &&\n getAvailabilityValue(primaryContentAvailability, availabilityIndex)\n ? getAvailabilityRank(primaryContentAvailability, availabilityIndex)\n : -1;\n const contentProperties = subtree.contentPropertyRows?.[contentPropertyIndex];\n const tileTemplateProperties =\n subtree.tileTemplatePropertyRows?.[tilePropertyIndex] || tileProperties;\n const contentTemplateProperties =\n subtree.contentTemplatePropertyRows?.[contentPropertyIndex] || contentProperties;\n const templateProperties = {...tileTemplateProperties, ...contentTemplateProperties};\n const tileAttributes = getSubtreeAttributeOverrides(\n subtree.tileAttributes,\n tilePropertyIndex,\n 'tile'\n );\n const contentAttributes = getSubtreeAttributeOverrides(\n subtree.contentAttributes,\n contentPropertyIndex,\n 'content'\n );\n const contentUrlTemplates = descriptor.contentUrlTemplates?.length\n ? descriptor.contentUrlTemplates\n : [descriptor.contentUrlTemplate];\n const contentEntries = contentUrlTemplates\n .map((templateUrl, contentIndex) => {\n if (!contentAvailability[contentIndex] || !templateUrl) {\n return null;\n }\n const contentUrl = replaceImplicitUrlTemplate(templateUrl, coordinates, templateProperties);\n if (/{[^{}]+}/.test(contentUrl)) {\n throw new Error(`Implicit content URI has unresolved template values: ${contentUrl}`);\n }\n return {\n contentIndex,\n contentUrl\n };\n })\n .filter((entry): entry is {contentIndex: number; contentUrl: string} => Boolean(entry));\n const availableContentUrls = contentEntries.map(entry => entry.contentUrl);\n const resourceFiles = mergeImplicitPackageFiles(descriptor.resourceFiles, subtree.resourceFiles);\n const content = contentEntries.map(({contentIndex, contentUrl}) => {\n const packageResource = findImplicitPackageResource(resourceFiles, contentUrl);\n return {\n ...(descriptor.contentHeaders?.[contentIndex] ||\n (contentIndex === 0 ? descriptor.contentHeader : {}) ||\n {}),\n ...contentAttributes,\n uri: contentUrl,\n ...(contentProperties ? {metadata: {properties: contentProperties}} : {}),\n ...(packageResource ? {_resource: packageResource} : {})\n };\n });\n const contentUrl = availableContentUrls[0];\n const computedLodMetricValue = descriptor.rootLodMetricValue / 2 ** coordinates.level;\n const lodMetricValue = tileAttributes.geometricError ?? computedLodMetricValue;\n const computedBoundingVolume = calculateImplicitBoundingVolume(\n descriptor.rootBoundingVolume,\n coordinates,\n descriptor.subdivisionScheme\n );\n\n return {\n id: getImplicitTileId(reference, coordinates),\n children,\n contentUrl,\n content: content.length > 1 ? content : content[0],\n contents: descriptor.useCanonicalContents && content.length ? content : undefined,\n contentUrls: availableContentUrls,\n refine: tileAttributes.refine || descriptor.refine,\n type: getImplicitTileType(contentUrl),\n lodMetricType: descriptor.lodMetricType,\n lodMetricValue,\n geometricError: lodMetricValue,\n boundingVolume: tileAttributes.boundingVolume || computedBoundingVolume,\n transform: tileAttributes.transform,\n transformMatrix: tileAttributes.transform,\n metadata: tileProperties ? {properties: tileProperties} : undefined,\n implicitMetadata: getImplicitSubtreeMetadata(subtree, tileProperties, contentProperties),\n _scaleGeometricError: descriptor.scaleGeometricError !== false\n };\n}\n\n/**\n * Copies subtree metadata references without interpreting property-table schemas.\n *\n * Keeping the references on generated headers makes metadata available to applications while\n * avoiding a false promise that the runtime has already decoded classes, enums, or values.\n *\n * @param subtree - Parsed subtree containing optional metadata declarations.\n * @returns Metadata references, or `undefined` when the subtree declares none.\n */\nfunction getImplicitSubtreeMetadata(\n subtree: ParsedImplicitSubtree,\n tileProperties?: Record<string, unknown>,\n contentProperties?: Record<string, unknown>\n): ImplicitSubtreeMetadata | undefined {\n if (\n !subtree.propertyTables &&\n subtree.tileMetadata === undefined &&\n !subtree.contentMetadata &&\n subtree.subtreeMetadata === undefined &&\n !tileProperties &&\n !contentProperties\n ) {\n return undefined;\n }\n return {\n propertyTables: subtree.propertyTables,\n tileMetadata: subtree.tileMetadata,\n contentMetadata: subtree.contentMetadata,\n subtreeMetadata: subtree.subtreeMetadata,\n tileProperties,\n contentProperties\n };\n}\n\n/**\n * Returns a stable identity for contentless and content-bearing implicit tiles.\n *\n * @param reference - Owning subtree reference.\n * @param coordinates - Global tile coordinates.\n * @returns Stable source identity independent of content availability.\n */\nfunction getImplicitTileId(\n reference: ImplicitSubtreeReference,\n coordinates: ImplicitTileCoordinates\n): string {\n return `${reference.subtreeUrl}#implicit=${coordinates.level}/${coordinates.x}/${coordinates.y}/${coordinates.z}`;\n}\n\n/**\n * Reads an availability bit without assuming 32-bit coordinate or Morton arithmetic.\n *\n * @param availability - Constant or expanded bitstream availability.\n * @param index - Zero-based availability index.\n * @returns Whether the addressed tile, content, or child subtree exists.\n */\nfunction getAvailabilityValue(availability: ImplicitAvailability, index: number): boolean {\n if (typeof availability?.constant === 'number') {\n return Boolean(availability.constant);\n }\n const bitstream = availability?.explicitBitstream;\n if (!bitstream) {\n return false;\n }\n const byteIndex = Math.floor(index / 8);\n const bitIndex = index % 8;\n return Boolean((bitstream[byteIndex] >> bitIndex) & 1);\n}\n\n/**\n * Reads every content availability stream for one tile in descriptor/source order.\n *\n * @param availability - Single or multiple-content availability declaration.\n * @returns Availability flags aligned with the content URL templates.\n */\nfunction getContentAvailability(\n availability: ImplicitAvailability | ImplicitAvailability[] | undefined,\n index: number\n): boolean[] {\n const streams = Array.isArray(availability) ? availability : [availability];\n return streams.map(stream => getAvailabilityValue(stream || {constant: 0}, index));\n}\n\n/**\n * Calculates the breadth-first availability offset for a local subtree level.\n *\n * @param childCount - Branching factor of the subdivision scheme.\n * @param localLevel - Level relative to the subtree root.\n * @returns First availability index for the requested level.\n */\nfunction getLevelOffset(childCount: number, localLevel: number): number {\n return (childCount ** localLevel - 1) / (childCount - 1);\n}\n\n/**\n * Calculates one child's global implicit coordinates.\n *\n * @param parent - Global parent coordinates.\n * @param childIndex - Morton-ordered child index.\n * @param subdivisionScheme - Quadtree or octree subdivision.\n * @returns Global child coordinates.\n */\nfunction getChildCoordinates(\n parent: ImplicitTileCoordinates,\n childIndex: number,\n subdivisionScheme: 'QUADTREE' | 'OCTREE'\n): ImplicitTileCoordinates {\n return {\n level: parent.level + 1,\n x: parent.x * 2 + (childIndex & 1),\n y: parent.y * 2 + ((childIndex >> 1) & 1),\n z: subdivisionScheme === 'OCTREE' ? parent.z * 2 + ((childIndex >> 2) & 1) : 0\n };\n}\n\n/**\n * Returns the branching factor for a supported implicit subdivision scheme.\n *\n * @param subdivisionScheme - Quadtree or octree subdivision.\n * @returns Four for quadtrees or eight for octrees.\n */\nfunction getImplicitChildCount(subdivisionScheme: 'QUADTREE' | 'OCTREE'): number {\n return subdivisionScheme === 'OCTREE' ? OCTREE_CHILD_COUNT : QUADTREE_CHILD_COUNT;\n}\n\n/**\n * Calculates the bounding volume for global implicit coordinates.\n *\n * Region volumes are divided in longitude/latitude and, for octrees, height. Oriented boxes are\n * divided along their half-axis vectors. S2 roots use math.gl's Hilbert-aware descendant indexing\n * to produce the exact child token and a corresponding geospatial oriented box.\n *\n * @param rootBoundingVolume - Bounding volume of the complete implicit hierarchy.\n * @param coordinates - Global tile coordinates.\n * @param subdivisionScheme - Quadtree or octree subdivision.\n * @returns Bounding volume for the addressed tile.\n */\nfunction calculateImplicitBoundingVolume(\n rootBoundingVolume: Record<string, any>,\n coordinates: ImplicitTileCoordinates,\n subdivisionScheme: 'QUADTREE' | 'OCTREE'\n): Record<string, any> {\n if (rootBoundingVolume.region) {\n const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;\n const divisionCount = 2 ** coordinates.level;\n const longitudeSpan = east >= west ? east - west : east + 2 * Math.PI - west;\n const longitudeSize = longitudeSpan / divisionCount;\n const latitudeSize = (north - south) / divisionCount;\n const childWest = normalizeRegionLongitude(west + longitudeSize * coordinates.x);\n const childEast = normalizeRegionLongitude(west + longitudeSize * (coordinates.x + 1));\n const childSouth = south + latitudeSize * coordinates.y;\n let childMinimumHeight = minimumHeight;\n let childMaximumHeight = maximumHeight;\n if (subdivisionScheme === 'OCTREE') {\n const heightSize = (maximumHeight - minimumHeight) / divisionCount;\n childMinimumHeight = minimumHeight + heightSize * coordinates.z;\n childMaximumHeight = childMinimumHeight + heightSize;\n }\n return {\n region: [\n childWest,\n childSouth,\n childEast,\n childSouth + latitudeSize,\n childMinimumHeight,\n childMaximumHeight\n ]\n };\n }\n\n if (rootBoundingVolume.box) {\n if (rootBoundingVolume.s2VolumeInfo) {\n return calculateS2ImplicitBoundingVolume(rootBoundingVolume, coordinates, subdivisionScheme);\n }\n if (rootBoundingVolume.extensions?.['3DTILES_shape_cylinder_region']) {\n return {\n ...rootBoundingVolume,\n box: [...rootBoundingVolume.box]\n };\n }\n const box = rootBoundingVolume.box;\n const divisionCount = 2 ** coordinates.level;\n const xOffset = -1 + (2 * coordinates.x + 1) / divisionCount;\n const yOffset = -1 + (2 * coordinates.y + 1) / divisionCount;\n const zOffset = -1 + (2 * coordinates.z + 1) / divisionCount;\n const divideHeight = subdivisionScheme === 'OCTREE';\n const center = [\n box[0] + box[3] * xOffset + box[6] * yOffset + (divideHeight ? box[9] * zOffset : 0),\n box[1] + box[4] * xOffset + box[7] * yOffset + (divideHeight ? box[10] * zOffset : 0),\n box[2] + box[5] * xOffset + box[8] * yOffset + (divideHeight ? box[11] * zOffset : 0)\n ];\n return {\n box: [\n ...center,\n box[3] / divisionCount,\n box[4] / divisionCount,\n box[5] / divisionCount,\n box[6] / divisionCount,\n box[7] / divisionCount,\n box[8] / divisionCount,\n divideHeight ? box[9] / divisionCount : box[9],\n divideHeight ? box[10] / divisionCount : box[10],\n divideHeight ? box[11] / divisionCount : box[11]\n ]\n };\n }\n\n throw new Error(\n `Unsupported implicit 3D Tiles bounding volume: ${JSON.stringify(rootBoundingVolume)}`\n );\n}\n\n/**\n * Calculates an implicit descendant of an S2 root using math.gl's canonical Hilbert hierarchy.\n *\n * @param rootBoundingVolume - Normalized S2 root volume.\n * @param coordinates - Global implicit tile coordinates.\n * @param subdivisionScheme - Quadtree or octree subdivision.\n * @returns Child volume with updated S2 metadata and oriented box.\n */\nfunction calculateS2ImplicitBoundingVolume(\n rootBoundingVolume: Record<string, any>,\n coordinates: ImplicitTileCoordinates,\n subdivisionScheme: 'QUADTREE' | 'OCTREE'\n): Record<string, any> {\n const rootS2VolumeInfo = rootBoundingVolume.s2VolumeInfo as S2VolumeInfo;\n const rootIndex = getS2IndexFromToken(rootS2VolumeInfo.token);\n const descendantIndex = getS2DescendantIndex(\n rootIndex,\n coordinates.level,\n coordinates.x,\n coordinates.y\n );\n const divisionCount = 2 ** coordinates.level;\n const heightSize =\n (rootS2VolumeInfo.maximumHeight - rootS2VolumeInfo.minimumHeight) / divisionCount;\n const childS2VolumeInfo: S2VolumeInfo = {\n token: getS2TokenFromIndex(descendantIndex),\n minimumHeight:\n rootS2VolumeInfo.minimumHeight +\n (subdivisionScheme === 'OCTREE' ? heightSize * coordinates.z : 0),\n maximumHeight:\n rootS2VolumeInfo.minimumHeight +\n (subdivisionScheme === 'OCTREE'\n ? heightSize * (coordinates.z + 1)\n : heightSize * divisionCount)\n };\n const extensions = rootBoundingVolume.extensions ? {...rootBoundingVolume.extensions} : undefined;\n if (extensions?.['3DTILES_bounding_volume_S2']) {\n extensions['3DTILES_bounding_volume_S2'] = childS2VolumeInfo;\n }\n if (extensions?.['3DTILES_shape_s2']) {\n extensions['3DTILES_shape_s2'] = childS2VolumeInfo;\n }\n return {\n ...rootBoundingVolume,\n ...(extensions ? {extensions} : {}),\n s2VolumeInfo: childS2VolumeInfo,\n box: convertS2BoundingVolumeToOBB(childS2VolumeInfo)\n };\n}\n\n/** Normalize a longitude while preserving the positive pi boundary for non-wrapped regions. */\nfunction normalizeRegionLongitude(longitude: number): number {\n let normalizedLongitude = longitude;\n while (normalizedLongitude > Math.PI) {\n normalizedLongitude -= 2 * Math.PI;\n }\n while (normalizedLongitude < -Math.PI) {\n normalizedLongitude += 2 * Math.PI;\n }\n return normalizedLongitude;\n}\n\n/**\n * Detects the runtime tile category from an available content URL.\n *\n * @param contentUrl - Concrete content URL, if content is available.\n * @returns Runtime tile category.\n */\nfunction getImplicitTileType(contentUrl?: string): TILE_TYPE | string {\n if (!contentUrl) {\n return TILE_TYPE.EMPTY;\n }\n const extension = contentUrl.split('?')[0].split('.').pop()?.toLowerCase();\n switch (extension) {\n case 'pnts':\n return TILE_TYPE.POINTCLOUD;\n case 'i3dm':\n case 'b3dm':\n case 'glb':\n case 'gltf':\n return TILE_TYPE.SCENEGRAPH;\n default:\n return extension || TILE_TYPE.EMPTY;\n }\n}\n\n/**\n * Validates descriptor invariants before allocating a runtime subtree.\n *\n * @param descriptor - Serializable implicit hierarchy description.\n * @throws If levels, scheme, or maximum-level semantics are invalid.\n */\nfunction validateImplicitDescriptor(descriptor: ImplicitTilingDescriptor): void {\n if (descriptor.subdivisionScheme !== 'QUADTREE' && descriptor.subdivisionScheme !== 'OCTREE') {\n throw new Error(`Unsupported implicit subdivision scheme: ${descriptor.subdivisionScheme}`);\n }\n if (!Number.isInteger(descriptor.subtreeLevels) || descriptor.subtreeLevels < 1) {\n throw new Error('Implicit subtreeLevels must be a positive integer');\n }\n if (!Number.isInteger(descriptor.maximumLevel) || descriptor.maximumLevel < 0) {\n throw new Error('Implicit availableLevels must describe at least the root level');\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright vis.gl contributors\n\nimport {getS2Bounds} from '@math.gl/dggs/s2';\nimport {Ellipsoid, makeOBBFromRegion} from '@math.gl/geospatial';\n\n/** Serialized S2 cell metadata used by 3D Tiles bounding-volume extensions. */\nexport type S2VolumeInfo = {\n /** S2 key or token. */\n token: string;\n /** Minimum height in meters. */\n minimumHeight: number;\n /** Maximum height in meters. */\n maximumHeight: number;\n};\n\n/**\n * Converts an S2 cell and its vertical range to the runtime oriented-box representation.\n *\n * @param s2VolumeInfo - S2 cell token and height range.\n * @returns A twelve-component center/half-axis oriented bounding box.\n */\nexport function convertS2BoundingVolumeToOBB(s2VolumeInfo: S2VolumeInfo): number[] {\n const [[west, south], [east, north]] = getS2Bounds(s2VolumeInfo.token);\n const orientedBoundingBox = makeOBBFromRegion(\n [west, south, east, north, s2VolumeInfo.minimumHeight, s2VolumeInfo.maximumHeight],\n Ellipsoid.WGS84,\n {units: 'degrees'}\n );\n return [...orientedBoundingBox.center, ...orientedBoundingBox.halfAxes];\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {path} from '@loaders.gl/loader-utils';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Vector3} from '@math.gl/core';\nimport type {CoreAPI, Loader, LoaderOptions} from '@loaders.gl/loader-utils';\nimport type {Tile3D} from '../common/tile-3d';\nimport {Tile3D as Tile3DNode} from '../common/tile-3d';\nimport type {Tile3DContent} from '../common/tile-3d-contracts';\nimport {I3STilesetTraverser} from './i3s-tileset-traverser';\nimport type {Tileset3D} from '../common/tileset-3d';\nimport type {FrameState} from '../helpers/frame-state';\nimport type {\n TileChildrenLoadResult,\n TileContentLoadResult,\n TilesetContentFormats,\n TilesetJSON,\n Tileset3DSource,\n TilesetSourceInput,\n TilesetSourceMetadata,\n TilesetSourceRequest,\n TilesetSourceResolver,\n TilesetSourceViewState\n} from '../common/tileset-source';\nimport {getZoomFromExtent, getZoomFromFullExtent} from '../helpers/zoom';\nimport {TILESET_TYPE} from '../../constants';\nimport type {TilesetTraverser, TilesetTraverserProps} from '../common/tileset-traverser';\nimport {getI3SSpatialReference} from '../../spatial/format-spatial-reference';\nimport {I3SSpatialTransformer} from '../../spatial/i3s-spatial-transformer';\n\nconst EMPTY_CONTENT_FORMATS: TilesetContentFormats = {\n draco: false,\n meshopt: false,\n dds: false,\n ktx2: false\n};\n\n/**\n * {@link Tileset3DSource} implementation for I3S datasets.\n */\nexport class I3SSource implements Tileset3DSource {\n /** I3S format discriminator. */\n readonly type = TILESET_TYPE.I3S;\n /** Primary I3S loader used for root and child metadata requests. */\n readonly loader: Loader;\n /** Worker-capable loader used for binary tile content when supplied by the format loader. */\n readonly contentLoader: Loader;\n /** Root I3S layer URL. */\n readonly url: string;\n /** Base path used for relative tile resource resolution. */\n readonly basePath: string;\n /** Parsed I3S layer metadata. */\n tileset: TilesetJSON | null = null;\n /** Loader options forwarded to tile requests. */\n readonly loadOptions: LoaderOptions;\n /** Core API used for metadata and tile-content loads when injected by the caller. */\n coreApi?: CoreAPI;\n /** Aggregate content-format flags discovered during streaming. */\n readonly contentFormats: TilesetContentFormats = {...EMPTY_CONTENT_FORMATS};\n\n asset?: Record<string, any>;\n properties?: any;\n extras?: any;\n credits?: any;\n metadata?: TilesetSourceMetadata;\n\n private readonly queryParams: Record<string, string> = {};\n private readonly resolver?: TilesetSourceResolver;\n private rootTileset: TilesetJSON;\n /** Spatial adapter created lazily after Tileset3D applies target options. */\n private spatialTransformer?: I3SSpatialTransformer;\n /** Root header prepared after asynchronous elevation sampling. */\n private preparedRootHeader?: any;\n\n /**\n * Creates an I3S source.\n * @param input Root metadata request, or preloaded root metadata for tests and internal callers.\n * @param loadOptions Loader options forwarded to tile requests.\n */\n constructor(input: TilesetSourceInput, loadOptions: LoaderOptions = {}) {\n const request = normalizeI3SRequest(input);\n this.rootTileset = isTilesetRequest(input) ? null : input;\n this.tileset = this.rootTileset;\n this.loader = request.loader;\n this.contentLoader = getI3SContentLoader(request.loader);\n this.url = request.url;\n this.basePath = request.basePath || path.dirname(request.url);\n this.resolver = request.resolver;\n this.coreApi = request.coreApi;\n this.loadOptions = loadOptions;\n this.initializeQueryParams(loadOptions);\n }\n\n /**\n * Fetches and normalizes root I3S metadata for runtime consumption.\n */\n async initialize(): Promise<void> {\n if (!this.rootTileset) {\n this.rootTileset = await this.loadRootData(this.getTileUrl(this.url), {\n ...this.loadOptions,\n i3s: {...(this.loadOptions.i3s as Record<string, unknown>), isTileset: true}\n });\n }\n this.tileset = this.rootTileset;\n\n if (this.rootTileset.root && typeof this.rootTileset.root.then === 'function') {\n this.rootTileset.root = await this.rootTileset.root;\n }\n\n this.metadata = {\n type: this.type,\n loader: this.loader,\n url: this.url,\n basePath: this.basePath,\n tileset: this.rootTileset,\n lodMetricType: this.rootTileset.lodMetricType,\n lodMetricValue: this.rootTileset.lodMetricValue,\n refine: this.rootTileset.root?.refine,\n spatialReference: getI3SSpatialReference(this.rootTileset)\n };\n }\n\n /**\n * Returns normalized source metadata after initialization.\n */\n getMetadata(): TilesetSourceMetadata {\n if (!this.metadata) {\n throw new Error('I3SSource has not been initialized');\n }\n return this.metadata;\n }\n\n /**\n * Returns the initialized I3S root metadata.\n */\n async getRootTileset(): Promise<TilesetJSON> {\n return this.getMetadata().tileset;\n }\n\n /** Prepare option-dependent spatial state and the asynchronously placed root bound. */\n async prepareTileset(tileset: Tileset3D): Promise<void> {\n const spatialReference = tileset.spatialReference;\n if (spatialReference.status === 'unresolved') {\n throw new Error(\n spatialReference.warnings[0] ||\n 'I3S spatial operations cannot be resolved from the supplied metadata and options'\n );\n }\n if (spatialReference.status !== 'transformable' && spatialReference.status !== 'transformed') {\n return;\n }\n this.spatialTransformer ||= new I3SSpatialTransformer(\n spatialReference,\n tileset.options.spatial\n );\n tileset.spatialReference = this.spatialTransformer.spatialReference;\n this.preparedRootHeader = await this.transformTileHeader(this.getMetadata().tileset.root);\n }\n\n /**\n * Creates the runtime root tile for an I3S subtree.\n */\n initializeTileHeaders(\n tileset: Tileset3D,\n tilesetJson: TilesetJSON,\n parentTile?: Tile3D | null\n ): Tile3D {\n const rootHeader = parentTile ? tilesetJson.root : this.preparedRootHeader || tilesetJson.root;\n if (this.spatialTransformer && !this.preparedRootHeader) {\n throw new Error('I3S spatial root header was not prepared before tile initialization');\n }\n const rootTile = new Tile3DNode(tileset, rootHeader, parentTile || undefined);\n if (parentTile) {\n parentTile.children.push(rootTile);\n rootTile.depth = parentTile.depth + 1;\n }\n return rootTile;\n }\n\n /**\n * Creates the standard I3S traverser.\n */\n createTraverser(options: TilesetTraverserProps): TilesetTraverser {\n return new I3STilesetTraverser(options);\n }\n\n /**\n * Loads renderable content for an I3S tile.\n */\n async loadTileContent(tile: Tile3D): Promise<TileContentLoadResult> {\n const contentUrl = this.getTileUrl(tile.contentUrl);\n const loaderId = this.loader.id;\n const loaderOptions = (this.loadOptions[loaderId] as Record<string, unknown>) || {};\n const metadata = this.getMetadata();\n const options = {\n ...this.loadOptions,\n [loaderId]: {\n ...loaderOptions,\n ...tile.tileset.options.i3s,\n _tileOptions: {\n attributeUrls: tile.header.attributeUrls,\n textureUrl: tile.header.textureUrl,\n textureUrls: tile.header.textureUrls,\n textureFormat: tile.header.textureFormat,\n textureLoaderOptions: tile.header.textureLoaderOptions,\n materialDefinition: tile.header.materialDefinition,\n layerType: tile.header.layerType,\n pointRenderer: tile.header.pointRenderer,\n pointSymbol: tile.header.pointSymbol,\n isDracoGeometry: tile.header.isDracoGeometry,\n mbs: tile.header.mbs\n },\n _tilesetOptions: {\n store: metadata.tileset.store,\n attributeStorageInfo: metadata.tileset.attributeStorageInfo,\n fields: metadata.tileset.fields,\n spatialReference: tile.tileset.spatialReference,\n spatialOptions: tile.tileset.options.spatial\n },\n isTileHeader: false\n }\n };\n\n tile.content = await this.loadResourceData(contentUrl, options, this.contentLoader);\n const contentEntry: Tile3DContent = {\n index: 0,\n uri: tile.contentUrl,\n type: tile.header.layerType,\n payload: tile.content,\n metadata: tile.header.metadata || null,\n boundingVolume: tile.boundingVolume,\n featureIds: tile.featureIdSets,\n renderable: Boolean(tile.content)\n };\n return {loaded: true, contents: [tile.content], contentEntries: [contentEntry]};\n }\n\n /**\n * Loads child tile metadata on demand from node pages or `/nodes/{id}` resources.\n */\n async loadChildTileHeader(\n _parentTile: Tile3D,\n childId: string,\n _frameState: FrameState | null\n ): Promise<any> {\n const metadata = this.getMetadata();\n if (metadata.tileset.nodePages || metadata.tileset.pointNodePages) {\n const header = await metadata.tileset.nodePagesTile.formTileFromNodePages(childId);\n return await this.transformTileHeader(header);\n }\n\n const nodeUrl = this.getTileUrl(`${this.url}/nodes/${childId}`);\n const i3sLoaderOptions =\n this.loadOptions.i3s && typeof this.loadOptions.i3s === 'object'\n ? (this.loadOptions.i3s as Record<string, unknown>)\n : {};\n const options = {\n ...this.loadOptions,\n i3s: {\n ...i3sLoaderOptions,\n isTileHeader: true\n }\n };\n\n const header = await this.loadResourceData(nodeUrl, options);\n return await this.transformTileHeader(header);\n }\n\n /** Loads all declared I3S child headers without camera or visibility state. */\n async loadTileChildrenForTraversal(\n parentTile: Tile3D,\n signal?: AbortSignal\n ): Promise<TileChildrenLoadResult> {\n const childHeaders = parentTile.header.children || [];\n let loadedChildren = 0;\n const orderedChildren: Tile3D[] = [];\n\n for (const childHeader of childHeaders) {\n throwIfTraversalAborted(signal);\n const childId = childHeader.id;\n if (typeof childId !== 'string' && typeof childId !== 'number') {\n throw new Error('I3S child header is missing its node ID');\n }\n const existingChild = parentTile.children.find(\n tile => tile.id === String(childId) || tile.header?.id === childId\n );\n if (existingChild) {\n orderedChildren.push(existingChild);\n continue;\n }\n\n const childTileHeader = await this.loadChildTileHeader(parentTile, String(childId), null);\n throwIfTraversalAborted(signal);\n const childTile = new Tile3DNode(\n parentTile.tileset,\n childTileHeader,\n parentTile,\n String(childId)\n );\n orderedChildren.push(childTile);\n loadedChildren++;\n }\n\n const orderedChildSet = new Set(orderedChildren);\n parentTile.children = [\n ...orderedChildren,\n ...parentTile.children.filter(childTile => !orderedChildSet.has(childTile))\n ];\n\n return {loaded: true, tileCount: loadedChildren, childSubtreeCount: 0};\n }\n\n /**\n * Resolves an I3S request URL with source-managed query parameters.\n */\n getTileUrl(tilePath: string): string {\n if (tilePath.startsWith('data:')) {\n return tilePath;\n }\n\n if (!Object.keys(this.queryParams).length) {\n return tilePath;\n }\n\n const hashIndex = tilePath.indexOf('#');\n const hash = hashIndex >= 0 ? tilePath.slice(hashIndex) : '';\n const tilePathWithoutHash = hashIndex >= 0 ? tilePath.slice(0, hashIndex) : tilePath;\n const queryDelimiterIndex = tilePathWithoutHash.indexOf('?');\n const path =\n queryDelimiterIndex === -1\n ? tilePathWithoutHash\n : tilePathWithoutHash.slice(0, queryDelimiterIndex);\n const existingQuery =\n queryDelimiterIndex === -1 ? '' : tilePathWithoutHash.slice(queryDelimiterIndex + 1);\n const existingQueryParams = new URLSearchParams(existingQuery);\n const queryParams = new URLSearchParams();\n for (const [key, value] of Object.entries(this.queryParams)) {\n if (!existingQueryParams.has(key)) {\n queryParams.set(key, value);\n }\n }\n\n const queryString = queryParams.toString();\n return `${path}${existingQuery ? `?${existingQuery}` : ''}${\n queryString ? `${existingQuery ? '&' : '?'}${queryString}` : ''\n }${hash}`;\n }\n\n /**\n * Derives the default view state from full extent or store extent metadata.\n */\n getViewState(rootTile: Tile3D | null): TilesetSourceViewState {\n if (this.spatialTransformer && rootTile) {\n const center = new Vector3(rootTile.boundingVolume.center);\n const cartographicCenter = new Vector3(rootTile.header.i3sLodMbs.slice(0, 3));\n if (this.spatialTransformer.targetCoordinateFrame === 'geographic') {\n return {\n boundingVolume: rootTile.boundingVolume,\n cartographicCenter,\n cartesianCenter: center,\n zoom: 1\n };\n }\n return {\n boundingVolume: rootTile.boundingVolume,\n cartographicCenter,\n cartesianCenter: center,\n zoom: 1\n };\n }\n const metadata = this.getMetadata();\n const fullExtent = metadata.tileset.fullExtent;\n if (fullExtent) {\n const {xmin, xmax, ymin, ymax, zmin, zmax} = fullExtent;\n const cartographicCenter = new Vector3(\n xmin + (xmax - xmin) / 2,\n ymin + (ymax - ymin) / 2,\n zmin + (zmax - zmin) / 2\n );\n const cartesianCenter = new Vector3();\n Ellipsoid.WGS84.cartographicToCartesian(cartographicCenter, cartesianCenter);\n return {\n cartographicCenter,\n cartesianCenter,\n zoom: getZoomFromFullExtent(fullExtent, cartographicCenter, cartesianCenter)\n };\n }\n\n const extent = metadata.tileset.store?.extent;\n if (extent) {\n const [xmin, ymin, xmax, ymax] = extent;\n const cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);\n const cartesianCenter = new Vector3();\n Ellipsoid.WGS84.cartographicToCartesian(cartographicCenter, cartesianCenter);\n return {\n cartographicCenter,\n cartesianCenter,\n zoom: getZoomFromExtent(extent, cartographicCenter, cartesianCenter)\n };\n }\n\n console.warn('Extent is not defined in the tileset header');\n return {\n cartographicCenter: new Vector3(),\n zoom: 1\n };\n }\n\n /**\n * Updates content-format flags after tile content loads.\n */\n onTileLoaded(_tileset: Tileset3D, tile: Tile3D): void {\n if (tile.header.isDracoGeometry) {\n this.contentFormats.draco = true;\n }\n\n switch (tile.header.textureFormat) {\n case 'dds':\n this.contentFormats.dds = true;\n break;\n case 'ktx2':\n this.contentFormats.ktx2 = true;\n break;\n default:\n }\n }\n\n /**\n * Returns the total number of known tiles when node pages metadata is available.\n */\n getTilesTotalCount(): number | null {\n const metadata = this.getMetadata();\n return metadata.tileset?.nodePagesTile?.nodesInNodePages || null;\n }\n\n /**\n * Loads data through injected core APIs so this module stays independent from `@loaders.gl/core`.\n */\n private async loadWithCoreApi(\n url: string,\n options: LoaderOptions,\n loader: Loader = this.loader\n ): Promise<any> {\n if (!this.coreApi) {\n throw new Error('I3SSource requires an injected coreApi to load tileset data');\n }\n\n return await this.coreApi.load(url, loader, options);\n }\n\n /**\n * Loads data through an injected resolver when present, otherwise through the injected core API.\n */\n private async loadRootData(url: string, options: LoaderOptions): Promise<any> {\n if (this.resolver) {\n return await this.resolver.loadRoot(url, this.loader, options);\n }\n\n return await this.loadWithCoreApi(url, options);\n }\n\n /**\n * Initializes query parameters before any URL-backed resource is requested.\n * @param loadOptions Loader options that may contain an ArcGIS token.\n */\n private initializeQueryParams(loadOptions: LoaderOptions): void {\n for (const [key, value] of Object.entries(loadOptions.searchParams || {})) {\n this.queryParams[key] = String(value);\n }\n\n const i3sOptions = loadOptions.i3s;\n if (i3sOptions && typeof i3sOptions === 'object' && 'token' in i3sOptions) {\n const token = (i3sOptions as Record<string, unknown>).token;\n if (typeof token === 'string') {\n this.queryParams.token = token;\n }\n }\n }\n\n /**\n * Loads tile metadata or content through an injected resolver when present, otherwise through the injected core API.\n */\n private async loadResourceData(\n url: string,\n options: LoaderOptions,\n loader: Loader = this.loader\n ): Promise<any> {\n if (this.resolver) {\n return await this.resolver.loadResource(url, loader, options);\n }\n\n return await this.loadWithCoreApi(url, options, loader);\n }\n\n /** Transform one I3S header bound after target options and elevation providers are available. */\n private async transformTileHeader(header: any): Promise<any> {\n if (!this.spatialTransformer) {\n return header;\n }\n const sourceBounds = {\n mbs: header.mbs,\n obb: header.obb,\n normalReferenceFrame: this.getMetadata().tileset.store?.normalReferenceFrame\n };\n const transformedBounds = await this.spatialTransformer.transformBoundsAsync(sourceBounds);\n return {\n ...header,\n // Tileset3D traversal and culling operate in WGS84 ECEF independently of content output.\n boundingVolume: transformedBounds.boundingVolume,\n // Preserve the renderer/output-frame bound for applications and content coordination.\n spatialBoundingVolume: transformedBounds.spatialBoundingVolume,\n i3sLodMbs: transformedBounds.i3sLodMbs\n };\n }\n}\n\n/** Throws a cancellation reason before or after source-managed traversal work. */\nfunction throwIfTraversalAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The operation was aborted', 'AbortError');\n }\n}\n\n/** Returns the format-provided binary content loader, falling back for custom legacy loaders. */\nfunction getI3SContentLoader(loader: Loader): Loader {\n return (loader as Loader & {contentLoader?: Loader}).contentLoader || loader;\n}\n\nfunction isTilesetRequest(input: TilesetSourceInput): input is TilesetSourceRequest {\n return Boolean(\n input && typeof input === 'object' && 'url' in input && 'loader' in input && !('type' in input)\n );\n}\n\n/**\n * Normalizes constructor input into a URL request descriptor.\n * @param input Constructor input for {@link I3SSource}.\n * @returns A normalized request with a resolved base path.\n */\nfunction normalizeI3SRequest(input: TilesetSourceInput): TilesetSourceRequest {\n if (isTilesetRequest(input)) {\n return {\n ...input,\n basePath: input.basePath || path.dirname(input.url)\n };\n }\n\n return {\n url: input.url,\n loader: input.loader,\n basePath: input.basePath || path.dirname(input.url),\n resolver: (input as TilesetSourceRequest).resolver,\n coreApi: (input as TilesetSourceRequest).coreApi\n };\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Counter to register pending tile headers for the particular frameNumber\n * Until all tiles are loaded we won't call `onTraversalEnd` callback\n */\nexport class I3SPendingTilesRegister {\n private frameNumberMap: Map<string, Map<number, number>> = new Map();\n\n /**\n * Register a new pending tile header for the particular frameNumber\n * @param viewportId\n * @param frameNumber\n */\n register(viewportId: string, frameNumber: number) {\n const viewportMap = this.frameNumberMap.get(viewportId) || new Map();\n const oldCount = viewportMap.get(frameNumber) || 0;\n viewportMap.set(frameNumber, oldCount + 1);\n this.frameNumberMap.set(viewportId, viewportMap);\n }\n\n /**\n * Deregister a pending tile header for the particular frameNumber\n * @param viewportId\n * @param frameNumber\n */\n deregister(viewportId: string, frameNumber: number) {\n const viewportMap = this.frameNumberMap.get(viewportId);\n if (!viewportMap) {\n return;\n }\n const oldCount = viewportMap.get(frameNumber) || 1;\n viewportMap.set(frameNumber, oldCount - 1);\n }\n\n /**\n * Check is there are no pending tile headers registered for the particular frameNumber\n * @param viewportId\n * @param frameNumber\n * @returns\n */\n isZero(viewportId: string, frameNumber: number) {\n const count = this.frameNumberMap.get(viewportId)?.get(frameNumber) || 0;\n return count === 0;\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {FrameState} from '../helpers/frame-state';\nimport {I3SPendingTilesRegister} from './i3s-pending-tiles-register';\n\nconst STATUS = {\n REQUESTED: 'REQUESTED',\n COMPLETED: 'COMPLETED',\n ERROR: 'ERROR'\n};\n\n// A helper class to manage tile metadata fetching\nexport class I3STileManager {\n private _statusMap: object;\n private pendingTilesRegister = new I3SPendingTilesRegister();\n\n constructor() {\n this._statusMap = {};\n }\n\n /**\n * Add request to map\n * @param request - node metadata request\n * @param key - unique key\n * @param callback - callback after request completed\n * @param frameState - frameState data\n */\n add(request, key, callback, frameState: FrameState) {\n if (!this._statusMap[key]) {\n const {\n frameNumber,\n viewport: {id}\n } = frameState;\n this._statusMap[key] = {request, callback, key, frameState, status: STATUS.REQUESTED};\n // Register pending request for the frameNumber\n this.pendingTilesRegister.register(id, frameNumber);\n request()\n .then(data => {\n this._statusMap[key].status = STATUS.COMPLETED;\n const {\n frameNumber: actualFrameNumber,\n viewport: {id}\n } = this._statusMap[key].frameState;\n // Deregister pending request for the frameNumber\n this.pendingTilesRegister.deregister(id, actualFrameNumber);\n this._statusMap[key].callback(data, frameState);\n })\n .catch(error => {\n this._statusMap[key].status = STATUS.ERROR;\n const {\n frameNumber: actualFrameNumber,\n viewport: {id}\n } = this._statusMap[key].frameState;\n // Deregister pending request for the frameNumber\n this.pendingTilesRegister.deregister(id, actualFrameNumber);\n callback(error);\n });\n }\n }\n\n /**\n * Update request if it is still actual for the new frameState\n * @param key - unique key\n * @param frameState - frameState data\n */\n update(key, frameState: FrameState) {\n if (this._statusMap[key]) {\n // Deregister pending request for the old frameNumber\n const {\n frameNumber,\n viewport: {id}\n } = this._statusMap[key].frameState;\n this.pendingTilesRegister.deregister(id, frameNumber);\n\n // Register pending request for the new frameNumber\n const {\n frameNumber: newFrameNumber,\n viewport: {id: newViewportId}\n } = frameState;\n this.pendingTilesRegister.register(newViewportId, newFrameNumber);\n this._statusMap[key].frameState = frameState;\n }\n }\n\n /**\n * Find request in the map\n * @param key - unique key\n * @returns\n */\n find(key) {\n return this._statusMap[key];\n }\n\n /**\n * Check it there are pending tile headers for the particular frameNumber\n * @param viewportId\n * @param frameNumber\n * @returns\n */\n hasPendingTiles(viewportId: string, frameNumber: number): boolean {\n return !this.pendingTilesRegister.isZero(viewportId, frameNumber);\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TilesetTraverser} from '../common/tileset-traverser';\n\nimport {getLodStatus} from '../helpers/i3s-lod';\nimport {Tile3D} from '../common/tile-3d';\nimport {I3STileManager} from './i3s-tile-manager';\nimport {FrameState} from '../helpers/frame-state';\n\nexport class I3STilesetTraverser extends TilesetTraverser {\n private _tileManager: I3STileManager;\n\n constructor(options) {\n super(options);\n this._tileManager = new I3STileManager();\n }\n\n /**\n * Check if there are no penging tile header requests,\n * that means the traversal is finished and we can call\n * following-up callbacks.\n */\n traversalFinished(frameState: FrameState): boolean {\n return !this._tileManager.hasPendingTiles(frameState.viewport.id, this._frameNumber || 0);\n }\n\n shouldRefine(tile, frameState: FrameState) {\n tile._lodJudge = getLodStatus(tile, frameState);\n return tile._lodJudge === 'DIG';\n }\n\n updateChildTiles(tile, frameState: FrameState): boolean {\n const children = tile.header.children || [];\n // children which are already fetched and constructed as Tile3D instances\n const childTiles = tile.children;\n for (const child of children) {\n const extendedId = `${child.id}-${frameState.viewport.id}`;\n // if child tile is not fetched\n const childTile =\n childTiles && childTiles.find(t => t.id === extendedId || t.header?.id === child.id);\n if (!childTile) {\n const request = () => this._loadTile(tile, child.id, frameState);\n const cachedRequest = this._tileManager.find(extendedId);\n if (!cachedRequest) {\n this._tileManager.add(\n request,\n extendedId,\n header => this._onTileLoad(header, tile, extendedId),\n frameState\n );\n } else {\n // update frameNumber since it is still needed in current frame\n this._tileManager.update(extendedId, frameState);\n }\n } else if (childTile) {\n // if child tile is fetched and available\n this.updateTile(childTile, frameState);\n }\n }\n return false;\n }\n\n async _loadTile(tile, nodeId, frameState) {\n if (!tile.tileset.source.loadChildTileHeader) {\n throw new Error('I3S source does not support child tile header loading');\n }\n\n return await tile.tileset.source.loadChildTileHeader(tile, nodeId, frameState);\n }\n\n /**\n * The callback to init Tile3D instance after loading the tile JSON\n * @param {Object} header - the tile JSON from a dataset\n * @param {Tile3D} tile - the parent Tile3D instance\n * @param {string} extendedId - optional ID to separate copies of a tile for different viewports.\n * const extendedId = `${tile.id}-${frameState.viewport.id}`;\n * @return {void}\n */\n _onTileLoad(header, tile, extendedId) {\n if (header instanceof Error) {\n tile.tileset._onSourceError(header, tile);\n return;\n }\n\n // after child tile is fetched\n const childTile = new Tile3D(tile.tileset, header, tile, extendedId);\n tile.children.push(childTile);\n const frameState = this._tileManager.find(childTile.id).frameState;\n this.updateTile(childTile, frameState);\n\n // after tile fetched, resume traversal if still in current update/traversal frame\n if (\n this._frameNumber === frameState.frameNumber &&\n (this.traversalFinished(frameState) ||\n new Date().getTime() - this.lastUpdate > this.updateDebounceTime)\n ) {\n this.executeTraversal(childTile, frameState);\n }\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Matrix3, Matrix4, Quaternion, Vector3} from '@math.gl/core';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {\n getSpatialCoordinateFrame,\n SpatialCoordinateTransformer\n} from './spatial-coordinate-transformer';\nimport {\n createTilesetSpatialReference,\n markTilesetSpatialReferenceTransformed\n} from './spatial-types';\nimport {getI3SLinearUnitScale} from './i3s-elevation';\nimport type {\n TilesetCoordinateFrame,\n TilesetElevationBounds,\n TilesetElevationMode,\n TilesetElevationProvider,\n TilesetSpatialOptions,\n TilesetSpatialReference\n} from './spatial-types';\n\n/** Minimal I3S oriented bounding box required by the spatial adapter. */\nexport type I3SSpatialObb = {\n /** Center in source CRS coordinates. */\n center: ArrayLike<number>;\n /** Half lengths along the oriented axes. */\n halfSize: ArrayLike<number>;\n /** Orientation quaternion. */\n quaternion: ArrayLike<number>;\n};\n\n/** Input used to rebuild an I3S node bound in the selected output frame. */\nexport type I3SSpatialBounds = {\n /** Minimum bounding sphere encoded as source center plus radius. */\n mbs?: ArrayLike<number>;\n /** Oriented source bound, preferred when available. */\n obb?: I3SSpatialObb;\n /** Frame in which I3S vectors and quaternions are expressed. */\n normalReferenceFrame?: string;\n};\n\n/** Renderer-ready positions and metadata produced for an I3S geometry resource. */\nexport type I3STransformedPositions = {\n /** Float32 offsets from the stable target origin. */\n positions: Float32Array;\n /** Reconstructed absolute source positions retained for normal transformation. */\n sourcePositions: Float64Array;\n /** Stable origin in target CRS coordinates. */\n origin: [number, number, number];\n /** Origin used by geographic deck.gl coordinate systems. */\n cartographicOrigin: [number, number, number];\n /** Renderer coordinate-system discriminator. */\n coordinateSystem: 'cartesian' | 'lnglat-offsets';\n /** Translation matrix used for Cartesian target offsets. */\n modelMatrix: Matrix4;\n};\n\n/** Double-precision conversion geometry after I3S units, elevation and CRS placement. */\nexport type I3STransformedGeometry = {\n /** Absolute target xyz positions, before any writer-owned float32 rebasing. */\n positions: Float64Array;\n /** Optional unit normals in the target basis. */\n normals?: Float32Array;\n};\n\n/**\n * Applies one normalized I3S horizontal CRS operation consistently to geometry, normals, origins,\n * and node bounds.\n */\nexport class I3SSpatialTransformer {\n /** Descriptor attached to output after all adapter-owned spatial values have been transformed. */\n readonly spatialReference: TilesetSpatialReference;\n\n /** Broad coordinate frame of the selected output CRS. */\n readonly targetCoordinateFrame: TilesetCoordinateFrame;\n\n /** Source-to-target position operation. */\n private readonly positionTransformer: SpatialCoordinateTransformer;\n\n /** Source-to-WGS84 geographic operation used for vector-frame conversion. */\n private readonly sourceToGeographicTransformer: SpatialCoordinateTransformer;\n\n /** WGS84-geographic-to-target operation used for normal finite differences. */\n private readonly geographicToTargetTransformer: SpatialCoordinateTransformer;\n\n /** Source frame recorded by I3S metadata. */\n private readonly sourceCoordinateFrame: TilesetCoordinateFrame;\n\n /** Source Z multiplier that normalizes stored elevation values to meters. */\n private readonly sourceVerticalUnitScale: number;\n\n /** I3S elevation placement mode. */\n private readonly elevationMode?: TilesetElevationMode;\n\n /** I3S elevation offset normalized to meters. */\n private readonly elevationOffset: number;\n\n /** Terrain or scene provider selected for the declared placement mode. */\n private readonly elevationProvider?: TilesetElevationProvider;\n\n /** Provider height multiplier that normalizes returned values to meters. */\n private readonly providerUnitScale: number;\n\n /** Optional provider-height to layer-height datum operation. */\n private readonly providerHeightTransformer?: SpatialCoordinateTransformer;\n\n /**\n * Creates an I3S spatial adapter.\n *\n * @param spatialReference - Transformable I3S spatial descriptor.\n * @param options - Registered geoid and custom resource options used by the shared transformer.\n */\n constructor(spatialReference: TilesetSpatialReference, options: TilesetSpatialOptions = {}) {\n if (spatialReference.status !== 'transformable' && spatialReference.status !== 'transformed') {\n throw new Error('I3SSpatialTransformer requires a requested, transformable spatial output');\n }\n const targetCrs = spatialReference.targetCrs || spatialReference.sourceCrs;\n if (!targetCrs) {\n throw new Error('I3S spatial transformation requires a target CRS');\n }\n\n this.positionTransformer = new SpatialCoordinateTransformer(spatialReference, options);\n this.sourceCoordinateFrame = spatialReference.coordinateFrame;\n this.sourceVerticalUnitScale = spatialReference.verticalUnitScale;\n this.elevationMode = spatialReference.elevationMode;\n this.elevationOffset =\n (spatialReference.elevationOffset || 0) * spatialReference.elevationUnitScale;\n this.elevationProvider = getElevationProvider(this.elevationMode, options);\n if (\n this.elevationProvider &&\n (typeof this.elevationProvider.sampleElevations !== 'function' ||\n typeof this.elevationProvider.getElevationRange !== 'function')\n ) {\n throw new Error(\n 'An I3S elevation provider must implement sampleElevations() and getElevationRange()'\n );\n }\n const providerUnitScale = getI3SLinearUnitScale(this.elevationProvider?.unit || 'meter');\n if (this.elevationProvider && providerUnitScale === undefined) {\n throw new Error(`Unsupported elevation-provider unit ${this.elevationProvider.unit}`);\n }\n this.providerUnitScale = providerUnitScale || 1;\n this.targetCoordinateFrame = getSpatialCoordinateFrame(targetCrs);\n this.spatialReference = markTilesetSpatialReferenceTransformed(spatialReference);\n\n const sourceToGeographicReference = createTilesetSpatialReference(\n {\n sourceCrs: spatialReference.sourceCrs,\n heightReference: spatialReference.heightReference,\n coordinateFrame: spatialReference.coordinateFrame,\n axisOrder: spatialReference.axisOrder,\n provenance: spatialReference.provenance\n },\n {targetCrs: 'EPSG:4326'}\n );\n this.sourceToGeographicTransformer = new SpatialCoordinateTransformer(\n sourceToGeographicReference\n );\n\n if (requiresElevationSurface(this.elevationMode)) {\n if (!this.elevationProvider) {\n const providerName = this.elevationMode === 'relativeToScene' ? 'scene' : 'terrain';\n throw new Error(\n `I3S elevation mode ${this.elevationMode} requires a ${providerName} elevation provider`\n );\n }\n if (spatialReference.heightReference === 'unknown') {\n throw new Error(\n `I3S elevation mode ${this.elevationMode} requires a known source height reference`\n );\n }\n const providerHeightReference =\n this.elevationProvider.heightReference || spatialReference.heightReference;\n if (providerHeightReference !== spatialReference.heightReference) {\n if (\n spatialReference.heightReference !== 'ellipsoidal' &&\n spatialReference.heightReference !== 'orthometric'\n ) {\n throw new Error(\n 'Converting elevation-provider heights requires an ellipsoidal or orthometric source height reference'\n );\n }\n const providerHeightSpatialReference = createTilesetSpatialReference(\n {\n sourceCrs: 'EPSG:4326',\n heightReference: providerHeightReference,\n coordinateFrame: 'geographic',\n axisOrder: 'xyz',\n provenance: 'caller-override'\n },\n {\n targetCrs: 'EPSG:4326',\n targetHeightReference: spatialReference.heightReference,\n geoidModel: options.geoidModel\n }\n );\n this.providerHeightTransformer = new SpatialCoordinateTransformer(\n providerHeightSpatialReference,\n options\n );\n }\n }\n\n const geographicToTargetReference = createTilesetSpatialReference(\n {\n sourceCrs: 'EPSG:4326',\n heightReference: spatialReference.heightReference,\n coordinateFrame: 'geographic',\n axisOrder: 'xyz',\n provenance: 'format-default'\n },\n {\n targetCrs,\n targetHeightReference: spatialReference.targetHeightReference,\n geoidModel: options.geoidModel\n }\n );\n this.geographicToTargetTransformer = new SpatialCoordinateTransformer(\n geographicToTargetReference,\n options\n );\n }\n\n /** Transform one absolute I3S source position. */\n transformPosition(position: ArrayLike<number>): [number, number, number] {\n const placedPosition = this.placeSourcePositionsSync(position);\n const transformed = this.positionTransformer.transformPosition([\n placedPosition[0],\n placedPosition[1],\n placedPosition[2]\n ]);\n return [transformed[0], transformed[1], transformed[2]];\n }\n\n /** Transform one absolute I3S source position after asynchronous surface placement. */\n async transformPositionAsync(position: ArrayLike<number>): Promise<[number, number, number]> {\n const placedPosition = await this.placeSourcePositions(position);\n const transformed = this.positionTransformer.transformPosition([\n placedPosition[0],\n placedPosition[1],\n placedPosition[2]\n ]);\n return [transformed[0], transformed[1], transformed[2]];\n }\n\n /** Transform an already placed, meter-normalized position to the requested target. */\n private transformPlacedPosition(position: ArrayLike<number>): [number, number, number] {\n const transformed = this.positionTransformer.transformPosition([\n position[0],\n position[1],\n position[2]\n ]);\n return [transformed[0], transformed[1], transformed[2]];\n }\n\n /** Transform one absolute I3S source position to WGS84 longitude, latitude, and height. */\n transformSourcePositionToGeographic(position: ArrayLike<number>): [number, number, number] {\n const placedPosition = this.placeSourcePositionsSync(position);\n const transformed = this.sourceToGeographicTransformer.transformPosition([\n placedPosition[0],\n placedPosition[1],\n placedPosition[2]\n ]);\n return [transformed[0], transformed[1], transformed[2]];\n }\n\n /** Transform one source position to WGS84 after asynchronous elevation placement. */\n async transformSourcePositionToGeographicAsync(\n position: ArrayLike<number>\n ): Promise<[number, number, number]> {\n const placedPosition = await this.placeSourcePositions(position);\n const transformed = this.sourceToGeographicTransformer.transformPosition([\n placedPosition[0],\n placedPosition[1],\n placedPosition[2]\n ]);\n return [transformed[0], transformed[1], transformed[2]];\n }\n\n /**\n * Transform absolute Float64 positions and return stable Float32 offsets around a target origin.\n *\n * @param sourcePositions - Absolute positions in source CRS order.\n * @param sourceOrigin - Stable source origin, normally the node MBS or OBB center.\n */\n transformPositions(\n sourcePositions: ArrayLike<number>,\n sourceOrigin: ArrayLike<number>\n ): I3STransformedPositions {\n const placedSourcePositions = this.placeSourcePositionsSync(sourcePositions);\n const placedSourceOrigin = this.placeSourcePositionsSync(sourceOrigin);\n return this.transformPlacedPositions(placedSourcePositions, placedSourceOrigin);\n }\n\n /**\n * Transform positions after asynchronously sampling any requested terrain or scene surface.\n *\n * @param sourcePositions - Absolute positions in source CRS order.\n * @param sourceOrigin - Stable source origin, normally the node MBS or OBB center.\n * @returns Renderer-ready target-frame offsets and stable origin metadata.\n */\n async transformPositionsAsync(\n sourcePositions: ArrayLike<number>,\n sourceOrigin: ArrayLike<number>\n ): Promise<I3STransformedPositions> {\n const combinedPositions = new Float64Array(sourcePositions.length + 3);\n combinedPositions.set(Array.from(sourcePositions), 0);\n combinedPositions.set(Array.from(sourceOrigin).slice(0, 3), sourcePositions.length);\n const placedPositions = await this.placeSourcePositions(combinedPositions);\n return this.transformPlacedPositions(\n placedPositions.subarray(0, sourcePositions.length),\n placedPositions.subarray(sourcePositions.length)\n );\n }\n\n /**\n * Transforms conversion geometry without passing through renderer float32 offsets.\n * Positions and normals share one batch of elevation samples. Source arrays remain unchanged.\n * @param sourcePositions - Packed absolute xyz positions in source units.\n * @param normals - Optional packed normals paired with the positions.\n * @param normalReferenceFrame - I3S earth-centered or vertex-reference-frame declaration.\n * @returns Absolute target positions and optional transformed normals.\n */\n async transformGeometryAsync(\n sourcePositions: ArrayLike<number>,\n normals?: ArrayLike<number>,\n normalReferenceFrame = 'earth-centered'\n ): Promise<I3STransformedGeometry> {\n if (sourcePositions.length % 3 || (normals && normals.length !== sourcePositions.length)) {\n throw new Error('Conversion positions and normals must contain matching finite xyz triples');\n }\n for (let index = 0; index < sourcePositions.length; index++) {\n if (\n !Number.isFinite(sourcePositions[index]) ||\n (normals && !Number.isFinite(normals[index]))\n ) {\n throw new Error(\n 'Conversion positions and normals must contain matching finite xyz triples'\n );\n }\n }\n if (!['earth-centered', 'vertex-reference-frame'].includes(normalReferenceFrame)) {\n throw new Error('Unsupported I3S normal reference frame');\n }\n const placedPositions = await this.placeSourcePositions(sourcePositions);\n return {\n positions: this.positionTransformer.transformPositions(placedPositions),\n normals: normals\n ? this.transformNormals(normals, placedPositions, normalReferenceFrame)\n : undefined\n };\n }\n\n /** Transform already placed positions into renderer-relative target coordinates. */\n private transformPlacedPositions(\n sourcePositions: ArrayLike<number>,\n sourceOrigin: ArrayLike<number>\n ): I3STransformedPositions {\n const origin = this.transformPlacedPosition(sourceOrigin);\n const positions = new Float32Array(sourcePositions.length);\n const absoluteSourcePositions = Float64Array.from(sourcePositions);\n\n for (let index = 0; index < sourcePositions.length; index += 3) {\n const transformed = this.transformPlacedPosition([\n sourcePositions[index],\n sourcePositions[index + 1],\n sourcePositions[index + 2]\n ]);\n positions[index] = transformed[0] - origin[0];\n positions[index + 1] = transformed[1] - origin[1];\n positions[index + 2] = transformed[2] - origin[2];\n }\n\n const isGeographic = this.targetCoordinateFrame === 'geographic';\n const modelMatrix = isGeographic ? new Matrix4() : new Matrix4().translate(origin);\n return {\n positions,\n sourcePositions: absoluteSourcePositions,\n origin,\n cartographicOrigin: isGeographic ? origin : [0, 0, 0],\n coordinateSystem: isGeographic ? 'lnglat-offsets' : 'cartesian',\n modelMatrix\n };\n }\n\n /**\n * Transform I3S normals into the selected target basis.\n *\n * Earth-centered normals are rotated directly. Vertex-reference-frame normals are first mapped\n * through the local east/north/up basis at each source position.\n *\n * @param normals - Three-component normal vectors.\n * @param sourcePositions - Absolute source position paired with each normal.\n * @param normalReferenceFrame - I3S normal frame declaration.\n */\n transformNormals(\n normals: ArrayLike<number>,\n sourcePositions: ArrayLike<number>,\n normalReferenceFrame = 'earth-centered'\n ): Float32Array {\n if (normals.length !== sourcePositions.length || normals.length % 3) {\n throw new Error('I3S normals and positions must have matching xyz component counts');\n }\n const transformedNormals = new Float32Array(normals.length);\n // Earth-centered I3S normals already use the output ECEF basis; no position projection is needed.\n if (\n normalReferenceFrame === 'earth-centered' &&\n (this.spatialReference.targetCrs || this.spatialReference.sourceCrs) === 'EPSG:4978'\n ) {\n for (let index = 0; index < normals.length; index += 3) {\n const length = Math.hypot(normals[index], normals[index + 1], normals[index + 2]);\n for (let axis = 0; axis < 3; axis++) {\n transformedNormals[index + axis] = length\n ? normals[index + axis] / length\n : normals[index + axis];\n }\n }\n return transformedNormals;\n }\n for (let index = 0; index < normals.length; index += 3) {\n const geographic = this.sourceToGeographicTransformer.transformPosition([\n sourcePositions[index],\n sourcePositions[index + 1],\n sourcePositions[index + 2]\n ]);\n const inputNormal = new Vector3([\n normals[index],\n normals[index + 1],\n normals[index + 2]\n ]).normalize();\n const ecefNormal =\n normalReferenceFrame === 'earth-centered'\n ? inputNormal\n : localEnuVectorToEcef(inputNormal, geographic);\n const outputNormal = this.transformEcefNormal(ecefNormal, geographic);\n transformedNormals.set(outputNormal, index);\n }\n return transformedNormals;\n }\n\n /**\n * Rebuild an I3S node bound from transformed corner or sphere-axis samples.\n *\n * @param bounds - Source MBS/OBB fields.\n * @returns A generic tile `region` for geographic output or axis-aligned `box` otherwise.\n */\n transformBoundingVolume(bounds: I3SSpatialBounds): {box?: number[]; region?: number[]} {\n const geographicSamples = this.getGeographicBoundSamples(bounds);\n const targetSamples = geographicSamples.map(position =>\n this.geographicToTargetTransformer.transformPosition(position)\n );\n return this.targetCoordinateFrame === 'geographic'\n ? {region: getGeographicRegion(targetSamples)}\n : {box: getAxisAlignedBox(targetSamples)};\n }\n\n /** Rebuild an I3S bound in the target frame after asynchronous elevation placement. */\n async transformBoundingVolumeAsync(\n bounds: I3SSpatialBounds\n ): Promise<{box?: number[]; region?: number[]}> {\n const geographicSamples = await this.getGeographicBoundSamplesAsync(bounds);\n const targetSamples = geographicSamples.map(position =>\n this.geographicToTargetTransformer.transformPosition(position)\n );\n return this.targetCoordinateFrame === 'geographic'\n ? {region: getGeographicRegion(targetSamples)}\n : {box: getAxisAlignedBox(targetSamples)};\n }\n\n /** Rebuild an I3S bound as a WGS84 geographic region for geographic traversal algorithms. */\n transformBoundingVolumeToGeographic(bounds: I3SSpatialBounds): {region: number[]} {\n return {region: getGeographicRegion(this.getGeographicBoundSamples(bounds))};\n }\n\n /** Rebuild an I3S bound as WGS84 geographic after asynchronous elevation placement. */\n async transformBoundingVolumeToGeographicAsync(\n bounds: I3SSpatialBounds\n ): Promise<{region: number[]}> {\n return {region: getGeographicRegion(await this.getGeographicBoundSamplesAsync(bounds))};\n }\n\n /** Rebuild an I3S bound as a WGS84 ECEF box for generic `Tileset3D` traversal. */\n transformBoundingVolumeToGeocentric(bounds: I3SSpatialBounds): {box: number[]} {\n const cartesianSamples = this.getGeographicBoundSamples(bounds).map(position =>\n Array.from(Ellipsoid.WGS84.cartographicToCartesian(new Vector3(position)))\n );\n return {box: getAxisAlignedBox(cartesianSamples)};\n }\n\n /** Rebuild an I3S bound as WGS84 ECEF after asynchronous elevation placement. */\n async transformBoundingVolumeToGeocentricAsync(\n bounds: I3SSpatialBounds\n ): Promise<{box: number[]}> {\n const cartesianSamples = (await this.getGeographicBoundSamplesAsync(bounds)).map(position =>\n Array.from(Ellipsoid.WGS84.cartographicToCartesian(new Vector3(position)))\n );\n return {box: getAxisAlignedBox(cartesianSamples)};\n }\n\n /** Return a WGS84 geographic MBS used by the I3S screen-threshold calculation. */\n transformBoundingSphereToGeographic(bounds: I3SSpatialBounds): [number, number, number, number] {\n const sourceCenter = bounds.mbs?.length\n ? Array.from(bounds.mbs).slice(0, 3)\n : bounds.obb\n ? Array.from(bounds.obb.center).slice(0, 3)\n : null;\n if (!sourceCenter) {\n throw new Error('I3S spatial transformation requires an MBS or OBB bound');\n }\n const placedCenter = this.placeSourcePositionsSync(sourceCenter);\n const geographicCenter = this.sourceToGeographicTransformer.transformPosition(\n Array.from(placedCenter)\n );\n const radius = bounds.mbs?.length\n ? bounds.mbs[3]\n : Math.hypot(...Array.from(bounds.obb!.halfSize).slice(0, 3));\n return [geographicCenter[0], geographicCenter[1], geographicCenter[2], radius];\n }\n\n /** Return a placed WGS84 MBS used by the I3S screen-threshold calculation. */\n async transformBoundingSphereToGeographicAsync(\n bounds: I3SSpatialBounds\n ): Promise<[number, number, number, number]> {\n return getGeographicBoundingSphere(await this.getGeographicBoundSamplesAsync(bounds));\n }\n\n /**\n * Rebuild traversal, target-output, and I3S LOD bounds from one elevation-sampling batch.\n *\n * @param bounds - Source MBS/OBB fields.\n * @returns Parallel bounds in WGS84 ECEF, the selected output frame, and WGS84 geographic.\n */\n async transformBoundsAsync(bounds: I3SSpatialBounds): Promise<{\n boundingVolume: {box: number[]};\n spatialBoundingVolume: {box?: number[]; region?: number[]};\n i3sLodMbs: [number, number, number, number];\n }> {\n const geographicSamples = await this.getGeographicBoundSamplesAsync(bounds);\n const cartesianSamples = geographicSamples.map(position =>\n Array.from(Ellipsoid.WGS84.cartographicToCartesian(new Vector3(position)))\n );\n const targetSamples = geographicSamples.map(position =>\n this.geographicToTargetTransformer.transformPosition(position)\n );\n return {\n boundingVolume: {box: getAxisAlignedBox(cartesianSamples)},\n spatialBoundingVolume:\n this.targetCoordinateFrame === 'geographic'\n ? {region: getGeographicRegion(targetSamples)}\n : {box: getAxisAlignedBox(targetSamples)},\n i3sLodMbs: requiresElevationSurface(this.elevationMode)\n ? getGeographicBoundingSphere(geographicSamples)\n : this.transformBoundingSphereToGeographic(bounds)\n };\n }\n\n /**\n * Rebuild Point Cloud traversal and target-output bounds from one elevation-sampling batch.\n *\n * @param bounds - Source OBB fields.\n * @returns WGS84 geographic traversal bound plus the selected output-frame bound.\n */\n async transformPointCloudBoundsAsync(bounds: I3SSpatialBounds): Promise<{\n boundingVolume: {region: number[]};\n spatialBoundingVolume: {box?: number[]; region?: number[]};\n }> {\n const geographicSamples = await this.getGeographicBoundSamplesAsync(bounds);\n const targetSamples = geographicSamples.map(position =>\n this.geographicToTargetTransformer.transformPosition(position)\n );\n return {\n boundingVolume: {region: getGeographicRegion(geographicSamples)},\n spatialBoundingVolume:\n this.targetCoordinateFrame === 'geographic'\n ? {region: getGeographicRegion(targetSamples)}\n : {box: getAxisAlignedBox(targetSamples)}\n };\n }\n\n /** Sample a source I3S bound and normalize every sample to WGS84 geographic coordinates. */\n private getGeographicBoundSamples(bounds: I3SSpatialBounds): number[][] {\n const sourceSamples = getSourceBoundSamples(\n bounds,\n this.sourceCoordinateFrame,\n this.sourceToGeographicTransformer,\n this.sourceVerticalUnitScale\n );\n if (!sourceSamples.length) {\n throw new Error('I3S spatial transformation requires an MBS or OBB bound');\n }\n const placedSourceSamples = this.placeSourcePositionsSync(sourceSamples.flat(), true);\n const placedSamples = toPositionArrays(placedSourceSamples);\n return this.sourceCoordinateFrame === 'geographic'\n ? placedSamples\n : placedSamples.map(position =>\n this.sourceToGeographicTransformer.transformPosition(position)\n );\n }\n\n /** Sample, place, and normalize one source bound to WGS84 geographic coordinates. */\n private async getGeographicBoundSamplesAsync(bounds: I3SSpatialBounds): Promise<number[][]> {\n const sourceSamples = getSourceBoundSamples(\n bounds,\n this.sourceCoordinateFrame,\n this.sourceToGeographicTransformer,\n this.sourceVerticalUnitScale\n );\n if (!sourceSamples.length) {\n throw new Error('I3S spatial transformation requires an MBS or OBB bound');\n }\n if (requiresElevationSurface(this.elevationMode)) {\n const geographicSamples =\n this.sourceCoordinateFrame === 'geographic'\n ? sourceSamples\n : sourceSamples.map(position =>\n this.sourceToGeographicTransformer.transformPosition(position)\n );\n return await this.placeGeographicBoundSamples(geographicSamples);\n }\n const placedSamples = toPositionArrays(\n await this.placeSourcePositions(sourceSamples.flat(), true)\n );\n return this.sourceCoordinateFrame === 'geographic'\n ? placedSamples\n : placedSamples.map(position =>\n this.sourceToGeographicTransformer.transformPosition(position)\n );\n }\n\n /** Apply a provider's conservative surface range to an entire geographic bound footprint. */\n private async placeGeographicBoundSamples(geographicSamples: number[][]): Promise<number[][]> {\n const elevationProvider = this.elevationProvider!;\n const elevationRange = await elevationProvider.getElevationRange(\n getElevationBounds(geographicSamples)\n );\n const minimumProviderHeight = elevationRange.minimum * this.providerUnitScale;\n const maximumProviderHeight = elevationRange.maximum * this.providerUnitScale;\n if (\n !Number.isFinite(minimumProviderHeight) ||\n !Number.isFinite(maximumProviderHeight) ||\n minimumProviderHeight > maximumProviderHeight\n ) {\n throw new Error(\n 'Elevation provider returned an invalid range; minimum and maximum must be finite and ordered'\n );\n }\n\n const sourceHeights = geographicSamples.map(position => position[2]);\n const minimumSourceHeight = Math.min(...sourceHeights);\n const maximumSourceHeight = Math.max(...sourceHeights);\n const placedSamples: number[][] = [];\n for (const [longitude, latitude] of geographicSamples) {\n const convertedMinimum = this.providerHeightTransformer\n ? this.providerHeightTransformer.transformPosition([\n longitude,\n latitude,\n minimumProviderHeight\n ])[2]\n : minimumProviderHeight;\n const convertedMaximum = this.providerHeightTransformer\n ? this.providerHeightTransformer.transformPosition([\n longitude,\n latitude,\n maximumProviderHeight\n ])[2]\n : maximumProviderHeight;\n const minimumSurfaceHeight = Math.min(convertedMinimum, convertedMaximum);\n const maximumSurfaceHeight = Math.max(convertedMinimum, convertedMaximum);\n const minimumHeight =\n this.elevationMode === 'onTheGround'\n ? minimumSurfaceHeight\n : minimumSurfaceHeight + minimumSourceHeight + this.elevationOffset;\n const maximumHeight =\n this.elevationMode === 'onTheGround'\n ? maximumSurfaceHeight\n : maximumSurfaceHeight + maximumSourceHeight + this.elevationOffset;\n placedSamples.push(\n [longitude, latitude, minimumHeight],\n [longitude, latitude, maximumHeight]\n );\n }\n return placedSamples;\n }\n\n /** Apply source units and non-surface placement without awaiting external resources. */\n private placeSourcePositionsSync(\n sourcePositions: ArrayLike<number>,\n sourceHeightsAreMeters = false\n ): Float64Array {\n if (requiresElevationSurface(this.elevationMode)) {\n throw new Error(\n `I3S elevation mode ${this.elevationMode} requires asynchronous surface placement`\n );\n }\n const positions = Float64Array.from(sourcePositions);\n const offset = this.elevationMode === 'absoluteHeight' ? this.elevationOffset : 0;\n for (let index = 2; index < positions.length; index += 3) {\n positions[index] =\n positions[index] * (sourceHeightsAreMeters ? 1 : this.sourceVerticalUnitScale) + offset;\n }\n return positions;\n }\n\n /** Apply source units and all I3S elevation-placement modes. */\n private async placeSourcePositions(\n sourcePositions: ArrayLike<number>,\n sourceHeightsAreMeters = false\n ): Promise<Float64Array> {\n if (!requiresElevationSurface(this.elevationMode)) {\n return this.placeSourcePositionsSync(sourcePositions, sourceHeightsAreMeters);\n }\n\n const positions = Float64Array.from(sourcePositions);\n const geographicLocations = toPositionArrays(positions).map(position => {\n const geographic = this.sourceToGeographicTransformer.transformPosition(position);\n return [geographic[0], geographic[1]] as const;\n });\n const sampledHeights = await this.elevationProvider!.sampleElevations(geographicLocations);\n if (sampledHeights.length !== geographicLocations.length) {\n throw new Error(\n `Elevation provider returned ${sampledHeights.length} heights for ${geographicLocations.length} positions`\n );\n }\n\n for (let positionIndex = 0; positionIndex < geographicLocations.length; positionIndex++) {\n const sampledHeight = sampledHeights[positionIndex] * this.providerUnitScale;\n if (!Number.isFinite(sampledHeight)) {\n throw new Error(\n `Elevation provider returned a non-finite height at index ${positionIndex}`\n );\n }\n const [longitude, latitude] = geographicLocations[positionIndex];\n const surfaceHeight = this.providerHeightTransformer\n ? this.providerHeightTransformer.transformPosition([longitude, latitude, sampledHeight])[2]\n : sampledHeight;\n const sourceHeight =\n positions[positionIndex * 3 + 2] *\n (sourceHeightsAreMeters ? 1 : this.sourceVerticalUnitScale);\n positions[positionIndex * 3 + 2] =\n this.elevationMode === 'onTheGround'\n ? surfaceHeight\n : surfaceHeight + sourceHeight + this.elevationOffset;\n }\n return positions;\n }\n\n /** Transform one earth-centered normal to the selected target basis. */\n private transformEcefNormal(ecefNormal: Vector3, geographic: number[]): Vector3 {\n if (this.targetCoordinateFrame === 'geocentric') {\n return ecefNormal.normalize();\n }\n if (this.targetCoordinateFrame === 'geographic') {\n return ecefVectorToLocalEnu(ecefNormal, geographic).normalize();\n }\n\n const cartesian = Ellipsoid.WGS84.cartographicToCartesian(new Vector3(geographic));\n const jacobianColumns: number[] = [];\n for (const direction of getPositiveAxisDirections()) {\n const positiveGeographic = Ellipsoid.WGS84.cartesianToCartographic(\n new Vector3(cartesian).add(direction)\n );\n const negativeGeographic = Ellipsoid.WGS84.cartesianToCartographic(\n new Vector3(cartesian).subtract(direction)\n );\n const positiveTarget =\n this.geographicToTargetTransformer.transformPosition(positiveGeographic);\n const negativeTarget =\n this.geographicToTargetTransformer.transformPosition(negativeGeographic);\n jacobianColumns.push(\n (positiveTarget[0] - negativeTarget[0]) / 2,\n (positiveTarget[1] - negativeTarget[1]) / 2,\n (positiveTarget[2] - negativeTarget[2]) / 2\n );\n }\n const normalMatrix = new Matrix3(jacobianColumns);\n if (Math.abs(normalMatrix.determinant()) < 1e-12) {\n throw new Error('Cannot transform an I3S normal through a singular local projection');\n }\n normalMatrix.invert().transpose();\n return new Vector3(ecefNormal).transformByMatrix3(normalMatrix).normalize();\n }\n}\n\n/** Select the application-owned surface required by one I3S elevation mode. */\nfunction getElevationProvider(\n mode: TilesetElevationMode | undefined,\n options: TilesetSpatialOptions\n): TilesetElevationProvider | undefined {\n return mode === 'relativeToScene'\n ? options.sceneElevationProvider\n : requiresElevationSurface(mode)\n ? options.terrainElevationProvider\n : undefined;\n}\n\n/** Return whether one placement mode requires external surface samples. */\nfunction requiresElevationSurface(mode: TilesetElevationMode | undefined): boolean {\n return mode === 'onTheGround' || mode === 'relativeToGround' || mode === 'relativeToScene';\n}\n\n/** Split one packed XYZ sequence into position arrays without losing Float64 precision. */\nfunction toPositionArrays(positions: ArrayLike<number>): number[][] {\n if (positions.length % 3 !== 0) {\n throw new Error('I3S position arrays must contain complete XYZ tuples');\n }\n const result: number[][] = [];\n for (let index = 0; index < positions.length; index += 3) {\n result.push([positions[index], positions[index + 1], positions[index + 2]]);\n }\n return result;\n}\n\n/** Return a dateline-aware WGS84 footprint in degrees for an elevation range request. */\nfunction getElevationBounds(geographicSamples: number[][]): TilesetElevationBounds {\n const region = getGeographicRegion(geographicSamples);\n return {\n west: (region[0] * 180) / Math.PI,\n south: (region[1] * 180) / Math.PI,\n east: (region[2] * 180) / Math.PI,\n north: (region[3] * 180) / Math.PI\n };\n}\n\n/** Build a conservative WGS84 geographic sphere from placed geographic samples. */\nfunction getGeographicBoundingSphere(\n geographicSamples: number[][]\n): [number, number, number, number] {\n if (!geographicSamples.length) {\n throw new Error('I3S spatial transformation requires at least one bound sample');\n }\n const cartesianSamples = geographicSamples.map(position =>\n Ellipsoid.WGS84.cartographicToCartesian(new Vector3(position))\n );\n const cartesianCenter = new Vector3();\n for (const sample of cartesianSamples) {\n cartesianCenter.add(sample);\n }\n cartesianCenter.scale(1 / cartesianSamples.length);\n let radius = 0;\n for (const sample of cartesianSamples) {\n radius = Math.max(radius, new Vector3(sample).subtract(cartesianCenter).magnitude());\n }\n const geographicCenter = Ellipsoid.WGS84.cartesianToCartographic(cartesianCenter);\n return [geographicCenter[0], geographicCenter[1], geographicCenter[2], radius];\n}\n\n/** Generate source-frame samples that conservatively cover an I3S MBS or OBB. */\nfunction getSourceBoundSamples(\n bounds: I3SSpatialBounds,\n sourceFrame: TilesetCoordinateFrame,\n sourceToGeographicTransformer: SpatialCoordinateTransformer,\n sourceVerticalUnitScale: number\n): number[][] {\n const obb = bounds.obb;\n if (obb) {\n const center = Array.from(obb.center).slice(0, 3);\n center[2] *= sourceVerticalUnitScale;\n const halfSize = Array.from(obb.halfSize).slice(0, 3);\n const quaternion = new Quaternion().fromArray(Array.from(obb.quaternion));\n const axes = [\n new Vector3([halfSize[0], 0, 0]).transformByQuaternion(quaternion),\n new Vector3([0, halfSize[1], 0]).transformByQuaternion(quaternion),\n new Vector3([0, 0, halfSize[2]]).transformByQuaternion(quaternion)\n ];\n if (sourceFrame === 'geographic') {\n const geographicCenter = sourceToGeographicTransformer.transformPosition(center);\n const cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(\n new Vector3(geographicCenter)\n );\n const cartesianAxes =\n bounds.normalReferenceFrame === 'vertex-reference-frame'\n ? axes.map(axis => localEnuVectorToEcef(axis, geographicCenter))\n : axes;\n return getBoxSigns().map(signs => {\n const corner = new Vector3(cartesianCenter);\n for (let axisIndex = 0; axisIndex < 3; axisIndex++) {\n corner.add(new Vector3(cartesianAxes[axisIndex]).scale(signs[axisIndex]));\n }\n return Array.from(Ellipsoid.WGS84.cartesianToCartographic(corner));\n });\n }\n return getBoxSigns().map(signs => {\n const corner = new Vector3(center);\n for (let axisIndex = 0; axisIndex < 3; axisIndex++) {\n corner.add(new Vector3(axes[axisIndex]).scale(signs[axisIndex]));\n }\n return Array.from(corner);\n });\n }\n\n const mbs = bounds.mbs ? Array.from(bounds.mbs) : [];\n if (mbs.length < 4) {\n return [];\n }\n const center = mbs.slice(0, 3);\n center[2] *= sourceVerticalUnitScale;\n const radius = mbs[3];\n if (sourceFrame === 'geographic') {\n const geographicCenter = sourceToGeographicTransformer.transformPosition(center);\n const cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(new Vector3(geographicCenter));\n return getAxisDirections().map(direction =>\n Array.from(\n Ellipsoid.WGS84.cartesianToCartographic(\n new Vector3(cartesianCenter).add(new Vector3(direction).scale(radius))\n )\n )\n );\n }\n return getAxisDirections().map(direction =>\n Array.from(new Vector3(center).add(new Vector3(direction).scale(radius)))\n );\n}\n\n/** Return the eight sign combinations of a box. */\nfunction getBoxSigns(): number[][] {\n return [-1, 1].flatMap(x => [-1, 1].flatMap(y => [-1, 1].map(z => [x, y, z])));\n}\n\n/** Return positive and negative unit directions for three Cartesian axes. */\nfunction getAxisDirections(): number[][] {\n return [\n [1, 0, 0],\n [-1, 0, 0],\n [0, 1, 0],\n [0, -1, 0],\n [0, 0, 1],\n [0, 0, -1]\n ];\n}\n\n/** Return the positive ECEF basis used to calculate a local projection Jacobian. */\nfunction getPositiveAxisDirections(): Vector3[] {\n return [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];\n}\n\n/** Convert a local east/north/up vector into an earth-centered vector. */\nfunction localEnuVectorToEcef(vector: ArrayLike<number>, geographic: ArrayLike<number>): Vector3 {\n const longitude = (geographic[0] * Math.PI) / 180;\n const latitude = (geographic[1] * Math.PI) / 180;\n const east = new Vector3([-Math.sin(longitude), Math.cos(longitude), 0]);\n const north = new Vector3([\n -Math.sin(latitude) * Math.cos(longitude),\n -Math.sin(latitude) * Math.sin(longitude),\n Math.cos(latitude)\n ]);\n const up = new Vector3([\n Math.cos(latitude) * Math.cos(longitude),\n Math.cos(latitude) * Math.sin(longitude),\n Math.sin(latitude)\n ]);\n return east.scale(vector[0]).add(north.scale(vector[1])).add(up.scale(vector[2]));\n}\n\n/** Convert an earth-centered vector into local east/north/up components. */\nfunction ecefVectorToLocalEnu(vector: Vector3, geographic: ArrayLike<number>): Vector3 {\n const longitude = (geographic[0] * Math.PI) / 180;\n const latitude = (geographic[1] * Math.PI) / 180;\n const east = new Vector3([-Math.sin(longitude), Math.cos(longitude), 0]);\n const north = new Vector3([\n -Math.sin(latitude) * Math.cos(longitude),\n -Math.sin(latitude) * Math.sin(longitude),\n Math.cos(latitude)\n ]);\n const up = new Vector3([\n Math.cos(latitude) * Math.cos(longitude),\n Math.cos(latitude) * Math.sin(longitude),\n Math.sin(latitude)\n ]);\n return new Vector3([east.dot(vector), north.dot(vector), up.dot(vector)]);\n}\n\n/** Build a target-frame axis-aligned generic tile box. */\nfunction getAxisAlignedBox(positions: number[][]): number[] {\n const minimum = [Infinity, Infinity, Infinity];\n const maximum = [-Infinity, -Infinity, -Infinity];\n for (const position of positions) {\n for (let component = 0; component < 3; component++) {\n minimum[component] = Math.min(minimum[component], position[component]);\n maximum[component] = Math.max(maximum[component], position[component]);\n }\n }\n const center = minimum.map((value, index) => (value + maximum[index]) / 2);\n const halfSize = minimum.map((value, index) => (maximum[index] - value) / 2);\n return [center[0], center[1], center[2], halfSize[0], 0, 0, 0, halfSize[1], 0, 0, 0, halfSize[2]];\n}\n\n/** Build a dateline-aware geographic tile region in radians. */\nfunction getGeographicRegion(positions: number[][]): number[] {\n const referenceLongitude = positions[0][0];\n let minimumLongitude = Infinity;\n let maximumLongitude = -Infinity;\n let minimumLatitude = Infinity;\n let maximumLatitude = -Infinity;\n let minimumHeight = Infinity;\n let maximumHeight = -Infinity;\n for (const position of positions) {\n const longitude = referenceLongitude + normalizeLongitude(position[0] - referenceLongitude);\n minimumLongitude = Math.min(minimumLongitude, longitude);\n maximumLongitude = Math.max(maximumLongitude, longitude);\n minimumLatitude = Math.min(minimumLatitude, position[1]);\n maximumLatitude = Math.max(maximumLatitude, position[1]);\n minimumHeight = Math.min(minimumHeight, position[2]);\n maximumHeight = Math.max(maximumHeight, position[2]);\n }\n return [\n (normalizeLongitude(minimumLongitude) * Math.PI) / 180,\n (minimumLatitude * Math.PI) / 180,\n (normalizeLongitude(maximumLongitude) * Math.PI) / 180,\n (maximumLatitude * Math.PI) / 180,\n minimumHeight,\n maximumHeight\n ];\n}\n\n/** Normalize a longitude delta to the interval [-180, 180). */\nfunction normalizeLongitude(longitude: number): number {\n return ((((longitude + 180) % 360) + 360) % 360) - 180;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/* eslint-env browser */\nimport {RequestScheduler} from '@loaders.gl/loader-utils';\nimport type {TileBoundingBox, TileIndex, TileLoadProps} from './types';\n\n/** Parameters used by {@link SharedTile2DHeader.loadData}. */\nexport type Tile2DLoadDataProps<DataT = any> = {\n /** Shared request scheduler for throttling tile fetches. */\n requestScheduler: RequestScheduler;\n /** Application-provided tile data loader. */\n getData: (props: TileLoadProps) => Promise<DataT | null> | DataT | null;\n /** Callback fired after tile content resolves successfully. */\n onLoad: (tile: SharedTile2DHeader<DataT>) => void;\n /** Callback fired after tile content fails to load. */\n onError: (error: any, tile: SharedTile2DHeader<DataT>) => void;\n};\n\n/** Shared tile cache entry used by {@link Tileset2D}. */\nexport class SharedTile2DHeader<DataT = any> {\n /** x/y/z tile coordinate. */\n index: TileIndex;\n /** Closest cached ancestor tile in the current tree. */\n parent: SharedTile2DHeader | null;\n /** Cached child tiles beneath this tile. */\n children: SharedTile2DHeader[] | null;\n /** Loaded tile payload. */\n content: DataT | null;\n /** Cached tile load error, if the last request failed. */\n error: Error | null;\n /** Stable tile cache id. */\n id!: string;\n /** Resolved zoom level for the tile. */\n zoom!: number;\n /** Optional application data associated with the tile. */\n userData?: Record<string, any>;\n /** Bounds represented as `[[minX, minY], [maxX, maxY]]` for loaders.gl compatibility. */\n boundingBox!: [min: number[], max: number[]];\n\n private _abortController: AbortController | null;\n private _loader: Promise<void> | undefined;\n private _loaderId: number;\n private _isLoaded: boolean;\n private _isCancelled: boolean;\n private _needsReload: boolean;\n private _bbox!: TileBoundingBox;\n\n /** Creates a tile header for a specific tile index. */\n constructor(index: TileIndex) {\n this.index = index;\n this.parent = null;\n this.children = [];\n this.content = null;\n this.error = null;\n this._loader = undefined;\n this._abortController = null;\n this._loaderId = 0;\n this._isLoaded = false;\n this._isCancelled = false;\n this._needsReload = false;\n }\n\n /** Structured bounds for the tile in the active coordinate system. */\n get bbox(): TileBoundingBox {\n return this._bbox;\n }\n\n /** Initializes the tile bounds once during tile creation. */\n set bbox(value: TileBoundingBox) {\n if (this._bbox) {\n return;\n }\n\n this._bbox = value;\n if ('west' in value) {\n this.boundingBox = [\n [value.west, value.south],\n [value.east, value.north]\n ];\n } else {\n this.boundingBox = [\n [value.left, value.top],\n [value.right, value.bottom]\n ];\n }\n }\n\n /** Resolves to loaded content while a request is in flight, otherwise returns cached content. */\n get data(): Promise<DataT | null> | DataT | null {\n const loader = this._loader;\n if (!this._isCancelled && loader !== undefined) {\n return loader.then(() => this.data);\n }\n return this.content;\n }\n\n /** Indicates whether tile content is available and up to date. */\n get isLoaded(): boolean {\n return this._isLoaded && !this._needsReload;\n }\n\n /** Indicates whether a tile request is currently in flight. */\n get isLoading(): boolean {\n return Boolean(this._loader) && !this._isCancelled;\n }\n\n /** Indicates whether the tile is cached in a failed state. */\n get hasError(): boolean {\n return Boolean(this.error);\n }\n\n /** Indicates whether the tile should be requested again. */\n get needsReload(): boolean {\n return this._needsReload || this._isCancelled;\n }\n\n /** Estimated byte size of the cached payload. */\n get byteLength(): number {\n const result = this.content ? (this.content as any).byteLength : 0;\n return Number.isFinite(result) ? result : 0;\n }\n\n /** Internal request pipeline used by {@link loadData}. */\n private async _loadData({\n getData,\n requestScheduler,\n onLoad,\n onError\n }: Tile2DLoadDataProps<DataT>): Promise<void> {\n const completeLoad = (tileData: DataT | null, error: unknown, loaderId: number): void => {\n if (loaderId !== this._loaderId) {\n return;\n }\n\n this._loader = undefined;\n this.content = tileData;\n this.error = error ? normalizeTileError(error) : null;\n\n if (this._isCancelled && !tileData) {\n this._isLoaded = false;\n return;\n }\n\n this._isLoaded = true;\n this._isCancelled = false;\n\n if (error) {\n onError(error, this);\n return;\n }\n onLoad(this);\n };\n\n const {index, id, bbox, userData, zoom} = this;\n const loaderId = this._loaderId;\n\n this._abortController = new AbortController();\n const {signal} = this._abortController;\n const requestToken = await requestScheduler.scheduleRequest(this, () => 1);\n\n if (!requestToken) {\n this._isCancelled = true;\n return;\n }\n if (this._isCancelled) {\n requestToken.done();\n return;\n }\n\n let tileData: DataT | null = null;\n let error;\n try {\n tileData = await getData({index, id, bbox, userData, zoom, signal});\n } catch (err) {\n error = err || true;\n } finally {\n requestToken.done();\n }\n\n completeLoad(tileData, error, loaderId);\n }\n\n /** Loads tile data through the shared scheduler. */\n loadData(opts: Tile2DLoadDataProps<DataT>): Promise<void> {\n this._isLoaded = false;\n this._isCancelled = false;\n this._needsReload = false;\n this.error = null;\n this._loaderId++;\n this._loader = this._loadData(opts);\n return this._loader;\n }\n\n /** Marks the tile stale so it is refreshed on the next traversal. */\n setNeedsReload(): void {\n if (this.isLoading) {\n this.abort();\n this._loader = undefined;\n }\n this._needsReload = true;\n }\n\n /** Cancels an in-flight tile request. */\n abort(): void {\n if (this.isLoaded) {\n return;\n }\n this._isCancelled = true;\n this._abortController?.abort();\n }\n}\n\n/** Normalizes arbitrary thrown values to `Error` instances for tile cache bookkeeping. */\nfunction normalizeTileError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error('Tile request failed');\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {RequestScheduler, type TileSource, type TileSourceMetadata} from '@loaders.gl/loader-utils';\nimport {Stats} from '@probe.gl/stats';\nimport {SharedTile2DHeader} from './tile-2d-header';\nimport type {Tileset2DAdapter, Tileset2DTileContext} from './adapter';\nimport type {TileIndex, TileLoadProps, ZRange} from './types';\n\n/** Never show ancestor or descendant placeholder tiles. */\nexport const STRATEGY_NEVER = 'never';\n/** Prefer non-overlapping loaded tiles while replacements stream in. */\nexport const STRATEGY_REPLACE = 'no-overlap';\n/** Prefer the best currently available loaded ancestor or descendant tiles. */\nexport const STRATEGY_DEFAULT = 'best-available';\n\n/**\n * Function form of a refinement strategy.\n *\n * The callback receives the current cached tiles and a visibility setter that can be used\n * to control placeholder visibility for individual tiles.\n */\nexport type RefinementStrategyFunction = (\n tiles: SharedTile2DHeader[],\n setVisible: (tile: SharedTile2DHeader, isVisible: boolean) => void\n) => void;\n\n/** Strategy controlling how parent and child placeholder tiles are displayed while content loads. */\nexport type RefinementStrategy =\n | typeof STRATEGY_NEVER\n | typeof STRATEGY_REPLACE\n | typeof STRATEGY_DEFAULT\n | RefinementStrategyFunction;\n\n/** Core configuration shared by all {@link Tileset2D} instances. */\nexport type Tileset2DBaseProps<DataT = any, ViewStateT = unknown> = {\n /** Callback used to load tile payloads. */\n getTileData: (props: TileLoadProps) => Promise<DataT | null> | DataT | null;\n /** Adapter used to compute tile traversal and tile metadata. */\n adapter?: Tileset2DAdapter<ViewStateT> | null;\n /** Bounding box limiting tile generation. */\n extent?: number[] | null;\n /** Tile size in pixels. */\n tileSize?: number;\n /** Maximum zoom level to request. */\n maxZoom?: number | null;\n /** Minimum zoom level to request. */\n minZoom?: number | null;\n /** Maximum number of tiles kept in cache. */\n maxCacheSize?: number | null;\n /** Maximum bytes kept in cache. */\n maxCacheByteSize?: number | null;\n /** Placeholder refinement strategy. */\n refinementStrategy?: RefinementStrategy;\n /** Elevation range used by geospatial tile selection. */\n zRange?: ZRange | null;\n /** Maximum concurrent tile requests. */\n maxRequests?: number;\n /** Debounce interval applied before issuing queued requests. */\n debounceTime?: number;\n /** Integer zoom offset applied when choosing tile levels. */\n zoomOffset?: number;\n /** Callback fired when a tile loads successfully. */\n onTileLoad?: (tile: SharedTile2DHeader<DataT>) => void;\n /** Callback fired when a tile is evicted from cache. */\n onTileUnload?: (tile: SharedTile2DHeader<DataT>) => void;\n /** Callback fired when a tile request fails. */\n onTileError?: (err: any, tile: SharedTile2DHeader<DataT>) => void;\n};\n\n/** Options for creating a shared tile cache that can be reused by multiple layers and views. */\nexport type Tileset2DProps<DataT = any, ViewStateT = unknown> = Omit<\n Tileset2DBaseProps<DataT, ViewStateT>,\n 'getTileData'\n> & {\n /** Optional tile loader used when not sourcing data from a loaders.gl TileSource. */\n getTileData?: (props: TileLoadProps) => Promise<DataT | null> | DataT | null;\n /** Optional loaders.gl TileSource backing this shared tileset. */\n tileSource?: TileSource | null;\n};\n\n/** Subscription callbacks emitted by {@link Tileset2D}. */\nexport type Tile2DListener<DataT = any> = {\n /** Fired after a tile loads successfully. */\n onTileLoad?: (tile: SharedTile2DHeader<DataT>) => void;\n /** Fired after a tile request fails. */\n onTileError?: (error: any, tile: SharedTile2DHeader<DataT>) => void;\n /** Fired after a tile is evicted from cache. */\n onTileUnload?: (tile: SharedTile2DHeader<DataT>) => void;\n /** Fired when metadata or effective configuration changes. */\n onUpdate?: () => void;\n /** Fired when asynchronous metadata initialization fails. */\n onError?: (error: Error) => void;\n /** Fired after live tileset counters are recomputed. */\n onStatsChange?: (stats: Stats) => void;\n};\n\ntype ConsumerState<DataT = any> = {\n selectedTiles: Set<SharedTile2DHeader<DataT>>;\n visibleTiles: Set<SharedTile2DHeader<DataT>>;\n};\n\nconst DEFAULT_TILESET2D_PROPS: Omit<Required<Tileset2DProps>, 'getTileData'> = {\n adapter: null,\n extent: null,\n tileSize: 512,\n maxZoom: null,\n minZoom: null,\n maxCacheSize: 100,\n maxCacheByteSize: null,\n refinementStrategy: STRATEGY_DEFAULT,\n zRange: null,\n maxRequests: 6,\n debounceTime: 0,\n zoomOffset: 0,\n onTileLoad: () => {},\n onTileUnload: () => {},\n onTileError: () => {},\n tileSource: null\n};\n\n/** Shared tile cache and loading engine for one or more consumers. */\nexport class Tileset2D<DataT = any, ViewStateT = unknown> {\n /** Live counters describing shared tileset state. */\n readonly stats: Stats;\n /** Cached metadata returned by the backing TileSource, if any. */\n sourceMetadata: TileSourceMetadata | null = null;\n\n protected opts: Required<Tileset2DProps<DataT, ViewStateT>>;\n\n private _requestScheduler: RequestScheduler;\n private _cache: Map<string, SharedTile2DHeader<DataT>>;\n private _dirty: boolean;\n private _tiles: SharedTile2DHeader<DataT>[];\n private _cacheByteSize: number;\n private _unloadedTileCount: number;\n private _listeners = new Set<Tile2DListener<DataT>>();\n private _consumers = new Map<symbol, ConsumerState<DataT>>();\n private _explicitOptionKeys = new Set<string>();\n private _baseOpts: Partial<Tileset2DProps<DataT, ViewStateT>> = {};\n private _sourceMetadataOverrides: Partial<Tileset2DProps<DataT, ViewStateT>> = {};\n private _maxZoom?: number;\n private _minZoom?: number;\n private _lastTileContext: Tileset2DTileContext<ViewStateT> | null = null;\n\n /** Creates a tileset from either `getTileData` or a loaders.gl `TileSource`. */\n constructor(opts: Tileset2DProps<DataT, ViewStateT>) {\n this.stats = new Stats({\n id: 'Tileset2D',\n stats: [\n {name: 'Tiles In Cache'},\n {name: 'Cache Size'},\n {name: 'Visible Tiles'},\n {name: 'Selected Tiles'},\n {name: 'Loading Tiles'},\n {name: 'Unloaded Tiles'},\n {name: 'Consumers'}\n ]\n });\n this.opts = {\n ...DEFAULT_TILESET2D_PROPS,\n ...opts,\n getTileData: opts.getTileData || (() => null),\n tileSource: opts.tileSource\n } as Required<Tileset2DProps<DataT, ViewStateT>>;\n\n this._requestScheduler = new RequestScheduler({\n throttleRequests: this.opts.maxRequests > 0 || this.opts.debounceTime > 0,\n maxRequests: this.opts.maxRequests,\n debounceTime: this.opts.debounceTime\n });\n\n this._cache = new Map();\n this._tiles = [];\n this._dirty = false;\n this._cacheByteSize = 0;\n this._unloadedTileCount = 0;\n\n if (!this.opts.tileSource && !opts.getTileData) {\n throw new Error('Tileset2D requires either `getTileData` or `tileSource`.');\n }\n\n this.setOptions(opts);\n this._updateStats();\n\n if (this.opts.tileSource) {\n this._initializeTileSource(this.opts.tileSource).catch(() => {});\n }\n }\n\n /** Convenience factory for wrapping a loaders.gl `TileSource`. */\n static fromTileSource<DataT = any>(\n tileSource: TileSource,\n opts: Omit<Tileset2DProps<DataT>, 'tileSource' | 'getTileData'> = {}\n ): Tileset2D<DataT> {\n return new Tileset2D<DataT>({...opts, tileSource});\n }\n\n /** All tiles currently present in the shared cache. */\n get tiles(): SharedTile2DHeader<DataT>[] {\n return this._tiles;\n }\n\n /** Estimated byte size of all tile content currently retained in cache. */\n get cacheByteSize(): number {\n return this._cacheByteSize;\n }\n\n /** Union of tiles selected by all attached consumers. */\n get selectedTiles(): SharedTile2DHeader<DataT>[] {\n return Array.from(this._getSelectedTilesUnion());\n }\n\n /** Union of tiles contributing to the visible result across all consumers and views. */\n get visibleTiles(): SharedTile2DHeader<DataT>[] {\n const union = this._getVisibleTilesUnion();\n for (const tile of this._getSelectedTilesUnion()) {\n union.add(tile);\n }\n return Array.from(union);\n }\n\n /** Tiles currently loading anywhere in the shared cache. */\n get loadingTiles(): SharedTile2DHeader<DataT>[] {\n return Array.from(this._cache.values()).filter(tile => tile.isLoading);\n }\n\n /** Tiles retained in cache that do not currently have loaded content. */\n get unloadedTiles(): SharedTile2DHeader<DataT>[] {\n return Array.from(this._cache.values()).filter(tile => !tile.isLoaded);\n }\n\n /** Maximum resolved zoom level after applying metadata and explicit options. */\n get maxZoom(): number | undefined {\n return this._maxZoom;\n }\n\n /** Minimum resolved zoom level after applying metadata and explicit options. */\n get minZoom(): number | undefined {\n return this._minZoom;\n }\n\n /** Active refinement strategy for placeholder handling. */\n get refinementStrategy(): RefinementStrategy {\n return this.opts.refinementStrategy || STRATEGY_DEFAULT;\n }\n\n /** Adapter currently used for traversal and tile metadata. */\n get adapter(): Tileset2DAdapter<ViewStateT> | null {\n return this.opts.adapter;\n }\n\n /** Subscribes to tileset lifecycle events. */\n subscribe(listener: Tile2DListener<DataT>): () => void {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n }\n\n /** Registers a consumer so cache pruning can account for its selected tiles. */\n attachConsumer(id: symbol): void {\n this._consumers.set(id, {selectedTiles: new Set(), visibleTiles: new Set()});\n this._updateStats();\n }\n\n /** Unregisters a consumer and prunes unused requests and tiles. */\n detachConsumer(id: symbol): void {\n this._consumers.delete(id);\n this._pruneRequests();\n this._resizeCache();\n this._updateStats();\n }\n\n /** Updates tileset options and reapplies TileSource metadata overrides. */\n setOptions(opts: Partial<Tileset2DProps<DataT, ViewStateT>>): void {\n this._rememberExplicitOptions(opts);\n this._baseOpts = {...this._baseOpts, ...opts};\n const previousMaxRequests = this.opts.maxRequests;\n const previousDebounceTime = this.opts.debounceTime;\n this._applyResolvedOptions();\n if (\n previousMaxRequests !== this.opts.maxRequests ||\n previousDebounceTime !== this.opts.debounceTime\n ) {\n this._requestScheduler = new RequestScheduler({\n throttleRequests: this.opts.maxRequests > 0 || this.opts.debounceTime > 0,\n maxRequests: this.opts.maxRequests,\n debounceTime: this.opts.debounceTime\n });\n }\n }\n\n /** Aborts in-flight requests and clears the shared cache. */\n finalize(): void {\n for (const tile of this._cache.values()) {\n if (tile.isLoading) {\n tile.abort();\n }\n }\n this._cache.clear();\n this._tiles = [];\n this._consumers.clear();\n this._cacheByteSize = 0;\n this._unloadedTileCount = 0;\n this._updateStats();\n }\n\n /** Marks all retained tiles stale and drops unused cached tiles. */\n reloadAll(): void {\n const selectedTiles = this._getSelectedTilesUnion();\n for (const id of this._cache.keys()) {\n const tile = this._cache.get(id);\n if (tile && !selectedTiles.has(tile)) {\n this._cache.delete(id);\n this._handleTileUnload(tile);\n this._dirty = true;\n } else if (tile) {\n tile.setNeedsReload();\n }\n }\n this._cacheByteSize = this._getCacheByteSize();\n this.prepareTiles();\n this._updateStats();\n }\n\n /** Updates the selected and visible tile sets for one consumer. */\n updateConsumer(\n id: symbol,\n selectedTiles: SharedTile2DHeader<DataT>[],\n visibleTiles: SharedTile2DHeader<DataT>[]\n ): void {\n this._consumers.set(id, {\n selectedTiles: new Set(selectedTiles),\n visibleTiles: new Set(visibleTiles)\n });\n this._pruneRequests();\n this._resizeCache();\n this._updateStats();\n }\n\n /** Rebuilds parent/child links if the cache changed since the last traversal. */\n prepareTiles(): void {\n if (this._dirty) {\n this._rebuildTree();\n this._syncTiles();\n this._dirty = false;\n }\n }\n\n /** Returns tile indices needed to cover a viewport. */\n getTileIndices({\n viewState,\n maxZoom,\n minZoom,\n zRange,\n modelMatrix,\n modelMatrixInverse\n }: {\n viewState: ViewStateT;\n maxZoom?: number;\n minZoom?: number;\n zRange: ZRange | null;\n modelMatrix?: readonly number[] | null;\n modelMatrixInverse?: readonly number[] | null;\n }): TileIndex[] {\n const {adapter, tileSize, extent, zoomOffset} = this.opts;\n if (!adapter) {\n throw new Error('Tileset2D requires an adapter before tile traversal can be used.');\n }\n this._lastTileContext = {viewState, tileSize};\n return adapter.getTileIndices({\n viewState,\n maxZoom,\n minZoom,\n zRange,\n tileSize,\n extent: normalizeBounds(extent),\n modelMatrix,\n modelMatrixInverse,\n zoomOffset\n });\n }\n\n /** Returns the stable cache id for a tile index. */\n getTileId(index: TileIndex): string {\n return `${index.x}-${index.y}-${index.z}`;\n }\n\n /** Returns the zoom level represented by a tile index. */\n getTileZoom(index: TileIndex): number {\n return index.z;\n }\n\n /** Returns derived metadata used to initialize a tile header. */\n getTileMetadata(index: TileIndex): Record<string, any> {\n if (!this._lastTileContext) {\n throw new Error('Tileset2D metadata requested before traversal context was set.');\n }\n if (!this.opts.adapter) {\n throw new Error('Tileset2D requires an adapter before tile metadata can be derived.');\n }\n return {bbox: this.opts.adapter.getTileBoundingBox(this._lastTileContext, index)};\n }\n\n /** Returns the parent tile index in the quadtree. */\n getParentIndex(index: TileIndex): TileIndex {\n return {x: Math.floor(index.x / 2), y: Math.floor(index.y / 2), z: index.z - 1};\n }\n\n /** Returns a cached tile and optionally creates and loads it on demand. */\n getTile(index: TileIndex, create: true): SharedTile2DHeader<DataT>;\n getTile(index: TileIndex, create?: false): SharedTile2DHeader<DataT> | undefined;\n getTile(index: TileIndex, create?: boolean): SharedTile2DHeader<DataT> | undefined {\n const id = this.getTileId(index);\n let tile = this._cache.get(id);\n let needsReload = false;\n\n if (!tile && create) {\n tile = new SharedTile2DHeader(index);\n Object.assign(tile, this.getTileMetadata(tile.index));\n Object.assign(tile, {id, zoom: this.getTileZoom(tile.index)});\n needsReload = true;\n this._cache.set(id, tile);\n this._dirty = true;\n this._updateStats();\n } else if (tile && tile.needsReload) {\n needsReload = true;\n }\n\n if (tile) {\n this._touchTile(id, tile);\n }\n\n if (tile && needsReload && create) {\n tile\n .loadData({\n getData: this.opts.getTileData,\n requestScheduler: this._requestScheduler,\n onLoad: this._handleTileLoad.bind(this),\n onError: this._handleTileError.bind(this)\n })\n .catch(() => {});\n this._updateStats();\n }\n\n return tile;\n }\n\n /** Loads metadata from a TileSource and reapplies derived option overrides. */\n private async _initializeTileSource(tileSource: TileSource): Promise<void> {\n try {\n this.sourceMetadata = await tileSource.getMetadata();\n this._sourceMetadataOverrides = this._getMetadataOverrides(this.sourceMetadata);\n this._applyResolvedOptions();\n this._notifyUpdate();\n } catch (error: any) {\n const normalizedError =\n error instanceof Error ? error : new Error(`TileSource metadata error: ${String(error)}`);\n this._notifyError(normalizedError);\n }\n }\n\n /** Tracks which options were explicitly set by the caller. */\n private _rememberExplicitOptions(opts: Partial<Tileset2DProps<DataT, ViewStateT>>): void {\n for (const key of Object.keys(opts)) {\n this._explicitOptionKeys.add(key);\n }\n }\n\n /** Resolves defaults, metadata overrides, and caller options into runtime settings. */\n private _applyResolvedOptions(): void {\n const resolvedOpts = {\n ...DEFAULT_TILESET2D_PROPS,\n ...this._sourceMetadataOverrides,\n ...this._baseOpts\n } as Required<Tileset2DProps<DataT, ViewStateT>>;\n\n if (resolvedOpts.tileSource) {\n const tileSource = resolvedOpts.tileSource;\n resolvedOpts.getTileData = (loadProps: TileLoadProps) =>\n tileSource.getTileData(loadProps) as Promise<DataT | null> | DataT | null;\n }\n\n this.opts = resolvedOpts;\n this._maxZoom =\n typeof this.opts.maxZoom === 'number' && Number.isFinite(this.opts.maxZoom)\n ? Math.floor(this.opts.maxZoom)\n : undefined;\n this._minZoom =\n typeof this.opts.minZoom === 'number' && Number.isFinite(this.opts.minZoom)\n ? Math.ceil(this.opts.minZoom)\n : undefined;\n }\n\n /** Maps TileSource metadata into supported tileset options. */\n private _getMetadataOverrides(\n metadata: TileSourceMetadata | null\n ): Partial<Tileset2DProps<DataT, ViewStateT>> {\n if (!metadata) {\n return {};\n }\n const overrides: Partial<Tileset2DProps<DataT, ViewStateT>> = {};\n if (!this._explicitOptionKeys.has('minZoom') && Number.isFinite(metadata.minZoom)) {\n overrides.minZoom = metadata.minZoom;\n }\n if (!this._explicitOptionKeys.has('maxZoom') && Number.isFinite(metadata.maxZoom)) {\n overrides.maxZoom = metadata.maxZoom;\n }\n if (!this._explicitOptionKeys.has('extent') && metadata.boundingBox) {\n overrides.extent = [\n metadata.boundingBox[0][0],\n metadata.boundingBox[0][1],\n metadata.boundingBox[1][0],\n metadata.boundingBox[1][1]\n ];\n }\n return overrides;\n }\n\n /** Handles successful tile loads. */\n private _handleTileLoad(tile: SharedTile2DHeader<DataT>): void {\n this.opts.onTileLoad?.(tile);\n this._cacheByteSize = this._getCacheByteSize();\n this._resizeCache();\n for (const listener of this._listeners) {\n listener.onTileLoad?.(tile);\n }\n this._updateStats();\n }\n\n /** Handles tile load failures. */\n private _handleTileError(error: any, tile: SharedTile2DHeader<DataT>): void {\n this.opts.onTileError?.(error, tile);\n for (const listener of this._listeners) {\n listener.onTileError?.(error, tile);\n }\n this._updateStats();\n }\n\n /** Handles tile eviction from cache. */\n private _handleTileUnload(tile: SharedTile2DHeader<DataT>): void {\n this._unloadedTileCount++;\n this.opts.onTileUnload?.(tile);\n for (const listener of this._listeners) {\n listener.onTileUnload?.(tile);\n }\n this._updateStats();\n }\n\n /** Notifies listeners that metadata or effective options changed. */\n private _notifyUpdate(): void {\n for (const listener of this._listeners) {\n listener.onUpdate?.();\n }\n }\n\n /** Notifies listeners about asynchronous metadata errors. */\n private _notifyError(error: Error): void {\n for (const listener of this._listeners) {\n listener.onError?.(error);\n }\n }\n\n /** Recomputes absolute counter stats and notifies listeners. */\n private _updateStats(): void {\n this._setStatCount('Tiles In Cache', this._cache.size);\n this._setStatCount('Cache Size', this.cacheByteSize);\n this._setStatCount('Visible Tiles', this.visibleTiles.length);\n this._setStatCount('Selected Tiles', this.selectedTiles.length);\n this._setStatCount('Loading Tiles', this.loadingTiles.length);\n this._setStatCount('Unloaded Tiles', this._unloadedTileCount);\n this._setStatCount('Consumers', this._consumers.size);\n\n for (const listener of this._listeners) {\n listener.onStatsChange?.(this.stats);\n }\n }\n\n /** Writes an absolute count into a probe.gl stat. */\n private _setStatCount(name: string, value: number): void {\n this.stats.get(name).reset().addCount(value);\n }\n\n /** Returns the union of selected tiles across all consumers. */\n private _getSelectedTilesUnion(): Set<SharedTile2DHeader<DataT>> {\n const union = new Set<SharedTile2DHeader<DataT>>();\n for (const consumer of this._consumers.values()) {\n for (const tile of consumer.selectedTiles) {\n union.add(tile);\n }\n }\n return union;\n }\n\n /** Returns the union of visible tiles across all consumers. */\n private _getVisibleTilesUnion(): Set<SharedTile2DHeader<DataT>> {\n const union = new Set<SharedTile2DHeader<DataT>>();\n for (const consumer of this._consumers.values()) {\n for (const tile of consumer.visibleTiles) {\n union.add(tile);\n }\n }\n return union;\n }\n\n /** Moves a touched tile to the back of the cache map for LRU eviction ordering. */\n private _touchTile(id: string, tile: SharedTile2DHeader<DataT>): void {\n this._cache.delete(id);\n this._cache.set(id, tile);\n }\n\n /** Computes the total byte size of all cached tile content. */\n private _getCacheByteSize(): number {\n let byteLength = 0;\n for (const tile of this._cache.values()) {\n byteLength += tile.byteLength;\n }\n return byteLength;\n }\n\n /** Cancels low-priority requests when consumers no longer need them. */\n private _pruneRequests(): void {\n const {maxRequests = 0} = this.opts;\n const selectedTiles = this._getSelectedTilesUnion();\n const visibleTiles = this._getVisibleTilesUnion();\n const abortCandidates: SharedTile2DHeader<DataT>[] = [];\n let ongoingRequestCount = 0;\n\n for (const tile of this._cache.values()) {\n if (tile.isLoading) {\n ongoingRequestCount++;\n if (!selectedTiles.has(tile) && !visibleTiles.has(tile)) {\n abortCandidates.push(tile);\n }\n }\n }\n\n while (maxRequests > 0 && ongoingRequestCount > maxRequests && abortCandidates.length > 0) {\n const tile = abortCandidates.shift();\n if (tile) {\n tile.abort();\n }\n ongoingRequestCount--;\n }\n }\n\n /** Rebuilds parent and child links for all cached tiles. */\n private _rebuildTree(): void {\n for (const tile of this._cache.values()) {\n tile.parent = null;\n if (tile.children) {\n tile.children.length = 0;\n }\n }\n for (const tile of this._cache.values()) {\n const parent = this._getNearestAncestor(tile);\n tile.parent = parent;\n if (parent?.children) {\n parent.children.push(tile);\n }\n }\n }\n\n /** Updates the sorted tile list used by traversal and rendering. */\n private _syncTiles(): void {\n this._tiles = Array.from(this._cache.values()).sort((tile1, tile2) => tile1.zoom - tile2.zoom);\n }\n\n /** Evicts unused cached tiles when configured cache limits are exceeded. */\n private _resizeCache(): void {\n const maxCacheSize = this.opts.maxCacheSize ?? 100;\n const maxCacheByteSize = this.opts.maxCacheByteSize ?? Infinity;\n const visibleTiles = this._getVisibleTilesUnion();\n const selectedTiles = this._getSelectedTilesUnion();\n const overflown = this._cache.size > maxCacheSize || this._cacheByteSize > maxCacheByteSize;\n\n if (overflown) {\n for (const [id, tile] of this._cache) {\n if (!visibleTiles.has(tile) && !selectedTiles.has(tile)) {\n this._cache.delete(id);\n this._cacheByteSize = this._getCacheByteSize();\n this._handleTileUnload(tile);\n }\n if (this._cache.size <= maxCacheSize && this._cacheByteSize <= maxCacheByteSize) {\n break;\n }\n }\n this._dirty = true;\n }\n\n if (this._dirty) {\n this._rebuildTree();\n this._syncTiles();\n this._dirty = false;\n }\n }\n\n /** Finds the nearest cached ancestor tile for placeholder rendering. */\n private _getNearestAncestor(tile: SharedTile2DHeader<DataT>): SharedTile2DHeader<DataT> | null {\n const {_minZoom = 0} = this;\n let index = tile.index;\n while (this.getTileZoom(index) > _minZoom) {\n index = this.getParentIndex(index);\n const parent = this.getTile(index);\n if (parent) {\n return parent;\n }\n }\n return null;\n }\n}\n\nfunction normalizeBounds(extent: number[] | null | undefined) {\n return extent && extent.length === 4 ? (extent as [number, number, number, number]) : undefined;\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n GetImageParameters,\n ImageSource,\n ImageSourceMetadata,\n ImageType\n} from '@loaders.gl/loader-utils';\n\n/** Accepted image request currently retained by {@link ImageSet}. */\nexport type ImageSetRequest<DataT = ImageType> = {\n /** Unique request id assigned by the manager. */\n requestId: number;\n /** Image request parameters that produced the accepted image. */\n parameters: GetImageParameters;\n /** Image retained as the current output. */\n image: DataT;\n};\n\n/** Configuration shared by all {@link ImageSet} instances. */\nexport type ImageSetBaseProps<DataT = ImageType> = {\n /** Callback used to load source metadata. */\n getMetadata: () => Promise<ImageSourceMetadata>;\n /** Callback used to load an image for a viewport-derived request. */\n getImage: (parameters: GetImageParameters) => Promise<DataT>;\n /** Debounce interval applied before issuing image requests. */\n debounceTime?: number;\n};\n\n/** Options for creating an {@link ImageSet}. */\nexport type ImageSetProps<DataT = ImageType> = Partial<ImageSetBaseProps<DataT>> & {\n /** Optional loaders.gl image source backing this manager. */\n imageSource?: ImageSource | null;\n};\n\n/** Subscription callbacks emitted by {@link ImageSet}. */\nexport type ImageSetListener<DataT = ImageType> = {\n /** Fired when metadata/image loading starts or stops. */\n onLoadingStateChange?: (isLoading: boolean) => void;\n /** Fired when source metadata resolves successfully. */\n onMetadataLoad?: (metadata: ImageSourceMetadata) => void;\n /** Fired when metadata loading fails. */\n onMetadataLoadError?: (error: Error) => void;\n /** Fired when a new image request is issued. */\n onImageLoadStart?: (requestId: number, parameters: GetImageParameters) => void;\n /** Fired when an image request resolves and becomes current. */\n onImageLoad?: (request: ImageSetRequest<DataT>) => void;\n /** Fired when an image request fails. */\n onImageLoadError?: (requestId: number, error: Error, parameters: GetImageParameters) => void;\n /** Fired when metadata or the current image changes. */\n onUpdate?: () => void;\n};\n\nconst DEFAULT_IMAGESET_PROPS: Required<Omit<ImageSetProps, 'imageSource'>> = {\n getMetadata: async () => ({name: '', keywords: [], layers: []}),\n getImage: async () => null as never,\n debounceTime: 0\n};\n\n/** Shared image request manager used by source-backed image layers. */\nexport class ImageSet<DataT = ImageType> {\n /** Cached metadata returned by the backing source, if any. */\n metadata: ImageSourceMetadata | null = null;\n\n private _opts: Required<ImageSetProps<DataT>>;\n private _listeners = new Set<ImageSetListener<DataT>>();\n private _currentRequest: ImageSetRequest<DataT> | null = null;\n private _lastAcceptedRequestId = -1;\n private _nextRequestId = 0;\n private _loadCounter = 0;\n private _timeoutId: ReturnType<typeof setTimeout> | null = null;\n private _abortController: AbortController | null = null;\n private _finalized = false;\n\n /** Creates an image manager from a source or direct callbacks. */\n constructor(opts: ImageSetProps<DataT>) {\n this._opts = this._normalizeOptions(opts);\n if (!this._opts.imageSource && (!opts.getImage || !opts.getMetadata)) {\n throw new Error(\n 'ImageSet requires either `imageSource` or both `getImage` and `getMetadata`.'\n );\n }\n }\n\n /** Convenience factory for wrapping a loaders.gl {@link ImageSource}. */\n static fromImageSource<DataT = ImageType>(\n imageSource: ImageSource,\n opts: Omit<ImageSetProps<DataT>, 'imageSource' | 'getImage' | 'getMetadata'> = {}\n ): ImageSet<DataT> {\n return new ImageSet<DataT>({...opts, imageSource});\n }\n\n /** Whether the manager has no requests in flight and a current image. */\n get isLoaded(): boolean {\n return this._loadCounter === 0 && Boolean(this._currentRequest);\n }\n\n /** Current accepted image, if any. */\n get image(): DataT | null {\n return this._currentRequest?.image || null;\n }\n\n /** Current accepted request and image payload, if any. */\n get currentRequest(): ImageSetRequest<DataT> | null {\n return this._currentRequest;\n }\n\n /** Backing image source when constructed from one. */\n get imageSource(): ImageSource | null {\n return this._opts.imageSource;\n }\n\n /** Subscribes to metadata and image lifecycle events. */\n subscribe(listener: ImageSetListener<DataT>): () => void {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n }\n\n /** Updates source callbacks or debounce settings, resetting state when the source changes. */\n setOptions(opts: ImageSetProps<DataT>): void {\n const previousImageSource = this._opts.imageSource;\n const nextOptions = this._normalizeOptions({...this._opts, ...opts});\n const sourceChanged =\n previousImageSource !== nextOptions.imageSource ||\n this._opts.getImage !== nextOptions.getImage ||\n this._opts.getMetadata !== nextOptions.getMetadata;\n\n this._opts = nextOptions;\n\n if (sourceChanged) {\n this._cancelScheduledImage();\n this.metadata = null;\n this._currentRequest = null;\n this._lastAcceptedRequestId = -1;\n this._nextRequestId = 0;\n this._emitUpdate();\n }\n }\n\n /** Loads metadata from the current image source or callbacks. */\n async loadMetadata(): Promise<ImageSourceMetadata> {\n this._startLoading();\n try {\n const metadata = await this._opts.getMetadata();\n if (this._finalized) {\n return metadata;\n }\n this.metadata = metadata;\n for (const listener of this._listeners) {\n listener.onMetadataLoad?.(metadata);\n }\n this._emitUpdate();\n return metadata;\n } catch (error) {\n const normalizedError = normalizeImageSetError(error, 'Image metadata request failed');\n if (!this._finalized) {\n for (const listener of this._listeners) {\n listener.onMetadataLoadError?.(normalizedError);\n }\n }\n throw normalizedError;\n } finally {\n this._finishLoading();\n }\n }\n\n /** Debounces and issues a new image request for the supplied parameters. */\n requestImage(parameters: GetImageParameters, debounceTime = this._opts.debounceTime): number {\n const requestId = this._nextRequestId++;\n this._cancelScheduledImage();\n this._abortActiveRequest();\n\n if (debounceTime > 0) {\n this._timeoutId = setTimeout(() => {\n this._timeoutId = null;\n void this._loadImage(requestId, parameters);\n }, debounceTime);\n } else {\n void this._loadImage(requestId, parameters);\n }\n\n return requestId;\n }\n\n /** Clears timers and listeners held by the manager. */\n finalize(): void {\n this._finalized = true;\n this._cancelScheduledImage();\n this._abortActiveRequest();\n this._listeners.clear();\n }\n\n /** Loads an image immediately and accepts it only if it is the newest completed request. */\n private async _loadImage(requestId: number, parameters: GetImageParameters): Promise<void> {\n if (this._finalized) {\n return;\n }\n\n this._startLoading();\n for (const listener of this._listeners) {\n listener.onImageLoadStart?.(requestId, parameters);\n }\n\n try {\n const abortController = new AbortController();\n this._abortController = abortController;\n const image = await this._opts.getImage({...parameters, signal: abortController.signal});\n if (this._finalized || requestId <= this._lastAcceptedRequestId) {\n return;\n }\n\n this._lastAcceptedRequestId = requestId;\n this._currentRequest = {requestId, parameters, image};\n\n for (const listener of this._listeners) {\n listener.onImageLoad?.(this._currentRequest);\n }\n this._emitUpdate();\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n const normalizedError = normalizeImageSetError(error, 'Image request failed');\n if (!this._finalized) {\n for (const listener of this._listeners) {\n listener.onImageLoadError?.(requestId, normalizedError, parameters);\n }\n }\n } finally {\n if (this._abortController?.signal === parameters.signal) {\n this._abortController = null;\n }\n this._finishLoading();\n }\n }\n\n /** Resolves current options from either a source or direct callbacks. */\n private _normalizeOptions(opts: ImageSetProps<DataT>): Required<ImageSetProps<DataT>> {\n const imageSource = opts.imageSource || null;\n return {\n ...DEFAULT_IMAGESET_PROPS,\n ...opts,\n imageSource,\n getMetadata:\n opts.getMetadata ||\n (() => {\n if (imageSource) {\n return imageSource.getMetadata();\n }\n return DEFAULT_IMAGESET_PROPS.getMetadata();\n }),\n getImage:\n opts.getImage ||\n ((parameters: GetImageParameters) => {\n if (imageSource) {\n return imageSource.getImage(parameters) as Promise<DataT>;\n }\n return DEFAULT_IMAGESET_PROPS.getImage(parameters) as Promise<DataT>;\n }),\n debounceTime: opts.debounceTime ?? DEFAULT_IMAGESET_PROPS.debounceTime\n };\n }\n\n /** Notifies listeners that current metadata or image output changed. */\n private _emitUpdate(): void {\n for (const listener of this._listeners) {\n listener.onUpdate?.();\n }\n }\n\n /** Increments the active load count and emits loading changes. */\n private _startLoading(): void {\n const wasLoading = this._loadCounter > 0;\n this._loadCounter++;\n if (!wasLoading) {\n this._emitLoadingStateChange(true);\n this._emitUpdate();\n }\n }\n\n /** Decrements the active load count and emits loading changes. */\n private _finishLoading(): void {\n const wasLoading = this._loadCounter > 0;\n this._loadCounter = Math.max(0, this._loadCounter - 1);\n if (wasLoading && this._loadCounter === 0) {\n this._emitLoadingStateChange(false);\n this._emitUpdate();\n }\n }\n\n /** Notifies listeners when the overall loading state changes. */\n private _emitLoadingStateChange(isLoading: boolean): void {\n for (const listener of this._listeners) {\n listener.onLoadingStateChange?.(isLoading);\n }\n }\n\n /** Clears any pending debounced image request. */\n private _cancelScheduledImage(): void {\n if (this._timeoutId !== null) {\n clearTimeout(this._timeoutId);\n this._timeoutId = null;\n }\n }\n\n /** Aborts the current in-flight image request, if any. */\n private _abortActiveRequest(): void {\n this._abortController?.abort();\n this._abortController = null;\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError';\n}\n\n/** Normalizes arbitrary thrown values to `Error` instances for bookkeeping. */\nfunction normalizeImageSetError(error: unknown, message: string): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error(message);\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// SPDX-FileCopyrightText: Copyright (c) vis.gl contributors\n\nimport type {\n GetRasterParameters,\n NumericRasterData,\n RasterData,\n RasterSource,\n RasterSourceMetadata\n} from '@loaders.gl/loader-utils';\nimport {waitForPromiseWithSignals} from '@loaders.gl/loader-utils';\n\n/** Accepted raster request currently retained by {@link RasterSet}. */\nexport type RasterSetRequest<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters\n> = {\n /** Unique request id assigned by the manager. */\n requestId: number;\n /** Raster request parameters that produced the accepted raster payload. */\n parameters: ParametersT;\n /** Raster retained as the current output. */\n raster: DataT;\n};\n\n/** Arguments supplied to {@link RasterSetBaseProps.shouldRefetch}. */\nexport type RasterSetShouldRefetchArgs<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n> = {\n /** Current accepted request retained by the raster manager, if any. */\n currentRequest: RasterSetRequest<DataT, ParametersT> | null;\n /** Source metadata resolved by {@link RasterSet.loadMetadata}, if available. */\n metadata: MetadataT | null;\n /** Candidate raster request parameters under evaluation. */\n nextParameters: ParametersT;\n};\n\n/** Configuration shared by all {@link RasterSet} instances. */\nexport type RasterSetBaseProps<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n> = {\n /** Callback used to load source metadata. */\n getMetadata: (options?: {\n /** Metadata request cancellation. */ signal?: AbortSignal;\n }) => Promise<MetadataT>;\n /** Callback used to load raster data for a viewport-derived request. */\n getRaster: (parameters: ParametersT) => Promise<DataT>;\n /** Debounce interval applied before issuing raster requests. */\n debounceTime?: number;\n /** Optional policy callback that can skip redundant raster requests. */\n shouldRefetch?: (args: RasterSetShouldRefetchArgs<DataT, ParametersT, MetadataT>) => boolean;\n};\n\n/** Options for creating a {@link RasterSet}. */\nexport type RasterSetProps<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n> = Partial<RasterSetBaseProps<DataT, ParametersT, MetadataT>> & {\n /** Optional loaders.gl raster source backing this manager. */\n rasterSource?: RasterSource<DataT, ParametersT & GetRasterParameters, MetadataT> | null;\n};\n\n/** Subscription callbacks emitted by {@link RasterSet}. */\nexport type RasterSetListener<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n> = {\n /** Fired when metadata/raster loading starts or stops. */\n onLoadingStateChange?: (isLoading: boolean) => void;\n /** Fired when source metadata resolves successfully. */\n onMetadataLoad?: (metadata: MetadataT) => void;\n /** Fired when metadata loading fails. */\n onMetadataLoadError?: (error: Error) => void;\n /** Fired when a new raster request is issued. */\n onRasterLoadStart?: (requestId: number, parameters: ParametersT) => void;\n /** Fired when a raster request resolves and becomes current. */\n onRasterLoad?: (request: RasterSetRequest<DataT, ParametersT>) => void;\n /** Fired when a raster request fails. */\n onRasterLoadError?: (requestId: number, error: Error, parameters: ParametersT) => void;\n /** Fired when metadata or the current raster changes. */\n onUpdate?: () => void;\n};\n\nconst DEFAULT_RASTERSET_PROPS: Required<Omit<RasterSetProps, 'rasterSource'>> = {\n getMetadata: async () => ({\n width: 0,\n height: 0,\n bandCount: 0,\n dtype: 'uint8'\n }),\n getRaster: async () =>\n ({\n data: new Uint8Array(0),\n width: 0,\n height: 0,\n bandCount: 0,\n dtype: 'uint8'\n }) as never,\n debounceTime: 0,\n shouldRefetch: () => true\n};\n\n/**\n * Shared raster request manager used by viewport-driven raster examples and layers.\n *\n * @typeParam DataT Raster payload retained by the manager.\n * @typeParam ParametersT Request parameters accepted by the source.\n * @typeParam MetadataT Metadata returned by the source.\n */\nexport class RasterSet<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n> {\n /** Cached metadata returned by the backing source, if any. */\n metadata: MetadataT | null = null;\n\n private _opts: Required<RasterSetProps<DataT, ParametersT, MetadataT>>;\n private _listeners = new Set<RasterSetListener<DataT, ParametersT, MetadataT>>();\n private _currentRequest: RasterSetRequest<DataT, ParametersT> | null = null;\n private _nextRequestId = 0;\n private _loadCounter = 0;\n private _timeoutId: ReturnType<typeof setTimeout> | null = null;\n private _abortController: AbortController | null = null;\n /** Controller owned by the newest metadata request. */\n private _metadataAbortController: AbortController | null = null;\n private _finalized = false;\n /** Generation invalidates metadata from replaced sources. */\n private _sourceGeneration = 0;\n /** Monotonic metadata request identity. */\n private _metadataRequestId = 0;\n\n /** Creates a raster manager from a source or direct callbacks. */\n constructor(opts: RasterSetProps<DataT, ParametersT, MetadataT>) {\n this._opts = this._normalizeOptions(opts);\n if (!this._opts.rasterSource && (!opts.getRaster || !opts.getMetadata)) {\n throw new Error(\n 'RasterSet requires either `rasterSource` or both `getRaster` and `getMetadata`.'\n );\n }\n }\n\n /** Convenience factory for wrapping a loaders.gl {@link RasterSource}. */\n static fromRasterSource<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends GetRasterParameters = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n >(\n rasterSource: RasterSource<DataT, ParametersT, MetadataT>,\n opts: Omit<\n RasterSetProps<DataT, ParametersT, MetadataT>,\n 'rasterSource' | 'getRaster' | 'getMetadata'\n > = {}\n ): RasterSet<DataT, ParametersT, MetadataT> {\n return new RasterSet<DataT, ParametersT, MetadataT>({...opts, rasterSource});\n }\n\n /** Convenience factory for sources whose requests are not viewport-shaped. */\n static fromCallbacks<\n DataT extends NumericRasterData = RasterData,\n ParametersT extends object = GetRasterParameters,\n MetadataT extends RasterSourceMetadata = RasterSourceMetadata\n >(\n opts: RasterSetBaseProps<DataT, ParametersT, MetadataT>\n ): RasterSet<DataT, ParametersT, MetadataT> {\n return new RasterSet<DataT, ParametersT, MetadataT>(opts);\n }\n\n /** Whether the manager has no requests in flight and a current raster. */\n get isLoaded(): boolean {\n return this._loadCounter === 0 && Boolean(this._currentRequest);\n }\n\n /** Current accepted raster, if any. */\n get raster(): DataT | null {\n return this._currentRequest?.raster || null;\n }\n\n /** Current accepted request and raster payload, if any. */\n get currentRequest(): RasterSetRequest<DataT, ParametersT> | null {\n return this._currentRequest;\n }\n\n /** Backing raster source when constructed from one. */\n get rasterSource(): RasterSource<DataT, ParametersT & GetRasterParameters, MetadataT> | null {\n return this._opts.rasterSource;\n }\n\n /** Subscribes to metadata and raster lifecycle events. */\n subscribe(listener: RasterSetListener<DataT, ParametersT, MetadataT>): () => void {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n }\n\n /** Updates source callbacks or debounce settings, resetting state when the source changes. */\n setOptions(opts: RasterSetProps<DataT, ParametersT, MetadataT>): void {\n const previousRasterSource = this._opts.rasterSource;\n const mergedOptions: RasterSetProps<DataT, ParametersT, MetadataT> = {...this._opts, ...opts};\n if (opts.rasterSource && opts.rasterSource !== previousRasterSource) {\n mergedOptions.getRaster = opts.getRaster;\n mergedOptions.getMetadata = opts.getMetadata;\n }\n const nextOptions = this._normalizeOptions(mergedOptions);\n const sourceChanged =\n previousRasterSource !== nextOptions.rasterSource ||\n this._opts.getRaster !== nextOptions.getRaster ||\n this._opts.getMetadata !== nextOptions.getMetadata;\n\n this._opts = nextOptions;\n\n if (sourceChanged) {\n this._cancelScheduledRaster();\n this._abortActiveRequest();\n this._metadataAbortController?.abort();\n this._sourceGeneration++;\n this.metadata = null;\n this._currentRequest = null;\n\n this._emitUpdate();\n }\n }\n\n /** Loads metadata from the current raster source or callbacks. */\n async loadMetadata(\n options: {/** Caller cancellation for metadata. */ signal?: AbortSignal} = {}\n ): Promise<MetadataT> {\n if (this._finalized) throw new Error('RasterSet is finalized');\n options.signal?.throwIfAborted();\n this._metadataAbortController?.abort();\n const abortController = new AbortController();\n this._metadataAbortController = abortController;\n const abortFromCaller = () => abortController.abort(options.signal?.reason);\n options.signal?.addEventListener('abort', abortFromCaller, {once: true});\n const metadataRequestId = ++this._metadataRequestId;\n const generation = this._sourceGeneration;\n try {\n this._startLoading();\n abortController.signal.throwIfAborted();\n const metadata = await waitForPromiseWithSignals(\n signal => this._opts.getMetadata({signal}),\n [abortController.signal]\n );\n abortController.signal.throwIfAborted();\n if (\n this._finalized ||\n generation !== this._sourceGeneration ||\n metadataRequestId !== this._metadataRequestId\n ) {\n return metadata;\n }\n this.metadata = metadata;\n for (const listener of this._listeners) {\n listener.onMetadataLoad?.(metadata);\n }\n this._emitUpdate();\n return metadata;\n } catch (error) {\n if (abortController.signal.aborted) throw abortController.signal.reason;\n if (isAbortError(error)) throw error;\n const normalizedError = normalizeRasterSetError(error, 'Raster metadata request failed');\n if (\n !this._finalized &&\n generation === this._sourceGeneration &&\n metadataRequestId === this._metadataRequestId\n ) {\n for (const listener of this._listeners) {\n listener.onMetadataLoadError?.(normalizedError);\n }\n }\n throw normalizedError;\n } finally {\n options.signal?.removeEventListener('abort', abortFromCaller);\n if (this._metadataAbortController === abortController) this._metadataAbortController = null;\n this._finishLoading();\n }\n }\n\n /** Debounces and issues a new raster request for the supplied parameters. */\n requestRaster(parameters: ParametersT, debounceTime = this._opts.debounceTime): number {\n if (this._finalized) return -1;\n if (!this.shouldRefetchRaster(parameters)) {\n this._cancelScheduledRaster();\n this._abortActiveRequest();\n this._nextRequestId++;\n return this._currentRequest?.requestId ?? -1;\n }\n\n const requestId = this._nextRequestId++;\n this._cancelScheduledRaster();\n this._abortActiveRequest();\n\n if (debounceTime > 0) {\n this._timeoutId = setTimeout(() => {\n this._timeoutId = null;\n void this._loadRaster(requestId, parameters);\n }, debounceTime);\n } else {\n void this._loadRaster(requestId, parameters);\n }\n\n return requestId;\n }\n\n /** Returns `true` when the supplied parameters warrant a new raster fetch. */\n shouldRefetchRaster(parameters: ParametersT): boolean {\n return this._opts.shouldRefetch({\n currentRequest: this._currentRequest,\n metadata: this.metadata,\n nextParameters: parameters\n });\n }\n\n /** Clears timers and listeners held by the manager. */\n finalize(): void {\n this._finalized = true;\n this._cancelScheduledRaster();\n this._abortActiveRequest();\n this._metadataAbortController?.abort();\n this._metadataAbortController = null;\n this._loadCounter = 0;\n this._listeners.clear();\n }\n\n /** Loads a raster immediately and accepts it only if it is the newest completed request. */\n private async _loadRaster(requestId: number, parameters: ParametersT): Promise<void> {\n if (this._finalized) {\n return;\n }\n\n const callerSignal = (parameters as {signal?: AbortSignal}).signal;\n if (callerSignal?.aborted) return;\n const abortController = new AbortController();\n this._abortController = abortController;\n const abortFromCaller = () => abortController.abort(callerSignal?.reason);\n callerSignal?.addEventListener('abort', abortFromCaller, {once: true});\n this._startLoading();\n try {\n abortController.signal.throwIfAborted();\n for (const listener of this._listeners) listener.onRasterLoadStart?.(requestId, parameters);\n abortController.signal.throwIfAborted();\n const raster = await waitForPromiseWithSignals(\n signal => this._opts.getRaster(withAbortSignal(parameters, signal)),\n [abortController.signal]\n );\n if (\n this._finalized ||\n abortController.signal.aborted ||\n requestId !== this._nextRequestId - 1\n ) {\n return;\n }\n\n this._currentRequest = {requestId, parameters, raster};\n\n for (const listener of this._listeners) {\n listener.onRasterLoad?.(this._currentRequest);\n }\n this._emitUpdate();\n } catch (error) {\n if (abortController.signal.aborted || isAbortError(error)) {\n return;\n }\n const normalizedError = normalizeRasterSetError(error, 'Raster request failed');\n if (!this._finalized && requestId === this._nextRequestId - 1) {\n for (const listener of this._listeners) {\n listener.onRasterLoadError?.(requestId, normalizedError, parameters);\n }\n }\n } finally {\n callerSignal?.removeEventListener('abort', abortFromCaller);\n if (this._abortController === abortController) this._abortController = null;\n this._finishLoading();\n }\n }\n\n /** Resolves current options from either a source or direct callbacks. */\n private _normalizeOptions(\n opts: RasterSetProps<DataT, ParametersT, MetadataT>\n ): Required<RasterSetProps<DataT, ParametersT, MetadataT>> {\n const rasterSource = opts.rasterSource || null;\n return {\n ...DEFAULT_RASTERSET_PROPS,\n ...opts,\n rasterSource,\n getMetadata:\n opts.getMetadata ||\n (options => {\n if (rasterSource) {\n return rasterSource.getMetadata(options);\n }\n return DEFAULT_RASTERSET_PROPS.getMetadata() as Promise<MetadataT>;\n }),\n getRaster:\n opts.getRaster ||\n ((parameters: ParametersT) => {\n if (rasterSource) {\n return rasterSource.getRaster(parameters as ParametersT & GetRasterParameters);\n }\n return DEFAULT_RASTERSET_PROPS.getRaster(\n parameters as GetRasterParameters\n ) as Promise<DataT>;\n }),\n debounceTime: opts.debounceTime ?? DEFAULT_RASTERSET_PROPS.debounceTime,\n shouldRefetch:\n (opts.shouldRefetch as\n | ((args: RasterSetShouldRefetchArgs<DataT, ParametersT, MetadataT>) => boolean)\n | undefined) ||\n ((args: RasterSetShouldRefetchArgs<DataT, ParametersT, MetadataT>) =>\n DEFAULT_RASTERSET_PROPS.shouldRefetch(args as RasterSetShouldRefetchArgs))\n };\n }\n\n /** Emits one generic update notification to all subscribers. */\n private _emitUpdate(): void {\n if (this._finalized) return;\n for (const listener of this._listeners) {\n listener.onUpdate?.();\n }\n }\n\n /** Emits one loading-state transition to all subscribers. */\n private _emitLoadingStateChange(isLoading: boolean): void {\n if (this._finalized) return;\n for (const listener of this._listeners) {\n listener.onLoadingStateChange?.(isLoading);\n }\n }\n\n /** Increments the active load count and emits loading-state transitions. */\n private _startLoading(): void {\n const wasLoading = this._loadCounter > 0;\n this._loadCounter++;\n if (!wasLoading) {\n this._emitLoadingStateChange(true);\n this._emitUpdate();\n }\n }\n\n /** Decrements the active load count and emits loading-state transitions. */\n private _finishLoading(): void {\n const wasLoading = this._loadCounter > 0;\n this._loadCounter = Math.max(0, this._loadCounter - 1);\n if (wasLoading && this._loadCounter === 0) {\n this._emitLoadingStateChange(false);\n this._emitUpdate();\n }\n }\n\n /** Clears any pending debounced raster request before it hits the network. */\n private _cancelScheduledRaster(): void {\n if (this._timeoutId !== null) {\n clearTimeout(this._timeoutId);\n this._timeoutId = null;\n }\n }\n\n /** Aborts the currently active raster request, if one exists. */\n private _abortActiveRequest(): void {\n this._abortController?.abort();\n this._abortController = null;\n }\n}\n\n/** Adds cancellation to a request while preserving its array/prototype shape. */\nfunction withAbortSignal<ParametersT extends object>(\n parameters: ParametersT,\n signal: AbortSignal\n): ParametersT {\n const descriptors = Object.getOwnPropertyDescriptors(parameters);\n delete descriptors.signal;\n const request = Array.isArray(parameters)\n ? Object.defineProperties(parameters.slice(), descriptors)\n : Object.create(Object.getPrototypeOf(parameters), descriptors);\n Object.defineProperty(request, 'signal', {\n configurable: true,\n enumerable: true,\n value: signal,\n writable: true\n });\n return request as ParametersT;\n}\n\n/** Normalizes arbitrary thrown values to `Error` instances for raster-set callbacks. */\nfunction normalizeRasterSetError(error: unknown, message: string): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error(message);\n}\n\n/** Returns true when an error came from an aborted request. */\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError';\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Vector3} from '@math.gl/core';\nimport {BoundingSphere, CullingVolume, Plane} from '@math.gl/culling';\nimport type {Viewport} from '../types';\nimport {PointCloudTile} from './point-cloud-tile';\nimport type {\n PointCloudBoundingVolume,\n PointCloudTileHeader,\n PointCloudTilesetSource\n} from './types';\n\nexport type PointCloudTilesetOptions = {\n debounceTime?: number;\n minimumNodePixelSize?: number;\n maximumScreenSpaceError?: number;\n /** Override source LOD metric for point-cloud traversal. */\n lodSelectionMetricType?: 'maxScreenThresholdSQ' | 'density-threshold';\n /** Minimum projected point density at which a node is refined. */\n densityThreshold?: number;\n pointBudget?: number;\n maxDepth?: number;\n onTileLoad?: (tile: PointCloudTile) => void;\n onTileError?: (tile: PointCloudTile, error: Error) => void;\n onTraversalComplete?: (selectedTiles: PointCloudTile[]) => PointCloudTile[];\n onUpdate?: () => void;\n};\n\ntype PointCloudTilesetProps = Required<PointCloudTilesetOptions>;\n\nconst DEFAULT_PROPS: PointCloudTilesetProps = {\n debounceTime: 0,\n minimumNodePixelSize: 150,\n maximumScreenSpaceError: 1,\n lodSelectionMetricType: 'maxScreenThresholdSQ',\n densityThreshold: 1,\n pointBudget: 2_000_000,\n maxDepth: Number.POSITIVE_INFINITY,\n onTileLoad: () => {},\n onTileError: () => {},\n onTraversalComplete: (selectedTiles: PointCloudTile[]) => selectedTiles,\n onUpdate: () => {}\n};\n\nconst VISIBILITY_MARGIN_PIXELS = 64;\n\ntype TraversalCandidate = {\n tile: PointCloudTile;\n weight: number;\n};\n\ntype ProjectedBounds = {\n minX: number;\n minY: number;\n maxX: number;\n maxY: number;\n};\n\ntype ProjectedFootprint = {\n x: number;\n y: number;\n radius: number;\n};\n\ntype FrustumPlane = {\n distance: number;\n normal: number[] | Vector3;\n};\n\ntype PointCloudViewport = Viewport & {\n cameraPosition?: number[] | Vector3;\n getFrustumPlanes?: () => Record<string, FrustumPlane>;\n projectPosition?: (coordinates: number[] | Vector3) => number[];\n projectionMatrix?: number[];\n};\n\ntype TraversalContext = {\n viewport: Viewport;\n cullingVolume: CullingVolume | null;\n};\n\n/**\n * A minimal point-cloud-oriented tileset manager backed by a DataSource.\n */\nexport class PointCloudTileset {\n readonly dataSource: PointCloudTilesetSource;\n options: PointCloudTilesetProps;\n root: PointCloudTile | null = null;\n cartographicCenter: Vector3 | null = null;\n zoom = 1;\n boundingVolume: PointCloudBoundingVolume | null = null;\n visibleTilesCount = 0;\n\n private frameNumberValue = 0;\n private pendingCount = 0;\n private lastUpdatedViewports: Viewport[] | Viewport | null = null;\n private updatePromise: Promise<number> | null = null;\n private readonly tilesMap: Map<string, PointCloudTile> = new Map();\n\n constructor(\n dataSource: PointCloudTilesetSource,\n options: Partial<PointCloudTilesetOptions> = {}\n ) {\n this.dataSource = dataSource;\n this.options = {...DEFAULT_PROPS, ...options};\n this.tilesetInitializationPromise = this.initialize();\n }\n\n readonly tilesetInitializationPromise: Promise<void>;\n\n /**\n * Whether the tileset finished initialization.\n */\n get isReady(): boolean {\n return this.dataSource.isReady;\n }\n\n /**\n * Runtime frame number.\n */\n get frameNumber(): number {\n return this.frameNumberValue;\n }\n\n /**\n * All discovered tiles.\n */\n get tiles(): PointCloudTile[] {\n return Array.from(this.tilesMap.values());\n }\n\n /**\n * Whether all currently selected tiles have finished loading.\n */\n isLoaded(): boolean {\n return (\n this.frameNumberValue > 0 &&\n this.pendingCount === 0 &&\n this.selectedTiles.every(tile => tile.contentAvailable || tile.contentFailed)\n );\n }\n\n /**\n * Currently selected tiles.\n */\n selectedTiles: PointCloudTile[] = [];\n\n /**\n * Fire-and-forget update helper.\n */\n update(viewports: Viewport[] | Viewport | null = null): void {\n this.selectTiles(viewports).catch(() => undefined);\n }\n\n /**\n * Releases traversal state held by this tileset.\n */\n destroy(): void {\n this.selectedTiles = [];\n this.tilesMap.clear();\n this.root = null;\n this.cartographicCenter = null;\n this.boundingVolume = null;\n this.visibleTilesCount = 0;\n this.pendingCount = 0;\n this.lastUpdatedViewports = null;\n this.updatePromise = null;\n }\n\n /**\n * Initialize the underlying source and the root tile.\n */\n async initialize(): Promise<void> {\n await this.dataSource.initialize();\n const rootHeader = await this.dataSource.getRootTile();\n this.root = this.getOrCreateTile(rootHeader, null);\n\n const viewState = await this.dataSource.getViewState?.();\n this.boundingVolume = viewState?.boundingVolume || this.root.boundingVolume;\n\n const center = viewState?.cartographicCenter || this.root.boundingVolume.center;\n this.cartographicCenter = new Vector3(center);\n this.zoom = viewState?.zoom || this.estimateZoom(this.boundingVolume);\n }\n\n /**\n * Debounced async tile selection.\n */\n async selectTiles(viewports: Viewport[] | Viewport | null = null): Promise<number> {\n await this.tilesetInitializationPromise;\n if (viewports) {\n this.lastUpdatedViewports = viewports;\n }\n\n if (!this.updatePromise) {\n this.updatePromise = new Promise<number>((resolve, reject) => {\n setTimeout(() => {\n this.doSelectTiles()\n .then(() => resolve(this.frameNumberValue))\n .catch(reject)\n .finally(() => {\n this.updatePromise = null;\n });\n }, this.options.debounceTime);\n });\n }\n\n return this.updatePromise;\n }\n\n private async doSelectTiles(): Promise<void> {\n if (!this.root || !this.lastUpdatedViewports) {\n return;\n }\n\n const previousSelectedIds = new Set(this.selectedTiles.map(tile => tile.id));\n for (const tile of this.tilesMap.values()) {\n tile.clearSelection();\n }\n\n this.frameNumberValue++;\n\n const preparedViewports = Array.isArray(this.lastUpdatedViewports)\n ? this.lastUpdatedViewports\n : [this.lastUpdatedViewports];\n\n const selectedTilesById = new Map<string, PointCloudTile>();\n const visibleTileIds = new Set<string>();\n let selectedPointCount = 0;\n for (const viewport of preparedViewports) {\n const traversalContext = this.getTraversalContext(viewport);\n selectedPointCount = await this.traverseTiles(\n traversalContext,\n selectedTilesById,\n selectedPointCount,\n visibleTileIds\n );\n }\n this.visibleTilesCount = visibleTileIds.size;\n\n this.selectedTiles = this.options.onTraversalComplete(Array.from(selectedTilesById.values()));\n\n for (const tile of this.selectedTiles) {\n this.loadTile(tile).catch(() => undefined);\n }\n\n const nextSelectedIds = new Set(this.selectedTiles.map(tile => tile.id));\n if (!this.haveSameIds(previousSelectedIds, nextSelectedIds)) {\n this.options.onUpdate();\n }\n }\n\n /**\n * Traverses visible tiles in descending projected-size order, similar to Potree's viewer update loop.\n */\n private async traverseTiles(\n traversalContext: TraversalContext,\n selectedTilesById: Map<string, PointCloudTile>,\n initialSelectedPointCount: number,\n visibleTileIds: Set<string>\n ): Promise<number> {\n if (!this.root) {\n return initialSelectedPointCount;\n }\n\n let selectedPointCount = initialSelectedPointCount;\n const traversalQueue: TraversalCandidate[] = [\n {tile: this.root, weight: this.estimateScreenRadius(this.root, traversalContext.viewport)}\n ];\n\n while (traversalQueue.length > 0) {\n traversalQueue.sort((candidateA, candidateB) => candidateB.weight - candidateA.weight);\n const candidate = traversalQueue.shift();\n if (!candidate) {\n break;\n }\n\n const {tile, weight} = candidate;\n if (!this.isVisible(tile, traversalContext)) {\n continue;\n }\n visibleTileIds.add(tile.id);\n\n if (!selectedTilesById.has(tile.id) && tile.pointCount > 0) {\n const exceedsPointBudget =\n selectedPointCount > 0 && selectedPointCount + tile.pointCount > this.options.pointBudget;\n if (exceedsPointBudget) {\n break;\n }\n\n selectedTilesById.set(tile.id, tile);\n selectedPointCount += tile.pointCount;\n }\n\n if (selectedTilesById.has(tile.id)) {\n tile.setSelected(traversalContext.viewport.id);\n }\n\n if (!this.shouldRefine(tile, weight)) {\n continue;\n }\n\n const visibleChildren = await this.getVisibleChildren(tile, traversalContext);\n if (visibleChildren.length > 0) {\n traversalQueue.push(...visibleChildren);\n }\n }\n\n return selectedPointCount;\n }\n\n /** Whether a tile should refine to children based on its projected screen radius. */\n private shouldRefine(tile: PointCloudTile, traversalWeight: number): boolean {\n if (\n tile.level < this.options.maxDepth &&\n Number.isFinite(traversalWeight) &&\n (tile.header.lodSelectionMetricType || this.options.lodSelectionMetricType) ===\n 'density-threshold'\n ) {\n const projectedArea = Math.max(1, Math.PI * traversalWeight * traversalWeight);\n const density = tile.pointCount / projectedArea;\n const threshold = tile.header.lodThreshold || this.options.densityThreshold;\n return density < threshold;\n }\n return (\n tile.level < this.options.maxDepth &&\n Number.isFinite(traversalWeight) &&\n traversalWeight >= this.options.minimumNodePixelSize\n );\n }\n\n /**\n * Build per-viewport traversal state once per traversal pass.\n */\n private getTraversalContext(viewport: Viewport): TraversalContext {\n const cullingVolume = this.getCullingVolume(viewport as PointCloudViewport);\n return {\n viewport,\n cullingVolume: this.shouldUseCullingVolume(viewport, cullingVolume) ? cullingVolume : null\n };\n }\n\n /**\n * Check tile visibility against the viewport frustum when possible.\n */\n private isVisible(tile: PointCloudTile, traversalContext: TraversalContext): boolean {\n if (traversalContext.cullingVolume) {\n const boundingSphere = this.getCommonSpaceBoundingSphere(\n tile.boundingVolume,\n traversalContext.viewport as PointCloudViewport\n );\n\n if (boundingSphere) {\n return this.isBoundingSphereInsideCullingVolume(\n boundingSphere,\n traversalContext.cullingVolume\n );\n }\n }\n\n const footprint = this.getProjectedFootprint(tile.boundingVolume, traversalContext.viewport);\n if (!footprint) {\n return false;\n }\n\n return this.isProjectedFootprintVisible(footprint, traversalContext.viewport);\n }\n\n /**\n * Returns true when the viewport frustum appears usable for this tileset's coordinate space.\n */\n private shouldUseCullingVolume(\n viewport: Viewport,\n cullingVolume: CullingVolume | null\n ): cullingVolume is CullingVolume {\n if (!this.root || !cullingVolume) {\n return false;\n }\n\n const rootBoundingSphere = this.getCommonSpaceBoundingSphere(\n this.root.boundingVolume,\n viewport as PointCloudViewport\n );\n if (!rootBoundingSphere) {\n return false;\n }\n\n if (this.isBoundingSphereInsideCullingVolume(rootBoundingSphere, cullingVolume)) {\n return true;\n }\n\n const projectedFootprint = this.getProjectedFootprint(this.root.boundingVolume, viewport);\n return !projectedFootprint || !this.isProjectedFootprintVisible(projectedFootprint, viewport);\n }\n\n /**\n * Checks whether a common-space bounding sphere intersects a culling volume.\n */\n private isBoundingSphereInsideCullingVolume(\n boundingSphere: BoundingSphere,\n cullingVolume: CullingVolume\n ): boolean {\n return (\n cullingVolume.computeVisibilityWithPlaneMask(\n boundingSphere,\n CullingVolume.MASK_INDETERMINATE\n ) !== CullingVolume.MASK_OUTSIDE\n );\n }\n\n /**\n * Checks a projected screen-space footprint against the viewport rectangle.\n */\n private isProjectedFootprintVisible(footprint: ProjectedFootprint, viewport: Viewport): boolean {\n return !(\n footprint.x + footprint.radius < -VISIBILITY_MARGIN_PIXELS ||\n footprint.x - footprint.radius > viewport.width + VISIBILITY_MARGIN_PIXELS ||\n footprint.y + footprint.radius < -VISIBILITY_MARGIN_PIXELS ||\n footprint.y - footprint.radius > viewport.height + VISIBILITY_MARGIN_PIXELS\n );\n }\n\n /** Estimate traversal priority from projected node radius in screen pixels. */\n private estimateScreenRadius(tile: PointCloudTile, viewport: Viewport): number {\n const footprint = this.getProjectedFootprint(tile.boundingVolume, viewport);\n return footprint ? footprint.radius : 0;\n }\n\n /**\n * Project a tile AABB into screen space and return its 2D footprint.\n */\n private projectBounds(\n boundingVolume: PointCloudBoundingVolume,\n viewport: Viewport\n ): ProjectedBounds | null {\n const corners = this.getBoundingVolumeCorners(boundingVolume);\n\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n\n try {\n for (const corner of corners) {\n const [x, y] = viewport.project(corner);\n if (!Number.isFinite(x) || !Number.isFinite(y)) {\n continue;\n }\n minX = Math.min(minX, x);\n minY = Math.min(minY, y);\n maxX = Math.max(maxX, x);\n maxY = Math.max(maxY, y);\n }\n } catch {\n return null;\n }\n\n if (\n !Number.isFinite(minX) ||\n !Number.isFinite(minY) ||\n !Number.isFinite(maxX) ||\n !Number.isFinite(maxY)\n ) {\n return null;\n }\n\n return {minX, minY, maxX, maxY};\n }\n\n /**\n * Project a tile to a screen-space center/radius footprint.\n */\n private getProjectedFootprint(\n boundingVolume: PointCloudBoundingVolume,\n viewport: Viewport\n ): ProjectedFootprint | null {\n let centerX = Number.NaN;\n let centerY = Number.NaN;\n\n try {\n [centerX, centerY] = viewport.project(boundingVolume.center);\n } catch {\n return null;\n }\n\n if (!Number.isFinite(centerX) || !Number.isFinite(centerY)) {\n return null;\n }\n\n const corners = this.getBoundingVolumeCorners(boundingVolume);\n let projectedRadius = 0;\n\n try {\n for (const corner of corners) {\n const [x, y] = viewport.project(corner);\n if (!Number.isFinite(x) || !Number.isFinite(y)) {\n continue;\n }\n\n projectedRadius = Math.max(projectedRadius, Math.hypot(x - centerX, y - centerY));\n }\n } catch {\n return null;\n }\n\n if (projectedRadius === 0) {\n const fallbackBounds = this.projectBounds(boundingVolume, viewport);\n if (fallbackBounds) {\n projectedRadius =\n Math.max(\n fallbackBounds.maxX - fallbackBounds.minX,\n fallbackBounds.maxY - fallbackBounds.minY\n ) / 2;\n }\n }\n\n return {x: centerX, y: centerY, radius: projectedRadius};\n }\n\n /**\n * Returns visible children ordered by their projected importance.\n */\n private async getVisibleChildren(\n tile: PointCloudTile,\n traversalContext: TraversalContext\n ): Promise<TraversalCandidate[]> {\n if (tile.level >= this.options.maxDepth) {\n return [];\n }\n\n const children = await this.getChildren(tile);\n\n return children\n .map(child => ({\n tile: child,\n weight: this.estimateScreenRadius(child, traversalContext.viewport)\n }))\n .filter(candidate => this.isVisible(candidate.tile, traversalContext));\n }\n\n private async getChildren(tile: PointCloudTile): Promise<PointCloudTile[]> {\n if (tile.childrenLoaded) {\n return tile.children;\n }\n\n if (!tile.childrenPromise) {\n const childrenPromise = this.dataSource\n .getChildren(tile.header)\n .then(headers => headers.map(header => this.getOrCreateTile(header, tile)))\n .then(children => {\n tile.children = children;\n tile.childrenLoaded = true;\n return children;\n });\n\n tile.childrenPromise = childrenPromise.finally(() => {\n if (tile.childrenPromise === childrenPromise) {\n tile.childrenPromise = null;\n }\n });\n }\n\n return tile.childrenPromise;\n }\n\n private getOrCreateTile(\n header: PointCloudTileHeader,\n parent: PointCloudTile | null\n ): PointCloudTile {\n const existingTile = this.tilesMap.get(header.id);\n if (existingTile) {\n existingTile.header = header;\n if (parent && existingTile.parent !== parent) {\n existingTile.parent = parent;\n }\n return existingTile;\n }\n\n const tile = new PointCloudTile(header, parent);\n this.tilesMap.set(header.id, tile);\n if (parent && !parent.children.find(child => child.id === tile.id)) {\n parent.children.push(tile);\n }\n return tile;\n }\n\n private async loadTile(tile: PointCloudTile): Promise<void> {\n if (tile.contentAvailable || tile.isContentLoading || tile.contentFailed) {\n return;\n }\n\n tile.isContentLoading = true;\n this.pendingCount++;\n\n try {\n const content = await this.dataSource.loadTileContent(tile.header);\n tile.content = content;\n tile.contentAvailable = true;\n if (content) {\n this.options.onTileLoad(tile);\n }\n } catch (error) {\n tile.contentFailed = true;\n this.options.onTileError(tile, error as Error);\n } finally {\n tile.isContentLoading = false;\n this.pendingCount--;\n }\n }\n\n private estimateZoom(boundingVolume: PointCloudBoundingVolume | null): number {\n if (!boundingVolume) {\n return 1;\n }\n if (boundingVolume.coordinateFrame === 'cartesian') {\n return 1;\n }\n\n const [minBounds, maxBounds] = boundingVolume.cartographicBounds;\n const longitudeSpan = boundingVolume.coversFullLongitude\n ? 360\n : boundingVolume.wrapsDateline\n ? 360 - Math.abs(maxBounds[0] - minBounds[0])\n : Math.abs(maxBounds[0] - minBounds[0]);\n const normalizedLongitudeSpan = Math.max(longitudeSpan, 0.000001);\n return Math.max(1, Math.round(Math.log2(360 / normalizedLongitudeSpan)));\n }\n\n private haveSameIds(idsA: Set<string>, idsB: Set<string>): boolean {\n if (idsA.size !== idsB.size) {\n return false;\n }\n\n for (const id of idsA) {\n if (!idsB.has(id)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Convert a tile bounding box into its eight corners.\n */\n private getBoundingVolumeCorners(boundingVolume: PointCloudBoundingVolume): number[][] {\n const [minBounds, maxBounds] = boundingVolume.cartographicBounds;\n const longitudeIntervals = boundingVolume.coversFullLongitude\n ? [[-180, 180]]\n : boundingVolume.wrapsDateline\n ? [\n [minBounds[0], 180],\n [-180, maxBounds[0]]\n ]\n : [[minBounds[0], maxBounds[0]]];\n const corners: number[][] = [];\n const wrappedLongitudeSpan = 360 - Math.abs(maxBounds[0] - minBounds[0]);\n const longitudeReference = minBounds[0] + wrappedLongitudeSpan / 2;\n for (const [minimumLongitude, maximumLongitude] of longitudeIntervals) {\n const normalizeLongitude = (longitude: number) => {\n if (!boundingVolume.wrapsDateline) {\n return longitude;\n }\n let normalizedLongitude = longitude;\n while (normalizedLongitude - longitudeReference > 180) {\n normalizedLongitude -= 360;\n }\n while (normalizedLongitude - longitudeReference < -180) {\n normalizedLongitude += 360;\n }\n return normalizedLongitude;\n };\n const unwrappedMinimumLongitude = normalizeLongitude(minimumLongitude);\n const unwrappedMaximumLongitude = normalizeLongitude(maximumLongitude);\n corners.push(\n [unwrappedMinimumLongitude, minBounds[1], minBounds[2] || 0],\n [unwrappedMinimumLongitude, minBounds[1], maxBounds[2] || 0],\n [unwrappedMinimumLongitude, maxBounds[1], minBounds[2] || 0],\n [unwrappedMinimumLongitude, maxBounds[1], maxBounds[2] || 0],\n [unwrappedMaximumLongitude, minBounds[1], minBounds[2] || 0],\n [unwrappedMaximumLongitude, minBounds[1], maxBounds[2] || 0],\n [unwrappedMaximumLongitude, maxBounds[1], minBounds[2] || 0],\n [unwrappedMaximumLongitude, maxBounds[1], maxBounds[2] || 0]\n );\n }\n return corners;\n }\n\n /**\n * Build a culling volume directly from the viewport frustum in common space.\n */\n private getCullingVolume(viewport: PointCloudViewport): CullingVolume | null {\n const getFrustumPlanes = viewport.getFrustumPlanes?.bind(viewport);\n if (!getFrustumPlanes) {\n return null;\n }\n\n const frustumPlanes = getFrustumPlanes();\n const directions = ['left', 'right', 'bottom', 'top', 'near', 'far'];\n const planes: Plane[] = [];\n\n for (const direction of directions) {\n const plane = frustumPlanes[direction];\n if (!plane) {\n return null;\n }\n\n planes.push(new Plane(plane.normal, -plane.distance));\n }\n\n return new CullingVolume(planes);\n }\n\n /**\n * Approximate a tile AABB by a common-space bounding sphere for frustum culling.\n */\n private getCommonSpaceBoundingSphere(\n boundingVolume: PointCloudBoundingVolume,\n viewport: PointCloudViewport\n ): BoundingSphere | null {\n const projectPosition = viewport.projectPosition?.bind(viewport);\n if (!projectPosition) {\n return null;\n }\n\n const corners = this.getBoundingVolumeCorners(boundingVolume);\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let minZ = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let maxZ = Number.NEGATIVE_INFINITY;\n\n try {\n for (const corner of corners) {\n const [x, y, z = 0] = projectPosition(corner);\n if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {\n continue;\n }\n\n minX = Math.min(minX, x);\n minY = Math.min(minY, y);\n minZ = Math.min(minZ, z);\n maxX = Math.max(maxX, x);\n maxY = Math.max(maxY, y);\n maxZ = Math.max(maxZ, z);\n }\n } catch {\n return null;\n }\n\n if (\n !Number.isFinite(minX) ||\n !Number.isFinite(minY) ||\n !Number.isFinite(minZ) ||\n !Number.isFinite(maxX) ||\n !Number.isFinite(maxY) ||\n !Number.isFinite(maxZ)\n ) {\n return null;\n }\n\n return new BoundingSphere().fromCornerPoints([minX, minY, minZ], [maxX, maxY, maxZ]);\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PointCloudTileContent, PointCloudTileHeader} from './types';\n\n/**\n * Runtime tile state for PointCloudTileset traversal and loading.\n */\nexport class PointCloudTile {\n header: PointCloudTileHeader;\n parent: PointCloudTile | null;\n children: PointCloudTile[] = [];\n childrenLoaded = false;\n childrenPromise: Promise<PointCloudTile[]> | null = null;\n selected = false;\n viewportIds: string[] = [];\n content: PointCloudTileContent | null = null;\n contentAvailable = false;\n contentFailed = false;\n isContentLoading = false;\n\n constructor(header: PointCloudTileHeader, parent: PointCloudTile | null = null) {\n this.header = header;\n this.parent = parent;\n }\n\n /**\n * Tile identifier.\n */\n get id(): string {\n return this.header.id;\n }\n\n /**\n * Tile depth level.\n */\n get level(): number {\n return this.header.level;\n }\n\n /**\n * Tile point count.\n */\n get pointCount(): number {\n return this.header.pointCount;\n }\n\n /**\n * Tile geometric error.\n */\n get geometricError(): number {\n return this.header.geometricError;\n }\n\n /**\n * Tile bounds.\n */\n get boundingVolume() {\n return this.header.boundingVolume;\n }\n\n /**\n * Update the selected state for a traversal cycle.\n */\n setSelected(viewportId: string): void {\n this.selected = true;\n if (!this.viewportIds.includes(viewportId)) {\n this.viewportIds.push(viewportId);\n }\n }\n\n /**\n * Clear transient selection state.\n */\n clearSelection(): void {\n this.selected = false;\n this.viewportIds = [];\n }\n}\n", "// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CoreAPI, SourceLoader} from '@loaders.gl/loader-utils';\nimport type {PointCloudTileSource} from './point-cloud-tile-source';\nimport type {\n PointCloudTileSourceInput,\n PointCloudTileSourceOptions\n} from './point-cloud-tile-source-types';\n\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n\n/** Loads the optional authoring runtime through an explicit package subpath. */\nasync function preloadPointCloudTileSource(): Promise<\n typeof import('./point-cloud-tile-source-loader').PointCloudTileSourceLoaderWithParser\n> {\n const {PointCloudTileSourceLoaderWithParser} = await import(\n '@loaders.gl/tiles/point-cloud-tile-source-loader'\n );\n return PointCloudTileSourceLoaderWithParser;\n}\n\n/** Metadata-only loader for creating an additive point source from decoded Mesh/Arrow input. */\nexport const PointCloudTileSourceLoader = {\n dataType: null as unknown as PointCloudTileSource,\n batchType: null as never,\n name: 'PointCloudTiler',\n id: 'point-cloud-tiler',\n module: 'tiles',\n version: VERSION,\n extensions: [],\n mimeTypes: [],\n type: 'point-cloud',\n fromUrl: false,\n fromBlob: false,\n testURL: () => false,\n options: {pointCloudTiler: {}},\n defaultOptions: {pointCloudTiler: {}},\n preload: preloadPointCloudTileSource,\n /** Direct construction requires the runtime rather than this metadata export. */\n createDataSource(\n _input: PointCloudTileSourceInput | string | Blob,\n _options: PointCloudTileSourceOptions = {},\n _coreApi?: CoreAPI\n ): PointCloudTileSource {\n throw new Error(\n 'PointCloudTileSourceLoader requires preload() or @loaders.gl/tiles/point-cloud-tile-source-loader'\n );\n }\n} as const satisfies SourceLoader<PointCloudTileSource>;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,IAAAA,eAA+B;AAC/B,IAAAC,qBAAwB;;;ACaV,SAAP,oBAAkC;AACvC,MAAI;AAEJ,MAAI,OAAO,WAAW,eAAe,OAAO,aAAa;AACvD,gBAAY,OAAO,YAAY,IAAG;EACpC,WAAW,OAAO,YAAY,eAAe,QAAQ,QAAQ;AAC3D,UAAM,YAAY,QAAQ,OAAM;AAChC,gBAAY,UAAU,CAAC,IAAI,MAAO,UAAU,CAAC,IAAI;EACnD,OAAO;AACL,gBAAY,KAAK,IAAG;EACtB;AAEA,SAAO;AACT;;;AC/BA,IAAqB,OAArB,MAAyB;EAiBvB,YAAY,MAAc,MAAa;AAdvC,SAAA,aAAqB;AACrB,SAAA,OAAe;AACf,SAAA,QAAgB;AAChB,SAAA,UAAkB;AAClB,SAAA,aAAqB;AACrB,SAAA,iBAAyB;AACzB,SAAA,kBAA0B;AAE1B,SAAA,SAAiB;AACjB,SAAA,QAAgB;AAChB,SAAA,WAAmB;AACnB,SAAA,aAAqB;AACrB,SAAA,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,SAAS,EAAC,iBAAiB,CAAA,EAAE;EAC7B,gBAAgB,EAAC,iBAAiB,CAAA,EAAE;EACpC,SAAS;;EAET,iBACE,QACA,WAAwC,CAAA,GACxC,UAAkB;AAElB,UAAM,IAAI,MACR,mGAAmG;EAEvG;;",
6
- "names": ["import_core", "import_geospatial", "import_loader_utils", "import_core", "import_geospatial", "cameraPositionCartesian", "import_core", "scratchPosition", "import_core", "import_culling", "TILE_REFINEMENT", "TILE_TYPE", "TILESET_TYPE", "LOD_METRIC_TYPE", "import_crs", "import_loader_utils", "import_core", "import_culling", "import_core", "import_culling", "import_geospatial", "import_loader_utils", "import_core", "import_geospatial", "import_loader_utils", "DEFAULT_PROPS", "scratchVector", "cullingVolume", "defined", "import_loader_utils", "import_geospatial", "import_core", "import_core", "import_culling", "import_geospatial", "scratchVector", "import_core", "import_geospatial", "import_core", "import_s2", "import_geospatial", "contentUrl", "import_loader_utils", "import_geospatial", "import_core", "id", "import_core", "import_geospatial", "center", "EMPTY_CONTENT_FORMATS", "isTilesetRequest", "header", "throwIfTraversalAborted", "path", "tileData", "error", "loaderId", "import_loader_utils", "import_loader_utils", "isAbortError", "import_core", "import_culling", "DEFAULT_PROPS", "cullingVolume", "normalizeLongitude"]
3
+ "sources": ["../../core/src/loader-utils/lib/env-utils/assert.ts", "../../core/src/loader-utils/lib/request-utils/request-scheduler.ts", "../../core/src/loader-utils/lib/request-utils/abort-utils.ts", "../../core/src/loader-utils/index.ts", "../src/index.ts", "../src/tileset-2d/tile-2d-header.ts", "../src/tileset-2d/tileset-2d.ts", "../src/image-set.ts", "../src/raster-set.ts", "../../tiles-3d/src/tileset-3d/common/tileset-3d.ts", "../../tiles-3d/src/utils/doubly-linked-list-node.ts", "../../tiles-3d/src/utils/doubly-linked-list.ts", "../../tiles-3d/src/tileset-3d/common/tileset-cache.ts", "../../tiles-3d/src/tileset-3d/helpers/transform-utils.ts", "../../tiles-3d/src/tileset-3d/helpers/frame-state.ts", "../../tiles-3d/src/tileset-3d/helpers/tiles-3d-lod.ts", "../../tiles-3d/src/tileset-3d/helpers/tiles-3d-request-priority.ts", "../../tiles-3d/src/constants.ts", "../../tiles-3d/src/spatial/spatial-types.ts", "../../tiles-3d/src/spatial/get-spatial-coordinate-frame.ts", "../../tiles-3d/src/spatial/normalize-crs-identifier.ts", "../../tiles-3d/src/tileset-3d/common/tileset-source.ts", "../src/tile-matrix.ts"],
4
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,SAAS,OAAO,WAAgB,SAAwB;AAC7D,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,WAAW,0BAA0B;AAAA,EACvD;AACF;AAZA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAIA,cAkBM,sBACA,sBACA,yBACA,2BACA,2BAEA,eAyBe;AArDrB;AAAA;AAAA;AAIA,mBAAoB;AAkBpB,IAAM,uBAAuB;AAC7B,IAAM,uBAAuB;AAC7B,IAAM,0BAA0B;AAChC,IAAM,4BAA4B;AAClC,IAAM,4BAA4B;AAElC,IAAM,gBAAiD;AAAA,MACrD,IAAI;AAAA;AAAA,MAEJ,kBAAkB;AAAA;AAAA,MAElB,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,MAKb,cAAc;AAAA,IAChB;AAcA,IAAqB,mBAArB,MAAsC;AAAA,MAC3B;AAAA,MACA;AAAA,MACT,qBAA6B;AAAA;AAAA,MAGrB,eAA0B,CAAC;AAAA,MAC3B,aAAkD,oBAAI,IAAI;AAAA;AAAA,MAE1D,cAAoD;AAAA,MAE5D,YAAY,QAA+B,CAAC,GAAG;AAC7C,aAAK,QAAQ,EAAC,GAAG,eAAe,GAAG,MAAK;AAGxC,aAAK,QAAQ,IAAI,mBAAM,EAAC,IAAI,KAAK,MAAM,GAAE,CAAC;AAC1C,aAAK,MAAM,IAAI,oBAAoB;AACnC,aAAK,MAAM,IAAI,oBAAoB;AACnC,aAAK,MAAM,IAAI,uBAAuB;AACtC,aAAK,MAAM,IAAI,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,UAAU;AAC9E,YAAM,CAAC,MAAM,QAAQ,OAAO,GAAG,QAAI,kCAAc,gBAAgB,QAAQ,GAAG;AAC5E,YAAM,KAAK;QACT,OAAO,EAAC,GAAG,QAAQ,GAAG,KAAK,GAAG,YAAW;QACzC,YAAY,eAAe;QAC3B,IAAI,KAAK,UAAU,CAAC,UAAU,KAAK,eAAe,IAAI,QAAQ,GAAG,CAAC;QAClE,MAAM,EAAC,MAAM,QAAQ,OAAO,IAAG;QAC/B,KAAK,UAAU;QACf,UAAU,CAAC,eAAe,SAAS,CAAC,GAAG,eAAe,SAAS,CAAC,CAAC;OACjB;IACpD;EACF;AACA,SAAO;AACT;",
5
+ "names": ["tileData", "error", "loaderId", "import_stats", "_a", "isAbortError", "import_core", "import_geospatial", "import_stats", "import_core", "import_geospatial", "import_core", "scratchPosition", "scratchPosition", "import_core", "import_culling", "TILE_TYPE", "TILESET_TYPE", "LOD_METRIC_TYPE", "import_crs", "DEFAULT_PROPS"]
7
6
  }