@loaders.gl/tiles 4.4.2 → 5.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +110 -1
  2. package/dist/dist.dev.js +4359 -1950
  3. package/dist/dist.min.js +1 -1
  4. package/dist/image-set.d.ts +94 -0
  5. package/dist/image-set.d.ts.map +1 -0
  6. package/dist/image-set.js +243 -0
  7. package/dist/image-set.js.map +1 -0
  8. package/dist/index.cjs +4178 -1892
  9. package/dist/index.cjs.map +4 -4
  10. package/dist/index.d.ts +27 -9
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +17 -8
  13. package/dist/index.js.map +1 -1
  14. package/dist/point-cloud/point-cloud-tile.d.ts +47 -0
  15. package/dist/point-cloud/point-cloud-tile.d.ts.map +1 -0
  16. package/dist/point-cloud/point-cloud-tile.js +67 -0
  17. package/dist/point-cloud/point-cloud-tile.js.map +1 -0
  18. package/dist/point-cloud/point-cloud-tileset.d.ts +131 -0
  19. package/dist/point-cloud/point-cloud-tileset.d.ts.map +1 -0
  20. package/dist/point-cloud/point-cloud-tileset.js +507 -0
  21. package/dist/point-cloud/point-cloud-tileset.js.map +1 -0
  22. package/dist/point-cloud/types.d.ts +64 -0
  23. package/dist/point-cloud/types.d.ts.map +1 -0
  24. package/dist/point-cloud/types.js +2 -0
  25. package/dist/point-cloud/types.js.map +1 -0
  26. package/dist/raster-set.d.ts +107 -0
  27. package/dist/raster-set.d.ts.map +1 -0
  28. package/dist/raster-set.js +268 -0
  29. package/dist/raster-set.js.map +1 -0
  30. package/dist/tileset-2d/adapter.d.ts +38 -0
  31. package/dist/tileset-2d/adapter.d.ts.map +1 -0
  32. package/dist/tileset-2d/adapter.js +5 -0
  33. package/dist/tileset-2d/adapter.js.map +1 -0
  34. package/dist/tileset-2d/index.d.ts +7 -0
  35. package/dist/tileset-2d/index.d.ts.map +1 -0
  36. package/dist/tileset-2d/index.js +6 -0
  37. package/dist/tileset-2d/index.js.map +1 -0
  38. package/dist/tileset-2d/tile-2d-header.d.ts +68 -0
  39. package/dist/tileset-2d/tile-2d-header.d.ts.map +1 -0
  40. package/dist/tileset-2d/tile-2d-header.js +181 -0
  41. package/dist/tileset-2d/tile-2d-header.js.map +1 -0
  42. package/dist/tileset-2d/tileset-2d.d.ts +201 -0
  43. package/dist/tileset-2d/tileset-2d.d.ts.map +1 -0
  44. package/dist/tileset-2d/tileset-2d.js +532 -0
  45. package/dist/tileset-2d/tileset-2d.js.map +1 -0
  46. package/dist/tileset-2d/types.d.ts +44 -0
  47. package/dist/tileset-2d/types.d.ts.map +1 -0
  48. package/dist/tileset-2d/types.js +5 -0
  49. package/dist/tileset-2d/types.js.map +1 -0
  50. package/dist/tileset-2d.d.ts +2 -0
  51. package/dist/tileset-2d.d.ts.map +1 -0
  52. package/dist/tileset-2d.js +5 -0
  53. package/dist/tileset-2d.js.map +1 -0
  54. package/dist/tileset-3d/common/indexed-archive-tileset-source.d.ts +60 -0
  55. package/dist/tileset-3d/common/indexed-archive-tileset-source.d.ts.map +1 -0
  56. package/dist/tileset-3d/common/indexed-archive-tileset-source.js +125 -0
  57. package/dist/tileset-3d/common/indexed-archive-tileset-source.js.map +1 -0
  58. package/dist/{tileset → tileset-3d/common}/tile-3d.d.ts +36 -27
  59. package/dist/tileset-3d/common/tile-3d.d.ts.map +1 -0
  60. package/dist/{tileset → tileset-3d/common}/tile-3d.js +53 -62
  61. package/dist/tileset-3d/common/tile-3d.js.map +1 -0
  62. package/dist/tileset-3d/common/tileset-3d.d.ts +177 -0
  63. package/dist/tileset-3d/common/tileset-3d.d.ts.map +1 -0
  64. package/dist/tileset-3d/common/tileset-3d.js +566 -0
  65. package/dist/tileset-3d/common/tileset-3d.js.map +1 -0
  66. package/dist/tileset-3d/common/tileset-cache.d.ts.map +1 -0
  67. package/dist/{tileset → tileset-3d/common}/tileset-cache.js +1 -1
  68. package/dist/tileset-3d/common/tileset-cache.js.map +1 -0
  69. package/dist/tileset-3d/common/tileset-source.d.ts +186 -0
  70. package/dist/tileset-3d/common/tileset-source.d.ts.map +1 -0
  71. package/dist/tileset-3d/common/tileset-source.js +17 -0
  72. package/dist/tileset-3d/common/tileset-source.js.map +1 -0
  73. package/dist/{tileset → tileset-3d/common}/tileset-traverser.d.ts +2 -2
  74. package/dist/tileset-3d/common/tileset-traverser.d.ts.map +1 -0
  75. package/dist/{tileset → tileset-3d/common}/tileset-traverser.js +2 -2
  76. package/dist/tileset-3d/common/tileset-traverser.js.map +1 -0
  77. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.d.ts +100 -0
  78. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.d.ts.map +1 -0
  79. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.js +312 -0
  80. package/dist/tileset-3d/format-3d-tiles/tiles-3d-source.js.map +1 -0
  81. package/dist/{tileset → tileset-3d}/format-3d-tiles/tileset-3d-traverser.d.ts +1 -1
  82. package/dist/tileset-3d/format-3d-tiles/tileset-3d-traverser.d.ts.map +1 -0
  83. package/dist/{tileset → tileset-3d}/format-3d-tiles/tileset-3d-traverser.js +1 -1
  84. package/dist/tileset-3d/format-3d-tiles/tileset-3d-traverser.js.map +1 -0
  85. package/dist/tileset-3d/format-i3s/i3s-pending-tiles-register.d.ts.map +1 -0
  86. package/dist/tileset-3d/format-i3s/i3s-pending-tiles-register.js.map +1 -0
  87. package/dist/tileset-3d/format-i3s/i3s-source.d.ts +99 -0
  88. package/dist/tileset-3d/format-i3s/i3s-source.d.ts.map +1 -0
  89. package/dist/tileset-3d/format-i3s/i3s-source.js +299 -0
  90. package/dist/tileset-3d/format-i3s/i3s-source.js.map +1 -0
  91. package/dist/tileset-3d/format-i3s/i3s-tile-manager.d.ts.map +1 -0
  92. package/dist/{tileset → tileset-3d}/format-i3s/i3s-tile-manager.js +2 -2
  93. package/dist/tileset-3d/format-i3s/i3s-tile-manager.js.map +1 -0
  94. package/dist/{tileset → tileset-3d}/format-i3s/i3s-tileset-traverser.d.ts +2 -2
  95. package/dist/tileset-3d/format-i3s/i3s-tileset-traverser.d.ts.map +1 -0
  96. package/dist/{tileset → tileset-3d}/format-i3s/i3s-tileset-traverser.js +14 -23
  97. package/dist/tileset-3d/format-i3s/i3s-tileset-traverser.js.map +1 -0
  98. package/dist/{tileset → tileset-3d}/helpers/3d-tiles-options.d.ts +1 -1
  99. package/dist/tileset-3d/helpers/3d-tiles-options.d.ts.map +1 -0
  100. package/dist/tileset-3d/helpers/3d-tiles-options.js.map +1 -0
  101. package/dist/tileset-3d/helpers/bounding-volume.d.ts.map +1 -0
  102. package/dist/tileset-3d/helpers/bounding-volume.js.map +1 -0
  103. package/dist/{tileset → tileset-3d}/helpers/frame-state.d.ts +1 -1
  104. package/dist/tileset-3d/helpers/frame-state.d.ts.map +1 -0
  105. package/dist/tileset-3d/helpers/frame-state.js.map +1 -0
  106. package/dist/{tileset → tileset-3d}/helpers/i3s-lod.d.ts +1 -1
  107. package/dist/tileset-3d/helpers/i3s-lod.d.ts.map +1 -0
  108. package/dist/{tileset → tileset-3d}/helpers/i3s-lod.js +1 -1
  109. package/dist/tileset-3d/helpers/i3s-lod.js.map +1 -0
  110. package/dist/tileset-3d/helpers/tiles-3d-lod.d.ts +20 -0
  111. package/dist/tileset-3d/helpers/tiles-3d-lod.d.ts.map +1 -0
  112. package/dist/{tileset → tileset-3d}/helpers/tiles-3d-lod.js +43 -4
  113. package/dist/tileset-3d/helpers/tiles-3d-lod.js.map +1 -0
  114. package/dist/{tileset → tileset-3d}/helpers/transform-utils.d.ts +1 -1
  115. package/dist/tileset-3d/helpers/transform-utils.d.ts.map +1 -0
  116. package/dist/tileset-3d/helpers/transform-utils.js.map +1 -0
  117. package/dist/tileset-3d/helpers/zoom.d.ts.map +1 -0
  118. package/dist/tileset-3d/helpers/zoom.js.map +1 -0
  119. package/dist/types.d.ts +7 -0
  120. package/dist/types.d.ts.map +1 -1
  121. package/package.json +7 -6
  122. package/src/image-set.ts +328 -0
  123. package/src/index.ts +80 -9
  124. package/src/point-cloud/point-cloud-tile.ts +76 -0
  125. package/src/point-cloud/point-cloud-tileset.ts +709 -0
  126. package/src/point-cloud/types.ts +78 -0
  127. package/src/raster-set.ts +374 -0
  128. package/src/tileset-2d/adapter.ts +47 -0
  129. package/src/tileset-2d/index.ts +33 -0
  130. package/src/tileset-2d/tile-2d-header.ts +224 -0
  131. package/src/tileset-2d/tileset-2d.ts +716 -0
  132. package/src/tileset-2d/types.ts +39 -0
  133. package/src/tileset-2d.ts +5 -0
  134. package/src/tileset-3d/common/indexed-archive-tileset-source.ts +205 -0
  135. package/src/{tileset → tileset-3d/common}/tile-3d.ts +64 -73
  136. package/src/tileset-3d/common/tileset-3d.ts +736 -0
  137. package/src/{tileset → tileset-3d/common}/tileset-cache.ts +1 -1
  138. package/src/tileset-3d/common/tileset-source.ts +234 -0
  139. package/src/{tileset → tileset-3d/common}/tileset-traverser.ts +3 -3
  140. package/src/tileset-3d/format-3d-tiles/tiles-3d-source.ts +379 -0
  141. package/src/{tileset → tileset-3d}/format-3d-tiles/tileset-3d-traverser.ts +1 -1
  142. package/src/tileset-3d/format-i3s/i3s-source.ts +366 -0
  143. package/src/{tileset → tileset-3d}/format-i3s/i3s-tile-manager.ts +2 -2
  144. package/src/{tileset → tileset-3d}/format-i3s/i3s-tileset-traverser.ts +15 -24
  145. package/src/{tileset → tileset-3d}/helpers/3d-tiles-options.ts +1 -1
  146. package/src/{tileset → tileset-3d}/helpers/frame-state.ts +1 -1
  147. package/src/{tileset → tileset-3d}/helpers/i3s-lod.ts +2 -2
  148. package/src/{tileset → tileset-3d}/helpers/tiles-3d-lod.ts +46 -4
  149. package/src/{tileset → tileset-3d}/helpers/transform-utils.ts +1 -1
  150. package/src/types.ts +7 -0
  151. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.d.ts.map +0 -1
  152. package/dist/tileset/format-3d-tiles/tileset-3d-traverser.js.map +0 -1
  153. package/dist/tileset/format-i3s/i3s-pending-tiles-register.d.ts.map +0 -1
  154. package/dist/tileset/format-i3s/i3s-pending-tiles-register.js.map +0 -1
  155. package/dist/tileset/format-i3s/i3s-tile-manager.d.ts.map +0 -1
  156. package/dist/tileset/format-i3s/i3s-tile-manager.js.map +0 -1
  157. package/dist/tileset/format-i3s/i3s-tileset-traverser.d.ts.map +0 -1
  158. package/dist/tileset/format-i3s/i3s-tileset-traverser.js.map +0 -1
  159. package/dist/tileset/helpers/3d-tiles-options.d.ts.map +0 -1
  160. package/dist/tileset/helpers/3d-tiles-options.js.map +0 -1
  161. package/dist/tileset/helpers/bounding-volume.d.ts.map +0 -1
  162. package/dist/tileset/helpers/bounding-volume.js.map +0 -1
  163. package/dist/tileset/helpers/frame-state.d.ts.map +0 -1
  164. package/dist/tileset/helpers/frame-state.js.map +0 -1
  165. package/dist/tileset/helpers/i3s-lod.d.ts.map +0 -1
  166. package/dist/tileset/helpers/i3s-lod.js.map +0 -1
  167. package/dist/tileset/helpers/tiles-3d-lod.d.ts +0 -8
  168. package/dist/tileset/helpers/tiles-3d-lod.d.ts.map +0 -1
  169. package/dist/tileset/helpers/tiles-3d-lod.js.map +0 -1
  170. package/dist/tileset/helpers/transform-utils.d.ts.map +0 -1
  171. package/dist/tileset/helpers/transform-utils.js.map +0 -1
  172. package/dist/tileset/helpers/zoom.d.ts.map +0 -1
  173. package/dist/tileset/helpers/zoom.js.map +0 -1
  174. package/dist/tileset/tile-3d.d.ts.map +0 -1
  175. package/dist/tileset/tile-3d.js.map +0 -1
  176. package/dist/tileset/tileset-3d.d.ts +0 -284
  177. package/dist/tileset/tileset-3d.d.ts.map +0 -1
  178. package/dist/tileset/tileset-3d.js +0 -814
  179. package/dist/tileset/tileset-3d.js.map +0 -1
  180. package/dist/tileset/tileset-cache.d.ts.map +0 -1
  181. package/dist/tileset/tileset-cache.js.map +0 -1
  182. package/dist/tileset/tileset-traverser.d.ts.map +0 -1
  183. package/dist/tileset/tileset-traverser.js.map +0 -1
  184. package/src/tileset/tileset-3d.ts +0 -1037
  185. /package/dist/{tileset → tileset-3d/common}/tileset-cache.d.ts +0 -0
  186. /package/dist/{tileset → tileset-3d}/format-i3s/i3s-pending-tiles-register.d.ts +0 -0
  187. /package/dist/{tileset → tileset-3d}/format-i3s/i3s-pending-tiles-register.js +0 -0
  188. /package/dist/{tileset → tileset-3d}/format-i3s/i3s-tile-manager.d.ts +0 -0
  189. /package/dist/{tileset → tileset-3d}/helpers/3d-tiles-options.js +0 -0
  190. /package/dist/{tileset → tileset-3d}/helpers/bounding-volume.d.ts +0 -0
  191. /package/dist/{tileset → tileset-3d}/helpers/bounding-volume.js +0 -0
  192. /package/dist/{tileset → tileset-3d}/helpers/frame-state.js +0 -0
  193. /package/dist/{tileset → tileset-3d}/helpers/transform-utils.js +0 -0
  194. /package/dist/{tileset → tileset-3d}/helpers/zoom.d.ts +0 -0
  195. /package/dist/{tileset → tileset-3d}/helpers/zoom.js +0 -0
  196. /package/src/{tileset → tileset-3d}/format-i3s/i3s-pending-tiles-register.ts +0 -0
  197. /package/src/{tileset → tileset-3d}/helpers/bounding-volume.ts +0 -0
  198. /package/src/{tileset → tileset-3d}/helpers/zoom.ts +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/tileset/tileset-3d.ts", "../src/utils/doubly-linked-list-node.ts", "../src/utils/doubly-linked-list.ts", "../src/tileset/tileset-cache.ts", "../src/tileset/helpers/transform-utils.ts", "../src/tileset/helpers/frame-state.ts", "../src/tileset/helpers/zoom.ts", "../src/tileset/tile-3d.ts", "../src/constants.ts", "../src/tileset/helpers/bounding-volume.ts", "../src/tileset/helpers/tiles-3d-lod.ts", "../src/tileset/helpers/i3s-lod.ts", "../src/tileset/helpers/3d-tiles-options.ts", "../src/utils/managed-array.ts", "../src/tileset/tileset-traverser.ts", "../src/tileset/format-3d-tiles/tileset-3d-traverser.ts", "../src/tileset/format-i3s/i3s-tileset-traverser.ts", "../src/tileset/format-i3s/i3s-pending-tiles-register.ts", "../src/tileset/format-i3s/i3s-tile-manager.ts"],
4
- "sourcesContent": ["// loaders.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {Tileset3DProps} from './tileset/tileset-3d';\nexport {Tileset3D} from './tileset/tileset-3d';\nexport {Tile3D} from './tileset/tile-3d';\n\nexport {TilesetTraverser} from './tileset/tileset-traverser';\nexport {TilesetCache} from './tileset/tileset-cache';\n\nexport {createBoundingVolume} from './tileset/helpers/bounding-volume';\nexport {calculateTransformProps} from './tileset/helpers/transform-utils';\n\nexport {getFrameState} from './tileset/helpers/frame-state';\nexport {getLodStatus} from './tileset/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", "// 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, path, LoaderWithParser, LoaderOptions} from '@loaders.gl/loader-utils';\nimport {TilesetCache} from './tileset-cache';\nimport {calculateTransformProps} from './helpers/transform-utils';\nimport {FrameState, getFrameState, limitSelectedTiles} from './helpers/frame-state';\nimport {getZoomFromBoundingVolume, getZoomFromExtent, getZoomFromFullExtent} from './helpers/zoom';\n\nimport type {GeospatialViewport, Viewport} from '../types';\nimport {Tile3D} from './tile-3d';\nimport {TILESET_TYPE} from '../constants';\n\nimport {TilesetTraverser} from './tileset-traverser';\n\n// TODO - these should be moved into their respective modules\nimport {Tileset3DTraverser} from './format-3d-tiles/tileset-3d-traverser';\nimport {I3STilesetTraverser} from './format-i3s/i3s-tileset-traverser';\n\nexport type TilesetJSON = any;\n\n/*\nexport type TilesetJSON = {\n loader;\n // could be 3d tiles, i3s\n type: 'I3S' | '3DTILES';\n /** The url to the top level tileset JSON file. *\n url: string;\n basePath?: string;\n // Geometric error when the tree is not rendered at all\n lodMetricType: string;\n lodMetricValue: number;\n root: {\n refine: string;\n [key: string]: unknown;\n },\n [key: string]: unknown;\n};\n*/\n\nexport type Tileset3DProps = {\n // loading\n throttleRequests?: boolean;\n maxRequests?: number;\n loadOptions?: LoaderOptions;\n loadTiles?: boolean;\n basePath?: string;\n maximumMemoryUsage?: number;\n memoryCacheOverflow?: number;\n maximumTilesSelected?: number;\n debounceTime?: number;\n\n // Metadata\n description?: string;\n attributions?: string[];\n\n // Transforms\n ellipsoid?: object;\n modelMatrix?: Matrix4;\n\n // Traversal\n maximumScreenSpaceError?: number;\n memoryAdjustedScreenSpaceError?: boolean;\n viewportTraversersMap?: any;\n updateTransforms?: boolean;\n viewDistanceScale?: number;\n\n // Callbacks\n onTileLoad?: (tile: Tile3D) => any;\n onTileUnload?: (tile: Tile3D) => any;\n onTileError?: (tile: Tile3D, message: string, url: string) => 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 /** A 4x4 transformation matrix this transforms the entire tileset. */\n modelMatrix: Matrix4;\n /** Set to false to disable network request throttling */\n throttleRequests: boolean;\n /** Number of simultaneous requsts, if throttleRequests is true */\n maxRequests: number;\n /* Maximum amount of GPU memory (in MB) that may be used to cache tiles. */\n maximumMemoryUsage: number;\n /* The maximum additional memory (in MB) to allow for cache headroom before adjusting the screen spacer error */\n memoryCacheOverflow: number;\n /** Maximum number limit of tiles selected for show. 0 means no limit */\n maximumTilesSelected: number;\n /** Delay time before the tileset traversal. It prevents traversal requests spam.*/\n debounceTime: number;\n /** Callback. Indicates this a tile's content was loaded */\n onTileLoad: (tile: Tile3D) => void;\n /** Callback. Indicates this a tile's content was unloaded (cache full) */\n onTileUnload: (tile: Tile3D) => void;\n /** Callback. Indicates this a tile's content failed to load */\n onTileError: (tile: Tile3D, message: string, url: string) => void;\n /** Callback. Allows post-process selectedTiles right after traversal. */\n onTraversalComplete: (selectedTiles: Tile3D[]) => Tile3D[];\n /** Callback. Called when the set of selected tiles changes. */\n onUpdate: () => void;\n /** The maximum screen space error used to drive level of detail refinement. */\n maximumScreenSpaceError: number;\n /** Whether to adjust the maximum screen space error to comply with the maximum memory limitation */\n memoryAdjustedScreenSpaceError: boolean;\n viewportTraversersMap: Record<string, any> | null;\n attributions: string[];\n loadTiles: boolean;\n loadOptions: LoaderOptions;\n updateTransforms: boolean;\n /** View distance scale modifier */\n viewDistanceScale: number;\n basePath: string;\n /** Optional async tile content loader */\n contentLoader?: (tile: Tile3D) => Promise<void>;\n /** @todo I3S specific knowledge should be moved to I3S module */\n i3s: Record<string, any>;\n};\n\nconst DEFAULT_PROPS: Props = {\n description: '',\n ellipsoid: Ellipsoid.WGS84,\n modelMatrix: new Matrix4(),\n throttleRequests: true,\n maxRequests: 64,\n /** Default memory values optimized for viewing mesh-based 3D Tiles on both mobile and desktop devices */\n maximumMemoryUsage: 32,\n memoryCacheOverflow: 1,\n maximumTilesSelected: 0,\n debounceTime: 0,\n onTileLoad: () => {},\n onTileUnload: () => {},\n onTileError: () => {},\n onTraversalComplete: (selectedTiles: Tile3D[]) => selectedTiles,\n onUpdate: () => {},\n contentLoader: undefined,\n viewDistanceScale: 1.0,\n maximumScreenSpaceError: 8,\n memoryAdjustedScreenSpaceError: false,\n loadTiles: true,\n updateTransforms: true,\n viewportTraversersMap: null,\n loadOptions: {fetch: {}},\n attributions: [],\n basePath: '',\n i3s: {}\n};\n\n// Tracked Stats\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 * The Tileset loading and rendering flow is as below,\n * A rendered (i.e. deck.gl `Tile3DLayer`) triggers `tileset.update()` after a `tileset` is loaded\n * `tileset` starts traversing the tile tree and update `requestTiles` (tiles of which content need\n * to be fetched) and `selectedTiles` (tiles ready for rendering under the current viewport).\n * `Tile3DLayer` will update rendering based on `selectedTiles`.\n * `Tile3DLayer` also listens to `onTileLoad` callback and trigger another round of `update and then traversal`\n * when new tiles are loaded.\n\n * As I3S tileset have stored `tileHeader` file (metadata) and tile content files (geometry, texture, ...) separately.\n * During each traversal, it issues `tilHeader` requests if that `tileHeader` is not yet fetched,\n * after the tile header is fulfilled, it will resume the traversal starting from the tile just fetched (not root).\n\n * Tile3DLayer\n * |\n * await load(tileset)\n * |\n * tileset.update()\n * | async load tileHeader\n * tileset.traverse() -------------------------- Queued\n * | resume traversal after fetched |\n * |----------------------------------------|\n * |\n * | async load tile content\n * tilset.requestedTiles ----------------------------- RequestScheduler\n * |\n * tilset.selectedTiles (ready for rendering) |\n * | Listen to |\n * Tile3DLayer ----------- onTileLoad ----------------------|\n * | | notify new tile is available\n * updateLayers |\n * tileset.update // trigger another round of update\n*/\nexport class Tileset3D {\n // props: Tileset3DProps;\n options: Props;\n loadOptions: LoaderOptions;\n\n type: TILESET_TYPE;\n tileset: TilesetJSON;\n loader: LoaderWithParser;\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 /** @todo any->unknown */\n asset: Record<string, any> = {};\n\n // Metadata for the entire tileset\n description: string = '';\n properties: any;\n\n extras: any = null;\n attributions: any = {};\n credits: any = {};\n\n stats: Stats;\n\n /** flags that contain information about data types in nested tiles */\n contentFormats = {draco: false, meshopt: false, dds: false, ktx2: false};\n\n // view props\n cartographicCenter: Vector3 | null = null;\n cartesianCenter: Vector3 | null = null;\n zoom: number = 1;\n boundingVolume: any = null;\n\n /** Updated based on the camera position and direction */\n dynamicScreenSpaceErrorComputedDensity: number = 0.0;\n\n // METRICS\n\n /**\n * The maximum amount of GPU memory (in MB) that may be used to cache tiles\n * Tiles not in view are unloaded to enforce private\n */\n maximumMemoryUsage: number = 32;\n\n /** The total amount of GPU memory in bytes used by the tileset. */\n gpuMemoryUsageInBytes: number = 0;\n\n /**\n * If loading the level of detail required by maximumScreenSpaceError\n * results in the memory usage exceeding maximumMemoryUsage (GPU), level of detail refinement\n * will instead use this (larger) adjusted screen space error to achieve the\n * best possible visual quality within the available memory.\n */\n memoryAdjustedScreenSpaceError: number = 0.0;\n\n private _cacheBytes: number = 0;\n private _cacheOverflowBytes: number = 0;\n\n /** Update tracker. increase in each update cycle. */\n _frameNumber: number = 0;\n private _queryParams: Record<string, string> = {};\n private _extensionsUsed: string[] = [];\n private _tiles: Record<string, Tile3D> = {};\n\n /** counter for tracking tiles requests */\n private _pendingCount: number = 0;\n\n /** Hold traversal results */\n selectedTiles: Tile3D[] = [];\n\n // TRAVERSAL\n traverseCounter: number = 0;\n geometricError: number = 0;\n private lastUpdatedVieports: Viewport[] | Viewport | null = null;\n private _requestedTiles: Tile3D[] = [];\n private _emptyTiles: Tile3D[] = [];\n private frameStateData: any = {};\n\n _traverser: TilesetTraverser;\n _cache = new TilesetCache();\n _requestScheduler: RequestScheduler;\n\n /** Tile IDs held visible during transitions until replacements have drawn */\n private _heldTiles: Set<string> = new Set();\n\n // Promise tracking\n private updatePromise: Promise<number> | null = null;\n tilesetInitializationPromise: Promise<void>;\n\n /**\n * Create a new Tileset3D\n * @param json\n * @param props\n */\n // eslint-disable-next-line max-statements\n constructor(tileset: TilesetJSON, options?: Tileset3DProps) {\n // PUBLIC MEMBERS\n this.options = {...DEFAULT_PROPS, ...options};\n // raw data\n this.tileset = tileset;\n this.loader = tileset.loader;\n // could be 3d tiles, i3s\n this.type = tileset.type;\n // The url to a tileset JSON file.\n this.url = tileset.url;\n this.basePath = tileset.basePath || path.dirname(this.url);\n this.modelMatrix = this.options.modelMatrix;\n this.ellipsoid = this.options.ellipsoid;\n\n // Geometric error when the tree is not rendered at all\n this.lodMetricType = tileset.lodMetricType;\n this.lodMetricValue = tileset.lodMetricValue;\n this.refine = tileset.root.refine;\n\n this.loadOptions = this.options.loadOptions || {};\n\n // TRAVERSAL\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 = this.options.maximumMemoryUsage * 1024 * 1024;\n this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;\n\n // METRICS\n // The total amount of GPU memory in bytes used by the tileset.\n this.stats = new Stats({id: this.url});\n this._initializeStats();\n\n this.tilesetInitializationPromise = this._initializeTileSet(tileset);\n }\n\n /** Release resources */\n destroy(): void {\n this._destroy();\n }\n\n /** Is the tileset loaded (update needs to have been called at least once) */\n isLoaded(): boolean {\n // Check that `_frameNumber !== 0` which means that update was called at least once\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 get queryParams(): string {\n return new URLSearchParams(this._queryParams).toString();\n }\n\n setProps(props: Tileset3DProps): void {\n this.options = {...this.options, ...props};\n }\n\n /** @deprecated */\n // setOptions(options: Tileset3DProps): void {\n // this.options = {...this.options, ...options};\n // }\n\n /**\n * Return a loadable tile url for a specific tile subpath\n * @param tilePath a tile subpath\n */\n getTileUrl(tilePath: string): string {\n const isDataUrl = tilePath.startsWith('data:');\n if (isDataUrl) {\n return tilePath;\n }\n\n let tileUrl = tilePath;\n if (this.queryParams.length) {\n tileUrl = `${tilePath}${tilePath.includes('?') ? '&' : '?'}${this.queryParams}`;\n }\n return tileUrl;\n }\n\n // TODO CESIUM specific\n hasExtension(extensionName: string): boolean {\n return Boolean(this._extensionsUsed.indexOf(extensionName) > -1);\n }\n\n /**\n * Update visible tiles relying on a list of viewports\n * @param viewports - list of viewports\n * @deprecated\n */\n update(viewports: Viewport[] | Viewport | null = null) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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 /**\n * Update visible tiles relying on a list of viewports.\n * Do it with debounce delay to prevent update spam\n * @param viewports viewports\n * @returns Promise of new frameNumber\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 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._cacheOverflowBytes) {\n this.memoryAdjustedScreenSpaceError *= 1.02;\n }\n }\n /**\n * Update visible tiles relying on a list of viewports\n * @param viewports viewports\n */\n // eslint-disable-next-line max-statements, complexity\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\n this._cache.reset();\n this._frameNumber++;\n this.traverseCounter = preparedViewports.length;\n const viewportsToTraverse: string[] = [];\n // First loop to decrement traverseCounter\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 // Second loop to traverse\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; // eslint-disable-line no-continue\n }\n const frameState = getFrameState(viewport as GeospatialViewport, this._frameNumber);\n this._traverser.traverse(this.roots[id], frameState, this.options);\n }\n }\n\n /**\n * Check if traversal is needed for particular viewport\n * @param {string} viewportId - id of a viewport\n * @return {boolean}\n */\n _needTraverse(viewportId: string): boolean {\n let traverserId = viewportId;\n if (this.options.viewportTraversersMap) {\n traverserId = this.options.viewportTraversersMap[viewportId];\n }\n if (traverserId !== viewportId) {\n return false;\n }\n\n return true;\n }\n\n /**\n * The callback to post-process tiles after traversal procedure\n * @param frameState - frame state for tile culling\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 /**\n * Update tiles relying on data from all traversers\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 // Transition hold: keep recently-deselected tiles visible until all their\n // replacements have been drawn by the renderer (e.g. deck.gl).\n // Without this, there are single-frame flashes during REPLACE refinement transitions.\n const selectedIds = new Set(this.selectedTiles.map((t) => t.id));\n const hasUndrawnTiles = this.selectedTiles.some((t) => !t.tileDrawn);\n\n // Keep recently-deselected tiles visible while new tiles haven't drawn yet\n let heldBackCount = 0;\n if (hasUndrawnTiles) {\n for (const tileId of selectedIds) {\n this._heldTiles.add(tileId);\n }\n for (const tileId of this._heldTiles) {\n // Skip tiles that are already selected\n if (selectedIds.has(tileId)) continue; // eslint-disable-line no-continue\n\n // Keep tiles previously drawn selected\n const tile = this._tiles[tileId];\n if (tile && tile.contentAvailable) {\n tile._selectedFrame = this._frameNumber;\n this.selectedTiles.push(tile);\n heldBackCount++;\n } else {\n this._heldTiles.delete(tileId);\n }\n }\n } else {\n // Store current selected ids for next frame\n this._heldTiles = selectedIds;\n }\n\n if (heldBackCount > 0) {\n // Schedule another update so that once all replacement tiles\n // have drawn, the held tiles get released\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 _tilesChanged(oldSelectedTiles: Tile3D[], selectedTiles: Tile3D[]): boolean {\n if (oldSelectedTiles.length !== selectedTiles.length) {\n return true;\n }\n const set1 = new Set(oldSelectedTiles.map((t) => t.id));\n const set2 = new Set(selectedTiles.map((t) => t.id));\n let changed = oldSelectedTiles.filter((x) => !set2.has(x.id)).length > 0;\n changed = changed || selectedTiles.filter((x) => !set1.has(x.id)).length > 0;\n return changed;\n }\n\n _loadTiles(): void {\n // Sort requests by priority before making any requests.\n // This makes it less likely this requests will be cancelled after being issued.\n this._requestedTiles.sort((a, b) => a._priority - b._priority);\n for (const tile of this._requestedTiles) {\n if (tile.contentUnloaded) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._loadTile(tile);\n }\n }\n }\n\n _unloadTiles(): void {\n // unload tiles from cache when hit maximumMemoryUsage\n this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));\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 if (tile.content.pointCount) {\n pointsRenderable += tile.content.pointCount;\n } else {\n // Calculate vertices for non point cloud tiles.\n pointsRenderable += tile.content.vertexCount;\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(tilesetJson: TilesetJSON): Promise<void> {\n if (this.type === TILESET_TYPE.I3S) {\n this.calculateViewPropsI3S();\n tilesetJson.root = await tilesetJson.root;\n }\n this.root = this._initializeTileHeaders(tilesetJson, null);\n\n if (this.type === TILESET_TYPE.TILES3D) {\n this._initializeTiles3DTileset(tilesetJson);\n this.calculateViewPropsTiles3D();\n }\n\n if (this.type === TILESET_TYPE.I3S) {\n this._initializeI3STileset();\n }\n }\n\n /**\n * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.\n * These metrics help apps center view on tileset\n * For I3S there is extent (<1.8 version) or fullExtent (>=1.8 version) to calculate view props\n * @returns\n */\n private calculateViewPropsI3S(): void {\n // for I3S 1.8 try to calculate with fullExtent\n const fullExtent = this.tileset.fullExtent;\n if (fullExtent) {\n const {xmin, xmax, ymin, ymax, zmin, zmax} = fullExtent;\n this.cartographicCenter = new Vector3(\n xmin + (xmax - xmin) / 2,\n ymin + (ymax - ymin) / 2,\n zmin + (zmax - zmin) / 2\n );\n this.cartesianCenter = new Vector3();\n Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);\n this.zoom = getZoomFromFullExtent(fullExtent, this.cartographicCenter, this.cartesianCenter);\n return;\n }\n // for I3S 1.6-1.7 try to calculate with extent\n const extent = this.tileset.store?.extent;\n if (extent) {\n const [xmin, ymin, xmax, ymax] = extent;\n this.cartographicCenter = new Vector3(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, 0);\n this.cartesianCenter = new Vector3();\n Ellipsoid.WGS84.cartographicToCartesian(this.cartographicCenter, this.cartesianCenter);\n this.zoom = getZoomFromExtent(extent, this.cartographicCenter, this.cartesianCenter);\n return;\n }\n // eslint-disable-next-line no-console\n console.warn('Extent is not defined in the tileset header');\n this.cartographicCenter = new Vector3();\n this.zoom = 1;\n return;\n }\n\n /**\n * Called during initialize Tileset to initialize the tileset's cartographic center (longitude, latitude) and zoom.\n * These metrics help apps center view on tileset.\n * For 3DTiles the root tile data is used to calculate view props.\n * @returns\n */\n private calculateViewPropsTiles3D() {\n const root = this.root as Tile3D;\n const {center} = root.boundingVolume;\n // TODO - handle all cases\n if (!center) {\n // eslint-disable-next-line no-console\n console.warn('center was not pre-calculated for the root tile');\n this.cartographicCenter = new Vector3();\n this.zoom = 1;\n return;\n }\n\n // cartographic coordinates are undefined at the center of the ellipsoid\n if (center[0] !== 0 || center[1] !== 0 || center[2] !== 0) {\n this.cartographicCenter = new Vector3();\n Ellipsoid.WGS84.cartesianToCartographic(center, this.cartographicCenter);\n } else {\n this.cartographicCenter = new Vector3(0, 0, -Ellipsoid.WGS84.radii[0]);\n }\n this.cartesianCenter = center;\n this.zoom = getZoomFromBoundingVolume(root.boundingVolume, this.cartographicCenter);\n }\n\n _initializeStats() {\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 // Installs the main tileset JSON file or a tileset JSON file referenced from a tile.\n // eslint-disable-next-line max-statements\n _initializeTileHeaders(tilesetJson: TilesetJSON, parentTileHeader?: any) {\n // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.\n // Get the basePath relative to the external tileset.\n const rootTile = new Tile3D(this, tilesetJson.root, parentTileHeader); // resource\n\n // If there is a parentTileHeader, add the root of the currently loading tileset\n // to parentTileHeader's children, and update its depth.\n if (parentTileHeader) {\n parentTileHeader.children.push(rootTile);\n rootTile.depth = parentTileHeader.depth + 1;\n }\n\n // 3DTiles knows the hierarchy beforehand\n if (this.type === TILESET_TYPE.TILES3D) {\n const stack: Tile3D[] = [];\n stack.push(rootTile);\n\n while (stack.length > 0) {\n const tile = stack.pop() as Tile3D;\n this.stats.get(TILES_TOTAL).incrementCount();\n const children = tile.header.children || [];\n for (const childHeader of children) {\n const childTile = new Tile3D(this, childHeader, tile);\n\n // Special handling for Google\n // A session key must be used for all tile requests\n if (childTile.contentUrl?.includes('?session=')) {\n const url = new URL(childTile.contentUrl);\n const session = url.searchParams.get('session');\n // eslint-disable-next-line max-depth\n if (session) {\n this._queryParams.session = session;\n }\n }\n\n tile.children.push(childTile);\n childTile.depth = tile.depth + 1;\n stack.push(childTile);\n }\n }\n }\n\n return rootTile;\n }\n\n _initializeTraverser(): TilesetTraverser {\n let TraverserClass;\n const type = this.type;\n switch (type) {\n case TILESET_TYPE.TILES3D:\n TraverserClass = Tileset3DTraverser;\n break;\n case TILESET_TYPE.I3S:\n TraverserClass = I3STilesetTraverser;\n break;\n default:\n TraverserClass = TilesetTraverser;\n }\n\n return new TraverserClass({\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 loaded;\n try {\n this._onStartTileLoading();\n loaded = await tile.loadContent();\n } catch (error: unknown) {\n this._onTileLoadError(tile, error instanceof Error ? error : new Error('load failed'));\n } finally {\n this._onEndTileLoading();\n this._onTileLoad(tile, loaded);\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 // TODO - Allow for probe log to be injected instead of console?\n console.error(`A 3D tile failed to load: ${tile.url} ${message}`); // eslint-disable-line\n this.options.onTileError(tile, message, url);\n }\n\n _onTileLoad(tile: Tile3D, loaded: boolean): void {\n if (!loaded) {\n return;\n }\n\n if (this.type === TILESET_TYPE.I3S) {\n // We can't calculate tiles total in I3S in advance so we calculate it dynamically.\n const nodesInNodePages = this.tileset?.nodePagesTile?.nodesInNodePages || 0;\n this.stats.get(TILES_TOTAL).reset();\n this.stats.get(TILES_TOTAL).addCount(nodesInNodePages);\n }\n\n // add coordinateOrigin and modelMatrix to tile\n if (tile && tile.content) {\n calculateTransformProps(tile, tile.content);\n }\n\n this.updateContentTypes(tile);\n this._addTileToCache(tile);\n this.options.onTileLoad(tile);\n }\n\n /**\n * Update information about data types in nested tiles\n * @param tile instance of a nested Tile3D\n */\n private updateContentTypes(tile: Tile3D) {\n if (this.type === TILESET_TYPE.I3S) {\n if (tile.header.isDracoGeometry) {\n this.contentFormats.draco = true;\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 } else if (this.type === TILESET_TYPE.TILES3D) {\n const {extensionsRemoved = []} = tile.content?.gltf || {};\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 }\n\n _onStartTileLoading() {\n this._pendingCount++;\n this.stats.get(TILES_LOADING).incrementCount();\n }\n\n _onEndTileLoading() {\n this._pendingCount--;\n this.stats.get(TILES_LOADING).decrementCount();\n }\n\n _addTileToCache(tile: Tile3D) {\n this._cache.add(this, tile, (tileset) => tileset._updateCacheStats(tile));\n }\n\n _updateCacheStats(tile) {\n this.stats.get(TILES_LOADED).incrementCount();\n this.stats.get(TILES_IN_MEMORY).incrementCount();\n\n // TODO: Calculate GPU memory usage statistics for a tile.\n this.gpuMemoryUsageInBytes += tile.gpuMemoryUsageInBytes || 0;\n\n this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;\n\n // Adjust SSE based on cache limits\n if (this.options.memoryAdjustedScreenSpaceError) {\n this.adjustScreenSpaceError();\n }\n }\n\n _unloadTile(tile) {\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 // Traverse the tree and destroy all tiles\n _destroy() {\n const stack: Tile3D[] = [];\n\n if (this.root) {\n stack.push(this.root);\n }\n\n while (stack.length > 0) {\n const tile: Tile3D = 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 // Traverse the tree and destroy all sub tiles\n _destroySubtree(tile) {\n const root = tile;\n const stack: Tile3D[] = [];\n stack.push(root);\n while (stack.length > 0) {\n tile = stack.pop();\n for (const child of tile.children) {\n stack.push(child);\n }\n if (tile !== root) {\n this._destroyTile(tile);\n }\n }\n root.children = [];\n }\n\n _destroyTile(tile) {\n this._cache.unloadTile(this, tile);\n this._unloadTile(tile);\n tile.destroy();\n }\n\n _initializeTiles3DTileset(tilesetJson) {\n if (tilesetJson.queryString) {\n const searchParams = new URLSearchParams(tilesetJson.queryString);\n const queryParams = Object.fromEntries(searchParams.entries());\n this._queryParams = {...this._queryParams, ...queryParams};\n }\n\n this.asset = tilesetJson.asset;\n if (!this.asset) {\n throw new Error('Tileset must have an asset property.');\n }\n if (\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 either 0.0 or 1.0 or 1.1.');\n }\n\n // Note: `asset.tilesetVersion` is version of the tileset itself (not the version of the 3D TILES standard)\n // We add this version as a `v=1.0` query param to fetch the right version and not get an older cached version\n if ('tilesetVersion' in this.asset) {\n this._queryParams.v = this.asset.tilesetVersion;\n }\n\n // TODO - ion resources have a credits property we can use for additional attribution.\n this.credits = {\n attributions: this.options.attributions || []\n };\n this.description = this.options.description || '';\n\n // Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.\n this.properties = tilesetJson.properties;\n this.geometricError = tilesetJson.geometricError;\n this._extensionsUsed = tilesetJson.extensionsUsed || [];\n // Returns the extras property at the top of the tileset JSON (application specific metadata).\n this.extras = tilesetJson.extras;\n }\n\n _initializeI3STileset() {\n const i3sOptions = this.loadOptions.i3s;\n if (i3sOptions && typeof i3sOptions === 'object' && 'token' in i3sOptions) {\n this._queryParams.token = (i3sOptions as Record<string, unknown>).token as string;\n }\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", "// 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 unloadTiles(tileset, unloadCallback): void {\n const trimTiles = this._trimTiles;\n this._trimTiles = false;\n\n const list = this._list;\n\n const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;\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 (\n node !== sentinel &&\n (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)\n ) {\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 '../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", "import {Tile3D} from '@loaders.gl/tiles';\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 position: number[];\n direction: number[];\n up: number[];\n };\n viewport: GeospatialViewport;\n topDownViewport: GeospatialViewport; // Use it to calculate projected radius for a tile\n height: number;\n cullingVolume: CullingVolume;\n frameNumber: number; // TODO: This can be the same between updates, what number is unique for between updates?\n sseDenominator: number; // Assumes fovy = 60 degrees\n};\n\nconst scratchVector = new Vector3();\nconst scratchPosition = new Vector3();\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// Extracts a frame state appropriate for tile culling from a deck.gl viewport\n// TODO - this could likely be generalized and merged back into deck.gl for other culling scenarios\nexport function getFrameState(viewport: GeospatialViewport, frameNumber: number): 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 {cameraDirection, cameraUp, height} = viewport;\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 const cameraDirectionCartesian = new Vector3(\n // @ts-ignore\n enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))\n ).normalize();\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} = viewport;\n // @ts-ignore\n const topDownViewport = new ViewportClass({\n longitude,\n latitude,\n height,\n width,\n bearing,\n zoom,\n pitch: 0\n });\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 },\n viewport,\n topDownViewport,\n height,\n cullingVolume,\n frameNumber, // TODO: This can be the same between updates, what number is unique for between updates?\n sseDenominator: 1.15 // Assumes fovy = 60 degrees\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, number, 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\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\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';\n\nimport {load} from '@loaders.gl/core';\n\n// Note: circular dependency\nimport type {Tileset3D} from './tileset-3d';\nimport type {DoublyLinkedListNode} from '../utils/doubly-linked-list-node';\nimport {TILE_REFINEMENT, TILE_CONTENT_STATE, TILESET_TYPE} from '../constants';\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 {get3dTilesOptions} from './helpers/3d-tiles-options';\nimport {TilesetTraverser} from './tileset-traverser';\n\nconst scratchVector = new Vector3();\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/**\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 /** Different refinement algorithms used by I3S and 3D tiles */\n lodMetricType: 'geometricError' | 'maxScreenThreshold' = 'geometricError';\n /** The error, in meters, introduced if this tile is rendered and its children are not. */\n lodMetricValue: number = 0;\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 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 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 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 private _visibilityPlaneMask: any;\n private _visible: boolean | undefined = undefined;\n\n private _contentBoundingVolume: any;\n private _viewerRequestVolume: any;\n\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\n this._initializeLodMetric(header);\n this._initializeTransforms(header);\n this._initializeBoundingVolumes(header);\n this._initializeContent(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 this.children.length > 0 || (this.header.children && this.header.children.length > 0);\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 bounding box 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(this.header.boundingVolume, this.boundingVolume);\n }\n return this._boundingBox;\n }\n\n /** Get the tile's screen space error. */\n getScreenSpaceError(frameState, useParentLodMetric) {\n switch (this.tileset.type) {\n case TILESET_TYPE.I3S:\n return getProjectedRadius(this, frameState);\n case TILESET_TYPE.TILES3D:\n return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);\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 return this.content.gpuMemoryUsageInBytes || this.content.byteLength || 0;\n }\n\n /*\n * If skipLevelOfDetail is off try to load child tiles as soon as possible so that their parent can refine sooner.\n * Tiles are prioritized by screen space error.\n */\n // eslint-disable-next-line complexity\n _getPriority() {\n const traverser = this.tileset._traverser;\n const {skipLevelOfDetail} = traverser.options;\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 if (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)\n return Math.max(rootScreenSpaceError - screenSpaceError, 0);\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<boolean> {\n if (this.hasEmptyContent) {\n return false;\n }\n\n if (this.content) {\n return 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 false;\n }\n\n try {\n const contentUrl = this.tileset.getTileUrl(this.contentUrl);\n // The content can be a binary tile ot a JSON tileset\n const loader = this.tileset.loader;\n const tilesetLoaderOptions =\n (this.tileset.loadOptions[loader.id] as Record<string, unknown>) || {};\n const options = {\n ...this.tileset.loadOptions,\n [loader.id]: {\n ...tilesetLoaderOptions,\n isTileset: this.type === 'json',\n ...this._getLoaderSpecificOptions(loader.id)\n } // TODO add typecheck - as const satisfies ...\n };\n\n this.content = await load(contentUrl, loader, options);\n\n if (this.tileset.options.contentLoader) {\n await this.tileset.options.contentLoader(this);\n }\n\n if (this._isTileset()) {\n // Add tile headers for the nested tilset's subtree\n // Async update of the tree should be fine since there would never be edits to the same node\n // TODO - we need to capture the child tileset's URL\n this.tileset._initializeTileHeaders(this.content, this);\n }\n\n this.contentState = TILE_CONTENT_STATE.READY;\n this._onContentLoaded();\n return true;\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 // Unloads the tile's content.\n unloadContent() {\n if (this.content && this.content.destroy) {\n this.content.destroy();\n }\n this.content = null;\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._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 // 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 // Assuming the tile's bounding volume intersects the culling volume, determines\n // whether the tile's content's bounding volume intersects the culling volume.\n // @param {FrameState} frameState The frame state.\n // @returns {Intersect} The result of the intersection: the tile's content is completely outside, completely inside, or intersecting the culling volume.\n contentVisibility() {\n return true;\n\n // TODO restore\n /*\n // Assumes the tile's bounding volume intersects the culling volume already, so\n // just return Intersect.INSIDE if there is no content bounding volume.\n if (!defined(this.contentBoundingVolume)) {\n return Intersect.INSIDE;\n }\n\n if (this._visibilityPlaneMask === CullingVolume.MASK_INSIDE) {\n // The tile's bounding volume is completely inside the culling volume so\n // the content bounding volume must also be inside.\n return Intersect.INSIDE;\n }\n\n // PERFORMANCE_IDEA: is it possible to burn less CPU on this test since we know the\n // tile's (not the content's) bounding volume intersects the culling volume?\n const cullingVolume = frameState.cullingVolume;\n const boundingVolume = tile.contentBoundingVolume;\n\n const tileset = this.tileset;\n const clippingPlanes = tileset.clippingPlanes;\n if (defined(clippingPlanes) && clippingPlanes.enabled) {\n const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(\n boundingVolume,\n tileset.clippingPlanesOriginMatrix\n );\n this._isClipped = intersection !== Intersect.INSIDE;\n if (intersection === Intersect.OUTSIDE) {\n return Intersect.OUTSIDE;\n }\n }\n\n return cullingVolume.computeVisibility(boundingVolume);\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 _initializeLodMetric(header) {\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.lodMetricValue = header.lodMetricValue;\n } else {\n this.lodMetricValue =\n (this.parent && this.parent.lodMetricValue) || 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\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 _initializeBoundingVolumes(tileHeader) {\n this._contentBoundingVolume = null;\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.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) {\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._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 _isTileset() {\n return this.contentUrl.indexOf('.json') !== -1;\n }\n\n _onContentLoaded() {\n // Vector and Geometry tile rendering do not support the skip LOD optimization.\n switch (this.content && this.content.type) {\n case 'vctr':\n case 'geom':\n // @ts-ignore\n this.tileset._traverser.disableSkipLevelOfDetail = true;\n break;\n default:\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 // Update the bounding volumes\n this.boundingVolume = createBoundingVolume(\n header.boundingVolume,\n this.computedTransform,\n this.boundingVolume\n );\n\n const content = header.content;\n if (!content) {\n return;\n }\n\n // TODO Cesium specific\n // Non-leaf tiles may have a content bounding-volume, which is a tight-fit bounding volume\n // around only the features in the tile. This box is useful for culling for rendering,\n // but not for culling for traversing the tree since it does not guarantee spatial coherence, i.e.,\n // since it only bounds features in the tile, not the entire tile, children may be\n // outside of this box.\n if (content.boundingVolume) {\n this._contentBoundingVolume = createBoundingVolume(\n content.boundingVolume,\n this.computedTransform,\n this._contentBoundingVolume\n );\n }\n if (header.viewerRequestVolume) {\n this._viewerRequestVolume = createBoundingVolume(\n header.viewerRequestVolume,\n this.computedTransform,\n this._viewerRequestVolume\n );\n }\n }\n\n // Update the tile's transform. The transform is applied to the tile's bounding volumes.\n _updateTransform(parentTransform = new Matrix4()) {\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 this._updateBoundingVolume(this.header);\n }\n\n // Get options which are applicable only for the particular loader\n _getLoaderSpecificOptions(loaderId) {\n switch (loaderId) {\n case 'i3s':\n return {\n ...this.tileset.options.i3s,\n _tileOptions: {\n attributeUrls: this.header.attributeUrls,\n textureUrl: this.header.textureUrl,\n textureFormat: this.header.textureFormat,\n textureLoaderOptions: this.header.textureLoaderOptions,\n materialDefinition: this.header.materialDefinition,\n isDracoGeometry: this.header.isDracoGeometry,\n mbs: this.header.mbs\n },\n _tilesetOptions: {\n store: this.tileset.tileset.store,\n attributeStorageInfo: this.tileset.tileset.attributeStorageInfo,\n fields: this.tileset.tileset.fields\n },\n isTileHeader: false\n };\n case '3d-tiles':\n case 'cesium-ion':\n default:\n return get3dTilesOptions(this.tileset.tileset);\n }\n }\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", "// 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} 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 scratchNorthWest = new Vector3();\nconst scratchSouthEast = new Vector3();\nconst scratchCenter = new Vector3();\nconst scratchXAxis = new Vector3();\nconst scratchYAxis = new Vector3();\nconst scratchZAxis = new Vector3();\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 transform to apply to the bounding volume.\n * @param [result] The object onto which to store the result.\n * @returns The modified result parameter or a new TileBoundingVolume instance if none was provided.\n */\nexport function createBoundingVolume(boundingVolumeHeader, transform, result?) {\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 return createBox(boundingVolumeHeader.box, transform, result);\n }\n if (boundingVolumeHeader.region) {\n return createObbFromRegion(boundingVolumeHeader.region);\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 * @returns {CartographicBounds}\n */\nexport function getCartographicBounds(\n boundingVolumeHeader,\n boundingVolume: OrientedBoundingBox | BoundingSphere\n): CartographicBounds {\n // boundingVolume schema:\n // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/schema/boundingVolume.schema.json\n if (boundingVolumeHeader.box) {\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\n/*\nfunction createBoxFromTransformedRegion(region, transform, initialTransform, result) {\n const rectangle = Rectangle.unpack(region, 0, scratchRectangle);\n const minimumHeight = region[4];\n const maximumHeight = region[5];\n\n const orientedBoundingBox = OrientedBoundingBox.fromRectangle(\n rectangle,\n minimumHeight,\n maximumHeight,\n Ellipsoid.WGS84,\n scratchOrientedBoundingBox\n );\n const center = orientedBoundingBox.center;\n const halfAxes = orientedBoundingBox.halfAxes;\n\n // A region bounding volume is not transformed by the transform in the tileset JSON,\n // but may be transformed by additional transforms applied in Cesium.\n // This is why the transform is calculated as the difference between the initial transform and the current transform.\n transform = Matrix4.multiplyTransformation(\n transform,\n Matrix4.inverseTransformation(initialTransform, scratchTransform),\n scratchTransform\n );\n center = Matrix4.multiplyByPoint(transform, center, center);\n const rotationScale = Matrix4.getRotation(transform, scratchMatrix);\n halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes);\n\n if (defined(result) && result instanceof TileOrientedBoundingBox) {\n result.update(center, halfAxes);\n return result;\n }\n\n return new TileOrientedBoundingBox(center, halfAxes);\n}\n\nfunction createRegion(region, transform, initialTransform, result) {\n if (!Matrix4.equalsEpsilon(transform, initialTransform, CesiumMath.EPSILON8)) {\n return createBoxFromTransformedRegion(region, transform, initialTransform, result);\n }\n\n if (defined(result)) {\n return result;\n }\n\n const rectangleRegion = Rectangle.unpack(region, 0, scratchRectangle);\n\n return new TileBoundingRegion({\n rectangle: rectangleRegion,\n minimumHeight: region[4],\n maximumHeight: region[5]\n });\n}\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 * Create OrientedBoundingBox instance from region 3D tiles bounding volume\n * @param region - region 3D tiles bounding volume\n * @returns OrientedBoundingBox instance\n */\nfunction createObbFromRegion(region: number[]): OrientedBoundingBox {\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] = region;\n\n const northWest = Ellipsoid.WGS84.cartographicToCartesian(\n [degrees(west), degrees(north), minHeight],\n scratchNorthWest\n );\n const southEast = Ellipsoid.WGS84.cartographicToCartesian(\n [degrees(east), degrees(south), maxHeight],\n scratchSouthEast\n );\n const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyByScalar(0.5);\n Ellipsoid.WGS84.cartesianToCartographic(centerInCartesian, scratchCenter);\n\n Ellipsoid.WGS84.cartographicToCartesian(\n [degrees(east), scratchCenter[1], scratchCenter[2]],\n scratchXAxis\n );\n Ellipsoid.WGS84.cartographicToCartesian(\n [scratchCenter[0], degrees(north), scratchCenter[2]],\n scratchYAxis\n );\n Ellipsoid.WGS84.cartographicToCartesian(\n [scratchCenter[0], scratchCenter[1], maxHeight],\n scratchZAxis\n );\n\n return createBox(\n [\n ...centerInCartesian,\n ...scratchXAxis.subtract(centerInCartesian),\n ...scratchYAxis.subtract(centerInCartesian),\n ...scratchZAxis.subtract(centerInCartesian)\n ],\n new Matrix4()\n );\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\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// TODO - Dynamic screen space error provides an optimization when looking at\n// tilesets from above\n\n/* eslint-disable */\n// @ts-nocheck\nimport {Matrix4, Vector3, clamp} from '@math.gl/core';\n\nconst scratchPositionNormal = new Vector3();\nconst scratchCartographic = new Vector3();\nconst scratchMatrix = new Matrix4();\nconst scratchCenter = new Vector3();\nconst scratchPosition = new Vector3();\nconst scratchDirection = new Vector3();\n\n// eslint-disable-next-line max-statements, complexity\nexport function calculateDynamicScreenSpaceError(root, {camera, mapProjection}, options = {}) {\n const {dynamicScreenSpaceErrorHeightFalloff = 0.25, dynamicScreenSpaceErrorDensity = 0.00278} =\n options;\n\n let up;\n let direction;\n let height;\n let minimumHeight;\n let maximumHeight;\n\n const tileBoundingVolume = root.contentBoundingVolume;\n\n if (tileBoundingVolume instanceof TileBoundingRegion) {\n up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);\n direction = camera.directionWC;\n height = camera.positionCartographic.height;\n minimumHeight = tileBoundingVolume.minimumHeight;\n maximumHeight = tileBoundingVolume.maximumHeight;\n } else {\n // Transform camera position and direction into the local coordinate system of the tileset\n const transformLocal = Matrix4.inverseTransformation(root.computedTransform, scratchMatrix);\n const ellipsoid = mapProjection.ellipsoid;\n const boundingVolume = tileBoundingVolume.boundingVolume;\n const centerLocal = Matrix4.multiplyByPoint(\n transformLocal,\n boundingVolume.center,\n scratchCenter\n );\n if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {\n // The tileset is defined in WGS84. Approximate the minimum and maximum height.\n const centerCartographic = Cartographic.fromCartesian(\n centerLocal,\n ellipsoid,\n scratchCartographic\n );\n up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);\n direction = camera.directionWC;\n height = camera.positionCartographic.height;\n minimumHeight = 0.0;\n maximumHeight = centerCartographic.height * 2.0;\n } else {\n // The tileset is defined in local coordinates (z-up)\n const positionLocal = Matrix4.multiplyByPoint(\n transformLocal,\n camera.positionWC,\n scratchPosition\n );\n up = Cartesian3.UNIT_Z;\n direction = Matrix4.multiplyByPointAsVector(\n transformLocal,\n camera.directionWC,\n scratchDirection\n );\n direction = Cartesian3.normalize(direction, direction);\n height = positionLocal.z;\n if (tileBoundingVolume instanceof TileOrientedBoundingBox) {\n // Assuming z-up, the last component stores the half-height of the box\n const boxHeight = root._header.boundingVolume.box[11];\n minimumHeight = centerLocal.z - boxHeight;\n maximumHeight = centerLocal.z + boxHeight;\n } else if (tileBoundingVolume instanceof TileBoundingSphere) {\n const radius = boundingVolume.radius;\n minimumHeight = centerLocal.z - radius;\n maximumHeight = centerLocal.z + radius;\n }\n }\n }\n\n // The range where the density starts to lessen. Start at the quarter height of the tileset.\n const heightFalloff = dynamicScreenSpaceErrorHeightFalloff;\n const heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;\n const heightFar = maximumHeight;\n\n const t = clamp((height - heightClose) / (heightFar - heightClose), 0.0, 1.0);\n\n // Increase density as the camera tilts towards the horizon\n const dot = Math.abs(Cartesian3.dot(direction, up));\n\n let horizonFactor = 1.0 - dot;\n\n // Weaken the horizon factor as the camera height increases, implying the camera is further away from the tileset.\n // The goal is to increase density for the \"street view\", not when viewing the tileset from a distance.\n horizonFactor = horizonFactor * (1.0 - t);\n\n return dynamicScreenSpaceErrorDensity * horizonFactor;\n}\n\nexport function fog(distanceToCamera, density) {\n const scalar = distanceToCamera * density;\n return 1.0 - Math.exp(-(scalar * scalar));\n}\n\nexport function getDynamicScreenSpaceError(tileset, distanceToCamera) {\n if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {\n const density = tileset.dynamicScreenSpaceErrorComputedDensity;\n const factor = tileset.dynamicScreenSpaceErrorFactor;\n // TODO: Refined screen space error that minimizes tiles in non-first-person\n const dynamicError = fog(distanceToCamera, density) * factor;\n return dynamicError;\n }\n\n return 0;\n}\n\nexport function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {\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.0) {\n return 0.0;\n }\n\n // TODO: Orthographic Frustum needs special treatment?\n // this._getOrthograhicScreenSpaceError();\n\n // Avoid divide by zero when viewer is inside the tile\n const distance = Math.max(tile._distanceToCamera, 1e-7);\n const {height, sseDenominator} = frameState;\n const {viewDistanceScale} = tileset.options;\n let error = (lodMetricValue * height * (viewDistanceScale || 1.0)) / (distance * sseDenominator);\n\n error -= getDynamicScreenSpaceError(tileset, distance);\n\n return error;\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 '../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 || 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 || screenSize <= tile.lodMetricValue) {\n return 'DRAW';\n } else if (tile.header.children) {\n return 'DIG';\n }\n return 'OUT';\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 mbsLat = tile.header.mbs[1];\n const mbsLon = tile.header.mbs[0];\n const mbsZ = tile.header.mbs[2];\n const mbsR = tile.header.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", "import type {Tileset3D} from '../tileset-3d';\n\nexport function get3dTilesOptions(tileset: Tileset3D): {assetGltfUpAxis: 'X' | 'Y' | 'Z'} {\n return {\n assetGltfUpAxis: (tileset.asset && tileset.asset.gltfUpAxis) || 'Y'\n };\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 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 updateTransforms: true,\n onTraversalEnd: () => {},\n viewportTraversersMap: {},\n basePath: ''\n};\n\nexport class TilesetTraverser {\n options: Required<TilesetTraverserProps>;\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 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 // 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.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 if (stoppedRefining) {\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 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, skipLevelOfDetail} = this.options;\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) {\n // Keep non-visible children loaded since they are still needed before the parent can refine.\n // Or loadSiblings is true so always load tiles regardless of visibility.\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 refines = refines && childRefines;\n\n if (!refines) {\n return false;\n }\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)) {\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 tile._requestedFrame = frameState.frameNumber;\n tile._priority = tile._getPriority();\n this.requestedTiles[tile.id] = tile;\n }\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 shouldSelectTile(tile: Tile3D): boolean {\n // if select tile is in current frame\n // and content available\n return tile.contentAvailable && !this.options.skipLevelOfDetail;\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 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\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 || allDescendantsLoaded;\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 '../tileset-traverser';\n\nexport class Tileset3DTraverser extends TilesetTraverser {\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 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", "import {load} from '@loaders.gl/core';\nimport {TilesetTraverser} from '../tileset-traverser';\n\nimport {getLodStatus} from '../helpers/i3s-lod';\nimport {Tile3D} from '../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 const tileset = tile.tileset;\n\n for (const child of children) {\n const extendedId = `${child.id}-${frameState.viewport.id}`;\n // if child tile is not fetched\n const childTile = childTiles && childTiles.find((t) => t.id === extendedId);\n if (!childTile) {\n let request = () => this._loadTile(child.id, tileset);\n const cachedRequest = this._tileManager.find(extendedId);\n if (!cachedRequest) {\n // eslint-disable-next-line max-depth\n if (tileset.tileset.nodePages) {\n request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);\n }\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(nodeId, tileset) {\n const {loader} = tileset;\n const nodeUrl = tileset.getTileUrl(`${tileset.url}/nodes/${nodeId}`);\n // load metadata\n const options = {\n ...tileset.loadOptions,\n i3s: {\n ...tileset.loadOptions.i3s,\n isTileHeader: true\n }\n };\n\n return await load(nodeUrl, loader, options);\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 // 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", "/**\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", "import {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"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;ACMA,IAAAA,gBAA+B;AAC/B,IAAAC,qBAAwB;AACxB,mBAAoB;AACpB,IAAAC,uBAAsE;;;ACEhE,IAAO,uBAAP,MAA2B;EAC/B;EACA;EACA;EAEA,YAAY,MAAM,UAAU,MAAI;AAC9B,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,OAAO;EACd;;;;ACXI,IAAO,mBAAP,MAAuB;EAC3B,OAAoC;EACpC,OAAoC;EACpC,UAAU;EAEV,IAAI,SAAM;AACR,WAAO,KAAK;EACd;;;;;;EAOA,IAAI,MAAI;AACN,UAAM,OAAO,IAAI,qBAAqB,MAAM,KAAK,MAAM,IAAI;AAE3D,QAAI,KAAK,MAAM;AACb,WAAK,KAAK,OAAO;AACjB,WAAK,OAAO;IACd,OAAO;AACL,WAAK,OAAO;AACZ,WAAK,OA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sC;IACxD;AACA,QACE,KAAK,MAAM,YAAY,SACvB,KAAK,MAAM,YAAY,SACvB,KAAK,MAAM,YAAY,OACvB;AACA,YAAM,IAAI,MAAM,gEAAgE;IAClF;AAIA,QAAI,oBAAoB,KAAK,OAAO;AAClC,WAAK,aAAa,IAAI,KAAK,MAAM;IACnC;AAGA,SAAK,UAAU;MACb,cAAc,KAAK,QAAQ,gBAAgB,CAAA;;AAE7C,SAAK,cAAc,KAAK,QAAQ,eAAe;AAG/C,SAAK,aAAa,YAAY;AAC9B,SAAK,iBAAiB,YAAY;AAClC,SAAK,kBAAkB,YAAY,kBAAkB,CAAA;AAErD,SAAK,SAAS,YAAY;EAC5B;EAEA,wBAAqB;AACnB,UAAM,aAAa,KAAK,YAAY;AACpC,QAAI,cAAc,OAAO,eAAe,YAAY,WAAW,YAAY;AACzE,WAAK,aAAa,QAAS,WAAuC;IACpE;EACF;;",
6
- "names": ["import_core", "import_geospatial", "import_loader_utils", "import_core", "import_geospatial", "cameraPositionCartesian", "import_core", "import_culling", "import_geospatial", "scratchVector", "import_core", "import_culling", "TILE_REFINEMENT", "TILE_TYPE", "TILESET_TYPE", "LOD_METRIC_TYPE", "import_core", "import_culling", "import_geospatial", "import_loader_utils", "import_core", "scratchCenter", "scratchPosition", "import_core", "import_geospatial", "import_loader_utils", "scratchVector", "defined", "cullingVolume", "import_core", "id", "DEFAULT_PROPS"]
3
+ "sources": ["../src/index.ts", "../src/tileset-3d/common/tileset-3d.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/common/tileset-source.ts", "../src/tileset-3d/common/indexed-archive-tileset-source.ts", "../src/tileset-3d/common/tile-3d.ts", "../src/constants.ts", "../src/tileset-3d/helpers/bounding-volume.ts", "../src/tileset-3d/helpers/tiles-3d-lod.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/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/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"],
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 {Tileset3D} from './tileset-3d/common/tileset-3d';\nexport type {\n TileContentLoadResult,\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 {Tiles3DSource} from './tileset-3d/format-3d-tiles/tiles-3d-source';\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} 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';\n\nexport {getFrameState} 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", "// 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, LoaderWithParser, LoaderOptions} from '@loaders.gl/loader-utils';\nimport {TilesetCache} from './tileset-cache';\nimport {calculateTransformProps} from '../helpers/transform-utils';\nimport {FrameState, getFrameState, limitSelectedTiles} from '../helpers/frame-state';\n\nimport type {GeospatialViewport, Viewport} from '../../types';\nimport {Tile3D} from './tile-3d';\nimport {TILESET_TYPE} from '../../constants';\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 throttleRequests?: boolean;\n maxRequests?: number;\n loadOptions?: LoaderOptions;\n loadTiles?: boolean;\n basePath?: string;\n maximumMemoryUsage?: number;\n memoryCacheOverflow?: number;\n maximumTilesSelected?: number;\n debounceTime?: number;\n\n description?: string;\n attributions?: string[];\n\n ellipsoid?: object;\n modelMatrix?: Matrix4;\n\n maximumScreenSpaceError?: number;\n memoryAdjustedScreenSpaceError?: boolean;\n viewportTraversersMap?: any;\n updateTransforms?: boolean;\n viewDistanceScale?: 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 maximumMemoryUsage: number;\n memoryCacheOverflow: 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 memoryAdjustedScreenSpaceError: boolean;\n viewportTraversersMap: Record<string, any> | null;\n attributions: string[];\n loadTiles: boolean;\n loadOptions: LoaderOptions;\n updateTransforms: boolean;\n viewDistanceScale: number;\n basePath: string;\n contentLoader?: (tile: Tile3D) => Promise<void>;\n i3s: Record<string, any>;\n};\n\nconst DEFAULT_PROPS: Props = {\n description: '',\n ellipsoid: Ellipsoid.WGS84,\n modelMatrix: new Matrix4(),\n throttleRequests: true,\n maxRequests: 64,\n maximumMemoryUsage: 32,\n memoryCacheOverflow: 1,\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 maximumScreenSpaceError: 8,\n memoryAdjustedScreenSpaceError: false,\n loadTiles: true,\n updateTransforms: true,\n viewportTraversersMap: null,\n loadOptions: {fetch: {}},\n attributions: [],\n basePath: '',\n i3s: {}\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: LoaderWithParser;\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\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 dynamicScreenSpaceErrorComputedDensity = 0.0;\n\n maximumMemoryUsage = 32;\n gpuMemoryUsageInBytes = 0;\n memoryAdjustedScreenSpaceError = 0.0;\n\n private _cacheBytes = 0;\n private _cacheOverflowBytes = 0;\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\n _traverser: TilesetTraverser;\n _cache = new TilesetCache();\n _requestScheduler: RequestScheduler;\n\n private _heldTiles: Set<string> = 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 this.options = {...DEFAULT_PROPS, ...options};\n this.loadOptions = this.options.loadOptions || {};\n\n if (!isTileset3DSource(source)) {\n throw new Error('Tileset3D requires a Tileset3DSource instance');\n }\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 = this.options.maximumMemoryUsage * 1024 * 1024;\n this._cacheOverflowBytes = this.options.memoryCacheOverflow * 1024 * 1024;\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._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 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 setProps(props: Tileset3DProps): void {\n this.options = {...this.options, ...props};\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 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._cacheOverflowBytes) {\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\n this._cache.reset();\n this._frameNumber++;\n this.traverseCounter = preparedViewports.length;\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 this._traverser.traverse(this.roots[id], frameState, this.options);\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 selectedIds = new Set(this.selectedTiles.map(tile => tile.id));\n const hasUndrawnTiles = this.selectedTiles.some(tile => !tile.tileDrawn);\n\n let heldBackCount = 0;\n if (hasUndrawnTiles) {\n for (const tileId of selectedIds) {\n this._heldTiles.add(tileId);\n }\n for (const tileId of this._heldTiles) {\n if (selectedIds.has(tileId)) continue;\n\n const tile = this._tiles[tileId];\n if (tile && tile.contentAvailable) {\n tile._selectedFrame = this._frameNumber;\n this.selectedTiles.push(tile);\n heldBackCount++;\n } else {\n this._heldTiles.delete(tileId);\n }\n }\n } else {\n this._heldTiles = selectedIds;\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 _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 }\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 if (tile.content.pointCount) {\n pointsRenderable += tile.content.pointCount;\n } else {\n pointsRenderable += tile.content.vertexCount;\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 ) {\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 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 _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 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", "// 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", "// 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 unloadTiles(tileset, unloadCallback): void {\n const trimTiles = this._trimTiles;\n this._trimTiles = false;\n\n const list = this._list;\n\n const maximumMemoryUsageInBytes = tileset.maximumMemoryUsage * 1024 * 1024;\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 (\n node !== sentinel &&\n (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)\n ) {\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", "import 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 position: number[];\n direction: number[];\n up: number[];\n };\n viewport: GeospatialViewport;\n topDownViewport: GeospatialViewport; // Use it to calculate projected radius for a tile\n height: number;\n cullingVolume: CullingVolume;\n frameNumber: number; // TODO: This can be the same between updates, what number is unique for between updates?\n sseDenominator: number; // Assumes fovy = 60 degrees\n};\n\nconst scratchVector = new Vector3();\nconst scratchPosition = new Vector3();\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// Extracts a frame state appropriate for tile culling from a deck.gl viewport\n// TODO - this could likely be generalized and merged back into deck.gl for other culling scenarios\nexport function getFrameState(viewport: GeospatialViewport, frameNumber: number): 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 {cameraDirection, cameraUp, height} = viewport;\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 const cameraDirectionCartesian = new Vector3(\n // @ts-ignore\n enuToFixedTransform.transformAsVector(new Vector3(cameraDirection).scale(metersPerUnit))\n ).normalize();\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} = viewport;\n // @ts-ignore\n const topDownViewport = new ViewportClass({\n longitude,\n latitude,\n height,\n width,\n bearing,\n zoom,\n pitch: 0\n });\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 },\n viewport,\n topDownViewport,\n height,\n cullingVolume,\n frameNumber, // TODO: This can be the same between updates, what number is unique for between updates?\n sseDenominator: 1.15 // Assumes fovy = 60 degrees\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, number, 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\nimport type {CoreAPI, LoaderOptions, LoaderWithParser} 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';\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>(\n url: string,\n loader: LoaderWithParser<DataT>,\n loadOptions: LoaderOptions\n ): Promise<DataT>;\n\n /**\n * Loads and parses an arbitrary source-relative resource.\n */\n loadResource<DataT>(\n url: string,\n loader: LoaderWithParser<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: LoaderWithParser;\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 /** Nested tileset metadata to install below the loaded tile, if any. */\n nestedTileset?: TilesetJSON;\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 /** Loader used for metadata and content requests. */\n loader: LoaderWithParser;\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};\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 /** Loader used for content and metadata requests. */\n readonly loader: LoaderWithParser;\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 * 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 * 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?(parentTile: Tile3D, childId: string, frameState: FrameState): 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", "// 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 {\n CoreAPI,\n LoaderOptions,\n LoaderWithParser,\n ReadableFile\n} 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: LoaderWithParser<DataT>,\n loadOptions: LoaderOptions\n ): Promise<DataT> {\n return await this.parseArchiveResource(\n url,\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: LoaderWithParser<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: LoaderWithParser<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 : 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 const queryIndex = url.indexOf('?');\n return queryIndex >= 0 ? url.slice(0, queryIndex) : url;\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';\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 {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';\n\nconst scratchVector = new Vector3();\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/**\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 /** 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 /** @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 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 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 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 private _visibilityPlaneMask: any;\n private _visible: boolean | undefined = undefined;\n\n private _contentBoundingVolume: any;\n private _viewerRequestVolume: any;\n\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\n this._initializeLodMetric(header);\n this._initializeTransforms(header);\n this._updateLodMetricScale();\n this._initializeBoundingVolumes(header);\n this._initializeContent(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 this.children.length > 0 || (this.header.children && this.header.children.length > 0);\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 bounding box 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(this.header.boundingVolume, this.boundingVolume);\n }\n return this._boundingBox;\n }\n\n /** Get the tile's screen space error. */\n getScreenSpaceError(frameState, useParentLodMetric) {\n switch (this.tileset.type) {\n case TILESET_TYPE.I3S:\n return getProjectedRadius(this, frameState);\n case TILESET_TYPE.TILES3D:\n return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);\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 return this.content.gpuMemoryUsageInBytes || this.content.byteLength || 0;\n }\n\n /*\n * If skipLevelOfDetail is off try to load child tiles as soon as possible so that their parent can refine sooner.\n * Tiles are prioritized by screen space error.\n */\n // eslint-disable-next-line complexity\n _getPriority() {\n const traverser = this.tileset._traverser;\n const {skipLevelOfDetail} = traverser.options;\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 if (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)\n return Math.max(rootScreenSpaceError - screenSpaceError, 0);\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 const loadResult = await this.tileset.source.loadTileContent(this);\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 return loadResult;\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 // Unloads the tile's content.\n unloadContent() {\n if (this.content && this.content.destroy) {\n this.content.destroy();\n }\n this.content = null;\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._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 // 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 // Assuming the tile's bounding volume intersects the culling volume, determines\n // whether the tile's content's bounding volume intersects the culling volume.\n // @param {FrameState} frameState The frame state.\n // @returns {Intersect} The result of the intersection: the tile's content is completely outside, completely inside, or intersecting the culling volume.\n contentVisibility() {\n return true;\n\n // TODO restore\n /*\n // Assumes the tile's bounding volume intersects the culling volume already, so\n // just return Intersect.INSIDE if there is no content bounding volume.\n if (!defined(this.contentBoundingVolume)) {\n return Intersect.INSIDE;\n }\n\n if (this._visibilityPlaneMask === CullingVolume.MASK_INSIDE) {\n // The tile's bounding volume is completely inside the culling volume so\n // the content bounding volume must also be inside.\n return Intersect.INSIDE;\n }\n\n // PERFORMANCE_IDEA: is it possible to burn less CPU on this test since we know the\n // tile's (not the content's) bounding volume intersects the culling volume?\n const cullingVolume = frameState.cullingVolume;\n const boundingVolume = tile.contentBoundingVolume;\n\n const tileset = this.tileset;\n const clippingPlanes = tileset.clippingPlanes;\n if (defined(clippingPlanes) && clippingPlanes.enabled) {\n const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(\n boundingVolume,\n tileset.clippingPlanesOriginMatrix\n );\n this._isClipped = intersection !== Intersect.INSIDE;\n if (intersection === Intersect.OUTSIDE) {\n return Intersect.OUTSIDE;\n }\n }\n\n return cullingVolume.computeVisibility(boundingVolume);\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 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) {\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._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.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) {\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._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 _isTileset() {\n return this.contentUrl.indexOf('.json') !== -1;\n }\n\n _onContentLoaded() {\n // Vector and Geometry tile rendering do not support the skip LOD optimization.\n switch (this.content && this.content.type) {\n case 'vctr':\n case 'geom':\n // @ts-ignore\n this.tileset._traverser.disableSkipLevelOfDetail = true;\n break;\n default:\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 // Update the bounding volumes\n this.boundingVolume = createBoundingVolume(\n header.boundingVolume,\n this.computedTransform,\n this.boundingVolume\n );\n\n const content = header.content;\n if (!content) {\n return;\n }\n\n // TODO Cesium specific\n // Non-leaf tiles may have a content bounding-volume, which is a tight-fit bounding volume\n // around only the features in the tile. This box is useful for culling for rendering,\n // but not for culling for traversing the tree since it does not guarantee spatial coherence, i.e.,\n // since it only bounds features in the tile, not the entire tile, children may be\n // outside of this box.\n if (content.boundingVolume) {\n this._contentBoundingVolume = createBoundingVolume(\n content.boundingVolume,\n this.computedTransform,\n this._contentBoundingVolume\n );\n }\n if (header.viewerRequestVolume) {\n this._viewerRequestVolume = createBoundingVolume(\n header.viewerRequestVolume,\n this.computedTransform,\n this._viewerRequestVolume\n );\n }\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\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", "// 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} 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 scratchNorthWest = new Vector3();\nconst scratchSouthEast = new Vector3();\nconst scratchCenter = new Vector3();\nconst scratchXAxis = new Vector3();\nconst scratchYAxis = new Vector3();\nconst scratchZAxis = new Vector3();\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 transform to apply to the bounding volume.\n * @param [result] The object onto which to store the result.\n * @returns The modified result parameter or a new TileBoundingVolume instance if none was provided.\n */\nexport function createBoundingVolume(boundingVolumeHeader, transform, result?) {\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 return createBox(boundingVolumeHeader.box, transform, result);\n }\n if (boundingVolumeHeader.region) {\n return createObbFromRegion(boundingVolumeHeader.region);\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 * @returns {CartographicBounds}\n */\nexport function getCartographicBounds(\n boundingVolumeHeader,\n boundingVolume: OrientedBoundingBox | BoundingSphere\n): CartographicBounds {\n // boundingVolume schema:\n // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/schema/boundingVolume.schema.json\n if (boundingVolumeHeader.box) {\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\n/*\nfunction createBoxFromTransformedRegion(region, transform, initialTransform, result) {\n const rectangle = Rectangle.unpack(region, 0, scratchRectangle);\n const minimumHeight = region[4];\n const maximumHeight = region[5];\n\n const orientedBoundingBox = OrientedBoundingBox.fromRectangle(\n rectangle,\n minimumHeight,\n maximumHeight,\n Ellipsoid.WGS84,\n scratchOrientedBoundingBox\n );\n const center = orientedBoundingBox.center;\n const halfAxes = orientedBoundingBox.halfAxes;\n\n // A region bounding volume is not transformed by the transform in the tileset JSON,\n // but may be transformed by additional transforms applied in Cesium.\n // This is why the transform is calculated as the difference between the initial transform and the current transform.\n transform = Matrix4.multiplyTransformation(\n transform,\n Matrix4.inverseTransformation(initialTransform, scratchTransform),\n scratchTransform\n );\n center = Matrix4.multiplyByPoint(transform, center, center);\n const rotationScale = Matrix4.getRotation(transform, scratchMatrix);\n halfAxes = Matrix3.multiply(rotationScale, halfAxes, halfAxes);\n\n if (defined(result) && result instanceof TileOrientedBoundingBox) {\n result.update(center, halfAxes);\n return result;\n }\n\n return new TileOrientedBoundingBox(center, halfAxes);\n}\n\nfunction createRegion(region, transform, initialTransform, result) {\n if (!Matrix4.equalsEpsilon(transform, initialTransform, CesiumMath.EPSILON8)) {\n return createBoxFromTransformedRegion(region, transform, initialTransform, result);\n }\n\n if (defined(result)) {\n return result;\n }\n\n const rectangleRegion = Rectangle.unpack(region, 0, scratchRectangle);\n\n return new TileBoundingRegion({\n rectangle: rectangleRegion,\n minimumHeight: region[4],\n maximumHeight: region[5]\n });\n}\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 * Create OrientedBoundingBox instance from region 3D tiles bounding volume\n * @param region - region 3D tiles bounding volume\n * @returns OrientedBoundingBox instance\n */\nfunction createObbFromRegion(region: number[]): OrientedBoundingBox {\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] = region;\n\n const northWest = Ellipsoid.WGS84.cartographicToCartesian(\n [degrees(west), degrees(north), minHeight],\n scratchNorthWest\n );\n const southEast = Ellipsoid.WGS84.cartographicToCartesian(\n [degrees(east), degrees(south), maxHeight],\n scratchSouthEast\n );\n const centerInCartesian = new Vector3().addVectors(northWest, southEast).multiplyByScalar(0.5);\n Ellipsoid.WGS84.cartesianToCartographic(centerInCartesian, scratchCenter);\n\n Ellipsoid.WGS84.cartographicToCartesian(\n [degrees(east), scratchCenter[1], scratchCenter[2]],\n scratchXAxis\n );\n Ellipsoid.WGS84.cartographicToCartesian(\n [scratchCenter[0], degrees(north), scratchCenter[2]],\n scratchYAxis\n );\n Ellipsoid.WGS84.cartographicToCartesian(\n [scratchCenter[0], scratchCenter[1], maxHeight],\n scratchZAxis\n );\n\n return createBox(\n [\n ...centerInCartesian,\n ...scratchXAxis.subtract(centerInCartesian),\n ...scratchYAxis.subtract(centerInCartesian),\n ...scratchZAxis.subtract(centerInCartesian)\n ],\n new Matrix4()\n );\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\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// TODO - Dynamic screen space error provides an optimization when looking at\n// tilesets from above\n\n/* eslint-disable */\n// @ts-nocheck\nimport {Matrix4, Vector3, clamp} from '@math.gl/core';\n\nconst scratchPositionNormal = new Vector3();\nconst scratchCartographic = new Vector3();\nconst scratchMatrix = new Matrix4();\nconst scratchCenter = new Vector3();\nconst scratchPosition = new Vector3();\nconst scratchDirection = new Vector3();\n\n// eslint-disable-next-line max-statements, complexity\nexport function calculateDynamicScreenSpaceError(root, {camera, mapProjection}, options = {}) {\n const {dynamicScreenSpaceErrorHeightFalloff = 0.25, dynamicScreenSpaceErrorDensity = 0.00278} =\n options;\n\n let up;\n let direction;\n let height;\n let minimumHeight;\n let maximumHeight;\n\n const tileBoundingVolume = root.contentBoundingVolume;\n\n if (tileBoundingVolume instanceof TileBoundingRegion) {\n up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);\n direction = camera.directionWC;\n height = camera.positionCartographic.height;\n minimumHeight = tileBoundingVolume.minimumHeight;\n maximumHeight = tileBoundingVolume.maximumHeight;\n } else {\n // Transform camera position and direction into the local coordinate system of the tileset\n const transformLocal = Matrix4.inverseTransformation(root.computedTransform, scratchMatrix);\n const ellipsoid = mapProjection.ellipsoid;\n const boundingVolume = tileBoundingVolume.boundingVolume;\n const centerLocal = Matrix4.multiplyByPoint(\n transformLocal,\n boundingVolume.center,\n scratchCenter\n );\n if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {\n // The tileset is defined in WGS84. Approximate the minimum and maximum height.\n const centerCartographic = Cartographic.fromCartesian(\n centerLocal,\n ellipsoid,\n scratchCartographic\n );\n up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);\n direction = camera.directionWC;\n height = camera.positionCartographic.height;\n minimumHeight = 0.0;\n maximumHeight = centerCartographic.height * 2.0;\n } else {\n // The tileset is defined in local coordinates (z-up)\n const positionLocal = Matrix4.multiplyByPoint(\n transformLocal,\n camera.positionWC,\n scratchPosition\n );\n up = Cartesian3.UNIT_Z;\n direction = Matrix4.multiplyByPointAsVector(\n transformLocal,\n camera.directionWC,\n scratchDirection\n );\n direction = Cartesian3.normalize(direction, direction);\n height = positionLocal.z;\n if (tileBoundingVolume instanceof TileOrientedBoundingBox) {\n // Assuming z-up, the last component stores the half-height of the box\n const boxHeight = root._header.boundingVolume.box[11];\n minimumHeight = centerLocal.z - boxHeight;\n maximumHeight = centerLocal.z + boxHeight;\n } else if (tileBoundingVolume instanceof TileBoundingSphere) {\n const radius = boundingVolume.radius;\n minimumHeight = centerLocal.z - radius;\n maximumHeight = centerLocal.z + radius;\n }\n }\n }\n\n // The range where the density starts to lessen. Start at the quarter height of the tileset.\n const heightFalloff = dynamicScreenSpaceErrorHeightFalloff;\n const heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;\n const heightFar = maximumHeight;\n\n const t = clamp((height - heightClose) / (heightFar - heightClose), 0.0, 1.0);\n\n // Increase density as the camera tilts towards the horizon\n const dot = Math.abs(Cartesian3.dot(direction, up));\n\n let horizonFactor = 1.0 - dot;\n\n // Weaken the horizon factor as the camera height increases, implying the camera is further away from the tileset.\n // The goal is to increase density for the \"street view\", not when viewing the tileset from a distance.\n horizonFactor = horizonFactor * (1.0 - t);\n\n return dynamicScreenSpaceErrorDensity * horizonFactor;\n}\n\nexport function fog(distanceToCamera, density) {\n const scalar = distanceToCamera * density;\n return 1.0 - Math.exp(-(scalar * scalar));\n}\n\nexport function getDynamicScreenSpaceError(tileset, distanceToCamera) {\n if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {\n const density = tileset.dynamicScreenSpaceErrorComputedDensity;\n const factor = tileset.dynamicScreenSpaceErrorFactor;\n // TODO: Refined screen space error that minimizes tiles in non-first-person\n const dynamicError = fog(distanceToCamera, density) * factor;\n return dynamicError;\n }\n\n return 0;\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. Orthographic projection has no perspective distance falloff, so\n * its error is divided directly by the viewport's world-space meters per logical pixel.\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 * @returns Estimated error in logical/CSS pixels.\n */\nexport function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {\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.0) {\n return 0.0;\n }\n\n const {viewDistanceScale} = tileset.options;\n const lodScale = viewDistanceScale || 1.0;\n const orthographicError = getOrthographicScreenSpaceError(lodMetricValue, frameState, lodScale);\n if (orthographicError !== null) {\n return orthographicError;\n }\n\n // Avoid divide by zero when viewer is inside the tile\n const distance = Math.max(tile._distanceToCamera, 1e-7);\n const {height, sseDenominator} = frameState;\n let error = (lodMetricValue * height * lodScale) / (distance * sseDenominator);\n\n error -= getDynamicScreenSpaceError(tileset, distance);\n\n return error;\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 * @returns SSE in logical pixels, or `null` when orthographic SSE cannot be calculated.\n */\nfunction getOrthographicScreenSpaceError(lodMetricValue, frameState, lodScale) {\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 <= 0) {\n return null;\n }\n\n return (lodMetricValue * lodScale) / metersPerPixel;\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 || screenSize <= tile.lodMetricValue) {\n return 'DRAW';\n } else if (tile.header.children) {\n return 'DIG';\n }\n return 'OUT';\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 mbsLat = tile.header.mbs[1];\n const mbsLon = tile.header.mbs[0];\n const mbsZ = tile.header.mbs[2];\n const mbsR = tile.header.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", "// 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 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 updateTransforms: true,\n onTraversalEnd: () => {},\n viewportTraversersMap: {},\n basePath: ''\n};\n\nexport class TilesetTraverser {\n options: Required<TilesetTraverserProps>;\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 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 // 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.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 if (stoppedRefining) {\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 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, skipLevelOfDetail} = this.options;\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) {\n // Keep non-visible children loaded since they are still needed before the parent can refine.\n // Or loadSiblings is true so always load tiles regardless of visibility.\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 refines = refines && childRefines;\n\n if (!refines) {\n return false;\n }\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)) {\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 tile._requestedFrame = frameState.frameNumber;\n tile._priority = tile._getPriority();\n this.requestedTiles[tile.id] = tile;\n }\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 shouldSelectTile(tile: Tile3D): boolean {\n // if select tile is in current frame\n // and content available\n return tile.contentAvailable && !this.options.skipLevelOfDetail;\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 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\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 || allDescendantsLoaded;\n }\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, LoaderOptions, LoaderWithParser} 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 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';\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 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: LoaderWithParser;\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 private readonly extensionsUsed: string[] = [];\n private readonly resolver?: TilesetSourceResolver;\n private rootTileset: TilesetJSON;\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 }\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 Object.assign(this.queryParams, Object.fromEntries(searchParams.entries()));\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.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 either 0.0 or 1.0 or 1.1.');\n }\n\n if ('tilesetVersion' in this.asset) {\n this.queryParams.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 };\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 /**\n * Builds the eager runtime tile tree for a 3D Tiles subtree.\n */\n initializeTileHeaders(\n tileset: Tileset3D,\n tilesetJson: TilesetJSON,\n parentTile?: Tile3D | null\n ): Tile3D {\n const rootTile = new Tile3DNode(tileset, tilesetJson.root, 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.queryParams.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 contentUrl = this.getTileUrl(tile.contentUrl);\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 isTileset: tile.type === 'json',\n assetGltfUpAxis: (this.asset && this.asset.gltfUpAxis) || 'Y'\n }\n };\n\n const content = await this.loadResourceData(contentUrl, options);\n tile.content = content;\n\n return {\n loaded: true,\n nestedTileset: tile.contentUrl.includes('.json') ? content : undefined\n };\n }\n\n /**\n * Resolves a tile content 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 [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 return queryParams ? `${pathWithoutQuery}?${queryParams}` : pathWithoutQuery;\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.\n */\n onTileLoaded(tileset: Tileset3D, tile: Tile3D, loadResult: TileContentLoadResult): void {\n const {extensionsRemoved = []} = tile.content?.gltf || {};\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 if (loadResult.nestedTileset) {\n tileset._initializeTileHeaders(loadResult.nestedTileset, tile);\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(url: string, options: LoaderOptions): 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, this.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 tile content through an injected resolver when present, otherwise through the injected core API.\n */\n private async loadResourceData(url: string, options: LoaderOptions): Promise<any> {\n if (this.resolver) {\n return await this.resolver.loadResource(url, this.loader, options);\n }\n\n return await this.loadWithCoreApi(url, options);\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", "// 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';\n\nexport class Tileset3DTraverser extends TilesetTraverser {\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 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\nimport {path} from '@loaders.gl/loader-utils';\nimport {Ellipsoid} from '@math.gl/geospatial';\nimport {Vector3} from '@math.gl/core';\nimport type {CoreAPI, LoaderOptions, LoaderWithParser} from '@loaders.gl/loader-utils';\nimport type {Tile3D} from '../common/tile-3d';\nimport {Tile3D as Tile3DNode} from '../common/tile-3d';\nimport {I3STilesetTraverser} from './i3s-tileset-traverser';\nimport type {Tileset3D} from '../common/tileset-3d';\nimport type {FrameState} from '../helpers/frame-state';\nimport type {\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';\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 /** Loader used for tile metadata and content requests. */\n readonly loader: LoaderWithParser;\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\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.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 }\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.url, this.loadOptions);\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 const i3sOptions = this.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 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 };\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 /**\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 rootTile = new Tile3DNode(tileset, tilesetJson.root, 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 textureFormat: tile.header.textureFormat,\n textureLoaderOptions: tile.header.textureLoaderOptions,\n materialDefinition: tile.header.materialDefinition,\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 },\n isTileHeader: false\n }\n };\n\n tile.content = await this.loadResourceData(contentUrl, options);\n return {loaded: true};\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\n ): Promise<any> {\n const metadata = this.getMetadata();\n if (metadata.tileset.nodePages) {\n return await metadata.tileset.nodePagesTile.formTileFromNodePages(childId);\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 return await this.loadResourceData(nodeUrl, options);\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 queryParams = new URLSearchParams(this.queryParams).toString();\n return `${tilePath}${tilePath.includes('?') ? '&' : '?'}${queryParams}`;\n }\n\n /**\n * Derives the default view state from full extent or store extent metadata.\n */\n getViewState(_rootTile: Tile3D | null): TilesetSourceViewState {\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(url: string, options: LoaderOptions): 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, this.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 tile metadata or content through an injected resolver when present, otherwise through the injected core API.\n */\n private async loadResourceData(url: string, options: LoaderOptions): Promise<any> {\n if (this.resolver) {\n return await this.resolver.loadResource(url, this.loader, options);\n }\n\n return await this.loadWithCoreApi(url, options);\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 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", "/**\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", "import {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", "import {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 = childTiles && childTiles.find(t => t.id === extendedId);\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\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 type {Matrix4} from '@math.gl/core';\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?: Matrix4 | null;\n modelMatrixInverse?: Matrix4 | 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// Copyright (c) vis.gl contributors\n\nimport type {\n GetRasterParameters,\n RasterData,\n RasterSource,\n RasterSourceMetadata\n} from '@loaders.gl/loader-utils';\n\n/** Accepted raster request currently retained by {@link RasterSet}. */\nexport type RasterSetRequest<DataT = RasterData> = {\n /** Unique request id assigned by the manager. */\n requestId: number;\n /** Raster request parameters that produced the accepted raster payload. */\n parameters: GetRasterParameters;\n /** Raster retained as the current output. */\n raster: DataT;\n};\n\n/** Arguments supplied to {@link RasterSetBaseProps.shouldRefetch}. */\nexport type RasterSetShouldRefetchArgs<DataT = RasterData> = {\n /** Current accepted request retained by the raster manager, if any. */\n currentRequest: RasterSetRequest<DataT> | null;\n /** Source metadata resolved by {@link RasterSet.loadMetadata}, if available. */\n metadata: RasterSourceMetadata | null;\n /** Candidate raster request parameters under evaluation. */\n nextParameters: GetRasterParameters;\n};\n\n/** Configuration shared by all {@link RasterSet} instances. */\nexport type RasterSetBaseProps<DataT = RasterData> = {\n /** Callback used to load source metadata. */\n getMetadata: () => Promise<RasterSourceMetadata>;\n /** Callback used to load raster data for a viewport-derived request. */\n getRaster: (parameters: GetRasterParameters) => 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>) => boolean;\n};\n\n/** Options for creating a {@link RasterSet}. */\nexport type RasterSetProps<DataT = RasterData> = Partial<RasterSetBaseProps<DataT>> & {\n /** Optional loaders.gl raster source backing this manager. */\n rasterSource?: RasterSource | null;\n};\n\n/** Subscription callbacks emitted by {@link RasterSet}. */\nexport type RasterSetListener<DataT = RasterData> = {\n /** Fired when metadata/raster loading starts or stops. */\n onLoadingStateChange?: (isLoading: boolean) => void;\n /** Fired when source metadata resolves successfully. */\n onMetadataLoad?: (metadata: RasterSourceMetadata) => 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: GetRasterParameters) => void;\n /** Fired when a raster request resolves and becomes current. */\n onRasterLoad?: (request: RasterSetRequest<DataT>) => void;\n /** Fired when a raster request fails. */\n onRasterLoadError?: (requestId: number, error: Error, parameters: GetRasterParameters) => 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/** Shared raster request manager used by viewport-driven raster examples and layers. */\nexport class RasterSet<DataT = RasterData> {\n /** Cached metadata returned by the backing source, if any. */\n metadata: RasterSourceMetadata | null = null;\n\n private _opts: Required<RasterSetProps<DataT>>;\n private _listeners = new Set<RasterSetListener<DataT>>();\n private _currentRequest: RasterSetRequest<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 a raster manager from a source or direct callbacks. */\n constructor(opts: RasterSetProps<DataT>) {\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<DataT = RasterData>(\n rasterSource: RasterSource,\n opts: Omit<RasterSetProps<DataT>, 'rasterSource' | 'getRaster' | 'getMetadata'> = {}\n ): RasterSet<DataT> {\n return new RasterSet<DataT>({...opts, rasterSource});\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> | null {\n return this._currentRequest;\n }\n\n /** Backing raster source when constructed from one. */\n get rasterSource(): RasterSource | null {\n return this._opts.rasterSource;\n }\n\n /** Subscribes to metadata and raster lifecycle events. */\n subscribe(listener: RasterSetListener<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: RasterSetProps<DataT>): void {\n const previousRasterSource = this._opts.rasterSource;\n const nextOptions = this._normalizeOptions({...this._opts, ...opts});\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.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 raster source or callbacks. */\n async loadMetadata(): Promise<RasterSourceMetadata> {\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 = normalizeRasterSetError(error, 'Raster 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 raster request for the supplied parameters. */\n requestRaster(parameters: GetRasterParameters, debounceTime = this._opts.debounceTime): number {\n if (!this.shouldRefetchRaster(parameters)) {\n return this._currentRequest?.requestId ?? -1;\n }\n\n const requestId = this._nextRequestId++;\n this._cancelScheduledRaster();\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: GetRasterParameters): 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._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: GetRasterParameters): Promise<void> {\n if (this._finalized) {\n return;\n }\n\n this._startLoading();\n for (const listener of this._listeners) {\n listener.onRasterLoadStart?.(requestId, parameters);\n }\n\n try {\n const abortController = new AbortController();\n this._abortController = abortController;\n const raster = await this._opts.getRaster({...parameters, signal: abortController.signal});\n if (\n this._finalized ||\n abortController.signal.aborted ||\n requestId <= this._lastAcceptedRequestId\n ) {\n return;\n }\n\n this._lastAcceptedRequestId = requestId;\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 (isAbortError(error)) {\n return;\n }\n const normalizedError = normalizeRasterSetError(error, 'Raster request failed');\n if (!this._finalized) {\n for (const listener of this._listeners) {\n listener.onRasterLoadError?.(requestId, normalizedError, parameters);\n }\n }\n } finally {\n this._abortController = null;\n this._finishLoading();\n }\n }\n\n /** Resolves current options from either a source or direct callbacks. */\n private _normalizeOptions(opts: RasterSetProps<DataT>): Required<RasterSetProps<DataT>> {\n const rasterSource = opts.rasterSource || null;\n return {\n ...DEFAULT_RASTERSET_PROPS,\n ...opts,\n rasterSource,\n getMetadata:\n opts.getMetadata ||\n (() => {\n if (rasterSource) {\n return rasterSource.getMetadata();\n }\n return DEFAULT_RASTERSET_PROPS.getMetadata();\n }),\n getRaster:\n opts.getRaster ||\n ((parameters: GetRasterParameters) => {\n if (rasterSource) {\n return rasterSource.getRaster(parameters) as Promise<DataT>;\n }\n return DEFAULT_RASTERSET_PROPS.getRaster(parameters) as Promise<DataT>;\n }),\n debounceTime: opts.debounceTime ?? DEFAULT_RASTERSET_PROPS.debounceTime,\n shouldRefetch:\n (opts.shouldRefetch as\n | ((args: RasterSetShouldRefetchArgs<DataT>) => boolean)\n | undefined) ||\n ((args: RasterSetShouldRefetchArgs<DataT>) =>\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 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 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/** 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", "import {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 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 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 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\n const [minBounds, maxBounds] = boundingVolume.cartographicBounds;\n const longitudeSpan = Math.max(Math.abs(maxBounds[0] - minBounds[0]), 0.000001);\n return Math.max(1, Math.round(Math.log2(360 / longitudeSpan)));\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 return [\n [minBounds[0], minBounds[1], minBounds[2] || 0],\n [minBounds[0], minBounds[1], maxBounds[2] || 0],\n [minBounds[0], maxBounds[1], minBounds[2] || 0],\n [minBounds[0], maxBounds[1], maxBounds[2] || 0],\n [maxBounds[0], minBounds[1], minBounds[2] || 0],\n [maxBounds[0], minBounds[1], maxBounds[2] || 0],\n [maxBounds[0], maxBounds[1], minBounds[2] || 0],\n [maxBounds[0], maxBounds[1], maxBounds[2] || 0]\n ];\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", "import 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"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,IAAAA,eAA+B;AAC/B,IAAAC,qBAAwB;AACxB,mBAAoB;AACpB,IAAAC,uBAAgE;;;ACE1D,IAAO,uBAAP,MAA2B;EAC/B;EACA;EACA;EAEA,YAAY,MAAM,UAAU,MAAI;AAC9B,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,OAAO;EACd;;;;ACXI,IAAO,mBAAP,MAAuB;EAC3B,OAAoC;EACpC,OAAoC;EACpC,UAAU;EAEV,IAAI,SAAM;AACR,WAAO,KAAK;EACd;;;;;;EAOA,IAAI,MAAI;AACN,UAAM,OAAO,IAAI,qBAAqB,MAAM,KAAK,MAAM,IAAI;AAE3D,QAAI,KAAK,MAAM;AACb,WAAK,KAAK,OAAO;AACjB,WAAK,OAAO;IACd,OAAO;AACL,WAAK,OAAO;AACZ,WAAK,OAAO;IACd;AAEA,MAAE,KAAK;AAEP,WAAO;EACT;;;;;EAMA,OAAO,MAAI;AACT,QAAI,CAAC,MAAM;AACT;IACF;AAEA,QAAI,KAA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KAAK,yBAAyB,cAAc;AAC5D,QAAI,OAAO,OAAO;AAClB,QAAI,OAAO,OAAO;AAClB,QAAI,OAAO,OAAO;AAClB,QAAI,OAAO,OAAO;AAClB,QAAI,OAAO,OAAO;AAClB,QAAI,OAAO,OAAO;AAElB,QAAI;AACF,iBAAW,UAAU,SAAS;AAC5B,cAAM,CAAC,GAAG,GAAG,IAAI,CAAC,IAAI,gBAAgB,MAAM;AAC5C,YAAI,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,GAAG;AACrE;QACF;AAEA,eAAO,KAAK,IAAI,MAAM,CAAC;AACvB,eAAO,KAAK,IAAI,MAAM,CAAC;AACvB,eAAO,KAAK,IAAI,MAAM,CAAC;AACvB,eAAO,KAAK,IAAI,MAAM,CAAC;AACvB,eAAO,KAAK,IAAI,MAAM,CAAC;AACvB,eAAO,KAAK,IAAI,MAAM,CAAC;MACzB;IACF,QAAE;AACA,aAAO;IACT;AAEA,QACE,CAAC,OAAO,SAAS,IAAI,KACrB,CAAC,OAAO,SAAS,IAAI,KACrB,CAAC,OAAO,SAAS,IAAI,KACrB,CAAC,OAAO,SAAS,IAAI,KACrB,CAAC,OAAO,SAAS,IAAI,KACrB,CAAC,OAAO,SAAS,IAAI,GACrB;AACA,aAAO;IACT;AAEA,WAAO,IAAI,+BAAc,EAAG,iBAAiB,CAAC,MAAM,MAAM,IAAI,GAAG,CAAC,MAAM,MAAM,IAAI,CAAC;EACrF;;",
6
+ "names": ["import_core", "import_geospatial", "import_loader_utils", "import_core", "import_geospatial", "cameraPositionCartesian", "import_loader_utils", "import_core", "import_culling", "TILE_REFINEMENT", "TILE_TYPE", "TILESET_TYPE", "LOD_METRIC_TYPE", "import_core", "import_culling", "import_geospatial", "import_loader_utils", "import_core", "scratchCenter", "scratchPosition", "import_core", "import_geospatial", "import_loader_utils", "DEFAULT_PROPS", "scratchVector", "defined", "cullingVolume", "import_loader_utils", "import_geospatial", "import_core", "import_core", "import_culling", "import_geospatial", "scratchVector", "import_loader_utils", "import_geospatial", "import_core", "id", "EMPTY_CONTENT_FORMATS", "isTilesetRequest", "tileData", "error", "loaderId", "import_loader_utils", "import_stats", "isAbortError", "import_core", "import_culling", "DEFAULT_PROPS", "cullingVolume"]
7
7
  }