@arcgis/core 5.0.0-next.34 → 5.0.0-next.36

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 (232) hide show
  1. package/applications/Components/SketchTooltipControls.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/06462b267ff8d5984882.js +1 -0
  4. package/assets/esri/core/workers/chunks/{b48bb38e5d60fc7a9097.js → 08ef90e3fcfd4eda4301.js} +1 -1
  5. package/assets/esri/core/workers/chunks/0a58b57e1777a8b0ea23.js +1 -0
  6. package/assets/esri/core/workers/chunks/{7115c52e22b7becff8de.js → 103153951ba312dc5e9e.js} +1 -1
  7. package/assets/esri/core/workers/chunks/15c1a48e8cd2a8882d85.js +1 -0
  8. package/assets/esri/core/workers/chunks/{f55328aabf84770c8e6a.js → 1817cf11e85afca947d3.js} +1 -1
  9. package/assets/esri/core/workers/chunks/{1dd867fa7c58c06b79ea.js → 1bacdd17e199e22b5cd1.js} +1 -1
  10. package/assets/esri/core/workers/chunks/20e4243ea563d05a5256.js +1 -0
  11. package/assets/esri/core/workers/chunks/234ffd08c2be03a0b9fe.js +1 -0
  12. package/assets/esri/core/workers/chunks/24a3c6f0154787968724.js +1 -0
  13. package/assets/esri/core/workers/chunks/{fafbacf2467e6883b6c9.js → 28db329528def851efd7.js} +1 -1
  14. package/assets/esri/core/workers/chunks/{2367bd1cb34799a3f08a.js → 30184e39129d9c66ea54.js} +1 -1
  15. package/assets/esri/core/workers/chunks/32d32d3c3b38a215d20d.js +1 -0
  16. package/assets/esri/core/workers/chunks/36130910ba141f34531b.js +1 -0
  17. package/assets/esri/core/workers/chunks/3f03165487c1c2340fff.js +1 -0
  18. package/assets/esri/core/workers/chunks/48d1a443b324753921de.js +1 -0
  19. package/assets/esri/core/workers/chunks/48e2737182c75005fb8f.js +1 -0
  20. package/assets/esri/core/workers/chunks/4f4d51181ae7db9fbe6d.js +1 -0
  21. package/assets/esri/core/workers/chunks/{05e55118dc0023d500fc.js → 5000a37fba27464d10ca.js} +1 -1
  22. package/assets/esri/core/workers/chunks/{fa01d1813fa78034526e.js → 51355866a0dcf41cfded.js} +1 -1
  23. package/assets/esri/core/workers/chunks/{486e69261aa2caf9ec3c.js → 52c8687b473c9953c2f2.js} +1 -1
  24. package/assets/esri/core/workers/chunks/{fee942ef802a162e0248.js → 5dc0d853c21ccb6054c7.js} +1 -1
  25. package/assets/esri/core/workers/chunks/640085b5ade5c7f16228.js +1 -0
  26. package/assets/esri/core/workers/chunks/727804cf901094b1d620.js +1 -0
  27. package/assets/esri/core/workers/chunks/{0446562aee0639c61485.js → 7420fa18ba12014b22ea.js} +1 -1
  28. package/assets/esri/core/workers/chunks/768d9b6eaba7bfa18dde.js +1 -0
  29. package/assets/esri/core/workers/chunks/{c9c2e00fed979c21e2f0.js → 8a946cbc816f373c136b.js} +1 -1
  30. package/assets/esri/core/workers/chunks/8c271e9272e4eaf1325a.js +1 -0
  31. package/assets/esri/core/workers/chunks/{2a0fe1aede5c68374ccf.js → 8ec238b5b59ef18a1713.js} +1 -1
  32. package/assets/esri/core/workers/chunks/{f1dfb1323d50247e80f9.js → 9110287f272141f60c35.js} +1 -1
  33. package/assets/esri/core/workers/chunks/951a3442d4342539f2ea.js +1 -0
  34. package/assets/esri/core/workers/chunks/9664d9e679abc41f6c42.js +1 -0
  35. package/assets/esri/core/workers/chunks/{2921f05a40fda12f9f81.js → a00bba1c7cbf8cd7892c.js} +1 -1
  36. package/assets/esri/core/workers/chunks/a716b8fdeda4e16f03ab.js +1 -0
  37. package/assets/esri/core/workers/chunks/aead7c9830fa310e5b53.js +1 -0
  38. package/assets/esri/core/workers/chunks/{483dc4ee5d73cdfe6229.js → b075d3714fab0591d67c.js} +1 -1
  39. package/assets/esri/core/workers/chunks/{82cc758bddd9f8397b9f.js → b451dc416eebd0931ef8.js} +4 -4
  40. package/assets/esri/core/workers/chunks/b59be95949445ff5afab.js +1 -0
  41. package/assets/esri/core/workers/chunks/b6dec5dfdeca54bae88d.js +1 -0
  42. package/assets/esri/core/workers/chunks/{4356274cfa477eb6d749.js → bfb9cbe59d36d18f9157.js} +1 -1
  43. package/assets/esri/core/workers/chunks/{6afd59412bfc134bdf75.js → c052fb8c952cda0b5d13.js} +1 -1
  44. package/assets/esri/core/workers/chunks/{f2ebd6471e1259a6eac0.js → c9e7cc5d853908ab5b2f.js} +1 -1
  45. package/assets/esri/core/workers/chunks/{97650ee3d0eecb69ccbb.js → d8623f5f13a084e439c2.js} +5 -5
  46. package/assets/esri/core/workers/chunks/dd105d6e0fcedee32644.js +1 -0
  47. package/assets/esri/core/workers/chunks/e1148067ceae7d9eaaf8.js +1 -0
  48. package/assets/esri/core/workers/chunks/{b536fdb655ad293d9024.js → eb6218634a492667506a.js} +1 -1
  49. package/assets/esri/core/workers/chunks/{7804be2f5b3d86188a24.js → edc3d98f33d7bf959154.js} +1 -1
  50. package/assets/esri/core/workers/chunks/eefad79be500667af96e.js +1 -0
  51. package/assets/esri/core/workers/chunks/{63933cbcb5c12df09715.js → f1ac1c8b1331ec79e898.js} +1 -1
  52. package/assets/esri/core/workers/chunks/{2b7f9a57a2cfbc108673.js → f1b99529e2055873b65a.js} +1 -1
  53. package/assets/esri/core/workers/chunks/f693a4d97b2762d0e6ff.js +1 -0
  54. package/assets/esri/core/workers/chunks/f8caceeaa14d99c35526.js +1 -0
  55. package/assets/esri/core/workers/chunks/febce0d80f019dc2a427.js +1 -0
  56. package/assets/esri/libs/lyr3d/lyr3DMain.wasm +0 -0
  57. package/assets/esri/rest/knowledgeGraph/wasmInterface/arcgis-knowledge-client-core-simd.wasm +0 -0
  58. package/assets/esri/rest/knowledgeGraph/wasmInterface/arcgis-knowledge-client-core.wasm +0 -0
  59. package/assets/esri/themes/base/widgets/_Attribution.scss +1 -0
  60. package/assets/esri/themes/dark/main.css +1 -1
  61. package/assets/esri/themes/light/main.css +1 -1
  62. package/assets/esri/themes/light/view.css +1 -1
  63. package/chunks/Magnifier.glsl.js +1 -1
  64. package/chunks/arcgis-knowledge-client-core-simd.js +1 -1
  65. package/chunks/arcgis-knowledge-client-core.js +1 -1
  66. package/chunks/cameraUtilsSpherical.js +1 -1
  67. package/chunks/vec42.js +1 -1
  68. package/config.js +1 -1
  69. package/core/libs/gl-matrix-2/math/quat.js +1 -1
  70. package/core/libs/gl-matrix-2/math/vec4.js +1 -1
  71. package/core/workers/registry.js +1 -1
  72. package/geometry/geometryEngineJSON.js +1 -1
  73. package/geometry/support/aaBoundingRect.js +1 -1
  74. package/geometry/support/buffer/BufferView.js +1 -1
  75. package/geometry/support/buffer/internals/Vec4.js +1 -1
  76. package/geometry/support/coordsUtils.js +1 -1
  77. package/geometry/support/curves/curveUtils.js +1 -1
  78. package/geometry/support/curves/interpolateCurve.js +5 -0
  79. package/geometry/support/meshUtils/Metadata.js +1 -1
  80. package/geometry/support/vector.js +1 -1
  81. package/interfaces.d.ts +134 -420
  82. package/kernel.js +1 -1
  83. package/layers/GaussianSplatLayer.js +1 -1
  84. package/layers/IntegratedMesh3DTilesLayer.js +1 -1
  85. package/layers/IntegratedMeshLayer.js +1 -1
  86. package/layers/SceneLayer.js +1 -1
  87. package/layers/graphics/data/QueryEngine.js +1 -1
  88. package/layers/graphics/data/QueryEngineResult.js +1 -1
  89. package/layers/graphics/sources/support/uploadAssets.js +1 -1
  90. package/package.json +1 -1
  91. package/rest/knowledgeGraph/DataModel.js +1 -1
  92. package/rest/knowledgeGraph/GraphDataModelSingletonOperationResult.d.ts +4 -0
  93. package/rest/knowledgeGraph/GraphDataModelSingletonOperationResult.js +5 -0
  94. package/rest/knowledgeGraph/GraphProperty.js +1 -1
  95. package/rest/knowledgeGraph/wasmInterface/WasmDataModelWrapperInterfaces.js +1 -1
  96. package/rest/knowledgeGraph/wasmInterface/updateToWasmEncodedFactories.js +1 -1
  97. package/rest/knowledgeGraph/wasmInterface/wasmToDataModelChangeResponseFactories.js +1 -1
  98. package/rest/knowledgeGraph/wasmInterface/wasmToDataModelFactories.js +1 -1
  99. package/rest/knowledgeGraphService.d.ts +3 -0
  100. package/rest/knowledgeGraphService.js +1 -1
  101. package/smartMapping/statistics/support/statsWorker.js +1 -1
  102. package/support/revision.js +1 -1
  103. package/views/2d/interactive/SegmentLabels2D.js +5 -0
  104. package/views/3d/GroundView3D.js +1 -1
  105. package/views/3d/analysis/ElevationProfile/ElevationProfileLineSceneComputation.js +1 -1
  106. package/views/3d/analysis/LineOfSight/LineOfSightRayIntersector.js +1 -1
  107. package/views/3d/environment/ChapmanAtmosphere.js +1 -1
  108. package/views/3d/environment/Fog.js +1 -1
  109. package/views/3d/interactive/SegmentLabels3D.js +1 -1
  110. package/views/3d/interactive/visualElements/ExtendedLineVisualElement.js +1 -1
  111. package/views/3d/interactive/visualElements/MeasurementAreaVisualElement.js +1 -1
  112. package/views/3d/interactive/visualElements/MeasurementArrowVisualElement.js +1 -1
  113. package/views/3d/interactive/visualElements/OutlineVisualElement.js +1 -1
  114. package/views/3d/interactive/visualElements/ParallelLineVisualElement.js +1 -1
  115. package/views/3d/interactive/visualElements/PointVisualElement.js +1 -1
  116. package/views/3d/interactive/visualElements/RightAngleQuadVisualElement.js +1 -1
  117. package/views/3d/interactive/visualElements/SlicePlaneVisualElement.js +1 -1
  118. package/views/3d/interactive/visualElements/VerticesVisualElement.js +1 -1
  119. package/views/3d/layers/DrapedSubView3D.js +1 -1
  120. package/views/3d/layers/I3SMeshView3D.js +1 -1
  121. package/views/3d/layers/IntegratedMesh3DTilesLayerView3D.js +1 -1
  122. package/views/3d/layers/IntegratedMeshLayerView3D.js +1 -1
  123. package/views/3d/layers/graphics/Deconflictor.js +1 -1
  124. package/views/3d/layers/graphics/Graphics3DFrustumVisibility.js +1 -1
  125. package/views/3d/layers/graphics/Graphics3DLineSymbolLayer.js +1 -1
  126. package/views/3d/layers/graphics/Graphics3DSymbolLayer.js +1 -1
  127. package/views/3d/layers/graphics/Graphics3DWaterSymbolLayer.js +1 -1
  128. package/views/3d/layers/graphics/graphicUtils.js +1 -1
  129. package/views/3d/layers/i3s/PointCloudRenderer.js +1 -1
  130. package/views/3d/layers/support/FastSymbolUpdates.js +1 -1
  131. package/views/3d/layers/support/Tiles3DIntersectionHandler.js +1 -1
  132. package/views/3d/state/ConstraintsManager.js +1 -1
  133. package/views/3d/state/ViewStateManager.js +1 -1
  134. package/views/3d/support/flow/FlowSubViewTiles3D.js +1 -1
  135. package/views/3d/support/gaussianSplatting/GaussianSplatFadeTexture.js +1 -1
  136. package/views/3d/support/gaussianSplatting/GaussianSplatOrderTexture.js +1 -1
  137. package/views/3d/support/gaussianSplatting/GaussianSplatTextureAtlas.js +1 -1
  138. package/views/3d/support/pointsOfInterest/CenterOnSurface.js +1 -1
  139. package/views/3d/support/pointsOfInterest/PointsOfInterest.js +1 -1
  140. package/views/3d/support/pointsOfInterest/StableSurfaceCenter.js +1 -1
  141. package/views/3d/terrain/Overlay.js +1 -1
  142. package/views/3d/terrain/OverlayManager.js +1 -1
  143. package/views/3d/terrain/PatchRenderData.js +1 -1
  144. package/views/3d/terrain/ScaleRangeQueries.js +1 -1
  145. package/views/3d/terrain/TerrainSurface.js +1 -1
  146. package/views/3d/terrain/TextureFader.js +1 -1
  147. package/views/3d/terrain/TextureReference.js +1 -1
  148. package/views/3d/terrain/Tile.js +1 -1
  149. package/views/3d/webgl/RenderCamera.js +1 -1
  150. package/views/3d/webgl-engine/collections/Component/ComponentObject.js +1 -1
  151. package/views/3d/webgl-engine/collections/Component/Material/ComponentData.glsl.js +18 -12
  152. package/views/3d/webgl-engine/core/shaderLibrary/TextureBackedBuffer.glsl.js +8 -8
  153. package/views/3d/webgl-engine/core/shaderLibrary/TextureBackedBufferFields.glsl.js +7 -12
  154. package/views/3d/webgl-engine/core/shaderLibrary/attributes/VerticalOffset.glsl.js +1 -1
  155. package/views/3d/webgl-engine/core/shaderLibrary/shading/EvaluateAmbientLighting.glsl.js +1 -1
  156. package/views/3d/webgl-engine/core/shaderLibrary/shading/WaterDistortion.glsl.js +1 -1
  157. package/views/3d/webgl-engine/core/shaderLibrary/util/CameraSpace.glsl.js +2 -2
  158. package/views/3d/webgl-engine/core/shaderModules/Texture2DUintDrawUniform.js +5 -0
  159. package/views/3d/webgl-engine/effects/haze/Haze.js +1 -1
  160. package/views/3d/webgl-engine/lib/GaussianSplatRenderNode.js +1 -1
  161. package/views/3d/webgl-engine/lib/MainFramebuffer.js +1 -1
  162. package/views/3d/webgl-engine/lib/PathGeometryData.js +1 -1
  163. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  164. package/views/3d/webgl-engine/lib/ShadowCastRenderer.js +1 -1
  165. package/views/3d/webgl-engine/lib/ShadowMap.js +1 -1
  166. package/views/3d/webgl-engine/lib/TextTextureAtlas.js +1 -1
  167. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBuffer.js +1 -1
  168. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBufferFields.js +1 -1
  169. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBufferLayout.js +1 -1
  170. package/views/3d/webgl-engine/lib/edgeRendering/EdgeRenderer.js +1 -1
  171. package/views/3d/webgl-engine/lib/edgeRendering/EdgeView.js +1 -1
  172. package/views/3d/webgl-engine/lib/edgeRendering/bufferLayouts.js +1 -1
  173. package/views/3d/webgl-engine/materials/DefaultLayouts.js +1 -1
  174. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  175. package/views/3d/webgl-engine/materials/renderers/MergedBuffer.js +1 -1
  176. package/views/3d/webgl-engine/shaders/AnimatedLine.glsl.js +1 -1
  177. package/views/3d/webgl-engine/shaders/ensureColor4.js +1 -1
  178. package/views/3d/webgl-engine/shaders/sources/edgeRenderer/EdgeUtil.glsl.js +18 -18
  179. package/views/Attribution.js +1 -1
  180. package/views/SceneView.js +1 -1
  181. package/views/draw/support/Reshape.js +1 -1
  182. package/views/interactive/SegmentLabels.js +1 -1
  183. package/views/interactive/coordinateHelper.js +1 -1
  184. package/views/interactive/editGeometry/EditGeometry.js +1 -1
  185. package/views/interactive/editGeometry/EditGeometryOperations.js +1 -1
  186. package/views/interactive/editGeometry/operations/SetAllVertexPositions.js +1 -1
  187. package/views/interactive/sketch/constraints.js +1 -1
  188. package/views/interactive/sketch/normalizedPoint.js +1 -1
  189. package/views/support/GroundElevationSampler.js +1 -1
  190. package/widgets/Editor/UpdateFeatureWorkflow.js +1 -1
  191. package/widgets/Editor/Upload.js +1 -1
  192. package/widgets/Editor/components/Settings.js +1 -1
  193. package/widgets/Editor/support/SketchController.js +1 -1
  194. package/widgets/Sketch/SketchViewModel.js +1 -1
  195. package/widgets/Sketch.js +1 -1
  196. package/widgets/support/SelectionList.js +1 -1
  197. package/widgets/support/SketchTooltipControls.js +1 -1
  198. package/assets/esri/core/workers/chunks/089221bac1f019692f48.js +0 -1
  199. package/assets/esri/core/workers/chunks/08957e462d06c4dc8ab5.js +0 -1
  200. package/assets/esri/core/workers/chunks/1bfe0b2bf38d4dee7fd6.js +0 -1
  201. package/assets/esri/core/workers/chunks/22d66d1c8dfccdbbcf30.js +0 -1
  202. package/assets/esri/core/workers/chunks/27bd88e1101873d4ce12.js +0 -1
  203. package/assets/esri/core/workers/chunks/484cd728dd17b8dc1f72.js +0 -1
  204. package/assets/esri/core/workers/chunks/53d95ba86d010231fc4e.js +0 -1
  205. package/assets/esri/core/workers/chunks/61cb30e2e8edd18ebbf0.js +0 -1
  206. package/assets/esri/core/workers/chunks/6c8f5a56e94fdbe6a4a5.js +0 -1
  207. package/assets/esri/core/workers/chunks/745fc2b89fd7d816f2e0.js +0 -1
  208. package/assets/esri/core/workers/chunks/79c7391f00a55e7bcf6b.js +0 -1
  209. package/assets/esri/core/workers/chunks/7f8b85de079614b9c336.js +0 -1
  210. package/assets/esri/core/workers/chunks/a4b7ba8aec109beb5b4d.js +0 -1
  211. package/assets/esri/core/workers/chunks/a5f2da24497349239648.js +0 -1
  212. package/assets/esri/core/workers/chunks/a7b1b42bdb9cb9ecac45.js +0 -1
  213. package/assets/esri/core/workers/chunks/acaaefd4997316d319b8.js +0 -1
  214. package/assets/esri/core/workers/chunks/c6cc3db057da49755d15.js +0 -1
  215. package/assets/esri/core/workers/chunks/cc7c37f9ed3f831fd25c.js +0 -1
  216. package/assets/esri/core/workers/chunks/d14bd320f72d8e8a0ad8.js +0 -1
  217. package/assets/esri/core/workers/chunks/d6d03f22c91f528b97e5.js +0 -1
  218. package/assets/esri/core/workers/chunks/d86e59da76eea888ba86.js +0 -1
  219. package/assets/esri/core/workers/chunks/de99c4fd1582a8e610cf.js +0 -1
  220. package/assets/esri/core/workers/chunks/ded3ef385d5a3a2ec8ca.js +0 -1
  221. package/assets/esri/core/workers/chunks/e3a994587f9b2e88db85.js +0 -1
  222. package/assets/esri/core/workers/chunks/ea5bf896acfcc3106bf5.js +0 -1
  223. package/assets/esri/core/workers/chunks/eab0938d4ad7d7cc7309.js +0 -1
  224. package/assets/esri/core/workers/chunks/ed1dabed10ff9f4e0369.js +0 -1
  225. package/assets/esri/core/workers/chunks/effbc4d240752e8ba0ab.js +0 -1
  226. package/assets/esri/core/workers/chunks/f403d8e414766fab2936.js +0 -1
  227. package/assets/esri/core/workers/chunks/f8a5b26e0231244972d8.js +0 -1
  228. package/chunks/geometryEngineJSON.js +0 -5
  229. package/geometry/geometryEngineAsync.d.ts +0 -39
  230. package/geometry/geometryEngineAsync.js +0 -5
  231. package/geometry/geometryEngineWorker.js +0 -5
  232. package/views/3d/webgl-engine/collections/Component/Material/ComponentDataConstants.js +0 -5
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../../../Color.js";import{filterInPlace as i,difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import{EventedAccessor as n}from"../../../core/Evented.js";import"../../../core/has.js";import l from"../../../core/Logger.js";import{clamp as o}from"../../../core/mathUtils.js";import{destroyMaybe as h}from"../../../core/maybe.js";import{MemCachePool as d}from"../../../core/MemCachePool.js";import p from"../../../core/ObjectPool.js";import u from"../../../core/PooledArray.js";import{throwIfAborted as c,isAbortError as g,isAborted as m}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as y,sync as f,initial as T}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as v}from"../../../core/units.js";import{property as w,subclass as C}from"../../../core/accessorSupport/decorators.js";import{m as S,h as b,d as E}from"../../../chunks/vec32.js";import{create as x}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as L}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as P,radiusModifier as U}from"../../../geometry/ellipsoidUtils.js";import R from"../../../geometry/SpatialReference.js";import{getProjector as M}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as j}from"../../../geometry/projection/projectVectorToVector.js";import{create as I,equals as k,intersection as V,intersectsSphere as A,empty as B,expand as O}from"../../../geometry/support/aaBoundingRect.js";import{copy as G,create as N}from"../../../geometry/support/frustum.js";import{createSpatialReferenceCyclical as q}from"../../../geometry/support/normalizeUtils.js";import{isPlateCarree as F}from"../../../geometry/support/spatialReferenceUtils.js";import{Sphere as W}from"../../../geometry/support/sphere.js";import{ElevationQueryTileCache as H}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{debugFlags as Q}from"../support/debugFlags.js";import{ElevationRange as z}from"../support/ElevationRange.js";import{toBoundingRect as Y}from"../support/extentUtils.js";import{updatingProgress as X}from"../support/updatingProperties.js";import{ElevationBounds as K}from"./ElevationBounds.js";import{ElevationData as J,sampleElevation as Z}from"./ElevationData.js";import{ElevationUpdateEventImplementation as ee}from"./ElevationUpdateEvent.js";import{create as te}from"./ExtentHelper.js";import{LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{Queue as ae}from"./Queue.js";import{ScaleRangeQueries as ne}from"./ScaleRangeQueries.js";import{SphericalPatch as le}from"./SphericalPatch.js";import{SplitLimits as oe}from"./SplitLimits.js";import{maxRootTiles as he,tooManyRootTilesAfterChangeError as de,tooManyRootTilesForLayerError as pe,maxTileNeighborLevelDelta as ue,maxMemoryLodBias as ce}from"./TerrainConst.js";import{TerrainRenderer as ge}from"./TerrainRenderer.js";import me from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as _e,isVectorTileLayerView as ye,neighborEdgeIndices as fe,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as we,isGroupLayerView as Ce,isMapTileLayerView as Se,isBlendableLayerView as be,isElevationLayerView as Ee,releaseTerrainData as xe,enableTerrainInternalChecks as Le,oppositeCorner as Pe,enableWaterproofTests as Ue,enableInternalTerrainChecks as Re,enableTerrainWaterproofChecks as Me,neighborCornerIndices as De}from"./terrainUtils.js";import{Tile as je,lijEquals as Ie}from"./Tile.js";import{printAllocations as ke}from"./TilePerLayerInfo.js";import{sortTiles as Ve,IteratorPreorder as Ae,IteratorPostorder as Be,compareTilesByLij as Oe,hasLoadableSiblings as Ge,sortTilesByPOI as Ne}from"./tileUtils.js";import{TilingSchemeLogic as qe}from"./TilingSchemeLogic.js";import{UpsampleInfo as Fe}from"./UpsampleInfo.js";import{isCompositeBlendMode as We,blendModeFromString as He}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{hasLayerBasedScaleVisibility as $e}from"../../support/layerViewUtils.js";import{ImmediateTask as Qe,TaskPriority as ze,noBudget as Ye}from"../../support/Scheduler.js";import{TextureCompressionTracker as Xe}from"../../support/TextureCompressionTracker.js";import{Yield as Ke}from"../../support/Yield.js";var Je;let Ze=class extends n{static{Je=this}get allTilesCreated(){return this._allTilesCreated}get allTiles(){return a(this._allTiles)}get renderedTiles(){return Ve(i(this._allTiles.toArray(),e=>e.visible&&e.rendered))}get demResolution(){const{_allTiles:e,tilingScheme:t}=this;if(0===e.length)return{min:1,max:1};const i=v(t.spatialReference);let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const a of e){const e=t.resolutionAtLevel(a.level)*i;r=Math.min(r,e),s=Math.max(s,e)}return{min:r,max:s}}constructor(e){super(e),this.terrainTextureCompressionTracker=new Xe,this._iteratorPool=new p(()=>new Ae,e=>e.remove=()=>this._iteratorPool.release(e)),this._postorderIterator=new Be,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._allTilesCreated=!1,this._usedMemory=null,this._performanceInfo=new me,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=x(),this._eyePosSurfaceSR=x(),this._splitLimits=new oe,this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new L,this._frameTask=Qe,this._allTiles=new u,this._upsampleInfoPool=new p(()=>new Fe),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=I(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=R.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationRange=new z(1/0,-1/0),this.rootTileElevationRange=new z(1/0,-1/0),this._projectorCache=new Map,this._tilingSchemeSpatialReference=null,this._updatingRootTiles=!1,this._pendingTilesForElevationUpdateEvent=new Set,this._pendingTilesToUpdate=new Set,this.totalGeometryUpdates=0,this.totalTileUpdates=0,this._oneBatchPerFrameTask=!0,this._layerViewsDirty=!1,this.unloadedMemory=0,this.ignoresMemoryFactor=!1,this._isWebMercator=!1,this._isWebMercatorOnPlateCarree=!1,this.enabled=!0;const{view:t}=e;this.overlayManager=new re({...e,terrainSurface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=P(t.spatialReference),this._renderer=new ge(this.overlayManager.renderer,t.stage,this._allTiles,this.terrainTextureCompressionTracker,t.resourceController.memoryController),$e()||(this._scaleRangeQueries=new ne)}initialize(){const{view:e}=this,{resourceController:t}=e,{memoryController:i}=t;this._tileCache=new d((e,t)=>i.newCache(e,t),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",({tile:e})=>e.unloadMapData()),this._elevationQueryCache=new H(i.newCache("elevation-query"));const r=this.overlayManager;this.addHandles([_(()=>r.renderer.isEmpty,()=>this._evaluateTransparency()),_(()=>this.renderer.visible,e=>this.suspended=!e),_(()=>this.heading,e=>{this._renderer.updateHeading(e),this._updateTileTextures(0)}),_(()=>({heading:e.camera?.heading,state:e.state?.mode}),({heading:e,state:t})=>{if(null==e)return;if(this.isGlobal&&this.isGeographic||this.isWebMercatorOnPlateCarree)return void(this.heading=90*Math.round(e/90)%360);const i=Math.round(e)%360,r=Math.abs(i-this.heading);(2===t||Math.min(r,360-r)>=30)&&(this.heading=i)})],"overlayManager"),this.addHandles([_(()=>this.baseOpacity,()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?1:2)},y),_(()=>this.hasCompositeBlendMode,()=>this._updateTileTextures(this._evaluateTransparency()?1:2),y),_(()=>this.backgroundColor,(e,t)=>{e?.equals(t)||(this._handleLayerViewChanges(),this._renderer.updateTileBackground(e))},f),_(()=>this.snapLevel,()=>this._viewChanged=!0,f),_(()=>this.view.pointsOfInterest,e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add(()=>e.focus?.renderLocation,()=>this._allTilesSorted=!1,{equals:S})}),_(()=>Q.TERRAIN_TILE_TREE_SHOW_TILES,t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then(({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&Q.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))}):t||(this._treeDebugger=h(this._treeDebugger))},T)]);const{spatialReference:a}=e;this._extentHelper=te(this.viewingMode,{layers:e.map.allLayers,layerViews:e.allLayerViews,viewSpatialReference:a});const n=new s({getCollections:()=>e.defaultsFromMap?.mapCollections?.map(({layers:e})=>e),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),l=new qe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme();const o=t.scheduler;this._frameTask=o.registerTask(ze.TERRAIN_SURFACE,this),this.addHandles([_(()=>this._extentHelper.stencilEnabledExtents,e=>this._renderer.setStencilEnabledLayerExtents(e),T),_(()=>this.tilingSchemeLogic.tilingScheme,()=>this._updateTilingScheme(),f),_(()=>this.extent,()=>this._updateRootTiles(),T),e.on("resize",()=>this._viewChangeUpdate()),_(()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]},()=>this._viewChangeUpdate(),y),_(()=>e.qualitySettings?.fadeDuration,e=>this._renderer.textureFadingEnabled=e>0,T),_(()=>e.qualitySettings?.physicallyBasedRenderingEnabled,e=>this._renderer.pbrMode=e?5:0,T),_(()=>e.qualitySettings?.tiledSurface.elevationLevelDelta,()=>this._updateAllTileGeometries()),_(()=>this._userClippingExtent,()=>this._updateClippingExtent(),f)]),this.addHandles(e.allLayerViews.on("after-changes",()=>this._layerViewsDirty=!0)),this._layerViewsDirty=!0,this._handleLayerViewChanges(),this._renderer.updateTileBackground(this.backgroundColor)}clearHandles(){this._watchUpdatingTracking?.removeAll(),this.removeAllHandles(),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear()}destroy(){this._frameTask.remove(),this._frameTask=Qe,this._watchUpdatingTracking?.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear(),this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),this._allTiles.prune(),je.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroyed||this._renderer.destroy(),this._renderer=null,this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),ke(),this._layerViews.forEach(e=>e.length=0),this._performanceInfo=null}get renderer(){return this._renderer}get frustum(){return this.view.state.camera.frustum}get snapLevel(){return this.lodSnappingEnabled?this.view.terrainLevel:null}get lodSnappingEnabled(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get hasStencilEnabledExtents(){return this._extentHelper.stencilEnabledExtents.length>0}get _userClippingExtent(){const{spatialReference:e}=this,t=this.view?.clippingArea;if(null==t||null==e)return null;const i=I(),r=Y(t,i,e)?i:null,s=this._get("extent");return k(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=V(this.groundExtent,this._userClippingExtent,I()),t=this._get("extent");return k(e,t)?t:e}get groundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),this.enabled&&!!((this.readyToRun||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get readyToRun(){return this.enabled&&(this._hasPendingUpdates||this._viewChanged||this._allTilesDirty||!this._allTilesSorted||this._layerViewsDirty||this._scaleRangeQueries?.updating||this._frameTask.updating)&&this.ready&&!this.suspended}get updatingProgressValue(){return this._maxNumUpdating=Math.max(this._pendingUpdates,this._maxNumUpdating),1-this._pendingUpdates/this._maxNumUpdating}get baseOpacity(){return this.view?.map?.ground?.opacity??1}set baseOpacity(e){this.view.map.ground.opacity=e}get viewingMode(){return this.view.state.viewingMode}get ready(){return!this.enabled||null!=this._rootTiles}get rootTiles(){return this._rootTiles}get spatialReference(){return this.tilingScheme?.spatialReference??null}get backgroundColor(){return this.view?.map?.ground?.surfaceColor}set backgroundColor(e){this.view.map.ground.surfaceColor=e}set slicePlaneEnabled(e){this._renderer.slicePlaneEnabled=e,this._set("slicePlaneEnabled",e),this._evaluateTransparency()}get tilingSchemeLocked(){return this.tilingSchemeLogic?.tilingSchemeLocked??!1}get wireframe(){return this._renderer?.wireframe}set wireframe(e){e!==this._renderer.wireframe&&(this._renderer.wireframe=e,this._updateAllTileGeometries())}get opaque(){return 0===this._renderer.transparency}get invisible(){return 3===this._renderer.transparency}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get fadeDuration(){return this.view.qualitySettings.fadeDuration??0}intersect(e,t,i,r){this._renderer.intersect(e,t,i,r)}getElevationLevelDelta(e){return e<4?3:this.view.qualitySettings.tiledSurface.elevationLevelDelta}get _xNormalizer(){return q(this._spatialReference)}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length||!this.enabled)return null;if(0===s[0].layerInfo[0].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=M(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return l.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const n=b(tt,e,t,i);a(n,0,n,0);return lt(s,this._xNormalizer?.normalize(n[0])??n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[0].length:0;if(r?.length&&0!==s&&this.enabled)for(let a=0;a<t;++a){const t=3*a;i(a,lt(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getLayerIndexByUID(e,t){return this._layerIndexByUid[e].get(t)}getScale(e){if(!this.tilingScheme)return null;if(!D(e,tt,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getScale(): could not project given point to tiling scheme coordinate system"),null;const t=this._rootTiles;if(null!=t)for(const i of t)if(i?.containsPoint(tt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;tt[0]>t[2]&&(i+=1),tt[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}_ensureProjector(e){const t=this._projectorCache.get(e);if(t)return t;const i=M(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationRange(e,t){if(!this.enabled||null==this._rootTiles)return null;const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationRange(): could not project given point to tiling scheme coordinate system"),null;it.copy(e),i(it.center,0,it.center,0);const r=new z,s=this._rootTiles;if(null!=s){const e=[];for(const i of s)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,it))continue;const s=i.children;if(null==s[0]||i.rendered)r.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of s)e.push(t)}}return r}getRootElevationRange(){return this.enabled&&null!=this._rootTiles?new z(this.rootTileElevationRange.minElevation,this.rootTileElevationRange.maxElevation):null}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationRange.minElevation)*U;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,it.center,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;it.radius=t;let i=null;const r=e=>{if(e&&A(e.extent,it)){const t=e.children;if(t[0]&&!e.rendered)for(const e of t)r(e);else{const t=this._getLodBiasCorrectedScale(e.level);i=null==i?t:Math.min(i,t)}}},s=this._rootTiles;if(null!=s)for(const a of s)r(a);return i}queryVisibleScaleRange(e,t,i,r){if(!this._scaleRangeQueries)return;const s=t?this.tilingScheme.levelAtScale(t):0,a=i?this.tilingScheme.levelAtScale(i):1/0,n=this._lodBias;this._scaleRangeQueries.queryVisibleLevelRange(e,s+n,a+n,r)}_evaluateTransparency(){const e=this.baseOpacity,t=this.overlayManager.renderer.isEmpty,i=this._renderer.transparency,r=this._isFullyTransparent?t?3:2:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?0:1;return this._renderer.transparency=r,i!==r}_updateTilingScheme(){const{tilingScheme:e}=this.tilingSchemeLogic;if(!(e!==this.tilingScheme))return;_e(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??R.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&F(this.view?.renderSpatialReference),this._isGeographic=t?.isGeographic??!1,this._set("tilingScheme",e),this._tilingSchemeSpatialReference=this.tilingScheme?.spatialReference,this._projectorCache.clear(),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.tileSize=e.pixelSize,this.overlayManager.spatialReference=e.spatialReference,this._updateRootTiles())}static{this._tileMemcacheKey="TerrainTileMemcache"}_acquireTile(e,t,i,r){const s=this._tileCache.pop(Je._tileMemcacheKey);return s?(s.init(e,t,i,r,this),s):new this._tileConstructor(e,t,i,r,this)}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{extent:e,tilingScheme:t}=this;if(!t)return;const i=rt;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void l.getLogger(this).warn(de);const e=this._rootTiles.map(e=>e.lij),t=r(e,s,Ie);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter(e=>!(t.removed.findIndex(t=>Ie(t,e.lij))>-1)||(this._purgeTile(e),!1));t.added.forEach(t=>e.push(this._newRootTile(t))),this._setRootTiles(e)}}else this._updatingRootTiles=!0,s.length>he&&(l.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map(e=>this._newRootTile(e)));k(i,this._rootTilesExtent)||(this._rootTilesExtent=I(i)),this.renderer.visible=!0,this._viewChangeUpdate(),this.overlayManager.setPlacementDirty(),this.notifyChange("ready"),this._updateAllTileGeometries(),this._updatingRootTiles=!1,this.checkAllTilesWaterproofness()}_updateAllTileGeometries(){const e=this._allTiles.filter(e=>e.loaded&&e.intersectsClippingArea);e.sort(Oe),e.forEach(e=>this._renderer.updateTileGeometryState(e)),e.forEach(e=>e.renderData.updateNeighborData()),this._updateTilesGeometries(e),this._pendingTilesToUpdate.clear()}_updateTilesGeometries(e){if(0===e.length)return;e.sort(Oe);const t=this.renderer;e.forEach(e=>t.updateGeometryIfNeeded(e)),e.forEach(e=>this._pendingTilesForElevationUpdateEvent.add(e))}_shouldSplit(e){return 1===e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(1),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationRange(),t}_setRootTiles(e){if(this._rootTiles=e,this._allTiles.clear(),null!=e){const t=this._iteratorPool.acquire();for(t.reset(e);!t.done;)this._allTiles.push(t.next());t.remove()}this._renderer.setRootTiles(this._rootTiles),this._updateTilesVisibility(e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this.renderer.visible&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.extent)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Ge(e),i=this.visibleElevationRange;let r=t?i.minElevation:1/0,s=t?i.maxElevation:-1/0;const a=this.extent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty(!1);const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBoundsMin,r),s=Math.max(e.elevationBoundsMax,s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._updatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.minElevation!==r||i.maxElevation!==s)&&(this.visibleElevationRange=new K(r,s))}_updateRootTileElevationRange(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach(({elevationBoundsMin:i,elevationBoundsMax:r})=>{e=Math.min(e,i),t=Math.max(t,r)});const r=this.rootTileElevationRange;r.minElevation===e&&r.maxElevation===t||(this.rootTileElevationRange=new K(e,t))}_updateViewDependentParameters(){const{camera:e,contentCamera:t}=this.view.state,i=Math.tan(.5*t.fovX),r=Math.tan(.5*t.fovY),s=this.tilingScheme.pixelSize,a=2**-this._lodBias*e.pixelRatio;this._splitLimits.aboveGround=e.aboveGround,this._splitLimits.fovX=i,this._splitLimits.fovY=r,this._splitLimits.relativeWidthLimit=s/e.width*this.maxTextureScale*a,this._splitLimits.relativeHeightLimit=s/e.height*this.maxTextureScale*a,this._splitLimits.maxLod=this.tilingScheme.getMaxLod(),this._splitLimits.angledSplitBias=this.view.qualitySettings.tiledSurface.angledSplitBias,this.view.state.fixedContentCamera?this._splitLimits.frustum=G(this._splitLimits.frustum??N(),t.frustum):this._splitLimits.frustum=null,E(this._eyePosRenderSR,t.eye),j(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateTileGeometryState(e){e.updateVisibility();this._renderer.updateTileGeometryState(e)&&this._markTileToUpdate(e),this.setMemoryDirty()}_markAllTileNeighborsForUpdate(e){e.forEachLoadedNeighbor(e=>{this._layerViews[1].some(ye)&&e.setPendingUpdate(32),this._pendingTilesToUpdate.add(e)})}_updateTileTexture(e,t){const i=e.resetPendingUpdate(32)?32:!!e.resetPendingUpdate(16)&&16;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=at.extent;B(e),this._pendingTilesForElevationUpdateEvent.forEach(t=>O(e,t.extent,e)),this._pendingTilesForElevationUpdateEvent.clear(),at.spatialReference=this.spatialReference,this.emit("elevation-change",at),this._shouldEmitChangeEvent=!1}runTask(e){this._handleLayerViewChanges(e),this._frameTask.processQueue(e),this.renderer.processScaleRangeQueries(this._scaleRangeQueries,e),this._inFrameTask=!0,this._pendingUpdates=0,this._hasPendingUpdates=!1,this._updateAllTilesStatus(e),this._sortTiles(e);const t=!this.view.state.fixedContentCamera;if(this._mergeAndSplit(e,t),this._updateElevation(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty(),this._updatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&e.hasProgressed&&this.requestUpdate(),this.notifyChange("updatingProgressValue"),Le&&this._checkTileInvariant(),!e.hasProgressed)return Ke}_checkTileInvariant(){const e=new Map;this._allTiles.forAll(t=>e.set(t,new Set)),this._allTiles.forAll(t=>{if(_e(t.rendered===t.leaf,` rendered ${t.rendered} != ${t.leaf} leaf`),!t.leaf){const e=e=>0===e.unmergableChildCount&&0===e.maxLevelDeltaNeighborCount,i=t.children.reduce((t,i)=>t+(e(i)?0:1),0);if(_e(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(4)){_e(!t.hasPendingUpdate(1),"Tile can be both split and merge at the same time");for(const e of t.children)_e(e.leaf||e.hasPendingUpdate(4),"Child of tile to merge must also merge")}}for(let i=0;i<4;++i){if(t.rendered){const e=t.renderData?.geometryState.edgePeerNeighbors[i];if(null!=e){{const r=t.level-e.level<=ue;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ue} (edge[${i}])`),_e(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}_e(t.level-e.level<=ue,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ue,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(fe[i],s);if(null!=a){if(t.leaf&&t.level>=ue){let i=a;for(;t.level-i.level<ue;)i=i.parent;const s=[r,t.lij[1]>>ue,t.lij[2]>>ue];if(!Ie(s,i.lij)){const r=e.get(i);_e(!r.has(t),"Cannot already have neighbor"),r.add(t)}}_e(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),_e(t.level-a.level<=ue,`Tile level delta [${t.level}] vs [${a.level}] > ${ue}`)}}}),this._allTiles.forAll(t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);_e(i===r.size,`Tile[${t.lij.toString()}] merge-blocker mismatch: actual ${i} vs ${r.size}`)})}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;const t=new ae(this._allTiles.length);t.pushAll(this._rootTiles);const i=this.snapLevel,r=this._splitLimits,s=this._eyePosRenderSR;this._allTiles.forAll(e=>{e.maxLevelDeltaNeighborCount=0,e.unmergableChildCount=0});const a=this.view.state.contentCamera.viewProjectionMatrix;for(;!t.empty;){const e=t.pop(),n=e.parent,l=n?.hasPendingUpdate(4),o=l?4:e.shouldSplit(r,s,i),h=1===o;e.leaf?ot(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(1),e.leaf||e.setPendingUpdate(4),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1)):(e.resetPendingUpdate(1)&&e.updateAgentSuspension(),2===o&&e.updateAgents(0),e.leaf||(e.setPendingUpdate(4),e.resetPendingUpdate(1)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||!this.view.pointsOfInterest?.focus||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger?.update(),e.madeProgress())}_markTileToUpdate(e){Te(e.loaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForUpdate(e))}_updatePendingTileGeometries(){const e=this._pendingTilesToUpdate,t=Array.from(e.keys()).filter(e=>e.loaded&&e.intersectsClippingArea);if(0===t.length)return void e.clear();const i=(i,r)=>{!r?.loaded||!r.intersectsClippingArea||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Oe);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Te(r.loaded),Te(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=De[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(Pe(t),e=>e.loaded))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(ve(fe[t]),t=>!(!t.loaded||!t.intersectsClippingArea)&&(Te(e.has(t)||Oe(r,t)<0),i(r,t),!0)),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,Le&&Ue&&this.checkAllTilesWaterproofness()}_mergeAndSplit(e,t){if(this.suspended||e.done||!this._allTilesDirty)return;this._allTilesDirty=!1,this.requestUpdate();let i=!1;const r=this.view.state.fixedContentCamera;let s=!1;for(;!e.done;){s=!0;let a=!1;const n=!this._allTiles.some(s=>{if(!i&&!r&&!s.visible)return e.done;let n=s;if(s.hasPendingUpdate(4)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(4);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(4);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(1)){let t=!0;const i=s.level;if(i>=ue){const e=e=>e.leaf||i-e.level<ue;for(let r=0;r<4;++r){const a=s.findNeighborTile(fe[r],e);null!=a&&i-a.level===ue&&(t=!1,Le&&(Te(a.leaf),Te(a.hasPendingUpdate(1))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(1)}return e.done});if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries()),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries(),this._allTilesCreated=!this.allTiles.some(e=>e.hasPendingUpdate(1)||e.hasPendingUpdate(4)),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some(t=>(t.resetPendingUpdate(8)&&(this._updateTileGeometryState(t),this._shortBatches&&this._updatePendingTileGeometries(),e.madeProgress()),e.done)),!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries())}_updateTextures(e){e.done||this._allTiles.some(t=>(this._updateTileTexture(t,e),e.done))}_updateClippingExtent(){this.spatialReference&&(this.updateOverlayParameters(),this.requestRender(1),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){return this.view.qualitySettings.tiledSurface.lodBias-(1-this.view.quality)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=o(e-this._lodBias,0,t.length-1),r=i-Math.floor(i);return t[Math.floor(i)].scale*(1-r)+t[Math.ceil(i)].scale*r}_removeAllTiles(){null!=this._rootTiles&&(this._rootTiles.forEach(e=>this._purgeTile(e)),this._setRootTiles(null),this.notifyChange("ready")),this._allTiles.clear(),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),this.renderer.visible=!1}_purgeSubtree(e){const t=e.children;t[0]&&(this._purgeTile(t[0]),this._purgeTile(t[1]),this._purgeTile(t[2]),this._purgeTile(t[3]),e.clearChildren())}_purgeTile(e){e.leaf?dt(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(Je._tileMemcacheKey,e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){_e(e.leaf,"Tile that is already split should not be split again!"),_e(e.rendered,"Tile marked to split is not rendered"),dt(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),_e(e.rendered,"parent should be rendered"),t.forEach(e=>this._loadTile(e)),t.forEach(e=>this._pendingTilesToUpdate.add(e)),this._unloadTile(e),this._markAllTileNeighborsForUpdate(e),this._emitTileScaleChange(e,e.level+1),this._allTilesDirty=!0,this._shortBatches&&this._updatePendingTileGeometries(),t.forEach(e=>ot(e,e.hasPendingUpdate(1))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){nt.spatialReference=this.spatialReference,nt.extent=e.extent,nt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",nt)}createTile(e,t,i,r){_e(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.extent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(1),s}get _shortBatches(){return 2!==this.view.state.mode}_mergeTile(e){_e(!e.hasPendingUpdate(1),"_mergeTile sanity check"),_e(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),_e(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),ot(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&e.updateOverlayParameters(this.overlayManager)}_handleLayerViewChanges(e=Ye){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(let s=this.view.allLayerViews.length-1;s>=0;s--){const e=this.view.allLayerViews.items[s];if(i.add(e.uid),we(e)||Ce(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Ce(e)){const i=this._layerClassFromLayerView(e),s=this.getLayerIndexByUID(i,e.uid);null!=s&&((s<r||null==r)&&(t=!0),r=s)}else this._registerTiledLayerView(e),e.layer.loaded&&(t=!0)}this._basemapLayerViewHandles.forEach((e,r)=>{i.has(r)||(this._unregisterTiledLayerView(r),t=!0)}),t&&this._updateTiledLayers(),this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._evaluateTransparency(),e.madeProgress()}get _isFullyTransparent(){if(this.view.map?.ground?.opacity>0)return!1;for(const e of this.view.allLayerViews.items)if(Se(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((be(e)||Ce(e))&&We(He[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Ee(e)?0:1}_registerTiledLayerView(e){const t=[];if((be(e)||Ce(e))&&t.push(_(()=>e.layer.blendMode,()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(2)})),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_(()=>!e.destroyed&&e.suspended,()=>this._updateTiledLayers())),t.push(_(()=>!e.destroyed&&e.fullOpacity,()=>this._updateTileTextures(2)));const{layer:r}=e;"effectiveScaleRange"in r&&t.push(_(()=>!e.destroyed&&r.effectiveScaleRange,()=>this._restartAllAgents(i))),t.push(e.on("data-changed",()=>{const t=this.getLayerIndexByUID(i,e.uid);null!=t&&this._invalidateLayerData(t,i)}))}this._unregisterTiledLayerView(e.uid),this._basemapLayerViewHandles.set(e.uid,t)}_unregisterTiledLayerView(e){const t=this._basemapLayerViewHandles.get(e);if(t){for(const e of t)e.remove();this._basemapLayerViewHandles.delete(e)}}_updateTiledLayers(){if(!this.tilingScheme||this.view.suspended)return;const e=this.view.allLayerViews,t=[[],[]];let i=null;e.forEach(e=>{if(!e.layer||e.suspended||!we(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(1===r){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)});for(const r of ie){const e=this._layerViews[r],i=t[r];i.reverse();const s=i.length;let a=e.length!==s;const n=new Array(s),l=new Array(e.length);this._layerIndexByUid[r].clear();for(let t=0;t<s;t++){const s=i[t].uid;this._layerIndexByUid[r].set(s,t);const o=e.indexOf(i[t]);n[t]=o,t!==o&&(a=!0),o>-1&&(l[o]=t)}if(a){const e=this._postorderIterator;for(e.reset(this._rootTiles);!e.done;)e.next().modifyLayers(l,n,r);this._layerViews[r]=i,this._restartAllAgents(r),this._updateTilesVisibility(this._rootTiles)}}this.tilingScheme.ensureMaxLod(i)&&(this._viewChangeUpdate(),this.notifyChange("tilingScheme"))}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),0===e&&i.computeElevationBounds()}this._updateRootTileElevationRange()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll(t=>{t.updateAgents(1),1===e?this.renderer.updateTileTexture(t,16):t.updateRenderData(1,e)}),this._evaluateTransparency()}_invalidateLayerData(e,t){this._allTiles.forAll(i=>i.removeLayerAgent(e,t)),this._allTiles.forAll(i=>i.invalidateLayerData(e,t))}setTileTreeDirty(e){this._allTilesDirty=!0,e&&(this._allTilesCreated=!1)}requestRender(e=1){this.renderer.setNeedsRender(e)}requestUpdate(){1===++this._pendingUpdates&&(this._hasPendingUpdates=!0)}requestTileData(e,t,i,r){const s=this.layerViewByIndex(t,i),a=s.layer;return!a.tilemapCache||ye(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.level,e.lij[1],e.lij[2],{...r,timeout:6e3}).then(()=>--this._asyncWorkItems).catch(t=>{throw--this._asyncWorkItems,c(r),g(t)||this._dataMissing(e,i,s),t}).then(()=>this._frameTask.schedule(()=>this._requestTileData(e,i,s,r),r.signal)))}_requestTileData(e,t,i,r){if(this.destroying)return Promise.resolve();return 0===t?Ee(i)?this._requestElevationTileData(e,i,r):Promise.reject():Se(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!m(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{g(i)||(l.getLogger(this).error(`Tile ${e.lij.toString()} layer 0/${t.uid} error ${i}`),this._dataMissing(e,0,t),this.requestUpdate())};return t.fetchElevationTile(e,i).then(e=>this._frameTask.schedule(()=>r(e)),s).finally(()=>--this._asyncWorkItems)}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[0].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",0,e.lij.toString());const s=new J(e.lij,e.extent,i);e.dataArrived(r,0,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:0});const a=[e],n=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,n),e.computeElevationBounds()}0===n&&this._updateRootTileElevationRange(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{xe(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer 1/${t.uid} error ${r}`),this._dataMissing(e,1,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule(()=>{this.requestUpdate(),m(i)?xe(r):this._mapTileDataArrived(e,t,r)},i.signal,s(r)).catch(s(r)),n=(e,t=null)=>this._frameTask.schedule(()=>r(e,t));return t.fetchTile(e.lij,i).then(a,n).finally(()=>--this._asyncWorkItems)}_mapTileDataArrived(e,t,i){const r=this.getLayerIndexByUID(1,t.uid);if(null==r)return xe(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,1,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:1})}_dataMissing(e,t,i){const r=this.getLayerIndexByUID(t,i.uid);null!=r?(e.dataMissing(r,t),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:t})):l.getLogger(this).warn("TerrainSurface: received data from unknown layer")}get performanceInfo(){const e=this._performanceInfo;return e.numNodes=this._allTiles.length,e.numLeaves=e.numVisible=e.numRendered=e.numLoadedPerLevel.length=e.numRenderedPerLevel.length=0,this._allTiles.forAll(t=>{t.leaf&&e.numLeaves++;const i=t.level;t.renderData&&(e.numLoadedPerLevel[i]=(e.numLoadedPerLevel[i]||0)+1),t.visible&&(e.numVisible++,t.rendered&&(e.numRenderedPerLevel[i]=(e.numRenderedPerLevel[i]||0)+1,e.numRendered++))}),e}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this.tilingScheme?(null==this._usedMemory&&(this._usedMemory=this._recalculateUsedMemory()),this._usedMemory??0):0}_recalculateUsedMemory(){return this.tilingScheme?Math.round(this._allTiles.reduce((e,t)=>e+t.usedMemory,0)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this.getLayerIndexByUID(i,e.uid);return null!=r&&this._allTiles.forAll(e=>t+=e.getUsedMemoryForLayer(i,r)),t}get renderPatchBorders(){return this._renderer.renderPatchBorders}set renderPatchBorders(e){this._renderer.renderPatchBorders=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!Ue)return;const e=this._rootTiles;if(null==e)return;const t=e=>e?.renderData?.geometry?.indices?.length>0,i=(e,i)=>{t(e)&&console.error("Tile[",e.lij,"] has geometry although parent[",i.lij,"] has geom")},r=e=>{if(e.intersectsClippingArea)if(e.renderData&&!e.renderData.geometryState&&console.error("Tile[",e.lij,"] has renderData but not geometryState"),e.renderData&&!e.renderData.geometry&&console.error("Tile[",e.lij,"] has renderData but not geometryInfo"),!e.renderData?.geometry||(e.renderData.geometry.indices?.length??0)>0||console.error("Tile[",e.lij,"] has renderData but no indices - geometryInfo: ",e.renderData.geometry),t(e)){e.checkGeometryWaterproofness();for(const t of e.children)i(t,e)}else if(e.leaf)console.error("Tile[",e.lij,"] has no geometry and no children, from root to leaf");else for(const t of e.children)r(t)},s=e=>{const t=e.parent?.visible??!0,i=e.visible;e.computeVisibility();const r=e.visible;if(i!==r&&t&&console.error(" Tile[",e.lij,"] has out of date visibility: ",i," instead of ",r),!e.leaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isGeographic(){return this._isGeographic}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateCarree(){return this._isWebMercatorOnPlateCarree}isEastEndWrap(e){return this._isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this._isGlobal&&0===e[2]}lijEastEnd(e){return 1<<e+(this._isGeographic?1:0)}wrapEastWest(e){const t=this.lijEastEnd(e[0]),i=e[2];if(0<=i&&i<t)return e;if(!this._isGlobal)return null;const r=(i+(i<0?t:0))%t;return[e[0],e[1],r]}enableInternalChecks(e){Re(e)}enableWaterproofnessChecks(e){Me(e)}static cleanupTerrainSurface(){st.prune()}enable(e){e!==this.enabled&&(e?(this._updateRootTiles(),this.suspended=!1):(this.suspended=!0,this._removeAllTiles(),this._setRootTiles(null)),this._set("enabled",e),this.notifyChange("ready"))}updateOverlayParameters(){const{overlayManager:e}=this;this.allTiles.forAll(t=>t.updateOverlayParameters(e))}};e([w()],Ze.prototype,"_renderer",void 0),e([w({constructOnly:!0})],Ze.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],Ze.prototype,"view",void 0),e([w({constructOnly:!0})],Ze.prototype,"overlayManager",void 0),e([w({constructOnly:!0})],Ze.prototype,"terrainTextureCompressionTracker",void 0),e([w()],Ze.prototype,"_hasPendingUpdates",void 0),e([w()],Ze.prototype,"_asyncWorkItems",void 0),e([w()],Ze.prototype,"_allTilesDirty",void 0),e([w()],Ze.prototype,"_allTilesSorted",void 0),e([w()],Ze.prototype,"_allTilesCreated",void 0),e([w()],Ze.prototype,"_viewChanged",void 0),e([w({type:Number})],Ze.prototype,"heading",void 0),e([w()],Ze.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],Ze.prototype,"_watchUpdatingTracking",void 0),e([w()],Ze.prototype,"_frameTask",void 0),e([w()],Ze.prototype,"demResolution",null),e([w({readOnly:!0})],Ze.prototype,"snapLevel",null),e([w({readOnly:!0})],Ze.prototype,"lodSnappingEnabled",null),e([w()],Ze.prototype,"_userClippingExtent",null),e([w()],Ze.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],Ze.prototype,"extent",null),e([w({readOnly:!0})],Ze.prototype,"groundExtent",null),e([w({readOnly:!0})],Ze.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],Ze.prototype,"updating",null),e([w({readOnly:!0})],Ze.prototype,"readyToRun",null),e([w(X)],Ze.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],Ze.prototype,"updatingProgressValue",null),e([w()],Ze.prototype,"_maxNumUpdating",void 0),e([w()],Ze.prototype,"baseOpacity",null),e([w()],Ze.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],Ze.prototype,"viewingMode",null),e([w()],Ze.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],Ze.prototype,"ready",null),e([w({readOnly:!0})],Ze.prototype,"rootTiles",null),e([w()],Ze.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],Ze.prototype,"spatialReference",null),e([w({type:t})],Ze.prototype,"backgroundColor",null),e([w({value:!1})],Ze.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],Ze.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],Ze.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],Ze.prototype,"tilingSchemeLogic",void 0),e([w()],Ze.prototype,"wireframe",null),e([w({value:!1})],Ze.prototype,"suspended",null),e([w()],Ze.prototype,"fadeDuration",null),e([w()],Ze.prototype,"_xNormalizer",null),e([w()],Ze.prototype,"visibleElevationRange",void 0),e([w()],Ze.prototype,"rootTileElevationRange",void 0),e([w()],Ze.prototype,"_layerViewsDirty",void 0),e([w()],Ze.prototype,"renderPatchBorders",null),e([w()],Ze.prototype,"renderingDisabled",null),e([w({readOnly:!0})],Ze.prototype,"enabled",void 0),Ze=Je=e([C("esri.views.3d.terrain.TerrainSurface")],Ze);const et=Ze,tt=x(),it=new W,rt=I(),st=new u,at=new ee("ground"),nt={spatialReference:null,extent:null,scale:0};function lt(e,t,i){for(const r of e){if(!r.containsPointXY(t,i))continue;let e=r;for(;e&&!e.renderData;){const r=(t>e.extentMidX?1:0)+(i<e.extentMidY?2:0);e=e.children[r]}const s=e?.renderData?.geometryState.samplerData??null;return Z(t,i,s)}return null}function ot(e,t){!e.leaf||e.level<ue||ut(e,e=>{t&&ht(e);const i=pt(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=pt(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}})}function ht(e){if(e.hasPendingUpdate(1))return;let t=e.parent;for(;t?.resetPendingUpdate(4);)t=t.parent;e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1),e.level<ue||ut(e,e=>{ht(e)})}function dt(e){e.level<ue||ut(e,e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,pt(t));)t=t.parent}})}function pt(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function ut(e,t){if(e.level<ue)return;const i=e.level-ue,r=e.lij[1]>>ue,s=e.lij[2]>>ue,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(fe[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{et as default};
5
+ import{__decorate as e}from"tslib";import t from"../../../Color.js";import{filterInPlace as i,difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import{EventedAccessor as n}from"../../../core/Evented.js";import"../../../core/has.js";import l from"../../../core/Logger.js";import{clamp as o}from"../../../core/mathUtils.js";import{destroyMaybe as h}from"../../../core/maybe.js";import{MemCachePool as d}from"../../../core/MemCachePool.js";import p from"../../../core/ObjectPool.js";import u from"../../../core/PooledArray.js";import{throwIfAborted as c,isAbortError as g,isAborted as m}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as f,sync as y,initial as T}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as v}from"../../../core/units.js";import{property as w,subclass as C}from"../../../core/accessorSupport/decorators.js";import{m as S,h as b,d as E}from"../../../chunks/vec32.js";import{create as x}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as L}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as P,radiusModifier as R}from"../../../geometry/ellipsoidUtils.js";import U from"../../../geometry/SpatialReference.js";import{getProjector as M}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as j}from"../../../geometry/projection/projectVectorToVector.js";import{create as I,equals as k,intersection as V,intersectsSphere as A,empty as B,expand as O}from"../../../geometry/support/aaBoundingRect.js";import{copy as G,create as N}from"../../../geometry/support/frustum.js";import{createSpatialReferenceCyclical as q}from"../../../geometry/support/normalizeUtils.js";import{isPlateCarree as F}from"../../../geometry/support/spatialReferenceUtils.js";import{Sphere as W}from"../../../geometry/support/sphere.js";import{ElevationQueryTileCache as H}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{debugFlags as Q}from"../support/debugFlags.js";import{ElevationRange as z}from"../support/ElevationRange.js";import{toBoundingRect as Y}from"../support/extentUtils.js";import{updatingProgress as X}from"../support/updatingProperties.js";import{ElevationBounds as K}from"./ElevationBounds.js";import{ElevationData as J,sampleElevation as Z}from"./ElevationData.js";import{ElevationUpdateEventImplementation as ee}from"./ElevationUpdateEvent.js";import{create as te}from"./ExtentHelper.js";import{LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{Queue as ae}from"./Queue.js";import{ScaleRangeQueries as ne}from"./ScaleRangeQueries.js";import{SphericalPatch as le}from"./SphericalPatch.js";import{SplitLimits as oe}from"./SplitLimits.js";import{maxRootTiles as he,tooManyRootTilesAfterChangeError as de,tooManyRootTilesForLayerError as pe,maxTileNeighborLevelDelta as ue,maxMemoryLodBias as ce}from"./TerrainConst.js";import{TerrainRenderer as ge}from"./TerrainRenderer.js";import me from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as _e,isVectorTileLayerView as fe,neighborEdgeIndices as ye,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as we,isGroupLayerView as Ce,isMapTileLayerView as Se,isBlendableLayerView as be,isElevationLayerView as Ee,releaseTerrainData as xe,enableTerrainInternalChecks as Le,oppositeCorner as Pe,enableWaterproofTests as Re,enableInternalTerrainChecks as Ue,enableTerrainWaterproofChecks as Me,neighborCornerIndices as De}from"./terrainUtils.js";import{Tile as je,lijEquals as Ie}from"./Tile.js";import{printAllocations as ke}from"./TilePerLayerInfo.js";import{sortTiles as Ve,IteratorPreorder as Ae,IteratorPostorder as Be,compareTilesByLij as Oe,hasLoadableSiblings as Ge,sortTilesByPOI as Ne}from"./tileUtils.js";import{TilingSchemeLogic as qe}from"./TilingSchemeLogic.js";import{UpsampleInfo as Fe}from"./UpsampleInfo.js";import{isCompositeBlendMode as We,blendModeFromString as He}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{hasLayerBasedScaleVisibility as $e}from"../../support/layerViewUtils.js";import{ImmediateTask as Qe,TaskPriority as ze,noBudget as Ye}from"../../support/Scheduler.js";import{TextureCompressionTracker as Xe}from"../../support/TextureCompressionTracker.js";import{Yield as Ke}from"../../support/Yield.js";var Je;let Ze=class extends n{static{Je=this}get allTilesCreated(){return this._allTilesCreated}get allTiles(){return a(this._allTiles)}get renderedTiles(){return Ve(i(this._allTiles.toArray(),e=>e.visible&&e.rendered))}get demResolution(){const{_allTiles:e,tilingScheme:t}=this;if(0===e.length)return{min:1,max:1};const i=v(t.spatialReference);let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const a of e){const e=t.resolutionAtLevel(a.level)*i;r=Math.min(r,e),s=Math.max(s,e)}return{min:r,max:s}}constructor(e){super(e),this.terrainTextureCompressionTracker=new Xe,this._iteratorPool=new p(()=>new Ae,e=>e.remove=()=>this._iteratorPool.release(e)),this._postorderIterator=new Be,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._allTilesCreated=!1,this._usedMemory=null,this._performanceInfo=new me,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=x(),this._eyePosSurfaceSR=x(),this._splitLimits=new oe,this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new L,this._frameTask=Qe,this._allTiles=new u,this._upsampleInfoPool=new p(()=>new Fe),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=I(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=U.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationRange=new z(1/0,-1/0),this._rootTileElevationRange=new z(1/0,-1/0),this._projectorCache=new Map,this._tilingSchemeSpatialReference=null,this._updatingRootTiles=!1,this._pendingTilesForElevationUpdateEvent=new Set,this._pendingTilesToUpdate=new Set,this.totalGeometryUpdates=0,this.totalTileUpdates=0,this._oneBatchPerFrameTask=!0,this._layerViewsDirty=!1,this.unloadedMemory=0,this.ignoresMemoryFactor=!1,this._isWebMercator=!1,this._isWebMercatorOnPlateCarree=!1,this.enabled=!0;const{view:t}=e;this.overlayManager=new re({...e,terrainSurface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=P(t.spatialReference),this._renderer=new ge(this.overlayManager.renderer,t.stage,this._allTiles,this.terrainTextureCompressionTracker,t.resourceController.memoryController),$e()||(this._scaleRangeQueries=new ne)}initialize(){const{view:e}=this,{resourceController:t}=e,{memoryController:i}=t;this._tileCache=new d((e,t)=>i.newCache(e,t),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",({tile:e})=>e.unloadMapData()),this._elevationQueryCache=new H(i.newCache("elevation-query"));const r=this.overlayManager;this.addHandles([_(()=>r.renderer.isEmpty,()=>this._evaluateTransparency()),_(()=>this.renderer.visible,e=>this.suspended=!e),_(()=>this.heading,e=>{this._renderer.updateHeading(e),this._updateTileTextures(0)}),_(()=>({heading:e.camera?.heading,state:e.state?.mode}),({heading:e,state:t})=>{if(null==e)return;if(this.isGlobal&&this.isGeographic||this.isWebMercatorOnPlateCarree)return void(this.heading=90*Math.round(e/90)%360);const i=Math.round(e)%360,r=Math.abs(i-this.heading);(2===t||Math.min(r,360-r)>=30)&&(this.heading=i)})],"overlayManager"),this.addHandles([_(()=>this.baseOpacity,()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?1:2)},f),_(()=>this.hasCompositeBlendMode,()=>this._updateTileTextures(this._evaluateTransparency()?1:2),f),_(()=>this.backgroundColor,(e,t)=>{e?.equals(t)||(this._handleLayerViewChanges(),this._renderer.updateTileBackground(e))},y),_(()=>this.snapLevel,()=>this._viewChanged=!0,y),_(()=>this.view.pointsOfInterest,e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add(()=>e.focus?.renderLocation,()=>this._allTilesSorted=!1,{equals:S})}),_(()=>Q.TERRAIN_TILE_TREE_SHOW_TILES,t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then(({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&Q.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))}):t||(this._treeDebugger=h(this._treeDebugger))},T)]);const{spatialReference:a}=e;this._extentHelper=te(this.viewingMode,{layers:e.map.allLayers,layerViews:e.allLayerViews,viewSpatialReference:a});const n=new s({getCollections:()=>e.defaultsFromMap?.mapCollections?.map(({layers:e})=>e),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),l=new qe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme();const o=t.scheduler;this._frameTask=o.registerTask(ze.TERRAIN_SURFACE,this),this.addHandles([_(()=>this._extentHelper.stencilEnabledExtents,e=>this._renderer.setStencilEnabledLayerExtents(e),T),_(()=>this.tilingSchemeLogic.tilingScheme,()=>this._updateTilingScheme(),y),_(()=>this.groundExtent,()=>this._updateRootTiles(),T),e.on("resize",()=>this._viewChangeUpdate()),_(()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]},()=>this._viewChangeUpdate(),f),_(()=>e.qualitySettings?.fadeDuration,e=>this._renderer.textureFadingEnabled=e>0,T),_(()=>e.qualitySettings?.physicallyBasedRenderingEnabled,e=>this._renderer.pbrMode=e?5:0,T),_(()=>e.qualitySettings?.tiledSurface.elevationLevelDelta,()=>this._updateAllTileGeometries()),_(()=>this.userClippingExtent,()=>this._updateClippingExtent(),y)]),this.addHandles(e.allLayerViews.on("after-changes",()=>this._layerViewsDirty=!0)),this._layerViewsDirty=!0,this._handleLayerViewChanges(),this._renderer.updateTileBackground(this.backgroundColor)}clearHandles(){this._watchUpdatingTracking?.removeAll(),this.removeAllHandles(),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear()}destroy(){this._frameTask.remove(),this._frameTask=Qe,this._watchUpdatingTracking?.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear(),this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),this._allTiles.prune(),je.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroyed||this._renderer.destroy(),this._renderer=null,this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),ke(),this._layerViews.forEach(e=>e.length=0),this._performanceInfo=null}get renderer(){return this._renderer}get frustum(){return this.view.state.camera.frustum}get snapLevel(){return this.lodSnappingEnabled?this.view.terrainLevel:null}get lodSnappingEnabled(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get hasStencilEnabledExtents(){return this._extentHelper.stencilEnabledExtents.length>0}get userClippingExtent(){const{spatialReference:e}=this,t=this.view?.clippingArea;if(null==t||null==e)return null;const i=I(),r=Y(t,i,e)?i:null,s=this._get("userClippingExtent");return k(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get groundExtent(){const e=V(this.fullGroundExtent,this.userClippingExtent,I()),t=this._get("groundExtent");return k(e,t)?t:e}get fullGroundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),this.enabled&&!!((this.readyToRun||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get readyToRun(){return this.enabled&&(this._hasPendingUpdates||this._viewChanged||this._allTilesDirty||!this._allTilesSorted||this._layerViewsDirty||this._scaleRangeQueries?.updating||this._frameTask.updating)&&this.ready&&!this.suspended}get updatingProgressValue(){return this._maxNumUpdating=Math.max(this._pendingUpdates,this._maxNumUpdating),1-this._pendingUpdates/this._maxNumUpdating}get baseOpacity(){return this.view?.map?.ground?.opacity??1}set baseOpacity(e){this.view.map.ground.opacity=e}get viewingMode(){return this.view.state.viewingMode}get ready(){return!this.enabled||null!=this._rootTiles}get rootTiles(){return this._rootTiles}get spatialReference(){return this.tilingScheme?.spatialReference??null}get backgroundColor(){return this.view?.map?.ground?.surfaceColor}set backgroundColor(e){this.view.map.ground.surfaceColor=e}set slicePlaneEnabled(e){this._renderer.slicePlaneEnabled=e,this._set("slicePlaneEnabled",e),this._evaluateTransparency()}get tilingSchemeLocked(){return this.tilingSchemeLogic?.tilingSchemeLocked??!1}get wireframe(){return this._renderer?.wireframe}set wireframe(e){e!==this._renderer.wireframe&&(this._renderer.wireframe=e,this._updateAllTileGeometries())}get opaque(){return 0===this._renderer.transparency}get invisible(){return 3===this._renderer.transparency}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get fadeDuration(){return this.view.qualitySettings.fadeDuration??0}intersect(e,t,i,r){this._renderer.intersect(e,t,i,r)}getElevationLevelDelta(e){return e<4?3:this.view.qualitySettings.tiledSurface.elevationLevelDelta}get _xNormalizer(){return q(this._spatialReference)}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length||!this.enabled)return null;if(0===s[0].layerInfo[0].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=M(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return l.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const n=b(tt,e,t,i);a(n,0,n,0);return lt(s,this._xNormalizer?.normalize(n[0])??n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[0].length:0;if(r?.length&&0!==s&&this.enabled)for(let a=0;a<t;++a){const t=3*a;i(a,lt(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getLayerIndexByUID(e,t){return this._layerIndexByUid[e].get(t)}getScale(e){if(!this.tilingScheme)return null;if(!D(e,tt,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getScale(): could not project given point to tiling scheme coordinate system"),null;const t=this._rootTiles;if(null!=t)for(const i of t)if(i?.containsPoint(tt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;tt[0]>t[2]&&(i+=1),tt[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}_ensureProjector(e){const t=this._projectorCache.get(e);if(t)return t;const i=M(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationRange(e,t){if(!this.enabled||null==this._rootTiles)return null;const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationRange(): could not project given point to tiling scheme coordinate system"),null;it.copy(e),i(it.center,0,it.center,0);const r=new z,s=this._rootTiles;if(null!=s){const e=[];for(const i of s)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,it))continue;const s=i.children;if(null==s[0]||i.rendered)r.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of s)e.push(t)}}return r}getRootElevationRange(){return this.enabled&&null!=this._rootTiles?new z(this._rootTileElevationRange.minElevation,this._rootTileElevationRange.maxElevation):null}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationRange.minElevation)*R;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,it.center,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;it.radius=t;let i=null;const r=e=>{if(e&&A(e.extent,it)){const t=e.children;if(t[0]&&!e.rendered)for(const e of t)r(e);else{const t=this._getLodBiasCorrectedScale(e.level);i=null==i?t:Math.min(i,t)}}},s=this._rootTiles;if(null!=s)for(const a of s)r(a);return i}queryVisibleScaleRange(e,t,i,r){if(!this._scaleRangeQueries)return;const s=t?this.tilingScheme.levelAtScale(t):0,a=i?this.tilingScheme.levelAtScale(i):1/0,n=this._lodBias;this._scaleRangeQueries.queryVisibleLevelRange(e,s+n,a+n,r)}_evaluateTransparency(){const e=this.baseOpacity,t=this.overlayManager.renderer.isEmpty,i=this._renderer.transparency,r=this._isFullyTransparent?t?3:2:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?0:1;return this._renderer.transparency=r,i!==r}_updateTilingScheme(){const{tilingScheme:e}=this.tilingSchemeLogic;if(!(e!==this.tilingScheme))return;_e(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??U.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&F(this.view?.renderSpatialReference),this._isGeographic=t?.isGeographic??!1,this._set("tilingScheme",e),this._tilingSchemeSpatialReference=this.tilingScheme?.spatialReference,this._projectorCache.clear(),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.tileSize=e.pixelSize,this.overlayManager.spatialReference=e.spatialReference,this._updateRootTiles())}static{this._tileMemcacheKey="TerrainTileMemcache"}_acquireTile(e,t,i,r){const s=this._tileCache.pop(Je._tileMemcacheKey);return s?(s.init(e,t,i,r,this),s):new this._tileConstructor(e,t,i,r,this)}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{groundExtent:e,tilingScheme:t}=this;if(!t)return;if(!this.enabled)return void this._setRootTiles(null);const i=rt;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void l.getLogger(this).warn(de);const e=this._rootTiles.map(e=>e.lij),t=r(e,s,Ie);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter(e=>!(t.removed.findIndex(t=>Ie(t,e.lij))>-1)||(this._purgeTile(e),!1));t.added.forEach(t=>e.push(this._newRootTile(t))),this._setRootTiles(e)}}else this._updatingRootTiles=!0,s.length>he&&(l.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map(e=>this._newRootTile(e)));k(i,this._rootTilesExtent)||(this._rootTilesExtent=I(i)),this.renderer.visible=!0,this._viewChangeUpdate(),this.overlayManager.setPlacementDirty(),this.notifyChange("ready"),this._updateAllTileGeometries(),this._updatingRootTiles=!1,this.checkAllTilesWaterproofness()}_updateAllTileGeometries(){const e=this._allTiles.filter(e=>e.loaded&&e.intersectsClippingArea);e.sort(Oe),e.forEach(e=>this._renderer.updateTileGeometryState(e)),e.forEach(e=>e.renderData.updateNeighborData()),this._updateTilesGeometries(e),this._pendingTilesToUpdate.clear()}_updateTilesGeometries(e){if(0===e.length)return;e.sort(Oe);const t=this.renderer;e.forEach(e=>t.updateGeometryIfNeeded(e)),e.forEach(e=>this._pendingTilesForElevationUpdateEvent.add(e))}_shouldSplit(e){return 1===e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(1),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationRange(),t}_setRootTiles(e){if(this._rootTiles=e,this._allTiles.clear(),null!=e){const t=this._iteratorPool.acquire();for(t.reset(e);!t.done;)this._allTiles.push(t.next());t.remove()}this._renderer.setRootTiles(this._rootTiles),this._updateTilesVisibility(e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this.renderer.visible&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.groundExtent)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Ge(e),i=this.visibleElevationRange;let r=t?i.minElevation:1/0,s=t?i.maxElevation:-1/0;const a=this.groundExtent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty(!1);const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBoundsMin,r),s=Math.max(e.elevationBoundsMax,s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._updatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.minElevation!==r||i.maxElevation!==s)&&(this.visibleElevationRange=new K(r,s))}_updateRootTileElevationRange(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach(({elevationBoundsMin:i,elevationBoundsMax:r})=>{e=Math.min(e,i),t=Math.max(t,r)});const r=this._rootTileElevationRange;r.minElevation===e&&r.maxElevation===t||(this._rootTileElevationRange=new K(e,t))}_updateViewDependentParameters(){const{camera:e,contentCamera:t}=this.view.state,i=Math.tan(.5*t.fovX),r=Math.tan(.5*t.fovY),s=this.tilingScheme.pixelSize,a=2**-this._lodBias*e.pixelRatio;this._splitLimits.aboveGround=e.aboveGround,this._splitLimits.fovX=i,this._splitLimits.fovY=r,this._splitLimits.relativeWidthLimit=s/e.width*this.maxTextureScale*a,this._splitLimits.relativeHeightLimit=s/e.height*this.maxTextureScale*a,this._splitLimits.maxLod=this.tilingScheme.getMaxLod(),this._splitLimits.angledSplitBias=this.view.qualitySettings.tiledSurface.angledSplitBias,this.view.state.fixedContentCamera?this._splitLimits.frustum=G(this._splitLimits.frustum??N(),t.frustum):this._splitLimits.frustum=null,E(this._eyePosRenderSR,t.eye),j(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateTileGeometryState(e){e.updateVisibility();this._renderer.updateTileGeometryState(e)&&this._markTileToUpdate(e),this.setMemoryDirty()}_markAllTileNeighborsForUpdate(e){e.forEachLoadedNeighbor(e=>{this._layerViews[1].some(fe)&&e.setPendingUpdate(32),this._pendingTilesToUpdate.add(e)})}_updateTileTexture(e,t){const i=e.resetPendingUpdate(32)?32:!!e.resetPendingUpdate(16)&&16;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=at.extent;B(e),this._pendingTilesForElevationUpdateEvent.forEach(t=>O(e,t.extent,e)),this._pendingTilesForElevationUpdateEvent.clear(),at.spatialReference=this.spatialReference,this.emit("elevation-change",at),this._shouldEmitChangeEvent=!1}runTask(e){this._handleLayerViewChanges(e),this._frameTask.processQueue(e),this.renderer.processScaleRangeQueries(this._scaleRangeQueries,e),this._inFrameTask=!0,this._pendingUpdates=0,this._hasPendingUpdates=!1,this._updateAllTilesStatus(e),this._sortTiles(e);const t=!this.view.state.fixedContentCamera;if(this._mergeAndSplit(e,t),this._updateElevation(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty(),this._updatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&e.hasProgressed&&this.requestUpdate(),this.notifyChange("updatingProgressValue"),Le&&this._checkTileInvariant(),!e.hasProgressed)return Ke}_checkTileInvariant(){const e=new Map;this._allTiles.forAll(t=>e.set(t,new Set)),this._allTiles.forAll(t=>{if(_e(t.rendered===t.leaf,` rendered ${t.rendered} != ${t.leaf} leaf`),!t.leaf){const e=e=>0===e.unmergableChildCount&&0===e.maxLevelDeltaNeighborCount,i=t.children.reduce((t,i)=>t+(e(i)?0:1),0);if(_e(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(4)){_e(!t.hasPendingUpdate(1),"Tile can be both split and merge at the same time");for(const e of t.children)_e(e.leaf||e.hasPendingUpdate(4),"Child of tile to merge must also merge")}}for(let i=0;i<4;++i){if(t.rendered){const e=t.renderData?.geometryState.edgePeerNeighbors[i];if(null!=e){{const r=t.level-e.level<=ue;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ue} (edge[${i}])`),_e(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}_e(t.level-e.level<=ue,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ue,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(ye[i],s);if(null!=a){if(t.leaf&&t.level>=ue){let i=a;for(;t.level-i.level<ue;)i=i.parent;const s=[r,t.lij[1]>>ue,t.lij[2]>>ue];if(!Ie(s,i.lij)){const r=e.get(i);_e(!r.has(t),"Cannot already have neighbor"),r.add(t)}}_e(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),_e(t.level-a.level<=ue,`Tile level delta [${t.level}] vs [${a.level}] > ${ue}`)}}}),this._allTiles.forAll(t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);_e(i===r.size,`Tile[${t.lij.toString()}] merge-blocker mismatch: actual ${i} vs ${r.size}`)})}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;const t=new ae(this._allTiles.length);t.pushAll(this._rootTiles);const i=this.snapLevel,r=this._splitLimits,s=this._eyePosRenderSR;this._allTiles.forAll(e=>{e.maxLevelDeltaNeighborCount=0,e.unmergableChildCount=0});const a=this.view.state.contentCamera.viewProjectionMatrix;for(;!t.empty;){const e=t.pop(),n=e.parent,l=n?.hasPendingUpdate(4),o=l?4:e.shouldSplit(r,s,i),h=1===o;e.leaf?ot(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(1),e.leaf||e.setPendingUpdate(4),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1)):(e.resetPendingUpdate(1)&&e.updateAgentSuspension(),2===o&&e.updateAgents(0),e.leaf||(e.setPendingUpdate(4),e.resetPendingUpdate(1)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||!this.view.pointsOfInterest?.focus||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger?.update(),e.madeProgress())}_markTileToUpdate(e){Te(e.loaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForUpdate(e))}_updatePendingTileGeometries(){const e=this._pendingTilesToUpdate,t=Array.from(e.keys()).filter(e=>e.loaded&&e.intersectsClippingArea);if(0===t.length)return void e.clear();const i=(i,r)=>{!r?.loaded||!r.intersectsClippingArea||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Oe);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Te(r.loaded),Te(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=De[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(Pe(t),e=>e.loaded))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(ve(ye[t]),t=>!(!t.loaded||!t.intersectsClippingArea)&&(Te(e.has(t)||Oe(r,t)<0),i(r,t),!0)),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,Le&&Re&&this.checkAllTilesWaterproofness()}_mergeAndSplit(e,t){if(this.suspended||e.done||!this._allTilesDirty)return;this._allTilesDirty=!1,this.requestUpdate();let i=!1;const r=this.view.state.fixedContentCamera;let s=!1;for(;!e.done;){s=!0;let a=!1;const n=!this._allTiles.some(s=>{if(!i&&!r&&!s.visible)return e.done;let n=s;if(s.hasPendingUpdate(4)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(4);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(4);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(1)){let t=!0;const i=s.level;if(i>=ue){const e=e=>e.leaf||i-e.level<ue;for(let r=0;r<4;++r){const a=s.findNeighborTile(ye[r],e);null!=a&&i-a.level===ue&&(t=!1,Le&&(Te(a.leaf),Te(a.hasPendingUpdate(1))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(1)}return e.done});if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries()),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries(),this._allTilesCreated=!this.allTiles.some(e=>e.hasPendingUpdate(1)||e.hasPendingUpdate(4)),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some(t=>(t.resetPendingUpdate(8)&&(this._updateTileGeometryState(t),this._shortBatches&&this._updatePendingTileGeometries(),e.madeProgress()),e.done)),!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries())}_updateTextures(e){e.done||this._allTiles.some(t=>(this._updateTileTexture(t,e),e.done))}_updateClippingExtent(){this.spatialReference&&(this.updateOverlayParameters(),this.requestRender(1),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){return this.view.qualitySettings.tiledSurface.lodBias-(1-this.view.quality)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=o(e-this._lodBias,0,t.length-1),r=i-Math.floor(i);return t[Math.floor(i)].scale*(1-r)+t[Math.ceil(i)].scale*r}_removeAllTiles(){null!=this._rootTiles&&(this._rootTiles.forEach(e=>this._purgeTile(e)),this._setRootTiles(null),this.notifyChange("ready")),this._allTiles.clear(),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),this.renderer.visible=!1}_purgeSubtree(e){const t=e.children;t[0]&&(this._purgeTile(t[0]),this._purgeTile(t[1]),this._purgeTile(t[2]),this._purgeTile(t[3]),e.clearChildren())}_purgeTile(e){e.leaf?dt(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(Je._tileMemcacheKey,e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){_e(e.leaf,"Tile that is already split should not be split again!"),_e(e.rendered,"Tile marked to split is not rendered"),dt(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),_e(e.rendered,"parent should be rendered"),t.forEach(e=>this._loadTile(e)),t.forEach(e=>this._pendingTilesToUpdate.add(e)),this._unloadTile(e),this._markAllTileNeighborsForUpdate(e),this._emitTileScaleChange(e,e.level+1),this._allTilesDirty=!0,this._shortBatches&&this._updatePendingTileGeometries(),t.forEach(e=>ot(e,e.hasPendingUpdate(1))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){nt.spatialReference=this.spatialReference,nt.extent=e.extent,nt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",nt)}createTile(e,t,i,r){_e(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.groundExtent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(1),s}get _shortBatches(){return 2!==this.view.state.mode}_mergeTile(e){_e(!e.hasPendingUpdate(1),"_mergeTile sanity check"),_e(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),_e(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),ot(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&e.updateOverlayParameters(this.overlayManager)}_handleLayerViewChanges(e=Ye){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(let s=this.view.allLayerViews.length-1;s>=0;s--){const e=this.view.allLayerViews.items[s];if(i.add(e.uid),we(e)||Ce(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Ce(e)){const i=this._layerClassFromLayerView(e),s=this.getLayerIndexByUID(i,e.uid);null!=s&&((s<r||null==r)&&(t=!0),r=s)}else this._registerTiledLayerView(e),e.layer.loaded&&(t=!0)}this._basemapLayerViewHandles.forEach((e,r)=>{i.has(r)||(this._unregisterTiledLayerView(r),t=!0)}),t&&this._updateTiledLayers(),this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._evaluateTransparency(),e.madeProgress()}get _isFullyTransparent(){if(this.view.map?.ground?.opacity>0)return!1;for(const e of this.view.allLayerViews.items)if(Se(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((be(e)||Ce(e))&&We(He[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Ee(e)?0:1}_registerTiledLayerView(e){const t=[];if((be(e)||Ce(e))&&t.push(_(()=>e.layer.blendMode,()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(2)})),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_(()=>!e.destroyed&&e.suspended,()=>this._updateTiledLayers())),t.push(_(()=>!e.destroyed&&e.fullOpacity,()=>this._updateTileTextures(2)));const{layer:r}=e;"effectiveScaleRange"in r&&t.push(_(()=>!e.destroyed&&r.effectiveScaleRange,()=>this._restartAllAgents(i))),t.push(e.on("data-changed",()=>{const t=this.getLayerIndexByUID(i,e.uid);null!=t&&this._invalidateLayerData(t,i)}))}this._unregisterTiledLayerView(e.uid),this._basemapLayerViewHandles.set(e.uid,t)}_unregisterTiledLayerView(e){const t=this._basemapLayerViewHandles.get(e);if(t){for(const e of t)e.remove();this._basemapLayerViewHandles.delete(e)}}_updateTiledLayers(){if(!this.tilingScheme||this.view.suspended)return;const e=this.view.allLayerViews,t=[[],[]];let i=null;e.forEach(e=>{if(!e.layer||e.suspended||!we(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(1===r){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)});for(const r of ie){const e=this._layerViews[r],i=t[r];i.reverse();const s=i.length;let a=e.length!==s;const n=new Array(s),l=new Array(e.length);this._layerIndexByUid[r].clear();for(let t=0;t<s;t++){const s=i[t].uid;this._layerIndexByUid[r].set(s,t);const o=e.indexOf(i[t]);n[t]=o,t!==o&&(a=!0),o>-1&&(l[o]=t)}if(a){const e=this._postorderIterator;for(e.reset(this._rootTiles);!e.done;)e.next().modifyLayers(l,n,r);this._layerViews[r]=i,this._restartAllAgents(r),this._updateTilesVisibility(this._rootTiles)}}this.tilingScheme.ensureMaxLod(i)&&(this._viewChangeUpdate(),this.notifyChange("tilingScheme"))}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),0===e&&i.computeElevationBounds()}this._updateRootTileElevationRange()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll(t=>{t.updateAgents(1),1===e?this.renderer.updateTileTexture(t,16):t.updateRenderData(1,e)}),this._evaluateTransparency()}_invalidateLayerData(e,t){this._allTiles.forAll(i=>i.removeLayerAgent(e,t)),this._allTiles.forAll(i=>i.invalidateLayerData(e,t))}setTileTreeDirty(e){this._allTilesDirty=!0,e&&(this._allTilesCreated=!1)}requestRender(e=1){this.renderer.setNeedsRender(e)}requestUpdate(){1===++this._pendingUpdates&&(this._hasPendingUpdates=!0)}requestTileData(e,t,i,r){const s=this.layerViewByIndex(t,i),a=s.layer;return!a.tilemapCache||fe(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.level,e.lij[1],e.lij[2],{...r,timeout:6e3}).then(()=>--this._asyncWorkItems).catch(t=>{throw--this._asyncWorkItems,c(r),g(t)||this._dataMissing(e,i,s),t}).then(()=>this._frameTask.schedule(()=>this._requestTileData(e,i,s,r),r.signal)))}_requestTileData(e,t,i,r){if(this.destroying)return Promise.resolve();return 0===t?Ee(i)?this._requestElevationTileData(e,i,r):Promise.reject():Se(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!m(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{g(i)||(l.getLogger(this).error(`Tile ${e.lij.toString()} layer 0/${t.uid} error ${i}`),this._dataMissing(e,0,t),this.requestUpdate())};return t.fetchElevationTile(e,i).then(e=>this._frameTask.schedule(()=>r(e)),s).finally(()=>--this._asyncWorkItems)}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[0].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",0,e.lij.toString());const s=new J(e.lij,e.extent,i);e.dataArrived(r,0,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:0});const a=[e],n=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,n),e.computeElevationBounds()}0===n&&this._updateRootTileElevationRange(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{xe(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer 1/${t.uid} error ${r}`),this._dataMissing(e,1,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule(()=>{this.requestUpdate(),m(i)?xe(r):this._mapTileDataArrived(e,t,r)},i.signal,s(r)).catch(s(r)),n=(e,t=null)=>this._frameTask.schedule(()=>r(e,t));return t.fetchTile(e.lij,i).then(a,n).finally(()=>--this._asyncWorkItems)}_mapTileDataArrived(e,t,i){const r=this.getLayerIndexByUID(1,t.uid);if(null==r)return xe(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,1,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:1})}_dataMissing(e,t,i){const r=this.getLayerIndexByUID(t,i.uid);null!=r?(e.dataMissing(r,t),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:t})):l.getLogger(this).warn("TerrainSurface: received data from unknown layer")}get performanceInfo(){const e=this._performanceInfo;return e.numNodes=this._allTiles.length,e.numLeaves=e.numVisible=e.numRendered=e.numLoadedPerLevel.length=e.numRenderedPerLevel.length=0,this._allTiles.forAll(t=>{t.leaf&&e.numLeaves++;const i=t.level;t.renderData&&(e.numLoadedPerLevel[i]=(e.numLoadedPerLevel[i]||0)+1),t.visible&&(e.numVisible++,t.rendered&&(e.numRenderedPerLevel[i]=(e.numRenderedPerLevel[i]||0)+1,e.numRendered++))}),e}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this.tilingScheme?(null==this._usedMemory&&(this._usedMemory=this._recalculateUsedMemory()),this._usedMemory??0):0}_recalculateUsedMemory(){return this.tilingScheme?Math.round(this._allTiles.reduce((e,t)=>e+t.usedMemory,0)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this.getLayerIndexByUID(i,e.uid);return null!=r&&this._allTiles.forAll(e=>t+=e.getUsedMemoryForLayer(i,r)),t}get renderPatchBorders(){return this._renderer.renderPatchBorders}set renderPatchBorders(e){this._renderer.renderPatchBorders=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!Re)return;const e=this._rootTiles;if(null==e)return;const t=e=>e?.renderData?.geometry?.indices?.length>0,i=(e,i)=>{t(e)&&console.error("Tile[",e.lij,"] has geometry although parent[",i.lij,"] has geom")},r=e=>{if(e.intersectsClippingArea)if(e.renderData&&!e.renderData.geometryState&&console.error("Tile[",e.lij,"] has renderData but not geometryState"),e.renderData&&!e.renderData.geometry&&console.error("Tile[",e.lij,"] has renderData but not geometryInfo"),!e.renderData?.geometry||(e.renderData.geometry.indices?.length??0)>0||console.error("Tile[",e.lij,"] has renderData but no indices - geometryInfo: ",e.renderData.geometry),t(e)){e.checkGeometryWaterproofness();for(const t of e.children)i(t,e)}else if(e.leaf)console.error("Tile[",e.lij,"] has no geometry and no children, from root to leaf");else for(const t of e.children)r(t)},s=e=>{const t=e.parent?.visible??!0,i=e.visible;e.computeVisibility();const r=e.visible;if(i!==r&&t&&console.error(" Tile[",e.lij,"] has out of date visibility: ",i," instead of ",r),!e.leaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isGeographic(){return this._isGeographic}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateCarree(){return this._isWebMercatorOnPlateCarree}isEastEndWrap(e){return this._isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this._isGlobal&&0===e[2]}lijEastEnd(e){return 1<<e+(this._isGeographic?1:0)}wrapEastWest(e){const t=this.lijEastEnd(e[0]),i=e[2];if(0<=i&&i<t)return e;if(!this._isGlobal)return null;const r=(i+(i<0?t:0))%t;return[e[0],e[1],r]}enableInternalChecks(e){Ue(e)}enableWaterproofnessChecks(e){Me(e)}static cleanupTerrainSurface(){st.prune()}enable(e){e!==this.enabled&&(this._set("enabled",e),e?(this._updateRootTiles(),this.suspended=!1):(this.suspended=!0,this._removeAllTiles(),this._setRootTiles(null)),this.notifyChange("ready"))}updateOverlayParameters(){const{overlayManager:e}=this;this.allTiles.forAll(t=>t.updateOverlayParameters(e))}};e([w()],Ze.prototype,"_renderer",void 0),e([w({constructOnly:!0})],Ze.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],Ze.prototype,"view",void 0),e([w({constructOnly:!0})],Ze.prototype,"overlayManager",void 0),e([w({constructOnly:!0})],Ze.prototype,"terrainTextureCompressionTracker",void 0),e([w()],Ze.prototype,"_hasPendingUpdates",void 0),e([w()],Ze.prototype,"_asyncWorkItems",void 0),e([w()],Ze.prototype,"_allTilesDirty",void 0),e([w()],Ze.prototype,"_allTilesSorted",void 0),e([w()],Ze.prototype,"_allTilesCreated",void 0),e([w()],Ze.prototype,"_viewChanged",void 0),e([w({type:Number})],Ze.prototype,"heading",void 0),e([w()],Ze.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],Ze.prototype,"_watchUpdatingTracking",void 0),e([w()],Ze.prototype,"_frameTask",void 0),e([w()],Ze.prototype,"demResolution",null),e([w({readOnly:!0})],Ze.prototype,"snapLevel",null),e([w({readOnly:!0})],Ze.prototype,"lodSnappingEnabled",null),e([w({readOnly:!0})],Ze.prototype,"userClippingExtent",null),e([w()],Ze.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],Ze.prototype,"groundExtent",null),e([w({readOnly:!0})],Ze.prototype,"fullGroundExtent",null),e([w({readOnly:!0})],Ze.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],Ze.prototype,"updating",null),e([w({readOnly:!0})],Ze.prototype,"readyToRun",null),e([w(X)],Ze.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],Ze.prototype,"updatingProgressValue",null),e([w()],Ze.prototype,"_maxNumUpdating",void 0),e([w()],Ze.prototype,"baseOpacity",null),e([w()],Ze.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],Ze.prototype,"viewingMode",null),e([w()],Ze.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],Ze.prototype,"ready",null),e([w({readOnly:!0})],Ze.prototype,"rootTiles",null),e([w()],Ze.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],Ze.prototype,"spatialReference",null),e([w({type:t})],Ze.prototype,"backgroundColor",null),e([w({value:!1})],Ze.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],Ze.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],Ze.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],Ze.prototype,"tilingSchemeLogic",void 0),e([w()],Ze.prototype,"wireframe",null),e([w({value:!1})],Ze.prototype,"suspended",null),e([w()],Ze.prototype,"fadeDuration",null),e([w()],Ze.prototype,"_xNormalizer",null),e([w()],Ze.prototype,"visibleElevationRange",void 0),e([w()],Ze.prototype,"_rootTileElevationRange",void 0),e([w()],Ze.prototype,"_layerViewsDirty",void 0),e([w()],Ze.prototype,"renderPatchBorders",null),e([w()],Ze.prototype,"renderingDisabled",null),e([w({readOnly:!0})],Ze.prototype,"enabled",void 0),Ze=Je=e([C("esri.views.3d.terrain.TerrainSurface")],Ze);const et=Ze,tt=x(),it=new W,rt=I(),st=new u,at=new ee("ground"),nt={spatialReference:null,extent:null,scale:0};function lt(e,t,i){for(const r of e){if(!r.containsPointXY(t,i))continue;let e=r;for(;e&&!e.renderData;){const r=(t>e.extentMidX?1:0)+(i<e.extentMidY?2:0);e=e.children[r]}const s=e?.renderData?.geometryState.samplerData??null;return Z(t,i,s)}return null}function ot(e,t){!e.leaf||e.level<ue||ut(e,e=>{t&&ht(e);const i=pt(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=pt(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}})}function ht(e){if(e.hasPendingUpdate(1))return;let t=e.parent;for(;t?.resetPendingUpdate(4);)t=t.parent;e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1),e.level<ue||ut(e,e=>{ht(e)})}function dt(e){e.level<ue||ut(e,e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,pt(t));)t=t.parent}})}function pt(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function ut(e,t){if(e.level<ue)return;const i=e.level-ue,r=e.lij[1]>>ue,s=e.lij[2]>>ue,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(ye[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{et as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{destroyMaybe as t}from"../../../core/maybe.js";class e{constructor(t){this._getFadeDuration=t,this._fadeStart=0,this._delayedTime=0}clear(){this._current=t(this._current),this._next=t(this._next),this._waiting=t(this._waiting),this._delayed=t(this._delayed)}get current(){if(null==this._current)return null;if(!this._isFadingEnabled){let t=null;this._delayed?(t=this._delayed,this._delayed=null):this._waiting?(t=this._waiting,this._waiting=null):this._next&&(t=this._next,this._next=null),t&&(this.clear(),this._current=t)}let i=e.test.fadeMoment;if(this._delayed&&(i=i||performance.now(),i>=this._delayedTime&&(this._push(this._delayed,0),this._delayed=null)),this._next){i=i||performance.now();const e=this._fadeDuration,n=null!=this._current&&this._next.texture===this._current.texture,s=0!==this._next.type,a=i-this._fadeStart>=e;(n||s||a)&&(t(this._current),this._current=this._next,this._next=this._waiting,this._waiting=null,this._fadeStart=this._alignFadeStart(i))}return this._current}get next(){return this._next}get fadeFactor(){if(null==this._next)return 1;const t=e.test.fadeMoment||performance.now(),i=Math.max(0,t-this._fadeStart),n=this._fadeDuration;return i>n?0:1-i/n}get isFading(){return null!=this._next||null!=this._delayed}push(e,i=0){this._delayed=t(this._delayed),this._push(e,i)}_push(i,n){if(this._isFadingEnabled||this.clear(),null==this._current)return void(this._current=i);const s=e.test.fadeMoment||performance.now();return 0!==n?(this._delayed=i,void(this._delayedTime=s+n)):null==this._next?(this._next=i,void(this._fadeStart=this._alignFadeStart(s))):void(null!=i&&(t(this._waiting),this._waiting=i))}get _fadeDuration(){const t=this._getFadeDuration();return this._waiting?.5*t:t}_alignFadeStart(t){const e=this._getFadeDuration();return t+e-t%e}get _isFadingEnabled(){return this._getFadeDuration()>0}static{this.test={fadeMoment:0}}}export{e as TextureFader};
5
+ import{destroyMaybe as t}from"../../../core/maybe.js";class e{constructor(t){this._getFadeDuration=t,this._fadeStart=0,this._delayedTime=0}clear(){this._current=t(this._current),this._next=t(this._next),this._waiting=t(this._waiting),this._delayed=t(this._delayed)}get current(){if(null==this._current)return null;if(!this._isFadingEnabled){let t=null;this._delayed?(t=this._delayed,this._delayed=null):this._waiting?(t=this._waiting,this._waiting=null):this._next&&(t=this._next,this._next=null),t&&(this.clear(),this._current=t)}let i=e.test.fadeMoment;if(this._delayed&&(i=i||performance.now(),i>=this._delayedTime&&(this._push(this._delayed,0),this._delayed=null)),this._next){i=i||performance.now();const e=this._fadeDuration,n=null!=this._current&&this._next.texture===this._current.texture,s=0!==this._next.type,r=i-this._fadeStart>=e;(n||s||r)&&(t(this._current),this._current=this._next,this._next=this._waiting,this._waiting=null,this._fadeStart=this._alignFadeStart(i))}return this._current}get next(){return this._next}get fadeFactor(){if(null==this._next)return 1;const t=e.test.fadeMoment||performance.now(),i=Math.max(0,t-this._fadeStart),n=this._fadeDuration;return i>n?0:1-i/n}get isFading(){return null!=this._next||null!=this._delayed}push(e,i=0){this._delayed=t(this._delayed),this._push(e,i)}_push(i,n){if(this._isFadingEnabled||this.clear(),null==this._current)return void(this._current=i);const s=this._waiting??this._next??this._current;if(i?.equals(s))return void i.destroy();const r=e.test.fadeMoment||performance.now();return 0!==n?(this._delayed=i,void(this._delayedTime=r+n)):null==this._next?(this._next=i,void(this._fadeStart=this._alignFadeStart(r))):void(null!=i&&(t(this._waiting),this._waiting=i))}get _fadeDuration(){const t=this._getFadeDuration();return this._waiting?.5*t:t}_alignFadeStart(t){const e=this._getFadeDuration();return t+e-t%e}get _isFadingEnabled(){return this._getFadeDuration()>0}static{this.test={fadeMoment:0}}}export{e as TextureFader};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{fromValues as t}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";class e{constructor(e,s,r,i,o,c){this.texture=e,this.type=s,this.offsetAndScale=r,e.retain(),this.opacities=t(i,o,c)}destroy(){this.texture.release()}}export{e as TextureReference};
5
+ import{equals as t}from"../../../core/arrayUtils.js";import{fromValues as e}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";class s{constructor(t,s,r,i,o,a){this.texture=t,this.type=s,this.offsetAndScale=r,t.retain(),this.opacities=e(i,o,a)}destroy(){this.texture.release()}equals(e){return null!=e&&this.texture===e.texture&&t(this.offsetAndScale,e.offsetAndScale)&&t(this.opacities,e.opacities)}}export{s as TextureReference};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{toConst as e}from"../../../core/compilerUtils.js";import{clamp as t}from"../../../core/mathUtils.js";import{abortMaybe as i}from"../../../core/maybe.js";import s from"../../../core/ObjectPool.js";import{e as n,F as r,g as a,j as l,i as o,b as h,d}from"../../../chunks/vec32.js";import{create as u,unitZ as c}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{getReferenceEllipsoid as g}from"../../../geometry/ellipsoidUtils.js";import{create as p,equals as f,rectangleContainsRectangleCyclicalAware as _,rectanglesIntersectCyclicalAware as m,width as y,height as v}from"../../../geometry/support/aaBoundingRect.js";import{Sphere as M}from"../../../geometry/support/sphere.js";import{isGroupLayer as A}from"../../../layers/support/layerUtils.js";import{ElevationBounds as x}from"./ElevationBounds.js";import{ElevationTileAgent as D,isElevationTileAgent as b}from"./ElevationTileAgent.js";import{LayerClasses as L}from"./LayerClass.js";import{MapDataCacheItem as I}from"./MapDataCacheItem.js";import{MapTileAgent as j,isMapTileAgent as T}from"./MapTileAgent.js";import{maxPatchTesselation as C}from"./TerrainConst.js";import{isVectorTile as B,isTileTexture as U,isRasterTile as S,isImageWithType as w}from"./TerrainData.js";import{weakAssert as E,isBlendableLayerView as P,oppositeCorner as O,internalAssert as R,enableTerrainInternalChecks as q,neighborEdgeIndices as V,oppositeEdge as N,neighborCornerIndices as G,almostEquals as k,enableWaterproofTests as F,isNorth as z,isSouth as W,isWest as H,isEast as J,isWestCorner as X,isNorthCorner as Y}from"./terrainUtils.js";import{tileAgentDone as $}from"./TileAgent.js";import{TilePerLayerInfo as Q}from"./TilePerLayerInfo.js";import{fallsWithinLayerView as K}from"./tileUtils.js";const Z=.1;class ee{constructor(){this._lij=[0,0,0],this._children=[null,null,null,null],this._pendingUpdates=0,this._dirty=!0,this._previouslyRendered=!1,this.extent=p(),this._elevationBoundsMin=NaN,this._elevationBoundsMax=0,this.layerInfo=[[],[]],this.extentInRadians=p(),this.centerAtSeaLevel=u(),this._center=[u(),new M,u()],this.up=c(),this._withinClippingArea=!0,this._intersectsClippingArea=!0,this._maxTesselation=0,this._usedMemory=0,this._rasterTileMemory=0,this._vectorTileMemory=0,this._mapDataRefCount=0,this.screenDepth=0,this.renderOrder=0,this._edgeLen=0,this._edgeLen2=0,this._curvatureHeight=0,this.onCompressionFinished=()=>{this.setPendingUpdate(16),this.setMemoryDirty()},this.extentMidX=0,this.extentMidY=0,this.distanceToPOI=-1,this._lastPOI=u(),this.maxLevelDeltaNeighborCount=0,this.unmergableChildCount=0}get lij(){return this._lij}get spatialReference(){return this._surface.spatialReference??this._surface.tilingScheme.spatialReference}get elevationLevelDelta(){return this._surface.getElevationLevelDelta(this.level)}static prune(){se.prune(0),ne.prune(0),Q.prune()}get _cached(){return!this.leaf&&this._mapDataRefCount<=0}get withinClippingArea(){return this._withinClippingArea}get intersectsClippingArea(){return this._intersectsClippingArea}get clippingArea(){return this._clippingArea}get parent(){return this._parent}get children(){return this._children}get surface(){return this._surface}get elevationBoundsMin(){return this._elevationBoundsMin}get elevationBoundsMax(){return this._elevationBoundsMax}get level(){return this._lij[0]}get key(){return`${this._lij[0]}/${this._lij[1]}/${this._lij[2]}`}get edgeLen(){return this._edgeLen}get radius(){return this._center[1].radius}get visible(){return this._dirty&&this.computeVisibility(),this._visible}get frustumVisibility(){return this._dirty&&this.computeVisibility(),this._frustumVisibility}computeVisibility(){this._dirty=!1;const e=this.parent,t=e?.frustumVisibility??1;this._frustumVisibility=0===t?0:2===t?2:this._calculateFrustumVisibility(this.surface.frustum);const i=2!==this._frustumVisibility&&this._intersectsClippingArea;i!==this._visible&&(this._visible=i,this._surface.emit("tiles-visibility-changed"),this._surface.renderer.setDirty(),this.updateAgentSuspension())}get _loadable(){return this.visible||this._surface.view.state.fixedContentCamera}get rendered(){const e=!!this.renderData;return e!==this._previouslyRendered&&(this._surface.emit("tiles-visibility-changed"),this._previouslyRendered=e,this._surface.renderer.setDirty()),e}init(e,t,i,s,n){this._lij[0]=e,this._lij[1]=t,this._lij[2]=i,this.ellipsoid=g(n.tilingScheme.spatialReference),n.tilingScheme.getExtent(e,t,i,this.extent),n.tilingScheme.convertExtentToRadians(this.extent,this.extentInRadians),this.extentMidX=.5*(this.extent[0]+this.extent[2]),this.extentMidY=.5*(this.extent[1]+this.extent[3]),this._withinClippingArea=!0,this._intersectsClippingArea=!0,this._clippingArea=null,this._mapDataRefCount=0,n.upsampleMapCache.pop(this.key),this._edgeLen=0,this._edgeLen2=0,this._center[1].radius=0,this.elevationLevel=e,s&&!Number.isNaN(s.elevationBoundsMin)?(this._elevationBoundsMin=s.elevationBoundsMin,this._elevationBoundsMax=s.elevationBoundsMax):(this._elevationBoundsMin=0,this._elevationBoundsMax=0),this._pendingUpdates=0,this.renderData=null,this.screenDepth=0,this._visible=!1,this._previouslyRendered=!1,this._parent=s,this.clearChildren(),this._surface=n,this.updateVisibility(),this.maxLevelDeltaNeighborCount=0,this.unmergableChildCount=0;for(const r of L){const e=n.numLayers(r),t=this.layerInfo[r];for(const i of t)i.release();t.length=e;for(let i=0;i<e;i++)t[i]=Q.acquire(this._surface.upsampleInfoPool),0===r&&this.findElevationBoundsForLayer(i,-1)}this.computeElevationBounds(),this._maxTesselation=Math.min(n.tilingScheme.pixelSize,C)}dispose(){E(!this.renderData,"tile.renderData was not unloaded"),this._surface?.upsampleMapCache.pop(this.key),this.layerInfo.forEach(e=>{e.forEach(e=>e.release()),e.length=0}),this._surface=this._parent=null,this.clearChildren(),this.setMemoryDirty()}refMapData(){++this._mapDataRefCount,this._cached||this._surface.upsampleMapCache.pop(this.key)}unrefMapData(){--this._mapDataRefCount,this._cached&&this.cachedMemory>0&&this._surface.upsampleMapCache.put(this.key,new I(e(this)))}setMemoryDirty(){this._usedMemory=0}get usedMemory(){return this._ensureUsedMemory()+(this._cached?0:this.mapDataMemory)}get cachedMemory(){return this._ensureUsedMemory(),null==this._surface?this.usedMemory:this._cached?this.mapDataMemory:0}get mapDataMemory(){return this._rasterTileMemory+this._vectorTileMemory}get _cpuImageMemorySize(){const e=4,t=this._surface.tilingScheme.pixelSize;return t*t*e}_ensureUsedMemory(){if(this._usedMemory>0)return this._vectorTileMemory=this.layerInfo[1].reduce((e,{data:t})=>e+(B(t)?t.usedMemoryPerReference:0),0),this._usedMemory;this._usedMemory=this._baseUsedMemory,this._rasterTileMemory=0,this._vectorTileMemory=0;for(const{data:e}of this.layerInfo[1])B(e)?this._vectorTileMemory+=e.usedMemoryPerReference:this._rasterTileMemory+=this.getTerrainDataMemory(e);for(const e of this.layerInfo[0])this._usedMemory+=e.data?this._cpuImageMemorySize:0;return this.renderData&&(this._usedMemory+=this.renderData.estimatedGeometryMemoryUsage,this._rasterTileMemory+=this.renderData.texture?.usedMemory??0),this._cached&&this._surface.upsampleMapCache.updateSize(this.key),this._usedMemory}getUsedMemoryForLayer(e,t){const i=this.layerInfo[e][t];return i?.data?1===e?this._cached?0:this.getTerrainDataMemory(i.data):0===e?this._cpuImageMemorySize:0:0}getTerrainDataMemory(e){return U(e)?e.texture.usedMemory:S(e)?e.memoryUsage:B(e)?e.usedMemoryPerReference:w(e)||e instanceof HTMLImageElement?this._cpuImageMemorySize:0}updateScreenDepth(e){const[t,i,s]=this._center[1].center,n=e,r=n[2]*t+n[6]*i+n[10]*s+n[14];this.screenDepth=r<0?0:r/(n[3]*t+n[7]*i+n[11]*s+n[15])}shouldSplit(e,t,i){if(!this.visible)return 0;if(e.frustum&&(!this._intersectsClippingArea||2===this._calculateFrustumVisibility(e.frustum)))return 0;const s=this.level;n(ue,this._center[1].center,t);let d=r(ue),u=ue,c=this._center[1].center;n(ce,this._center[0],t);const g=r(ce);g<d&&(d=g,u=ce,c=this._center[0]),n(ge,this._center[2],t);const p=r(ge);if(p<d&&(d=p,u=ge,c=this._center[2]),this._edgeLen2>d&&s<e.maxLod)return 1;const f=Math.sqrt(d),_=e.fovX*f*2,m=this._edgeLen/_,y=()=>{if(s<e.maxLod)return this.elevationLevel=s,0;const t=s+Math.ceil(-Math.log2(e.relativeWidthLimit/m));return t!==this.elevationLevel?(this.elevationLevel=t,2):0},v=null!=i?i-s:1/0;if(v<=.5)return y();const M=a(this.up,ue),A=this._elevationBoundsMax-this._elevationBoundsMin,x=A/this.edgeLen;if(e.aboveGround&&M>0&&x<.001){if(M/f-Math.sin(this._curvatureHeight/(this.edgeLen*Math.SQRT1_2)*Math.PI)-x>0)return 0}const D=null!=i?3-Math.min(v,2):1;if(m*D<e.relativeWidthLimit||s>=e.maxLod)return y();if(s<7)return 1;l(pe,this.up,M),n(pe,pe,u);const b=r(pe);if(b<=this.radius*this.radius)return 1;l(pe,pe,this.radius/Math.sqrt(b)),o(pe,pe,c),n(pe,t,pe);const L=Math.min(1,(Math.abs(a(pe,this.up))+.5*A+this._curvatureHeight)/h(pe)),I=Z/e.angledSplitBias,j=e.fovY*f*2;return L*(this._edgeLen/j*D)<I*e.relativeHeightLimit?0:1}createChildren(){const e=this._children,t=this.lij[0]+1,i=2*this.lij[1],s=2*this.lij[2];return e[0]=this.surface.createTile(t,i,s,this),e[1]=this.surface.createTile(t,i,s+1,this),e[2]=this.surface.createTile(t,i+1,s,this),e[3]=this.surface.createTile(t,i+1,s+1,this),e}clearChildren(){this._children[0]=this._children[1]=this._children[2]=this._children[3]=null}get loaded(){return this.renderData?.hasGeometry??!1}load(){this.refMapData();for(const e of L)this._createOrUpdateAgents(0,e);this.surface.renderer.loadTile(this)}unload(){this.renderData&&this.unrefMapData(),this.surface.renderer.unloadTile(this);for(const e of L){const t=this.layerInfo[e];for(const e of t)e.loadingAgent&&e.loadingAgent!==$&&(ie(e.loadingAgent),e.loadingAgent=null),e.pendingUpdates=0}this.resetPendingUpdate(8),this.resetPendingUpdate(16),this.resetPendingUpdate(32)}unloadMapData(){const e=this.layerInfo[1];for(const t of e)t.loadingAgent&&t.loadingAgent!==$&&(ie(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0,t.invalidateSourceData();this.renderData?.releaseTexture(),this.setMemoryDirty()}updateClippingStatus(e){if(f(e,this._clippingArea))return!1;const t=this._intersectsClippingArea,i=this._withinClippingArea;null!=e?(this._intersectsClippingArea=this.intersectsExtent(e),this._withinClippingArea=this._isWithinExtent(e)):(this._intersectsClippingArea=!0,this._withinClippingArea=!0),this._clippingArea=e,this.updateVisibility();const s=i&&this._withinClippingArea,n=!(i||t||this._withinClippingArea||this._intersectsClippingArea);return!this.renderData||s||n||this.setPendingUpdate(8),!0}updateVisibility(){this._dirty=!0,this._surface.setTileTreeDirty(!1)}getLayerInfo(e,t){return this.layerInfo[t][e]}hasLayerData(e,t){const i=this.layerInfo[t][e];return!(!i?.data||i.dataInvalidated)}get updating(){if(this.hasPendingUpdates)return!0;for(const e of L){const t=this.layerInfo[e];for(const e of t)if(e.loadingAgent&&e.loadingAgent!==$&&e.loadingAgent.updating)return!0}return!1}_isSuspended(e){return!!this.hasPendingUpdate(1)||0!==e&&!this._loadable}get hasPendingUpdates(){return 0!==this._pendingUpdates}hasPendingUpdate(e){return(this._pendingUpdates&e)===e}setPendingUpdate(e){const t=this._pendingUpdates;return this._pendingUpdates|=e,1===e||4===e?this._surface.setTileTreeDirty(!0):this._surface.requestUpdate(),t!==this._pendingUpdates}resetPendingUpdate(e){return!!this.hasPendingUpdate(e)&&(this._pendingUpdates&=~e,!0)}requestLayerData(e,t,s){const n=this.layerInfo[t][e];if(n.waitingAgents.has(s))return console.warn("agent already requested this piece of map data (tile %s, agent tile %s, layer: %d/%d)",this._lij.toString(),s.tile.lij.toString(),t,e),!0;if(n.waitingAgents.push(s),n.data&&!n.dataInvalidated){console.warn("agent requested existing data (tile %s, agent tile %s, layer: %d/%d)",this._lij.toString(),s.tile.lij.toString(),t,e);const i=B(n.data);return s.dataArrived(this,i),!0}if(n.requestPromise)return!0;i(n.requestAbort),n.requestAbort=new AbortController;const r=this._surface.requestTileData(this,e,t,n.requestAbort);if(!r)return n.requestAbort=null,!1;const a=()=>{n.requestPromise===r&&(n.requestPromise=null,n.requestAbort=null)};return n.requestPromise=r,r.then(a,a),!0}get leaf(){return null==this._children[0]}hasLij(e){return this._lij[0]===e[0]&&this._lij[1]===e[1]&&this._lij[2]===e[2]}findByLij(e){if(this.hasLij(e))return this;const t=this._children;if(!t[0])return null;return t[0].findByLij(e)||t[1].findByLij(e)||t[2].findByLij(e)||t[3].findByLij(e)}distanceToSquared(e){return r(n(pe,this._center[1].center,e))}containsPoint(e){const t=this.extent;return e[0]>=t[0]&&e[1]>=t[1]&&e[0]<=t[2]&&e[1]<=t[3]}containsPointXY(e,t){const i=this.extent;return e>=i[0]&&t>=i[1]&&e<=i[2]&&t<=i[3]}unrequestLayerData(e,t,i){const s=this.layerInfo[t][e],n=s.waitingAgents,r=null!=n.removeUnordered(i);E(r,"agent has not requested this piece of map data"),n.length<1&&(s.abortRequest(),this.setMemoryDirty())}dataArrived(e,t,i){const s=B(i),n=this.layerInfo[t][e];n.data=i,n.dataInvalidated=!1,n.waitingAgents.forAll(e=>e.dataArrived(this,s)),n.waitingAgents.clear(),this.setMemoryDirty()}dataMissing(e,t){const i=this.layerInfo[t][e];i.dataMissing=!0,i.waitingAgents.forAll(e=>e.dataMissing()),i.waitingAgents.clear(),this.setMemoryDirty()}updateRenderData(e,t,i){switch(i&&this.forEachLoadedNeighbor(i=>i.updateRenderData(e,t)),e){case 1:return this._updateTexture(t);case 0:return this._updateGeometry()}}_updateTexture(e){this.renderData&&(this.resetPendingUpdate(0===e?16:32),this.setPendingUpdate(0===e?32:16))}_updateGeometry(){this.setPendingUpdate(8);for(const e of this.layerInfo[0])e.pendingUpdates|=8}invalidateLayerData(e,t){this.layerInfo[t][e].invalidateSourceData(),this.restartAgents(t)}computeElevationBounds(){const e=this._elevationBoundsMin,t=this._elevationBoundsMax;let i=1/0,s=-1/0;const n=this.layerInfo[0];let r=!0;for(const a of n)null!=a.elevationBounds&&(i=Math.min(i,a.elevationBounds.minElevation),s=Math.max(s,a.elevationBounds.maxElevation),a.elevationBounds.hasNoDataValues||(r=!1));r&&(i=Math.min(i,0),s=Math.max(s,0)),e===i&&t===s||(this._elevationBoundsMin=i,this._elevationBoundsMax=s,this.updateRadiusAndCenter(),this._surface.setTileTreeDirty(!1))}_updateCenter(){const e=this._elevationBoundsMin,t=this._elevationBoundsMax,i=.5*(e+t),s=this._center;l(pe,this.up,i),o(s[1].center,this.centerAtSeaLevel,pe),l(pe,this.up,e),o(s[0],this.centerAtSeaLevel,pe),l(pe,this.up,t),o(s[2],this.centerAtSeaLevel,pe)}findElevationBoundsForLayer(e,t){const i=this.layerInfo[0][e],s=this.elevationLevelDelta,n=Math.max(this.elevationLevel-s,0),r=i.elevationBounds;if(null!=r&&r.level>=t&&r.level<=n)return;const a=this._surface.layerViewByIndex(e,0);if(!K(this,a))return;const l=re;let o=!1;const h=i.data;if(h&&h.level<=n){const e=i.data;l.minElevation=e.samplerData.data.minValue,l.maxElevation=e.samplerData.data.maxValue,l.hasNoDataValues=e.samplerData.data.hasNoDataValues,l.level=this.level,o=!0}else{let t,i,r=0;for(let a=this._parent;a&&(!i||r<s)&&(r=this.elevationLevel-a.level,t=i||t,i=a.layerInfo[0][e].data,!(!i&&t&&a.level<=n));a=a.parent);i=i||t,i&&(i.computeMinMaxValue(this._lij[0],this._lij[1],this._lij[2],l),l.minElevation!==1/0&&(l.level=i.level,o=!0))}o&&(null==i.elevationBounds&&(i.elevationBounds=new x),i.elevationBounds.copyFrom(l))}modifyLayers(e,t,i){const s=this.layerInfo[i];for(const a of s)a.loadingAgent&&a.loadingAgent!==$&&(ie(a.loadingAgent),a.loadingAgent=null),a.waitingAgents.clear();for(let a=0;a<s.length;++a)void 0===e[a]&&s[a].release();const n=new Array(...s),r=t.length;s.length=r;for(let a=0;a<r;a++){const e=t[a];s[a]=e>-1?n[e]:Q.acquire(this._surface.upsampleInfoPool)}this.setMemoryDirty()}restartAgents(e){this.renderData&&(this._createOrUpdateAgents(0,e),this.updateRenderData(e,0))}updateAgents(e){if(this.renderData){const t=this.layerInfo[e];for(const e of t)e.loadingAgent===$&&(e.loadingAgent=null);this._createOrUpdateAgents(0,e)}}updateAgentSuspension(){for(const e of L){const t=this._isSuspended(e);for(const i of this.layerInfo[e])i.loadingAgent&&i.loadingAgent!==$&&(i.loadingAgent.setSuspension(t),i.loadingAgent===$&&this.updateRenderData(e,0))}}removeLayerAgent(e,t){const i=this.layerInfo[t][e];i.loadingAgent&&i.loadingAgent!==$&&i.loadingAgent.dispose(),i.loadingAgent=null}agentDone(e,t){const i=this.layerInfo[t][e];i.loadingAgent=$,i.data||null!=i.upsampleInfo||this._createOrUpdateAgents(e+1,t)}_hasBlendableAncestor(e){return"normal"!==e.blendMode||A(e.parent)&&this._hasBlendableAncestor(e.parent)}_hasBlendModes(e,t,i){for(let s=e;s<t;++s){const e=this._surface.layerViewByIndex(s,i);if(P(e)&&"normal"!==e?.layer?.blendMode||A(e?.layer?.parent)&&this._hasBlendableAncestor(e?.layer?.parent))return!0}return!1}_createOrUpdateAgents(e,t){const i=this.layerInfo[t];if(0===i.length)return;const s=this._isSuspended(t);for(let n=e;n<i.length;++n){const r=i[n],a=this._surface.layerViewByIndex(n,t);let l=!1;if(r.loadingAgent?K(this,a)?(r.loadingAgent!==$&&r.loadingAgent.setSuspension(s),r.loadingAgent!==$&&(l=r.loadingAgent.update())):r.dispose():K(this,a)&&(r.loadingAgent=te(this,n,t,s),l=r.loadingAgent.startLoading(),l?r.loadingAgent===$&&this.setPendingUpdate(8):(ie(r.loadingAgent),r.loadingAgent=$)),r.loadingAgent===$&&this.updateRenderData(t,0),!a.destroyed&&!this._hasBlendModes(e,i.length,t)&&l&&a.isOpaque)return}}_isWithinExtent(e){const t=this.extent;return t[0]>=e[0]&&e[2]>=t[2]&&t[1]>=e[1]&&e[3]>=t[3]}intersectsExtent(e){const t=this.extent;return t[2]>=e[0]&&e[2]>=t[0]&&t[3]>=e[1]&&e[3]>=t[1]}getElevationVerticesPerSide(e){const i=this.elevationLevel-this.level,s=Math.max(this.level-e,this.elevationLevelDelta-i),n=t(1+(this._maxTesselation>>s),2,this._maxTesselation+1),r=this.minimumVerticesPerSide;return Math.max(n,r)}_findLIJ(e,t){if(!e)return null;const i=this.surface.rootTiles;if(null!=i)for(const s of i)if(ae(s,e)){let i=s,n=e[0]-i.level-1;for(;n>=0&&!i.leaf&&!t(i);){const t=e[1]>>n&1,s=e[2]>>n&1;i=i.children[2*t+s],n--}return t(i)?i:null}return null}findNeighborTile(e,t){const i=this._lij,s=this._getNeighborLIJ(i,e);return s?le(i,s)?t(this)?this:null:this._findLIJ(s,t):null}findCorner(e,t){const i=1===e?1:7===e?0:5===e?2:3;let s=this;for(;s.children[0]&&(!t||!t(s));)s=s.children[i];return s}findNeighborCornerTileExact(e,t){return this.findNeighborTile(e,e=>t(e)||e.level===this.level)?.findCorner(O(e),t)||null}forAllSubtreeOnSide(e,t){const i=0===e?[0,1]:1===e?[1]:2===e?[1,3]:3===e?[3]:4===e?[2,3]:5===e?[2]:6===e?[0,2]:[0],s=e=>{const n=e.children;!t(e)&&n[0]&&i.forEach(e=>s(n[e]))};s(this)}getNeighborEdgeStartVertexIndex(e,t){if(!t)return 0;const i=this.level-t.level;if(R(!q||i>=0),0===i)return 0;const s=2**i,n=!(1&~e),r=n?0:1,a=t.lij[r+1]*s,l=this._lij[r+1],o=l-a,h=n?s-1-o:o;return q&&(R(a<=l&&l<a+s),R(0<=h&&h<s)),h}forEachLoadedNeighbor(e){const t=this.level,i=e=>e.level===t||e.loaded;V.forEach(t=>{const s=this.findNeighborTile(t,i);null!=s&&s!==this&&s.forAllSubtreeOnSide(N(t),i=>!!i.loaded&&(e(i,t),!0))}),G.forEach(t=>{const s=this.findNeighborTile(t,i)?.findCorner(O(t),e=>e.loaded);R(!s||oe(this,s,t)),s?.loaded&&e(s,t)})}_getNeighborLIJ(e,t){const i=z(t)?-1:W(t)?1:0,s=H(t)?-1:J(t)?1:0,n=[e[0],e[1]+i,e[2]+s];return n[1]<0?null:this.surface.isGlobal?this._wrapLIJ(n):n[2]<0?null:n}_wrapLIJ(e){return!e||e[1]<0||e[1]>=2**e[0]?null:this.surface.wrapEastWest(e)}isEdgeNeighbor(e,t){if(null==e)return!1;if(0===this.level&&0===e.level){if(this._eastEnd&&e._westEnd&&2===t)return!0;if(this._westEnd&&e._eastEnd&&6===t)return!0}const i=Math.max(1e-6*(this.extent[2]-this.extent[0]),1);switch(t){case 0:return k(this.extent[3],e.extent[1],i);case 4:return k(this.extent[1],e.extent[3],i);case 2:return k(this.extent[2],e.extent[0],i)||k(this.extent[2],-e.extent[0],i);case 6:return k(this.extent[0],e.extent[2],i)||k(this.extent[0],-e.extent[2],i)}}get _eastEnd(){return this._lij[2]===this.surface.lijEastEnd(this.level)-1}get _westEnd(){return 0===this._lij[2]}checkGeometryWaterproofness(){F&&(R(this.loaded),this.renderData?.checkGeometryWaterproofness())}shouldHaveNeighbor(e){const t=this.extent,i=this.surface.rootTilesExtent,s=.25*(t[2]-t[0]);if(z(e)&&t[3]+s>=i[3])return!1;if(W(e)&&t[1]-s<=i[1])return!1;const n=this.surface.isGlobal;return!(!n&&H(e)&&t[0]-s<=i[0])&&!(!n&&J(e)&&t[2]+s>=i[2])}updateDistanceToPOI(e){const t=this._lastPOI;if(this.distanceToPOI>=0&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return;d(this._lastPOI,e);const i=this._center[1].center,s=e[0]-i[0],n=e[1]-i[1],r=e[2]-i[2];this.distanceToPOI=s*s+n*n+r*r}updateOverlayParameters(e){const{renderData:t}=this;if(!t)return;const{overlays:i,longitudeCyclical:s}=e,n=t.overlay;if(0===i.length)this._clearTileOverlayData(0,n),this._clearTileOverlayData(1,n);else{const[e,t]=i,r=this.extent;_(e.extent,r,s)||m(r,e.extent,s)||m(r,t.extent,s)?(this._setOverlayData(i,s,r,0,n),this._setOverlayData(i,s,r,1,n)):(this._clearTileOverlayData(0,n),this._clearTileOverlayData(1,n))}}_setOverlayData(e,t,i,s,n){const r=e[s].extent,a=y(r),l=v(r);let o=i[0];if(t){o=t.minimalMonotonic(r[0],o);const e=t.minimalMonotonic(r[0],i[2]);o>e&&(o=e-(i[2]-i[0]))}if(0===a||0===l)return void n.setOffsetAndScale(s,0,0,1,1);const h=y(i)/a,d=v(i)/l,u=(o-r[0])/a,c=(i[1]-r[1])/l;n.setOffsetAndScale(s,u,c,h,d)}_clearTileOverlayData(e,t){t.setOffsetAndScale(e,-1,-1,-1,-1)}}function te(e,t,i,s){const n=0===i?ne.acquire():se.acquire();return n.init(e,t,i,s),n}function ie(e){e.dispose(),b(e)?ne.release(e):T(e)&&se.release(e)}const se=new s(()=>new j),ne=new s(()=>new D),re=new x;function ae(e,t){const i=e.lij,s=t[0]-i[0];return!(s<0)&&(t[1]>>s===i[1]&&t[2]>>s===i[2])}function le(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function oe(e,t,i){return null!=e&&null!=t&&t!==e&&(e.level>=t.level?he(e,t,i):he(t,e,O(i)))}function he(e,t,i){R(e.level>=t.level);const s=X(i),n=Y(i),r=e.extent,a=t.extent,l=[s?r[0]:r[2],n?r[3]:r[1]],o=[s?a[2]:a[0],n?a[1]:a[3]],h=1e-5*(r[2]-r[0]),d=k(l[0],o[0],h)||e.surface.isGlobal&&k(l[0],-o[0],h),u=k(l[1],o[1],h);if(d&&u)return!0;if(e.level===t.level)return R(!1),!1;if(!d&&!u)return R(!1),!1;const c=d?de(a[1],a[3],r[1],r[3],h):de(a[0],a[2],r[0],r[2],h);return R(c),c}function de(e,t,i,s,n){return e-n<=i&&i<=s&&s<=t+n}const ue=u(),ce=u(),ge=u(),pe=u();export{ee as Tile,oe as isCornerNeighbor,le as lijEquals};
5
+ import{toConst as e}from"../../../core/compilerUtils.js";import{clamp as t}from"../../../core/mathUtils.js";import{abortMaybe as i}from"../../../core/maybe.js";import s from"../../../core/ObjectPool.js";import{e as n,F as r,g as a,j as l,i as o,b as h,d}from"../../../chunks/vec32.js";import{create as u,unitZ as c}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{getReferenceEllipsoid as g}from"../../../geometry/ellipsoidUtils.js";import{create as p,equals as f,rectangleContainsRectangleCyclicalAware as _,rectanglesIntersectCyclicalAware as m,width as y,height as v}from"../../../geometry/support/aaBoundingRect.js";import{Sphere as M}from"../../../geometry/support/sphere.js";import{isGroupLayer as A}from"../../../layers/support/layerUtils.js";import{ElevationBounds as x}from"./ElevationBounds.js";import{ElevationTileAgent as D,isElevationTileAgent as b}from"./ElevationTileAgent.js";import{LayerClasses as L}from"./LayerClass.js";import{MapDataCacheItem as I}from"./MapDataCacheItem.js";import{MapTileAgent as j,isMapTileAgent as T}from"./MapTileAgent.js";import{maxPatchTesselation as C}from"./TerrainConst.js";import{isVectorTile as B,isTileTexture as U,isRasterTile as S,isImageWithType as w}from"./TerrainData.js";import{weakAssert as E,isBlendableLayerView as P,oppositeCorner as O,internalAssert as R,enableTerrainInternalChecks as q,neighborEdgeIndices as V,oppositeEdge as N,neighborCornerIndices as G,almostEquals as k,enableWaterproofTests as F,isNorth as z,isSouth as W,isWest as H,isEast as J,isWestCorner as X,isNorthCorner as Y}from"./terrainUtils.js";import{tileAgentDone as $}from"./TileAgent.js";import{TilePerLayerInfo as Q}from"./TilePerLayerInfo.js";import{fallsWithinLayerView as K}from"./tileUtils.js";const Z=.1;class ee{constructor(){this._lij=[0,0,0],this._children=[null,null,null,null],this._pendingUpdates=0,this._dirty=!0,this._previouslyRendered=!1,this.extent=p(),this._elevationBoundsMin=NaN,this._elevationBoundsMax=0,this.layerInfo=[[],[]],this.extentInRadians=p(),this.centerAtSeaLevel=u(),this._center=[u(),new M,u()],this.up=c(),this._withinClippingArea=!0,this._intersectsClippingArea=!0,this._maxTesselation=0,this._usedMemory=0,this._rasterTileMemory=0,this._vectorTileMemory=0,this._mapDataRefCount=0,this.screenDepth=0,this.renderOrder=0,this._edgeLen=0,this._edgeLen2=0,this._curvatureHeight=0,this.onCompressionFinished=()=>{this.setPendingUpdate(16),this.setMemoryDirty()},this.extentMidX=0,this.extentMidY=0,this.distanceToPOI=-1,this._lastPOI=u(),this.maxLevelDeltaNeighborCount=0,this.unmergableChildCount=0}get lij(){return this._lij}get spatialReference(){return this._surface.spatialReference??this._surface.tilingScheme.spatialReference}get isDisposed(){return null==this._surface}get elevationLevelDelta(){return this._surface.getElevationLevelDelta(this.level)}static prune(){se.prune(0),ne.prune(0),Q.prune()}get _cached(){return!this.leaf&&this._mapDataRefCount<=0}get withinClippingArea(){return this._withinClippingArea}get intersectsClippingArea(){return this._intersectsClippingArea}get clippingArea(){return this._clippingArea}get parent(){return this._parent}get children(){return this._children}get surface(){return this._surface}get elevationBoundsMin(){return this._elevationBoundsMin}get elevationBoundsMax(){return this._elevationBoundsMax}get level(){return this._lij[0]}get key(){return`${this._lij[0]}/${this._lij[1]}/${this._lij[2]}`}get edgeLen(){return this._edgeLen}get radius(){return this._center[1].radius}get visible(){return this._dirty&&this.computeVisibility(),this._visible}get frustumVisibility(){return this._dirty&&this.computeVisibility(),this._frustumVisibility}computeVisibility(){this._dirty=!1;const e=this.parent,t=e?.frustumVisibility??1;this._frustumVisibility=0===t?0:2===t?2:this._calculateFrustumVisibility(this.surface.frustum);const i=2!==this._frustumVisibility&&this._intersectsClippingArea;i!==this._visible&&(this._visible=i,this._surface.emit("tiles-visibility-changed"),this._surface.renderer.setDirty(),this.updateAgentSuspension())}get _loadable(){return this.visible||this._surface.view.state.fixedContentCamera}get rendered(){const e=!!this.renderData;return e!==this._previouslyRendered&&(this._surface.emit("tiles-visibility-changed"),this._previouslyRendered=e,this._surface.renderer.setDirty()),e}init(e,t,i,s,n){this._lij[0]=e,this._lij[1]=t,this._lij[2]=i,this.ellipsoid=g(n.tilingScheme.spatialReference),n.tilingScheme.getExtent(e,t,i,this.extent),n.tilingScheme.convertExtentToRadians(this.extent,this.extentInRadians),this.extentMidX=.5*(this.extent[0]+this.extent[2]),this.extentMidY=.5*(this.extent[1]+this.extent[3]),this._withinClippingArea=!0,this._intersectsClippingArea=!0,this._clippingArea=null,this._mapDataRefCount=0,n.upsampleMapCache.pop(this.key),this._edgeLen=0,this._edgeLen2=0,this._center[1].radius=0,this.elevationLevel=e,s&&!Number.isNaN(s.elevationBoundsMin)?(this._elevationBoundsMin=s.elevationBoundsMin,this._elevationBoundsMax=s.elevationBoundsMax):(this._elevationBoundsMin=0,this._elevationBoundsMax=0),this._pendingUpdates=0,this.renderData=null,this.screenDepth=0,this._visible=!1,this._previouslyRendered=!1,this._parent=s,this.clearChildren(),this._surface=n,this.updateVisibility(),this.maxLevelDeltaNeighborCount=0,this.unmergableChildCount=0;for(const r of L){const e=n.numLayers(r),t=this.layerInfo[r];for(const i of t)i.release();t.length=e;for(let i=0;i<e;i++)t[i]=Q.acquire(this._surface.upsampleInfoPool),0===r&&this.findElevationBoundsForLayer(i,-1)}this.computeElevationBounds(),this._maxTesselation=Math.min(n.tilingScheme.pixelSize,C)}dispose(){E(!this.renderData,"tile.renderData was not unloaded"),this._surface?.upsampleMapCache.pop(this.key),this.layerInfo.forEach(e=>{e.forEach(e=>e.release()),e.length=0}),this._surface=this._parent=null,this.clearChildren(),this.setMemoryDirty()}refMapData(){++this._mapDataRefCount,this._cached||this._surface.upsampleMapCache.pop(this.key)}unrefMapData(){--this._mapDataRefCount,this._cached&&this.cachedMemory>0&&this._surface.upsampleMapCache.put(this.key,new I(e(this)))}setMemoryDirty(){this._usedMemory=0}get usedMemory(){return this._ensureUsedMemory()+(this._cached?0:this.mapDataMemory)}get cachedMemory(){return this._ensureUsedMemory(),null==this._surface?this.usedMemory:this._cached?this.mapDataMemory:0}get mapDataMemory(){return this._rasterTileMemory+this._vectorTileMemory}get _cpuImageMemorySize(){const e=4,t=this._surface.tilingScheme.pixelSize;return t*t*e}_ensureUsedMemory(){if(this._usedMemory>0)return this._vectorTileMemory=this.layerInfo[1].reduce((e,{data:t})=>e+(B(t)?t.usedMemoryPerReference:0),0),this._usedMemory;this._usedMemory=this._baseUsedMemory,this._rasterTileMemory=0,this._vectorTileMemory=0;for(const{data:e}of this.layerInfo[1])B(e)?this._vectorTileMemory+=e.usedMemoryPerReference:this._rasterTileMemory+=this.getTerrainDataMemory(e);for(const e of this.layerInfo[0])this._usedMemory+=e.data?this._cpuImageMemorySize:0;return this.renderData&&(this._usedMemory+=this.renderData.estimatedGeometryMemoryUsage,this._rasterTileMemory+=this.renderData.texture?.usedMemory??0),this._cached&&this._surface.upsampleMapCache.updateSize(this.key),this._usedMemory}getUsedMemoryForLayer(e,t){const i=this.layerInfo[e][t];return i?.data?1===e?this._cached?0:this.getTerrainDataMemory(i.data):0===e?this._cpuImageMemorySize:0:0}getTerrainDataMemory(e){return U(e)?e.texture.usedMemory:S(e)?e.memoryUsage:B(e)?e.usedMemoryPerReference:w(e)||e instanceof HTMLImageElement?this._cpuImageMemorySize:0}updateScreenDepth(e){const[t,i,s]=this._center[1].center,n=e,r=n[2]*t+n[6]*i+n[10]*s+n[14];this.screenDepth=r<0?0:r/(n[3]*t+n[7]*i+n[11]*s+n[15])}shouldSplit(e,t,i){if(!this.visible)return 0;if(e.frustum&&(!this._intersectsClippingArea||2===this._calculateFrustumVisibility(e.frustum)))return 0;const s=this.level;n(ue,this._center[1].center,t);let d=r(ue),u=ue,c=this._center[1].center;n(ce,this._center[0],t);const g=r(ce);g<d&&(d=g,u=ce,c=this._center[0]),n(ge,this._center[2],t);const p=r(ge);if(p<d&&(d=p,u=ge,c=this._center[2]),this._edgeLen2>d&&s<e.maxLod)return 1;const f=Math.sqrt(d),_=e.fovX*f*2,m=this._edgeLen/_,y=()=>{if(s<e.maxLod)return this.elevationLevel=s,0;const t=s+Math.ceil(-Math.log2(e.relativeWidthLimit/m));return t!==this.elevationLevel?(this.elevationLevel=t,2):0},v=null!=i?i-s:1/0;if(v<=.5)return y();const M=a(this.up,ue),A=this._elevationBoundsMax-this._elevationBoundsMin,x=A/this.edgeLen;if(e.aboveGround&&M>0&&x<.001){if(M/f-Math.sin(this._curvatureHeight/(this.edgeLen*Math.SQRT1_2)*Math.PI)-x>0)return 0}const D=null!=i?3-Math.min(v,2):1;if(m*D<e.relativeWidthLimit||s>=e.maxLod)return y();if(s<7)return 1;l(pe,this.up,M),n(pe,pe,u);const b=r(pe);if(b<=this.radius*this.radius)return 1;l(pe,pe,this.radius/Math.sqrt(b)),o(pe,pe,c),n(pe,t,pe);const L=Math.min(1,(Math.abs(a(pe,this.up))+.5*A+this._curvatureHeight)/h(pe)),I=Z/e.angledSplitBias,j=e.fovY*f*2;return L*(this._edgeLen/j*D)<I*e.relativeHeightLimit?0:1}createChildren(){const e=this._children,t=this.lij[0]+1,i=2*this.lij[1],s=2*this.lij[2];return e[0]=this.surface.createTile(t,i,s,this),e[1]=this.surface.createTile(t,i,s+1,this),e[2]=this.surface.createTile(t,i+1,s,this),e[3]=this.surface.createTile(t,i+1,s+1,this),e}clearChildren(){this._children[0]=this._children[1]=this._children[2]=this._children[3]=null}get loaded(){return this.renderData?.hasGeometry??!1}load(){this.refMapData();for(const e of L)this._createOrUpdateAgents(0,e);this.surface.renderer.loadTile(this)}unload(){this.renderData&&this.unrefMapData(),this.surface.renderer.unloadTile(this);for(const e of L){const t=this.layerInfo[e];for(const e of t)e.loadingAgent&&e.loadingAgent!==$&&(ie(e.loadingAgent),e.loadingAgent=null),e.pendingUpdates=0}this.resetPendingUpdate(8),this.resetPendingUpdate(16),this.resetPendingUpdate(32)}unloadMapData(){const e=this.layerInfo[1];for(const t of e)t.loadingAgent&&t.loadingAgent!==$&&(ie(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0,t.invalidateSourceData();this.renderData?.releaseTexture(),this.setMemoryDirty()}updateClippingStatus(e){if(f(e,this._clippingArea))return!1;const t=this._intersectsClippingArea,i=this._withinClippingArea;null!=e?(this._intersectsClippingArea=this.intersectsExtent(e),this._withinClippingArea=this._isWithinExtent(e)):(this._intersectsClippingArea=!0,this._withinClippingArea=!0),this._clippingArea=e,this.updateVisibility();const s=i&&this._withinClippingArea,n=!(i||t||this._withinClippingArea||this._intersectsClippingArea);return!this.renderData||s||n||this.setPendingUpdate(8),!0}updateVisibility(){this._dirty=!0,this._surface.setTileTreeDirty(!1)}getLayerInfo(e,t){return this.layerInfo[t][e]}hasLayerData(e,t){const i=this.layerInfo[t][e];return!(!i?.data||i.dataInvalidated)}get updating(){if(this.hasPendingUpdates)return!0;for(const e of L){const t=this.layerInfo[e];for(const e of t)if(e.loadingAgent&&e.loadingAgent!==$&&e.loadingAgent.updating)return!0}return!1}_isSuspended(e){return!!this.hasPendingUpdate(1)||0!==e&&!this._loadable}get hasPendingUpdates(){return 0!==this._pendingUpdates}hasPendingUpdate(e){return(this._pendingUpdates&e)===e}setPendingUpdate(e){const t=this._pendingUpdates;return this._pendingUpdates|=e,1===e||4===e?this._surface.setTileTreeDirty(!0):this._surface.requestUpdate(),t!==this._pendingUpdates}resetPendingUpdate(e){return!!this.hasPendingUpdate(e)&&(this._pendingUpdates&=~e,!0)}requestLayerData(e,t,s){const n=this.layerInfo[t][e];if(n.waitingAgents.has(s))return console.warn("agent already requested this piece of map data (tile %s, agent tile %s, layer: %d/%d)",this._lij.toString(),s.tile.lij.toString(),t,e),!0;if(n.waitingAgents.push(s),n.data&&!n.dataInvalidated){console.warn("agent requested existing data (tile %s, agent tile %s, layer: %d/%d)",this._lij.toString(),s.tile.lij.toString(),t,e);const i=B(n.data);return s.dataArrived(this,i),!0}if(n.requestPromise)return!0;i(n.requestAbort),n.requestAbort=new AbortController;const r=this._surface.requestTileData(this,e,t,n.requestAbort);if(!r)return n.requestAbort=null,!1;const a=()=>{n.requestPromise===r&&(n.requestPromise=null,n.requestAbort=null)};return n.requestPromise=r,r.then(a,a),!0}get leaf(){return null==this._children[0]}hasLij(e){return this._lij[0]===e[0]&&this._lij[1]===e[1]&&this._lij[2]===e[2]}findByLij(e){if(this.hasLij(e))return this;const t=this._children;if(!t[0])return null;return t[0].findByLij(e)||t[1].findByLij(e)||t[2].findByLij(e)||t[3].findByLij(e)}distanceToSquared(e){return r(n(pe,this._center[1].center,e))}containsPoint(e){const t=this.extent;return e[0]>=t[0]&&e[1]>=t[1]&&e[0]<=t[2]&&e[1]<=t[3]}containsPointXY(e,t){const i=this.extent;return e>=i[0]&&t>=i[1]&&e<=i[2]&&t<=i[3]}unrequestLayerData(e,t,i){const s=this.layerInfo[t][e],n=s.waitingAgents,r=null!=n.removeUnordered(i);E(r,"agent has not requested this piece of map data"),n.length<1&&(s.abortRequest(),this.setMemoryDirty())}dataArrived(e,t,i){const s=B(i),n=this.layerInfo[t][e];n.data=i,n.dataInvalidated=!1,n.waitingAgents.forAll(e=>e.dataArrived(this,s)),n.waitingAgents.clear(),this.setMemoryDirty()}dataMissing(e,t){const i=this.layerInfo[t][e];i.dataMissing=!0,i.waitingAgents.forAll(e=>e.dataMissing()),i.waitingAgents.clear(),this.setMemoryDirty()}updateRenderData(e,t,i){switch(i&&this.forEachLoadedNeighbor(i=>i.updateRenderData(e,t)),e){case 1:return this._updateTexture(t);case 0:return this._updateGeometry()}}_updateTexture(e){this.renderData&&(this.resetPendingUpdate(0===e?16:32),this.setPendingUpdate(0===e?32:16))}_updateGeometry(){this.setPendingUpdate(8);for(const e of this.layerInfo[0])e.pendingUpdates|=8}invalidateLayerData(e,t){this.layerInfo[t][e].invalidateSourceData(),this.restartAgents(t)}computeElevationBounds(){const e=this._elevationBoundsMin,t=this._elevationBoundsMax;let i=1/0,s=-1/0;const n=this.layerInfo[0];let r=!0;for(const a of n)null!=a.elevationBounds&&(i=Math.min(i,a.elevationBounds.minElevation),s=Math.max(s,a.elevationBounds.maxElevation),a.elevationBounds.hasNoDataValues||(r=!1));r&&(i=Math.min(i,0),s=Math.max(s,0)),e===i&&t===s||(this._elevationBoundsMin=i,this._elevationBoundsMax=s,this.updateRadiusAndCenter(),this._surface.setTileTreeDirty(!1))}_updateCenter(){const e=this._elevationBoundsMin,t=this._elevationBoundsMax,i=.5*(e+t),s=this._center;l(pe,this.up,i),o(s[1].center,this.centerAtSeaLevel,pe),l(pe,this.up,e),o(s[0],this.centerAtSeaLevel,pe),l(pe,this.up,t),o(s[2],this.centerAtSeaLevel,pe)}findElevationBoundsForLayer(e,t){const i=this.layerInfo[0][e],s=this.elevationLevelDelta,n=Math.max(this.elevationLevel-s,0),r=i.elevationBounds;if(null!=r&&r.level>=t&&r.level<=n)return;const a=this._surface.layerViewByIndex(e,0);if(!K(this,a))return;const l=re;let o=!1;const h=i.data;if(h&&h.level<=n){const e=i.data;l.minElevation=e.samplerData.data.minValue,l.maxElevation=e.samplerData.data.maxValue,l.hasNoDataValues=e.samplerData.data.hasNoDataValues,l.level=this.level,o=!0}else{let t,i,r=0;for(let a=this._parent;a&&(!i||r<s)&&(r=this.elevationLevel-a.level,t=i||t,i=a.layerInfo[0][e].data,!(!i&&t&&a.level<=n));a=a.parent);i=i||t,i&&(i.computeMinMaxValue(this._lij[0],this._lij[1],this._lij[2],l),l.minElevation!==1/0&&(l.level=i.level,o=!0))}o&&(null==i.elevationBounds&&(i.elevationBounds=new x),i.elevationBounds.copyFrom(l))}modifyLayers(e,t,i){const s=this.layerInfo[i];for(const a of s)a.loadingAgent&&a.loadingAgent!==$&&(ie(a.loadingAgent),a.loadingAgent=null),a.waitingAgents.clear();for(let a=0;a<s.length;++a)void 0===e[a]&&s[a].release();const n=new Array(...s),r=t.length;s.length=r;for(let a=0;a<r;a++){const e=t[a];s[a]=e>-1?n[e]:Q.acquire(this._surface.upsampleInfoPool)}this.setMemoryDirty()}restartAgents(e){this.renderData&&(this._createOrUpdateAgents(0,e),this.updateRenderData(e,0))}updateAgents(e){if(this.renderData){const t=this.layerInfo[e];for(const e of t)e.loadingAgent===$&&(e.loadingAgent=null);this._createOrUpdateAgents(0,e)}}updateAgentSuspension(){for(const e of L){const t=this._isSuspended(e);for(const i of this.layerInfo[e])i.loadingAgent&&i.loadingAgent!==$&&(i.loadingAgent.setSuspension(t),i.loadingAgent===$&&this.updateRenderData(e,0))}}removeLayerAgent(e,t){const i=this.layerInfo[t][e];i.loadingAgent&&i.loadingAgent!==$&&i.loadingAgent.dispose(),i.loadingAgent=null}agentDone(e,t){const i=this.layerInfo[t][e];i.loadingAgent=$,i.data||null!=i.upsampleInfo||this._createOrUpdateAgents(e+1,t)}_hasBlendableAncestor(e){return"normal"!==e.blendMode||A(e.parent)&&this._hasBlendableAncestor(e.parent)}_hasBlendModes(e,t,i){for(let s=e;s<t;++s){const e=this._surface.layerViewByIndex(s,i);if(P(e)&&"normal"!==e?.layer?.blendMode||A(e?.layer?.parent)&&this._hasBlendableAncestor(e?.layer?.parent))return!0}return!1}_createOrUpdateAgents(e,t){const i=this.layerInfo[t];if(0===i.length)return;const s=this._isSuspended(t);for(let n=e;n<i.length;++n){const r=i[n],a=this._surface.layerViewByIndex(n,t);let l=!1;if(r.loadingAgent?K(this,a)?(r.loadingAgent!==$&&r.loadingAgent.setSuspension(s),r.loadingAgent!==$&&(l=r.loadingAgent.update())):r.dispose():K(this,a)&&(r.loadingAgent=te(this,n,t,s),l=r.loadingAgent.startLoading(),l?r.loadingAgent===$&&this.setPendingUpdate(8):(ie(r.loadingAgent),r.loadingAgent=$)),r.loadingAgent===$&&this.updateRenderData(t,0),!a.destroyed&&!this._hasBlendModes(e,i.length,t)&&l&&a.isOpaque)return}}_isWithinExtent(e){const t=this.extent;return t[0]>=e[0]&&e[2]>=t[2]&&t[1]>=e[1]&&e[3]>=t[3]}intersectsExtent(e){const t=this.extent;return t[2]>=e[0]&&e[2]>=t[0]&&t[3]>=e[1]&&e[3]>=t[1]}getElevationVerticesPerSide(e){const i=this.elevationLevel-this.level,s=Math.max(this.level-e,this.elevationLevelDelta-i),n=t(1+(this._maxTesselation>>s),2,this._maxTesselation+1),r=this.minimumVerticesPerSide;return Math.max(n,r)}_findLIJ(e,t){if(!e)return null;const{rootTiles:i}=this.surface;if(null!=i)for(const s of i)if(ae(s,e)){let i=s,n=e[0]-i.level-1;for(;n>=0&&!i.leaf&&!t(i);){const t=e[1]>>n&1,s=e[2]>>n&1;i=i.children[2*t+s],n--}return t(i)?i:null}return null}findNeighborTile(e,t){const i=this._lij,s=this._getNeighborLIJ(i,e);return s?le(i,s)?t(this)?this:null:this._findLIJ(s,t):null}findCorner(e,t){const i=1===e?1:7===e?0:5===e?2:3;let s=this;for(;s.children[0]&&(!t||!t(s));)s=s.children[i];return s}findNeighborCornerTileExact(e,t){return this.findNeighborTile(e,e=>t(e)||e.level===this.level)?.findCorner(O(e),t)||null}forAllSubtreeOnSide(e,t){const i=0===e?[0,1]:1===e?[1]:2===e?[1,3]:3===e?[3]:4===e?[2,3]:5===e?[2]:6===e?[0,2]:[0],s=e=>{const n=e.children;!t(e)&&n[0]&&i.forEach(e=>s(n[e]))};s(this)}getNeighborEdgeStartVertexIndex(e,t){if(!t)return 0;const i=this.level-t.level;if(R(!q||i>=0),0===i)return 0;const s=2**i,n=!(1&~e),r=n?0:1,a=t.lij[r+1]*s,l=this._lij[r+1],o=l-a,h=n?s-1-o:o;return q&&(R(a<=l&&l<a+s),R(0<=h&&h<s)),h}forEachLoadedNeighbor(e){const t=this.level,i=e=>e.level===t||e.loaded;V.forEach(t=>{const s=this.findNeighborTile(t,i);null!=s&&s!==this&&s.forAllSubtreeOnSide(N(t),i=>!!i.loaded&&(e(i,t),!0))}),G.forEach(t=>{const s=this.findNeighborTile(t,i)?.findCorner(O(t),e=>e.loaded);R(!s||oe(this,s,t)),s?.loaded&&e(s,t)})}_getNeighborLIJ(e,t){const i=z(t)?-1:W(t)?1:0,s=H(t)?-1:J(t)?1:0,n=[e[0],e[1]+i,e[2]+s];return n[1]<0?null:this.surface.isGlobal?this._wrapLIJ(n):n[2]<0?null:n}_wrapLIJ(e){return!e||e[1]<0||e[1]>=2**e[0]?null:this.surface.wrapEastWest(e)}isEdgeNeighbor(e,t){if(null==e)return!1;if(0===this.level&&0===e.level){if(this._eastEnd&&e._westEnd&&2===t)return!0;if(this._westEnd&&e._eastEnd&&6===t)return!0}const i=Math.max(1e-6*(this.extent[2]-this.extent[0]),1);switch(t){case 0:return k(this.extent[3],e.extent[1],i);case 4:return k(this.extent[1],e.extent[3],i);case 2:return k(this.extent[2],e.extent[0],i)||k(this.extent[2],-e.extent[0],i);case 6:return k(this.extent[0],e.extent[2],i)||k(this.extent[0],-e.extent[2],i)}}get _eastEnd(){return this._lij[2]===this.surface.lijEastEnd(this.level)-1}get _westEnd(){return 0===this._lij[2]}checkGeometryWaterproofness(){F&&(R(this.loaded),this.renderData?.checkGeometryWaterproofness())}shouldHaveNeighbor(e){const t=this.extent,{rootTilesExtent:i}=this._surface,s=.25*(t[2]-t[0]);if(z(e)&&t[3]+s>=i[3])return!1;if(W(e)&&t[1]-s<=i[1])return!1;const n=this.surface.isGlobal;return!(!n&&H(e)&&t[0]-s<=i[0])&&!(!n&&J(e)&&t[2]+s>=i[2])}updateDistanceToPOI(e){const t=this._lastPOI;if(this.distanceToPOI>=0&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return;d(this._lastPOI,e);const i=this._center[1].center,s=e[0]-i[0],n=e[1]-i[1],r=e[2]-i[2];this.distanceToPOI=s*s+n*n+r*r}updateOverlayParameters(e){const{renderData:t}=this;if(!t)return;const{overlays:i,longitudeCyclical:s}=e,n=t.overlay;if(0===i.length)this._clearTileOverlayData(0,n),this._clearTileOverlayData(1,n);else{const[e,t]=i,r=this.extent;_(e.extent,r,s)||m(r,e.extent,s)||m(r,t.extent,s)?(this._setOverlayData(i,s,r,0,n),this._setOverlayData(i,s,r,1,n)):(this._clearTileOverlayData(0,n),this._clearTileOverlayData(1,n))}}_setOverlayData(e,t,i,s,n){const r=e[s].extent,a=y(r),l=v(r);let o=i[0];if(t){o=t.minimalMonotonic(r[0],o);const e=t.minimalMonotonic(r[0],i[2]);o>e&&(o=e-(i[2]-i[0]))}if(0===a||0===l)return void n.setOffsetAndScale(s,0,0,1,1);const h=y(i)/a,d=v(i)/l,u=(o-r[0])/a,c=(i[1]-r[1])/l;n.setOffsetAndScale(s,u,c,h,d)}_clearTileOverlayData(e,t){t.setOffsetAndScale(e,-1,-1,-1,-1)}}function te(e,t,i,s){const n=0===i?ne.acquire():se.acquire();return n.init(e,t,i,s),n}function ie(e){e.dispose(),b(e)?ne.release(e):T(e)&&se.release(e)}const se=new s(()=>new j),ne=new s(()=>new D),re=new x;function ae(e,t){const i=e.lij,s=t[0]-i[0];return!(s<0)&&(t[1]>>s===i[1]&&t[2]>>s===i[2])}function le(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function oe(e,t,i){return null!=e&&null!=t&&t!==e&&(e.level>=t.level?he(e,t,i):he(t,e,O(i)))}function he(e,t,i){R(e.level>=t.level);const s=X(i),n=Y(i),r=e.extent,a=t.extent,l=[s?r[0]:r[2],n?r[3]:r[1]],o=[s?a[2]:a[0],n?a[1]:a[3]],h=1e-5*(r[2]-r[0]),d=k(l[0],o[0],h)||e.surface.isGlobal&&k(l[0],-o[0],h),u=k(l[1],o[1],h);if(d&&u)return!0;if(e.level===t.level)return R(!1),!1;if(!d&&!u)return R(!1),!1;const c=d?de(a[1],a[3],r[1],r[3],h):de(a[0],a[2],r[0],r[2],h);return R(c),c}function de(e,t,i,s,n){return e-n<=i&&i<=s&&s<=t+n}const ue=u(),ce=u(),ge=u(),pe=u();export{ee as Tile,oe as isCornerNeighbor,le as lijEquals};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t}from"tslib";import i from"../../../core/Accessor.js";import e from"../../../core/Logger.js";import{lerp as r}from"../../../core/mathUtils.js";import{createScreenPointArray as s,createRenderScreenPointArray3 as o}from"../../../core/screenUtils.js";import{property as n,subclass as h}from"../../../core/accessorSupport/decorators.js";import{copy as a,multiply as p,invert as u,transpose as l,frustum as _,equals as v,lookAt as c}from"../../../core/libs/gl-matrix-2/math/mat4.js";import{create as w}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{copy as d,exactEquals as y}from"../../../core/libs/gl-matrix-2/math/vec2.js";import{fromValues as g}from"../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{e as m,h as f,D as x,d as M,m as D,a as j,g as R,w as P,v as V,j as F,b as C,f as b,n as S,E as T}from"../../../chunks/vec32.js";import{create as I,UNIT_Z as A}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{c as E,e as O,a as U,d as H,f as k,t as z}from"../../../chunks/vec42.js";import{fromValues as W,create as Y}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{create as L,copy as X,fromMatrix as q}from"../../../geometry/support/frustum.js";import{create as G}from"../../../geometry/support/ray.js";import{projectPointSignedLength as N}from"../../../geometry/support/vector.js";import{viewAngle as B}from"../state/utils/viewUtils.js";import{fovd2fovx as J,fovx2fovd as K,fovd2fovy as Q,fovy2fovd as Z}from"../webgl-engine/lib/fov.js";var $;let tt=$=class extends i{constructor(t){super(t),this._ray=G(),this._viewport=W(0,0,1,1),this._padding=W(0,0,0,0),this._fov=55/180*Math.PI,this._nearFar=g(1,1e3),this._viewDirty=!0,this._viewMatrix=w(),this._viewProjectionDirty=!0,this._viewProjectionMatrix=w(),this._viewInverseTransposeMatrixDirty=!0,this._viewInverseTransposeMatrix=w(),this._frustumDirty=!0,this._frustum=L(),this._fullViewport=Y(),this._pixelRatio=1,this.row=0,this.column=0,this._rows=1,this._columns=1,this._center=I(),this._up=I(),this.relativeElevation=0}get pixelRatio(){return this._pixelRatio}set pixelRatio(t){this._pixelRatio=t>0?t:1}get rows(){return this._rows}set rows(t){this._rows=Math.max(1,t)}get columns(){return this._columns}set columns(t){this._columns=Math.max(1,t)}get eye(){return this._ray.origin}set eye(t){this._compareAndSetView(t,this._ray.origin)}get center(){return this._center}set center(t){this._compareAndSetView(t,this._center,"_center")}get ray(){return m(this._ray.direction,this.center,this.eye),this._ray}get up(){return this._up}set up(t){this._compareAndSetView(t,this._up,"_up")}get viewMatrix(){return this._ensureViewClean(),this._viewMatrix}set viewMatrix(t){a(this._viewMatrix,t),this.notifyChange("_viewMatrix"),this._viewDirty=!1,this._viewInverseTransposeMatrixDirty=!0,this._viewProjectionDirty=!0,this._frustumDirty=!0}get viewForward(){return this._ensureViewClean(),f(I(),-this._viewMatrix[2],-this._viewMatrix[6],-this._viewMatrix[10])}get viewUp(){return this._ensureViewClean(),f(I(),this._viewMatrix[1],this._viewMatrix[5],this._viewMatrix[9])}get viewRight(){return this._ensureViewClean(),f(I(),this._viewMatrix[0],this._viewMatrix[4],this._viewMatrix[8])}get nearFar(){return this._nearFar}get near(){return this._nearFar[0]}set near(t){this._nearFar[0]!==t&&(this._nearFar[0]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_nearFar"))}get far(){return this._nearFar[1]}set far(t){this._nearFar[1]!==t&&(this._nearFar[1]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_nearFar"))}get viewport(){return this._viewport}set viewport(t){this.x=t[0],this.y=t[1],this.width=t[2],this.height=t[3]}get screenViewport(){if(1===this.pixelRatio)return this._viewport;const t=E(Y(),this._viewport,1/this.pixelRatio),i=this._get("screenViewport");return i&&O(t,i)?i:t}get screenPadding(){if(1===this.pixelRatio)return this._padding;const t=E(Y(),this._padding,1/this.pixelRatio),i=this._get("screenPadding");return i&&O(t,i)?i:t}get x(){return this._viewport[0]}set x(t){t+=this._padding[3],this._viewport[0]!==t&&(this._viewport[0]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get y(){return this._viewport[1]}set y(t){t+=this._padding[2],this._viewport[1]!==t&&(this._viewport[1]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get width(){return this._viewport[2]}set width(t){this._viewport[2]!==t&&(this._viewport[2]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get height(){return this._viewport[3]}set height(t){this._viewport[3]!==t&&(this._viewport[3]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get fullWidth(){return this._viewport[2]+this._padding[1]+this._padding[3]}set fullWidth(t){this.width=t-(this._padding[1]+this._padding[3])}get fullHeight(){return this._viewport[3]+this._padding[0]+this._padding[2]}set fullHeight(t){this.height=t-(this._padding[0]+this._padding[2])}get fullViewport(){return this._fullViewport[0]=this._viewport[0]-this._padding[3],this._fullViewport[1]=this._viewport[1]-this._padding[2],this._fullViewport[2]=this.fullWidth,this._fullViewport[3]=this.fullHeight,this._fullViewport}get _aspect(){return this.width/this.height}get padding(){return this._padding}set padding(t){U(this._padding,t)||(this._viewport[0]+=t[3]-this._padding[3],this._viewport[1]+=t[2]-this._padding[2],this._viewport[2]-=t[1]+t[3]-(this._padding[1]+this._padding[3]),this._viewport[3]-=t[0]+t[2]-(this._padding[0]+this._padding[2]),H(this._padding,t),this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_padding"),this.notifyChange("_viewport"))}get viewProjectionMatrix(){return this._viewProjectionDirty&&(p(this._viewProjectionMatrix,this.projectionMatrix,this.viewMatrix),this._viewProjectionDirty=!1),this._viewProjectionMatrix}get projectionMatrix(){return this._projectionMatrixInternal}get inverseProjectionMatrix(){return u(w(),this.projectionMatrix)||this._get("inverseProjectionMatrix")||w()}get fov(){return this._fov}set fov(t){this._fov=t,this._viewProjectionDirty=!0,this._frustumDirty=!0}get fovX(){return J(this._fov,this.width,this.height)}set fovX(t){this._fov=K(t,this.width,this.height),this._viewProjectionDirty=!0,this._frustumDirty=!0}get fovY(){return Q(this._fov,this.width,this.height)}set fovY(t){this._fov=Z(t,this.width,this.height),this._viewProjectionDirty=!0,this._frustumDirty=!0}get distance(){return x(this.center,this.eye)}get frustum(){return this._recomputeFrustum(),this._frustum}get viewInverseTransposeMatrix(){return(this._viewInverseTransposeMatrixDirty||this._viewDirty)&&(u(this._viewInverseTransposeMatrix,this.viewMatrix),l(this._viewInverseTransposeMatrix,this._viewInverseTransposeMatrix),this._viewInverseTransposeMatrixDirty=!1),this._viewInverseTransposeMatrix}depthNDCToWorld(t){const{near:i,far:e}=this;return 2*i*e/(e+i-t*(e-i))}get perRenderPixelRatio(){return Math.tan(this.fovX/2)/(this.width/2)}get perScreenPixelRatio(){return this.perRenderPixelRatio*this.pixelRatio}get aboveGround(){return null!=this.relativeElevation&&this.relativeElevation>=0}get _projectionMatrixInternal(){const t=this.width,i=this.height,e=this.near*Math.tan(this.fovY/2)*2,r=e*this._aspect,s=e/this.rows,o=r/this.columns,n=-r/2+this.column*o,h=n+o,a=-e/2+this.row*s,p=a+s,u=_(w(),n*(1+2*this._padding[3]/t),h*(1+2*this._padding[1]/t),a*(1+2*this._padding[2]/i),p*(1+2*this._padding[0]/i),this.near,this.far),l=this._get("projectionMatrix");return l&&v(l,u)?l:u}copyFrom(t){M(this._ray.origin,t.eye),this.center=t.center,this.up=t.up,H(this._viewport,t.viewport),this.notifyChange("_viewport"),H(this._padding,t.padding),this.notifyChange("_padding"),d(this._nearFar,t.nearFar),this.notifyChange("_nearFar"),this._fov=t.fov,this.row=t.row,this.column=t.column,this.rows=t.rows,this.columns=t.columns,this.relativeElevation=t.relativeElevation;const i=t;return this._viewDirty=i._viewDirty,this._viewDirty||(a(this._viewMatrix,t.viewMatrix),this.notifyChange("_viewMatrix")),this._viewProjectionDirty=!0,this._frustumDirty=i._frustumDirty,this._frustumDirty||(X(this._frustum,t.frustum),this._frustumDirty=!1),i._viewInverseTransposeMatrixDirty?this._viewInverseTransposeMatrixDirty=!0:(a(this._viewInverseTransposeMatrix,t.viewInverseTransposeMatrix),this._viewInverseTransposeMatrixDirty=!1),H(this._fullViewport,t.fullViewport),this.pixelRatio=t.pixelRatio,this}copyViewFrom(t){this.eye=t.eye,this.center=t.center,this.up=t.up,this.fov=t.fov}clone(){return(new $).copyFrom(this)}equals(t){return D(this.eye,t.eye)&&D(this.center,t.center)&&D(this.up,t.up)&&U(this._viewport,t.viewport)&&U(this._padding,t.padding)&&y(this.nearFar,t.nearFar)&&this._fov===t.fov&&this.pixelRatio===t.pixelRatio&&this.relativeElevation===t.relativeElevation&&this.row===t.row&&this.column===t.column&&this.rows===t.rows&&this.columns===t.columns}almostEquals(t){const i=Math.max(1,1/this.pixelRatio,1/t.pixelRatio);if(Math.abs(t.fov-this._fov)>=.001||k(t.screenPadding,this.screenPadding)>=i||k(this.screenViewport,t.screenViewport)>=i||this.row!==t.row||this.column!==t.column||this.rows!==t.rows||this.columns!==t.columns)return!1;j(st,t.eye,t.center),j(ot,this.eye,this.center);const e=R(st,ot),r=P(st),s=P(ot),o=5e-4;return e*e>=(1-1e-10)*r*s&&V(t.eye,this.eye)<Math.max(r,s)*o*o}computeRenderPixelSizeAt(t){return this.computeRenderPixelSizeAtDist(this._viewDirectionDistance(t))}computeRenderPixelSizeAtDist(t){return t*this.perRenderPixelRatio}computeScreenPixelSizeAt(t){return this.computeScreenPixelSizeAtDist(this._viewDirectionDistance(t))}_viewDirectionDistance(t){return Math.abs(N(this.viewForward,m(st,t,this.eye)))}computeScreenPixelSizeAtDist(t){return t*this.perScreenPixelRatio}computeDistanceFromRadius(t,i){return t/Math.tan(Math.min(this.fovX,this.fovY)/(2*(i||1)))}getScreenCenter(t=s()){return t[0]=(this.padding[3]+this.width/2)/this.pixelRatio,t[1]=(this.padding[0]+this.height/2)/this.pixelRatio,t}getRenderCenter(t,i=.5,e=.5){return t[0]=this.padding[3]+this.width*i,t[1]=this.padding[2]+this.height*e,t[2]=.5,t}setGLViewport(t){const i=this.viewport,e=this.padding;t.setViewport(i[0]-e[3],i[1]-e[2],i[2]+e[1]+e[3],i[3]+e[0]+e[2])}applyProjection(t,i){t!==et&&M(et,t),et[3]=1,z(et,et,this.projectionMatrix);const e=Math.abs(et[3]);F(et,et,1/e);const s=this.fullViewport;i[0]=r(0,s[0]+s[2],.5+.5*et[0]),i[1]=r(0,s[1]+s[3],.5+.5*et[1]),i[2]=.5*(et[2]+1),i[3]=e}unapplyProjection(t,i){const e=this.fullViewport;et[0]=(t[0]/(e[0]+e[2])*2-1)*t[3],et[1]=(t[1]/(e[1]+e[3])*2-1)*t[3],et[2]=(2*t[2]-1)*t[3],et[3]=t[3],null!=this.inverseProjectionMatrix&&(z(et,et,this.inverseProjectionMatrix),i[0]=et[0],i[1]=et[1],i[2]=et[2])}projectToScreen(t,i){return this.projectToRenderScreen(t,nt),this.renderToScreen(nt,i),i}projectToRenderScreen(t,i){if(et[0]=t[0],et[1]=t[1],et[2]=t[2],et[3]=1,z(et,et,this.viewProjectionMatrix),0===et[3])return null;const e=et;F(e,e,1/Math.abs(et[3]));const s=this.fullViewport,o=r(0,s[0]+s[2],.5+.5*e[0]),n=r(0,s[1]+s[3],.5+.5*e[1]);return"x"in i?(i.x=o,i.y=n):(i[0]=o,i[1]=n,i.length>2&&(i[2]=.5*(e[2]+1))),i}unprojectFromScreen(t,i){return this.unprojectFromRenderScreen(this.screenToRender(t,nt),i)}unprojectFromRenderScreen(t,i){if(p(rt,this.projectionMatrix,this.viewMatrix),!u(rt,rt))return null;const e=this.fullViewport;return et[0]=2*(t[0]-e[0])/e[2]-1,et[1]=2*(t[1]-e[1])/e[3]-1,et[2]=2*t[2]-1,et[3]=1,z(et,et,rt),0===et[3]?null:(i[0]=et[0]/et[3],i[1]=et[1]/et[3],i[2]=et[2]/et[3],i)}constrainWindowSize(t,i,e,r){const s=t*this.pixelRatio,o=i*this.pixelRatio,n=Math.max(s-e/2,0),h=Math.max(this.fullHeight-o-r/2,0),a=-Math.min(s-e/2,0),p=-Math.min(this.fullHeight-o-r/2,0),u=e-a- -Math.min(this.fullWidth-s-e/2,0),l=r-p- -Math.min(o-r/2,0);return[Math.round(n),Math.round(h),Math.round(u),Math.round(l)]}computeUp(t){1===t?this._computeUpGlobal():this._computeUpLocal()}screenToRender(t,i){const e=t[0]*this.pixelRatio,r=this.fullHeight-t[1]*this.pixelRatio;return i[0]=e,i[1]=r,i}renderToScreen(t,i){const e=t[0]/this.pixelRatio,r=(this.fullHeight-t[1])/this.pixelRatio;i[0]=e,i[1]=r}sphereFrustumCoverage(t,i){const{center:e,eye:r,distance:s,fovY:o}=this,n=Math.abs(Math.PI/2-B(i,e,r));return t.frustumCoverage(n,s,o)}_computeUpGlobal(){m(st,this.center,this.eye);const t=C(this.center);t<1?D(this._up,A)&&(M(this._up,A),this._markViewDirty(),this.notifyChange("_up")):Math.abs(R(st,this.center))>.9999*C(st)*t||(b(ot,st,this.center),b(ot,ot,st),S(ot,ot),D(this._up,ot)||(M(this._up,ot),this.notifyChange("_up"),this._markViewDirty()))}_computeUpLocal(){T(st,this.eye,this.center),Math.abs(st[2])<=.9999&&(F(st,st,st[2]),f(st,-st[0],-st[1],1-st[2]),S(st,st),D(this._up,st)||(M(this._up,st),this.notifyChange("_up"),this._markViewDirty()))}_compareAndSetView(t,i,r=""){"number"==typeof t[0]&&isFinite(t[0])&&"number"==typeof t[1]&&isFinite(t[1])&&"number"==typeof t[2]&&isFinite(t[2])?D(t,i)||(M(i,t),this._markViewDirty(),r.length&&this.notifyChange(r)):e.getLogger("esri.views.3d.webgl-engine.lib.RenderCamera").warn("RenderCamera vector contains invalid number, ignoring value")}_markViewDirty(){this._viewDirty=!0,this._frustumDirty=!0,this._viewProjectionDirty=!0}_recomputeFrustum(){this._frustumDirty&&(q(this.viewMatrix,this.projectionMatrix,this._frustum),this._frustumDirty=!1)}_ensureViewClean(){this._viewDirty&&(c(this._viewMatrix,this.eye,this.center,this.up),this.notifyChange("_viewMatrix"),this._viewDirty=!1,this._viewInverseTransposeMatrixDirty=!0)}};t([n()],tt.prototype,"_viewport",void 0),t([n()],tt.prototype,"_padding",void 0),t([n()],tt.prototype,"_fov",void 0),t([n()],tt.prototype,"_nearFar",void 0),t([n()],tt.prototype,"_viewDirty",void 0),t([n()],tt.prototype,"_viewMatrix",void 0),t([n()],tt.prototype,"_pixelRatio",void 0),t([n()],tt.prototype,"pixelRatio",null),t([n()],tt.prototype,"row",void 0),t([n()],tt.prototype,"column",void 0),t([n()],tt.prototype,"_rows",void 0),t([n()],tt.prototype,"rows",null),t([n()],tt.prototype,"_columns",void 0),t([n()],tt.prototype,"columns",null),t([n()],tt.prototype,"eye",null),t([n()],tt.prototype,"center",null),t([n()],tt.prototype,"_center",void 0),t([n()],tt.prototype,"up",null),t([n()],tt.prototype,"_up",void 0),t([n()],tt.prototype,"viewMatrix",null),t([n({readOnly:!0})],tt.prototype,"viewForward",null),t([n({readOnly:!0})],tt.prototype,"viewUp",null),t([n({readOnly:!0})],tt.prototype,"viewRight",null),t([n({readOnly:!0})],tt.prototype,"nearFar",null),t([n()],tt.prototype,"near",null),t([n()],tt.prototype,"far",null),t([n()],tt.prototype,"viewport",null),t([n({readOnly:!0})],tt.prototype,"screenViewport",null),t([n({readOnly:!0})],tt.prototype,"screenPadding",null),t([n()],tt.prototype,"x",null),t([n()],tt.prototype,"y",null),t([n()],tt.prototype,"width",null),t([n()],tt.prototype,"height",null),t([n()],tt.prototype,"fullWidth",null),t([n()],tt.prototype,"fullHeight",null),t([n({readOnly:!0})],tt.prototype,"_aspect",null),t([n()],tt.prototype,"padding",null),t([n({readOnly:!0})],tt.prototype,"projectionMatrix",null),t([n({readOnly:!0})],tt.prototype,"inverseProjectionMatrix",null),t([n()],tt.prototype,"fov",null),t([n()],tt.prototype,"fovX",null),t([n()],tt.prototype,"fovY",null),t([n()],tt.prototype,"viewInverseTransposeMatrix",null),t([n({readOnly:!0})],tt.prototype,"_projectionMatrixInternal",null),t([n()],tt.prototype,"relativeElevation",void 0),tt=$=t([h("esri.views.3d.webgl.RenderCamera")],tt);const it=tt,et=Y(),rt=w(),st=I(),ot=I(),nt=o();export{it as default};
5
+ import{__decorate as t}from"tslib";import i from"../../../core/Accessor.js";import e from"../../../core/Logger.js";import{lerp as r}from"../../../core/mathUtils.js";import{createScreenPointArray as s,createRenderScreenPointArray3 as o}from"../../../core/screenUtils.js";import{property as n,subclass as h}from"../../../core/accessorSupport/decorators.js";import{copy as a,multiply as p,invert as u,transpose as l,frustum as _,equals as v,lookAt as c}from"../../../core/libs/gl-matrix-2/math/mat4.js";import{create as w}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{copy as d,exactEquals as y}from"../../../core/libs/gl-matrix-2/math/vec2.js";import{fromValues as g}from"../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{e as m,h as f,D as x,d as M,m as D,a as j,g as R,w as P,v as V,j as F,b as C,f as b,n as S,E as T}from"../../../chunks/vec32.js";import{create as I,UNIT_Z as A}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as E,e as O,a as U,f as H,g as k,t as z}from"../../../chunks/vec42.js";import{fromValues as W,create as Y}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{create as L,copy as X,fromMatrix as q}from"../../../geometry/support/frustum.js";import{create as G}from"../../../geometry/support/ray.js";import{projectPointSignedLength as N}from"../../../geometry/support/vector.js";import{viewAngle as B}from"../state/utils/viewUtils.js";import{fovd2fovx as J,fovx2fovd as K,fovd2fovy as Q,fovy2fovd as Z}from"../webgl-engine/lib/fov.js";var $;let tt=$=class extends i{constructor(t){super(t),this._ray=G(),this._viewport=W(0,0,1,1),this._padding=W(0,0,0,0),this._fov=55/180*Math.PI,this._nearFar=g(1,1e3),this._viewDirty=!0,this._viewMatrix=w(),this._viewProjectionDirty=!0,this._viewProjectionMatrix=w(),this._viewInverseTransposeMatrixDirty=!0,this._viewInverseTransposeMatrix=w(),this._frustumDirty=!0,this._frustum=L(),this._fullViewport=Y(),this._pixelRatio=1,this.row=0,this.column=0,this._rows=1,this._columns=1,this._center=I(),this._up=I(),this.relativeElevation=0}get pixelRatio(){return this._pixelRatio}set pixelRatio(t){this._pixelRatio=t>0?t:1}get rows(){return this._rows}set rows(t){this._rows=Math.max(1,t)}get columns(){return this._columns}set columns(t){this._columns=Math.max(1,t)}get eye(){return this._ray.origin}set eye(t){this._compareAndSetView(t,this._ray.origin)}get center(){return this._center}set center(t){this._compareAndSetView(t,this._center,"_center")}get ray(){return m(this._ray.direction,this.center,this.eye),this._ray}get up(){return this._up}set up(t){this._compareAndSetView(t,this._up,"_up")}get viewMatrix(){return this._ensureViewClean(),this._viewMatrix}set viewMatrix(t){a(this._viewMatrix,t),this.notifyChange("_viewMatrix"),this._viewDirty=!1,this._viewInverseTransposeMatrixDirty=!0,this._viewProjectionDirty=!0,this._frustumDirty=!0}get viewForward(){return this._ensureViewClean(),f(I(),-this._viewMatrix[2],-this._viewMatrix[6],-this._viewMatrix[10])}get viewUp(){return this._ensureViewClean(),f(I(),this._viewMatrix[1],this._viewMatrix[5],this._viewMatrix[9])}get viewRight(){return this._ensureViewClean(),f(I(),this._viewMatrix[0],this._viewMatrix[4],this._viewMatrix[8])}get nearFar(){return this._nearFar}get near(){return this._nearFar[0]}set near(t){this._nearFar[0]!==t&&(this._nearFar[0]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_nearFar"))}get far(){return this._nearFar[1]}set far(t){this._nearFar[1]!==t&&(this._nearFar[1]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_nearFar"))}get viewport(){return this._viewport}set viewport(t){this.x=t[0],this.y=t[1],this.width=t[2],this.height=t[3]}get screenViewport(){if(1===this.pixelRatio)return this._viewport;const t=E(Y(),this._viewport,1/this.pixelRatio),i=this._get("screenViewport");return i&&O(t,i)?i:t}get screenPadding(){if(1===this.pixelRatio)return this._padding;const t=E(Y(),this._padding,1/this.pixelRatio),i=this._get("screenPadding");return i&&O(t,i)?i:t}get x(){return this._viewport[0]}set x(t){t+=this._padding[3],this._viewport[0]!==t&&(this._viewport[0]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get y(){return this._viewport[1]}set y(t){t+=this._padding[2],this._viewport[1]!==t&&(this._viewport[1]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get width(){return this._viewport[2]}set width(t){this._viewport[2]!==t&&(this._viewport[2]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get height(){return this._viewport[3]}set height(t){this._viewport[3]!==t&&(this._viewport[3]=t,this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_viewport"))}get fullWidth(){return this._viewport[2]+this._padding[1]+this._padding[3]}set fullWidth(t){this.width=t-(this._padding[1]+this._padding[3])}get fullHeight(){return this._viewport[3]+this._padding[0]+this._padding[2]}set fullHeight(t){this.height=t-(this._padding[0]+this._padding[2])}get fullViewport(){return this._fullViewport[0]=this._viewport[0]-this._padding[3],this._fullViewport[1]=this._viewport[1]-this._padding[2],this._fullViewport[2]=this.fullWidth,this._fullViewport[3]=this.fullHeight,this._fullViewport}get _aspect(){return this.width/this.height}get padding(){return this._padding}set padding(t){U(this._padding,t)||(this._viewport[0]+=t[3]-this._padding[3],this._viewport[1]+=t[2]-this._padding[2],this._viewport[2]-=t[1]+t[3]-(this._padding[1]+this._padding[3]),this._viewport[3]-=t[0]+t[2]-(this._padding[0]+this._padding[2]),H(this._padding,t),this._viewProjectionDirty=!0,this._frustumDirty=!0,this.notifyChange("_padding"),this.notifyChange("_viewport"))}get viewProjectionMatrix(){return this._viewProjectionDirty&&(p(this._viewProjectionMatrix,this.projectionMatrix,this.viewMatrix),this._viewProjectionDirty=!1),this._viewProjectionMatrix}get projectionMatrix(){return this._projectionMatrixInternal}get inverseProjectionMatrix(){return u(w(),this.projectionMatrix)||this._get("inverseProjectionMatrix")||w()}get fov(){return this._fov}set fov(t){this._fov=t,this._viewProjectionDirty=!0,this._frustumDirty=!0}get fovX(){return J(this._fov,this.width,this.height)}set fovX(t){this._fov=K(t,this.width,this.height),this._viewProjectionDirty=!0,this._frustumDirty=!0}get fovY(){return Q(this._fov,this.width,this.height)}set fovY(t){this._fov=Z(t,this.width,this.height),this._viewProjectionDirty=!0,this._frustumDirty=!0}get distance(){return x(this.center,this.eye)}get frustum(){return this._recomputeFrustum(),this._frustum}get viewInverseTransposeMatrix(){return(this._viewInverseTransposeMatrixDirty||this._viewDirty)&&(u(this._viewInverseTransposeMatrix,this.viewMatrix),l(this._viewInverseTransposeMatrix,this._viewInverseTransposeMatrix),this._viewInverseTransposeMatrixDirty=!1),this._viewInverseTransposeMatrix}depthNDCToWorld(t){const{near:i,far:e}=this;return 2*i*e/(e+i-t*(e-i))}get perRenderPixelRatio(){return Math.tan(this.fovX/2)/(this.width/2)}get perScreenPixelRatio(){return this.perRenderPixelRatio*this.pixelRatio}get aboveGround(){return null!=this.relativeElevation&&this.relativeElevation>=0}get _projectionMatrixInternal(){const t=this.width,i=this.height,e=this.near*Math.tan(this.fovY/2)*2,r=e*this._aspect,s=e/this.rows,o=r/this.columns,n=-r/2+this.column*o,h=n+o,a=-e/2+this.row*s,p=a+s,u=_(w(),n*(1+2*this._padding[3]/t),h*(1+2*this._padding[1]/t),a*(1+2*this._padding[2]/i),p*(1+2*this._padding[0]/i),this.near,this.far),l=this._get("projectionMatrix");return l&&v(l,u)?l:u}copyFrom(t){M(this._ray.origin,t.eye),this.center=t.center,this.up=t.up,H(this._viewport,t.viewport),this.notifyChange("_viewport"),H(this._padding,t.padding),this.notifyChange("_padding"),d(this._nearFar,t.nearFar),this.notifyChange("_nearFar"),this._fov=t.fov,this.row=t.row,this.column=t.column,this.rows=t.rows,this.columns=t.columns,this.relativeElevation=t.relativeElevation;const i=t;return this._viewDirty=i._viewDirty,this._viewDirty||(a(this._viewMatrix,t.viewMatrix),this.notifyChange("_viewMatrix")),this._viewProjectionDirty=!0,this._frustumDirty=i._frustumDirty,this._frustumDirty||(X(this._frustum,t.frustum),this._frustumDirty=!1),i._viewInverseTransposeMatrixDirty?this._viewInverseTransposeMatrixDirty=!0:(a(this._viewInverseTransposeMatrix,t.viewInverseTransposeMatrix),this._viewInverseTransposeMatrixDirty=!1),H(this._fullViewport,t.fullViewport),this.pixelRatio=t.pixelRatio,this}copyViewFrom(t){this.eye=t.eye,this.center=t.center,this.up=t.up,this.fov=t.fov}clone(){return(new $).copyFrom(this)}equals(t){return D(this.eye,t.eye)&&D(this.center,t.center)&&D(this.up,t.up)&&U(this._viewport,t.viewport)&&U(this._padding,t.padding)&&y(this.nearFar,t.nearFar)&&this._fov===t.fov&&this.pixelRatio===t.pixelRatio&&this.relativeElevation===t.relativeElevation&&this.row===t.row&&this.column===t.column&&this.rows===t.rows&&this.columns===t.columns}almostEquals(t){const i=Math.max(1,1/this.pixelRatio,1/t.pixelRatio);if(Math.abs(t.fov-this._fov)>=.001||k(t.screenPadding,this.screenPadding)>=i||k(this.screenViewport,t.screenViewport)>=i||this.row!==t.row||this.column!==t.column||this.rows!==t.rows||this.columns!==t.columns)return!1;j(st,t.eye,t.center),j(ot,this.eye,this.center);const e=R(st,ot),r=P(st),s=P(ot),o=5e-4;return e*e>=(1-1e-10)*r*s&&V(t.eye,this.eye)<Math.max(r,s)*o*o}computeRenderPixelSizeAt(t){return this.computeRenderPixelSizeAtDist(this._viewDirectionDistance(t))}computeRenderPixelSizeAtDist(t){return t*this.perRenderPixelRatio}computeScreenPixelSizeAt(t){return this.computeScreenPixelSizeAtDist(this._viewDirectionDistance(t))}_viewDirectionDistance(t){return Math.abs(N(this.viewForward,m(st,t,this.eye)))}computeScreenPixelSizeAtDist(t){return t*this.perScreenPixelRatio}computeDistanceFromRadius(t,i){return t/Math.tan(Math.min(this.fovX,this.fovY)/(2*(i||1)))}getScreenCenter(t=s()){return t[0]=(this.padding[3]+this.width/2)/this.pixelRatio,t[1]=(this.padding[0]+this.height/2)/this.pixelRatio,t}getRenderCenter(t,i=.5,e=.5){return t[0]=this.padding[3]+this.width*i,t[1]=this.padding[2]+this.height*e,t[2]=.5,t}setGLViewport(t){const i=this.viewport,e=this.padding;t.setViewport(i[0]-e[3],i[1]-e[2],i[2]+e[1]+e[3],i[3]+e[0]+e[2])}applyProjection(t,i){t!==et&&M(et,t),et[3]=1,z(et,et,this.projectionMatrix);const e=Math.abs(et[3]);F(et,et,1/e);const s=this.fullViewport;i[0]=r(0,s[0]+s[2],.5+.5*et[0]),i[1]=r(0,s[1]+s[3],.5+.5*et[1]),i[2]=.5*(et[2]+1),i[3]=e}unapplyProjection(t,i){const e=this.fullViewport;et[0]=(t[0]/(e[0]+e[2])*2-1)*t[3],et[1]=(t[1]/(e[1]+e[3])*2-1)*t[3],et[2]=(2*t[2]-1)*t[3],et[3]=t[3],null!=this.inverseProjectionMatrix&&(z(et,et,this.inverseProjectionMatrix),i[0]=et[0],i[1]=et[1],i[2]=et[2])}projectToScreen(t,i){return this.projectToRenderScreen(t,nt),this.renderToScreen(nt,i),i}projectToRenderScreen(t,i){if(et[0]=t[0],et[1]=t[1],et[2]=t[2],et[3]=1,z(et,et,this.viewProjectionMatrix),0===et[3])return null;const e=et;F(e,e,1/Math.abs(et[3]));const s=this.fullViewport,o=r(0,s[0]+s[2],.5+.5*e[0]),n=r(0,s[1]+s[3],.5+.5*e[1]);return"x"in i?(i.x=o,i.y=n):(i[0]=o,i[1]=n,i.length>2&&(i[2]=.5*(e[2]+1))),i}unprojectFromScreen(t,i){return this.unprojectFromRenderScreen(this.screenToRender(t,nt),i)}unprojectFromRenderScreen(t,i){if(p(rt,this.projectionMatrix,this.viewMatrix),!u(rt,rt))return null;const e=this.fullViewport;return et[0]=2*(t[0]-e[0])/e[2]-1,et[1]=2*(t[1]-e[1])/e[3]-1,et[2]=2*t[2]-1,et[3]=1,z(et,et,rt),0===et[3]?null:(i[0]=et[0]/et[3],i[1]=et[1]/et[3],i[2]=et[2]/et[3],i)}constrainWindowSize(t,i,e,r){const s=t*this.pixelRatio,o=i*this.pixelRatio,n=Math.max(s-e/2,0),h=Math.max(this.fullHeight-o-r/2,0),a=-Math.min(s-e/2,0),p=-Math.min(this.fullHeight-o-r/2,0),u=e-a- -Math.min(this.fullWidth-s-e/2,0),l=r-p- -Math.min(o-r/2,0);return[Math.round(n),Math.round(h),Math.round(u),Math.round(l)]}computeUp(t){1===t?this._computeUpGlobal():this._computeUpLocal()}screenToRender(t,i){const e=t[0]*this.pixelRatio,r=this.fullHeight-t[1]*this.pixelRatio;return i[0]=e,i[1]=r,i}renderToScreen(t,i){const e=t[0]/this.pixelRatio,r=(this.fullHeight-t[1])/this.pixelRatio;i[0]=e,i[1]=r}sphereFrustumCoverage(t,i){const{center:e,eye:r,distance:s,fovY:o}=this,n=Math.abs(Math.PI/2-B(i,e,r));return t.frustumCoverage(n,s,o)}_computeUpGlobal(){m(st,this.center,this.eye);const t=C(this.center);t<1?D(this._up,A)&&(M(this._up,A),this._markViewDirty(),this.notifyChange("_up")):Math.abs(R(st,this.center))>.9999*C(st)*t||(b(ot,st,this.center),b(ot,ot,st),S(ot,ot),D(this._up,ot)||(M(this._up,ot),this.notifyChange("_up"),this._markViewDirty()))}_computeUpLocal(){T(st,this.eye,this.center),Math.abs(st[2])<=.9999&&(F(st,st,st[2]),f(st,-st[0],-st[1],1-st[2]),S(st,st),D(this._up,st)||(M(this._up,st),this.notifyChange("_up"),this._markViewDirty()))}_compareAndSetView(t,i,r=""){"number"==typeof t[0]&&isFinite(t[0])&&"number"==typeof t[1]&&isFinite(t[1])&&"number"==typeof t[2]&&isFinite(t[2])?D(t,i)||(M(i,t),this._markViewDirty(),r.length&&this.notifyChange(r)):e.getLogger("esri.views.3d.webgl-engine.lib.RenderCamera").warn("RenderCamera vector contains invalid number, ignoring value")}_markViewDirty(){this._viewDirty=!0,this._frustumDirty=!0,this._viewProjectionDirty=!0}_recomputeFrustum(){this._frustumDirty&&(q(this.viewMatrix,this.projectionMatrix,this._frustum),this._frustumDirty=!1)}_ensureViewClean(){this._viewDirty&&(c(this._viewMatrix,this.eye,this.center,this.up),this.notifyChange("_viewMatrix"),this._viewDirty=!1,this._viewInverseTransposeMatrixDirty=!0)}};t([n()],tt.prototype,"_viewport",void 0),t([n()],tt.prototype,"_padding",void 0),t([n()],tt.prototype,"_fov",void 0),t([n()],tt.prototype,"_nearFar",void 0),t([n()],tt.prototype,"_viewDirty",void 0),t([n()],tt.prototype,"_viewMatrix",void 0),t([n()],tt.prototype,"_pixelRatio",void 0),t([n()],tt.prototype,"pixelRatio",null),t([n()],tt.prototype,"row",void 0),t([n()],tt.prototype,"column",void 0),t([n()],tt.prototype,"_rows",void 0),t([n()],tt.prototype,"rows",null),t([n()],tt.prototype,"_columns",void 0),t([n()],tt.prototype,"columns",null),t([n()],tt.prototype,"eye",null),t([n()],tt.prototype,"center",null),t([n()],tt.prototype,"_center",void 0),t([n()],tt.prototype,"up",null),t([n()],tt.prototype,"_up",void 0),t([n()],tt.prototype,"viewMatrix",null),t([n({readOnly:!0})],tt.prototype,"viewForward",null),t([n({readOnly:!0})],tt.prototype,"viewUp",null),t([n({readOnly:!0})],tt.prototype,"viewRight",null),t([n({readOnly:!0})],tt.prototype,"nearFar",null),t([n()],tt.prototype,"near",null),t([n()],tt.prototype,"far",null),t([n()],tt.prototype,"viewport",null),t([n({readOnly:!0})],tt.prototype,"screenViewport",null),t([n({readOnly:!0})],tt.prototype,"screenPadding",null),t([n()],tt.prototype,"x",null),t([n()],tt.prototype,"y",null),t([n()],tt.prototype,"width",null),t([n()],tt.prototype,"height",null),t([n()],tt.prototype,"fullWidth",null),t([n()],tt.prototype,"fullHeight",null),t([n({readOnly:!0})],tt.prototype,"_aspect",null),t([n()],tt.prototype,"padding",null),t([n({readOnly:!0})],tt.prototype,"projectionMatrix",null),t([n({readOnly:!0})],tt.prototype,"inverseProjectionMatrix",null),t([n()],tt.prototype,"fov",null),t([n()],tt.prototype,"fovX",null),t([n()],tt.prototype,"fovY",null),t([n()],tt.prototype,"viewInverseTransposeMatrix",null),t([n({readOnly:!0})],tt.prototype,"_projectionMatrixInternal",null),t([n()],tt.prototype,"relativeElevation",void 0),tt=$=t([h("esri.views.3d.webgl.RenderCamera")],tt);const it=tt,et=Y(),rt=w(),st=I(),ot=I(),nt=o();export{it as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{destroyMaybe as e}from"../../../../../core/maybe.js";import{s as t,h as o,t as r,i as a}from"../../../../../chunks/vec32.js";import{create as i}from"../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{create as s}from"../../../../../geometry/support/aaBoundingBox.js";import{encodeSymbolColor as n}from"../../../layers/support/symbolColorUtils.js";import{computeOffsetObb as l}from"../../../support/orientedBoundingBox.js";import{UniformComponentParameters as m}from"./UniformComponentParameters.js";import{ComponentParametersVarying as c,ComponentParametersUniform as h}from"./Material/ComponentMaterial.js";import{olidEnabled as d}from"../../effects/geometry/olidUtils.js";class u{constructor(e,t,o,r,a){this.transform=e,this.obb=t,this._componentData=o,this._renderable=r,this._intersectionGeometry=a,this.visible=!1,this.offsetObb=null,this._aabbInWorldCoordinates=null}get componentData(){return this._componentData}get renderable(){return this._renderable}get intersectionGeometry(){return this._intersectionGeometry}updateMaterial(e){e(this._renderable.material)}updateCameraDerivedParameters(e){const{eye:o}=e;this._renderable.meta.cameraDepthSquared=t(o,this.obb.center)}setComponentData(e,t){const o=this._componentData,{materialDataBuffer:r,materialDataIndices:a}=o,i=new m,s=r.textureBuffer,u=s.getVec5Field("colorAndCastShadows"),p=s.getScalarField("elevationOffset"),b=s.getScalarField("emissiveStrength"),g=s.getScalarField("emissiveSourceMode"),v=s.getVec4Field("olidColor"),C=new Uint8Array(4),x=new Uint32Array(C.buffer);let S=0,_=0,M=0,y=0,w=0,D=o.verticalOffsets,O=1/0,B=-1/0,j=!1,k=!1,A=!1,I=0,W=!1;for(let l=0;l<o.count;l++){e(l,i),S+=+(i.externalColor[3]<1),_+=+(3===i.externalColorMixMode&&1===i.externalColor[3]),y+=+(i.emissiveStrength>0),w+=+(1===i.emissiveSource),k||=1!==i.emissiveStrength,M+=+i.castShadows,n(i.externalColor,i.externalColorMixMode,C),u.setValues(a[l],C[0],C[1],C[2],C[3],+i.castShadows),j||=l>0&&(I!==x[0]||W!==i.castShadows),I=x[0],W=i.castShadows,A||=0!==i.elevationOffset,A&&null==D&&(D=new Array(l).fill(0)),null!=D&&(D[l]=i.elevationOffset),O=Math.min(O,i.elevationOffset),B=Math.max(B,i.elevationOffset),p.set(a[l],i.elevationOffset),b.set(a[l],i.emissiveStrength),g.set(a[l],0===i.emissiveSource?0:255);const t=i.olidColor;null!=t&&v.setArray(a[l],t),i.pickable!==o.isPickable(l)&&o.updatePickabilityWithCount(l,i.pickable)}o.verticalOffsets=A?D:null,this.offsetObb=A?l(this.obb,O,B,t,this.offsetObb??this.obb.clone()):null,this.updateMaterial(e=>{if(j||A||d()||(k||w>0)&&y>0){const t=new c;t.castShadows=f(M,o.count),t.transparent=f(S,o.count),t.opaqueOverride=f(_,o.count),t.emissiveOverride=f(y,o.count),t.emissiveSourceOverride=f(w,o.count),e.textureBackedBuffer=s,e.componentParameters=t,s.updateTexture()}else{const t=new h;t.castShadows=i.castShadows?0:2,t.externalColor=i.externalColor,t.externalColorMixMode=i.externalColorMixMode,t.emissiveStrength=i.emissiveStrength,t.emissiveSource=i.emissiveSource,e.textureBackedBuffer=null,e.componentParameters=t}})}addComponentHighlight(e,t){return this._componentData.addComponentHighlight(e,t)}removeComponentHighlight(e,t){return this._componentData.removeComponentHighlight(e,t)}clearHighlights(){this._componentData.clearHighlights()}destroy(){this._intersectionGeometry=e(this._intersectionGeometry),this._renderable=e(this._renderable),this._componentData=e(this._componentData)}get aabbInWorldCoordinates(){let e=this._aabbInWorldCoordinates;return e||(e=this._computeAabbInWorldCoordinates(),this._aabbInWorldCoordinates=e),e}_computeAabbInWorldCoordinates(){const e=s(),{positions:t}=this._intersectionGeometry;if(Math.floor(t.length/3)>0){const{rotationScale:s,position:n}=this.transform;let l=1/0,m=1/0,c=1/0,h=-1/0,d=-1/0,u=-1/0;const f=i();for(let e=0;e<t.length;e+=3)o(f,t[e+0],t[e+1],t[e+2]),r(f,f,s),a(f,f,n),l=Math.min(l,f[0]),m=Math.min(m,f[1]),c=Math.min(c,f[2]),h=Math.max(h,f[0]),d=Math.max(d,f[1]),u=Math.max(u,f[2]);e[0]=l,e[1]=m,e[2]=c,e[3]=h,e[4]=d,e[5]=u}return e}}function f(e,t){return e===t?0:0===e?2:1}export{u as ComponentObject};
5
+ import{destroyMaybe as e}from"../../../../../core/maybe.js";import{s as t,h as o,t as r,i}from"../../../../../chunks/vec32.js";import{create as a}from"../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{create as s}from"../../../../../geometry/support/aaBoundingBox.js";import{encodeSymbolColor as n}from"../../../layers/support/symbolColorUtils.js";import{computeOffsetObb as l}from"../../../support/orientedBoundingBox.js";import{UniformComponentParameters as m}from"./UniformComponentParameters.js";import{ComponentParametersVarying as c,ComponentParametersUniform as h}from"./Material/ComponentMaterial.js";import{olidEnabled as d}from"../../effects/geometry/olidUtils.js";class f{constructor(e,t,o,r,i){this.transform=e,this.obb=t,this._componentData=o,this._renderable=r,this._intersectionGeometry=i,this.visible=!1,this.offsetObb=null,this._aabbInWorldCoordinates=null}get componentData(){return this._componentData}get renderable(){return this._renderable}get intersectionGeometry(){return this._intersectionGeometry}updateMaterial(e){e(this._renderable.material)}updateCameraDerivedParameters(e){const{eye:o}=e;this._renderable.meta.cameraDepthSquared=t(o,this.obb.center)}setComponentData(e,t){const o=this._componentData,{materialDataBuffer:r,materialDataIndices:i}=o,a=new m,s=r.textureBuffer,f=s.getVec4Field("colorAndCastShadows"),p=s.getScalarField("elevationOffset"),b=s.getScalarField("emissiveStrength"),g=s.getScalarField("emissiveSourceMode"),v=s.getVec4Field("olidColor"),C=new Uint8Array(4),x=new Uint32Array(C.buffer);let _=0,S=0,M=0,y=0,D=0,O=o.verticalOffsets,w=1/0,B=-1/0,j=!1,A=!1,k=!1,I=0;for(let l=0;l<o.count;l++){e(l,a),_+=+(a.externalColor[3]<1),S+=+(3===a.externalColorMixMode&&1===a.externalColor[3]),y+=+(a.emissiveStrength>0),D+=+(1===a.emissiveSource),A||=1!==a.emissiveStrength,M+=+a.castShadows,n(a.externalColor,a.externalColorMixMode,C),C[2]=254&C[2]|+a.castShadows,f.setArray(i[l],C),j||=l>0&&I!==x[0],I=x[0],k||=0!==a.elevationOffset,k&&null==O&&(O=new Array(l).fill(0)),null!=O&&(O[l]=a.elevationOffset),w=Math.min(w,a.elevationOffset),B=Math.max(B,a.elevationOffset),p.set(i[l],a.elevationOffset),b.set(i[l],a.emissiveStrength),g.set(i[l],0===a.emissiveSource?0:255);const t=a.olidColor;null!=t&&v.setArray(i[l],t),a.pickable!==o.isPickable(l)&&o.updatePickabilityWithCount(l,a.pickable)}o.verticalOffsets=k?O:null,this.offsetObb=k?l(this.obb,w,B,t,this.offsetObb??this.obb.clone()):null,this.updateMaterial(e=>{if(j||k||d()||(A||D>0)&&y>0){const t=new c;t.castShadows=u(M,o.count),t.transparent=u(_,o.count),t.opaqueOverride=u(S,o.count),t.emissiveOverride=u(y,o.count),t.emissiveSourceOverride=u(D,o.count),e.textureBackedBuffer=s,e.componentParameters=t,s.updateTexture()}else{const t=new h;t.castShadows=a.castShadows?0:2,t.externalColor=a.externalColor,t.externalColorMixMode=a.externalColorMixMode,t.emissiveStrength=a.emissiveStrength,t.emissiveSource=a.emissiveSource,e.textureBackedBuffer=null,e.componentParameters=t}})}addComponentHighlight(e,t){return this._componentData.addComponentHighlight(e,t)}removeComponentHighlight(e,t){return this._componentData.removeComponentHighlight(e,t)}clearHighlights(){this._componentData.clearHighlights()}destroy(){this._intersectionGeometry=e(this._intersectionGeometry),this._renderable=e(this._renderable),this._componentData=e(this._componentData)}get aabbInWorldCoordinates(){let e=this._aabbInWorldCoordinates;return e||(e=this._computeAabbInWorldCoordinates(),this._aabbInWorldCoordinates=e),e}_computeAabbInWorldCoordinates(){const e=s(),{positions:t}=this._intersectionGeometry;if(Math.floor(t.length/3)>0){const{rotationScale:s,position:n}=this.transform;let l=1/0,m=1/0,c=1/0,h=-1/0,d=-1/0,f=-1/0;const u=a();for(let e=0;e<t.length;e+=3)o(u,t[e+0],t[e+1],t[e+2]),r(u,u,s),i(u,u,n),l=Math.min(l,u[0]),m=Math.min(m,u[1]),c=Math.min(c,u[2]),h=Math.max(h,u[0]),d=Math.max(d,u[1]),f=Math.max(f,u[2]);e[0]=l,e[1]=m,e[2]=c,e[3]=h,e[4]=d,e[5]=f}return e}}function u(e,t){return e===t?0:0===e?2:1}export{f as ComponentObject};
@@ -2,24 +2,30 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{neverReached as o}from"../../../../../../core/compilerUtils.js";import{DecodeSymbolColor as e}from"./DecodeSymbolColor.glsl.js";import{TextureBackedBufferModule as r}from"../../../core/shaderLibrary/TextureBackedBuffer.glsl.js";import{Float4DrawUniform as t}from"../../../core/shaderModules/Float4DrawUniform.js";import{FloatDrawUniform as a}from"../../../core/shaderModules/FloatDrawUniform.js";import{glsl as d,If as n}from"../../../core/shaderModules/glsl.js";import{IntegerDrawUniform as l}from"../../../core/shaderModules/IntegerDrawUniform.js";import{Texture2DDrawUniform as i}from"../../../core/shaderModules/Texture2DDrawUniform.js";import{olidEnabled as s}from"../../../effects/geometry/olidUtils.js";import{componentDataLayout as c,componentDataOlidLayout as m}from"../../../materials/DefaultLayouts.js";function u(e,r){switch(r.componentData){case 1:return p(e,r);case 0:return w(e,r);case 2:return;default:o(r.componentData)}}const v=(o,e)=>"emissiveSourceMode"===o||"emissiveStrength"===o?e.hasEmission:"olidColor"!==o||9===e.output,f=new i("componentColorTex",o=>o.textureBackedBuffer.texture),x=new r(c,"componentIndex",f,v),C=new r(m,"componentIndex",f,v);function M(){return s()?C:x}function p(o,r){const{vertex:t,fragment:a}=o,{output:l,hasEmission:i}=r,s=9===l,{getTextureAttribute:c,TextureBackedBufferModule:m}=M();o.include(m,r),o.attributes.add("componentIndex","float"),o.varyings.add("vExternalColorMixMode","mediump float"),o.varyings.add("vExternalColor","vec4"),s&&o.varyings.add("vObjectAndLayerIdColor","vec4"),i&&(o.varyings.add("emissiveStrength","float"),o.varyings.add("emissiveSource","int")),o.include(e),t.code.add(d`
5
+ import{neverReached as o}from"../../../../../../core/compilerUtils.js";import{DecodeSymbolColor as e}from"./DecodeSymbolColor.glsl.js";import{TextureBackedBufferModule as r}from"../../../core/shaderLibrary/TextureBackedBuffer.glsl.js";import{Float4DrawUniform as t}from"../../../core/shaderModules/Float4DrawUniform.js";import{FloatDrawUniform as d}from"../../../core/shaderModules/FloatDrawUniform.js";import{glsl as n,If as a}from"../../../core/shaderModules/glsl.js";import{IntegerDrawUniform as l}from"../../../core/shaderModules/IntegerDrawUniform.js";import{Texture2DUintDrawUniform as i}from"../../../core/shaderModules/Texture2DUintDrawUniform.js";import{olidEnabled as s}from"../../../effects/geometry/olidUtils.js";import{componentDataLayout as c,componentDataOlidLayout as m}from"../../../materials/DefaultLayouts.js";function u(e,r){switch(r.componentData){case 1:return M(e,r);case 0:return h(e,r);case 2:return;default:o(r.componentData)}}const v=(o,e)=>"emissiveSourceMode"===o||"emissiveStrength"===o?e.hasEmission:"olidColor"!==o||9===e.output,f=new i("componentTextureBuffer",o=>o.textureBackedBuffer?.texture),C=new r(c,"componentIndex",f,v),x=new r(m,"componentIndex",f,v);function p(){return s()?x:C}function M(o,r){const{vertex:t,fragment:d}=o,{output:l,hasEmission:i}=r,s=9===l,{getTextureAttribute:c,TextureBackedBufferModule:m}=p();o.include(m,r),o.attributes.add("componentIndex","float"),o.varyings.add("vExternalColorMixMode","mediump float"),o.varyings.add("vExternalColor","vec4"),s&&o.varyings.add("vObjectAndLayerIdColor","vec4"),i&&(o.varyings.add("emissiveStrength","float"),o.varyings.add("emissiveSource","int")),o.include(e),t.code.add(n`
6
6
  float readElevationOffset() {
7
7
  return ${c("elevationOffset")};
8
8
  }
9
9
 
10
10
  void forwardEmissiveStrength() {
11
- ${n(i,d`emissiveStrength = ${c("emissiveStrength")};
12
- emissiveSource = ${c("emissiveSourceMode")} == 0.0 ? 0 : 1;`)}
11
+ ${a(i,n`emissiveStrength = ${c("emissiveStrength")};
12
+ emissiveSource = ${c("emissiveSourceMode")} == 0u ? 0 : 1;`)}
13
13
  }
14
14
 
15
15
  void forwardObjectAndLayerIdColor() {
16
- ${n(s,d`vObjectAndLayerIdColor = ${c("olidColor")};`)}
16
+ ${a(s,n`vObjectAndLayerIdColor = vec4(${c("olidColor")})/255.0;`)}
17
+ }
18
+
19
+ void decodeColorAndCastShadow(uvec4 colorAndCastShadowEncoded, out vec4 color, out bool castShadow) {
20
+ uvec4 componentColor = colorAndCastShadowEncoded;
21
+ castShadow = bool(componentColor.b & 1u);
22
+ componentColor.b = componentColor.b & 254u;
23
+ color = vec4(componentColor);
17
24
  }
18
25
 
19
26
  vec4 forwardExternalColor(out bool castShadows) {
20
- vec5 colorAndCastShadow = ${c("colorAndCastShadows")};
21
- vec4 componentColor = vec4(colorAndCastShadow.x, colorAndCastShadow.y, colorAndCastShadow.z, colorAndCastShadow.w);
22
- castShadows = colorAndCastShadow.v >= 1.0;
27
+ vec4 componentColor;
28
+ decodeColorAndCastShadow(${c("colorAndCastShadows")}, componentColor, castShadows);
23
29
 
24
30
  int decodedColorMixMode;
25
31
  vExternalColor = decodeSymbolColor(componentColor, decodedColorMixMode) * 0.003921568627451; // = 1/255;
@@ -27,16 +33,16 @@ import{neverReached as o}from"../../../../../../core/compilerUtils.js";import{De
27
33
 
28
34
  return vExternalColor;
29
35
  }
30
- `),a.code.add(d`
36
+ `),d.code.add(n`
31
37
  void readExternalColor(out vec4 externalColor, out int externalColorMixMode) {
32
38
  externalColor = vExternalColor;
33
39
  externalColorMixMode = int(vExternalColorMixMode);
34
40
  }
35
41
 
36
42
  void outputObjectAndLayerIdColor() {
37
- ${s?d`fragColor = vObjectAndLayerIdColor;`:""}
43
+ ${s?n`fragColor = vObjectAndLayerIdColor;`:""}
38
44
  }
39
- `)}function w(o,e){const{vertex:r,fragment:i}=o;o.varyings.add("vExternalColor","vec4"),i.uniforms.add(new a("emissiveStrength",o=>o.componentParameters.emissiveStrength)),r.uniforms.add(new t("externalColor",o=>o.componentParameters.externalColor)).code.add(d`float readElevationOffset() {
45
+ `)}function h(o,e){const{vertex:r,fragment:i}=o;o.varyings.add("vExternalColor","vec4"),i.uniforms.add(new d("emissiveStrength",o=>o.componentParameters.emissiveStrength)),r.uniforms.add(new t("externalColor",o=>o.componentParameters.externalColor)).code.add(n`float readElevationOffset() {
40
46
  return 0.0;
41
47
  }
42
48
  void forwardObjectAndLayerIdColor() {}
@@ -45,13 +51,13 @@ vec4 forwardExternalColor(out bool castShadows) {
45
51
  vExternalColor = externalColor;
46
52
  castShadows = true;
47
53
  return externalColor;
48
- }`);const s=9===e.output;i.uniforms.add(new l("externalColorMixMode",o=>o.componentParameters.externalColorMixMode)).code.add(d`
54
+ }`);const s=9===e.output;i.uniforms.add(new l("externalColorMixMode",o=>o.componentParameters.externalColorMixMode)).code.add(n`
49
55
  void readExternalColor(out vec4 color, out int colorMixMode) {
50
56
  color = vExternalColor;
51
57
  colorMixMode = externalColorMixMode;
52
58
  }
53
59
 
54
60
  void outputObjectAndLayerIdColor() {
55
- ${n(s,"fragColor = vec4(0, 0, 0, 0);")}
61
+ ${a(s,"fragColor = vec4(0, 0, 0, 0);")}
56
62
  }
57
63
  `)}export{u as ComponentData};