@arcgis/core 4.34.0-next.17 → 4.34.0-next.18

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 (136) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/{400a4c9fa62964f8fa1d.js → 1f48d6c76f0014064eca.js} +1 -1
  3. package/assets/esri/core/workers/chunks/3cf31e51266f40072f71.js +1 -0
  4. package/assets/esri/core/workers/chunks/4325fdd96d9ea344132e.js +1 -0
  5. package/assets/esri/core/workers/chunks/68374cf42a069436830d.js +1 -0
  6. package/assets/esri/core/workers/chunks/6f8de923519bb16af8ba.js +1 -0
  7. package/assets/esri/core/workers/chunks/85753105268aeff84e69.js +1 -0
  8. package/assets/esri/core/workers/chunks/8637b9cb30170ac4eae2.js +1 -0
  9. package/assets/esri/core/workers/chunks/872f151a3a2bc9052be0.js +1 -0
  10. package/assets/esri/core/workers/chunks/8b4a35e3ed39d8be3394.js +1 -0
  11. package/assets/esri/core/workers/chunks/{d33a5d79f2163ad62b1d.js → 9965961bad09910f577b.js} +1 -1
  12. package/assets/esri/core/workers/chunks/9d499a37b960273c3f84.js +1 -0
  13. package/assets/esri/core/workers/chunks/a507192771e5f4f82973.js +1 -0
  14. package/assets/esri/core/workers/chunks/a9e1caf05c81055ae194.js +1 -0
  15. package/assets/esri/core/workers/chunks/{1415d4e2f5f3193be004.js → aa4ae0e54a0507e8dd0f.js} +1 -1
  16. package/assets/esri/core/workers/chunks/d3bfd0c382c2f39a787b.js +1 -0
  17. package/assets/esri/core/workers/chunks/d6df12bed626d56cd6b2.js +1 -0
  18. package/assets/esri/core/workers/chunks/e0146db608959ead9c97.js +1 -0
  19. package/assets/esri/core/workers/chunks/f4442a2b40e44f90b461.js +1 -0
  20. package/assets/esri/core/workers/chunks/{fa5715ca3ce95d005b0a.js → faa892ad4cc8a90b6c79.js} +1 -1
  21. package/assets/esri/themes/base/widgets/_Legend.scss +2 -0
  22. package/assets/esri/themes/dark/main.css +1 -1
  23. package/assets/esri/themes/light/main.css +1 -1
  24. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ar.json +1 -1
  25. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_bg.json +1 -1
  26. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_bs.json +1 -1
  27. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ca.json +1 -1
  28. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_cs.json +1 -1
  29. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_da.json +1 -1
  30. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_de.json +1 -1
  31. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_el.json +1 -1
  32. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_es.json +1 -1
  33. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_et.json +1 -1
  34. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_fi.json +1 -1
  35. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_fr.json +1 -1
  36. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_he.json +1 -1
  37. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_hr.json +1 -1
  38. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_hu.json +1 -1
  39. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_id.json +1 -1
  40. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_it.json +1 -1
  41. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ja.json +1 -1
  42. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ko.json +1 -1
  43. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_lt.json +1 -1
  44. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_lv.json +1 -1
  45. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_nl.json +1 -1
  46. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_no.json +1 -1
  47. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_pl.json +1 -1
  48. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_pt-BR.json +1 -1
  49. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_pt-PT.json +1 -1
  50. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ro.json +1 -1
  51. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_ru.json +1 -1
  52. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sk.json +1 -1
  53. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sl.json +1 -1
  54. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sr.json +1 -1
  55. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_sv.json +1 -1
  56. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_th.json +1 -1
  57. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_tr.json +1 -1
  58. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_uk.json +1 -1
  59. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_vi.json +1 -1
  60. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_zh-CN.json +1 -1
  61. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_zh-HK.json +1 -1
  62. package/assets/esri/widgets/BatchAttributeForm/t9n/BatchAttributeForm_zh-TW.json +1 -1
  63. package/chunks/sphere.js +1 -1
  64. package/config.js +1 -1
  65. package/core/accessorSupport/trackingUtils.js +1 -1
  66. package/core/sql.js +1 -1
  67. package/geometry/spatialReferenceEllipsoidUtils.js +1 -1
  68. package/geometry/support/sphere.js +1 -1
  69. package/interfaces.d.ts +38 -33
  70. package/kernel.js +1 -1
  71. package/layers/FeatureLayer.js +1 -1
  72. package/layers/SubtypeGroupLayer.js +1 -1
  73. package/layers/VectorTileLayer.js +1 -1
  74. package/layers/VideoLayer.js +1 -1
  75. package/layers/orientedImagery/core/ExposurePoint.js +1 -1
  76. package/layers/orientedImagery/core/coverageUtils.js +1 -1
  77. package/layers/orientedImagery/core/utils.js +1 -1
  78. package/layers/orientedImagery/transformations/updateElevation.js +1 -1
  79. package/layers/orientedImagery/transformations/updateElevationUtils.js +1 -1
  80. package/layers/orientedImagery/transformations/utils.js +1 -1
  81. package/layers/support/SubtypeSublayer.js +1 -1
  82. package/layers/support/TitleCreator.js +1 -1
  83. package/layers/support/fieldUtils.js +1 -1
  84. package/layers/video/VideoCameraSensorModel.js +1 -1
  85. package/layers/video/VideoController.js +1 -1
  86. package/networks/UtilityNetwork.js +1 -1
  87. package/package.json +1 -1
  88. package/rest/knowledgeGraphService.js +1 -1
  89. package/smartMapping/renderers/support/spikeUtils.js +1 -1
  90. package/support/revision.js +1 -1
  91. package/symbols/support/previewCIMSymbol.js +1 -1
  92. package/symbols/support/previewSymbol2D.js +1 -1
  93. package/symbols/support/svgUtils.js +1 -1
  94. package/views/2d/engine/vectorTiles/style/StyleRepository.js +1 -1
  95. package/views/3d/camera/constraintUtils/tilt.js +1 -1
  96. package/views/3d/camera/intersectionUtils.js +1 -1
  97. package/views/3d/layers/graphics/Deconflictor.js +1 -1
  98. package/views/3d/layers/i3s/I3SIndex.js +1 -1
  99. package/views/3d/layers/support/StageLayerElevationProvider.js +1 -1
  100. package/views/3d/state/ViewState.js +1 -1
  101. package/views/3d/state/ViewStateManager.js +1 -1
  102. package/views/3d/state/controllers/GamepadKeyboardController.js +1 -1
  103. package/views/3d/state/controllers/PointToPointAnimationController.js +1 -1
  104. package/views/3d/state/utils/navigationUtils.js +1 -1
  105. package/views/3d/terrain/OverlayManager.js +1 -1
  106. package/views/3d/terrain/TerrainSurface.js +1 -1
  107. package/views/3d/terrain/TileRenderer.js +1 -1
  108. package/views/3d/webgl-engine/lib/Octree.js +1 -1
  109. package/views/3d/webgl-engine/lib/ShadowMap.js +1 -1
  110. package/views/3d/webgl-engine/lib/edgeRendering/edgePreprocessing.js +1 -1
  111. package/views/SceneView.js +1 -1
  112. package/views/support/drapedUtils.js +1 -1
  113. package/widgets/AreaMeasurement2D/AreaMeasurement2DTool.js +1 -1
  114. package/widgets/DistanceMeasurement2D/DistanceMeasurement2DTool.js +1 -1
  115. package/widgets/Expand.js +1 -1
  116. package/widgets/Legend/styles/support/sizeRampUtils.js +1 -1
  117. package/widgets/Legend/support/ActiveLayerInfo.js +1 -1
  118. package/widgets/Legend/support/sizeRampUtils.js +1 -1
  119. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  120. package/widgets/OrientedImageryViewer.js +1 -1
  121. package/widgets/support/GridControls.js +1 -1
  122. package/assets/esri/core/workers/chunks/254c4f7e277ae9915dce.js +0 -1
  123. package/assets/esri/core/workers/chunks/273beed633cc37416ad7.js +0 -1
  124. package/assets/esri/core/workers/chunks/49a57dc1e6d1048fa949.js +0 -1
  125. package/assets/esri/core/workers/chunks/500fb5f615f0c1db1b66.js +0 -1
  126. package/assets/esri/core/workers/chunks/52239e958a82ebcd2e7a.js +0 -1
  127. package/assets/esri/core/workers/chunks/78a57f5aeb277b84b3da.js +0 -1
  128. package/assets/esri/core/workers/chunks/802c6b1a6cb9264b8e4f.js +0 -1
  129. package/assets/esri/core/workers/chunks/88b1214c284c2ec7d51b.js +0 -1
  130. package/assets/esri/core/workers/chunks/932808e485f305b6a26a.js +0 -1
  131. package/assets/esri/core/workers/chunks/beb01d400f1aa089d2dc.js +0 -1
  132. package/assets/esri/core/workers/chunks/cfc5e0ec9b0290407383.js +0 -1
  133. package/assets/esri/core/workers/chunks/d2139307f62ea8bf999a.js +0 -1
  134. package/assets/esri/core/workers/chunks/ddb66fe6fcd0764daa7a.js +0 -1
  135. package/assets/esri/core/workers/chunks/eac7af86166c09c6a9be.js +0 -1
  136. package/assets/esri/core/workers/chunks/ec49e2849766402ad5c7.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import i from"../../../core/Accessor.js";import{difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import 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/unitUtils.js";import{property as E}from"../../../core/accessorSupport/decorators/property.js";import{subclass as S}from"../../../core/accessorSupport/decorators/subclass.js";import{i as w,c as C}from"../../../chunks/vec32.js";import{create as b}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as L}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as P}from"../../../geometry/ellipsoidUtils.js";import M from"../../../geometry/SpatialReference.js";import{getProjector as x}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as U}from"../../../geometry/projection/projectVectorToVector.js";import{create as R,equals as I,intersection as j,intersectsSphere as A,empty as V,expand as B}from"../../../geometry/support/aaBoundingRect.js";import{create as k,copy as N}from"../../../geometry/support/frustum.js";import{isPlateCarree as O}from"../../../geometry/support/spatialReferenceUtils.js";import{e as G,c as F,a as q}from"../../../chunks/sphere.js";import{ElevationQueryTileCache as W}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{debugFlags as H}from"../support/debugFlags.js";import{ElevationRange as Q}from"../support/ElevationRange.js";import{ElevationUpdateEvent as z}from"../support/ElevationUpdateEvent.js";import{toBoundingRect as X}from"../support/extentUtils.js";import{ClientType as Y}from"../support/index.js";import{updatingProgress as K}from"../support/updatingProperties.js";import{ElevationBounds as J}from"./ElevationBounds.js";import{ElevationData as Z,sampleElevation as ee}from"./ElevationData.js";import{create as te}from"./ExtentHelper.js";import{TextureUpdate as ie}from"./interfaces.js";import{LayerClass as re,LayerClasses as se}from"./LayerClass.js";import{OverlayManager as ae}from"./OverlayManager.js";import{PlanarPatch as ne}from"./PlanarPatch.js";import{RenderOrder as le}from"./RenderOrder.js";import{ScaleRangeQueries as oe}from"./ScaleRangeQueries.js";import{SphericalPatch as he}from"./SphericalPatch.js";import{SplitLimits as de}from"./SplitLimits.js";import{maxRootTiles as pe,tooManyRootTilesAfterChangeError as ue,tooManyRootTilesForLayerError as ce,maxTileNeighborLevelDelta as ge,maxMemoryLodBias as me}from"./TerrainConst.js";import{TerrainRenderer as _e}from"./TerrainRenderer.js";import fe from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as ye,isVectorTileLayerView as Te,neighborEdgeIndices as ve,internalAssert as Ee,oppositeEdge as Se,isSurfaceLayerView as we,isGroupLayerView as Ce,isMapTileLayerView as be,isBlendableLayerView as Le,isElevationLayerView as Pe,releaseTerrainData as Me,enableTerrainInternalChecks as xe,oppositeCorner as De,enableWaterproofTests as Ue,enableInternalTerrainChecks as Re,enableTerrainWaterproofChecks as Ie,neighborCornerIndices as je}from"./terrainUtils.js";import{Tile as Ae,lijEquals as Ve}from"./Tile.js";import{printAllocations as Be}from"./TilePerLayerInfo.js";import{TileUpdate as ke}from"./TileUpdate.js";import{IteratorPreorder as Ne,IteratorPostorder as Oe,compareTilesByLij as Ge,hasLoadableSiblings as Fe,sortTilesByPOI as qe}from"./tileUtils.js";import{TilingSchemeLogic as We}from"./TilingSchemeLogic.js";import{TransparencyMode as $e}from"./TransparencyMode.js";import{UpsampleInfo as He}from"./UpsampleInfo.js";import{isCompositeBlendMode as Qe,blendModeFromString as ze}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{PBRMode as Xe}from"../webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{RenderRequestType as Ye}from"../webgl-engine/lib/basicInterfaces.js";import{hasLayerBasedScaleVisibility as Ke}from"../../support/layerViewUtils.js";import{RenderState as Je}from"../../support/RenderState.js";import{ImmediateTask as Ze,TaskPriority as et,noBudget as tt}from"../../support/Scheduler.js";import{TextureCompressionTracker as it}from"../../support/TextureCompressionTracker.js";import{Yield as rt}from"../../support/Yield.js";var st;let at=class extends(n.EventedMixin(i)){static{st=this}get allTiles(){return a(this._allTiles)}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 it,this._iteratorPool=new p(Ne,(e=>e.remove=()=>this._iteratorPool.release(e))),this._postorderIterator=new Oe,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._usedMemory=null,this._performanceInfo=new fe,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=b(),this._eyePosSurfaceSR=b(),this._splitLimits=new de,this._frustum=k(),this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new L,this._frameTask=Ze,this._allTiles=new u,this._upsampleInfoPool=new p(He),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=R(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=M.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationBounds=new J(1/0,-1/0),this.rootTileElevationBounds=new J(1/0,-1/0),this._projectorCache=new Map,this._radiusModifier=Math.cos(Math.PI/16/16),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;const t=e.view;this.overlayManager=new ae({...e,surface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?he:ne,this._ellipsoid=P(t.spatialReference),this._renderer=new _e(this.overlayManager.renderer,t.stage,this._allTiles,this._ellipsoid.radius,this.terrainTextureCompressionTracker,t.resourceController.memoryController),Ke()||(this._scaleRangeQueries=new oe)}initialize(){const e=this.view,t=e.resourceController,i=t.memoryController;this._tileCache=new d(((e,t)=>i.newCache(e,t)),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",(e=>e.unloadMapData())),this._elevationQueryCache=new W(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(ie.FADING)})),_((()=>({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);(t===Je.IDLE||Math.min(r,360-r)>=30)&&(this.heading=i)}))],"overlayManager"),this.addHandles([_((()=>this.baseOpacity),(()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?ie.UNFADED:ie.IMMEDIATE)}),f),_((()=>this.hasCompositeBlendMode),(()=>this._updateTileTextures(this._evaluateTransparency()?ie.UNFADED:ie.IMMEDIATE)),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))})),_((()=>H.TERRAIN_TILE_TREE_SHOW_TILES),(t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then((({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&H.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 We({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme(),this._elevationDataRequester=t.createStreamDataRequester(Y.ELEVATION),this._mapDataRequester=t.createStreamDataRequester(Y.BASEMAP);const o=t.scheduler;this._frameTask=o.registerTask(et.TERRAIN_SURFACE,this),this.addHandles([_((()=>this._extentHelper.stencilEnabledExtents),(e=>this._renderer.setStencilEnabledLayerExtents(e)),T),_((()=>this.tilingSchemeLogic.tilingScheme),(()=>this._updateTilingScheme()),y),_((()=>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()),f),_((()=>e.qualitySettings?.fadeDuration),(e=>this._renderer.textureFadingEnabled=e>0),T),_((()=>e.qualitySettings?.physicallyBasedRenderingEnabled),(e=>this._renderer.pbrMode=e?Xe.Simplified:Xe.Disabled),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)}destroy(){this._frameTask.remove(),this._watchUpdatingTracking.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach(((e,t)=>this._unregisterTiledLayerView(t))),this._elevationDataRequester=null,this._mapDataRequester=null,this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),Ae.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroy(),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),Be(),this._layerViews.forEach((e=>e.length=0))}get renderer(){return this._renderer}get frustum(){return this._frustum}get snapLevel(){if(this.lodSnappingEnabled){const{view:e,tilingScheme:t}=this,i=e.scale;if(t&&i){const r=t.levelAtScale(i)+e.qualitySettings.tiledSurface.lodBias,s=t.getMaxLod();return r<=0?null:Math.min(r,s||1/0)}}return 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,{clippingArea:t}=this.view;if(null==t||null==e)return null;const i=R(),r=X(t,i,e)?i:null,s=this._get("extent");return I(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=j(this.groundExtent,this._userClippingExtent,R()),t=this._get("extent");return I(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.running||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get running(){return(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 null!=this._rootTiles}set renderOrder(e){this._renderer.renderOrder=e,this._set("renderOrder",e)}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 this._renderer.transparency===$e.Opaque}get invisible(){return this._renderer.transparency===$e.Invisible}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}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length)return null;if(0===s[0].layerInfo[re.ELEVATION].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=x(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=w(lt,e,t,i);a(n,0,n,0);return ut(s,n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[re.ELEVATION].length:0;if(r?.length&&0!==s)for(let a=0;a<t;++a){const t=3*a;i(a,ut(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,lt,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(lt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;lt[0]>t[2]&&(i+=1),lt[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=x(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationBounds(e,t){const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationBounds(): could not project given point to tiling scheme coordinate system"),null;G(e,ot);const r=q(ot);i(r,0,r,0);const s=new Q,a=this._rootTiles;if(null!=a){const e=[];for(const i of a)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,ot))continue;const r=i.children;if(null==r[0]||i.rendered)s.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of r)e.push(t)}}return s}getRootElevationBounds(){return new Q(this.rootTileElevationBounds.min,this.rootTileElevationBounds.max)}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationBounds.min)*this._radiusModifier;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,q(ot),this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;ot[3]=t;let i=null;const r=e=>{if(e&&A(e.extent,ot)){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?$e.Invisible:$e.InvisibleWithDraped:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?$e.Opaque:$e.Transparent;return this._renderer.transparency=r,i!==r}_updateTilingScheme(){const e=this.tilingSchemeLogic.tilingScheme;if(!(e!==this.tilingScheme))return;ye(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??M.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&O(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(st._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=ht;let s=t.rootTilesInExtent(e,i,5*pe);if(null!=this._rootTiles){if(s.length>pe)return void l.getLogger(this).warn(ue);const e=this._rootTiles.map((e=>e.lij)),t=r(e,s,Ve);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter((e=>!(t.removed.findIndex((t=>Ve(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>pe&&(l.getLogger(this).warn(ce),s=t.rootTilesInExtent(e,i,pe)),this._setRootTiles(s.map((e=>this._newRootTile(e))));I(i,this._rootTilesExtent)||(this._rootTilesExtent=R(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(Ge),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(Ge);const t=this.renderer;e.forEach((e=>t.updateGeometryIfNeeded(e))),e.forEach((e=>this._pendingTilesForElevationUpdateEvent.add(e)))}_shouldSplit(e){return e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)===ke.SPLIT}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(ke.SPLIT),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationBounds(),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(ke.GEOMETRY)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Fe(e),i=this.visibleElevationBounds;let r=t?i.min:1/0,s=t?i.max:-1/0;const a=this.extent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty();const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(ke.GEOMETRY)&&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.min!==r||i.max!==s)&&(this.visibleElevationBounds=new J(r,s))}_updateRootTileElevationBounds(){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.rootTileElevationBounds;r.min===e&&r.max===t||(this.rootTileElevationBounds=new J(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=N(this._splitLimits.frustum??k(),t.frustum):this._splitLimits.frustum=null,N(this._frustum,e.frustum),C(this._eyePosRenderSR,t.eye),U(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[re.MAP].some(Te)&&e.setPendingUpdate(ke.TEXTURE_FADING),this._pendingTilesToUpdate.add(e)}))}_updateTileTexture(e,t){const i=e.resetPendingUpdate(ke.TEXTURE_FADING)?ke.TEXTURE_FADING:!!e.resetPendingUpdate(ke.TEXTURE_NOFADING)&&ke.TEXTURE_NOFADING;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=dt.extent;V(e),this._pendingTilesForElevationUpdateEvent.forEach((t=>B(e,t.extent,e))),this._pendingTilesForElevationUpdateEvent.clear(),dt.spatialReference=this.spatialReference,this.emit("elevation-change",dt),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"),xe&&this._checkTileInvariant(),!e.hasProgressed)return rt}_checkTileInvariant(){const e=new Map;this._allTiles.forAll((t=>e.set(t,new Set))),this._allTiles.forAll((t=>{if(ye(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(ye(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(ke.MERGE)){ye(!t.hasPendingUpdate(ke.SPLIT),"Tile can be both split and merge at the same time");for(const e of t.children)ye(e.leaf||e.hasPendingUpdate(ke.MERGE),"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<=ge;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ge} (edge[${i}])`),ye(r,`tile level delta [${t.level}] vs [${e.level}] > ${ge}`))}ye(t.level-e.level<=ge,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ge,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(ve[i],s);if(null!=a){if(t.leaf&&t.level>=ge){let i=a;for(;t.level-i.level<ge;)i=i.parent;const s=[r,t.lij[1]>>ge,t.lij[2]>>ge];if(!Ve(s,i.lij)){const r=e.get(i);ye(!r.has(t),"Cannot already have neighbor"),r.add(t)}}ye(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),ye(t.level-a.level<=ge,`Tile level delta [${t.level}] vs [${a.level}] > ${ge}`)}}})),this._allTiles.forAll((t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);ye(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 ct(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=null!=n&&n.hasPendingUpdate(ke.MERGE),o=l?ke.MERGE:e.shouldSplit(r,s,i),h=o===ke.SPLIT;e.leaf?gt(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(ke.SPLIT),e.leaf||e.setPendingUpdate(ke.MERGE),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(ke.MERGE),e.leaf&&e.setPendingUpdate(ke.SPLIT)):(e.resetPendingUpdate(ke.SPLIT)&&e.updateAgentSuspension(),o===ke.ELEVATION&&e.updateAgents(re.ELEVATION),e.leaf||(e.setPendingUpdate(ke.MERGE),e.resetPendingUpdate(ke.SPLIT)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||(qe(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger&&this._treeDebugger.update(),e.madeProgress())}_markTileToUpdate(e){Ee(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(Ge);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Ee(r.loaded),Ee(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=je[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(De(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(Se(ve[t]),(t=>!(!t.loaded||!t.intersectsClippingArea)&&(Ee(e.has(t)||Ge(r,t)<0),i(r,t),!0))),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,xe&&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(ke.MERGE)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(ke.MERGE);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(ke.MERGE);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(ke.SPLIT)){let t=!0;const i=s.level;if(i>=ge){const e=e=>e.leaf||i-e.level<ge;for(let r=0;r<4;++r){const a=s.findNeighborTile(ve[r],e);null!=a&&i-a.level===ge&&(t=!1,xe&&(Ee(a.leaf),Ee(a.hasPendingUpdate(ke.SPLIT))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(ke.SPLIT)}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._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some((t=>(t.resetPendingUpdate(ke.GEOMETRY)&&(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.overlayManager?.updateOverlayParameters(Ye.UPDATE),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){const e=this.view.quality;return this.view.qualitySettings.tiledSurface.lodBias-(1-e)*me}_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?_t(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(st._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){ye(e.leaf,"Tile that is already split should not be split again!"),ye(e.rendered,"Tile marked to split is not rendered"),_t(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),ye(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=>gt(e,e.hasPendingUpdate(ke.SPLIT)))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){pt.spatialReference=this.spatialReference,pt.extent=e.extent,pt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",pt)}createTile(e,t,i,r){ye(!!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(ke.SPLIT),s}get _shortBatches(){return this.view.state.mode!==Je.IDLE}_mergeTile(e){ye(!e.hasPendingUpdate(ke.SPLIT),"_mergeTile sanity check"),ye(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),ye(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),gt(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&this.overlayManager.updateTileOverlayParameters(e)}_handleLayerViewChanges(e=tt){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(be(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((Le(e)||Ce(e))&&Qe(ze[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Pe(e)?re.ELEVATION:re.MAP}_registerTiledLayerView(e){const t=[];if((Le(e)||Ce(e))&&t.push(_((()=>e.layer.blendMode),(()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(ie.UNFADED)}))),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_((()=>e.suspended),(()=>this._updateTiledLayers()))),t.push(_((()=>e.fullOpacity),(()=>this._updateTileTextures(ie.UNFADED)))),t.push(_((()=>"effectiveScaleRange"in e.layer?e.layer.effectiveScaleRange:null),(()=>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(r===re.MAP){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)}));for(const r of se){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),e===re.ELEVATION&&i.computeElevationBounds()}this._updateRootTileElevationBounds()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll((t=>{t.updateAgents(re.MAP),e===ie.IMMEDIATE?this.renderer.updateTileTexture(t,ke.TEXTURE_NOFADING):t.updateRenderData(re.MAP,e)})),this._evaluateTransparency()}_invalidateLayerData(e,t){this._allTiles.forAll((i=>i.removeLayerAgent(e,t))),this._allTiles.forAll((i=>i.invalidateLayerData(e,t)))}setTileTreeDirty(){this._allTilesDirty=!0}requestRender(e=Ye.UPDATE){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||Te(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();const s=t===re.ELEVATION;return r.requester??=s?this._elevationDataRequester:this._mapDataRequester,s?Pe(i)?this._requestElevationTileData(e,i,r):Promise.reject():be(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 ${re.ELEVATION}/${t.uid} error ${i}`),this._dataMissing(e,re.ELEVATION,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[re.ELEVATION].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",re.ELEVATION,e.lij.toString());const s=new Z(e.lij,e.extent,i);e.dataArrived(r,re.ELEVATION,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:re.ELEVATION});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._updateRootTileElevationBounds(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{Me(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer ${re.MAP}/${t.uid} error ${r}`),this._dataMissing(e,re.MAP,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule((()=>{this.requestUpdate(),m(i)?Me(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(re.MAP,t.uid);if(null==r)return Me(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,re.MAP,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:re.MAP})}_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 visualizeNormals(){return this._renderer.visualizeNormals}set visualizeNormals(e){this._renderer.visualizeNormals=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){Ie(e)}};e([E()],at.prototype,"_renderer",void 0),e([E({constructOnly:!0})],at.prototype,"_scaleRangeQueries",void 0),e([E({constructOnly:!0})],at.prototype,"view",void 0),e([E({constructOnly:!0})],at.prototype,"overlayManager",void 0),e([E({constructOnly:!0})],at.prototype,"terrainTextureCompressionTracker",void 0),e([E()],at.prototype,"_hasPendingUpdates",void 0),e([E()],at.prototype,"_asyncWorkItems",void 0),e([E()],at.prototype,"_allTilesDirty",void 0),e([E()],at.prototype,"_allTilesSorted",void 0),e([E()],at.prototype,"_viewChanged",void 0),e([E({type:Number})],at.prototype,"heading",void 0),e([E()],at.prototype,"_splitLimits",void 0),e([E({readOnly:!0})],at.prototype,"_watchUpdatingTracking",void 0),e([E()],at.prototype,"_frameTask",void 0),e([E()],at.prototype,"demResolution",null),e([E({readOnly:!0})],at.prototype,"snapLevel",null),e([E({readOnly:!0})],at.prototype,"lodSnappingEnabled",null),e([E()],at.prototype,"_userClippingExtent",null),e([E()],at.prototype,"_rootTilesExtent",void 0),e([E({readOnly:!0})],at.prototype,"extent",null),e([E({readOnly:!0})],at.prototype,"groundExtent",null),e([E({readOnly:!0})],at.prototype,"_tilingSchemeExtent",null),e([E({readOnly:!0})],at.prototype,"updating",null),e([E({readOnly:!0})],at.prototype,"running",null),e([E(K)],at.prototype,"updatingProgress",void 0),e([E({readOnly:!0})],at.prototype,"updatingProgressValue",null),e([E()],at.prototype,"_maxNumUpdating",void 0),e([E()],at.prototype,"baseOpacity",null),e([E()],at.prototype,"hasCompositeBlendMode",void 0),e([E({readOnly:!0})],at.prototype,"viewingMode",null),e([E()],at.prototype,"maxTextureScale",void 0),e([E({readOnly:!0})],at.prototype,"ready",null),e([E({value:le.FRONT_TO_BACK})],at.prototype,"renderOrder",null),e([E({readOnly:!0})],at.prototype,"rootTiles",null),e([E()],at.prototype,"_rootTiles",void 0),e([E({readOnly:!0})],at.prototype,"spatialReference",null),e([E({type:t})],at.prototype,"backgroundColor",null),e([E({value:!1})],at.prototype,"slicePlaneEnabled",null),e([E({readOnly:!0})],at.prototype,"tilingScheme",void 0),e([E({readOnly:!0})],at.prototype,"tilingSchemeLocked",null),e([E({readOnly:!0})],at.prototype,"tilingSchemeLogic",void 0),e([E()],at.prototype,"wireframe",null),e([E({value:!1})],at.prototype,"suspended",null),e([E()],at.prototype,"fadeDuration",null),e([E()],at.prototype,"visibleElevationBounds",void 0),e([E()],at.prototype,"rootTileElevationBounds",void 0),e([E()],at.prototype,"_layerViewsDirty",void 0),e([E()],at.prototype,"renderPatchBorders",null),e([E()],at.prototype,"visualizeNormals",null),e([E()],at.prototype,"renderingDisabled",null),at=st=e([S("esri.views.3d.terrain.TerrainSurface")],at);const nt=at,lt=b(),ot=F(),ht=R();new u;const dt=new z("ground"),pt={spatialReference:null,extent:null,scale:0};function ut(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 ee(t,i,s)}return null}class ct{constructor(e){this.capacity=e,this._head=0,this._tail=0,this._data=new Array(e)}push(e){const t=this._tail;if(!(t<this.capacity))throw new Error("Queue full");this._data[t]=e,this._tail=t+1}pushAll(e){const t=e.length;if(0===t)return;const i=this._tail;if(!(i+t<=this.capacity))throw new Error("Queue full");for(let r=0;r<t;++r)this._data[i+r]=e[r];this._tail=i+t}pop(){const e=this._head;if(e<this._tail){const t=this._data[e];return this._head=e+1,t}}get empty(){return this._head>=this._tail}get full(){return this._tail>=this._data.length}}function gt(e,t){!e.leaf||e.level<ge||yt(e,(e=>{t&&mt(e);const i=ft(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ft(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}}))}function mt(e){if(e.hasPendingUpdate(ke.SPLIT))return;let t=e.parent;for(;t?.resetPendingUpdate(ke.MERGE);)t=t.parent;e.resetPendingUpdate(ke.MERGE),e.leaf&&e.setPendingUpdate(ke.SPLIT),e.level<ge||yt(e,(e=>{mt(e)}))}function _t(e){e.level<ge||yt(e,(e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ft(t));)t=t.parent}}))}function ft(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function yt(e,t){if(e.level<ge)return;const i=e.level-ge,r=e.lij[1]>>ge,s=e.lij[2]>>ge,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(ve[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{nt as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import i from"../../../core/Accessor.js";import{difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import 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/unitUtils.js";import{property as E}from"../../../core/accessorSupport/decorators/property.js";import{subclass as S}from"../../../core/accessorSupport/decorators/subclass.js";import{i as w,c as C}from"../../../chunks/vec32.js";import{create as b}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as L}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as P}from"../../../geometry/ellipsoidUtils.js";import M from"../../../geometry/SpatialReference.js";import{getProjector as x}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as U}from"../../../geometry/projection/projectVectorToVector.js";import{create as R,equals as I,intersection as j,intersectsSphere as A,empty as V,expand as B}from"../../../geometry/support/aaBoundingRect.js";import{create as k,copy as N}from"../../../geometry/support/frustum.js";import{isPlateCarree as O}from"../../../geometry/support/spatialReferenceUtils.js";import{h as G,c as F,a as q}from"../../../chunks/sphere.js";import{ElevationQueryTileCache as W}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{debugFlags as H}from"../support/debugFlags.js";import{ElevationRange as Q}from"../support/ElevationRange.js";import{ElevationUpdateEvent as z}from"../support/ElevationUpdateEvent.js";import{toBoundingRect as X}from"../support/extentUtils.js";import{ClientType as Y}from"../support/index.js";import{updatingProgress as K}from"../support/updatingProperties.js";import{ElevationBounds as J}from"./ElevationBounds.js";import{ElevationData as Z,sampleElevation as ee}from"./ElevationData.js";import{create as te}from"./ExtentHelper.js";import{TextureUpdate as ie}from"./interfaces.js";import{LayerClass as re,LayerClasses as se}from"./LayerClass.js";import{OverlayManager as ae}from"./OverlayManager.js";import{PlanarPatch as ne}from"./PlanarPatch.js";import{RenderOrder as le}from"./RenderOrder.js";import{ScaleRangeQueries as oe}from"./ScaleRangeQueries.js";import{SphericalPatch as he}from"./SphericalPatch.js";import{SplitLimits as de}from"./SplitLimits.js";import{maxRootTiles as pe,tooManyRootTilesAfterChangeError as ue,tooManyRootTilesForLayerError as ce,maxTileNeighborLevelDelta as ge,maxMemoryLodBias as me}from"./TerrainConst.js";import{TerrainRenderer as _e}from"./TerrainRenderer.js";import fe from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as ye,isVectorTileLayerView as Te,neighborEdgeIndices as ve,internalAssert as Ee,oppositeEdge as Se,isSurfaceLayerView as we,isGroupLayerView as Ce,isMapTileLayerView as be,isBlendableLayerView as Le,isElevationLayerView as Pe,releaseTerrainData as Me,enableTerrainInternalChecks as xe,oppositeCorner as De,enableWaterproofTests as Ue,enableInternalTerrainChecks as Re,enableTerrainWaterproofChecks as Ie,neighborCornerIndices as je}from"./terrainUtils.js";import{Tile as Ae,lijEquals as Ve}from"./Tile.js";import{printAllocations as Be}from"./TilePerLayerInfo.js";import{TileUpdate as ke}from"./TileUpdate.js";import{IteratorPreorder as Ne,IteratorPostorder as Oe,compareTilesByLij as Ge,hasLoadableSiblings as Fe,sortTilesByPOI as qe}from"./tileUtils.js";import{TilingSchemeLogic as We}from"./TilingSchemeLogic.js";import{TransparencyMode as $e}from"./TransparencyMode.js";import{UpsampleInfo as He}from"./UpsampleInfo.js";import{isCompositeBlendMode as Qe,blendModeFromString as ze}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{PBRMode as Xe}from"../webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{RenderRequestType as Ye}from"../webgl-engine/lib/basicInterfaces.js";import{hasLayerBasedScaleVisibility as Ke}from"../../support/layerViewUtils.js";import{RenderState as Je}from"../../support/RenderState.js";import{ImmediateTask as Ze,TaskPriority as et,noBudget as tt}from"../../support/Scheduler.js";import{TextureCompressionTracker as it}from"../../support/TextureCompressionTracker.js";import{Yield as rt}from"../../support/Yield.js";var st;let at=class extends(n.EventedMixin(i)){static{st=this}get allTiles(){return a(this._allTiles)}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 it,this._iteratorPool=new p(Ne,(e=>e.remove=()=>this._iteratorPool.release(e))),this._postorderIterator=new Oe,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._usedMemory=null,this._performanceInfo=new fe,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=b(),this._eyePosSurfaceSR=b(),this._splitLimits=new de,this._frustum=k(),this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new L,this._frameTask=Ze,this._allTiles=new u,this._upsampleInfoPool=new p(He),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=R(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=M.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationBounds=new J(1/0,-1/0),this.rootTileElevationBounds=new J(1/0,-1/0),this._projectorCache=new Map,this._radiusModifier=Math.cos(Math.PI/16/16),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;const t=e.view;this.overlayManager=new ae({...e,surface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?he:ne,this._ellipsoid=P(t.spatialReference),this._renderer=new _e(this.overlayManager.renderer,t.stage,this._allTiles,this._ellipsoid.radius,this.terrainTextureCompressionTracker,t.resourceController.memoryController),Ke()||(this._scaleRangeQueries=new oe)}initialize(){const e=this.view,t=e.resourceController,i=t.memoryController;this._tileCache=new d(((e,t)=>i.newCache(e,t)),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",(e=>e.unloadMapData())),this._elevationQueryCache=new W(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(ie.FADING)})),_((()=>({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);(t===Je.IDLE||Math.min(r,360-r)>=30)&&(this.heading=i)}))],"overlayManager"),this.addHandles([_((()=>this.baseOpacity),(()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?ie.UNFADED:ie.IMMEDIATE)}),f),_((()=>this.hasCompositeBlendMode),(()=>this._updateTileTextures(this._evaluateTransparency()?ie.UNFADED:ie.IMMEDIATE)),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))})),_((()=>H.TERRAIN_TILE_TREE_SHOW_TILES),(t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then((({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&H.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 We({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme(),this._elevationDataRequester=t.createStreamDataRequester(Y.ELEVATION),this._mapDataRequester=t.createStreamDataRequester(Y.BASEMAP);const o=t.scheduler;this._frameTask=o.registerTask(et.TERRAIN_SURFACE,this),this.addHandles([_((()=>this._extentHelper.stencilEnabledExtents),(e=>this._renderer.setStencilEnabledLayerExtents(e)),T),_((()=>this.tilingSchemeLogic.tilingScheme),(()=>this._updateTilingScheme()),y),_((()=>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()),f),_((()=>e.qualitySettings?.fadeDuration),(e=>this._renderer.textureFadingEnabled=e>0),T),_((()=>e.qualitySettings?.physicallyBasedRenderingEnabled),(e=>this._renderer.pbrMode=e?Xe.Simplified:Xe.Disabled),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)}destroy(){this._frameTask.remove(),this._watchUpdatingTracking.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach(((e,t)=>this._unregisterTiledLayerView(t))),this._elevationDataRequester=null,this._mapDataRequester=null,this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),Ae.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroy(),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),Be(),this._layerViews.forEach((e=>e.length=0))}get renderer(){return this._renderer}get frustum(){return this._frustum}get snapLevel(){if(this.lodSnappingEnabled){const{view:e,tilingScheme:t}=this,i=e.scale;if(t&&i){const r=t.levelAtScale(i)+e.qualitySettings.tiledSurface.lodBias,s=t.getMaxLod();return r<=0?null:Math.min(r,s||1/0)}}return 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,{clippingArea:t}=this.view;if(null==t||null==e)return null;const i=R(),r=X(t,i,e)?i:null,s=this._get("extent");return I(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=j(this.groundExtent,this._userClippingExtent,R()),t=this._get("extent");return I(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.running||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get running(){return(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 null!=this._rootTiles}set renderOrder(e){this._renderer.renderOrder=e,this._set("renderOrder",e)}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 this._renderer.transparency===$e.Opaque}get invisible(){return this._renderer.transparency===$e.Invisible}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}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length)return null;if(0===s[0].layerInfo[re.ELEVATION].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=x(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=w(lt,e,t,i);a(n,0,n,0);return ut(s,n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[re.ELEVATION].length:0;if(r?.length&&0!==s)for(let a=0;a<t;++a){const t=3*a;i(a,ut(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,lt,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(lt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;lt[0]>t[2]&&(i+=1),lt[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=x(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationBounds(e,t){const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationBounds(): could not project given point to tiling scheme coordinate system"),null;G(e,ot);const r=q(ot);i(r,0,r,0);const s=new Q,a=this._rootTiles;if(null!=a){const e=[];for(const i of a)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,ot))continue;const r=i.children;if(null==r[0]||i.rendered)s.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of r)e.push(t)}}return s}getRootElevationBounds(){return new Q(this.rootTileElevationBounds.min,this.rootTileElevationBounds.max)}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationBounds.min)*this._radiusModifier;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,q(ot),this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;ot[3]=t;let i=null;const r=e=>{if(e&&A(e.extent,ot)){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?$e.Invisible:$e.InvisibleWithDraped:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?$e.Opaque:$e.Transparent;return this._renderer.transparency=r,i!==r}_updateTilingScheme(){const e=this.tilingSchemeLogic.tilingScheme;if(!(e!==this.tilingScheme))return;ye(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??M.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&O(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(st._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=ht;let s=t.rootTilesInExtent(e,i,5*pe);if(null!=this._rootTiles){if(s.length>pe)return void l.getLogger(this).warn(ue);const e=this._rootTiles.map((e=>e.lij)),t=r(e,s,Ve);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter((e=>!(t.removed.findIndex((t=>Ve(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>pe&&(l.getLogger(this).warn(ce),s=t.rootTilesInExtent(e,i,pe)),this._setRootTiles(s.map((e=>this._newRootTile(e))));I(i,this._rootTilesExtent)||(this._rootTilesExtent=R(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(Ge),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(Ge);const t=this.renderer;e.forEach((e=>t.updateGeometryIfNeeded(e))),e.forEach((e=>this._pendingTilesForElevationUpdateEvent.add(e)))}_shouldSplit(e){return e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)===ke.SPLIT}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(ke.SPLIT),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationBounds(),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(ke.GEOMETRY)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Fe(e),i=this.visibleElevationBounds;let r=t?i.min:1/0,s=t?i.max:-1/0;const a=this.extent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty();const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(ke.GEOMETRY)&&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.min!==r||i.max!==s)&&(this.visibleElevationBounds=new J(r,s))}_updateRootTileElevationBounds(){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.rootTileElevationBounds;r.min===e&&r.max===t||(this.rootTileElevationBounds=new J(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=N(this._splitLimits.frustum??k(),t.frustum):this._splitLimits.frustum=null,N(this._frustum,e.frustum),C(this._eyePosRenderSR,t.eye),U(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[re.MAP].some(Te)&&e.setPendingUpdate(ke.TEXTURE_FADING),this._pendingTilesToUpdate.add(e)}))}_updateTileTexture(e,t){const i=e.resetPendingUpdate(ke.TEXTURE_FADING)?ke.TEXTURE_FADING:!!e.resetPendingUpdate(ke.TEXTURE_NOFADING)&&ke.TEXTURE_NOFADING;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=dt.extent;V(e),this._pendingTilesForElevationUpdateEvent.forEach((t=>B(e,t.extent,e))),this._pendingTilesForElevationUpdateEvent.clear(),dt.spatialReference=this.spatialReference,this.emit("elevation-change",dt),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"),xe&&this._checkTileInvariant(),!e.hasProgressed)return rt}_checkTileInvariant(){const e=new Map;this._allTiles.forAll((t=>e.set(t,new Set))),this._allTiles.forAll((t=>{if(ye(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(ye(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(ke.MERGE)){ye(!t.hasPendingUpdate(ke.SPLIT),"Tile can be both split and merge at the same time");for(const e of t.children)ye(e.leaf||e.hasPendingUpdate(ke.MERGE),"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<=ge;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ge} (edge[${i}])`),ye(r,`tile level delta [${t.level}] vs [${e.level}] > ${ge}`))}ye(t.level-e.level<=ge,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ge,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(ve[i],s);if(null!=a){if(t.leaf&&t.level>=ge){let i=a;for(;t.level-i.level<ge;)i=i.parent;const s=[r,t.lij[1]>>ge,t.lij[2]>>ge];if(!Ve(s,i.lij)){const r=e.get(i);ye(!r.has(t),"Cannot already have neighbor"),r.add(t)}}ye(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),ye(t.level-a.level<=ge,`Tile level delta [${t.level}] vs [${a.level}] > ${ge}`)}}})),this._allTiles.forAll((t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);ye(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 ct(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=null!=n&&n.hasPendingUpdate(ke.MERGE),o=l?ke.MERGE:e.shouldSplit(r,s,i),h=o===ke.SPLIT;e.leaf?gt(e,h):t.pushAll(e.children),l?(e.resetPendingUpdate(ke.SPLIT),e.leaf||e.setPendingUpdate(ke.MERGE),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(a)):h?(e.resetPendingUpdate(ke.MERGE),e.leaf&&e.setPendingUpdate(ke.SPLIT)):(e.resetPendingUpdate(ke.SPLIT)&&e.updateAgentSuspension(),o===ke.ELEVATION&&e.updateAgents(re.ELEVATION),e.leaf||(e.setPendingUpdate(ke.MERGE),e.resetPendingUpdate(ke.SPLIT)))}this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||(qe(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger&&this._treeDebugger.update(),e.madeProgress())}_markTileToUpdate(e){Ee(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(Ge);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Ee(r.loaded),Ee(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=je[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(De(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(Se(ve[t]),(t=>!(!t.loaded||!t.intersectsClippingArea)&&(Ee(e.has(t)||Ge(r,t)<0),i(r,t),!0))),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,xe&&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(ke.MERGE)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(ke.MERGE);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(ke.MERGE);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(ke.SPLIT)){let t=!0;const i=s.level;if(i>=ge){const e=e=>e.leaf||i-e.level<ge;for(let r=0;r<4;++r){const a=s.findNeighborTile(ve[r],e);null!=a&&i-a.level===ge&&(t=!1,xe&&(Ee(a.leaf),Ee(a.hasPendingUpdate(ke.SPLIT))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(ke.SPLIT)}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._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some((t=>(t.resetPendingUpdate(ke.GEOMETRY)&&(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.overlayManager?.updateOverlayParameters(Ye.UPDATE),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){const e=this.view.quality;return this.view.qualitySettings.tiledSurface.lodBias-(1-e)*me}_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?_t(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(st._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){ye(e.leaf,"Tile that is already split should not be split again!"),ye(e.rendered,"Tile marked to split is not rendered"),_t(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),ye(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=>gt(e,e.hasPendingUpdate(ke.SPLIT)))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){pt.spatialReference=this.spatialReference,pt.extent=e.extent,pt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",pt)}createTile(e,t,i,r){ye(!!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(ke.SPLIT),s}get _shortBatches(){return this.view.state.mode!==Je.IDLE}_mergeTile(e){ye(!e.hasPendingUpdate(ke.SPLIT),"_mergeTile sanity check"),ye(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),ye(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),gt(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&this.overlayManager.updateTileOverlayParameters(e)}_handleLayerViewChanges(e=tt){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(be(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((Le(e)||Ce(e))&&Qe(ze[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Pe(e)?re.ELEVATION:re.MAP}_registerTiledLayerView(e){const t=[];if((Le(e)||Ce(e))&&t.push(_((()=>e.layer.blendMode),(()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(ie.UNFADED)}))),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_((()=>e.suspended),(()=>this._updateTiledLayers()))),t.push(_((()=>e.fullOpacity),(()=>this._updateTileTextures(ie.UNFADED)))),t.push(_((()=>"effectiveScaleRange"in e.layer?e.layer.effectiveScaleRange:null),(()=>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(r===re.MAP){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)}));for(const r of se){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),e===re.ELEVATION&&i.computeElevationBounds()}this._updateRootTileElevationBounds()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll((t=>{t.updateAgents(re.MAP),e===ie.IMMEDIATE?this.renderer.updateTileTexture(t,ke.TEXTURE_NOFADING):t.updateRenderData(re.MAP,e)})),this._evaluateTransparency()}_invalidateLayerData(e,t){this._allTiles.forAll((i=>i.removeLayerAgent(e,t))),this._allTiles.forAll((i=>i.invalidateLayerData(e,t)))}setTileTreeDirty(){this._allTilesDirty=!0}requestRender(e=Ye.UPDATE){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||Te(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();const s=t===re.ELEVATION;return r.requester??=s?this._elevationDataRequester:this._mapDataRequester,s?Pe(i)?this._requestElevationTileData(e,i,r):Promise.reject():be(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 ${re.ELEVATION}/${t.uid} error ${i}`),this._dataMissing(e,re.ELEVATION,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[re.ELEVATION].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",re.ELEVATION,e.lij.toString());const s=new Z(e.lij,e.extent,i);e.dataArrived(r,re.ELEVATION,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:re.ELEVATION});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._updateRootTileElevationBounds(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{Me(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer ${re.MAP}/${t.uid} error ${r}`),this._dataMissing(e,re.MAP,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule((()=>{this.requestUpdate(),m(i)?Me(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(re.MAP,t.uid);if(null==r)return Me(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,re.MAP,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:re.MAP})}_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 visualizeNormals(){return this._renderer.visualizeNormals}set visualizeNormals(e){this._renderer.visualizeNormals=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){Ie(e)}};e([E()],at.prototype,"_renderer",void 0),e([E({constructOnly:!0})],at.prototype,"_scaleRangeQueries",void 0),e([E({constructOnly:!0})],at.prototype,"view",void 0),e([E({constructOnly:!0})],at.prototype,"overlayManager",void 0),e([E({constructOnly:!0})],at.prototype,"terrainTextureCompressionTracker",void 0),e([E()],at.prototype,"_hasPendingUpdates",void 0),e([E()],at.prototype,"_asyncWorkItems",void 0),e([E()],at.prototype,"_allTilesDirty",void 0),e([E()],at.prototype,"_allTilesSorted",void 0),e([E()],at.prototype,"_viewChanged",void 0),e([E({type:Number})],at.prototype,"heading",void 0),e([E()],at.prototype,"_splitLimits",void 0),e([E({readOnly:!0})],at.prototype,"_watchUpdatingTracking",void 0),e([E()],at.prototype,"_frameTask",void 0),e([E()],at.prototype,"demResolution",null),e([E({readOnly:!0})],at.prototype,"snapLevel",null),e([E({readOnly:!0})],at.prototype,"lodSnappingEnabled",null),e([E()],at.prototype,"_userClippingExtent",null),e([E()],at.prototype,"_rootTilesExtent",void 0),e([E({readOnly:!0})],at.prototype,"extent",null),e([E({readOnly:!0})],at.prototype,"groundExtent",null),e([E({readOnly:!0})],at.prototype,"_tilingSchemeExtent",null),e([E({readOnly:!0})],at.prototype,"updating",null),e([E({readOnly:!0})],at.prototype,"running",null),e([E(K)],at.prototype,"updatingProgress",void 0),e([E({readOnly:!0})],at.prototype,"updatingProgressValue",null),e([E()],at.prototype,"_maxNumUpdating",void 0),e([E()],at.prototype,"baseOpacity",null),e([E()],at.prototype,"hasCompositeBlendMode",void 0),e([E({readOnly:!0})],at.prototype,"viewingMode",null),e([E()],at.prototype,"maxTextureScale",void 0),e([E({readOnly:!0})],at.prototype,"ready",null),e([E({value:le.FRONT_TO_BACK})],at.prototype,"renderOrder",null),e([E({readOnly:!0})],at.prototype,"rootTiles",null),e([E()],at.prototype,"_rootTiles",void 0),e([E({readOnly:!0})],at.prototype,"spatialReference",null),e([E({type:t})],at.prototype,"backgroundColor",null),e([E({value:!1})],at.prototype,"slicePlaneEnabled",null),e([E({readOnly:!0})],at.prototype,"tilingScheme",void 0),e([E({readOnly:!0})],at.prototype,"tilingSchemeLocked",null),e([E({readOnly:!0})],at.prototype,"tilingSchemeLogic",void 0),e([E()],at.prototype,"wireframe",null),e([E({value:!1})],at.prototype,"suspended",null),e([E()],at.prototype,"fadeDuration",null),e([E()],at.prototype,"visibleElevationBounds",void 0),e([E()],at.prototype,"rootTileElevationBounds",void 0),e([E()],at.prototype,"_layerViewsDirty",void 0),e([E()],at.prototype,"renderPatchBorders",null),e([E()],at.prototype,"visualizeNormals",null),e([E()],at.prototype,"renderingDisabled",null),at=st=e([S("esri.views.3d.terrain.TerrainSurface")],at);const nt=at,lt=b(),ot=F(),ht=R();new u;const dt=new z("ground"),pt={spatialReference:null,extent:null,scale:0};function ut(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 ee(t,i,s)}return null}class ct{constructor(e){this.capacity=e,this._head=0,this._tail=0,this._data=new Array(e)}push(e){const t=this._tail;if(!(t<this.capacity))throw new Error("Queue full");this._data[t]=e,this._tail=t+1}pushAll(e){const t=e.length;if(0===t)return;const i=this._tail;if(!(i+t<=this.capacity))throw new Error("Queue full");for(let r=0;r<t;++r)this._data[i+r]=e[r];this._tail=i+t}pop(){const e=this._head;if(e<this._tail){const t=this._data[e];return this._head=e+1,t}}get empty(){return this._head>=this._tail}get full(){return this._tail>=this._data.length}}function gt(e,t){!e.leaf||e.level<ge||yt(e,(e=>{t&&mt(e);const i=ft(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ft(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}}))}function mt(e){if(e.hasPendingUpdate(ke.SPLIT))return;let t=e.parent;for(;t?.resetPendingUpdate(ke.MERGE);)t=t.parent;e.resetPendingUpdate(ke.MERGE),e.leaf&&e.setPendingUpdate(ke.SPLIT),e.level<ge||yt(e,(e=>{mt(e)}))}function _t(e){e.level<ge||yt(e,(e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ft(t));)t=t.parent}}))}function ft(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function yt(e,t){if(e.level<ge)return;const i=e.level-ge,r=e.lij[1]>>ge,s=e.lij[2]>>ge,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(ve[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{nt 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/4.34/esri/copyright.txt for details.
4
4
  */
5
- import"../../../core/has.js";import{disposeMaybe as e,releaseMaybe as t}from"../../../core/maybe.js";import{set as r,copy as s}from"../../../core/libs/gl-matrix-2/math/vec2.js";import{ZEROS as o}from"../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{fromValues as i}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{isBaseLayer as a,isGroupLayer as n,isReferenceLayer as c}from"../../../layers/support/layerUtils.js";import{isLayerViewWithFlowRenderer as u}from"../support/flowUtils.js";import{BlendLayersPassParameters as l}from"./BlendLayersTechnique.js";import{TextureUpdate as p}from"./interfaces.js";import{LayerClass as m}from"./LayerClass.js";import{NeighborIndex as d}from"./NeighborIndex.js";import{isImageWithType as h}from"./TerrainData.js";import{isBlendableLayerView as f,isVectorTileLayerView as _,isVectorTileRenderInfo as T,isImageryTileRenderInfo as x,isImageSourceRenderInfo as b,isTextureTileRenderInfo as y,isVectorTilePerLayerInfo as g}from"./terrainUtils.js";import{ActivationTime as I}from"./TextureFader.js";import{TextureReference as w}from"./TextureReference.js";import{TileCompositor as k}from"./TileCompositor.js";import{TileRenderInfo as A}from"./TileRenderInfo.js";import{TileTexture as P,getCacheKey as E}from"./TileTexture.js";import{TileUpdate as O}from"./TileUpdate.js";import{fallsWithinLayerView as j}from"./tileUtils.js";import{blendModeFromString as C}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{BlendLayersOutput as M}from"../webgl-engine/core/shaderLibrary/terrain/BlendLayersOutput.js";import{createEmptyTexture as L}from"../webgl-engine/lib/glUtil3D.js";import{isCompressible as R}from"../../support/TextureCompressionWorkerHandle.js";import{TextureSamplingMode as N,TextureWrapMode as D,PixelFormat as B}from"../../webgl/enums.js";import{Texture as U}from"../../webgl/Texture.js";import{TextureDescriptor as S}from"../../webgl/TextureDescriptor.js";class G{constructor(e,t,r,s,o,i){this.start=e,this.end=t,this.blendMode=r,this.opacity=s,this.output=o,this.baseOpacity=i}}class F{constructor(e,t,r,s,o){this._rctx=e,this.tileSize=t,this._techniques=r,this._cache=s,this._compressionTracker=o,this._passParameters=new l,this._backgroundColor=null,this._maxAnisotropy=this._rctx.parameters.maxMaxAnisotropy,this._compositor=new k(this._rctx,this._techniques)}dispose(){this._compositor=e(this._compositor),this._backgroundTexture=t(this._backgroundTexture)}get backgroundIsGrid(){return null==this._backgroundColor}get backgroundColor(){return this._backgroundColor}updateHeading(e){this._compositor?.updateHeading(e)}updateTileTexture(e,t){if(!e.renderData)return;const r=e.surface,s=r.baseOpacity;let o=0,i=0,l=this.tileSize,d=!1,h=!1;const T=r.view.state.contentPixelRatio;let x=!1;V.clear(),X.length=0;const b=e.layerInfo[m.MAP];let y=0,g=null;for(;y<b.length;y++){const t=r.layerViewByIndex(y,m.MAP),p=t.layer,I=!j(e,t),w=p.opacity,k=t.fullOpacity;if(h=h||a(p),u(t))continue;if(f(t)){let e="normal"!==t.layer.blendMode;if(n(p.parent)){const t=p.parent.uid;null!=t&&""!==t&&(e=q(p.parent)||e)}e&&(x=e,d=!1)}if((I||0===w)&&!x){b[y].pendingUpdates&=~(O.TEXTURE_NOFADING&O.TEXTURE_FADING);continue}++i;const A=_(t),P=v(e,y,A);if(P){if(b[y].pendingUpdates&=~(O.TEXTURE_NOFADING&O.TEXTURE_FADING),n(p.parent)){const e=p.parent.uid;null!=e&&""!==e&&z(p.parent,y)}A?l=Math.max(l,this.tileSize*T):1===s&&1===k&&(t.isOpaque||this._dataToTexture(P,c(p))&&P.sourceLayerInfo.data.descriptor.isOpaque)&&(d=!0),++o,null===g&&(g=y)}}const I=l/this.tileSize;0!==o&&null!==g?1===o&&!x&&this._useLayerTexture(e,g)||this._composeLayers(e,t,y-1,h,l,I,!d||x,V,x):this._useBackgroundTexture(e,i,t!==p.FADING)}setBackground(e){this._backgroundColor!==e&&(this._backgroundColor=e,this._backgroundTexture&&this._drawBackgroundTexture(this._backgroundTexture))}_ensureBackgroundTexture(){return null==this._backgroundTexture&&(this._backgroundTexture=this._buildTexture(this.tileSize,!1),this._drawBackgroundTexture(this._backgroundTexture)),this._backgroundTexture}_drawBackgroundTexture(e){this._compositor.bind(this.tileSize),this._passParameters.offset=o,this._passParameters.scale=1,this._passParameters.opacity=1,this.backgroundColor&&(this._passParameters.backgroundColor=this.backgroundColor),this._compositor.drawBackground(this._passParameters,null!=this.backgroundColor),this._compositor.copyFBOToTexture(e),this._compositor.unbind()}_useBackgroundTexture(e,t,r){const s=e.renderData,o=!r&&null!=s.textureReference&&(e.surface.view.layerViewManager.updating||t>0)?I.Delayed:I.Immediate,i=this._ensureBackgroundTexture();s.setTextureReference(new w(i,p.FADING,J,e.surface.baseOpacity,0,1),o)}_useLayerTexture(e,t){const r=e.surface.layerViewByIndex(t,m.MAP),s=a(r.layer),o=s?e.surface.baseOpacity:1,n=s?1:e.surface.baseOpacity,u=r.fullOpacity,l=v(e,t,!1);return!!this._dataToTexture(l,c(r.layer))&&(e.renderData.setTextureReference(new w(l.sourceLayerInfo.data,p.FADING,i(l.offset[0],l.offset[1],l.scale,l.scale),o,n,u)),!0)}_composeLayers(e,t,r,s,i,n,l,p,d){this._compositor.ensureBuffer(i);const h=e.surface.baseOpacity;let b=!1,y=N.LINEAR_MIPMAP_LINEAR,g=!1,I=0;for(let w=r;w>=0;w--){const t=e.surface.layerViewByIndex(w,m.MAP),r=t.layer,k=_(t),A=v(e,w,k),P=r.opacity,E=!j(e,t);if(!A||(0===P||E)&&!d)continue;if(u(t))continue;const O=!a(r)&&!b;O&&(b=!0);let L=!1;p.forEach((e=>{e.start===w&&(e.output=s?M.Composite:l&&O?this.backgroundIsGrid?M.GridComposite:M.ColorComposite:M.Composite,e.baseOpacity=O?h:1,X.push(e),this._compositor.openGroup(i),L=!0)}));const R=0===I,D=L?M.GroupBackgroundComposite:l&&R?this.backgroundIsGrid?M.GridComposite:M.ColorComposite:M.Composite,B=C[f(t)?t.layer.blendMode:"normal"];for(this._passParameters.baseOpacity=O&&!L&&h<1?h:1,this._passParameters.opacity=P,T(A)?g=this._compositor.drawVectorData(this._passParameters,D,i,B,A,n,this.tileSize,g):x(A)?(this._compositor.drawRasterData(this._passParameters,D,i,B,A),H(A)&&(y=N.NEAREST)):this._dataToTexture(A,c(r))&&(this._passParameters.texture=A.sourceLayerInfo.data.texture,this._passParameters.offset=A.offset,this._passParameters.scale=A.scale,this._compositor.drawImageData(this._passParameters,D,i,B));X.length>0&&X[X.length-1].end===w;){const e=X.pop();this._passParameters.baseOpacity=e.baseOpacity,this._passParameters.opacity=e.opacity,this._passParameters.offset=o,this._passParameters.scale=1,this._compositor.drawGroup(this._passParameters,e.output,i,C[e.blendMode])}I++}const k=e.renderData,A=d||b&&h<1,P=k.ensureTexture(i,A,t,(()=>this._buildTexture(i,A,y)));this._compositor.copyFBOToTexture(P),this._compositor.unbind(),k.setTextureReference(new w(P,t,J,b?1:h,0,1))}_dataToTexture(e,t){if(b(e)){const r=e.sourceLayerInfo,s=1===e.scale&&!t;r.data=this._buildTexture(r.data,!0,s,e.tile.onCompressionFinished),e.tile.setMemoryDirty()}return y(e)}_buildTexture(e,t,r=N.LINEAR_MIPMAP_LINEAR,s=()=>{}){if(null==e)return null;const o=new S;o.wrapMode=D.CLAMP_TO_EDGE,o.samplingMode="boolean"==typeof r?N.LINEAR_MIPMAP_LINEAR:r,o.maxAnisotropy=this._maxAnisotropy,o.preMultiplyAlpha=!0,o.flipped=!0,o.hasMipmap=!0,t||(o.pixelFormat=B.RGB);const i=this._rctx,a="boolean"==typeof r&&r;let n;if("number"==typeof e)o.width=o.height=e,n=this._buildTileTexture(o);else if(h(e))o.isOpaque=e.isOpaque,o.isOpaque&&(o.pixelFormat=B.RGB),o.width=e.element.width,o.height=e.element.height,n=this._buildTileTexture(o,a,s,e.element);else try{o.width=e.width,o.height=e.height,n=this._buildTileTexture(o,a,s,e)}catch(u){n=new P(L(i)),console.warn("TileRenderer: failed to execute 'texImage2D', cross-origin image may not be loaded.")}const c=i.bindTexture(n.texture,U.TEXTURE_UNIT_FOR_UPDATES);return n.generateMipmap(),i.bindTexture(c,U.TEXTURE_UNIT_FOR_UPDATES),n}_buildTileTexture(e,t=!1,r=()=>{},s){const o=this._cache.pop(E(e,!1))??this._cache.pop(E(e,!0));if(t&&=R(s,e),o)return o.retain(),t?o.texture.enableCompression({compressionTracker:this._compressionTracker,compressionCallback:r}):o.texture.disableCompression(),o.texture.setData(s),o;e.compress=t?{compressionTracker:this._compressionTracker,compressionCallback:r}:void 0;const i=new U(this._rctx,e,s);return new P(i,this._cache)}get test(){}}function v(e,t,o){W.layerIndex=t,W.vtlNeighborInfos.clear();const i=e.layerInfo[m.MAP][t];if(r(W.offset,0,0),W.tile=e,W.scale=1,W.sourceLod=e.lij,W.sourceLayerInfo=i,W.isVTLBackground=o,i.data)return o&&e.forEachLoadedNeighbor(((r,s)=>{if(r.level!==e.level)return;const o=r.layerInfo[m.MAP][t];if(!g(o)||i.data===o.data)return;const a=W.vtlNeighborInfos.pushNew();a.offset=K[s],a.sourceLod=r.lij,a.sourceLayerInfo=o})),W;const a=i.upsampleInfo,n=a?.tile?.layerInfo[m.MAP][t];return n&&a.tile?(W.tile=a.tile,s(W.offset,a.offset),W.scale=a.scale,W.sourceLod=a.tile.lij,W.sourceLayerInfo=n,W):o?W:null}function H(e){const t=e.sourceLayerInfo.data;return!!t.source&&"nearest"===t.interpolation}function q(e){let t="normal"!==e.blendMode;return n(e.parent)&&(t=q(e.parent)||t),t}function z(e,t){n(e.parent)&&z(e.parent,t);const r=e.uid;if(null!=r&&""!==r){const s=V.get(r);s?s.start=t:V.set(r,new G(t,t,e.blendMode,e.opacity,M.Composite,1))}}const V=new Map,X=new Array,W=new A,J=i(0,0,1,1),K=new Array;K[d.NORTH]=[0,-1],K[d.NORTH_EAST]=[-1,-1],K[d.EAST]=[-1,0],K[d.SOUTH_EAST]=[-1,1],K[d.SOUTH]=[0,1],K[d.SOUTH_WEST]=[1,1],K[d.WEST]=[1,0],K[d.NORTH_WEST]=[1,-1];export{G as GroupInfo,F as TileRenderer};
5
+ import"../../../core/has.js";import{disposeMaybe as e,releaseMaybe as t}from"../../../core/maybe.js";import{set as r,copy as s}from"../../../core/libs/gl-matrix-2/math/vec2.js";import{ZEROS as o}from"../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{fromValues as i}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{isBaseLayer as a,isGroupLayer as n,isReferenceLayer as c}from"../../../layers/support/layerUtils.js";import{isLayerViewWithFlowRenderer as u}from"../support/flowUtils.js";import{BlendLayersPassParameters as l}from"./BlendLayersTechnique.js";import{TextureUpdate as p}from"./interfaces.js";import{LayerClass as m}from"./LayerClass.js";import{NeighborIndex as h}from"./NeighborIndex.js";import{isImageWithType as d}from"./TerrainData.js";import{isBlendableLayerView as f,isVectorTileLayerView as _,isVectorTileRenderInfo as T,isImageryTileRenderInfo as x,isImageSourceRenderInfo as b,isTextureTileRenderInfo as y,isVectorTilePerLayerInfo as g}from"./terrainUtils.js";import{ActivationTime as I}from"./TextureFader.js";import{TextureReference as w}from"./TextureReference.js";import{TileCompositor as k}from"./TileCompositor.js";import{TileRenderInfo as A}from"./TileRenderInfo.js";import{TileTexture as P,getCacheKey as E}from"./TileTexture.js";import{TileUpdate as O}from"./TileUpdate.js";import{fallsWithinLayerView as j}from"./tileUtils.js";import{blendModeFromString as C}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{BlendLayersOutput as L}from"../webgl-engine/core/shaderLibrary/terrain/BlendLayersOutput.js";import{createEmptyTexture as M}from"../webgl-engine/lib/glUtil3D.js";import{isCompressible as R}from"../../support/TextureCompressionWorkerHandle.js";import{TextureSamplingMode as N,TextureWrapMode as D,PixelFormat as B}from"../../webgl/enums.js";import{Texture as U}from"../../webgl/Texture.js";import{TextureDescriptor as S}from"../../webgl/TextureDescriptor.js";class G{constructor(e,t,r,s,o,i){this.start=e,this.end=t,this.blendMode=r,this.opacity=s,this.output=o,this.baseOpacity=i}}class F{constructor(e,t,r,s,o){this._rctx=e,this.tileSize=t,this._techniques=r,this._cache=s,this._compressionTracker=o,this._passParameters=new l,this._backgroundColor=null,this._maxAnisotropy=this._rctx.parameters.maxMaxAnisotropy,this._compositor=new k(this._rctx,this._techniques)}dispose(){this._compositor=e(this._compositor),this._backgroundTexture=t(this._backgroundTexture)}get backgroundIsGrid(){return null==this._backgroundColor}get backgroundColor(){return this._backgroundColor}updateHeading(e){this._compositor?.updateHeading(e)}updateTileTexture(e,t){if(!e.renderData)return;const r=e.surface,s=r.baseOpacity;let o=0,i=0,l=this.tileSize,h=!1,d=!1;const T=r.view.state.contentPixelRatio;let x=!1;V.clear(),X.length=0;const b=e.layerInfo[m.MAP];let y=0,g=null;for(;y<b.length;y++){const t=r.layerViewByIndex(y,m.MAP),p=t.layer,I=!j(e,t),w=p.opacity,k=t.fullOpacity;if(d=d||a(p),u(t))continue;if(f(t)){let e="normal"!==t.layer.blendMode;if(n(p.parent)){const t=p.parent.uid;null!=t&&""!==t&&(e=q(p.parent)||e)}e&&(x=e,h=!1)}if((I||0===w)&&!x){b[y].pendingUpdates&=~(O.TEXTURE_NOFADING&O.TEXTURE_FADING);continue}++i;const A=_(t),P=v(e,y,A);if(P){if(b[y].pendingUpdates&=~(O.TEXTURE_NOFADING&O.TEXTURE_FADING),n(p.parent)){const e=p.parent.uid;null!=e&&""!==e&&z(p.parent,y)}A?l=Math.max(l,this.tileSize*T):1===s&&1===k&&(t.isOpaque||this._dataToTexture(P,c(p))&&P.sourceLayerInfo.data.descriptor.isOpaque)&&(h=!0),++o,null===g&&(g=y)}}const I=l/this.tileSize;0!==o&&null!==g?1===o&&!x&&this._useLayerTexture(e,g)||this._composeLayers(e,t,y-1,d,l,I,!h||x,V,x):this._useBackgroundTexture(e,i,t!==p.FADING)}setBackground(e){this._backgroundColor!==e&&(this._backgroundColor=e,this._backgroundTexture&&this._drawBackgroundTexture(this._backgroundTexture))}_ensureBackgroundTexture(){return null==this._backgroundTexture&&(this._backgroundTexture=this._buildTexture(this.tileSize,!1),this._drawBackgroundTexture(this._backgroundTexture)),this._backgroundTexture}_drawBackgroundTexture(e){this._compositor.bind(this.tileSize),this._passParameters.offset=o,this._passParameters.scale=1,this._passParameters.opacity=1,this.backgroundColor&&(this._passParameters.backgroundColor=this.backgroundColor),this._compositor.drawBackground(this._passParameters,null!=this.backgroundColor),this._compositor.copyFBOToTexture(e),this._compositor.unbind()}_useBackgroundTexture(e,t,r){const s=e.renderData,o=!r&&null!=s.textureReference&&(e.surface.view.layerViewManager.updating||t>0)?I.Delayed:I.Immediate,i=this._ensureBackgroundTexture();s.setTextureReference(new w(i,p.FADING,J,e.surface.baseOpacity,0,1),o)}_useLayerTexture(e,t){const r=e.surface.layerViewByIndex(t,m.MAP),s=a(r.layer),o=s?e.surface.baseOpacity:1,n=s?1:e.surface.baseOpacity,u=r.fullOpacity,l=v(e,t,!1);return!!this._dataToTexture(l,c(r.layer))&&(e.renderData.setTextureReference(new w(l.sourceLayerInfo.data,p.FADING,i(l.offset[0],l.offset[1],l.scale,l.scale),o,n,u)),!0)}_composeLayers(e,t,r,s,i,n,l,p,h){this._compositor.ensureBuffer(i);const d=e.surface.baseOpacity;let b=!1,y=N.LINEAR_MIPMAP_LINEAR,g=!1,I=0;for(let w=r;w>=0;w--){const t=e.surface.layerViewByIndex(w,m.MAP),r=t.layer,k=_(t),A=v(e,w,k),P=r.opacity,E=!j(e,t);if(!A||(0===P||E)&&!h)continue;if(u(t))continue;const O=!a(r)&&!b;O&&(b=!0);let M=!1;p.forEach((e=>{e.start===w&&(e.output=s?L.Composite:l&&O?this.backgroundIsGrid?L.GridComposite:L.ColorComposite:L.Composite,e.baseOpacity=O?d:1,X.push(e),this._compositor.openGroup(i),M=!0)}));const R=0===I,D=M?L.GroupBackgroundComposite:l&&R?this.backgroundIsGrid?L.GridComposite:L.ColorComposite:L.Composite,B=C[f(t)?t.layer.blendMode:"normal"];for(this._passParameters.baseOpacity=O&&!M&&d<1?d:1,this._passParameters.opacity=P,T(A)?g=this._compositor.drawVectorData(this._passParameters,D,i,B,A,n,this.tileSize,g):x(A)?(this._compositor.drawRasterData(this._passParameters,D,i,B,A),H(A)&&(y=N.NEAREST)):this._dataToTexture(A,c(r))&&(this._passParameters.texture=A.sourceLayerInfo.data.texture,this._passParameters.offset=A.offset,this._passParameters.scale=A.scale,this._compositor.drawImageData(this._passParameters,D,i,B));X.length>0&&X[X.length-1].end===w;){const e=X.pop();this._passParameters.baseOpacity=e.baseOpacity,this._passParameters.opacity=e.opacity,this._passParameters.offset=o,this._passParameters.scale=1,this._compositor.drawGroup(this._passParameters,e.output,i,C[e.blendMode])}I++}const k=e.renderData,A=h||b&&d<1,P=k.ensureTexture(i,A,t,(()=>this._buildTexture(i,A,y)));this._compositor.copyFBOToTexture(P),this._compositor.unbind(),k.setTextureReference(new w(P,t,J,b?1:d,0,1))}_dataToTexture(e,t){if(b(e)){const r=e.sourceLayerInfo,s=1===e.scale&&!t;r.data=this._buildTexture(r.data,!0,s,e.tile.onCompressionFinished),e.tile.setMemoryDirty()}return y(e)}_buildTexture(e,t,r=N.LINEAR_MIPMAP_LINEAR,s=()=>{}){if(null==e)return null;const o=new S;o.wrapMode=D.CLAMP_TO_EDGE,o.samplingMode="boolean"==typeof r?N.LINEAR_MIPMAP_LINEAR:r,o.maxAnisotropy=this._maxAnisotropy,o.preMultiplyAlpha=!0,o.flipped=!0,o.hasMipmap=!0,t||(o.pixelFormat=B.RGB);const i=this._rctx,a="boolean"==typeof r&&r;let n;if("number"==typeof e)o.width=o.height=e,n=this._buildTileTexture(o);else if(d(e))o.isOpaque=e.isOpaque,o.isOpaque&&(o.pixelFormat=B.RGB),o.width=e.element.width,o.height=e.element.height,n=this._buildTileTexture(o,a,s,e.element);else try{o.width=e.width,o.height=e.height,n=this._buildTileTexture(o,a,s,e)}catch(u){n=new P(M(i)),console.warn("TileRenderer: failed to execute 'texImage2D', cross-origin image may not be loaded.")}const c=i.bindTexture(n.texture,U.TEXTURE_UNIT_FOR_UPDATES);return n.generateMipmap(),i.bindTexture(c,U.TEXTURE_UNIT_FOR_UPDATES),n}_buildTileTexture(e,t=!1,r=()=>{},s){const o=this._cache.pop(E(e,!1))??this._cache.pop(E(e,!0));if(t&&=R(s,e),o)return o.retain(),t?o.texture.enableCompression({compressionTracker:this._compressionTracker,compressionCallback:r}):o.texture.disableCompression(),o.texture.setData(s),o;e.compress=t?{compressionTracker:this._compressionTracker,compressionCallback:r}:void 0;const i=new U(this._rctx,e,s);return new P(i,this._cache)}get test(){}}function v(e,t,o){W.layerIndex=t,W.vtlNeighborInfos.clear();const i=e.layerInfo[m.MAP][t];if(r(W.offset,0,0),W.tile=e,W.scale=1,W.sourceLod=e.lij,W.sourceLayerInfo=i,W.isVTLBackground=o,i.data)return o&&e.forEachLoadedNeighbor(((r,s)=>{if(r.level!==e.level)return;const o=r.layerInfo[m.MAP][t];if(!g(o)||i.data===o.data)return;const a=W.vtlNeighborInfos.pushNew();a.offset=K[s],a.sourceLod=r.lij,a.sourceLayerInfo=o})),W;const a=i.upsampleInfo,n=a?.tile?.layerInfo[m.MAP][t];return n&&a.tile?(W.tile=a.tile,s(W.offset,a.offset),W.scale=a.scale,W.sourceLod=a.tile.lij,W.sourceLayerInfo=n,W):o?W:null}function H(e){const t=e.sourceLayerInfo.data;return!!t.source&&"nearest"===t.interpolation}function q(e){let t="normal"!==e.blendMode;return n(e.parent)&&(t=q(e.parent)||t),t}function z(e,t){n(e.parent)&&z(e.parent,t);const r=e.uid;if(null!=r&&""!==r){const s=V.get(r);s?s.start=t:V.set(r,new G(t,t,e.blendMode,e.opacity,L.Composite,1))}}const V=new Map,X=new Array,W=new A,J=i(0,0,1,1),K=new Array;function Q(){W.sourceLayerInfo=null,W.tile=null,W.vtlNeighborInfos.prune()}K[h.NORTH]=[0,-1],K[h.NORTH_EAST]=[-1,-1],K[h.EAST]=[-1,0],K[h.SOUTH_EAST]=[-1,1],K[h.SOUTH]=[0,1],K[h.SOUTH_WEST]=[1,1],K[h.WEST]=[1,0],K[h.NORTH_WEST]=[1,-1];export{G as GroupInfo,F as TileRenderer,Q as cleanupTileRenderer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import t from"../../../../core/ObjectPool.js";import e from"../../../../core/PooledArray.js";import{c as n,m as o,s as i,g as r,f as s}from"../../../../chunks/vec32.js";import{fromValues as h,create as a}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{intersectsSphere as l}from"../../../../geometry/support/frustum.js";import{wrap as d}from"../../../../geometry/support/ray.js";import{e as u,g as c,k as f,c as m,a as _}from"../../../../chunks/sphere.js";import{rayBoxTest as p}from"./Util.js";class b{get bounds(){return this._root.bounds}get halfSize(){return this._root.halfSize}get root(){return this._root.node}get maximumObjectsPerNode(){return this._maximumObjectsPerNode}get maximumDepth(){return this._maximumDepth}get objectCount(){return this._objectCount}constructor(t,e){this.objectToBoundingSphere=t,this._maximumObjectsPerNode=10,this._maximumDepth=20,this._degenerateObjects=new Set,this._root=new g,this._objectCount=0,e&&(void 0!==e.maximumObjectsPerNode&&(this._maximumObjectsPerNode=e.maximumObjectsPerNode),void 0!==e.maximumDepth&&(this._maximumDepth=e.maximumDepth))}destroy(){this._degenerateObjects.clear(),g.clearPool(),y[0]=null,K.prune(),Q.prune()}add(t){const e=Array.from(t);this._grow(e);const n=g.acquire();for(const o of e)++this._objectCount,this._isDegenerate(o)?this._degenerateObjects.add(o):(n.init(this._root),this._add(o,n));g.release(n)}remove(t,e=null){this._objectCount-=t.length;const n=g.acquire();for(const o of t){const t=e??u(this.objectToBoundingSphere(o),J);C(t[3])?(n.init(this._root),O(o,t,n)):this._degenerateObjects.delete(o)}g.release(n),this._shrink()}update(t,e){if(!C(e[3])&&this._isDegenerate(t))return;const n=k(t);this.remove(n,e),this.add(n)}forEachAlongRay(t,e,n){const o=d(t,e);S(this._root,(t=>{if(!T(o,t))return!1;const e=t.node;return e.terminals.forAll((t=>{this._intersectsObject(o,t)&&n(t)})),null!==e.residents&&e.residents.forAll((t=>{this._intersectsObject(o,t)&&n(t)})),!0}))}forEachAlongRayWithVerticalOffset(t,e,n,o){const i=d(t,e);S(this._root,(t=>{if(!z(i,t,o))return!1;const e=t.node;return e.terminals.forAll((t=>{this._intersectsObjectWithOffset(i,t,o)&&n(t)})),null!==e.residents&&e.residents.forAll((t=>{this._intersectsObjectWithOffset(i,t,o)&&n(t)})),!0}))}forEach(t){S(this._root,(e=>{const n=e.node;return n.terminals.forAll(t),null!==n.residents&&n.residents.forAll(t),!0})),this._degenerateObjects.forEach(t)}forEachDegenerateObject(t){this._degenerateObjects.forEach(t)}findClosest(t,e,n,o=()=>!0,i=1/0){let h=1/0,a=1/0,d=null;const u=F(t,e),c=r=>{if(--i,!o(r))return;const s=this.objectToBoundingSphere(r);if(!l(n,s))return;const u=v(t,e,_(s)),c=u-s[3],f=u+s[3];c<h&&(h=c,a=f,d=r)};return j(this._root,(o=>{if(i<=0||!l(n,o.bounds))return!1;r(I,u,o.halfSize),s(I,I,_(o.bounds));if(v(t,e,I)>a)return!1;const h=o.node;return h.terminals.forAll((t=>c(t))),null!==h.residents&&h.residents.forAll((t=>c(t))),!0}),t,e),d}forEachInDepthRange(t,e,n,o,i,h,a){let d=-1/0,u=1/0;const c={setRange:t=>{n===b.DepthOrder.FRONT_TO_BACK?(d=Math.max(d,t.near),u=Math.min(u,t.far)):(d=Math.max(d,-t.far),u=Math.min(u,-t.near))}};c.setRange(o);const f=v(e,n,t),m=F(e,n),p=F(e,-n),g=t=>{if(!a(t))return;const o=this.objectToBoundingSphere(t),r=_(o),s=v(e,n,r)-f,m=s-o[3],p=s+o[3];m>u||p<d||!l(h,o)||i(t,c)};j(this._root,(t=>{if(!l(h,t.bounds))return!1;r(I,m,t.halfSize),s(I,I,_(t.bounds));if(v(e,n,I)-f>u)return!1;r(I,p,t.halfSize),s(I,I,_(t.bounds));if(v(e,n,I)-f<d)return!1;const o=t.node;return o.terminals.forAll((t=>g(t))),null!==o.residents&&o.residents.forAll((t=>g(t))),!0}),e,n)}forEachNode(t){S(this._root,(e=>t(e.node,e.bounds,e.halfSize,e.depth)))}forEachNeighbor(t,e){const n=c(e),o=_(e),r=e=>{const r=this.objectToBoundingSphere(e),s=c(r),h=n+s;return!(i(_(r),o)-h*h<=0)||t(e)};let s=!0;const h=t=>{s&&(s=r(t))};S(this._root,(t=>{const e=c(t.bounds),r=n+e;if(i(_(t.bounds),o)-r*r>0)return!1;const a=t.node;return a.terminals.forAll(h),s&&null!==a.residents&&a.residents.forAll(h),s})),s&&this.forEachDegenerateObject(h)}_intersectsObject(t,e){const n=this.objectToBoundingSphere(e);return!(n[3]>0)||f(n,t)}_intersectsObjectWithOffset(t,e,n){const o=this.objectToBoundingSphere(e);return!(o[3]>0)||f(n.applyToBoundingSphere(o),t)}_add(t,e){e.advanceTo(this.objectToBoundingSphere(t))?e.node.terminals.push(t):(e.node.residents.push(t),e.node.residents.length>this._maximumObjectsPerNode&&e.depth<this._maximumDepth&&this._split(e))}_split(t){const e=t.node.residents;t.node.residents=null;for(let n=0;n<e.length;n++){const o=g.acquire().init(t);this._add(e.at(n),o),g.release(o)}}_grow(t){if(D(t,(t=>this.objectToBoundingSphere(t)),W),C(W[3])&&!this._fitsInsideTree(W))if(N(this._root.node))u(W,this._root.bounds),this._root.halfSize=1.25*this._root.bounds[3],this._root.updateBoundsRadiusFromHalfSize();else{const t=this._rootBoundsForRootAsSubNode(W);this._placingRootViolatesMaxDepth(t)?this._rebuildTree(W,t):this._growRootAsSubNode(t),g.release(t)}}_rebuildTree(t,e){n(_(V),_(e.bounds)),V[3]=e.halfSize,D([t,V],(t=>t),G);const o=g.acquire().init(this._root);this._root.initFrom(null,G,G[3]),this._root.increaseHalfSize(1.25),S(o,(t=>(this.add(t.node.terminals.data),null!==t.node.residents&&this.add(t.node.residents.data),!0))),g.release(o)}_placingRootViolatesMaxDepth(t){const e=Math.log(t.halfSize/this._root.halfSize)*Math.LOG2E;let n=0;return S(this._root,(t=>(n=Math.max(n,t.depth),n+e<=this._maximumDepth))),n+e>this._maximumDepth}_rootBoundsForRootAsSubNode(t){const e=t[3],n=t;let o=-1/0;const i=this._root.bounds,r=this._root.halfSize;for(let h=0;h<3;h++){const t=i[h]-r-(n[h]-e),s=n[h]+e-(i[h]+r),a=Math.max(0,Math.ceil(t/(2*r))),l=Math.max(0,Math.ceil(s/(2*r)))+1,d=2**Math.ceil(Math.log(a+l)*Math.LOG2E);o=Math.max(o,d),U[h].min=a,U[h].max=l}for(let h=0;h<3;h++){let t=U[h].min,e=U[h].max;const n=(o-(t+e))/2;t+=Math.ceil(n),e+=Math.floor(n);const s=i[h]-r-t*r*2;q[h]=s+(e+t)*r}const s=o*r;return q[3]=s*w,g.acquire().initFrom(null,q,s,0)}_growRootAsSubNode(t){const e=this._root.node;n(_(W),_(this._root.bounds)),W[3]=this._root.halfSize,this._root.init(t),t.advanceTo(W,null,!0),t.node.children=e.children,t.node.residents=e.residents,t.node.terminals=e.terminals}_shrink(){for(;;){const t=this._findShrinkIndex();if(-1===t)break;this._root.advance(t),this._root.depth=0}}_findShrinkIndex(){if(0!==this._root.node.terminals.length||this._root.isLeaf())return-1;let t=null;const e=this._root.node.children;let n=0,o=0;for(;o<e.length&&null==t;)n=o++,t=e[n];for(;o<e.length;)if(e[o++])return-1;return n}_isDegenerate(t){return!C(this.objectToBoundingSphere(t)[3])}_fitsInsideTree(t){const e=this._root.bounds,n=this._root.halfSize;return t[3]<=n&&t[0]>=e[0]-n&&t[0]<=e[0]+n&&t[1]>=e[1]-n&&t[1]<=e[1]+n&&t[2]>=e[2]-n&&t[2]<=e[2]+n}toJSON(){const{maximumDepth:t,maximumObjectsPerNode:e,_objectCount:n}=this,o=this._nodeToJSON(this._root.node);return{maximumDepth:t,maximumObjectsPerNode:e,objectCount:n,root:{bounds:this._root.bounds,halfSize:this._root.halfSize,depth:this._root.depth,node:o}}}_nodeToJSON(t){const e=t.children.map((t=>t?this._nodeToJSON(t):null)),n=t.residents?.map((t=>this.objectToBoundingSphere(t))),o=t.terminals?.map((t=>this.objectToBoundingSphere(t)));return{children:e,residents:n,terminals:o}}static fromJSON(t){const e=new b((t=>t),{maximumDepth:t.maximumDepth,maximumObjectsPerNode:t.maximumObjectsPerNode});return e._objectCount=t.objectCount,e._root.initFrom(t.root.node,t.root.bounds,t.root.halfSize,t.root.depth),e}}class g{constructor(){this.bounds=m(),this.halfSize=0,this.initFrom(null,null,0,0)}init(t){return this.initFrom(t.node,t.bounds,t.halfSize,t.depth)}initFrom(t,e,n,o=this.depth){return this.node=null!=t?t:g.createEmptyNode(),e&&u(e,this.bounds),this.halfSize=n,this.depth=o,this}increaseHalfSize(t){this.halfSize*=t,this.updateBoundsRadiusFromHalfSize()}updateBoundsRadiusFromHalfSize(){this.bounds[3]=this.halfSize*w}advance(t){let e=this.node.children[t];e||(e=g.createEmptyNode(),this.node.children[t]=e),this.node=e,this.halfSize/=2,this.depth++;const n=E[t];return this.bounds[0]+=n[0]*this.halfSize,this.bounds[1]+=n[1]*this.halfSize,this.bounds[2]+=n[2]*this.halfSize,this.updateBoundsRadiusFromHalfSize(),this}advanceTo(t,e,n=!1){for(;;){if(this.isTerminalFor(t))return e&&e(this,-1),!0;if(this.isLeaf()){if(!n)return e&&e(this,-1),!1;this.node.residents=null}const o=this._childIndex(t);e&&e(this,o),this.advance(o)}}isLeaf(){return null!=this.node.residents}isTerminalFor(t){return t[3]>this.halfSize/2}_childIndex(t){const e=this.bounds;return(e[0]<t[0]?1:0)+(e[1]<t[1]?2:0)+(e[2]<t[2]?4:0)}static createEmptyNode(){return{children:[null,null,null,null,null,null,null,null],terminals:new e({shrink:!0}),residents:new e({shrink:!0})}}static{this._pool=new t(g)}static acquire(){return g._pool.acquire()}static release(t){g._pool.release(t)}static clearPool(){g._pool.prune()}}function S(t,e){let n=g.acquire().init(t);const o=[n];for(;0!==o.length;){if(n=o.pop(),e(n)&&!n.isLeaf())for(let t=0;t<n.node.children.length;t++){n.node.children[t]&&o.push(g.acquire().init(n).advance(t))}g.release(n)}}function j(t,e,n,o=b.DepthOrder.FRONT_TO_BACK){let i=g.acquire().init(t);const r=[i];for(R(n,o,X);0!==r.length;){if(i=r.pop(),e(i)&&!i.isLeaf())for(let t=7;t>=0;--t){const e=X[t];i.node.children[e]&&r.push(g.acquire().init(i).advance(e))}g.release(i)}}function O(t,e,n){K.clear();const o=n.advanceTo(e,((t,e)=>{K.push(t.node),K.push(e)}))?n.node.terminals:n.node.residents;if(o.removeUnordered(t),0===o.length)for(let i=K.length-2;i>=0;i-=2){if(!x(K.data[i],K.data[i+1]))break}}function x(t,n){return n>=0&&(t.children[n]=null),!!N(t)&&(null===t.residents&&(t.residents=new e({shrink:!0})),!0)}function T(t,e){return B(_(e.bounds),2*-e.halfSize,L),B(_(e.bounds),2*e.halfSize,H),p(t.origin,t.direction,L,H)}function z(t,e,n){return B(_(e.bounds),2*-e.halfSize,L),B(_(e.bounds),2*e.halfSize,H),n.applyToMinMax(L,H),p(t.origin,t.direction,L,H)}function N(t){if(0!==t.terminals.length)return!1;if(null!==t.residents)return 0===t.residents.length;for(let e=0;e<t.children.length;e++)if(t.children[e])return!1;return!0}function M(t,e){t[0]=Math.min(t[0],e[0]-e[3]),t[1]=Math.min(t[1],e[1]-e[3]),t[2]=Math.min(t[2],e[2]-e[3])}function A(t,e){t[0]=Math.max(t[0],e[0]+e[3]),t[1]=Math.max(t[1],e[1]+e[3]),t[2]=Math.max(t[2],e[2]+e[3])}function B(t,e,n){n[0]=t[0]+e,n[1]=t[1]+e,n[2]=t[2]+e}function D(t,e,n){L[0]=1/0,L[1]=1/0,L[2]=1/0,H[0]=-1/0,H[1]=-1/0,H[2]=-1/0;for(const o of t){const t=e(o);C(t[3])&&(M(L,t),A(H,t))}o(_(n),L,H,.5),n[3]=Math.max(H[0]-L[0],H[1]-L[1],H[2]-L[2])/2}function R(t,e,n){if(!Q.length)for(let o=0;o<8;++o)Q.push({index:0,distance:0});for(let o=0;o<8;++o){const n=E[o];Q.data[o].index=o,Q.data[o].distance=v(t,e,n)}Q.sort(((t,e)=>t.distance-e.distance));for(let o=0;o<8;++o)n[o]=Q.data[o].index}function F(t,e){let n,o=1/0;for(let i=0;i<8;++i){const r=v(t,e,P[i]);r<o&&(o=r,n=P[i])}return n}function v(t,e,n){return e*(t[0]*n[0]+t[1]*n[1]+t[2]*n[2])}function C(t){return!isNaN(t)&&t!==-1/0&&t!==1/0&&t>0}!function(t){var e;(e=t.DepthOrder||(t.DepthOrder={}))[e.FRONT_TO_BACK=1]="FRONT_TO_BACK",e[e.BACK_TO_FRONT=-1]="BACK_TO_FRONT"}(b||(b={}));const E=[h(-1,-1,-1),h(1,-1,-1),h(-1,1,-1),h(1,1,-1),h(-1,-1,1),h(1,-1,1),h(-1,1,1),h(1,1,1)],P=[h(-1,-1,-1),h(-1,-1,1),h(-1,1,-1),h(-1,1,1),h(1,-1,-1),h(1,-1,1),h(1,1,-1),h(1,1,1)],w=Math.sqrt(3),y=[null];function k(t){return y[0]=t,y}const q=m(),I=a(),L=a(),H=a(),K=new e,J=m(),W=m(),V=m(),G=m(),U=[{min:0,max:0},{min:0,max:0},{min:0,max:0}],Q=new e,X=[0,0,0,0,0,0,0,0];export{b as default};
5
+ import t from"../../../../core/ObjectPool.js";import e from"../../../../core/PooledArray.js";import{c as n,m as o,s as i,g as r,f as s}from"../../../../chunks/vec32.js";import{fromValues as h,create as a}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{intersectsSphere as l}from"../../../../geometry/support/frustum.js";import{wrap as d}from"../../../../geometry/support/ray.js";import{h as u,g as c,k as f,c as m,a as _}from"../../../../chunks/sphere.js";import{rayBoxTest as p}from"./Util.js";class b{get bounds(){return this._root.bounds}get halfSize(){return this._root.halfSize}get root(){return this._root.node}get maximumObjectsPerNode(){return this._maximumObjectsPerNode}get maximumDepth(){return this._maximumDepth}get objectCount(){return this._objectCount}constructor(t,e){this.objectToBoundingSphere=t,this._maximumObjectsPerNode=10,this._maximumDepth=20,this._degenerateObjects=new Set,this._root=new g,this._objectCount=0,e&&(void 0!==e.maximumObjectsPerNode&&(this._maximumObjectsPerNode=e.maximumObjectsPerNode),void 0!==e.maximumDepth&&(this._maximumDepth=e.maximumDepth))}destroy(){this._degenerateObjects.clear(),g.clearPool(),y[0]=null,K.prune(),Q.prune()}add(t){const e=Array.from(t);this._grow(e);const n=g.acquire();for(const o of e)++this._objectCount,this._isDegenerate(o)?this._degenerateObjects.add(o):(n.init(this._root),this._add(o,n));g.release(n)}remove(t,e=null){this._objectCount-=t.length;const n=g.acquire();for(const o of t){const t=e??u(this.objectToBoundingSphere(o),J);C(t[3])?(n.init(this._root),O(o,t,n)):this._degenerateObjects.delete(o)}g.release(n),this._shrink()}update(t,e){if(!C(e[3])&&this._isDegenerate(t))return;const n=k(t);this.remove(n,e),this.add(n)}forEachAlongRay(t,e,n){const o=d(t,e);S(this._root,(t=>{if(!T(o,t))return!1;const e=t.node;return e.terminals.forAll((t=>{this._intersectsObject(o,t)&&n(t)})),null!==e.residents&&e.residents.forAll((t=>{this._intersectsObject(o,t)&&n(t)})),!0}))}forEachAlongRayWithVerticalOffset(t,e,n,o){const i=d(t,e);S(this._root,(t=>{if(!z(i,t,o))return!1;const e=t.node;return e.terminals.forAll((t=>{this._intersectsObjectWithOffset(i,t,o)&&n(t)})),null!==e.residents&&e.residents.forAll((t=>{this._intersectsObjectWithOffset(i,t,o)&&n(t)})),!0}))}forEach(t){S(this._root,(e=>{const n=e.node;return n.terminals.forAll(t),null!==n.residents&&n.residents.forAll(t),!0})),this._degenerateObjects.forEach(t)}forEachDegenerateObject(t){this._degenerateObjects.forEach(t)}findClosest(t,e,n,o=()=>!0,i=1/0){let h=1/0,a=1/0,d=null;const u=F(t,e),c=r=>{if(--i,!o(r))return;const s=this.objectToBoundingSphere(r);if(!l(n,s))return;const u=v(t,e,_(s)),c=u-s[3],f=u+s[3];c<h&&(h=c,a=f,d=r)};return j(this._root,(o=>{if(i<=0||!l(n,o.bounds))return!1;r(I,u,o.halfSize),s(I,I,_(o.bounds));if(v(t,e,I)>a)return!1;const h=o.node;return h.terminals.forAll((t=>c(t))),null!==h.residents&&h.residents.forAll((t=>c(t))),!0}),t,e),d}forEachInDepthRange(t,e,n,o,i,h,a){let d=-1/0,u=1/0;const c={setRange:t=>{n===b.DepthOrder.FRONT_TO_BACK?(d=Math.max(d,t.near),u=Math.min(u,t.far)):(d=Math.max(d,-t.far),u=Math.min(u,-t.near))}};c.setRange(o);const f=v(e,n,t),m=F(e,n),p=F(e,-n),g=t=>{if(!a(t))return;const o=this.objectToBoundingSphere(t),r=_(o),s=v(e,n,r)-f,m=s-o[3],p=s+o[3];m>u||p<d||!l(h,o)||i(t,c)};j(this._root,(t=>{if(!l(h,t.bounds))return!1;r(I,m,t.halfSize),s(I,I,_(t.bounds));if(v(e,n,I)-f>u)return!1;r(I,p,t.halfSize),s(I,I,_(t.bounds));if(v(e,n,I)-f<d)return!1;const o=t.node;return o.terminals.forAll((t=>g(t))),null!==o.residents&&o.residents.forAll((t=>g(t))),!0}),e,n)}forEachNode(t){S(this._root,(e=>t(e.node,e.bounds,e.halfSize,e.depth)))}forEachNeighbor(t,e){const n=c(e),o=_(e),r=e=>{const r=this.objectToBoundingSphere(e),s=c(r),h=n+s;return!(i(_(r),o)-h*h<=0)||t(e)};let s=!0;const h=t=>{s&&(s=r(t))};S(this._root,(t=>{const e=c(t.bounds),r=n+e;if(i(_(t.bounds),o)-r*r>0)return!1;const a=t.node;return a.terminals.forAll(h),s&&null!==a.residents&&a.residents.forAll(h),s})),s&&this.forEachDegenerateObject(h)}_intersectsObject(t,e){const n=this.objectToBoundingSphere(e);return!(n[3]>0)||f(n,t)}_intersectsObjectWithOffset(t,e,n){const o=this.objectToBoundingSphere(e);return!(o[3]>0)||f(n.applyToBoundingSphere(o),t)}_add(t,e){e.advanceTo(this.objectToBoundingSphere(t))?e.node.terminals.push(t):(e.node.residents.push(t),e.node.residents.length>this._maximumObjectsPerNode&&e.depth<this._maximumDepth&&this._split(e))}_split(t){const e=t.node.residents;t.node.residents=null;for(let n=0;n<e.length;n++){const o=g.acquire().init(t);this._add(e.at(n),o),g.release(o)}}_grow(t){if(D(t,(t=>this.objectToBoundingSphere(t)),W),C(W[3])&&!this._fitsInsideTree(W))if(N(this._root.node))u(W,this._root.bounds),this._root.halfSize=1.25*this._root.bounds[3],this._root.updateBoundsRadiusFromHalfSize();else{const t=this._rootBoundsForRootAsSubNode(W);this._placingRootViolatesMaxDepth(t)?this._rebuildTree(W,t):this._growRootAsSubNode(t),g.release(t)}}_rebuildTree(t,e){n(_(V),_(e.bounds)),V[3]=e.halfSize,D([t,V],(t=>t),G);const o=g.acquire().init(this._root);this._root.initFrom(null,G,G[3]),this._root.increaseHalfSize(1.25),S(o,(t=>(this.add(t.node.terminals.data),null!==t.node.residents&&this.add(t.node.residents.data),!0))),g.release(o)}_placingRootViolatesMaxDepth(t){const e=Math.log(t.halfSize/this._root.halfSize)*Math.LOG2E;let n=0;return S(this._root,(t=>(n=Math.max(n,t.depth),n+e<=this._maximumDepth))),n+e>this._maximumDepth}_rootBoundsForRootAsSubNode(t){const e=t[3],n=t;let o=-1/0;const i=this._root.bounds,r=this._root.halfSize;for(let h=0;h<3;h++){const t=i[h]-r-(n[h]-e),s=n[h]+e-(i[h]+r),a=Math.max(0,Math.ceil(t/(2*r))),l=Math.max(0,Math.ceil(s/(2*r)))+1,d=2**Math.ceil(Math.log(a+l)*Math.LOG2E);o=Math.max(o,d),U[h].min=a,U[h].max=l}for(let h=0;h<3;h++){let t=U[h].min,e=U[h].max;const n=(o-(t+e))/2;t+=Math.ceil(n),e+=Math.floor(n);const s=i[h]-r-t*r*2;q[h]=s+(e+t)*r}const s=o*r;return q[3]=s*w,g.acquire().initFrom(null,q,s,0)}_growRootAsSubNode(t){const e=this._root.node;n(_(W),_(this._root.bounds)),W[3]=this._root.halfSize,this._root.init(t),t.advanceTo(W,null,!0),t.node.children=e.children,t.node.residents=e.residents,t.node.terminals=e.terminals}_shrink(){for(;;){const t=this._findShrinkIndex();if(-1===t)break;this._root.advance(t),this._root.depth=0}}_findShrinkIndex(){if(0!==this._root.node.terminals.length||this._root.isLeaf())return-1;let t=null;const e=this._root.node.children;let n=0,o=0;for(;o<e.length&&null==t;)n=o++,t=e[n];for(;o<e.length;)if(e[o++])return-1;return n}_isDegenerate(t){return!C(this.objectToBoundingSphere(t)[3])}_fitsInsideTree(t){const e=this._root.bounds,n=this._root.halfSize;return t[3]<=n&&t[0]>=e[0]-n&&t[0]<=e[0]+n&&t[1]>=e[1]-n&&t[1]<=e[1]+n&&t[2]>=e[2]-n&&t[2]<=e[2]+n}toJSON(){const{maximumDepth:t,maximumObjectsPerNode:e,_objectCount:n}=this,o=this._nodeToJSON(this._root.node);return{maximumDepth:t,maximumObjectsPerNode:e,objectCount:n,root:{bounds:this._root.bounds,halfSize:this._root.halfSize,depth:this._root.depth,node:o}}}_nodeToJSON(t){const e=t.children.map((t=>t?this._nodeToJSON(t):null)),n=t.residents?.map((t=>this.objectToBoundingSphere(t))),o=t.terminals?.map((t=>this.objectToBoundingSphere(t)));return{children:e,residents:n,terminals:o}}static fromJSON(t){const e=new b((t=>t),{maximumDepth:t.maximumDepth,maximumObjectsPerNode:t.maximumObjectsPerNode});return e._objectCount=t.objectCount,e._root.initFrom(t.root.node,t.root.bounds,t.root.halfSize,t.root.depth),e}}class g{constructor(){this.bounds=m(),this.halfSize=0,this.initFrom(null,null,0,0)}init(t){return this.initFrom(t.node,t.bounds,t.halfSize,t.depth)}initFrom(t,e,n,o=this.depth){return this.node=null!=t?t:g.createEmptyNode(),e&&u(e,this.bounds),this.halfSize=n,this.depth=o,this}increaseHalfSize(t){this.halfSize*=t,this.updateBoundsRadiusFromHalfSize()}updateBoundsRadiusFromHalfSize(){this.bounds[3]=this.halfSize*w}advance(t){let e=this.node.children[t];e||(e=g.createEmptyNode(),this.node.children[t]=e),this.node=e,this.halfSize/=2,this.depth++;const n=E[t];return this.bounds[0]+=n[0]*this.halfSize,this.bounds[1]+=n[1]*this.halfSize,this.bounds[2]+=n[2]*this.halfSize,this.updateBoundsRadiusFromHalfSize(),this}advanceTo(t,e,n=!1){for(;;){if(this.isTerminalFor(t))return e&&e(this,-1),!0;if(this.isLeaf()){if(!n)return e&&e(this,-1),!1;this.node.residents=null}const o=this._childIndex(t);e&&e(this,o),this.advance(o)}}isLeaf(){return null!=this.node.residents}isTerminalFor(t){return t[3]>this.halfSize/2}_childIndex(t){const e=this.bounds;return(e[0]<t[0]?1:0)+(e[1]<t[1]?2:0)+(e[2]<t[2]?4:0)}static createEmptyNode(){return{children:[null,null,null,null,null,null,null,null],terminals:new e({shrink:!0}),residents:new e({shrink:!0})}}static{this._pool=new t(g)}static acquire(){return g._pool.acquire()}static release(t){g._pool.release(t)}static clearPool(){g._pool.prune()}}function S(t,e){let n=g.acquire().init(t);const o=[n];for(;0!==o.length;){if(n=o.pop(),e(n)&&!n.isLeaf())for(let t=0;t<n.node.children.length;t++){n.node.children[t]&&o.push(g.acquire().init(n).advance(t))}g.release(n)}}function j(t,e,n,o=b.DepthOrder.FRONT_TO_BACK){let i=g.acquire().init(t);const r=[i];for(R(n,o,X);0!==r.length;){if(i=r.pop(),e(i)&&!i.isLeaf())for(let t=7;t>=0;--t){const e=X[t];i.node.children[e]&&r.push(g.acquire().init(i).advance(e))}g.release(i)}}function O(t,e,n){K.clear();const o=n.advanceTo(e,((t,e)=>{K.push(t.node),K.push(e)}))?n.node.terminals:n.node.residents;if(o.removeUnordered(t),0===o.length)for(let i=K.length-2;i>=0;i-=2){if(!x(K.data[i],K.data[i+1]))break}}function x(t,n){return n>=0&&(t.children[n]=null),!!N(t)&&(null===t.residents&&(t.residents=new e({shrink:!0})),!0)}function T(t,e){return B(_(e.bounds),2*-e.halfSize,L),B(_(e.bounds),2*e.halfSize,H),p(t.origin,t.direction,L,H)}function z(t,e,n){return B(_(e.bounds),2*-e.halfSize,L),B(_(e.bounds),2*e.halfSize,H),n.applyToMinMax(L,H),p(t.origin,t.direction,L,H)}function N(t){if(0!==t.terminals.length)return!1;if(null!==t.residents)return 0===t.residents.length;for(let e=0;e<t.children.length;e++)if(t.children[e])return!1;return!0}function M(t,e){t[0]=Math.min(t[0],e[0]-e[3]),t[1]=Math.min(t[1],e[1]-e[3]),t[2]=Math.min(t[2],e[2]-e[3])}function A(t,e){t[0]=Math.max(t[0],e[0]+e[3]),t[1]=Math.max(t[1],e[1]+e[3]),t[2]=Math.max(t[2],e[2]+e[3])}function B(t,e,n){n[0]=t[0]+e,n[1]=t[1]+e,n[2]=t[2]+e}function D(t,e,n){L[0]=1/0,L[1]=1/0,L[2]=1/0,H[0]=-1/0,H[1]=-1/0,H[2]=-1/0;for(const o of t){const t=e(o);C(t[3])&&(M(L,t),A(H,t))}o(_(n),L,H,.5),n[3]=Math.max(H[0]-L[0],H[1]-L[1],H[2]-L[2])/2}function R(t,e,n){if(!Q.length)for(let o=0;o<8;++o)Q.push({index:0,distance:0});for(let o=0;o<8;++o){const n=E[o];Q.data[o].index=o,Q.data[o].distance=v(t,e,n)}Q.sort(((t,e)=>t.distance-e.distance));for(let o=0;o<8;++o)n[o]=Q.data[o].index}function F(t,e){let n,o=1/0;for(let i=0;i<8;++i){const r=v(t,e,P[i]);r<o&&(o=r,n=P[i])}return n}function v(t,e,n){return e*(t[0]*n[0]+t[1]*n[1]+t[2]*n[2])}function C(t){return!isNaN(t)&&t!==-1/0&&t!==1/0&&t>0}!function(t){var e;(e=t.DepthOrder||(t.DepthOrder={}))[e.FRONT_TO_BACK=1]="FRONT_TO_BACK",e[e.BACK_TO_FRONT=-1]="BACK_TO_FRONT"}(b||(b={}));const E=[h(-1,-1,-1),h(1,-1,-1),h(-1,1,-1),h(1,1,-1),h(-1,-1,1),h(1,-1,1),h(-1,1,1),h(1,1,1)],P=[h(-1,-1,-1),h(-1,-1,1),h(-1,1,-1),h(-1,1,1),h(1,-1,-1),h(1,-1,1),h(1,1,-1),h(1,1,1)],w=Math.sqrt(3),y=[null];function k(t){return y[0]=t,y}const q=m(),I=a(),L=a(),H=a(),K=new e,J=m(),W=m(),V=m(),G=m(),U=[{min:0,max:0},{min:0,max:0},{min:0,max:0}],Q=new e,X=[0,0,0,0,0,0,0,0];export{b 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/4.34/esri/copyright.txt for details.
4
4
  */
5
- import has from"../../../../core/has.js";import{clamp as t,lerp as s,acosClamped as e}from"../../../../core/mathUtils.js";import{releaseMaybe as i}from"../../../../core/maybe.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{translate as r,multiply as h,invert as o,lookAt as n}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{IDENTITY as c,create as l}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{set as d,add as u,scale as m,lerp as _,squaredDistance as f,subtract as g,dot as p,negate as x,normalize as b,copy as w}from"../../../../core/libs/gl-matrix-2/math/vec2.js";import{create as M}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{q as C,c as j,u as y,t as H,i as v}from"../../../../chunks/vec32.js";import{create as D}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as S,t as O}from"../../../../chunks/vec42.js";import{create as T}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{ViewingMode as F}from"../../../ViewingMode.js";import{DepthFormat as B}from"../core/FBOCacheFormats.js";import{CascadeCamera as Q}from"./CascadeCamera.js";import{applyTextureResizeModulo as V}from"./textureUtils.js";import{assert as L,logWithBase as N,verify as q,rayRay2D as R}from"./Util.js";import{DepthStencilAttachment as W,FramebufferBit as z}from"../../../webgl/enums.js";var E;!function(t){t[t.Highlight=0]="Highlight",t[t.ExcludeHighlight=1]="ExcludeHighlight"}(E||(E={}));class P{constructor(){this.camera=new Q,this.lightMat=l()}}class A{constructor(){this.maxNumCascadesHighQuality=4,this.maxNumCascadesLowQuality=4,this.textureSizeModHighQuality=1.3,this.textureSizeModLowQuality=.9,this.splitSchemeLambda=0}}class I{constructor(t,s){this._fbos=t,this._viewingMode=s,this._snapshots=new Array,this._textureHeight=0,this._numCascades=1,this.settings=new A,this._projectionView=l(),this._projectionViewInverse=l(),this._modelViewLight=l(),this._cascadeDistances=[0,0,0,0,0],this._usedCascadeDistances=T(),this._cascades=[new P,new P,new P,new P],this._lastOrigin=null,this._enabled=!1,this._maxTextureWidth=Math.min(has("esri-mobile")?4096:16384,t.rctx.parameters.maxTextureSize)}dispose(){this.enabled=!1,this.disposeOffscreenBuffers()}get depthTexture(){return this._handle?.getTexture(W)}get _textureWidth(){return this._textureHeight*this._numCascades}get numCascades(){return this._numCascades}get cascadeDistances(){return S(this._usedCascadeDistances,this._cascadeDistances[0],this._numCascades>1?this._cascadeDistances[1]:1/0,this._numCascades>2?this._cascadeDistances[2]:1/0,this._numCascades>3?this._cascadeDistances[3]:1/0)}disposeMainBuffer(){this._handle=i(this._handle)}disposeOffscreenBuffers(){this.disposeMainBuffer(),this._discardSnapshots()}set maxCascades(s){this.settings.maxNumCascadesHighQuality=t(Math.floor(s),1,4)}get maxCascades(){return this.settings.maxNumCascadesHighQuality}set enabled(t){this._enabled=t,t||this.disposeOffscreenBuffers()}get enabled(){return this._enabled}get ready(){return this._enabled&&null!=this.depthTexture}get cascades(){for(let t=0;t<this._numCascades;++t)tt[t]=this._cascades[t];return tt.length=this._numCascades,tt}start(t,s,e,i,a){L(this.enabled);const{near:r,far:h}=Mt(e);this._computeCascadeDistances(r,h,i),this._textureHeight=this._computeTextureHeight(t,a,i),this._setupMatrices(t,s);const{viewMatrix:o,projectionMatrix:n}=t;for(let c=0;c<this._numCascades;++c)this._constructCascade(c,n,o,s);this._lastOrigin=null,this.clear()}finish(){L(this.enabled)}getShadowMapMatrices(t){if(!this._lastOrigin||!C(t,this._lastOrigin)){this._lastOrigin=this._lastOrigin||D(),j(this._lastOrigin,t);for(let s=0;s<this._numCascades;++s){r(st,this._cascades[s].lightMat,t);for(let t=0;t<16;++t)et[16*s+t]=st[t]}}return et}moveSnapshot(t){L(this.enabled),this._snapshots[t]?.release(),this._snapshots[t]=this._handle,this._handle?.setName(t===E.Highlight?"shadow map highlight":"shadow map excluding highlight"),this._handle=null}copySnapshot(t){if(!this.enabled)return;const s=this._handle?.getTexture(W)?.descriptor;if(!s)return;this._snapshots[t]?.release();const e=t===E.Highlight?"shadow map highlight":"shadow map excluding highlight",i=this._acquireFBO(e);this._snapshots[t]=i;const a=this._handle?.fbo;if(!a||!i?.fbo)return void console.error("No FBO");const{rctx:r}=this._fbos;r.blitFramebuffer(a,i.fbo,z.DEPTH)}getSnapshot(t){return this.enabled?this._snapshots[t]?.getTexture(W):null}clear(){this._ensureFbo(),this.bindFbo(),this._fbos.rctx.clear(z.DEPTH)}_computeTextureHeight({pixelRatio:t,fullWidth:s,fullHeight:e},i,a){const r=Math.min(window.devicePixelRatio,i)/t,h=a?this.settings.textureSizeModHighQuality:this.settings.textureSizeModLowQuality;return V(Math.max(s,e)*r*h,this._maxTextureWidth/this._numCascades)}_ensureFbo(){this._handle?.fbo?.width===this._textureWidth&&this._handle?.fbo.height===this._textureHeight||(this._handle?.release(),this._handle=this._acquireFBO("shadow map"))}_acquireFBO(t){const s=this._fbos.acquire(this._textureWidth,this._textureHeight,t,B.DEPTH16);return s.getTexture(W)?.setShadowFiltering(!0),s}_discardSnapshot(t){this._snapshots[t]=i(this._snapshots[t])}_discardSnapshots(){for(let t=0;t<this._snapshots.length;++t)this._discardSnapshot(t);this._snapshots.length=0}bindFbo(){this._fbos.rctx.bindFramebuffer(this._handle?.fbo)}_constructCascade(t,s,e,i){const a=this._cascades[t],o=-this._cascadeDistances[t],n=-this._cascadeDistances[t+1],c=(s[10]*o+s[14])/Math.abs(s[11]*o+s[15]),l=(s[10]*n+s[14])/Math.abs(s[11]*n+s[15]);L(c<l);for(let r=0;r<8;++r){S(k,r%4==0||r%4==3?-1:1,r%4==0||r%4==1?-1:1,r<4?c:l,1);const t=G[r];O(t,k,this._projectionViewInverse),t[0]/=t[3],t[1]/=t[3],t[2]/=t[3]}y($,G[0]),a.camera.viewMatrix=r(U,this._modelViewLight,$);for(let r=0;r<8;++r)H(G[r],G[r],a.camera.viewMatrix);let d=G[0][2],u=G[0][2];for(let r=1;r<8;++r)d=Math.min(d,G[r][2]),u=Math.max(u,G[r][2]);d-=200,u+=200,a.camera.near=-u,a.camera.far=-d,wt(e,i,d,u,a.camera),h(a.lightMat,a.camera.projectionMatrix,a.camera.viewMatrix);const m=this._textureHeight;a.camera.viewport=[t*m,0,m,m]}_setupMatrices(t,s){h(this._projectionView,t.projectionMatrix,t.viewMatrix),o(this._projectionViewInverse,this._projectionView);const e=this._viewingMode===F.Global?t.eye:v($,0,0,1);n(this._modelViewLight,[0,0,0],[-s[0],-s[1],-s[2]],e)}_computeCascadeDistances(t,e,i){const a=i?this.settings.maxNumCascadesHighQuality:this.settings.maxNumCascadesLowQuality;this._numCascades=Math.min(1+Math.floor(N(e/t,4)),a);const r=(e-t)/this._numCascades,h=(e/t)**(1/this._numCascades);let o=t,n=t;for(let c=0;c<this._numCascades+1;++c)this._cascadeDistances[c]=s(o,n,this.settings.splitSchemeLambda),o*=h,n+=r}get test(){}}const U=l(),k=T(),G=[];for(let Ct=0;Ct<8;++Ct)G.push(T());const J=M(),K=M(),X=M(),Y=M(),Z=M(),$=D(),tt=[],st=l(),et=c.concat(c,c,c,c),it=M(),at=M(),rt=[M(),M(),M(),M()],ht=M(),ot=M(),nt=M(),ct=M(),lt=M(),dt=M(),ut=M();function mt(t,s,e,i,a,r,h,o){d(it,0,0);for(let d=0;d<4;++d)u(it,it,t[d]);m(it,it,.25),d(at,0,0);for(let d=4;d<8;++d)u(at,at,t[d]);m(at,at,.25),_(rt[0],t[4],t[5],.5),_(rt[1],t[5],t[6],.5),_(rt[2],t[6],t[7],.5),_(rt[3],t[7],t[4],.5);let n=0,c=f(rt[0],it);for(let d=1;d<4;++d){const t=f(rt[d],it);t<c&&(c=t,n=d)}g(ht,rt[n],t[n+4]);const l=ht[0];let M,C;ht[0]=-ht[1],ht[1]=l,g(ot,at,it),p(ot,ht)<0&&x(ht,ht),_(ht,ht,ot,e),b(ht,ht),M=C=p(g(nt,t[0],it),ht);for(let d=1;d<8;++d){const s=p(g(nt,t[d],it),ht);s<M?M=s:s>C&&(C=s)}w(i,it),m(nt,ht,M-s),u(i,i,nt);let j=-1,y=1,H=0,v=0;for(let d=0;d<8;++d){g(ct,t[d],i),b(ct,ct);const s=ht[0]*ct[1]-ht[1]*ct[0];s>0?s>j&&(j=s,H=d):s<y&&(y=s,v=d)}q(j>0,"leftArea"),q(y<0,"rightArea"),m(lt,ht,M),u(lt,lt,it),m(dt,ht,C),u(dt,dt,it),ut[0]=-ht[1],ut[1]=ht[0];const D=R(i,t[v],dt,u(nt,dt,ut),1,a),S=R(i,t[H],dt,nt,1,r),O=R(i,t[H],lt,u(nt,lt,ut),1,h),T=R(i,t[v],lt,nt,1,o);q(D,"rayRay"),q(S,"rayRay"),q(O,"rayRay"),q(T,"rayRay")}function _t(t,s){return 3*s+t}const ft=M();function gt(t,s){return d(ft,t[s],t[s+3]),ft}const pt=M(),xt=a();function bt(t,s,e,i,a){g(pt,e,i),m(pt,pt,.5),xt[0]=pt[0],xt[1]=pt[1],xt[2]=0,xt[3]=pt[1],xt[4]=-pt[0],xt[5]=0,xt[6]=pt[0]*pt[0]+pt[1]*pt[1],xt[7]=pt[0]*pt[1]-pt[1]*pt[0],xt[8]=1,xt[_t(0,2)]=-p(gt(xt,0),t),xt[_t(1,2)]=-p(gt(xt,1),t);let r=p(gt(xt,0),e)+xt[_t(0,2)],h=p(gt(xt,1),e)+xt[_t(1,2)],o=p(gt(xt,0),i)+xt[_t(0,2)],n=p(gt(xt,1),i)+xt[_t(1,2)];r=-(r+o)/(h+n),xt[_t(0,0)]+=xt[_t(1,0)]*r,xt[_t(0,1)]+=xt[_t(1,1)]*r,xt[_t(0,2)]+=xt[_t(1,2)]*r,r=1/(p(gt(xt,0),e)+xt[_t(0,2)]),h=1/(p(gt(xt,1),e)+xt[_t(1,2)]),xt[_t(0,0)]*=r,xt[_t(0,1)]*=r,xt[_t(0,2)]*=r,xt[_t(1,0)]*=h,xt[_t(1,1)]*=h,xt[_t(1,2)]*=h,xt[_t(2,0)]=xt[_t(1,0)],xt[_t(2,1)]=xt[_t(1,1)],xt[_t(2,2)]=xt[_t(1,2)],xt[_t(1,2)]+=1,r=p(gt(xt,1),s)+xt[_t(1,2)],h=p(gt(xt,2),s)+xt[_t(2,2)],o=p(gt(xt,1),e)+xt[_t(1,2)],n=p(gt(xt,2),e)+xt[_t(2,2)],r=-.5*(r/h+o/n),xt[_t(1,0)]+=xt[_t(2,0)]*r,xt[_t(1,1)]+=xt[_t(2,1)]*r,xt[_t(1,2)]+=xt[_t(2,2)]*r,r=p(gt(xt,1),s)+xt[_t(1,2)],h=p(gt(xt,2),s)+xt[_t(2,2)],o=-h/r,xt[_t(1,0)]*=o,xt[_t(1,1)]*=o,xt[_t(1,2)]*=o,a[0]=xt[0],a[1]=xt[1],a[2]=0,a[3]=xt[2],a[4]=xt[3],a[5]=xt[4],a[6]=0,a[7]=xt[5],a[8]=0,a[9]=0,a[10]=1,a[11]=0,a[12]=xt[6],a[13]=xt[7],a[14]=0,a[15]=xt[8]}function wt(t,s,i,a,r){const h=1/G[0][3],o=1/G[4][3];L(h<o);let n=h+Math.sqrt(h*o);const c=Math.sin(e(t[2]*s[0]+t[6]*s[1]+t[10]*s[2]));n/=c,mt(G,n,c,J,K,X,Y,Z),bt(J,K,Y,Z,r.projectionMatrix),r.projectionMatrix[10]=2/(i-a),r.projectionMatrix[14]=-(i+a)/(i-a)}function Mt(t){let{near:s,far:e}=t;return s<2&&(s=2),e<2&&(e=2),s>=e&&(s=2,e=4),{near:s,far:e}}export{I as ShadowMap,E as SnapshotSlot};
5
+ import has from"../../../../core/has.js";import{clamp as t,lerp as s,acosClamped as e}from"../../../../core/mathUtils.js";import{releaseMaybe as i}from"../../../../core/maybe.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{translate as r,multiply as h,invert as o,lookAt as n}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{IDENTITY as c,create as l}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{set as d,add as u,scale as m,lerp as _,squaredDistance as f,subtract as g,dot as p,negate as x,normalize as b,copy as w}from"../../../../core/libs/gl-matrix-2/math/vec2.js";import{create as M}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{q as C,c as j,u as y,t as H,i as v}from"../../../../chunks/vec32.js";import{create as D}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as S,t as O}from"../../../../chunks/vec42.js";import{create as T}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{ViewingMode as F}from"../../../ViewingMode.js";import{DepthFormat as B}from"../core/FBOCacheFormats.js";import{CascadeCamera as Q}from"./CascadeCamera.js";import{applyTextureResizeModulo as V}from"./textureUtils.js";import{assert as L,logWithBase as N,verify as q,rayRay2D as R}from"./Util.js";import{DepthStencilAttachment as W,FramebufferBit as z}from"../../../webgl/enums.js";var E;!function(t){t[t.Highlight=0]="Highlight",t[t.ExcludeHighlight=1]="ExcludeHighlight"}(E||(E={}));class P{constructor(){this.camera=new Q,this.lightMat=l()}}class A{constructor(){this.maxNumCascadesHighQuality=4,this.maxNumCascadesLowQuality=4,this.textureSizeModHighQuality=1.3,this.textureSizeModLowQuality=.9,this.splitSchemeLambda=0}}class I{constructor(t,s){this._fbos=t,this._viewingMode=s,this._snapshots=new Array,this._textureHeight=0,this._numCascades=1,this.settings=new A,this._projectionView=l(),this._projectionViewInverse=l(),this._modelViewLight=l(),this._cascadeDistances=[0,0,0,0,0],this._usedCascadeDistances=T(),this._cascades=[new P,new P,new P,new P],this._lastOrigin=null,this._enabled=!1,this._maxTextureWidth=Math.min(has("esri-mobile")?4096:16384,t.rctx.parameters.maxTextureSize)}dispose(){this.enabled=!1,this.disposeOffscreenBuffers()}get depthTexture(){return this._handle?.getTexture(W)}get _textureWidth(){return this._textureHeight*this._numCascades}get numCascades(){return this._numCascades}get cascadeDistances(){return S(this._usedCascadeDistances,this._cascadeDistances[0],this._numCascades>1?this._cascadeDistances[1]:1/0,this._numCascades>2?this._cascadeDistances[2]:1/0,this._numCascades>3?this._cascadeDistances[3]:1/0)}disposeMainBuffer(){this._handle=i(this._handle)}disposeOffscreenBuffers(){this.disposeMainBuffer(),this._discardSnapshots()}set maxCascades(s){this.settings.maxNumCascadesHighQuality=t(Math.floor(s),1,4)}get maxCascades(){return this.settings.maxNumCascadesHighQuality}set enabled(t){this._enabled=t,t||this.disposeOffscreenBuffers()}get enabled(){return this._enabled}get ready(){return this._enabled&&null!=this.depthTexture}get cascades(){for(let t=0;t<this._numCascades;++t)tt[t]=this._cascades[t];return tt.length=this._numCascades,tt}start(t,s,e,i,a){L(this.enabled);const{near:r,far:h}=Ct(e);this._computeCascadeDistances(r,h,i),this._textureHeight=this._computeTextureHeight(t,a,i),this._setupMatrices(t,s);const{viewMatrix:o,projectionMatrix:n}=t;for(let c=0;c<this._numCascades;++c)this._constructCascade(c,n,o,s);this._lastOrigin=null,this.clear()}finish(){L(this.enabled)}getShadowMapMatrices(t){if(!this._lastOrigin||!C(t,this._lastOrigin)){this._lastOrigin=this._lastOrigin||D(),j(this._lastOrigin,t);for(let s=0;s<this._numCascades;++s){r(et,this._cascades[s].lightMat,t);for(let t=0;t<16;++t)it[16*s+t]=et[t]}}return it}moveSnapshot(t){L(this.enabled),this._snapshots[t]?.release(),this._snapshots[t]=this._handle,this._handle?.setName(t===E.Highlight?"shadow map highlight":"shadow map excluding highlight"),this._handle=null}copySnapshot(t){if(!this.enabled)return;const s=this._handle?.getTexture(W)?.descriptor;if(!s)return;this._snapshots[t]?.release();const e=t===E.Highlight?"shadow map highlight":"shadow map excluding highlight",i=this._acquireFBO(e);this._snapshots[t]=i;const a=this._handle?.fbo;if(!a||!i?.fbo)return void console.error("No FBO");const{rctx:r}=this._fbos;r.blitFramebuffer(a,i.fbo,z.DEPTH)}getSnapshot(t){return this.enabled?this._snapshots[t]?.getTexture(W):null}clear(){this._ensureFbo(),this.bindFbo(),this._fbos.rctx.clear(z.DEPTH)}_computeTextureHeight({pixelRatio:t,fullWidth:s,fullHeight:e},i,a){const r=Math.min(window.devicePixelRatio,i)/t,h=a?this.settings.textureSizeModHighQuality:this.settings.textureSizeModLowQuality;return V(Math.max(s,e)*r*h,this._maxTextureWidth/this._numCascades)}_ensureFbo(){this._handle?.fbo?.width===this._textureWidth&&this._handle?.fbo.height===this._textureHeight||(this._handle?.release(),this._handle=this._acquireFBO("shadow map"))}_acquireFBO(t){const s=this._fbos.acquire(this._textureWidth,this._textureHeight,t,B.DEPTH16);return s.getTexture(W)?.setShadowFiltering(!0),s}_discardSnapshot(t){this._snapshots[t]=i(this._snapshots[t])}_discardSnapshots(){for(let t=0;t<this._snapshots.length;++t)this._discardSnapshot(t);this._snapshots.length=0}bindFbo(){this._fbos.rctx.bindFramebuffer(this._handle?.fbo)}_constructCascade(t,s,e,i){const a=this._cascades[t],o=-this._cascadeDistances[t],n=-this._cascadeDistances[t+1],c=(s[10]*o+s[14])/Math.abs(s[11]*o+s[15]),l=(s[10]*n+s[14])/Math.abs(s[11]*n+s[15]);L(c<l);for(let r=0;r<8;++r){S(k,r%4==0||r%4==3?-1:1,r%4==0||r%4==1?-1:1,r<4?c:l,1);const t=G[r];O(t,k,this._projectionViewInverse),t[0]/=t[3],t[1]/=t[3],t[2]/=t[3]}y($,G[0]),a.camera.viewMatrix=r(U,this._modelViewLight,$);for(let r=0;r<8;++r)H(G[r],G[r],a.camera.viewMatrix);let d=G[0][2],u=G[0][2];for(let r=1;r<8;++r)d=Math.min(d,G[r][2]),u=Math.max(u,G[r][2]);d-=200,u+=200,a.camera.near=-u,a.camera.far=-d,Mt(e,i,d,u,a.camera),h(a.lightMat,a.camera.projectionMatrix,a.camera.viewMatrix);const m=this._textureHeight;a.camera.viewport=[t*m,0,m,m]}_setupMatrices(t,s){h(this._projectionView,t.projectionMatrix,t.viewMatrix),o(this._projectionViewInverse,this._projectionView);const e=this._viewingMode===F.Global?t.eye:v($,0,0,1);n(this._modelViewLight,[0,0,0],[-s[0],-s[1],-s[2]],e)}_computeCascadeDistances(t,e,i){const a=i?this.settings.maxNumCascadesHighQuality:this.settings.maxNumCascadesLowQuality;this._numCascades=Math.min(1+Math.floor(N(e/t,4)),a);const r=(e-t)/this._numCascades,h=(e/t)**(1/this._numCascades);let o=t,n=t;for(let c=0;c<this._numCascades+1;++c)this._cascadeDistances[c]=s(o,n,this.settings.splitSchemeLambda),o*=h,n+=r}get test(){}}const U=l(),k=T(),G=[];for(let jt=0;jt<8;++jt)G.push(T());const J=M(),K=M(),X=M(),Y=M(),Z=M(),$=D(),tt=[];function st(){tt.length=0}const et=l(),it=c.concat(c,c,c,c),at=M(),rt=M(),ht=[M(),M(),M(),M()],ot=M(),nt=M(),ct=M(),lt=M(),dt=M(),ut=M(),mt=M();function _t(t,s,e,i,a,r,h,o){d(at,0,0);for(let d=0;d<4;++d)u(at,at,t[d]);m(at,at,.25),d(rt,0,0);for(let d=4;d<8;++d)u(rt,rt,t[d]);m(rt,rt,.25),_(ht[0],t[4],t[5],.5),_(ht[1],t[5],t[6],.5),_(ht[2],t[6],t[7],.5),_(ht[3],t[7],t[4],.5);let n=0,c=f(ht[0],at);for(let d=1;d<4;++d){const t=f(ht[d],at);t<c&&(c=t,n=d)}g(ot,ht[n],t[n+4]);const l=ot[0];let M,C;ot[0]=-ot[1],ot[1]=l,g(nt,rt,at),p(nt,ot)<0&&x(ot,ot),_(ot,ot,nt,e),b(ot,ot),M=C=p(g(ct,t[0],at),ot);for(let d=1;d<8;++d){const s=p(g(ct,t[d],at),ot);s<M?M=s:s>C&&(C=s)}w(i,at),m(ct,ot,M-s),u(i,i,ct);let j=-1,y=1,H=0,v=0;for(let d=0;d<8;++d){g(lt,t[d],i),b(lt,lt);const s=ot[0]*lt[1]-ot[1]*lt[0];s>0?s>j&&(j=s,H=d):s<y&&(y=s,v=d)}q(j>0,"leftArea"),q(y<0,"rightArea"),m(dt,ot,M),u(dt,dt,at),m(ut,ot,C),u(ut,ut,at),mt[0]=-ot[1],mt[1]=ot[0];const D=R(i,t[v],ut,u(ct,ut,mt),1,a),S=R(i,t[H],ut,ct,1,r),O=R(i,t[H],dt,u(ct,dt,mt),1,h),T=R(i,t[v],dt,ct,1,o);q(D,"rayRay"),q(S,"rayRay"),q(O,"rayRay"),q(T,"rayRay")}function ft(t,s){return 3*s+t}const gt=M();function pt(t,s){return d(gt,t[s],t[s+3]),gt}const xt=M(),bt=a();function wt(t,s,e,i,a){g(xt,e,i),m(xt,xt,.5),bt[0]=xt[0],bt[1]=xt[1],bt[2]=0,bt[3]=xt[1],bt[4]=-xt[0],bt[5]=0,bt[6]=xt[0]*xt[0]+xt[1]*xt[1],bt[7]=xt[0]*xt[1]-xt[1]*xt[0],bt[8]=1,bt[ft(0,2)]=-p(pt(bt,0),t),bt[ft(1,2)]=-p(pt(bt,1),t);let r=p(pt(bt,0),e)+bt[ft(0,2)],h=p(pt(bt,1),e)+bt[ft(1,2)],o=p(pt(bt,0),i)+bt[ft(0,2)],n=p(pt(bt,1),i)+bt[ft(1,2)];r=-(r+o)/(h+n),bt[ft(0,0)]+=bt[ft(1,0)]*r,bt[ft(0,1)]+=bt[ft(1,1)]*r,bt[ft(0,2)]+=bt[ft(1,2)]*r,r=1/(p(pt(bt,0),e)+bt[ft(0,2)]),h=1/(p(pt(bt,1),e)+bt[ft(1,2)]),bt[ft(0,0)]*=r,bt[ft(0,1)]*=r,bt[ft(0,2)]*=r,bt[ft(1,0)]*=h,bt[ft(1,1)]*=h,bt[ft(1,2)]*=h,bt[ft(2,0)]=bt[ft(1,0)],bt[ft(2,1)]=bt[ft(1,1)],bt[ft(2,2)]=bt[ft(1,2)],bt[ft(1,2)]+=1,r=p(pt(bt,1),s)+bt[ft(1,2)],h=p(pt(bt,2),s)+bt[ft(2,2)],o=p(pt(bt,1),e)+bt[ft(1,2)],n=p(pt(bt,2),e)+bt[ft(2,2)],r=-.5*(r/h+o/n),bt[ft(1,0)]+=bt[ft(2,0)]*r,bt[ft(1,1)]+=bt[ft(2,1)]*r,bt[ft(1,2)]+=bt[ft(2,2)]*r,r=p(pt(bt,1),s)+bt[ft(1,2)],h=p(pt(bt,2),s)+bt[ft(2,2)],o=-h/r,bt[ft(1,0)]*=o,bt[ft(1,1)]*=o,bt[ft(1,2)]*=o,a[0]=bt[0],a[1]=bt[1],a[2]=0,a[3]=bt[2],a[4]=bt[3],a[5]=bt[4],a[6]=0,a[7]=bt[5],a[8]=0,a[9]=0,a[10]=1,a[11]=0,a[12]=bt[6],a[13]=bt[7],a[14]=0,a[15]=bt[8]}function Mt(t,s,i,a,r){const h=1/G[0][3],o=1/G[4][3];L(h<o);let n=h+Math.sqrt(h*o);const c=Math.sin(e(t[2]*s[0]+t[6]*s[1]+t[10]*s[2]));n/=c,_t(G,n,c,J,K,X,Y,Z),wt(J,K,Y,Z,r.projectionMatrix),r.projectionMatrix[10]=2/(i-a),r.projectionMatrix[14]=-(i+a)/(i-a)}function Ct(t){let{near:s,far:e}=t;return s<2&&(s=2),e<2&&(e=2),s>=e&&(s=2,e=4),{near:s,far:e}}export{I as ShadowMap,E as SnapshotSlot,st as cleanupShadowmap};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{acosClamped as e,deg2rad as t}from"../../../../../core/mathUtils.js";import o from"../../../../../core/PooledArray.js";import{j as n,i as s,c as a,e as r,d as c,h as l,n as i,E as h}from"../../../../../chunks/vec32.js";import{create as g}from"../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{Edge as u}from"./Edge.js";const d=-1;function p(e,t,o){const c=e.vertices.position,l=e.vertices.componentIndex,i=y.position0,h=y.position1,g=y.faceNormal0,u=y.faceNormal1,{edges:p,normals:v}=w(e),V=p.length/4,j=t.allocate(V);let I=0;const N=V,E=o?.allocate(N);let b=0,D=0,k=0;x.length=0;for(let s=0;s<V;++s){const e=4*s;c.getVec(p.data[e],i),c.getVec(p.data[e+1],h);const t=x.pushNew();t.index=4*s,t.length=n(i,h)}x.sort(((e,t)=>t.length-e.length));const P=new Array,U=new Array;x.forAll((({length:e,index:n})=>{const w=p.data[n],x=p.data[n+1],V=p.data[n+2],N=p.data[n+3],q=N===d;if(c.getVec(w,i),c.getVec(x,h),q){const e=3*V;s(g,v.data[e],v.data[e+1],v.data[e+2]),a(u,g),y.componentIndex=l.get(w),y.cosAngle=r(g,u)}else{let e=3*V;if(s(g,v.data[e],v.data[e+1],v.data[e+2]),e=3*N,s(u,v.data[e],v.data[e+1],v.data[e+2]),y.componentIndex=l.get(w),y.cosAngle=r(g,u),m(y,M))return;y.cosAngle<-.9999&&a(u,g)}D+=e,k++,q||f(y,L)?(t.write(j,I++,y),P.push(e)):A(y,F)&&(E&&o&&o.write(E,b++,y),U.push(e))}));const q=new Float32Array(P.reverse()),z=new Float32Array(U.reverse()),B=E&&o?{instancesData:E.slice(0,b),lodInfo:{lengths:z}}:void 0;return{regular:{instancesData:j.slice(0,I),lodInfo:{lengths:q}},silhouette:B,averageEdgeLength:D/k}}function f(e,t){return e.cosAngle<t}function m(e,t){return e.cosAngle>t}function A(t,o){const n=e(t.cosAngle);h(N,t.position1,t.position0);return n*(r(l(I,t.faceNormal0,t.faceNormal1),N)>0?-1:1)>o}function w(e){const t=e.faces.length/3,o=e.faces,n=e.neighbors,s=e.vertices.position;V.length=j.length=0;for(let a=0;a<t;a++){const e=3*a,t=n[e],r=n[e+1],h=n[e+2],g=o[e],u=o[e+1],p=o[e+2];s.getVec(g,E),s.getVec(u,b),s.getVec(p,D),c(b,b,E),c(D,D,E),l(E,b,D),i(E,E),j.pushArray(E),(t===d||g<u)&&(V.push(g),V.push(u),V.push(a),V.push(t)),(r===d||u<p)&&(V.push(u),V.push(p),V.push(a),V.push(r)),(h===d||p<g)&&(V.push(p),V.push(g),V.push(a),V.push(h))}return{edges:V,normals:j}}class v{constructor(){this.index=0,this.length=0}}const x=new o({allocator:e=>e||new v,deallocator:null}),V=new o({deallocator:null}),j=new o({deallocator:null}),y=new u,I=g(),N=g(),E=g(),b=g(),D=g(),F=t(4),M=Math.cos(F),k=t(35),L=Math.cos(k);export{p as extractEdges};
5
+ import{acosClamped as e,deg2rad as t}from"../../../../../core/mathUtils.js";import n from"../../../../../core/PooledArray.js";import{j as o,i as s,c as a,e as r,d as c,h as l,n as i,E as h}from"../../../../../chunks/vec32.js";import{create as u}from"../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{Edge as g}from"./Edge.js";const p=-1;function d(e,t,n){const c=e.vertices.position,l=e.vertices.componentIndex,i=I.position0,h=I.position1,u=I.faceNormal0,g=I.faceNormal1,{edges:d,normals:v}=w(e),x=d.length/4,j=t.allocate(x);let y=0;const N=x,E=n?.allocate(N);let b=0,D=0,F=0;V.length=0;for(let s=0;s<x;++s){const e=4*s;c.getVec(d.data[e],i),c.getVec(d.data[e+1],h);const t=V.pushNew();t.index=4*s,t.length=o(i,h)}V.sort(((e,t)=>t.length-e.length));const L=new Array,U=new Array;V.forAll((({length:e,index:o})=>{const w=d.data[o],x=d.data[o+1],V=d.data[o+2],N=d.data[o+3],q=N===p;if(c.getVec(w,i),c.getVec(x,h),q){const e=3*V;s(u,v.data[e],v.data[e+1],v.data[e+2]),a(g,u),I.componentIndex=l.get(w),I.cosAngle=r(u,g)}else{let e=3*V;if(s(u,v.data[e],v.data[e+1],v.data[e+2]),e=3*N,s(g,v.data[e],v.data[e+1],v.data[e+2]),I.componentIndex=l.get(w),I.cosAngle=r(u,g),m(I,k))return;I.cosAngle<-.9999&&a(g,u)}D+=e,F++,q||f(I,P)?(t.write(j,y++,I),L.push(e)):A(I,M)&&(E&&n&&n.write(E,b++,I),U.push(e))}));const q=new Float32Array(L.reverse()),z=new Float32Array(U.reverse()),B=E&&n?{instancesData:E.slice(0,b),lodInfo:{lengths:z}}:void 0;return{regular:{instancesData:j.slice(0,y),lodInfo:{lengths:q}},silhouette:B,averageEdgeLength:D/F}}function f(e,t){return e.cosAngle<t}function m(e,t){return e.cosAngle>t}function A(t,n){const o=e(t.cosAngle);h(E,t.position1,t.position0);return o*(r(l(N,t.faceNormal0,t.faceNormal1),E)>0?-1:1)>n}function w(e){const t=e.faces.length/3,n=e.faces,o=e.neighbors,s=e.vertices.position;j.length=y.length=0;for(let a=0;a<t;a++){const e=3*a,t=o[e],r=o[e+1],h=o[e+2],u=n[e],g=n[e+1],d=n[e+2];s.getVec(u,b),s.getVec(g,D),s.getVec(d,F),c(D,D,b),c(F,F,b),l(b,D,F),i(b,b),y.pushArray(b),(t===p||u<g)&&(j.push(u),j.push(g),j.push(a),j.push(t)),(r===p||g<d)&&(j.push(g),j.push(d),j.push(a),j.push(r)),(h===p||d<u)&&(j.push(d),j.push(u),j.push(a),j.push(h))}return{edges:j,normals:y}}class v{constructor(){this.index=0,this.length=0}}function x(){V.prune(),j.prune(),y.prune()}const V=new n({allocator:e=>e||new v,deallocator:null}),j=new n({deallocator:null}),y=new n({deallocator:null}),I=new g,N=u(),E=u(),b=u(),D=u(),F=u(),M=t(4),k=Math.cos(M),L=t(35),P=Math.cos(L);export{x as cleanupEdgeProcessing,d as extractEdges};