@arcgis/core 4.28.0-next.20230713 → 4.28.0-next.20230714

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 (52) hide show
  1. package/Basemap.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/{08ee2bd914867fd2cbd5.js → 490629c6f9fee501c9cd.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{044b15794b6403792f04.js → 4f079d0e69189c1d8bd9.js} +1 -1
  5. package/assets/esri/core/workers/chunks/{3835a76c017431f19422.js → 51da3c5c50b153ce6bc7.js} +1 -1
  6. package/assets/esri/core/workers/chunks/b694126184f85a832b39.js +1 -0
  7. package/assets/esri/core/workers/chunks/b8a45b28a915a423d09d.js +1 -0
  8. package/assets/esri/core/workers/chunks/{55109f141c9f120833f6.js → c3d773c93efb41088c54.js} +1 -1
  9. package/assets/esri/core/workers/chunks/e433440fecd0114cb23d.js +1 -0
  10. package/assets/esri/themes/base/widgets/_ElevationProfile.scss +3 -0
  11. package/assets/esri/themes/dark/main.css +1 -1
  12. package/assets/esri/themes/light/main.css +1 -1
  13. package/assets/esri/themes/light/view.css +1 -1
  14. package/chunks/RibbonLine.glsl.js +57 -72
  15. package/core/image/apng.js +1 -1
  16. package/core/image/gif.js +1 -1
  17. package/core/urlUtils.js +1 -1
  18. package/interfaces.d.ts +12 -0
  19. package/layers/support/ImageElement.js +1 -1
  20. package/layers/video/VideoController.js +1 -1
  21. package/package.json +1 -1
  22. package/support/BasemapStyle.js +5 -0
  23. package/support/basemapUtils.js +1 -1
  24. package/support/revision.js +1 -1
  25. package/views/2d/engine/webgl/Overlay.js +1 -1
  26. package/views/2d/engine/webgl/animatedFormats/utils.js +1 -1
  27. package/views/3d/analysis/AreaMeasurement/support/AreaMeasurementVisualization.js +1 -1
  28. package/views/3d/analysis/Dimension/DimensionVisualization.js +1 -1
  29. package/views/3d/analysis/DirectLineMeasurement/DirectLineMeasurementVisualization.js +1 -1
  30. package/views/3d/interactive/editingTools/settings.js +1 -1
  31. package/views/3d/layers/graphics/Graphics3DLineSymbolLayer.js +1 -1
  32. package/views/3d/layers/graphics/Graphics3DPolygonFillSymbolLayer.js +1 -1
  33. package/views/3d/terrain/TerrainRenderer.js +1 -1
  34. package/views/3d/terrain/TerrainSurface.js +1 -1
  35. package/views/3d/terrain/Tile.js +1 -1
  36. package/views/3d/terrain/TileRenderer.js +1 -1
  37. package/views/3d/terrain/TileTexture.js +1 -1
  38. package/views/3d/webgl-engine/core/shaderLibrary/shading/LineStipple.glsl.js +12 -13
  39. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  40. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBuffer.js +1 -1
  41. package/views/3d/webgl-engine/lib/edgeRendering/strokes.js +1 -1
  42. package/views/3d/webgl-engine/lib/glUtil3D.js +1 -1
  43. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  44. package/views/3d/webgl-engine/materials/internal/WaterTextureRepository.js +1 -1
  45. package/views/3d/webgl-engine/shaders/HUDMaterialTechnique.js +1 -1
  46. package/views/3d/webgl-engine/shaders/RibbonLineTechniqueConfiguration.js +1 -1
  47. package/views/3d/webgl-engine/statistics/RendererPerformanceInfo.js +1 -1
  48. package/views/webgl/Texture.js +1 -1
  49. package/widgets/ElevationProfile/support/chartUtils.js +1 -1
  50. package/assets/esri/core/workers/chunks/308eeeaec591b4eea1de.js +0 -1
  51. package/assets/esri/core/workers/chunks/498dca81073e1fb477b9.js +0 -1
  52. package/assets/esri/core/workers/chunks/b2a0e3e1dfccda7ed12e.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.28/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 a from"../../../core/Evented.js";import n from"../../../core/Logger.js";import{clamp as l}from"../../../core/mathUtils.js";import{releaseMaybe as o,destroyMaybe as h}from"../../../core/maybe.js";import d from"../../../core/ObjectPool.js";import p from"../../../core/PooledArray.js";import{throwIfAborted as u,isAbortError as c,isAborted as _,createAbortError as g}from"../../../core/promiseUtils.js";import{watch as m,syncAndInitial as T,sync as y,initial as f}from"../../../core/reactiveUtils.js";import{property as v}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import"../../../core/has.js";import{subclass as w}from"../../../core/accessorSupport/decorators/subclass.js";import{m as E}from"../../../chunks/mat4.js";import{c as S}from"../../../chunks/mat4f64.js";import{c as L}from"../../../chunks/vec3.js";import{c as D}from"../../../chunks/vec3f64.js";import{c as P}from"../../../chunks/vec4f64.js";import{UpdatingHandles as b}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as U}from"../../../geometry/ellipsoidUtils.js";import{projectVectorToVector as x,projectPointToVector as R}from"../../../geometry/projection.js";import C from"../../../geometry/SpatialReference.js";import{create as M,equals as j,intersection as A,empty as I,expand as O,intersectsSphere as V}from"../../../geometry/support/aaBoundingRect.js";import{create as B,copy as k}from"../../../geometry/support/frustum.js";import{isPlateCarree as N}from"../../../geometry/support/spatialReferenceUtils.js";import{isRefreshableLayer as q}from"../../../layers/mixins/RefreshableLayer.js";import{ElevationQueryTileCache as F}from"../../../layers/support/ElevationQueryTileCache.js";import{ElevationTileData as G}from"../../../layers/support/ElevationTileData.js";import{isBaseLayer as W}from"../../../layers/support/layerUtils.js";import{acquireDecoder as H}from"../../../layers/support/LercDecoder.js";import{printAllocations as Q}from"../../2d/engine/vectorTiles/VectorTile.js";import{directionToHeadingTilt as z}from"../support/cameraUtils.js";import X from"../support/debugFlags.js";import{toBoundingRect as Y}from"../support/extentUtils.js";import{ClientType as $}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{LODSnapping as ie,TextureUpdate as re}from"./interfaces.js";import{LayerClass as se,LayerClasses as ae}from"./LayerClass.js";import{OverlayManager as ne}from"./OverlayManager.js";import{PlanarPatch as le}from"./PlanarPatch.js";import{RenderOrder as oe}from"./RenderOrder.js";import{ScaleRangeQueries as he}from"./ScaleRangeQueries.js";import{SphericalPatch as de}from"./SphericalPatch.js";import{SplitLimits as pe}from"./SplitLimits.js";import{MAX_ROOT_TILES as ue,TOO_MANY_ROOT_TILES_AFTER_CHANGE_ERROR as ce,TOO_MANY_ROOT_TILES_FOR_LAYER_ERROR as _e,MAX_MEMORY_LOD_BIAS as ge,ELEVATION_NODATA_VALUE as me}from"./TerrainConst.js";import{TerrainRenderer as Te,TransparencyMode as ye}from"./TerrainRenderer.js";import fe from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as ve,internalAssert as we,oppositeEdge as Ee,isSurfaceLayerView as Se,isGroupLayerView as Le,isMapTileLayerView as De,isBlendableLayerView as Pe,isElevationLayerView as be,isVectorTileLayerView as Ue,useFetchTileForLayer as xe,isImageryTileLayerView as Re,isTileLayerView as Ce,releaseTileData as Me,neighborCornerIndices as je,oppositeCorner as Ae,neighborEdgeIndices as Ie,ENABLE_TERRAIN_INTERNAL_CHECKS as Oe,ENABLE_WATERPROOFNESS_TESTS as Ve,enableTerrainInternalChecks as Be,enableTerrainWaterproofnessChecks as ke}from"./terrainUtils.js";import{Tile as Ne}from"./Tile.js";import{printAllocations as qe}from"./TilePerLayerInfo.js";import{TileUpdate as Fe}from"./TileUpdate.js";import{IteratorPreorder as Ge,IteratorPostorder as We,compareTilesByLij as He,hasLoadableSiblings as Qe,sortTilesByPOI as ze,sortTiles as Xe}from"./tileUtils.js";import{TilingSchemeLogic as Ye}from"./TilingSchemeLogic.js";import{UpsampleInfo as $e}from"./UpsampleInfo.js";import{isCompositeBlendMode as Ke,blendModeFromString as Je}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{PBRMode as Ze}from"../webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{RenderRequestType as et}from"../webgl-engine/lib/basicInterfaces.js";import{RenderState as tt}from"../../support/RenderState.js";import{ImmediateTask as it,TaskPriority as rt,noBudget as st}from"../../support/Scheduler.js";let at=class extends(a.EventedMixin(i)){constructor(e){super(e),this._scaleRangeQueries=new he,this._iteratorPool=new d(Ge,(e=>e.remove=()=>this._iteratorPool.release(e))),this._postorderIterator=new We,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._visibleCached=!1,this._usedMemory=null,this._performanceInfo=new fe,this._viewChanged=!1,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=D(),this._eyePosSurfaceSR=D(),this._splitLimits=new pe,this._frustum=B(),this._viewProjectionMatrix=S(),this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new b,this._frameTask=it,this._allTiles=new p,this._upsampleInfoPool=new d($e),this._rootTilesExtent=M(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=C.WebMercator,this.visibleElevationBounds=new J(1/0,-1/0),this.rootTileElevationBounds=new J(1/0,-1/0),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._isWebMercatorOnPlateeCarree=!1,this.overlayManager=new ne({...e,surface:this}),this._isGlobal=!e.view?.state?.isLocal}initialize(){this._lercDecoder=H(this.view.resourceController),this._tilePool=this.view.state.isLocal?new d(le):new d(de);const e=this.view.resourceController.memoryController;this._upsampleMapCache=e.newCache("terrain-upsample",(e=>e.unloadMapData())),this._elevationQueryCache=new F(e.newCache("elevation-query")),this.addHandles([m((()=>this.overlayManager.hasHighlights),(e=>this._renderer.setNeedsHighlight(e))),m((()=>this.overlayManager.rendersOccluded),(e=>this._renderer.setRenderOccludedOverlay(e))),m((()=>this.overlayManager.renderer.isEmpty),(()=>this._evaluateTransparency()))],"overlayManager"),this._renderer=new Te({_overlayRenderer:this.overlayManager.renderer,_ellipsoidRadius:U(this.view.spatialReference).radius,_stage:this.view._stage,_allTiles:this._allTiles}),this.addHandles([m((()=>this.baseOpacity),(()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?re.UNFADED:re.IMMEDIATE)}),T),m((()=>this.hasCompositeBlendMode),(()=>this._updateTileTextures(this._evaluateTransparency()?re.UNFADED:re.IMMEDIATE)),T),m((()=>this.renderingDisabled),(()=>this.view?._stage?.renderer.setParameters({terrainRenderingEnabled:!this.renderingDisabled})),y),m((()=>this.backgroundColor),(e=>{this._handleLayerViewChanges(),this._renderer.updateTileBackground(e)}),T),m((()=>this.snapLevel),(()=>this._viewChanged=!0),y),m((()=>this.view.pointsOfInterest),(e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add((()=>e.focus.renderLocation),(()=>this._allTilesSorted=!1))})),m((()=>X.TERRAIN_TILE_TREE_SHOW_TILES),(e=>{e&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then((({TerrainTileTree3DDebugger:e})=>{!this._treeDebugger&&X.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new e({view:this.view}))})):e||(this._treeDebugger=h(this._treeDebugger))}),f)]);const{spatialReference:t}=this.view;this._extentHelper=te(this.viewingMode,{layers:this.view.map.allLayers,layerViews:this.view.allLayerViews,viewSpatialReference:t});const i=new s({getCollections:()=>this.view?.defaultsFromMap?.mapCollections?.map((({layers:e})=>e)),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),r=new Ye({layers:i,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:t});this._set("tilingSchemeLogic",r),this._updateTilingScheme(),this._elevationDataRequester=this.view.resourceController.createStreamDataRequester($.ELEVATION),this._mapDataRequester=this.view.resourceController.createStreamDataRequester($.BASEMAP);const a=this.view.resourceController.scheduler;this._frameTask=a.registerTask(rt.TERRAIN_SURFACE,this),this.addHandles([m((()=>this._extentHelper.stencilEnabledExtents),(e=>this._renderer.setStencilEnabledLayerExtents(e)),f),m((()=>this.tilingSchemeLogic.tilingScheme),(()=>this._updateTilingScheme()),y),m((()=>this.extent),(()=>this._updateRootTiles()),f),this.view.on("resize",(()=>this._viewChangeUpdate())),m((()=>{const e=this.view,t=e.state;return[this._lodBias,this.lodSnapping,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]}),(()=>this._viewChangeUpdate()),T),m((()=>this.view.qualitySettings?.tiledSurface?.textureFadeDuration),(e=>this._renderer.textureFadingEnabled=e>0),f),m((()=>this.view.qualitySettings?.physicallyBasedRenderingEnabled),(e=>this._renderer.pbrMode=e?Ze.Terrain:Ze.Disabled),f),m((()=>this._userClippingExtent),(()=>this._updateClippingExtent()),y)]),this.addHandles(this.view.allLayerViews.on("after-changes",(()=>this._layerViewsDirty=!0))),this._layerViewsDirty=!0,this._handleLayerViewChanges()}destroy(){this._frameTask.remove(),this._watchUpdatingTracking.destroy(),this._lercDecoder=o(this._lercDecoder),this._removeAllTiles(),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),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._tilePool=h(this._tilePool),Ne.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer=h(this._renderer),this._iteratorPool=h(this._iteratorPool),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),Q(),qe()}get renderer(){return this._renderer}get frustum(){return this._frustum}get snapLevel(){if(this.lodSnapping===ie.ON){const e=this.view,t=this.tilingScheme,i=e.pointsOfInterest?.cameraOnSurface?.scale;if(t&&i){const r=e.state.contentCamera;let s=z(e,r.eye,r.viewForward,r.up).tilt;s>90&&(s=180-s);const a=2*(s/90)**2,n=t.levelAtScale(i)-a,l=Math.min(n+e.qualitySettings.tiledSurface.lodBias,this._splitLimits.maxLod||1/0);return l<=0?null:l}}return null}get lodSnapping(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences?ie.ON:ie.OFF}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get mapTileRequester(){return this._mapDataRequester}get _userClippingExtent(){const{spatialReference:e}=this,{clippingArea:t}=this.view;if(null==t||null==e)return null;const i=M(),r=Y(t,i,e)?i:null,s=this._get("extent");return j(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=A(this.groundExtent,this._userClippingExtent,M()),t=this._get("extent");return j(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)}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())}set _visible(e){e!==this._visibleCached&&(this._visibleCached=e,this._renderer.setVisibility(e),this.suspended=!e)}get opaque(){return this._renderer.transparency===ye.Opaque}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get textureFadeDuration(){return this.view.qualitySettings.tiledSurface.textureFadeDuration??0}intersect(e,t,i,r){this._renderer.intersect(e,t,i,r)}getElevation(e,t,i,r){const s=this._rootTiles;if(null==s||!s.length)return null;if(0===s[0].layerInfo[se.ELEVATION].length)return null;const a=dt;if(a[0]=e,a[1]=t,a[2]=i,!x(a,r,a,this._spatialReference))return n.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;return mt(s,a[0],a[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[se.ELEVATION].length:0;if(null!=r&&r.length&&0!==s)for(let a=0;a<t;++a){const t=3*a;i(a,mt(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getScale(e){if(!this.tilingScheme)return null;if(!R(e,dt,this.spatialReference))return n.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(dt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;dt[0]>t[2]&&(i+=1),dt[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}getSphereElevationBounds(e,t){if(dt[0]=e[0],dt[1]=e[1],dt[2]=e[2],dt[3]=e[3],!x(dt,t,dt,this.tilingScheme?.spatialReference))return n.getLogger(this).error("TerrainSurface.getSphereElevationBounds(): could not project given point to tiling scheme coordinate system"),null;let i=1/0,r=-1/0;const s=e=>{if(e&&V(e.extent,dt))if(e.isLeaf||e.rendered)i=Math.min(i,e.elevationBounds[0]),r=Math.max(r,e.elevationBounds[1]);else for(const t of e.children)s(t)},a=this._rootTiles;if(null!=a)for(const n of a)s(n);return{min:i,max:r}}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!R(e,dt,this.spatialReference))return n.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;dt[3]=t;let i=null;const r=e=>{if(e&&V(e.extent,dt)){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){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._allSurfaceLayersTransparent()?t?ye.Empty:ye.TransparentWithDraped:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?ye.Opaque:ye.Semitransparent,s=i!==r;return s&&(this._renderer.transparency=r,this.view?._stage?.renderer.setParameters({terrainTransparency:this._renderer.transparency})),s}_updateTilingScheme(){const e=this.tilingSchemeLogic.tilingScheme;if(!(e!==this.tilingScheme))return;ve(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??C.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateeCarree=this._isWebMercator&&N(this.view?.renderSpatialReference),this._set("tilingScheme",e),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.setTileSize(e.pixelSize),this.overlayManager.setSpatialReference(e.spatialReference),this._updateRootTiles())}_acquireTile(e,t,i,r){const s=this._tilePool.acquire();return ut[0]=e,ut[1]=t,ut[2]=i,s.init(ut,r,this),s}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{extent:e,tilingScheme:t}=this;if(!t)return;const i=pt;let s=t.rootTilesInExtent(e,i,5*ue);if(null!=this._rootTiles){if(s.length>ue)return void n.getLogger(this).warn(ce);const e=this._rootTiles.map((e=>e.lij)),t=r(e,s,lt);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter((e=>!(t.removed.findIndex((t=>lt(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>ue&&(n.getLogger(this).warn(_e),s=t.rootTilesInExtent(e,i,ue)),this._setRootTiles(s.map((e=>this._newRootTile(e))));j(i,this._rootTilesExtent)||(this._rootTilesExtent=M(i)),this._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.isLoaded&&e.intersectsClippingArea));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(He);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)===Fe.SPLIT}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(Fe.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)}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this._visibleCached&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.extent)&&e.resetPendingUpdate(Fe.GEOMETRY)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Qe(e),i=this.visibleElevationBounds;let r=t?i.min:1/0,s=t?i.max:-1/0;const a=this.extent,n=this._viewProjectionMatrix;this.setTileTreeDirty();const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(Fe.GEOMETRY)&&this._updateTileGeometryState(e),e.setPendingUpdate(Fe.RENDERDATA),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBounds[0],r),s=Math.max(e.elevationBounds[1],s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._batchUpdatePendingTileGeometries(),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((({elevationBounds:i})=>{e=Math.min(e,i[0]),t=Math.max(t,i[1])}));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?(null==this._splitLimits.frustum&&(this._splitLimits.frustum=B()),k(this._splitLimits.frustum,t.frustum)):this._splitLimits.frustum=null,k(this._frustum,e.frustum),E(this._viewProjectionMatrix,t.projectionMatrix,t.viewMatrix),L(this._eyePosRenderSR,t.eye),x(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateRenderData(e){e.rendered&&!e.shouldLoad&&(ot(e)?this._loadChildren(e):ht(e)&&this._loadParent(e))}_updateTileGeometryState(e){e.updateVisibility();this._renderer.updateTileGeometryState(e)&&this._markTileToUpdate(e),this._usedMemory=null}_markAllTileNeighborsForGeometryUpdate(e){const t=this._pendingTilesToUpdate;e.forEachLoadedNeighbor((e=>{t.add(e)}))}_updateTileTexture(e,t){const i=e.resetPendingUpdate(Fe.TEXTURE_FADING)?Fe.TEXTURE_FADING:!!e.resetPendingUpdate(Fe.TEXTURE_NOFADING)&&Fe.TEXTURE_NOFADING;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){const e=_t.extent;I(e),this._pendingTilesForElevationUpdateEvent.forEach((t=>O(e,t.extent,e))),this._pendingTilesForElevationUpdateEvent.clear(),_t.spatialReference=this.spatialReference,this.emit("elevation-change",_t)}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;this._mergeAndSplit(e,t),this._updateElevation(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty(),this._batchUpdatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&e.hasProgressed&&this.requestUpdate(),this.notifyChange("updatingProgressValue")}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;const t=this._iteratorPool.acquire();t.reset(this._rootTiles);const i=this.snapLevel,r=this._splitLimits,s=this._eyePosRenderSR;for(;!t.done;){const e=t.next(),a=e.shouldSplit(r,s,i);if(a!==Fe.SPLIT){if(e.resetPendingUpdate(Fe.SPLIT)&&e.updateAgentSuspension(),a===Fe.ELEVATION&&e.updateAgents(se.ELEVATION),t.skipSubtree(),!e.isLeaf){e.setPendingUpdate(Fe.MERGE),e.resetPendingUpdate(Fe.SPLIT);const t=this._iteratorPool.acquire();t.resetOne(e);const i=this._viewProjectionMatrix;for(let e=t.next();!t.done;e=t.next())this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(i);t.remove()}}else e.resetPendingUpdate(Fe.MERGE),e.isLeaf&&(e.setPendingUpdate(Fe.SPLIT),t.skipSubtree()),e.rendered&&e.setPendingUpdate(Fe.RENDERDATA)}t.remove(),this.requestUpdate(),(this.shortBatches||!this.oneBatchPerFrameTask)&&this._batchUpdatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||(ze(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger&&this._treeDebugger.update(),e.madeProgress())}_markTileToUpdate(e){we(e.isLoaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForGeometryUpdate(e))}_batchUpdatePendingTileGeometries(){const e=this._pendingTilesToUpdate;if(0===e.size)return;const t=Array.from(this._pendingTilesToUpdate.keys()).filter((e=>e.isLoaded&&e.intersectsClippingArea)),i=(i,r)=>{!r?.isLoaded||!r.intersectsClippingArea||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(He);const r=t.length;for(let s=0;s<r;++s){const r=t[s];we(r.isLoaded),we(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a._dirtyEdgeResolutions,l=a.geometryState.neighborData.cornerPeerNeighbors,o=e=>{const t=je[e];i(r,l[e]?.findCorner(Ae(t),(e=>e.isLoaded)))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.neighborData.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(Ee(Ie[t]),(t=>!(!t.isLoaded||!t.intersectsClippingArea)&&(we(e.has(t)||He(r,t)<0),i(r,t),!0))),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),Oe&&Ve&&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.resetPendingUpdate(Fe.MERGE)){if(!t)return s.setPendingUpdate(Fe.MERGE),e.done;for(;n.parent?.resetPendingUpdate(Fe.MERGE);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else s.resetPendingUpdate(Fe.SPLIT)&&(this._splitTile(s),a=!0,e.madeProgress());return!e.done&&n===s&&s.resetPendingUpdate(Fe.RENDERDATA)&&(this._updateRenderData(s),e.madeProgress()),e.done}));if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this.oneBatchPerFrameTask&&this._batchUpdatePendingTileGeometries(),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some((t=>(t.resetPendingUpdate(Fe.GEOMETRY)&&(this._updateTileGeometryState(t),this._updateTileTexture(t,e),this.shortBatches&&this._batchUpdatePendingTileGeometries(),e.madeProgress()),e.done))),!this.oneBatchPerFrameTask&&this._batchUpdatePendingTileGeometries())}_updateTextures(e){e.done||this._allTiles.some((t=>(this._updateTileTexture(t,e),e.done)))}_updateClippingExtent(){this.spatialReference&&(this.updateTileOverlayParams(et.UPDATE),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){const e=this.view.quality;return this.view.qualitySettings.tiledSurface.lodBias-(1-e)*ge}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=l(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._visible=!1}_purgeDescendantTiles(e){if(!e.children[0])return!1;let t=!1;for(let i=0;i<4;++i)t=this._purgeTile(e.children[i])||t;return e.unsetChildren(),t}_purgeTile(e){const t=this._purgeDescendantTiles(e)||e.rendered;return this._allTiles.removeUnordered(e),this._unloadTile(e),this._tilePool.release(e),t}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload(this._renderer)}_splitTile(e){ve(e.isLeaf,"tile that is already split should not be split again!");const t=e.level+1,i=2*e.lij[1],r=2*e.lij[2];e.setChildren(this._createTile(t,i,r,e),this._createTile(t,i,r+1,e),this._createTile(t,i+1,r,e),this._createTile(t,i+1,r+1,e)),e.setPendingUpdate(Fe.RENDERDATA),e.updateAgentSuspension(),this._allTiles.pushArray(e.children),this._allTilesDirty=!0,++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){gt.spatialReference=this.spatialReference,gt.extent=e.extent,gt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",gt)}_createTile(e,t,i,r){ve(!!r,"_createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.extent),s.updateScreenDepth(this._viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(Fe.SPLIT),s}get shortBatches(){return this.view.state.mode!==tt.IDLE}_mergeTile(e){ve(!e.hasPendingUpdate(Fe.SPLIT),"_mergeTile sanity check"),this._purgeDescendantTiles(e)&&(ve(!e.renderData,"_mergeTile sanity check"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this.shortBatches&&this._batchUpdatePendingTileGeometries()),this._allTilesDirty=!0,++this._performanceInfo.numMerged}_loadChildren(e){ve(e.rendered,"parent should be rendered"),this._unloadTile(e);const t=e.children;t.forEach((e=>this._loadTile(e))),t.forEach((e=>this._pendingTilesToUpdate.add(e))),this._markAllTileNeighborsForGeometryUpdate(e),this._emitTileScaleChange(e,e.level+1),this.shortBatches&&this._batchUpdatePendingTileGeometries()}_loadParent(e){const t=e.parent;this._unloadChildren(t),this._loadTile(t),this._markTileToUpdate(t),this._emitTileScaleChange(t,t.level),this.shortBatches&&this._batchUpdatePendingTileGeometries()}_unloadChildren(e){const t=e.children;if(t[0])for(let i=0;i<4;++i){const e=t[i];this._unloadChildren(e),this._unloadTile(e)}}_loadTile(e){e.load(),e.setPendingUpdate(Fe.RENDERDATA),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager&&this.overlayManager.hasOverlays&&this.overlayManager.setTileParameters(e)}_elevationDataArrived(e,t,i){const r=new Z(e.lij,e.extent,i);e.dataArrived(t,se.ELEVATION,r);const s=[e],a=e.level,n=this._iteratorPool.acquire();for(n.reset(s);!n.done;){const e=n.next();e.findElevationBoundsForLayer(t,a),e.computeElevationBounds()}0===a&&this._updateRootTileElevationBounds(),n.remove(),this._updateTilesVisibility(s)}_handleLayerViewChanges(e=st){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(const s of this.view.allLayerViews.items)if(i.add(s.uid),Se(s)||Le(s))if(this._basemapLayerViewHandles.has(s.uid)&&!Le(s)){const e=this._layerClassFromLayerView(s),i=this._getLayerIdxByUID(e,s.uid);null!=i&&((i<r||null==r)&&(t=!0),r=i)}else this._registerTiledLayerView(s),s.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()}_allSurfaceLayersTransparent(){let e=0===this.view.map?.ground?.opacity;for(const t of this.view.allLayerViews.items)if(De(t)&&!W(t.layer)&&0!==t.fullOpacity)return e=!1,e;return e}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((Pe(e)||Le(e))&&Ke(Je[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return be(e)?se.ELEVATION:se.MAP}_registerTiledLayerView(e){const t=[];if((Pe(e)||Le(e))&&t.push(m((()=>e.layer.blendMode),(()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(re.UNFADED)}))),!Le(e)){const i=this._layerClassFromLayerView(e);t.push(m((()=>e.suspended),(()=>this._updateTiledLayers()))),t.push(m((()=>e.fullOpacity),(()=>this._updateTileTextures(re.UNFADED)))),t.push(m((()=>"effectiveScaleRange"in e.layer?e.layer.effectiveScaleRange:null),(()=>this._restartAllAgents(i)))),t.push(e.on("data-changed",(()=>{const t=this._getLayerIdxByUID(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||!Se(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(r===se.MAP){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)}));for(const r of ae){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()}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),e===se.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(se.MAP),e===re.IMMEDIATE?this.renderer.updateTileTexture(t,Fe.TEXTURE_NOFADING):t.updateRenderData(se.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=et.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||Ue(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.lij[0],e.lij[1],e.lij[2],{...r,timeout:6e3}).then((()=>--this._asyncWorkItems)).catch((t=>{throw--this._asyncWorkItems,u(r),c(t)||this._dataMissing(e,i,s,{notInTilemap:!0}),t})).then((()=>this._frameTask.schedule((()=>this._requestTileData(e,i,s,r)),r.signal))))}_requestTileData(e,t,i,r){return t===se.ELEVATION?be(i)?this._requestElevationTileData(e,i,r):Promise.reject():De(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{if(_(i))return;const s=this._layerIndexByUid[se.ELEVATION].get(t.uid);null!=s?(this._usedMemory=null,this.requestUpdate(),this._elevationDataArrived(e,s,r)):n.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",se.ELEVATION,e.lij.toString())},s=i=>{c(i)||(this._dataMissing(e,se.ELEVATION,t,i),this.requestUpdate())};if(xe(t.layer))return t.layer.fetchTile(e.lij[0],e.lij[1],e.lij[2],{noDataValue:me,signal:i.signal}).then((e=>{if(!_(i))return this._frameTask.schedule((()=>r(e)),i.signal,s);n.getLogger(this).warnOnce("A call to fetchTile resolved even though the request was aborted. fetchTile should not resolve if options.signal.aborted is true.")}),s).finally((()=>{--this._asyncWorkItems}));const a=t.getTileUrl(e.lij[0],e.lij[1],e.lij[2]);return this._elevationDataRequester.request(a,"binary",i).then((e=>this._lercDecoder.decode(e,{noDataValue:me},i.signal))).then((e=>{e?r(new G(e)):s(new Error("LERC decoding failed"))}),s).finally((()=>{--this._asyncWorkItems}))}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{--this._asyncWorkItems,Me(s),_(i)||(this._dataMissing(e,se.MAP,t,r),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule((()=>{--this._asyncWorkItems,this.requestUpdate(),_(i)?Me(r):this._mapTileDataArrived(e,t,r)}),i.signal,s(r)).catch(s(r)),l=(e,t=null)=>this._frameTask.schedule((()=>r(e,t)));if(Ue(t)){const r=t.schemaHelper.getLevelRowColumn(e.lij);return t.fetchTile(r[0],r[1],r[2],i).then(a,l)}if(Re(t))return t.fetchTile(e.lij[0],e.lij[1],e.lij[2],i).then(a,l);if(Ce(t)&&xe(t.layer))return t.layer.fetchTile(e.lij[0],e.lij[1],e.lij[2],i).then((e=>{if(_(i))return n.getLogger(this).warnOnce("A call to fetchTile resolved even though the request was aborted. fetchTile should not resolve if options.signal.aborted is true."),void l(g());a(e)}),l);let o=t.getTileUrl(e.lij[0],e.lij[1],e.lij[2]);q(t.layer)&&t.layer.refreshTimestamp&&(o+=`${o.includes("?")?"&":"?"}_ts=${t.layer.refreshTimestamp}`);const h=t.hasMixedImageFormats?"image+type":"image";return this._mapDataRequester.request(o,h,i).then(a,l)}_mapTileDataArrived(e,t,i){const r=this._getLayerIdxByUID(se.MAP,t.uid);null!=r?e.dataArrived(r,se.MAP,i):(Me(i),n.getLogger(this).warn("TerrainSurface: received data from unknown layer"))}_getLayerIdxByUID(e,t){return this._layerIndexByUid[e].get(t)}_dataMissing(e,t,i,r){const s=this._getLayerIdxByUID(t,i.uid);null!=s?e.dataMissing(s,t,r):n.getLogger(this).warn("TerrainSurface: received data from unknown layer")}updateTileOverlayParams(e){this._rootTiles&&this.overlayManager&&(this._allTiles.forAll((e=>{e.renderData&&this.overlayManager.setTileParameters(e)})),this._renderer.setNeedsRender(e))}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.isLeaf&&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}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),this.overlayManager.usedMemory)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this._getLayerIdxByUID(i,e.uid);return null!=r&&this._allTiles.forAll((e=>t+=e.getUsedMemoryForLayer(i,r))),t}getTile(e){if(null==e||null==this._rootTiles)return null;const t=e.split("/").map((e=>+e));if(0===t[0])return this._rootTiles.find((e=>e.lij[1]===t[1]&&e.lij[2]===t[2]));const i=2**t[0],r=Math.floor(t[1]/i),s=Math.floor(t[2]/i);let a;if(this._rootTiles.some((e=>e.lij[1]===r&&e.lij[2]===s&&(a=e,!0))),a){let e=1<<t[0]-1;for(;a.lij[0]<t[0];){let i=t[1]&e?2:0;if((t[2]&e)>0&&i++,!a.children[i])return null;a=a.children[i],e>>=1}return ve(a.lij[0]===t[0]&&a.lij[1]===t[1]&&a.lij[2]===t[2],"not the right tile?"),a}return null}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(){const e=this;return{renderer:e._renderer,lercDecoder:e._lercDecoder,forceReload:()=>{null!=e._rootTiles&&e._rootTiles.length>0&&(e._mergeTile(e._rootTiles[0]),e._viewChangeUpdate())},getTiles:()=>e._allTiles.toArray(),getRenderedTiles(){ct.clear(),e._allTiles.forAll((e=>{e.visible&&e.rendered&&ct.push(e)}));const t=ct.toArray();return Xe(e.renderOrder,t),t},lockTilingScheme(t,i){e._extentHelper.defaultTiledLayersExtent=i,e.tilingSchemeLogic.test.lockTilingScheme(t)}}}checkAllTilesWaterproofness(){if(!Ve)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.isLeaf)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.isLeaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateeCarree(){return this._isWebMercatorOnPlateeCarree}isEastEndWrap(e){return this.isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this.isGlobal&&0===e[2]}lijEastEnd(e){return 2**(e+(null!=this.spatialReference&&this.spatialReference.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){Be(e)}enableWaterproofnessChecks(e){ke(e)}};e([v()],at.prototype,"_renderer",void 0),e([v({constructOnly:!0})],at.prototype,"_scaleRangeQueries",void 0),e([v({constructOnly:!0})],at.prototype,"view",void 0),e([v({constructOnly:!0})],at.prototype,"overlayManager",void 0),e([v()],at.prototype,"_hasPendingUpdates",void 0),e([v()],at.prototype,"_asyncWorkItems",void 0),e([v()],at.prototype,"_allTilesDirty",void 0),e([v()],at.prototype,"_allTilesSorted",void 0),e([v()],at.prototype,"_viewChanged",void 0),e([v()],at.prototype,"_splitLimits",void 0),e([v({readOnly:!0})],at.prototype,"_watchUpdatingTracking",void 0),e([v()],at.prototype,"_frameTask",void 0),e([v({readOnly:!0})],at.prototype,"snapLevel",null),e([v({readOnly:!0})],at.prototype,"lodSnapping",null),e([v()],at.prototype,"_userClippingExtent",null),e([v()],at.prototype,"_rootTilesExtent",void 0),e([v({readOnly:!0})],at.prototype,"extent",null),e([v({readOnly:!0})],at.prototype,"groundExtent",null),e([v({readOnly:!0})],at.prototype,"_tilingSchemeExtent",null),e([v({readOnly:!0})],at.prototype,"updating",null),e([v({readOnly:!0})],at.prototype,"running",null),e([v(K)],at.prototype,"updatingProgress",void 0),e([v({readOnly:!0})],at.prototype,"updatingProgressValue",null),e([v()],at.prototype,"_maxNumUpdating",void 0),e([v()],at.prototype,"baseOpacity",null),e([v()],at.prototype,"hasCompositeBlendMode",void 0),e([v({readOnly:!0})],at.prototype,"viewingMode",null),e([v()],at.prototype,"maxTextureScale",void 0),e([v({readOnly:!0})],at.prototype,"ready",null),e([v({value:oe.FRONT_TO_BACK})],at.prototype,"renderOrder",null),e([v({readOnly:!0})],at.prototype,"rootTiles",null),e([v()],at.prototype,"_rootTiles",void 0),e([v({readOnly:!0})],at.prototype,"spatialReference",null),e([v({type:t})],at.prototype,"backgroundColor",null),e([v({value:!1})],at.prototype,"slicePlaneEnabled",null),e([v({readOnly:!0})],at.prototype,"tilingScheme",void 0),e([v({readOnly:!0})],at.prototype,"tilingSchemeLocked",null),e([v({readOnly:!0})],at.prototype,"tilingSchemeLogic",void 0),e([v()],at.prototype,"wireframe",null),e([v({value:!1})],at.prototype,"suspended",null),e([v()],at.prototype,"textureFadeDuration",null),e([v()],at.prototype,"visibleElevationBounds",void 0),e([v()],at.prototype,"rootTileElevationBounds",void 0),e([v()],at.prototype,"_layerViewsDirty",void 0),e([v()],at.prototype,"renderPatchBorders",null),e([v()],at.prototype,"visualizeNormals",null),e([v()],at.prototype,"renderingDisabled",null),at=e([w("esri.views.3d.terrain.TerrainSurface")],at);const nt=at;function lt(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function ot(e){const t=e.children;if(!t[0])return!1;for(const i of t)if(i.shouldLoad)return!0;for(const i of t)if(ot(i))return!0;return!1}function ht(e){return e.isLeaf&&(e.parent?.shouldLoad??!1)}const dt=P(),pt=M(),ut=[0,0,0],ct=new p,_t={spatialReference:null,extent:M(),context:"ground"},gt={spatialReference:null,extent:null,scale:0};function mt(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}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 a from"../../../core/Evented.js";import n from"../../../core/Logger.js";import{clamp as l}from"../../../core/mathUtils.js";import{releaseMaybe as o,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 _,isAborted as g,createAbortError as m}from"../../../core/promiseUtils.js";import{watch as T,syncAndInitial as y,sync as f,initial as v}from"../../../core/reactiveUtils.js";import{property as w}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import"../../../core/has.js";import{subclass as E}from"../../../core/accessorSupport/decorators/subclass.js";import{m as S}from"../../../chunks/mat4.js";import{c as L}from"../../../chunks/mat4f64.js";import{c as D}from"../../../chunks/vec3.js";import{c as P}from"../../../chunks/vec3f64.js";import{c as b}from"../../../chunks/vec4f64.js";import{UpdatingHandles as x}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as U}from"../../../geometry/ellipsoidUtils.js";import{projectVectorToVector as R,projectPointToVector as C}from"../../../geometry/projection.js";import M from"../../../geometry/SpatialReference.js";import{create as j,equals as A,intersection as I,empty as O,expand as V,intersectsSphere as B}from"../../../geometry/support/aaBoundingRect.js";import{create as k,copy as N}from"../../../geometry/support/frustum.js";import{isPlateCarree as q}from"../../../geometry/support/spatialReferenceUtils.js";import{isRefreshableLayer as F}from"../../../layers/mixins/RefreshableLayer.js";import{ElevationQueryTileCache as G}from"../../../layers/support/ElevationQueryTileCache.js";import{ElevationTileData as W}from"../../../layers/support/ElevationTileData.js";import{isBaseLayer as H}from"../../../layers/support/layerUtils.js";import{acquireDecoder as Q}from"../../../layers/support/LercDecoder.js";import{printAllocations as z}from"../../2d/engine/vectorTiles/VectorTile.js";import{directionToHeadingTilt as X}from"../support/cameraUtils.js";import Y from"../support/debugFlags.js";import{toBoundingRect as $}from"../support/extentUtils.js";import{ClientType as K}from"../support/index.js";import{updatingProgress as J}from"../support/updatingProperties.js";import{ElevationBounds as Z}from"./ElevationBounds.js";import{ElevationData as ee,sampleElevation as te}from"./ElevationData.js";import{create as ie}from"./ExtentHelper.js";import{LODSnapping as re,TextureUpdate as se}from"./interfaces.js";import{LayerClass as ae,LayerClasses as ne}from"./LayerClass.js";import{OverlayManager as le}from"./OverlayManager.js";import{PlanarPatch as oe}from"./PlanarPatch.js";import{RenderOrder as he}from"./RenderOrder.js";import{ScaleRangeQueries as de}from"./ScaleRangeQueries.js";import{SphericalPatch as pe}from"./SphericalPatch.js";import{SplitLimits as ue}from"./SplitLimits.js";import{MAX_ROOT_TILES as ce,TOO_MANY_ROOT_TILES_AFTER_CHANGE_ERROR as _e,TOO_MANY_ROOT_TILES_FOR_LAYER_ERROR as ge,MAX_MEMORY_LOD_BIAS as me,ELEVATION_NODATA_VALUE as Te}from"./TerrainConst.js";import{TerrainRenderer as ye,TransparencyMode as fe}from"./TerrainRenderer.js";import ve from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as we,internalAssert as Ee,oppositeEdge as Se,isSurfaceLayerView as Le,isGroupLayerView as De,isMapTileLayerView as Pe,isBlendableLayerView as be,isElevationLayerView as xe,isVectorTileLayerView as Ue,useFetchTileForLayer as Re,isImageryTileLayerView as Ce,isTileLayerView as Me,releaseTileData as je,neighborCornerIndices as Ae,oppositeCorner as Ie,neighborEdgeIndices as Oe,ENABLE_TERRAIN_INTERNAL_CHECKS as Ve,ENABLE_WATERPROOFNESS_TESTS as Be,enableTerrainInternalChecks as ke,enableTerrainWaterproofnessChecks as Ne}from"./terrainUtils.js";import{Tile as qe}from"./Tile.js";import{printAllocations as Fe}from"./TilePerLayerInfo.js";import{TileUpdate as Ge}from"./TileUpdate.js";import{IteratorPreorder as We,IteratorPostorder as He,compareTilesByLij as Qe,hasLoadableSiblings as ze,sortTilesByPOI as Xe,sortTiles as Ye}from"./tileUtils.js";import{TilingSchemeLogic as $e}from"./TilingSchemeLogic.js";import{UpsampleInfo as Ke}from"./UpsampleInfo.js";import{isCompositeBlendMode as Je,blendModeFromString as Ze}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{PBRMode as et}from"../webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{RenderRequestType as tt}from"../webgl-engine/lib/basicInterfaces.js";import{RenderState as it}from"../../support/RenderState.js";import{ImmediateTask as rt,TaskPriority as st,noBudget as at}from"../../support/Scheduler.js";let nt=class extends(a.EventedMixin(i)){constructor(e){super(e),this._scaleRangeQueries=new de,this._iteratorPool=new p(We,(e=>e.remove=()=>this._iteratorPool.release(e))),this._postorderIterator=new He,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._visibleCached=!1,this._usedMemory=null,this._performanceInfo=new ve,this._viewChanged=!1,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=P(),this._eyePosSurfaceSR=P(),this._splitLimits=new ue,this._frustum=k(),this._viewProjectionMatrix=L(),this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new x,this._frameTask=rt,this._allTiles=new u,this._upsampleInfoPool=new p(Ke),this._rootTilesExtent=j(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=M.WebMercator,this.visibleElevationBounds=new Z(1/0,-1/0),this.rootTileElevationBounds=new Z(1/0,-1/0),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._isWebMercatorOnPlateeCarree=!1,this.overlayManager=new le({...e,surface:this}),this._isGlobal=!e.view?.state?.isLocal}initialize(){this._lercDecoder=Q(this.view.resourceController),this._tilePool=this.view.state.isLocal?new p(oe):new p(pe);const e=this.view.resourceController.memoryController;this._upsampleMapCache=e.newCache("terrain-upsample",(e=>e.unloadMapData())),this._elevationQueryCache=new G(e.newCache("elevation-query")),this._tileTextureCache=new d(((t,i)=>e.newCache(t,i)),"TileTexture"),this.addHandles([T((()=>this.overlayManager.hasHighlights),(e=>this._renderer.setNeedsHighlight(e))),T((()=>this.overlayManager.rendersOccluded),(e=>this._renderer.setRenderOccludedOverlay(e))),T((()=>this.overlayManager.renderer.isEmpty),(()=>this._evaluateTransparency()))],"overlayManager"),this._renderer=new ye({_overlayRenderer:this.overlayManager.renderer,_ellipsoidRadius:U(this.view.spatialReference).radius,_stage:this.view._stage,_allTiles:this._allTiles,_cache:this._tileTextureCache}),this.addHandles([T((()=>this.baseOpacity),(()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?se.UNFADED:se.IMMEDIATE)}),y),T((()=>this.hasCompositeBlendMode),(()=>this._updateTileTextures(this._evaluateTransparency()?se.UNFADED:se.IMMEDIATE)),y),T((()=>this.renderingDisabled),(()=>this.view?._stage?.renderer.setParameters({terrainRenderingEnabled:!this.renderingDisabled})),f),T((()=>this.backgroundColor),(e=>{this._handleLayerViewChanges(),this._renderer.updateTileBackground(e)}),y),T((()=>this.snapLevel),(()=>this._viewChanged=!0),f),T((()=>this.view.pointsOfInterest),(e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add((()=>e.focus.renderLocation),(()=>this._allTilesSorted=!1))})),T((()=>Y.TERRAIN_TILE_TREE_SHOW_TILES),(e=>{e&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then((({TerrainTileTree3DDebugger:e})=>{!this._treeDebugger&&Y.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new e({view:this.view}))})):e||(this._treeDebugger=h(this._treeDebugger))}),v)]);const{spatialReference:t}=this.view;this._extentHelper=ie(this.viewingMode,{layers:this.view.map.allLayers,layerViews:this.view.allLayerViews,viewSpatialReference:t});const i=new s({getCollections:()=>this.view?.defaultsFromMap?.mapCollections?.map((({layers:e})=>e)),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),r=new $e({layers:i,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:t});this._set("tilingSchemeLogic",r),this._updateTilingScheme(),this._elevationDataRequester=this.view.resourceController.createStreamDataRequester(K.ELEVATION),this._mapDataRequester=this.view.resourceController.createStreamDataRequester(K.BASEMAP);const a=this.view.resourceController.scheduler;this._frameTask=a.registerTask(st.TERRAIN_SURFACE,this),this.addHandles([T((()=>this._extentHelper.stencilEnabledExtents),(e=>this._renderer.setStencilEnabledLayerExtents(e)),v),T((()=>this.tilingSchemeLogic.tilingScheme),(()=>this._updateTilingScheme()),f),T((()=>this.extent),(()=>this._updateRootTiles()),v),this.view.on("resize",(()=>this._viewChangeUpdate())),T((()=>{const e=this.view,t=e.state;return[this._lodBias,this.lodSnapping,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]}),(()=>this._viewChangeUpdate()),y),T((()=>this.view.qualitySettings?.tiledSurface?.textureFadeDuration),(e=>this._renderer.textureFadingEnabled=e>0),v),T((()=>this.view.qualitySettings?.physicallyBasedRenderingEnabled),(e=>this._renderer.pbrMode=e?et.Terrain:et.Disabled),v),T((()=>this._userClippingExtent),(()=>this._updateClippingExtent()),f)]),this.addHandles(this.view.allLayerViews.on("after-changes",(()=>this._layerViewsDirty=!0))),this._layerViewsDirty=!0,this._handleLayerViewChanges()}destroy(){this._frameTask.remove(),this._watchUpdatingTracking.destroy(),this._lercDecoder=o(this._lercDecoder),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._tilePool=h(this._tilePool),qe.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer=h(this._renderer),this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._tileTextureCache=h(this._tileTextureCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),z(),Fe()}get renderer(){return this._renderer}get frustum(){return this._frustum}get snapLevel(){if(this.lodSnapping===re.ON){const e=this.view,t=this.tilingScheme,i=e.pointsOfInterest?.cameraOnSurface?.scale;if(t&&i){const r=e.state.contentCamera;let s=X(e,r.eye,r.viewForward,r.up).tilt;s>90&&(s=180-s);const a=2*(s/90)**2,n=t.levelAtScale(i)-a,l=Math.min(n+e.qualitySettings.tiledSurface.lodBias,this._splitLimits.maxLod||1/0);return l<=0?null:l}}return null}get lodSnapping(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences?re.ON:re.OFF}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get mapTileRequester(){return this._mapDataRequester}get _userClippingExtent(){const{spatialReference:e}=this,{clippingArea:t}=this.view;if(null==t||null==e)return null;const i=j(),r=$(t,i,e)?i:null,s=this._get("extent");return A(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get extent(){const e=I(this.groundExtent,this._userClippingExtent,j()),t=this._get("extent");return A(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)}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())}set _visible(e){e!==this._visibleCached&&(this._visibleCached=e,this._renderer.setVisibility(e),this.suspended=!e)}get opaque(){return this._renderer.transparency===fe.Opaque}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get textureFadeDuration(){return this.view.qualitySettings.tiledSurface.textureFadeDuration??0}intersect(e,t,i,r){this._renderer.intersect(e,t,i,r)}getElevation(e,t,i,r){const s=this._rootTiles;if(null==s||!s.length)return null;if(0===s[0].layerInfo[ae.ELEVATION].length)return null;const a=pt;if(a[0]=e,a[1]=t,a[2]=i,!R(a,r,a,this._spatialReference))return n.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;return Tt(s,a[0],a[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[ae.ELEVATION].length:0;if(null!=r&&r.length&&0!==s)for(let a=0;a<t;++a){const t=3*a;i(a,Tt(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getScale(e){if(!this.tilingScheme)return null;if(!C(e,pt,this.spatialReference))return n.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(pt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;pt[0]>t[2]&&(i+=1),pt[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}getSphereElevationBounds(e,t){if(pt[0]=e[0],pt[1]=e[1],pt[2]=e[2],pt[3]=e[3],!R(pt,t,pt,this.tilingScheme?.spatialReference))return n.getLogger(this).error("TerrainSurface.getSphereElevationBounds(): could not project given point to tiling scheme coordinate system"),null;let i=1/0,r=-1/0;const s=e=>{if(e&&B(e.extent,pt))if(e.isLeaf||e.rendered)i=Math.min(i,e.elevationBounds[0]),r=Math.max(r,e.elevationBounds[1]);else for(const t of e.children)s(t)},a=this._rootTiles;if(null!=a)for(const n of a)s(n);return{min:i,max:r}}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!C(e,pt,this.spatialReference))return n.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;pt[3]=t;let i=null;const r=e=>{if(e&&B(e.extent,pt)){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){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._allSurfaceLayersTransparent()?t?fe.Empty:fe.TransparentWithDraped:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?fe.Opaque:fe.Semitransparent,s=i!==r;return s&&(this._renderer.transparency=r,this.view?._stage?.renderer.setParameters({terrainTransparency:this._renderer.transparency})),s}_updateTilingScheme(){const e=this.tilingSchemeLogic.tilingScheme;if(!(e!==this.tilingScheme))return;we(!!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._isWebMercatorOnPlateeCarree=this._isWebMercator&&q(this.view?.renderSpatialReference),this._set("tilingScheme",e),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.setTileSize(e.pixelSize),this.overlayManager.setSpatialReference(e.spatialReference),this._updateRootTiles())}_acquireTile(e,t,i,r){const s=this._tilePool.acquire();return ct[0]=e,ct[1]=t,ct[2]=i,s.init(ct,r,this),s}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{extent:e,tilingScheme:t}=this;if(!t)return;const i=ut;let s=t.rootTilesInExtent(e,i,5*ce);if(null!=this._rootTiles){if(s.length>ce)return void n.getLogger(this).warn(_e);const e=this._rootTiles.map((e=>e.lij)),t=r(e,s,ot);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter((e=>!(t.removed.findIndex((t=>ot(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>ce&&(n.getLogger(this).warn(ge),s=t.rootTilesInExtent(e,i,ce)),this._setRootTiles(s.map((e=>this._newRootTile(e))));A(i,this._rootTilesExtent)||(this._rootTilesExtent=j(i)),this._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.isLoaded&&e.intersectsClippingArea));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(Qe);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)===Ge.SPLIT}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(Ge.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)}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this._visibleCached&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.extent)&&e.resetPendingUpdate(Ge.GEOMETRY)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=ze(e),i=this.visibleElevationBounds;let r=t?i.min:1/0,s=t?i.max:-1/0;const a=this.extent,n=this._viewProjectionMatrix;this.setTileTreeDirty();const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(Ge.GEOMETRY)&&this._updateTileGeometryState(e),e.setPendingUpdate(Ge.RENDERDATA),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBounds[0],r),s=Math.max(e.elevationBounds[1],s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._batchUpdatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.min!==r||i.max!==s)&&(this.visibleElevationBounds=new Z(r,s))}_updateRootTileElevationBounds(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach((({elevationBounds:i})=>{e=Math.min(e,i[0]),t=Math.max(t,i[1])}));const r=this.rootTileElevationBounds;r.min===e&&r.max===t||(this.rootTileElevationBounds=new Z(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?(null==this._splitLimits.frustum&&(this._splitLimits.frustum=k()),N(this._splitLimits.frustum,t.frustum)):this._splitLimits.frustum=null,N(this._frustum,e.frustum),S(this._viewProjectionMatrix,t.projectionMatrix,t.viewMatrix),D(this._eyePosRenderSR,t.eye),R(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateRenderData(e){e.rendered&&!e.shouldLoad&&(ht(e)?this._loadChildren(e):dt(e)&&this._loadParent(e))}_updateTileGeometryState(e){e.updateVisibility();this._renderer.updateTileGeometryState(e)&&this._markTileToUpdate(e),this._usedMemory=null}_markAllTileNeighborsForGeometryUpdate(e){const t=this._pendingTilesToUpdate;e.forEachLoadedNeighbor((e=>{t.add(e)}))}_updateTileTexture(e,t){const i=e.resetPendingUpdate(Ge.TEXTURE_FADING)?Ge.TEXTURE_FADING:!!e.resetPendingUpdate(Ge.TEXTURE_NOFADING)&&Ge.TEXTURE_NOFADING;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){const e=gt.extent;O(e),this._pendingTilesForElevationUpdateEvent.forEach((t=>V(e,t.extent,e))),this._pendingTilesForElevationUpdateEvent.clear(),gt.spatialReference=this.spatialReference,this.emit("elevation-change",gt)}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;this._mergeAndSplit(e,t),this._updateElevation(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty(),this._batchUpdatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&e.hasProgressed&&this.requestUpdate(),this.notifyChange("updatingProgressValue")}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;const t=this._iteratorPool.acquire();t.reset(this._rootTiles);const i=this.snapLevel,r=this._splitLimits,s=this._eyePosRenderSR;for(;!t.done;){const e=t.next(),a=e.shouldSplit(r,s,i);if(a!==Ge.SPLIT){if(e.resetPendingUpdate(Ge.SPLIT)&&e.updateAgentSuspension(),a===Ge.ELEVATION&&e.updateAgents(ae.ELEVATION),t.skipSubtree(),!e.isLeaf){e.setPendingUpdate(Ge.MERGE),e.resetPendingUpdate(Ge.SPLIT);const t=this._iteratorPool.acquire();t.resetOne(e);const i=this._viewProjectionMatrix;for(let e=t.next();!t.done;e=t.next())this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(i);t.remove()}}else e.resetPendingUpdate(Ge.MERGE),e.isLeaf&&(e.setPendingUpdate(Ge.SPLIT),t.skipSubtree()),e.rendered&&e.setPendingUpdate(Ge.RENDERDATA)}t.remove(),this.requestUpdate(),(this.shortBatches||!this.oneBatchPerFrameTask)&&this._batchUpdatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||(Xe(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger&&this._treeDebugger.update(),e.madeProgress())}_markTileToUpdate(e){Ee(e.isLoaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForGeometryUpdate(e))}_batchUpdatePendingTileGeometries(){const e=this._pendingTilesToUpdate;if(0===e.size)return;const t=Array.from(this._pendingTilesToUpdate.keys()).filter((e=>e.isLoaded&&e.intersectsClippingArea)),i=(i,r)=>{!r?.isLoaded||!r.intersectsClippingArea||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Qe);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Ee(r.isLoaded),Ee(r.intersectsClippingArea);const a=r.renderData;a.updateNeighborData();const n=a._dirtyEdgeResolutions,l=a.geometryState.neighborData.cornerPeerNeighbors,o=e=>{const t=Ae[e];i(r,l[e]?.findCorner(Ie(t),(e=>e.isLoaded)))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.neighborData.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(Se(Oe[t]),(t=>!(!t.isLoaded||!t.intersectsClippingArea)&&(Ee(e.has(t)||Qe(r,t)<0),i(r,t),!0))),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),Ve&&Be&&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.resetPendingUpdate(Ge.MERGE)){if(!t)return s.setPendingUpdate(Ge.MERGE),e.done;for(;n.parent?.resetPendingUpdate(Ge.MERGE);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else s.resetPendingUpdate(Ge.SPLIT)&&(this._splitTile(s),a=!0,e.madeProgress());return!e.done&&n===s&&s.resetPendingUpdate(Ge.RENDERDATA)&&(this._updateRenderData(s),e.madeProgress()),e.done}));if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this.oneBatchPerFrameTask&&this._batchUpdatePendingTileGeometries(),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some((t=>(t.resetPendingUpdate(Ge.GEOMETRY)&&(this._updateTileGeometryState(t),this._updateTileTexture(t,e),this.shortBatches&&this._batchUpdatePendingTileGeometries(),e.madeProgress()),e.done))),!this.oneBatchPerFrameTask&&this._batchUpdatePendingTileGeometries())}_updateTextures(e){e.done||this._allTiles.some((t=>(this._updateTileTexture(t,e),e.done)))}_updateClippingExtent(){this.spatialReference&&(this.updateTileOverlayParams(tt.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=l(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._visible=!1}_purgeDescendantTiles(e){if(!e.children[0])return!1;let t=!1;for(let i=0;i<4;++i)t=this._purgeTile(e.children[i])||t;return e.unsetChildren(),t}_purgeTile(e){const t=this._purgeDescendantTiles(e)||e.rendered;return this._allTiles.removeUnordered(e),this._unloadTile(e),this._tilePool.release(e),t}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload(this._renderer)}_splitTile(e){we(e.isLeaf,"tile that is already split should not be split again!");const t=e.level+1,i=2*e.lij[1],r=2*e.lij[2];e.setChildren(this._createTile(t,i,r,e),this._createTile(t,i,r+1,e),this._createTile(t,i+1,r,e),this._createTile(t,i+1,r+1,e)),e.setPendingUpdate(Ge.RENDERDATA),e.updateAgentSuspension(),this._allTiles.pushArray(e.children),this._allTilesDirty=!0,++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){mt.spatialReference=this.spatialReference,mt.extent=e.extent,mt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",mt)}_createTile(e,t,i,r){we(!!r,"_createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.extent),s.updateScreenDepth(this._viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(Ge.SPLIT),s}get shortBatches(){return this.view.state.mode!==it.IDLE}_mergeTile(e){we(!e.hasPendingUpdate(Ge.SPLIT),"_mergeTile sanity check"),this._purgeDescendantTiles(e)&&(we(!e.renderData,"_mergeTile sanity check"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this.shortBatches&&this._batchUpdatePendingTileGeometries()),this._allTilesDirty=!0,++this._performanceInfo.numMerged}_loadChildren(e){we(e.rendered,"parent should be rendered"),this._unloadTile(e);const t=e.children;t.forEach((e=>this._loadTile(e))),t.forEach((e=>this._pendingTilesToUpdate.add(e))),this._markAllTileNeighborsForGeometryUpdate(e),this._emitTileScaleChange(e,e.level+1),this.shortBatches&&this._batchUpdatePendingTileGeometries()}_loadParent(e){const t=e.parent;this._unloadChildren(t),this._loadTile(t),this._markTileToUpdate(t),this._emitTileScaleChange(t,t.level),this.shortBatches&&this._batchUpdatePendingTileGeometries()}_unloadChildren(e){const t=e.children;if(t[0])for(let i=0;i<4;++i){const e=t[i];this._unloadChildren(e),this._unloadTile(e)}}_loadTile(e){e.load(),e.setPendingUpdate(Ge.RENDERDATA),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager&&this.overlayManager.hasOverlays&&this.overlayManager.setTileParameters(e)}_elevationDataArrived(e,t,i){const r=new ee(e.lij,e.extent,i);e.dataArrived(t,ae.ELEVATION,r);const s=[e],a=e.level,n=this._iteratorPool.acquire();for(n.reset(s);!n.done;){const e=n.next();e.findElevationBoundsForLayer(t,a),e.computeElevationBounds()}0===a&&this._updateRootTileElevationBounds(),n.remove(),this._updateTilesVisibility(s)}_handleLayerViewChanges(e=at){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(const s of this.view.allLayerViews.items)if(i.add(s.uid),Le(s)||De(s))if(this._basemapLayerViewHandles.has(s.uid)&&!De(s)){const e=this._layerClassFromLayerView(s),i=this._getLayerIdxByUID(e,s.uid);null!=i&&((i<r||null==r)&&(t=!0),r=i)}else this._registerTiledLayerView(s),s.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()}_allSurfaceLayersTransparent(){let e=0===this.view.map?.ground?.opacity;for(const t of this.view.allLayerViews.items)if(Pe(t)&&!H(t.layer)&&0!==t.fullOpacity)return e=!1,e;return e}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((be(e)||De(e))&&Je(Ze[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return xe(e)?ae.ELEVATION:ae.MAP}_registerTiledLayerView(e){const t=[];if((be(e)||De(e))&&t.push(T((()=>e.layer.blendMode),(()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(se.UNFADED)}))),!De(e)){const i=this._layerClassFromLayerView(e);t.push(T((()=>e.suspended),(()=>this._updateTiledLayers()))),t.push(T((()=>e.fullOpacity),(()=>this._updateTileTextures(se.UNFADED)))),t.push(T((()=>"effectiveScaleRange"in e.layer?e.layer.effectiveScaleRange:null),(()=>this._restartAllAgents(i)))),t.push(e.on("data-changed",(()=>{const t=this._getLayerIdxByUID(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||!Le(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(r===ae.MAP){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)}));for(const r of ne){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()}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),e===ae.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(ae.MAP),e===se.IMMEDIATE?this.renderer.updateTileTexture(t,Ge.TEXTURE_NOFADING):t.updateRenderData(ae.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=tt.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||Ue(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.lij[0],e.lij[1],e.lij[2],{...r,timeout:6e3}).then((()=>--this._asyncWorkItems)).catch((t=>{throw--this._asyncWorkItems,c(r),_(t)||this._dataMissing(e,i,s,{notInTilemap:!0}),t})).then((()=>this._frameTask.schedule((()=>this._requestTileData(e,i,s,r)),r.signal))))}_requestTileData(e,t,i,r){return t===ae.ELEVATION?xe(i)?this._requestElevationTileData(e,i,r):Promise.reject():Pe(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{if(g(i))return;const s=this._layerIndexByUid[ae.ELEVATION].get(t.uid);null!=s?(this._usedMemory=null,this.requestUpdate(),this._elevationDataArrived(e,s,r)):n.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",ae.ELEVATION,e.lij.toString())},s=i=>{_(i)||(this._dataMissing(e,ae.ELEVATION,t,i),this.requestUpdate())};if(Re(t.layer))return t.layer.fetchTile(e.lij[0],e.lij[1],e.lij[2],{noDataValue:Te,signal:i.signal}).then((e=>{if(!g(i))return this._frameTask.schedule((()=>r(e)),i.signal,s);n.getLogger(this).warnOnce("A call to fetchTile resolved even though the request was aborted. fetchTile should not resolve if options.signal.aborted is true.")}),s).finally((()=>{--this._asyncWorkItems}));const a=t.getTileUrl(e.lij[0],e.lij[1],e.lij[2]);return this._elevationDataRequester.request(a,"binary",i).then((e=>this._lercDecoder.decode(e,{noDataValue:Te},i.signal))).then((e=>{e?r(new W(e)):s(new Error("LERC decoding failed"))}),s).finally((()=>{--this._asyncWorkItems}))}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{--this._asyncWorkItems,je(s),g(i)||(this._dataMissing(e,ae.MAP,t,r),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule((()=>{--this._asyncWorkItems,this.requestUpdate(),g(i)?je(r):this._mapTileDataArrived(e,t,r)}),i.signal,s(r)).catch(s(r)),l=(e,t=null)=>this._frameTask.schedule((()=>r(e,t)));if(Ue(t)){const r=t.schemaHelper.getLevelRowColumn(e.lij);return t.fetchTile(r[0],r[1],r[2],i).then(a,l)}if(Ce(t))return t.fetchTile(e.lij[0],e.lij[1],e.lij[2],i).then(a,l);if(Me(t)&&Re(t.layer))return t.layer.fetchTile(e.lij[0],e.lij[1],e.lij[2],i).then((e=>{if(g(i))return n.getLogger(this).warnOnce("A call to fetchTile resolved even though the request was aborted. fetchTile should not resolve if options.signal.aborted is true."),void l(m());a(e)}),l);let o=t.getTileUrl(e.lij[0],e.lij[1],e.lij[2]);F(t.layer)&&t.layer.refreshTimestamp&&(o+=`${o.includes("?")?"&":"?"}_ts=${t.layer.refreshTimestamp}`);const h=t.hasMixedImageFormats?"image+type":"image";return this._mapDataRequester.request(o,h,i).then(a,l)}_mapTileDataArrived(e,t,i){const r=this._getLayerIdxByUID(ae.MAP,t.uid);null!=r?e.dataArrived(r,ae.MAP,i):(je(i),n.getLogger(this).warn("TerrainSurface: received data from unknown layer"))}_getLayerIdxByUID(e,t){return this._layerIndexByUid[e].get(t)}_dataMissing(e,t,i,r){const s=this._getLayerIdxByUID(t,i.uid);null!=s?e.dataMissing(s,t,r):n.getLogger(this).warn("TerrainSurface: received data from unknown layer")}updateTileOverlayParams(e){this._rootTiles&&this.overlayManager&&(this._allTiles.forAll((e=>{e.renderData&&this.overlayManager.setTileParameters(e)})),this._renderer.setNeedsRender(e))}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.isLeaf&&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}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),this.overlayManager.usedMemory)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this._getLayerIdxByUID(i,e.uid);return null!=r&&this._allTiles.forAll((e=>t+=e.getUsedMemoryForLayer(i,r))),t}getTile(e){if(null==e||null==this._rootTiles)return null;const t=e.split("/").map((e=>+e));if(0===t[0])return this._rootTiles.find((e=>e.lij[1]===t[1]&&e.lij[2]===t[2]));const i=2**t[0],r=Math.floor(t[1]/i),s=Math.floor(t[2]/i);let a;if(this._rootTiles.some((e=>e.lij[1]===r&&e.lij[2]===s&&(a=e,!0))),a){let e=1<<t[0]-1;for(;a.lij[0]<t[0];){let i=t[1]&e?2:0;if((t[2]&e)>0&&i++,!a.children[i])return null;a=a.children[i],e>>=1}return we(a.lij[0]===t[0]&&a.lij[1]===t[1]&&a.lij[2]===t[2],"not the right tile?"),a}return null}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(){const e=this;return{renderer:e._renderer,lercDecoder:e._lercDecoder,forceReload:()=>{null!=e._rootTiles&&e._rootTiles.length>0&&(e._mergeTile(e._rootTiles[0]),e._viewChangeUpdate())},getTiles:()=>e._allTiles.toArray(),getRenderedTiles(){_t.clear(),e._allTiles.forAll((e=>{e.visible&&e.rendered&&_t.push(e)}));const t=_t.toArray();return Ye(e.renderOrder,t),t},lockTilingScheme(t,i){e._extentHelper.defaultTiledLayersExtent=i,e.tilingSchemeLogic.test.lockTilingScheme(t)}}}checkAllTilesWaterproofness(){if(!Be)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.isLeaf)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.isLeaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateeCarree(){return this._isWebMercatorOnPlateeCarree}isEastEndWrap(e){return this.isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this.isGlobal&&0===e[2]}lijEastEnd(e){return 2**(e+(null!=this.spatialReference&&this.spatialReference.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){ke(e)}enableWaterproofnessChecks(e){Ne(e)}};e([w()],nt.prototype,"_renderer",void 0),e([w({constructOnly:!0})],nt.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],nt.prototype,"view",void 0),e([w({constructOnly:!0})],nt.prototype,"overlayManager",void 0),e([w()],nt.prototype,"_hasPendingUpdates",void 0),e([w()],nt.prototype,"_asyncWorkItems",void 0),e([w()],nt.prototype,"_allTilesDirty",void 0),e([w()],nt.prototype,"_allTilesSorted",void 0),e([w()],nt.prototype,"_viewChanged",void 0),e([w()],nt.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],nt.prototype,"_watchUpdatingTracking",void 0),e([w()],nt.prototype,"_frameTask",void 0),e([w({readOnly:!0})],nt.prototype,"snapLevel",null),e([w({readOnly:!0})],nt.prototype,"lodSnapping",null),e([w()],nt.prototype,"_userClippingExtent",null),e([w()],nt.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],nt.prototype,"extent",null),e([w({readOnly:!0})],nt.prototype,"groundExtent",null),e([w({readOnly:!0})],nt.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],nt.prototype,"updating",null),e([w({readOnly:!0})],nt.prototype,"running",null),e([w(J)],nt.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],nt.prototype,"updatingProgressValue",null),e([w()],nt.prototype,"_maxNumUpdating",void 0),e([w()],nt.prototype,"baseOpacity",null),e([w()],nt.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],nt.prototype,"viewingMode",null),e([w()],nt.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],nt.prototype,"ready",null),e([w({value:he.FRONT_TO_BACK})],nt.prototype,"renderOrder",null),e([w({readOnly:!0})],nt.prototype,"rootTiles",null),e([w()],nt.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],nt.prototype,"spatialReference",null),e([w({type:t})],nt.prototype,"backgroundColor",null),e([w({value:!1})],nt.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],nt.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],nt.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],nt.prototype,"tilingSchemeLogic",void 0),e([w()],nt.prototype,"wireframe",null),e([w({value:!1})],nt.prototype,"suspended",null),e([w()],nt.prototype,"textureFadeDuration",null),e([w()],nt.prototype,"visibleElevationBounds",void 0),e([w()],nt.prototype,"rootTileElevationBounds",void 0),e([w()],nt.prototype,"_layerViewsDirty",void 0),e([w()],nt.prototype,"renderPatchBorders",null),e([w()],nt.prototype,"visualizeNormals",null),e([w()],nt.prototype,"renderingDisabled",null),nt=e([E("esri.views.3d.terrain.TerrainSurface")],nt);const lt=nt;function ot(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function ht(e){const t=e.children;if(!t[0])return!1;for(const i of t)if(i.shouldLoad)return!0;for(const i of t)if(ht(i))return!0;return!1}function dt(e){return e.isLeaf&&(e.parent?.shouldLoad??!1)}const pt=b(),ut=j(),ct=[0,0,0],_t=new u,gt={spatialReference:null,extent:j(),context:"ground"},mt={spatialReference:null,extent:null,scale:0};function Tt(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 te(t,i,s)}return null}export{lt 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.28/esri/copyright.txt for details.
4
4
  */
5
- import{clamp as e}from"../../../core/mathUtils.js";import{abortMaybe as t}from"../../../core/maybe.js";import i from"../../../core/ObjectPool.js";import{j as s,s as n}from"../../../chunks/vec2.js";import{a as r}from"../../../chunks/vec2f64.js";import{b as a,p as o,e as l,g as h,a as u,l as d,c}from"../../../chunks/vec3.js";import{c as g,u as p}from"../../../chunks/vec3f64.js";import{g as f}from"../../../chunks/common.js";import{getReferenceEllipsoid as m}from"../../../geometry/ellipsoidUtils.js";import{create as _,equals as y}from"../../../geometry/support/aaBoundingRect.js";import{c as A}from"../../../chunks/sphere.js";import{isGroupLayer as T}from"../../../layers/support/layerUtils.js";import{VectorTile as E}from"../../2d/engine/vectorTiles/VectorTile.js";import{ImageWithType as v}from"../support/StreamDataLoader.js";import{ElevationBounds as I}from"./ElevationBounds.js";import{ElevationTileAgent as M}from"./ElevationTileAgent.js";import{TextureUpdate as D}from"./interfaces.js";import{TileFrustumVisibility as L,NeighborIndex as x}from"./ITile.js";import{LayerClasses as S,LayerClass as O}from"./LayerClass.js";import{MapTileAgent as N}from"./MapTileAgent.js";import{RasterTile as j}from"./RasterTile.js";import{MAX_PATCH_TESSELATION as b,getElevationDesiredResolutionLevel as U}from"./TerrainConst.js";import{weakAssert as C,getLayerWithExtentRange as P,isBlendableLayerView as B,oppositeCorner as R,neighborCornerIndices as V,neighborEdgeIndices as w,oppositeEdge as G,internalAssert as W,ENABLE_TERRAIN_INTERNAL_CHECKS as q,isNorth as F,isSouth as H,isWest as k,isEast as X,ENABLE_WATERPROOFNESS_TESTS as Y,almostEquals as z,isWestCorner as $,isNorthCorner as J}from"./terrainUtils.js";import{TILE_AGENT_DONE as Q}from"./TileAgent.js";import{TilePerLayerInfo as K}from"./TilePerLayerInfo.js";import Z from"./TileTexture.js";import{TileUpdate as ee}from"./TileUpdate.js";import{fallsWithinLayer as te}from"./tileUtils.js";const ie=.1;class se{constructor(){this.lij=[0,0,0],this._children=[null,null,null,null],this._pendingUpdates=0,this.renderData=null,this._dirty=!0,this._previouslyRendered=!1,this.extent=_(),this._elevationBounds=r(),this.layerInfo=[[],[]],this.extentInRadians=_(),this.centerAtSeaLevel=g(),this._center=[g(),A(),g()],this.up=p(),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._maxTesselation=0,this._usedMemory=null,this._mapTileMemoryInternal=0,this._mapDataRefCount=0,this.screenDepth=0,this.renderOrder=0,this._edgeLen=0,this._edgeLen2=0,this._curvatureHeight=0,this.extentMidX=0,this.extentMidY=0,this.distanceToPOI=-1,this._lastPOI=g()}static prune(){ae.prune(0),oe.prune(0),K.prune()}get _isCached(){return!this.shouldLoad&&this._mapDataRefCount<=0}get maxTesselation(){return this._maxTesselation}get isWithinClippingArea(){return this._isWithinClippingArea}get intersectsClippingArea(){return this._intersectsClippingArea}get clippingArea(){return this._clippingArea}get parent(){return this._parent}get children(){return this._children}get surface(){return this._surface}get elevationBounds(){return this._elevationBounds}get level(){return this.lij[0]}get key(){return`${this.lij[0]}/${this.lij[1]}/${this.lij[2]}`}get edgeLen(){return this._edgeLen}get radius(){return this._center[he.MIDDLE][3]}get visible(){return this._dirty&&this.computeVisibility(),this._visible}get frustumVisibility(){return this._dirty&&this.computeVisibility(),this._frustumVisibility}computeVisibility(){this._dirty=!1;const e=this.parent,t=e?.frustumVisibility??L.INTERSECTS;this._frustumVisibility=t===L.INSIDE?L.INSIDE:t===L.OUTSIDE?L.OUTSIDE:this._calculateFrustumVisibilityStatus(this.surface.frustum);const i=this._frustumVisibility!==L.OUTSIDE&&this._intersectsClippingArea;i!==this._visible&&(this._visible=i,this._surface.emit("tiles-visibility-changed"),this._surface.renderer.setDirty(),this.updateAgentSuspension())}get loadable(){return this.visible||this._surface.view.state.fixedContentCamera}get rendered(){const e=!!this.renderData;return e!==this._previouslyRendered&&(this._surface.emit("tiles-visibility-changed"),this._previouslyRendered=e,this._surface.renderer.setDirty()),e}get shouldLoad(){return this.isLeaf}init(e,t,i){this.lij[0]=e[0],this.lij[1]=e[1],this.lij[2]=e[2],this.ellipsoid=m(i.tilingScheme.spatialReference),i.tilingScheme.getExtent(e[0],e[1],e[2],this.extent),i.tilingScheme.convertExtentToRadians(this.extent,this.extentInRadians),this.extentMidX=.5*(this.extent[0]+this.extent[2]),this.extentMidY=.5*(this.extent[1]+this.extent[3]),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._clippingArea=null,this._mapDataRefCount=0,i.upsampleMapCache.pop(this.key),this._edgeLen=0,this._edgeLen2=0,this._center[he.MIDDLE][3]=0,this.elevationLevel=e?e[0]:0,t&&t.elevationBounds?s(this._elevationBounds,t.elevationBounds):n(this._elevationBounds,0,0),this._pendingUpdates=0,this.renderData=null,this.screenDepth=0,this._visible=!1,this._previouslyRendered=!1,this._parent=t,this.unsetChildren(),this._surface=i,this.updateVisibility();for(const s of S){const e=i.numLayers(s),t=this.layerInfo[s];for(const i of t)i.release();t.length=e;for(let i=0;i<e;i++)t[i]=K.acquire(this._surface.upsampleInfoPool),s===O.ELEVATION&&this.findElevationBoundsForLayer(i,-1)}this.computeElevationBounds(),this._maxTesselation=Math.min(i.tilingScheme.pixelSize,b)}release(){C(!this.renderData,"tile.renderData was not unloaded"),this._surface.upsampleMapCache.pop(this.key);for(const e of S){for(const t of this.layerInfo[e])t.release();this.layerInfo[e].length=0}this._parent=null;for(let e=0;e<4;++e)this._children[e]=null;this._surface=null,this.setMemoryDirty()}refMapData(){++this._mapDataRefCount,this._isCached||this._surface.upsampleMapCache.pop(this.key)}unrefMapData(){if(--this._mapDataRefCount,this._isCached){this.setMemoryDirty();const e=this._cachedMemory;e>0&&this._surface.upsampleMapCache.put(this.key,this,e)}}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this._ensureUsedMemory()+(this._isCached?0:this._mapTileMemoryInternal)}get _cachedMemory(){return this._isCached?this._mapTileMemory:0}get _mapTileMemory(){return this._ensureUsedMemory(),this.layerInfo[O.MAP].reduce(((e,t)=>e+(t instanceof E?t.memoryUsed/t.referenced:0)),this._mapTileMemoryInternal)}get _cpuImageMemorySize(){const e=4,t=this._surface.tilingScheme.pixelSize;return t*t*e}_ensureUsedMemory(){if(null!=this._usedMemory)return this._usedMemory;this._usedMemory=0,this._mapTileMemoryInternal=0;let e=0;for(const{data:i}of this.layerInfo[O.MAP])i instanceof E?e+=this._getTerrainDataMemory(i):this._mapTileMemoryInternal+=this._getTerrainDataMemory(i);const t=this._cpuImageMemorySize;for(const i of this.layerInfo[O.ELEVATION])this._usedMemory+=i.data?t:0;return this.renderData&&(this._usedMemory+=this.renderData.estimatedGeometryMemoryUsage,this._mapTileMemoryInternal+=this.renderData.texture?.gpuMemoryUsage??0),this._isCached&&this._surface.upsampleMapCache.updateSize(this.key,this,this._mapTileMemoryInternal+e),this._usedMemory}getUsedMemoryForLayer(e,t){const i=this.layerInfo[e][t];return i?.data?e===O.MAP?this._isCached?0:this._getTerrainDataMemory(i.data):e===O.ELEVATION?this._cpuImageMemorySize:0:0}_getTerrainDataMemory(e){return e instanceof Z?e.texture.gpuMemoryUsage:e instanceof HTMLImageElement||e instanceof v?this._cpuImageMemorySize:e instanceof j?e.memoryUsage:e instanceof E?e.memoryUsed/e.referenced:0}updateScreenDepth(e){const t=this._center[he.MIDDLE],i=e,s=t[0],n=t[1],r=t[2],a=i[2]*s+i[6]*n+i[10]*r+i[14];this.screenDepth=a<0?0:a/(i[3]*s+i[7]*n+i[11]*r+i[15])}shouldSplit(e,t,i){if(!this.visible)return ee.NONE;if(null!=e.frustum&&(!this._intersectsClippingArea||this._calculateFrustumVisibilityStatus(e.frustum)===L.OUTSIDE))return ee.NONE;const s=this.level;a(me,this._center[he.MIDDLE],t);let n=o(me),r=me,c=he.MIDDLE;a(_e,this._center[he.TOP],t);const g=o(_e);g<n&&(n=g,r=_e,c=he.TOP),a(ye,this._center[he.BOTTOM],t);const p=o(ye);if(p<n&&(n=p,r=ye,c=he.BOTTOM),this._edgeLen2>n&&s<e.maxLod)return ee.SPLIT;const f=null!=i?i-s:1/0,m=Math.sqrt(n),_=e.fovX*m*2,y=this._edgeLen/_,A=()=>{if(s<e.maxLod)return this.elevationLevel=s,ee.NONE;const t=s+Math.ceil(-Math.log2(e.relativeWidthLimit/y));return t!==this.elevationLevel?(this.elevationLevel=t,ee.ELEVATION):ee.NONE};if(f<=.5)return A();const T=l(this.up,me),E=this._elevationBounds[1]-this._elevationBounds[0],v=E/this.edgeLen;if(e.aboveGround&&T>0&&v<.001){if(T/m-Math.sin(this._curvatureHeight/(this.edgeLen*Math.SQRT1_2)*Math.PI)-v>0)return ee.NONE}const I=null!=i?3-Math.min(f,2):1;if(y*I<e.relativeWidthLimit||s>=e.maxLod)return A();if(s<7)return ee.SPLIT;h(Ae,this.up,T),a(Ae,Ae,r);const M=o(Ae);if(M<=this.radius*this.radius)return ee.SPLIT;h(Ae,Ae,this.radius/Math.sqrt(M)),u(Ae,Ae,this._center[c]),a(Ae,t,Ae);const D=Math.min(1,(Math.abs(l(Ae,this.up))+.5*E+this._curvatureHeight)/d(Ae)),x=ie/e.angledSplitBias,S=e.fovY*m*2;return D*(this._edgeLen/S*I)<x*e.relativeHeightLimit?ee.NONE:ee.SPLIT}setChildren(e,t,i,s){C(!!(e&&t&&i&&s),"Null child passed"),this._children[0]=e,this._children[1]=t,this._children[2]=i,this._children[3]=s}unsetChildren(){this._children[0]=null,this._children[1]=null,this._children[2]=null,this._children[3]=null}get isLoaded(){return this.renderData?.hasGeometry??!1}load(){this.refMapData();for(const e of S)this._createOrUpdateAgents(0,e);this.surface.renderer.loadTile(this)}unload(e){e.unloadTile(this);for(const t of S){const e=this.layerInfo[t];for(const t of e)t.loadingAgent&&t.loadingAgent!==Q&&(re(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0}this.resetPendingUpdate(ee.GEOMETRY),this.resetPendingUpdate(ee.TEXTURE_NOFADING),this.resetPendingUpdate(ee.TEXTURE_FADING),this.unrefMapData()}unloadMapData(){const e=this.layerInfo[O.MAP];for(const t of e)t.loadingAgent&&t.loadingAgent!==Q&&(re(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0;this.renderData&&this.renderData.releaseTexture(),this.setMemoryDirty()}updateClippingStatus(e){if(y(e,this._clippingArea))return!1;const t=this._intersectsClippingArea,i=this._isWithinClippingArea;null!=e?(this._intersectsClippingArea=this.intersectsExtent(e),this._isWithinClippingArea=this._isWithinExtent(e)):(this._intersectsClippingArea=!0,this._isWithinClippingArea=!0),this._clippingArea=e,this.updateVisibility();const s=i&&this._isWithinClippingArea,n=!(i||t||this._isWithinClippingArea||this._intersectsClippingArea);return!this.renderData||s||n||this.setPendingUpdate(ee.GEOMETRY),!0}updateVisibility(){this._dirty=!0,this._surface.setTileTreeDirty()}getLayerInfo(e,t){return this.layerInfo[t][e]}hasLayerData(e,t){const i=this.layerInfo[t][e];return!(!i||!i.data||i.dataInvalidated)}get updating(){if(this.hasPendingUpdates)return!0;for(const e of S){const t=this.layerInfo[e];for(const e of t)if(e.loadingAgent&&e.loadingAgent!==Q&&e.loadingAgent.updating)return!0}return!1}_isSuspended(e){return!!this.hasPendingUpdate(ee.SPLIT)||e!==O.ELEVATION&&!this.loadable}get hasPendingUpdates(){return 0!==this._pendingUpdates}hasPendingUpdate(e){return(this._pendingUpdates&e)===e}setPendingUpdate(e){this._pendingUpdates|=e,e===ee.SPLIT||e===ee.MERGE?this._surface.setTileTreeDirty():this._surface.requestUpdate()}resetPendingUpdate(e){return!!this.hasPendingUpdate(e)&&(this._pendingUpdates&=~e,!0)}requestLayerData(e,i,s){const n=this.layerInfo[i][e];if(n.waitingAgents.has(s))return console.warn("agent already requested this piece of map data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),s.tile.lij.toString(),i,e),!0;if(n.waitingAgents.push(s),n.data&&!n.dataInvalidated){console.warn("agent requested existing data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),s.tile.lij.toString(),i,e);const t=n.data&&"type"in n.data&&"vector-tile"===n.data.type;return s.dataArrived(this,t),!0}if(n.requestPromise)return!0;t(n.requestAbort),n.requestAbort=new AbortController;const r=this._surface.requestTileData(this,e,i,n.requestAbort);if(!r)return n.requestAbort=null,!1;const a=()=>{n.requestPromise===r&&(n.requestPromise=null,n.requestAbort=null)};return n.requestPromise=r,r.then(a,a),!0}get isLeaf(){return null==this._children[0]}hasLij(e){return this.lij[0]===e[0]&&this.lij[1]===e[1]&&this.lij[2]===e[2]}findByLij(e){if(this.hasLij(e))return this;const t=this._children;if(!t[0])return null;return t[0].findByLij(e)||t[1].findByLij(e)||t[2].findByLij(e)||t[3].findByLij(e)}distanceToSquared(e){return o(a(Ae,this._center[he.MIDDLE],e))}containsPoint(e){const t=this.extent;return e[0]>=t[0]&&e[1]>=t[1]&&e[0]<=t[2]&&e[1]<=t[3]}containsPointXY(e,t){const i=this.extent;return e>=i[0]&&t>=i[1]&&e<=i[2]&&t<=i[3]}unrequestLayerData(e,t,i){const s=this.layerInfo[t][e],n=s.waitingAgents,r=null!=n.removeUnordered(i);C(r,"agent has not requested this piece of map data"),n.length<1&&(s.abortRequest(),this.setMemoryDirty())}dataArrived(e,t,i){const s=null!=i&&"type"in i&&"vector-tile"===i.type,n=this.layerInfo[t][e];n.data=i,n.dataInvalidated=!1,n.waitingAgents.forAll((e=>e.dataArrived(this,s))),n.waitingAgents.clear(),this.setMemoryDirty()}dataMissing(e,t,i){i.notInTilemap||console.error(`Tile ${this.lij.toString()} layer ${t}/${e} error ${i}`);const s=this.layerInfo[t][e];s.dataMissing=!0,s.waitingAgents.forAll((e=>e.dataMissing())),s.waitingAgents.clear(),this.setMemoryDirty()}updateRenderData(e,t,i){switch(i&&this.forEachLoadedNeighbor((i=>i.updateRenderData(e,t))),e){case O.MAP:return this._updateTexture(t);case O.ELEVATION:return this._updateGeometry()}}_updateTexture(e){this.renderData&&(this.resetPendingUpdate(e===D.FADING?ee.TEXTURE_NOFADING:ee.TEXTURE_FADING),this.setPendingUpdate(e===D.FADING?ee.TEXTURE_FADING:ee.TEXTURE_NOFADING))}_updateGeometry(){this.setPendingUpdate(ee.GEOMETRY);for(const e of this.layerInfo[O.ELEVATION])e.pendingUpdates|=ee.GEOMETRY}invalidateLayerData(e,t){this.layerInfo[t][e].invalidateSourceData(),this.restartAgents(t)}computeElevationBounds(){const e=this._elevationBounds,t=e[0],i=e[1];n(e,1/0,-1/0);const s=this.layerInfo[O.ELEVATION];let r=!0;for(const n of s)null!=n.elevationBounds&&(e[0]=Math.min(e[0],n.elevationBounds.min),e[1]=Math.max(e[1],n.elevationBounds.max),n.elevationBounds.hasNoDataValues||(r=!1));r&&(e[0]=Math.min(e[0],0),e[1]=Math.max(e[1],0)),t===e[0]&&i===e[1]||(this.updateRadiusAndCenter(),this._surface.setTileTreeDirty())}_updateCenter(){const e=this._elevationBounds,t=.5*(e[0]+e[1]),i=this._center;h(Ae,this.up,t),u(i[he.MIDDLE],this.centerAtSeaLevel,Ae),h(Ae,this.up,e[0]),u(i[he.TOP],this.centerAtSeaLevel,Ae),h(Ae,this.up,e[1]),u(i[he.BOTTOM],this.centerAtSeaLevel,Ae)}findElevationBoundsForLayer(e,t){const i=this.layerInfo[O.ELEVATION][e],s=U(this.level),n=Math.max(this.elevationLevel-s,0),r=i.elevationBounds;if(null!=r&&r.level>=t&&r.level<=n)return;const a=this._surface.layerViewByIndex(e,O.ELEVATION),o=P(a);if(!te(this,o,!1))return;const l=le;let h=!1;const u=i.data;if(u&&u.level<=n){const e=i.data;l.min=e.samplerData.data.minValue,l.max=e.samplerData.data.maxValue,l.hasNoDataValues=e.samplerData.data.hasNoDataValues,l.level=this.level,h=!0}else{let t,i,r=0;for(let a=this._parent;a&&(!i||r<s)&&(r=this.elevationLevel-a.level,t=i||t,i=a.layerInfo[O.ELEVATION][e].data,!(!i&&t&&a.level<=n));a=a.parent);i=i||t,i&&(i.computeMinMaxValue(this.lij[0],this.lij[1],this.lij[2],l),l.min!==1/0&&(l.level=i.level,h=!0))}h&&(null==i.elevationBounds&&(i.elevationBounds=new I),i.elevationBounds.copyFrom(l))}modifyLayers(e,t,i){const s=this.layerInfo[i];for(const a of s)a.loadingAgent&&a.loadingAgent!==Q&&(re(a.loadingAgent),a.loadingAgent=null),a.waitingAgents.clear();for(let a=0;a<s.length;++a)void 0===e[a]&&s[a].release();const n=new Array(...s),r=t.length;s.length=r;for(let a=0;a<r;a++){const e=t[a];s[a]=e>-1?n[e]:K.acquire(this._surface.upsampleInfoPool)}this.setMemoryDirty()}restartAgents(e){this.renderData&&(this._createOrUpdateAgents(0,e),this.updateRenderData(e,D.FADING))}updateAgents(e){if(this.renderData){const t=this.layerInfo[e];for(const e of t)e.loadingAgent===Q&&(e.loadingAgent=null);this._createOrUpdateAgents(0,e)}}updateAgentSuspension(){for(const e of S){const t=this._isSuspended(e);for(const i of this.layerInfo[e])i.loadingAgent&&i.loadingAgent!==Q&&(i.loadingAgent.setSuspension(t),i.loadingAgent===Q&&this.updateRenderData(e,D.FADING))}}removeLayerAgent(e,t){const i=this.layerInfo[t][e];i.loadingAgent&&i.loadingAgent!==Q&&i.loadingAgent.dispose(),i.loadingAgent=null}agentDone(e,t){const i=this.layerInfo[t][e];i.loadingAgent=Q,i.data||null!=i.upsampleInfo||this._createOrUpdateAgents(e+1,t)}_hasBlendableAncestor(e){return"normal"!==e.blendMode||T(e.parent)&&this._hasBlendableAncestor(e.parent)}_hasBlendModes(e,t,i){for(let s=e;s<t;++s){const e=this._surface.layerViewByIndex(s,i);if(B(e)&&"normal"!==e?.layer?.blendMode||T(e?.layer?.parent)&&this._hasBlendableAncestor(e?.layer?.parent))return!0}return!1}_createOrUpdateAgents(e,t){const i=this.layerInfo[t];if(0===i.length)return;const s=this._isSuspended(t);for(let n=e;n<i.length;++n){const r=i[n];let a=!1;const o=this._surface.layerViewByIndex(n,t),l=P(o);if(r.loadingAgent?te(this,l,!1)?(r.loadingAgent!==Q&&r.loadingAgent.setSuspension(s),r.loadingAgent!==Q&&(a=r.loadingAgent.update())):r.dispose():te(this,l,!1)&&(r.loadingAgent=ne(this,n,t,s),a=r.loadingAgent.startLoading(),a?r.loadingAgent===Q&&this.setPendingUpdate(ee.GEOMETRY):(re(r.loadingAgent),r.loadingAgent=Q)),r.loadingAgent===Q&&this.updateRenderData(t,D.FADING),!this._hasBlendModes(e,i.length,t)&&a&&o.isOpaque)return}}_isWithinExtent(e){const t=this.extent;return t[0]>=e[0]&&e[2]>=t[2]&&t[1]>=e[1]&&e[3]>=t[3]}intersectsExtent(e){const t=this.extent;return t[2]>=e[0]&&e[2]>=t[0]&&t[3]>=e[1]&&e[3]>=t[1]}getElevationVerticesPerSide(t){const i=this.elevationLevel-this.level,s=Math.max(this.level-t,U(this.level)-i),n=e(1+(this.maxTesselation>>s),2,this.maxTesselation+1),r=this.getDefaultVerticesPerSide();return Math.max(n,r)}get test(){return{cachedMemory:this._cachedMemory}}_findLIJ(e,t){if(!e)return null;const i=this.surface.rootTiles;if(null!=i)for(const s of i)if(ue(s,e)){let i=s,n=e[0]-i.level-1;for(;n>=0&&!i.isLeaf&&!t(i);){const t=e[1]>>n&1,s=e[2]>>n&1;i=i.children[2*t+s],n--}return t(i)?i:null}return null}findNeighborTile(e,t){const i=this.lij,s=this.getNeighborLIJ(i,e);return s?de(i,s)?t(this)?this:null:this._findLIJ(s,t):null}findCorner(e,t){const i=e===x.NORTH_EAST?1:e===x.NORTH_WEST?0:e===x.SOUTH_WEST?2:3;let s=this;for(;s.children[0]&&(!t||!t(s));)s=s.children[i];return s}findNeighborCornerTileExact(e,t){return this.findNeighborTile(e,(e=>t(e)||e.level===this.level))?.findCorner(R(e),t)||null}forAllSubtreeOnSide(e,t){const i=e===x.NORTH?[0,1]:e===x.NORTH_EAST?[1]:e===x.EAST?[1,3]:e===x.SOUTH_EAST?[3]:e===x.SOUTH?[2,3]:e===x.SOUTH_WEST?[2]:e===x.WEST?[0,2]:[0],s=e=>{const n=e.children;!t(e)&&n[0]&&i.forEach((e=>s(n[e])))};s(this)}forallNeighbors(e){V.forEach((t=>this.findNeighborCornerTileExact(t,e))),w.forEach((t=>this.findNeighborTile(t,(t=>t.level===this.level||e(t)))?.forAllSubtreeOnSide(G(t),e)))}getNeighborEdgeStartVertexIndex(e,t){if(!t)return 0;const i=this.level-t.level;if(W(!q||i>=0),0===i)return 0;const s=2**i,n=1==(1&e),r=n?0:1,a=t.lij[r+1]*s,o=this.lij[r+1],l=o-a,h=n?s-1-l:l;return q&&(W(a<=o&&o<a+s),W(0<=h&&h<s)),h}forEachLoadedNeighbor(e){const t=this.level,i=e=>e.level===t||e.isLoaded;w.forEach((t=>{const s=this.findNeighborTile(t,i);null!=s&&s!==this&&s.forAllSubtreeOnSide(G(t),(i=>!!i.isLoaded&&(e(i,t),!0)))})),V.forEach((t=>{const s=this.findNeighborTile(t,i)?.findCorner(R(t),(e=>e.isLoaded));W(!s||ge(this,s,t)),s?.isLoaded&&e(s,t)}))}getNeighborLIJ(e,t){const i=F(t)?-1:H(t)?1:0,s=k(t)?-1:X(t)?1:0,n=[e[0],e[1]+i,e[2]+s];return n[1]<0?null:this.surface.isGlobal?this.wrapLIJ(n):n[2]<0?null:n}wrapLIJ(e){return!e||e[1]<0||e[1]>=2**e[0]?null:this.surface.wrapEastWest(e)}get westNeighborWestExtent(){return this.extent[0]*(this.isWestEnd?-1:1)}get eastNeighborEastExtent(){return this.extent[2]*(this.isEastEnd?-1:1)}get isEastEnd(){return this.lij[2]===this.surface.lijEastEnd(this.level)-1}get isWestEnd(){return 0===this.lij[2]}get isNorthEnd(){return 0===this.lij[1]}get isSouthEnd(){const e=this.surface.extent,t=e?.[1]??null;return null!=t&&this.extent[1]+f()>=t}checkGeometryWaterproofness(){Y&&(W(this.isLoaded),this.renderData?.checkGeometryWaterproofness())}shouldHaveNeighbor(e){const t=this.extent,i=this.surface.rootTilesExtent,s=.25*(t[2]-t[0]);if(F(e)&&t[3]+s>=i[3])return!1;if(H(e)&&t[1]-s<=i[1])return!1;const n=this.surface.isGlobal;return!(!n&&k(e)&&t[0]-s<=i[0])&&!(!n&&X(e)&&t[2]+s>=i[2])}updateDistanceToPOI(e){const t=this._lastPOI;if(this.distanceToPOI>=0&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return;c(this._lastPOI,e);const i=this._center[he.MIDDLE],s=e[0]-i[0],n=e[1]-i[1],r=e[2]-i[2];this.distanceToPOI=s*s+n*n+r*r}}function ne(e,t,i,s){const n=i===O.ELEVATION?oe.acquire():ae.acquire();return n.init(e,t,i,s),n}function re(e){e.dispose(),e instanceof M?oe.release(e):e instanceof N&&ae.release(e)}const ae=new i(N),oe=new i(M),le=new I;var he;function ue(e,t){const i=e.level,s=t[0];if(i>s)return!1;const n=s-i,r=Math.floor(t[1]/2**n),a=Math.floor(t[2]/2**n);return r===e.lij[1]&&a===e.lij[2]}function de(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function ce(e,t,i){if(null==e||null==t)return!1;if(0===e.level&&0===t.level){if(e.isEastEnd&&t.isWestEnd&&i===x.EAST)return!0;if(e.isWestEnd&&t.isEastEnd&&i===x.WEST)return!0}const s=Math.max(1e-6*(e.extent[2]-e.extent[0]),1);switch(i){case x.NORTH:return z(e.extent[3],t.extent[1],s);case x.SOUTH:return z(e.extent[1],t.extent[3],s);case x.EAST:return z(e.extent[2],t.extent[0],s)||z(e.extent[2],-t.extent[0],s);case x.WEST:return z(e.extent[0],t.extent[2],s)||z(e.extent[0],-t.extent[2],s)}}function ge(e,t,i){return null!=e&&null!=t&&t!==e&&(e.level>=t.level?pe(e,t,i):pe(t,e,R(i)))}function pe(e,t,i){W(e.level>=t.level);const s=$(i),n=J(i),r=e.extent,a=t.extent,o=[s?r[0]:r[2],n?r[3]:r[1]],l=[s?a[2]:a[0],n?a[1]:a[3]],h=1e-5*(r[2]-r[0]),u=z(o[0],l[0],h)||e.surface.isGlobal&&z(o[0],-l[0],h),d=z(o[1],l[1],h);if(u&&d)return!0;if(e.level===t.level)return W(!1),!1;if(!u&&!d)return W(!1),!1;const c=u?fe(a[1],a[3],r[1],r[3],h):fe(a[0],a[2],r[0],r[2],h);return W(c),c}function fe(e,t,i,s,n){return e-n<=i&&i<=s&&s<=t+n}!function(e){e[e.TOP=0]="TOP",e[e.MIDDLE=1]="MIDDLE",e[e.BOTTOM=2]="BOTTOM"}(he||(he={}));const me=g(),_e=g(),ye=g(),Ae=g();export{he as CenterPosition,se as Tile,ge as isCornerNeighbor,ce as isEdgeNeighbor};
5
+ import{clamp as e}from"../../../core/mathUtils.js";import{abortMaybe as t}from"../../../core/maybe.js";import i from"../../../core/ObjectPool.js";import{j as s,s as n}from"../../../chunks/vec2.js";import{a as r}from"../../../chunks/vec2f64.js";import{b as a,p as o,e as l,g as h,a as u,l as d,c}from"../../../chunks/vec3.js";import{c as g,u as p}from"../../../chunks/vec3f64.js";import{g as f}from"../../../chunks/common.js";import{getReferenceEllipsoid as m}from"../../../geometry/ellipsoidUtils.js";import{create as _,equals as y}from"../../../geometry/support/aaBoundingRect.js";import{c as A}from"../../../chunks/sphere.js";import{isGroupLayer as T}from"../../../layers/support/layerUtils.js";import{VectorTile as E}from"../../2d/engine/vectorTiles/VectorTile.js";import{ImageWithType as v}from"../support/StreamDataLoader.js";import{ElevationBounds as I}from"./ElevationBounds.js";import{ElevationTileAgent as M}from"./ElevationTileAgent.js";import{TextureUpdate as D}from"./interfaces.js";import{TileFrustumVisibility as L,NeighborIndex as x}from"./ITile.js";import{LayerClasses as S,LayerClass as O}from"./LayerClass.js";import{MapTileAgent as N}from"./MapTileAgent.js";import{RasterTile as j}from"./RasterTile.js";import{MAX_PATCH_TESSELATION as b,getElevationDesiredResolutionLevel as U}from"./TerrainConst.js";import{weakAssert as C,getLayerWithExtentRange as P,isBlendableLayerView as B,oppositeCorner as R,neighborCornerIndices as V,neighborEdgeIndices as w,oppositeEdge as G,internalAssert as W,ENABLE_TERRAIN_INTERNAL_CHECKS as q,isNorth as F,isSouth as H,isWest as k,isEast as X,ENABLE_WATERPROOFNESS_TESTS as Y,almostEquals as z,isWestCorner as $,isNorthCorner as J}from"./terrainUtils.js";import{TILE_AGENT_DONE as Q}from"./TileAgent.js";import{TilePerLayerInfo as K}from"./TilePerLayerInfo.js";import Z from"./TileTexture.js";import{TileUpdate as ee}from"./TileUpdate.js";import{fallsWithinLayer as te}from"./tileUtils.js";const ie=.1;class se{constructor(){this.lij=[0,0,0],this._children=[null,null,null,null],this._pendingUpdates=0,this.renderData=null,this._dirty=!0,this._previouslyRendered=!1,this.extent=_(),this._elevationBounds=r(),this.layerInfo=[[],[]],this.extentInRadians=_(),this.centerAtSeaLevel=g(),this._center=[g(),A(),g()],this.up=p(),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._maxTesselation=0,this._usedMemory=null,this._mapTileMemoryInternal=0,this._mapDataRefCount=0,this.screenDepth=0,this.renderOrder=0,this._edgeLen=0,this._edgeLen2=0,this._curvatureHeight=0,this.extentMidX=0,this.extentMidY=0,this.distanceToPOI=-1,this._lastPOI=g()}static prune(){ae.prune(0),oe.prune(0),K.prune()}get _isCached(){return!this.shouldLoad&&this._mapDataRefCount<=0}get maxTesselation(){return this._maxTesselation}get isWithinClippingArea(){return this._isWithinClippingArea}get intersectsClippingArea(){return this._intersectsClippingArea}get clippingArea(){return this._clippingArea}get parent(){return this._parent}get children(){return this._children}get surface(){return this._surface}get elevationBounds(){return this._elevationBounds}get level(){return this.lij[0]}get key(){return`${this.lij[0]}/${this.lij[1]}/${this.lij[2]}`}get edgeLen(){return this._edgeLen}get radius(){return this._center[he.MIDDLE][3]}get visible(){return this._dirty&&this.computeVisibility(),this._visible}get frustumVisibility(){return this._dirty&&this.computeVisibility(),this._frustumVisibility}computeVisibility(){this._dirty=!1;const e=this.parent,t=e?.frustumVisibility??L.INTERSECTS;this._frustumVisibility=t===L.INSIDE?L.INSIDE:t===L.OUTSIDE?L.OUTSIDE:this._calculateFrustumVisibilityStatus(this.surface.frustum);const i=this._frustumVisibility!==L.OUTSIDE&&this._intersectsClippingArea;i!==this._visible&&(this._visible=i,this._surface.emit("tiles-visibility-changed"),this._surface.renderer.setDirty(),this.updateAgentSuspension())}get loadable(){return this.visible||this._surface.view.state.fixedContentCamera}get rendered(){const e=!!this.renderData;return e!==this._previouslyRendered&&(this._surface.emit("tiles-visibility-changed"),this._previouslyRendered=e,this._surface.renderer.setDirty()),e}get shouldLoad(){return this.isLeaf}init(e,t,i){this.lij[0]=e[0],this.lij[1]=e[1],this.lij[2]=e[2],this.ellipsoid=m(i.tilingScheme.spatialReference),i.tilingScheme.getExtent(e[0],e[1],e[2],this.extent),i.tilingScheme.convertExtentToRadians(this.extent,this.extentInRadians),this.extentMidX=.5*(this.extent[0]+this.extent[2]),this.extentMidY=.5*(this.extent[1]+this.extent[3]),this._isWithinClippingArea=!0,this._intersectsClippingArea=!0,this._clippingArea=null,this._mapDataRefCount=0,i.upsampleMapCache.pop(this.key),this._edgeLen=0,this._edgeLen2=0,this._center[he.MIDDLE][3]=0,this.elevationLevel=e?e[0]:0,t&&t.elevationBounds?s(this._elevationBounds,t.elevationBounds):n(this._elevationBounds,0,0),this._pendingUpdates=0,this.renderData=null,this.screenDepth=0,this._visible=!1,this._previouslyRendered=!1,this._parent=t,this.unsetChildren(),this._surface=i,this.updateVisibility();for(const s of S){const e=i.numLayers(s),t=this.layerInfo[s];for(const i of t)i.release();t.length=e;for(let i=0;i<e;i++)t[i]=K.acquire(this._surface.upsampleInfoPool),s===O.ELEVATION&&this.findElevationBoundsForLayer(i,-1)}this.computeElevationBounds(),this._maxTesselation=Math.min(i.tilingScheme.pixelSize,b)}release(){C(!this.renderData,"tile.renderData was not unloaded"),this._surface.upsampleMapCache.pop(this.key);for(const e of S){for(const t of this.layerInfo[e])t.release();this.layerInfo[e].length=0}this._parent=null;for(let e=0;e<4;++e)this._children[e]=null;this._surface=null,this.setMemoryDirty()}refMapData(){++this._mapDataRefCount,this._isCached||this._surface.upsampleMapCache.pop(this.key)}unrefMapData(){if(--this._mapDataRefCount,this._isCached){this.setMemoryDirty();const e=this._cachedMemory;e>0&&this._surface.upsampleMapCache.put(this.key,this,e)}}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this._ensureUsedMemory()+(this._isCached?0:this._mapTileMemoryInternal)}get _cachedMemory(){return this._isCached?this._mapTileMemory:0}get _mapTileMemory(){return this._ensureUsedMemory(),this.layerInfo[O.MAP].reduce(((e,t)=>e+(t instanceof E?t.memoryUsed/t.referenced:0)),this._mapTileMemoryInternal)}get _cpuImageMemorySize(){const e=4,t=this._surface.tilingScheme.pixelSize;return t*t*e}_ensureUsedMemory(){if(null!=this._usedMemory)return this._usedMemory;this._usedMemory=0,this._mapTileMemoryInternal=0;let e=0;for(const{data:i}of this.layerInfo[O.MAP])i instanceof E?e+=this._getTerrainDataMemory(i):this._mapTileMemoryInternal+=this._getTerrainDataMemory(i);const t=this._cpuImageMemorySize;for(const i of this.layerInfo[O.ELEVATION])this._usedMemory+=i.data?t:0;return this.renderData&&(this._usedMemory+=this.renderData.estimatedGeometryMemoryUsage,this._mapTileMemoryInternal+=this.renderData.texture?.memoryUsage??0),this._isCached&&this._surface.upsampleMapCache.updateSize(this.key,this,this._mapTileMemoryInternal+e),this._usedMemory}getUsedMemoryForLayer(e,t){const i=this.layerInfo[e][t];return i?.data?e===O.MAP?this._isCached?0:this._getTerrainDataMemory(i.data):e===O.ELEVATION?this._cpuImageMemorySize:0:0}_getTerrainDataMemory(e){return e instanceof Z?e.texture.gpuMemoryUsage:e instanceof HTMLImageElement||e instanceof v?this._cpuImageMemorySize:e instanceof j?e.memoryUsage:e instanceof E?e.memoryUsed/e.referenced:0}updateScreenDepth(e){const t=this._center[he.MIDDLE],i=e,s=t[0],n=t[1],r=t[2],a=i[2]*s+i[6]*n+i[10]*r+i[14];this.screenDepth=a<0?0:a/(i[3]*s+i[7]*n+i[11]*r+i[15])}shouldSplit(e,t,i){if(!this.visible)return ee.NONE;if(null!=e.frustum&&(!this._intersectsClippingArea||this._calculateFrustumVisibilityStatus(e.frustum)===L.OUTSIDE))return ee.NONE;const s=this.level;a(me,this._center[he.MIDDLE],t);let n=o(me),r=me,c=he.MIDDLE;a(_e,this._center[he.TOP],t);const g=o(_e);g<n&&(n=g,r=_e,c=he.TOP),a(ye,this._center[he.BOTTOM],t);const p=o(ye);if(p<n&&(n=p,r=ye,c=he.BOTTOM),this._edgeLen2>n&&s<e.maxLod)return ee.SPLIT;const f=null!=i?i-s:1/0,m=Math.sqrt(n),_=e.fovX*m*2,y=this._edgeLen/_,A=()=>{if(s<e.maxLod)return this.elevationLevel=s,ee.NONE;const t=s+Math.ceil(-Math.log2(e.relativeWidthLimit/y));return t!==this.elevationLevel?(this.elevationLevel=t,ee.ELEVATION):ee.NONE};if(f<=.5)return A();const T=l(this.up,me),E=this._elevationBounds[1]-this._elevationBounds[0],v=E/this.edgeLen;if(e.aboveGround&&T>0&&v<.001){if(T/m-Math.sin(this._curvatureHeight/(this.edgeLen*Math.SQRT1_2)*Math.PI)-v>0)return ee.NONE}const I=null!=i?3-Math.min(f,2):1;if(y*I<e.relativeWidthLimit||s>=e.maxLod)return A();if(s<7)return ee.SPLIT;h(Ae,this.up,T),a(Ae,Ae,r);const M=o(Ae);if(M<=this.radius*this.radius)return ee.SPLIT;h(Ae,Ae,this.radius/Math.sqrt(M)),u(Ae,Ae,this._center[c]),a(Ae,t,Ae);const D=Math.min(1,(Math.abs(l(Ae,this.up))+.5*E+this._curvatureHeight)/d(Ae)),x=ie/e.angledSplitBias,S=e.fovY*m*2;return D*(this._edgeLen/S*I)<x*e.relativeHeightLimit?ee.NONE:ee.SPLIT}setChildren(e,t,i,s){C(!!(e&&t&&i&&s),"Null child passed"),this._children[0]=e,this._children[1]=t,this._children[2]=i,this._children[3]=s}unsetChildren(){this._children[0]=null,this._children[1]=null,this._children[2]=null,this._children[3]=null}get isLoaded(){return this.renderData?.hasGeometry??!1}load(){this.refMapData();for(const e of S)this._createOrUpdateAgents(0,e);this.surface.renderer.loadTile(this)}unload(e){e.unloadTile(this);for(const t of S){const e=this.layerInfo[t];for(const t of e)t.loadingAgent&&t.loadingAgent!==Q&&(re(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0}this.resetPendingUpdate(ee.GEOMETRY),this.resetPendingUpdate(ee.TEXTURE_NOFADING),this.resetPendingUpdate(ee.TEXTURE_FADING),this.unrefMapData()}unloadMapData(){const e=this.layerInfo[O.MAP];for(const t of e)t.loadingAgent&&t.loadingAgent!==Q&&(re(t.loadingAgent),t.loadingAgent=null),t.pendingUpdates=0;this.renderData&&this.renderData.releaseTexture(),this.setMemoryDirty()}updateClippingStatus(e){if(y(e,this._clippingArea))return!1;const t=this._intersectsClippingArea,i=this._isWithinClippingArea;null!=e?(this._intersectsClippingArea=this.intersectsExtent(e),this._isWithinClippingArea=this._isWithinExtent(e)):(this._intersectsClippingArea=!0,this._isWithinClippingArea=!0),this._clippingArea=e,this.updateVisibility();const s=i&&this._isWithinClippingArea,n=!(i||t||this._isWithinClippingArea||this._intersectsClippingArea);return!this.renderData||s||n||this.setPendingUpdate(ee.GEOMETRY),!0}updateVisibility(){this._dirty=!0,this._surface.setTileTreeDirty()}getLayerInfo(e,t){return this.layerInfo[t][e]}hasLayerData(e,t){const i=this.layerInfo[t][e];return!(!i||!i.data||i.dataInvalidated)}get updating(){if(this.hasPendingUpdates)return!0;for(const e of S){const t=this.layerInfo[e];for(const e of t)if(e.loadingAgent&&e.loadingAgent!==Q&&e.loadingAgent.updating)return!0}return!1}_isSuspended(e){return!!this.hasPendingUpdate(ee.SPLIT)||e!==O.ELEVATION&&!this.loadable}get hasPendingUpdates(){return 0!==this._pendingUpdates}hasPendingUpdate(e){return(this._pendingUpdates&e)===e}setPendingUpdate(e){this._pendingUpdates|=e,e===ee.SPLIT||e===ee.MERGE?this._surface.setTileTreeDirty():this._surface.requestUpdate()}resetPendingUpdate(e){return!!this.hasPendingUpdate(e)&&(this._pendingUpdates&=~e,!0)}requestLayerData(e,i,s){const n=this.layerInfo[i][e];if(n.waitingAgents.has(s))return console.warn("agent already requested this piece of map data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),s.tile.lij.toString(),i,e),!0;if(n.waitingAgents.push(s),n.data&&!n.dataInvalidated){console.warn("agent requested existing data (tile %s, agent tile %s, layer: %d/%d)",this.lij.toString(),s.tile.lij.toString(),i,e);const t=n.data&&"type"in n.data&&"vector-tile"===n.data.type;return s.dataArrived(this,t),!0}if(n.requestPromise)return!0;t(n.requestAbort),n.requestAbort=new AbortController;const r=this._surface.requestTileData(this,e,i,n.requestAbort);if(!r)return n.requestAbort=null,!1;const a=()=>{n.requestPromise===r&&(n.requestPromise=null,n.requestAbort=null)};return n.requestPromise=r,r.then(a,a),!0}get isLeaf(){return null==this._children[0]}hasLij(e){return this.lij[0]===e[0]&&this.lij[1]===e[1]&&this.lij[2]===e[2]}findByLij(e){if(this.hasLij(e))return this;const t=this._children;if(!t[0])return null;return t[0].findByLij(e)||t[1].findByLij(e)||t[2].findByLij(e)||t[3].findByLij(e)}distanceToSquared(e){return o(a(Ae,this._center[he.MIDDLE],e))}containsPoint(e){const t=this.extent;return e[0]>=t[0]&&e[1]>=t[1]&&e[0]<=t[2]&&e[1]<=t[3]}containsPointXY(e,t){const i=this.extent;return e>=i[0]&&t>=i[1]&&e<=i[2]&&t<=i[3]}unrequestLayerData(e,t,i){const s=this.layerInfo[t][e],n=s.waitingAgents,r=null!=n.removeUnordered(i);C(r,"agent has not requested this piece of map data"),n.length<1&&(s.abortRequest(),this.setMemoryDirty())}dataArrived(e,t,i){const s=null!=i&&"type"in i&&"vector-tile"===i.type,n=this.layerInfo[t][e];n.data=i,n.dataInvalidated=!1,n.waitingAgents.forAll((e=>e.dataArrived(this,s))),n.waitingAgents.clear(),this.setMemoryDirty()}dataMissing(e,t,i){i.notInTilemap||console.error(`Tile ${this.lij.toString()} layer ${t}/${e} error ${i}`);const s=this.layerInfo[t][e];s.dataMissing=!0,s.waitingAgents.forAll((e=>e.dataMissing())),s.waitingAgents.clear(),this.setMemoryDirty()}updateRenderData(e,t,i){switch(i&&this.forEachLoadedNeighbor((i=>i.updateRenderData(e,t))),e){case O.MAP:return this._updateTexture(t);case O.ELEVATION:return this._updateGeometry()}}_updateTexture(e){this.renderData&&(this.resetPendingUpdate(e===D.FADING?ee.TEXTURE_NOFADING:ee.TEXTURE_FADING),this.setPendingUpdate(e===D.FADING?ee.TEXTURE_FADING:ee.TEXTURE_NOFADING))}_updateGeometry(){this.setPendingUpdate(ee.GEOMETRY);for(const e of this.layerInfo[O.ELEVATION])e.pendingUpdates|=ee.GEOMETRY}invalidateLayerData(e,t){this.layerInfo[t][e].invalidateSourceData(),this.restartAgents(t)}computeElevationBounds(){const e=this._elevationBounds,t=e[0],i=e[1];n(e,1/0,-1/0);const s=this.layerInfo[O.ELEVATION];let r=!0;for(const n of s)null!=n.elevationBounds&&(e[0]=Math.min(e[0],n.elevationBounds.min),e[1]=Math.max(e[1],n.elevationBounds.max),n.elevationBounds.hasNoDataValues||(r=!1));r&&(e[0]=Math.min(e[0],0),e[1]=Math.max(e[1],0)),t===e[0]&&i===e[1]||(this.updateRadiusAndCenter(),this._surface.setTileTreeDirty())}_updateCenter(){const e=this._elevationBounds,t=.5*(e[0]+e[1]),i=this._center;h(Ae,this.up,t),u(i[he.MIDDLE],this.centerAtSeaLevel,Ae),h(Ae,this.up,e[0]),u(i[he.TOP],this.centerAtSeaLevel,Ae),h(Ae,this.up,e[1]),u(i[he.BOTTOM],this.centerAtSeaLevel,Ae)}findElevationBoundsForLayer(e,t){const i=this.layerInfo[O.ELEVATION][e],s=U(this.level),n=Math.max(this.elevationLevel-s,0),r=i.elevationBounds;if(null!=r&&r.level>=t&&r.level<=n)return;const a=this._surface.layerViewByIndex(e,O.ELEVATION),o=P(a);if(!te(this,o,!1))return;const l=le;let h=!1;const u=i.data;if(u&&u.level<=n){const e=i.data;l.min=e.samplerData.data.minValue,l.max=e.samplerData.data.maxValue,l.hasNoDataValues=e.samplerData.data.hasNoDataValues,l.level=this.level,h=!0}else{let t,i,r=0;for(let a=this._parent;a&&(!i||r<s)&&(r=this.elevationLevel-a.level,t=i||t,i=a.layerInfo[O.ELEVATION][e].data,!(!i&&t&&a.level<=n));a=a.parent);i=i||t,i&&(i.computeMinMaxValue(this.lij[0],this.lij[1],this.lij[2],l),l.min!==1/0&&(l.level=i.level,h=!0))}h&&(null==i.elevationBounds&&(i.elevationBounds=new I),i.elevationBounds.copyFrom(l))}modifyLayers(e,t,i){const s=this.layerInfo[i];for(const a of s)a.loadingAgent&&a.loadingAgent!==Q&&(re(a.loadingAgent),a.loadingAgent=null),a.waitingAgents.clear();for(let a=0;a<s.length;++a)void 0===e[a]&&s[a].release();const n=new Array(...s),r=t.length;s.length=r;for(let a=0;a<r;a++){const e=t[a];s[a]=e>-1?n[e]:K.acquire(this._surface.upsampleInfoPool)}this.setMemoryDirty()}restartAgents(e){this.renderData&&(this._createOrUpdateAgents(0,e),this.updateRenderData(e,D.FADING))}updateAgents(e){if(this.renderData){const t=this.layerInfo[e];for(const e of t)e.loadingAgent===Q&&(e.loadingAgent=null);this._createOrUpdateAgents(0,e)}}updateAgentSuspension(){for(const e of S){const t=this._isSuspended(e);for(const i of this.layerInfo[e])i.loadingAgent&&i.loadingAgent!==Q&&(i.loadingAgent.setSuspension(t),i.loadingAgent===Q&&this.updateRenderData(e,D.FADING))}}removeLayerAgent(e,t){const i=this.layerInfo[t][e];i.loadingAgent&&i.loadingAgent!==Q&&i.loadingAgent.dispose(),i.loadingAgent=null}agentDone(e,t){const i=this.layerInfo[t][e];i.loadingAgent=Q,i.data||null!=i.upsampleInfo||this._createOrUpdateAgents(e+1,t)}_hasBlendableAncestor(e){return"normal"!==e.blendMode||T(e.parent)&&this._hasBlendableAncestor(e.parent)}_hasBlendModes(e,t,i){for(let s=e;s<t;++s){const e=this._surface.layerViewByIndex(s,i);if(B(e)&&"normal"!==e?.layer?.blendMode||T(e?.layer?.parent)&&this._hasBlendableAncestor(e?.layer?.parent))return!0}return!1}_createOrUpdateAgents(e,t){const i=this.layerInfo[t];if(0===i.length)return;const s=this._isSuspended(t);for(let n=e;n<i.length;++n){const r=i[n];let a=!1;const o=this._surface.layerViewByIndex(n,t),l=P(o);if(r.loadingAgent?te(this,l,!1)?(r.loadingAgent!==Q&&r.loadingAgent.setSuspension(s),r.loadingAgent!==Q&&(a=r.loadingAgent.update())):r.dispose():te(this,l,!1)&&(r.loadingAgent=ne(this,n,t,s),a=r.loadingAgent.startLoading(),a?r.loadingAgent===Q&&this.setPendingUpdate(ee.GEOMETRY):(re(r.loadingAgent),r.loadingAgent=Q)),r.loadingAgent===Q&&this.updateRenderData(t,D.FADING),!this._hasBlendModes(e,i.length,t)&&a&&o.isOpaque)return}}_isWithinExtent(e){const t=this.extent;return t[0]>=e[0]&&e[2]>=t[2]&&t[1]>=e[1]&&e[3]>=t[3]}intersectsExtent(e){const t=this.extent;return t[2]>=e[0]&&e[2]>=t[0]&&t[3]>=e[1]&&e[3]>=t[1]}getElevationVerticesPerSide(t){const i=this.elevationLevel-this.level,s=Math.max(this.level-t,U(this.level)-i),n=e(1+(this.maxTesselation>>s),2,this.maxTesselation+1),r=this.getDefaultVerticesPerSide();return Math.max(n,r)}get test(){return{cachedMemory:this._cachedMemory}}_findLIJ(e,t){if(!e)return null;const i=this.surface.rootTiles;if(null!=i)for(const s of i)if(ue(s,e)){let i=s,n=e[0]-i.level-1;for(;n>=0&&!i.isLeaf&&!t(i);){const t=e[1]>>n&1,s=e[2]>>n&1;i=i.children[2*t+s],n--}return t(i)?i:null}return null}findNeighborTile(e,t){const i=this.lij,s=this.getNeighborLIJ(i,e);return s?de(i,s)?t(this)?this:null:this._findLIJ(s,t):null}findCorner(e,t){const i=e===x.NORTH_EAST?1:e===x.NORTH_WEST?0:e===x.SOUTH_WEST?2:3;let s=this;for(;s.children[0]&&(!t||!t(s));)s=s.children[i];return s}findNeighborCornerTileExact(e,t){return this.findNeighborTile(e,(e=>t(e)||e.level===this.level))?.findCorner(R(e),t)||null}forAllSubtreeOnSide(e,t){const i=e===x.NORTH?[0,1]:e===x.NORTH_EAST?[1]:e===x.EAST?[1,3]:e===x.SOUTH_EAST?[3]:e===x.SOUTH?[2,3]:e===x.SOUTH_WEST?[2]:e===x.WEST?[0,2]:[0],s=e=>{const n=e.children;!t(e)&&n[0]&&i.forEach((e=>s(n[e])))};s(this)}forallNeighbors(e){V.forEach((t=>this.findNeighborCornerTileExact(t,e))),w.forEach((t=>this.findNeighborTile(t,(t=>t.level===this.level||e(t)))?.forAllSubtreeOnSide(G(t),e)))}getNeighborEdgeStartVertexIndex(e,t){if(!t)return 0;const i=this.level-t.level;if(W(!q||i>=0),0===i)return 0;const s=2**i,n=1==(1&e),r=n?0:1,a=t.lij[r+1]*s,o=this.lij[r+1],l=o-a,h=n?s-1-l:l;return q&&(W(a<=o&&o<a+s),W(0<=h&&h<s)),h}forEachLoadedNeighbor(e){const t=this.level,i=e=>e.level===t||e.isLoaded;w.forEach((t=>{const s=this.findNeighborTile(t,i);null!=s&&s!==this&&s.forAllSubtreeOnSide(G(t),(i=>!!i.isLoaded&&(e(i,t),!0)))})),V.forEach((t=>{const s=this.findNeighborTile(t,i)?.findCorner(R(t),(e=>e.isLoaded));W(!s||ge(this,s,t)),s?.isLoaded&&e(s,t)}))}getNeighborLIJ(e,t){const i=F(t)?-1:H(t)?1:0,s=k(t)?-1:X(t)?1:0,n=[e[0],e[1]+i,e[2]+s];return n[1]<0?null:this.surface.isGlobal?this.wrapLIJ(n):n[2]<0?null:n}wrapLIJ(e){return!e||e[1]<0||e[1]>=2**e[0]?null:this.surface.wrapEastWest(e)}get westNeighborWestExtent(){return this.extent[0]*(this.isWestEnd?-1:1)}get eastNeighborEastExtent(){return this.extent[2]*(this.isEastEnd?-1:1)}get isEastEnd(){return this.lij[2]===this.surface.lijEastEnd(this.level)-1}get isWestEnd(){return 0===this.lij[2]}get isNorthEnd(){return 0===this.lij[1]}get isSouthEnd(){const e=this.surface.extent,t=e?.[1]??null;return null!=t&&this.extent[1]+f()>=t}checkGeometryWaterproofness(){Y&&(W(this.isLoaded),this.renderData?.checkGeometryWaterproofness())}shouldHaveNeighbor(e){const t=this.extent,i=this.surface.rootTilesExtent,s=.25*(t[2]-t[0]);if(F(e)&&t[3]+s>=i[3])return!1;if(H(e)&&t[1]-s<=i[1])return!1;const n=this.surface.isGlobal;return!(!n&&k(e)&&t[0]-s<=i[0])&&!(!n&&X(e)&&t[2]+s>=i[2])}updateDistanceToPOI(e){const t=this._lastPOI;if(this.distanceToPOI>=0&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return;c(this._lastPOI,e);const i=this._center[he.MIDDLE],s=e[0]-i[0],n=e[1]-i[1],r=e[2]-i[2];this.distanceToPOI=s*s+n*n+r*r}}function ne(e,t,i,s){const n=i===O.ELEVATION?oe.acquire():ae.acquire();return n.init(e,t,i,s),n}function re(e){e.dispose(),e instanceof M?oe.release(e):e instanceof N&&ae.release(e)}const ae=new i(N),oe=new i(M),le=new I;var he;function ue(e,t){const i=e.level,s=t[0];if(i>s)return!1;const n=s-i,r=Math.floor(t[1]/2**n),a=Math.floor(t[2]/2**n);return r===e.lij[1]&&a===e.lij[2]}function de(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function ce(e,t,i){if(null==e||null==t)return!1;if(0===e.level&&0===t.level){if(e.isEastEnd&&t.isWestEnd&&i===x.EAST)return!0;if(e.isWestEnd&&t.isEastEnd&&i===x.WEST)return!0}const s=Math.max(1e-6*(e.extent[2]-e.extent[0]),1);switch(i){case x.NORTH:return z(e.extent[3],t.extent[1],s);case x.SOUTH:return z(e.extent[1],t.extent[3],s);case x.EAST:return z(e.extent[2],t.extent[0],s)||z(e.extent[2],-t.extent[0],s);case x.WEST:return z(e.extent[0],t.extent[2],s)||z(e.extent[0],-t.extent[2],s)}}function ge(e,t,i){return null!=e&&null!=t&&t!==e&&(e.level>=t.level?pe(e,t,i):pe(t,e,R(i)))}function pe(e,t,i){W(e.level>=t.level);const s=$(i),n=J(i),r=e.extent,a=t.extent,o=[s?r[0]:r[2],n?r[3]:r[1]],l=[s?a[2]:a[0],n?a[1]:a[3]],h=1e-5*(r[2]-r[0]),u=z(o[0],l[0],h)||e.surface.isGlobal&&z(o[0],-l[0],h),d=z(o[1],l[1],h);if(u&&d)return!0;if(e.level===t.level)return W(!1),!1;if(!u&&!d)return W(!1),!1;const c=u?fe(a[1],a[3],r[1],r[3],h):fe(a[0],a[2],r[0],r[2],h);return W(c),c}function fe(e,t,i,s,n){return e-n<=i&&i<=s&&s<=t+n}!function(e){e[e.TOP=0]="TOP",e[e.MIDDLE=1]="MIDDLE",e[e.BOTTOM=2]="BOTTOM"}(he||(he={}));const me=g(),_e=g(),ye=g(),Ae=g();export{he as CenterPosition,se as Tile,ge as isCornerNeighbor,ce as isEdgeNeighbor};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.28/esri/copyright.txt for details.
4
4
  */
5
- import{disposeMaybe as e,releaseMaybe as t}from"../../../core/maybe.js";import{s as r,j as s}from"../../../chunks/vec2.js";import{Z as o}from"../../../chunks/vec2f64.js";import{isBaseLayer as a,isGroupLayer as i}from"../../../layers/support/layerUtils.js";import{ImageWithType as n}from"../support/StreamDataLoader.js";import{BlendLayersPassParameters as u}from"./BlendLayersTechnique.js";import{TextureUpdate as c}from"./interfaces.js";import{NeighborIndex as l}from"./ITile.js";import{LayerClass as p}from"./LayerClass.js";import{isBlendableLayerView as h,isVectorTileLayerView as d,isVectorTileRenderInfo as m,isImageryTileRenderInfo as _,isRasterTileRenderInfo as f,isTextureTileRenderInfo as T,isVectorTilePerLayerInfo as y}from"./terrainUtils.js";import{ActivationTime as g}from"./TextureFader.js";import{TextureReference as b}from"./TextureReference.js";import{TileCompositor as x}from"./TileCompositor.js";import{TileRenderInfo as w}from"./TileRenderInfo.js";import I from"./TileTexture.js";import{TileUpdate as k}from"./TileUpdate.js";import{blendModeFromString as A}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{BaseOpacityMode as P,BlendLayersOutput as R}from"../webgl-engine/core/shaderLibrary/terrain/TileBackground.glsl.js";import{createColorTexture as E,createEmptyTexture as M}from"../webgl-engine/lib/glUtil3D.js";import{TextureSamplingMode as D,TextureWrapMode as O,PixelFormat as j}from"../../webgl/enums.js";import{Texture as L}from"../../webgl/Texture.js";import{TextureDescriptor as N}from"../../webgl/TextureDescriptor.js";class C{constructor(e,t,r,s){this.start=e,this.end=t,this.blendMode=r,this.opacity=s}}class S{constructor(e,t,r){this._rctx=e,this.tileSize=t,this._techniqueRepository=r,this._passParameters=new u,this._backgroundTexture=null,this._backgroundColor=null,this._backgroundDirty=!1,this._maxAnisotropy=this._rctx.parameters.maxMaxAnisotropy,this._composition=new x(this._rctx,this._techniqueRepository),this._blackTex=new I(E(this._rctx,[0,0,0,1])),this._ensureBackgroundTexture(this.tileSize)}dispose(){this._composition=e(this._composition),this._backgroundTexture=t(this._backgroundTexture),this._blackTex=t(this._blackTex)}get backgroundIsGrid(){return null==this._backgroundColor}get backgroundColor(){return this._backgroundColor}updateTileTexture(e,t){if(!e.renderData)return;const r=e.surface,s=r.baseOpacity;let o=0,n=0,u=this.tileSize,c=!1;const l=r.view.state.contentPixelRatio;let m=!1;H.clear(),X.length=0;const _=e.layerInfo[p.MAP];let f=_.length,T=0,y=null;for(;T<_.length;T++){const t=r.layerViewByIndex(T,p.MAP),g=t.layer.opacity;q[T]=g;const b=t.fullOpacity;if(v[T]=b,a(t.layer)&&f>=_.length&&(f=T),h(t)){z[T]=t.layer.blendMode;let e="normal"!==t.layer.blendMode;if(i(t.layer.parent)){const r=B(t.layer.parent);null!=r&&""!==r&&(e=G(t.layer.parent)||e)}e&&(m=e,c=!1)}if(0===g&&!m){_[T].pendingUpdates&=~(k.TEXTURE_NOFADING&k.TEXTURE_FADING);continue}++n;const x=U(e,T);if(x){if(_[T].pendingUpdates&=~(k.TEXTURE_NOFADING&k.TEXTURE_FADING),i(t.layer.parent)){const e=B(t.layer.parent);null!=e&&""!==e&&F(t.layer.parent,T)}d(t)?u=Math.max(u,this.tileSize*l):1===s&&1===b&&(t.isOpaque||this._dataToTexture(x)&&x.sourceLayerInfo.data.descriptor.isOpaque)&&(c=!0),++o,null===y&&(y=T)}}const g=u/this.tileSize;0!==o&&null!==y?1===o&&!m&&this._useLayerTexture(e,y,f,v[y])||this._composeMapLayers(e,t,T-1,f,q,z,u,g,!c||m,H,m):this._useBackgroundTexture(e,n)}_ensureBackgroundTexture(e){return null==this._backgroundTexture&&(this._backgroundTexture=this._buildTexture(e,!1),this._backgroundDirty=!0),this._backgroundDirty&&(this._composition.bind(e),this._passParameters.offset=o,this._passParameters.scale=1,this._passParameters.opacity=1,null!=this.backgroundColor&&(this._passParameters.backgroundColor=this.backgroundColor),this._composition.drawBackground(this._passParameters,null!=this.backgroundColor),this._composition.copyFBOToTexture(this._backgroundTexture),this._composition.unbind(),this._backgroundDirty=!1),this._backgroundTexture}_useBackgroundTexture(e,t){const r=this._ensureBackgroundTexture(this.tileSize);let s=g.Immediate;(e.surface.view.layerViewManager.updating||t>0)&&(s=g.Delayed);const o=e.renderData;null==o.textureReference&&(s=g.Immediate),o.setTextureReference(new b(r,c.FADING,W,e.surface.baseOpacity,0,1),s)}_useLayerTexture(e,t,r,s){const o=t<r,a=o?1:e.surface.baseOpacity,i=o?e.surface.baseOpacity:1,n=U(e,t);return!!this._dataToTexture(n)&&(e.renderData.setTextureReference(new b(n.sourceLayerInfo.data,c.FADING,n,a,i,s)),!0)}_composeMapLayers(e,t,r,s,a,i,n,u,c,l,p){this._composition.ensureBuffer(n);const h=e.surface.baseOpacity;let d=!1,f=D.LINEAR_MIPMAP_LINEAR,T=!1,y=0;for(let b=r;b>=0;b--){const t=U(e,b);if(!t||0===a[b]&&!p)continue;const r=b<s&&h<1&&!d;r&&(d=!0),this._passParameters.baseOpacity=r?h:1;const g=this._passParameters.baseOpacity<1?P.Required:P.NotRequired;let x=!1;l.forEach((e=>{e.start===b&&(X.push(e),this._composition.openGroup(n),x=!0)}));const w=0===y,I=x?R.GroupBackgroundComposite:c&&w?this.backgroundIsGrid?R.GridComposite:R.ColorComposite:R.Composite,k=A[i[b]];for(m(t)?(this._passParameters.opacity=a[b],T=this._composition.drawVectorData(this._passParameters,I,n,k,g,t,u,this.tileSize,T)):_(t)?(this._passParameters.opacity=a[b],this._composition.drawImageryTileData(this._passParameters,I,n,k,g,t),this._hasNearestInterpolation(t)&&(f=D.NEAREST)):this._dataToTexture(t)&&(this._passParameters.texture=t.sourceLayerInfo.data.texture,this._passParameters.offset=t.offset,this._passParameters.scale=t.scale,this._passParameters.opacity=a[b],this._composition.drawRasterData(this._passParameters,I,n,k,g));X.length>0&&X[X.length-1].end===b;){const e=X.pop();this._passParameters.opacity=e.opacity,this._passParameters.offset=o,this._passParameters.scale=1;const t=c&&w?this.backgroundIsGrid?R.GridComposite:R.ColorComposite:R.Composite;this._composition.drawGroup(this._passParameters,t,n,A[e.blendMode],g)}y++}const g=e.renderData,x=p||d&&h<1,w=g.ensureTexture(n,x,(()=>this._buildTexture(n,x,f)));this._composition.copyFBOToTexture(w),this._composition.unbind(),g.setTextureReference(new b(w,t,W,d?1:h,0,1))}_hasNearestInterpolation(e){const t=e.sourceLayerInfo.data;return!!t.source&&"nearest"===t.interpolation}_dataToTexture(e){if(f(e)){const t=e.sourceLayerInfo;t.data=this._buildTexture(t.data,!0),e.tile.setMemoryDirty()}return T(e)}setBackground(e){this._backgroundColor!==e&&(this._backgroundColor=e,this._backgroundDirty=!0)}_buildTexture(e,t,r=D.LINEAR_MIPMAP_LINEAR){if(null==e)return null;const s=new N;s.wrapMode=O.CLAMP_TO_EDGE,s.samplingMode=r,s.maxAnisotropy=this._maxAnisotropy,s.preMultiplyAlpha=!0,s.flipped=!0,s.hasMipmap=!0,t||(s.pixelFormat=j.RGB);const o=this._rctx;let a;if("number"==typeof e)s.width=s.height=e,a=new I(new L(o,s));else if(e instanceof n)s.isOpaque=e.isOpaque,s.isOpaque&&(s.pixelFormat=j.RGB),a=new I(new L(o,s,e.image)),e.release();else try{s.width=e.width,s.height=e.height,a=new I(new L(o,s,e))}catch(u){a=new I(M(o)),console.warn("TileRenderer: failed to execute 'texImage2D', cross-origin image may not be loaded.")}const i=o.bindTexture(a.texture,L.TEXTURE_UNIT_FOR_UPDATES);return a.generateMipmap(),o.bindTexture(i,L.TEXTURE_UNIT_FOR_UPDATES),a}get test(){return{backgroundTexture:this._backgroundTexture}}}function U(e,t){V.layerIndex=t,V.vtlNeighborInfos.clear();const o=e.layerInfo[p.MAP][t];if(o.data)return r(V.offset,0,0),V.tile=e,V.scale=1,V.sourceLod=e.lij,V.sourceLayerInfo=o,m(V)&&e.forEachLoadedNeighbor(((r,s)=>{if(r.level!==e.level)return;const a=r.layerInfo[p.MAP][t];if(!y(a)||o.data===a.data)return;const i=V.vtlNeighborInfos.pushNew();i.offset=Z[s],i.sourceLod=r.lij,i.sourceLayerInfo=a})),V;const a=o.upsampleInfo;if(a){const e=a.tile.layerInfo[p.MAP][t];return V.tile=a.tile,s(V.offset,a.offset),V.scale=a.scale,V.sourceLod=a.tile.lij,V.sourceLayerInfo=e,V}return null}function B(e){return e.uid}function G(e){let t="normal"!==e.blendMode;return i(e.parent)&&(t=G(e.parent)||t),t}function F(e,t){i(e.parent)&&F(e.parent,t);const r=B(e);if(null!=r&&""!==r){const s=H.get(r);s?s.start=t:H.set(r,new C(t,t,e.blendMode,e.opacity))}}const q=new Array,v=new Array,z=new Array,H=new Map,X=new Array,V=new w,W={offset:[0,0],scale:1},Z=new Array;Z[l.NORTH]=[0,-1],Z[l.NORTH_EAST]=[-1,-1],Z[l.EAST]=[-1,0],Z[l.SOUTH_EAST]=[-1,1],Z[l.SOUTH]=[0,1],Z[l.SOUTH_WEST]=[1,1],Z[l.WEST]=[1,0],Z[l.NORTH_WEST]=[1,-1];export{C as GroupInfo,S as TileRenderer};
5
+ import{disposeMaybe as e,releaseMaybe as t}from"../../../core/maybe.js";import{s as r,j as s}from"../../../chunks/vec2.js";import{Z as o}from"../../../chunks/vec2f64.js";import{isBaseLayer as a,isGroupLayer as i}from"../../../layers/support/layerUtils.js";import{ImageWithType as n}from"../support/StreamDataLoader.js";import{BlendLayersPassParameters as c}from"./BlendLayersTechnique.js";import{TextureUpdate as u}from"./interfaces.js";import{NeighborIndex as l}from"./ITile.js";import{LayerClass as p}from"./LayerClass.js";import{isBlendableLayerView as h,isVectorTileLayerView as d,isVectorTileRenderInfo as m,isImageryTileRenderInfo as _,isRasterTileRenderInfo as f,isTextureTileRenderInfo as T,isVectorTilePerLayerInfo as y}from"./terrainUtils.js";import{ActivationTime as g}from"./TextureFader.js";import{TextureReference as b}from"./TextureReference.js";import{TileCompositor as x}from"./TileCompositor.js";import{TileRenderInfo as w}from"./TileRenderInfo.js";import I from"./TileTexture.js";import{TileUpdate as k}from"./TileUpdate.js";import{blendModeFromString as A}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{BaseOpacityMode as P,BlendLayersOutput as E}from"../webgl-engine/core/shaderLibrary/terrain/TileBackground.glsl.js";import{createEmptyTexture as R}from"../webgl-engine/lib/glUtil3D.js";import{TextureSamplingMode as M,TextureWrapMode as D,PixelFormat as O}from"../../webgl/enums.js";import{Texture as j}from"../../webgl/Texture.js";import{TextureDescriptor as L}from"../../webgl/TextureDescriptor.js";class N{constructor(e,t,r,s){this.start=e,this.end=t,this.blendMode=r,this.opacity=s}}class C{constructor(e,t,r,s){this._rctx=e,this.tileSize=t,this._techniques=r,this._cache=s,this._passParameters=new c,this._backgroundTexture=null,this._backgroundColor=null,this._backgroundDirty=!1,this._maxAnisotropy=this._rctx.parameters.maxMaxAnisotropy,this._composition=new x(this._rctx,this._techniques),this._ensureBackgroundTexture(this.tileSize)}dispose(){this._composition=e(this._composition),this._backgroundTexture=t(this._backgroundTexture)}get backgroundIsGrid(){return null==this._backgroundColor}get backgroundColor(){return this._backgroundColor}updateTileTexture(e,t){if(!e.renderData)return;const r=e.surface,s=r.baseOpacity;let o=0,n=0,c=this.tileSize,u=!1;const l=r.view.state.contentPixelRatio;let m=!1;z.clear(),H.length=0;const _=e.layerInfo[p.MAP];let f=_.length,T=0,y=null;for(;T<_.length;T++){const t=r.layerViewByIndex(T,p.MAP),g=t.layer.opacity;F[T]=g;const b=t.fullOpacity;if(q[T]=b,a(t.layer)&&f>=_.length&&(f=T),h(t)){v[T]=t.layer.blendMode;let e="normal"!==t.layer.blendMode;if(i(t.layer.parent)){const r=U(t.layer.parent);null!=r&&""!==r&&(e=B(t.layer.parent)||e)}e&&(m=e,u=!1)}if(0===g&&!m){_[T].pendingUpdates&=~(k.TEXTURE_NOFADING&k.TEXTURE_FADING);continue}++n;const x=S(e,T);if(x){if(_[T].pendingUpdates&=~(k.TEXTURE_NOFADING&k.TEXTURE_FADING),i(t.layer.parent)){const e=U(t.layer.parent);null!=e&&""!==e&&G(t.layer.parent,T)}d(t)?c=Math.max(c,this.tileSize*l):1===s&&1===b&&(t.isOpaque||this._dataToTexture(x)&&x.sourceLayerInfo.data.descriptor.isOpaque)&&(u=!0),++o,null===y&&(y=T)}}const g=c/this.tileSize;0!==o&&null!==y?1===o&&!m&&this._useLayerTexture(e,y,f,q[y])||this._composeMapLayers(e,t,T-1,f,F,v,c,g,!u||m,z,m):this._useBackgroundTexture(e,n)}_ensureBackgroundTexture(e){return null==this._backgroundTexture&&(this._backgroundTexture=this._buildTexture(e,!1),this._backgroundDirty=!0),this._backgroundDirty&&(this._composition.bind(e),this._passParameters.offset=o,this._passParameters.scale=1,this._passParameters.opacity=1,null!=this.backgroundColor&&(this._passParameters.backgroundColor=this.backgroundColor),this._composition.drawBackground(this._passParameters,null!=this.backgroundColor),this._composition.copyFBOToTexture(this._backgroundTexture),this._composition.unbind(),this._backgroundDirty=!1),this._backgroundTexture}_useBackgroundTexture(e,t){const r=this._ensureBackgroundTexture(this.tileSize);let s=g.Immediate;(e.surface.view.layerViewManager.updating||t>0)&&(s=g.Delayed);const o=e.renderData;null==o.textureReference&&(s=g.Immediate),o.setTextureReference(new b(r,u.FADING,V,e.surface.baseOpacity,0,1),s)}_useLayerTexture(e,t,r,s){const o=t<r,a=o?1:e.surface.baseOpacity,i=o?e.surface.baseOpacity:1,n=S(e,t);return!!this._dataToTexture(n)&&(e.renderData.setTextureReference(new b(n.sourceLayerInfo.data,u.FADING,n,a,i,s)),!0)}_composeMapLayers(e,t,r,s,a,i,n,c,u,l,p){this._composition.ensureBuffer(n);const h=e.surface.baseOpacity;let d=!1,f=M.LINEAR_MIPMAP_LINEAR,T=!1,y=0;for(let b=r;b>=0;b--){const t=S(e,b);if(!t||0===a[b]&&!p)continue;const r=b<s&&h<1&&!d;r&&(d=!0),this._passParameters.baseOpacity=r?h:1;const g=this._passParameters.baseOpacity<1?P.Required:P.NotRequired;let x=!1;l.forEach((e=>{e.start===b&&(H.push(e),this._composition.openGroup(n),x=!0)}));const w=0===y,I=x?E.GroupBackgroundComposite:u&&w?this.backgroundIsGrid?E.GridComposite:E.ColorComposite:E.Composite,k=A[i[b]];for(m(t)?(this._passParameters.opacity=a[b],T=this._composition.drawVectorData(this._passParameters,I,n,k,g,t,c,this.tileSize,T)):_(t)?(this._passParameters.opacity=a[b],this._composition.drawImageryTileData(this._passParameters,I,n,k,g,t),this._hasNearestInterpolation(t)&&(f=M.NEAREST)):this._dataToTexture(t)&&(this._passParameters.texture=t.sourceLayerInfo.data.texture,this._passParameters.offset=t.offset,this._passParameters.scale=t.scale,this._passParameters.opacity=a[b],this._composition.drawRasterData(this._passParameters,I,n,k,g));H.length>0&&H[H.length-1].end===b;){const e=H.pop();this._passParameters.opacity=e.opacity,this._passParameters.offset=o,this._passParameters.scale=1;const t=u&&w?this.backgroundIsGrid?E.GridComposite:E.ColorComposite:E.Composite;this._composition.drawGroup(this._passParameters,t,n,A[e.blendMode],g)}y++}const g=e.renderData,x=p||d&&h<1,w=g.ensureTexture(n,x,(()=>this._buildTexture(n,x,f)));this._composition.copyFBOToTexture(w),this._composition.unbind(),g.setTextureReference(new b(w,t,V,d?1:h,0,1))}_hasNearestInterpolation(e){const t=e.sourceLayerInfo.data;return!!t.source&&"nearest"===t.interpolation}_dataToTexture(e){if(f(e)){const t=e.sourceLayerInfo;t.data=this._buildTexture(t.data,!0),e.tile.setMemoryDirty()}return T(e)}setBackground(e){this._backgroundColor!==e&&(this._backgroundColor=e,this._backgroundDirty=!0)}_buildTexture(e,t,r=M.LINEAR_MIPMAP_LINEAR){if(null==e)return null;const s=new L;s.wrapMode=D.CLAMP_TO_EDGE,s.samplingMode=r,s.maxAnisotropy=this._maxAnisotropy,s.preMultiplyAlpha=!0,s.flipped=!0,s.hasMipmap=!0,t||(s.pixelFormat=O.RGB);const o=this._rctx;let a;if("number"==typeof e){s.width=s.height=e;const t=`${e} ${s.pixelFormat}`,r=this._cache.pop(t);r?(r.retain(),a=r):a=new I(new j(o,s),this._cache)}else if(e instanceof n)s.isOpaque=e.isOpaque,s.isOpaque&&(s.pixelFormat=O.RGB),a=new I(new j(o,s,e.image)),e.release();else try{s.width=e.width,s.height=e.height,a=new I(new j(o,s,e))}catch(c){a=new I(R(o)),console.warn("TileRenderer: failed to execute 'texImage2D', cross-origin image may not be loaded.")}const i=o.bindTexture(a.texture,j.TEXTURE_UNIT_FOR_UPDATES);return a.generateMipmap(),o.bindTexture(i,j.TEXTURE_UNIT_FOR_UPDATES),a}get test(){return{backgroundTexture:this._backgroundTexture}}}function S(e,t){X.layerIndex=t,X.vtlNeighborInfos.clear();const o=e.layerInfo[p.MAP][t];if(o.data)return r(X.offset,0,0),X.tile=e,X.scale=1,X.sourceLod=e.lij,X.sourceLayerInfo=o,m(X)&&e.forEachLoadedNeighbor(((r,s)=>{if(r.level!==e.level)return;const a=r.layerInfo[p.MAP][t];if(!y(a)||o.data===a.data)return;const i=X.vtlNeighborInfos.pushNew();i.offset=W[s],i.sourceLod=r.lij,i.sourceLayerInfo=a})),X;const a=o.upsampleInfo;if(a){const e=a.tile.layerInfo[p.MAP][t];return X.tile=a.tile,s(X.offset,a.offset),X.scale=a.scale,X.sourceLod=a.tile.lij,X.sourceLayerInfo=e,X}return null}function U(e){return e.uid}function B(e){let t="normal"!==e.blendMode;return i(e.parent)&&(t=B(e.parent)||t),t}function G(e,t){i(e.parent)&&G(e.parent,t);const r=U(e);if(null!=r&&""!==r){const s=z.get(r);s?s.start=t:z.set(r,new N(t,t,e.blendMode,e.opacity))}}const F=new Array,q=new Array,v=new Array,z=new Map,H=new Array,X=new w,V={offset:[0,0],scale:1},W=new Array;W[l.NORTH]=[0,-1],W[l.NORTH_EAST]=[-1,-1],W[l.EAST]=[-1,0],W[l.SOUTH_EAST]=[-1,1],W[l.SOUTH]=[0,1],W[l.SOUTH_WEST]=[1,1],W[l.WEST]=[1,0],W[l.NORTH_WEST]=[1,-1];export{N as GroupInfo,C as TileRenderer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.28/esri/copyright.txt for details.
4
4
  */
5
- class t{constructor(t){this._texture=t,this.type="tile-texture",this._refCount=1}retain(){++this._refCount}release(){--this._refCount,0===this._refCount&&this._texture.dispose()}get texture(){return this._texture}generateMipmap(){this._texture.generateMipmap()}get descriptor(){return this._texture.descriptor}get gpuMemoryUsage(){return this._texture.gpuMemoryUsage}}export{t as default};
5
+ class t{constructor(t,e){this._texture=t,this._cache=e,this.type="tile-texture",this._refCount=1}retain(){++this._refCount}release(){if(--this._refCount,0===this._refCount)if(this._cache){const t=`${this._texture.descriptor.width} ${this._texture.descriptor.pixelFormat}`;this._cache.put(t,this)}else this.dispose()}dispose(){this._texture.dispose()}get texture(){return this._texture}generateMipmap(){this._texture.generateMipmap()}get descriptor(){return this._texture.descriptor}get memoryUsage(){return this._texture.gpuMemoryUsage}}export{t as default};
@@ -2,12 +2,12 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.28/esri/copyright.txt for details.
4
4
  */
5
- import{RgbaFloatEncoding as e}from"../util/RgbaFloatEncoding.glsl.js";import{addCameraPosition as t,addPixelRatio as i}from"../util/View.glsl.js";import{Float4PassUniform as o}from"../../shaderModules/Float4PassUniform.js";import{FloatPassUniform as r}from"../../shaderModules/FloatPassUniform.js";import{glsl as l}from"../../shaderModules/interfaces.js";import{Texture2DPassUniform as a}from"../../shaderModules/Texture2DPassUniform.js";import{computeLongestPattern as p,computeTextureSize as s}from"../../../materials/stippleTextureRepository.js";import{ensureColor4 as n}from"../../../shaders/ensureColor4.js";function d(e,t){e.constants.add("stippleAlphaColorDiscard","float",.001),e.constants.add("stippleAlphaHighlightDiscard","float",.5),t.stippleEnabled?c(e,t):f(e)}function c(p,s){const d=!(s.draped&&s.stipplePreferContinuous),{vertex:c,fragment:f}=p;f.include(e),s.draped||(t(c,s),c.uniforms.add(new r("worldToScreenPerDistanceRatio",((e,t)=>1/t.camera.perScreenPixelRatio))),c.code.add(l`float computeWorldToScreenRatio(vec3 segmentCenter) {
5
+ import{RgbaFloatEncoding as e}from"../util/RgbaFloatEncoding.glsl.js";import{addCameraPosition as t,addPixelRatio as o}from"../util/View.glsl.js";import{Float4PassUniform as i}from"../../shaderModules/Float4PassUniform.js";import{FloatPassUniform as r}from"../../shaderModules/FloatPassUniform.js";import{glsl as l}from"../../shaderModules/interfaces.js";import{Texture2DPassUniform as a}from"../../shaderModules/Texture2DPassUniform.js";import{computeLongestPattern as s,computeTextureSize as p}from"../../../materials/stippleTextureRepository.js";import{ensureColor4 as n}from"../../../shaders/ensureColor4.js";function d(e,t){e.constants.add("stippleAlphaColorDiscard","float",.001),e.constants.add("stippleAlphaHighlightDiscard","float",.5),t.stippleEnabled?c(e,t):f(e)}function c(s,p){const d=!(p.draped&&p.stipplePreferContinuous),{vertex:c,fragment:f}=s;f.include(e),p.draped||(t(c,p),c.uniforms.add(new r("worldToScreenPerDistanceRatio",((e,t)=>1/t.camera.perScreenPixelRatio))),c.code.add(l`float computeWorldToScreenRatio(vec3 segmentCenter) {
6
6
  float segmentDistanceToCamera = length(segmentCenter - cameraPosition);
7
7
  return worldToScreenPerDistanceRatio / segmentDistanceToCamera;
8
- }`)),p.varyings.add("vStippleDistance","float"),s.stippleRequiresClamp&&p.varyings.add("vStippleDistanceLimits","vec2"),s.stippleRequiresStretchMeasure&&p.varyings.add("vStipplePatternStretch","float"),c.code.add(l`
8
+ }`)),s.varyings.add("vStippleDistance","float"),p.stippleRequiresClamp&&s.varyings.add("vStippleDistanceLimits","vec2"),p.stippleRequiresStretchMeasure&&s.varyings.add("vStipplePatternStretch","float"),c.code.add(l`
9
9
  float discretizeWorldToScreenRatio(float worldToScreenRatio) {
10
- float step = ${u};
10
+ float step = ${S};
11
11
 
12
12
  float discreteWorldToScreenRatio = log(worldToScreenRatio);
13
13
  discreteWorldToScreenRatio = ceil(discreteWorldToScreenRatio / step) * step;
@@ -16,13 +16,13 @@ return worldToScreenPerDistanceRatio / segmentDistanceToCamera;
16
16
  }
17
17
  `),c.code.add(l`vec2 computeStippleDistanceLimits(float startPseudoScreen, float segmentLengthPseudoScreen, float segmentLengthScreen, float patternLength) {`),c.code.add(l`
18
18
  if (segmentLengthPseudoScreen >= ${d?"patternLength":"1e4"}) {
19
- `),i(c),c.code.add(l`
19
+ `),o(c),c.code.add(l`
20
20
  // Round the screen length to get an integer number of pattern repetitions (minimum 1).
21
21
  float repetitions = segmentLengthScreen / (patternLength * pixelRatio);
22
22
  float flooredRepetitions = max(1.0, floor(repetitions + 0.5));
23
23
  float segmentLengthScreenRounded = flooredRepetitions * patternLength;
24
24
 
25
- ${s.stippleRequiresStretchMeasure?l`
25
+ ${p.stippleRequiresStretchMeasure?l`
26
26
  float stretch = repetitions / flooredRepetitions;
27
27
 
28
28
  // We need to impose a lower bound on the stretch factor to prevent the dots from merging together when there is only 1 repetition.
@@ -33,23 +33,22 @@ return worldToScreenPerDistanceRatio / segmentDistanceToCamera;
33
33
  }
34
34
  return vec2(startPseudoScreen, startPseudoScreen + segmentLengthPseudoScreen);
35
35
  }
36
- `),f.uniforms.add(new a("stipplePatternTexture",(e=>e.stippleTexture)),new r("stipplePatternSDFNormalizer",(e=>m(e.stipplePattern))),new r("stipplePatternPixelSizeInv",(e=>1/S(e)))),f.code.add(l`
36
+ `),f.uniforms.add(new a("stipplePatternTexture",(e=>e.stippleTexture)),new r("stipplePatternSDFNormalizer",(e=>m(e.stipplePattern))),new r("stipplePatternPixelSizeInv",(e=>1/u(e)))),f.code.add(l`
37
37
  float getStippleSDF(out bool isClamped) {
38
- ${s.stippleRequiresClamp?l`
38
+ ${p.stippleRequiresClamp?l`
39
39
  float stippleDistanceClamped = clamp(vStippleDistance, vStippleDistanceLimits.x, vStippleDistanceLimits.y);
40
40
  vec2 aaCorrectedLimits = vStippleDistanceLimits + vec2(1.0, -1.0) / gl_FragCoord.w;
41
41
  isClamped = vStippleDistance < aaCorrectedLimits.x || vStippleDistance > aaCorrectedLimits.y;`:l`
42
42
  float stippleDistanceClamped = vStippleDistance;
43
43
  isClamped = false;`}
44
44
 
45
- float u = stippleDistanceClamped * gl_FragCoord.w * stipplePatternPixelSizeInv;
46
- ${s.stippleScaleWithLineWidth?l`u *= vLineSizeInv;`:""}
45
+ float u = stippleDistanceClamped * gl_FragCoord.w * stipplePatternPixelSizeInv * vLineSizeInv;
47
46
  u = fract(u);
48
47
 
49
48
  float encodedSDF = rgba2float(texture(stipplePatternTexture, vec2(u, 0.5)));
50
49
  float sdf = (encodedSDF * 2.0 - 1.0) * stipplePatternSDFNormalizer;
51
50
 
52
- ${s.stippleRequiresStretchMeasure?l`return (sdf - 0.5) * vStipplePatternStretch + 0.5;`:l`return sdf;`}
51
+ ${p.stippleRequiresStretchMeasure?l`return (sdf - 0.5) * vStipplePatternStretch + 0.5;`:l`return sdf;`}
53
52
  }
54
53
 
55
54
  float getStippleSDF() {
@@ -61,12 +60,12 @@ return worldToScreenPerDistanceRatio / segmentDistanceToCamera;
61
60
  bool isClamped;
62
61
  float stippleSDF = getStippleSDF(isClamped);
63
62
 
64
- float antiAliasedResult = ${s.stippleScaleWithLineWidth?l`clamp(stippleSDF * vLineWidth + 0.5, 0.0, 1.0);`:l`clamp(stippleSDF + 0.5, 0.0, 1.0);`}
63
+ float antiAliasedResult = clamp(stippleSDF * vLineWidth + 0.5, 0.0, 1.0);
65
64
 
66
65
  return isClamped ? floor(antiAliasedResult + 0.5) : antiAliasedResult;
67
66
  }
68
- `),s.stippleOffColorEnabled?(f.uniforms.add(new o("stippleOffColor",(e=>n(e.stippleOffColor)))),f.code.add(l`#define discardByStippleAlpha(stippleAlpha, threshold) {}
67
+ `),p.stippleOffColorEnabled?(f.uniforms.add(new i("stippleOffColor",(e=>n(e.stippleOffColor)))),f.code.add(l`#define discardByStippleAlpha(stippleAlpha, threshold) {}
69
68
  #define blendStipple(color, stippleAlpha) mix(color, stippleOffColor, stippleAlpha)`)):f.code.add(l`#define discardByStippleAlpha(stippleAlpha, threshold) if (stippleAlpha < threshold) { discard; }
70
69
  #define blendStipple(color, stippleAlpha) vec4(color.rgb, color.a * stippleAlpha)`)}function f(e){e.fragment.code.add(l`float getStippleAlpha() { return 1.0; }
71
70
  #define discardByStippleAlpha(_stippleAlpha_, _threshold_) {}
72
- #define blendStipple(color, _stippleAlpha_) color`)}function m(e){return e?(Math.floor(.5*(p(e)-1))+.5)/e.pixelRatio:1}function S(e){const t=e.stipplePattern;return t?s(e.stipplePattern)/t.pixelRatio:1}const u=l.float(.4);export{d as LineStipple,S as computePixelSize};
71
+ #define blendStipple(color, _stippleAlpha_) color`)}function m(e){return e?(Math.floor(.5*(s(e)-1))+.5)/e.pixelRatio:1}function u(e){const t=e.stipplePattern;return t?p(e.stipplePattern)/t.pixelRatio:1}const S=l.float(.4);export{d as LineStipple,u as computePixelSize};