@arcgis/core 5.2.0-next.55 → 5.2.0-next.57

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 (41) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/{0ffd0190adfed8e5937a.js → 2aeb8a4a426ec56f6133.js} +1 -1
  3. package/assets/esri/core/workers/chunks/{2fbb00a29faeaa02912b.js → 2cfd2b433deecec413d3.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{77f19d204a4673b1e676.js → 358b22e4940ae9329ffa.js} +2 -2
  5. package/assets/esri/core/workers/chunks/{847ce06b14a921cd16f0.js → 4a7d48b5c75cb710689a.js} +1 -1
  6. package/assets/esri/core/workers/chunks/4abd54518e35050feb90.js +1 -0
  7. package/assets/esri/core/workers/chunks/61d0ada7627f21988183.js +1 -0
  8. package/assets/esri/core/workers/chunks/{a239f1e82dde4f7ada32.js → 7f67c6e9e0a8fe918711.js} +1 -1
  9. package/assets/esri/core/workers/chunks/8ce649e55fefc8eca55c.js +1 -0
  10. package/assets/esri/core/workers/chunks/{5d6d07ecebf881ad913f.js → 912e9743d006ccc723bf.js} +1 -1
  11. package/assets/esri/core/workers/chunks/{7e2bf6dd26c3cf0b49b0.js → 9de1125b708c4a591edf.js} +1 -1
  12. package/assets/esri/core/workers/chunks/{ce719d3aec8b52bfe160.js → ba65c976eaa458d82ab9.js} +1 -1
  13. package/assets/esri/core/workers/chunks/c25dc9073e73d6b44d88.js +1 -0
  14. package/assets/esri/core/workers/chunks/{c38992b250731137cb1a.js → c39b6707d8284d57ff26.js} +1 -1
  15. package/assets/esri/core/workers/chunks/{2d6d2d4df05bba9fa4a6.js → f9e299ac2d1c9ef78326.js} +1 -1
  16. package/config.js +1 -1
  17. package/core/has.js +1 -1
  18. package/geometry/support/normalizeUtilsSync.js +1 -1
  19. package/kernel.js +1 -1
  20. package/package.json +6 -6
  21. package/support/revision.js +1 -1
  22. package/views/3d/analysis/LineOfSight/LineOfSightTool.js +1 -1
  23. package/views/3d/analysis/LineOfSightAnalysisView3D.js +1 -1
  24. package/views/3d/layers/GaussianSplatLayerView3D.js +1 -1
  25. package/views/3d/layers/I3SMeshView3D.js +1 -1
  26. package/views/3d/layers/IntegratedMesh3DTilesLayerView3D.js +1 -1
  27. package/views/3d/layers/SceneLayerWorkerHandle.js +1 -1
  28. package/views/3d/layers/graphics/SpatialIndex2D.js +1 -1
  29. package/views/3d/layers/i3s/LayerElevationProvider.js +1 -1
  30. package/views/3d/layers/support/StageLayerElevationProvider.js +1 -1
  31. package/views/3d/support/ElevationUpdateEvent.js +2 -0
  32. package/views/3d/support/elevationUpdateExtentUtils.js +2 -0
  33. package/views/3d/terrain/TerrainSurface.js +1 -1
  34. package/views/SceneView.js +1 -1
  35. package/assets/esri/core/workers/chunks/2da337d7fd9295f6b967.js +0 -1
  36. package/assets/esri/core/workers/chunks/9e474465d069cb9e94f5.js +0 -1
  37. package/assets/esri/core/workers/chunks/c5043c42a6aaa276a521.js +0 -1
  38. package/assets/esri/core/workers/chunks/c8db0a4fb5bc982dc9fc.js +0 -1
  39. package/views/3d/analysis/LineOfSight/LineOfSightTool2.js +0 -2
  40. package/views/3d/terrain/ElevationUpdateEvent.js +0 -2
  41. /package/assets/esri/core/workers/chunks/{77f19d204a4673b1e676.js.LICENSE.txt → 358b22e4940ae9329ffa.js.LICENSE.txt} +0 -0
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import has from"../../../core/has.js";import t from"../../../core/Logger.js";import{abortMaybe as i,destroyMaybe as r,removeMaybe as s}from"../../../core/maybe.js";import{throwIfAborted as o}from"../../../core/promiseUtils.js";import{initial as n,watch as a,when as l}from"../../../core/reactiveUtils.js";import{schedule as c}from"../../../core/scheduling.js";import{unitFromRESTJSON as h,convertUnit as d}from"../../../core/units.js";import{property as u,subclass as m}from"../../../core/accessorSupport/decorators.js";import{fromMat4 as p,invert as f}from"../../../core/libs/gl-matrix-2/math/mat3.js";import{create as b,IDENTITY as g}from"../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{create as y}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{fromValues as _}from"../../../core/libs/gl-matrix-2/factories/quatf64.js";import{normalize as v,sub as w,dot as C,set as x}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as T,freeze as j,clone as E,ZEROS as R,fromValues as M}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{fromValues as O,clone as S,ONES as V}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{isMoon as U,isMars as H,getReferenceEllipsoid as D,SphericalECEFSpatialReferenceLike as I}from"../../../geometry/ellipsoidUtils.js";import P from"../../../geometry/HeightModelInfo.js";import{computeTranslationToOriginAndRotation as k}from"../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{localLinearScaleFactors as L}from"../../../geometry/projection/localLinearScaleFactors.js";import{projectVectorToVector as A}from"../../../geometry/projection/projectVectorToVector.js";import{create as F}from"../../../geometry/support/aaBoundingRect.js";import{isCompatible as G}from"../../../geometry/support/heightModelInfoUtils.js";import{isPlateCarree as z,isWebMercator as B,equals as N,isGeographic as W,isCGCS2000 as q}from"../../../geometry/support/spatialReferenceUtils.js";import X from"../../../geometry/support/WKIDUnitConversion.js";import{BufferViewVec4f as $,BufferViewVec4u8 as Z,BufferViewVec4u16 as Y,BufferViewVec3f as J,BufferViewVec3u8 as K,BufferViewVec3u16 as Q,BufferViewVec2f as ee,BufferViewUint32 as te,BufferViewUint16 as ie}from"../../../geometry/support/buffer/BufferView.js";import re from"../../../layers/support/SceneModification.js";import{getHeightModelInfoFromVCS as se,validateMeshData as oe,makeCacheKey as ne}from"../../../layers/support/tiles3DUtils.js";import{getElevationOffsetInMeters as ae}from"../../../support/elevationInfoUtils.js";import{IntegratedMesh3DTilesLayerWorkerHandle as le}from"./IntegratedMesh3DTilesLayerWorkerHandle.js";import{LayerView3D as ce}from"./LayerView3D.js";import{Lyr3DViewPerformanceInfo as he}from"./Lyr3DViewPerformanceInfo.js";import{addLayerViewToWasm as de,removeLayerViewFromWasm as ue,getLyr3DWasm as me}from"./Lyr3DWasm.js";import{toWasmModification as pe}from"./SceneLayerWorkerHandle.js";import{LayerElevationProvider as fe}from"./i3s/LayerElevationProvider.js";import{IntegratedMesh3DTilesLayerView3DSymbol as be}from"./support/integratedMesh3DTilesLayerViewInstanceUtils.js";import{primTypeConversion as ge,alphaModeConversion as ye,faceCullingConversion as _e,wrapModeConversion as ve}from"./support/lyr3dTypeConversions.js";import{makeScheduleFunction as we}from"./support/makeScheduleFunction.js";import{Tiles3DMeshIntersectionHandler as Ce}from"./support/Tiles3DMeshIntersectionHandler.js";import{Frustum as xe}from"../state/Frustum.js";import{ElevationRange as Te}from"../support/ElevationRange.js";import{toBoundingRect as je}from"../support/extentUtils.js";import{Obb as Ee}from"../support/orientedBoundingBox.js";import{glLayout as Re}from"../support/buffer/glUtil.js";import{ComponentGeometryParameters as Me,SourceGeometry as Oe}from"../webgl-engine/collections/Component/SourceGeometry.js";import{Transform as Se}from"../webgl-engine/collections/Component/Transform.js";import{RenderTexture as Ve}from"../webgl-engine/core/material/RenderTexture.js";import{ManagedTexture as Ue}from"../webgl-engine/lib/ManagedTexture.js";import{compressNormals as He}from"../webgl-engine/lib/Normals.js";import{advancedMRRFactors as De}from"../webgl-engine/materials/pbrUtils.js";import Ie from"../../layers/LayerView.js";import{spatialReferenceIncompatibleError as Pe,isInEffectiveScaleRange as ke,validateScaleRange as Le}from"../../support/layerViewUtils.js";import{TaskPriority as Ae}from"../../support/Scheduler.js";import{TextureCompressionTracker as Fe}from"../../support/TextureCompressionTracker.js";import{CompressedTextureFormat as Ge,SizedPixelFormat as ze}from"../../webgl/enums.js";import{alphaCutoff as Be}from"../../../webscene/support/AlphaCutoff.js";var Ne;function We(e,t,i){if("image/vnd-ms.dds"===t)switch(i){case"Dxt1":return Ge.COMPRESSED_RGB_S3TC_DXT1_EXT;case"Dxt5":return Ge.COMPRESSED_RGBA_S3TC_DXT5_EXT;default:return null}if("image/ktx2"===t)return null;switch(e){case 33319:return ze.RG8;case 6407:return ze.RGB8;case 6408:return ze.RGBA8;case 6403:return ze.R8;default:return null}}let qe=class extends(ce(Ie)){static{Ne=be}constructor(e){super(e),this[Ne]=!0,this.type="integrated-mesh-3dtiles",this._modifications=new Array,this._visibleGeometryChangedSchedulerHandle=null,this._initializationController=null,this._wasmLayerId=-1,this._metersPerVCSUnit=1,this.ignoresMemoryFactor=!1,this._usedMemory=0,this._cacheMemory=0,this._useEsriCrs=!1,this.drapeTargetType=1,this.fullExtentInLocalViewSpatialReference=null,this._replacesTerrain=!1,this._isUsedAsGroundLayer=!1,this._applySSAO=!has("disable-feature:im-ssao"),this._imShading=!!has("enable-feature:im-shading"),this._imVertexNormals=!!has("enable-feature:im-vertex-normals"),this._lyrHandleToObjects=new Map,this._visibleObjects=new Set,this._loadedObjects=new Set,this._compressionTracker=new Fe,this._dbgFlags=new Set;const t=e.view.resourceController;this._memCache=t.memoryController.newCache(`IM3DTiles-${this.uid}`,e=>this._deletePerObjectData(e)),this._replacesTerrain=e.layer.replacesTerrain,this._isUsedAsGroundLayer=e.layer.isUsedAsGroundLayer,this._frameTask=t.scheduler.registerTask(Ae.TILES3D,this),this._frustum=new xe(e.view.renderCoordsHelper)}tryRecycleWith(e,t){return this.canRecycleWith(e)?e.load(t).then(()=>{o(t);const i=this.layer.queryElevationCallback;this.layer=e,this.layer.queryElevationCallback=i}):null}canRecycleWith(e){return e.url===this.layer.url&&"integrated-mesh-3dtiles"===e.type&&e.replacesTerrain===this._replacesTerrain&&e.isUsedAsGroundLayer===this._isUsedAsGroundLayer}initialize(){this._dbg(2,"Tiles3DLayerView3D initialize() called");const{view:e}=this;if(this._workerHandle=new le(we(e.resourceController)),this._updatingHandles.add(()=>this.layer.modifications,()=>this._loadModifications(),n),!this._canProjectWithoutEngine())throw Pe("layer",this.layer.spatialReference.wkid,e.renderSpatialReference?.wkid);this._initializationController=new AbortController;const t=de(this,this._initializationController.signal).then(t=>{o(this._initializationController.signal),this._wasmLayerId=t,this._intersectionHandler=new Ce(this),e.sceneIntersectionHelper.addIntersectionHandler(this._intersectionHandler),this._updatingHandles.add(()=>this.slicePlaneEnabled,e=>this._slicePlaneEnabledChange(e)),this._updatingHandles.add(()=>this._modifications,()=>this._modificationsChanged()),this._updatingHandles.add(()=>this.fullOpacity,()=>this._opacityChange()),this._updatingHandles.add(()=>e.clippingArea,()=>this._clippingAreaChanged(),n),this._updatingHandles.add(()=>e.state.contentCamera,()=>this._cameraChanged(),n),this._elevationProvider=new fe({view:e,layerElevationSource:this,intersectionHandler:this._intersectionHandler});const i=this._replacesTerrain?0:1;e.elevationProvider.register(i,this._elevationProvider),e.overlayManager.registerDrapeTarget(this),this.addHandles([a(()=>this.layer.elevationInfo,e=>this._elevationInfoChanged(e)),l(()=>this.fullOpacity,()=>this._opacityChange()),a(()=>this.suspended,e=>this._wasm?.setEnabled(this,!e),n)]),this._initializationController=null});this.layer.queryElevationCallback=(e,t)=>this._wasm.queryElevation(this,e,t),this.addResolvingPromise(t)}destroy(){this._initializationController=i(this._initializationController),this._dbg(2,"Tiles3DLayerView3D destroy() called"),this._workerHandle?.destroyContextAndSelf(this.uid),ue(this),this.layer.queryElevationCallback=null,this._intersectionHandler&&(this.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler),this._intersectionHandler.destroy(),this._intersectionHandler=null),this._elevationProvider&&(this._elevationProvider.notifyObjectsChangedFunctional(e=>this.forEachComponentObject(t=>e(t.obb))),this.view.elevationProvider.unregister(this._elevationProvider),this._elevationProvider=null),this.view.overlayManager.unregisterDrapeTarget(this),this._lyrHandleToObjects.forEach(e=>this.freeObject(e)),this._lyrHandleToObjects.clear(),this._visibleObjects.clear(),this._loadedObjects.clear(),this._usedMemory=0,this._cacheMemory=0,this._memCache.destroy(),this._frameTask.remove(),this._updatingHandles=r(this._updatingHandles),this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=s(this._visibleGeometryChangedSchedulerHandle)}get fullOpacity(){return this.layer.replacesTerrain?this.view.map.ground.opacity:1}get hasModifications(){return this._modifications&&this._modifications.length>0}_opacityChange(){const{fullOpacity:e}=this;this.forEachComponentObject(t=>this._collection.updateObjectOpacity(t,e))}_cameraChanged(){const e=this._frustum;e.update(this.view.state.contentCamera);const t=this._visibleObjects;let i=!1;this._loadedObjects.forEach(r=>{const s=r.obb?.intersectsFrustum(e)??!1;s!==r.isVisible&&(r.isVisible=s,s?t.add(r):t.delete(r),r.componentObjects.forEach(e=>this._collection.setObjectVisibility(e,s)),i||=this._isVisibileElevationRangeModifiedByChangedTileVisbility(s,r.elevationRange))}),i&&this._setVisibleElevationRangeDirty()}intersect(e,t,i,r){this._intersectionHandler.intersectRay(e,t,i,r,null,!1)}get ready(){return!this.layer.replacesTerrain||!!this._wasm?.isTerrainReady}_modificationsChanged(){const e=this.useEsriCrs?this.layer.supportedSpatialReferences[1]:this.layer.supportedSpatialReferences[0],t=pe(this._layerClippingArea,this._modifications,e);this._wasm?.setMeshModifications(this,t)}_clippingAreaChanged(){const e=this.layer.spatialReference,t=F();this._layerClippingArea=je(this.view.clippingArea,t,e)?t:null,this._modificationsChanged()}_visibleGeometryChanged(){this._visibleGeometryChangedSchedulerHandle??=c(()=>{this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=null})}_slicePlaneEnabledChange(e){this._intersectionHandler&&(this._intersectionHandler.slicePlaneEnabled=e&&!this.layer.replacesTerrain),this.forEachComponentObject(t=>t.updateMaterial({slicePlaneEnabled:e}))}_elevationInfoChanged(e){this._wasm?.setLayerOffset(this,ae(e))}get _wasm(){return me(this.view)}get wasmLayerId(){return this._wasmLayerId}get metersPerVCSUnit(){return this._metersPerVCSUnit}get usedMemory(){return this._usedMemory}get unloadedMemory(){return 0}get cachedMemory(){return this._cacheMemory}get useEsriCrs(){return this._useEsriCrs}get visibleAtCurrentScale(){return this.layer.isUsedAsGroundLayer||ke(this.layer.effectiveScaleRange,this.view.scale)}canResume(){const e=this.layer&&"effectiveScaleRange"in this.layer?this.layer.effectiveScaleRange:null;return this.visible&&this.layer?.loaded&&this.parent&&!this.parent.suspended&&this.view?.ready&&(this.layer.isUsedAsGroundLayer||Le(e)&&this.visibleAtCurrentScale)&&this.visibleAtCurrentTimeExtent||!1}get performanceInfo(){let e=0,t=0,i=0,r=0,s=0,o=0;return this._lyrHandleToObjects.forEach(n=>{n.isLoaded?(e+=n.textureMemoryUsage,t+=n.vboMemoryUsage,s++):(i+=n.textureMemoryUsage,r+=n.vboMemoryUsage,o++)}),new he(this.usedMemory,s,o,Ze(t),Ze(e),Ze(r),Ze(i))}_canProjectWithoutEngine(){if(1===this.view.state.viewingMode)return!0;if(z(this.view.renderSpatialReference)||B(this.view.renderSpatialReference))return!0;if(this.layer.esriCrsSpatialReference&&N(this.layer.esriCrsSpatialReference,this.view.renderSpatialReference)){if(115700===this.layer.esriCrsSpatialReference.vcsWkid)return!1;let e=se(this.layer.esriCrsSpatialReference);if(!e){const t=this.layer.esriCrsSpatialReference;let i="meters";!W(t)&&t.wkid&&-1!==t.wkid&&(i=h(X.units[X[t.wkid]])),i&&(e=new P({heightModel:"gravity-related-height",heightUnit:i}))}const t=this.view.heightModelInfo;return this._useEsriCrs=0===G(e,t,!1),this._useEsriCrs&&(e&&(this._metersPerVCSUnit=d(1,e.heightUnit,"meters")),this.fullExtentInLocalViewSpatialReference=this.layer.esriCrsFullExtent),this._useEsriCrs}return!1}get _stage(){return this.view.stage}get _collection(){return this._stage.renderView.componentObjectCollection}get elevationProvider(){return this._elevationProvider}get elevationOffset(){return ae(this.layer.elevationInfo)}get elevationRange(){const e=this.fullExtent;return e?.zmin&&e?.zmax?new Te(e.zmin,e.zmax):null}getElevationRange(e){return this._intersectionHandler.getElevationRange(e)}get visibleElevationRange(){const e=new Te;0===this._visibleObjects.size?e.setElevationRangeValues(0,0):(e.setElevationRangeValues(1/0,-1/0),this._forEachRelevantVisibleTile(t=>e.expandElevationRange(t.elevationRange)),e.minElevation===1/0&&e.setElevationRangeValues(0,0));const t=this._get("visibleElevationRange");return t&&t.minElevation===e.minElevation&&t.maxElevation===e.maxElevation?t:e}_setVisibleElevationRangeDirty(){this.notifyChange("visibleElevationRange")}_forEachRelevantVisibleTile(e){const{view:t}=this,{spatialReference:i}=t,r=i.isWGS84||i.isWebMercator||q(i)||U(i)||H(i);if(this.view.state.isGlobal||!r)return this.forEachVisibleTile(e);const s=D(i).radius,{eye:o,viewForward:n,near:a}=t.state.camera,l=v(T(),n),c=500,h=Math.max(o[2],c),d=h+s,u=Math.sqrt(d**2-s**2),m=Math.abs(Math.atan2(u,s))*s,p=h>.5*s?.5*Math.PI*s:m,f=T();this.forEachVisibleTile(t=>{const{mbsRadius:i,mbsCenter:r}=t;if(i<0)return;w(f,r,o);const s=C(f,l);Math.abs(s)<p&&s+i>a&&s-i<p&&e(t)})}get fullExtent(){return this.layer.fullExtent}forEachComponentObject(e){this._forEachObject(this._lyrHandleToObjects.values(),e)}forEachVisibleTile(e){for(const t of this._visibleObjects)e(t)}forEachTile(e){for(const t of this._loadedObjects)e(t)}forEachVisibleComponentObject(e){this._forEachObject(this._visibleObjects,e)}_forEachObject(e,t){for(const{componentObjects:i}of e)for(const e of i)t(e)}isUpdating(){const e=this._wasm;return this._wasmLayerId>=0&&null!=e&&(e.isUpdating(this._wasmLayerId)||this._compressionTracker.compressing)}get readyToRun(){return!!this._frameTask?.readyToRun}runTask(e){this._frameTask.processQueue(e)}updatingFlagChanged(){this.notifyChange("updating")}async createRenderable(e){if(this.destroyed||this.destroying)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderable called after destroy");const{meshData:t}=e;if(!oe(t))throw new Error("meshData not valid");const i=new Map;let r;try{r=this._createPrimitiveTextureBundles(t,i)}catch(o){throw i.forEach(e=>this._stage?.removeTexture(e)),o}let s=null;try{if(s=await this._createRenderableMain(t,r),this.destroyed)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderable aborted due to destroyed instance");const{tileObb:o,componentObjects:n,elevationRange:a}=s;let l=0,c=0,h=0;for(const e of n){const{texture:t,textureMetallicRoughness:i,textureEmissive:r,textureOcclusion:s,textureNormal:o}=e.renderable.drawParameters;l+=(t?.usedMemory??0)+(i?.usedMemory??0)+(r?.usedMemory??0)+(s?.usedMemory??0)+(o?.usedMemory??0),c+=this._collection.getObjectGPUMemoryUsage(e),h+=e.intersectionGeometry.usedMemory}const d=Array.from(i.values()),u=new $e(e.handle,n,d,h,c,l,o,e.stableNodeId,e.nodeDepth,a);return this._lyrHandleToObjects.set(e.handle,u),()=>{this._memCache.put(ne(u.handle),u);const{usedMemory:e}=u;return this._cacheMemory+=e,{memUsageBytes:e}}}catch(o){throw r.forEach(e=>e.cleanup()),s?.componentObjects.forEach(e=>this._collection.destroyObject(e)),i.forEach(e=>this._stage?.removeTexture(e)),o}}_createPrimitiveTextureBundles(e,t){const i=new Array,r=e.desc.prims.length;try{const s=e.desc;for(let o=0;o<r;o++){const r=s.prims[o].materialId,n=s.materials&&null!=r?s.materials[r]:null;let a=Promise.resolve(Je),l=null,c=null,h=null,d=null,u=null;if(n){const i="Pbr"===n.lightingModel;l=this._getTexture(n.baseColorTex,e,t),c=i?this._getTexture(n.metalTex,e,t):null,h=i?this._getTexture(n.emissiveTex,e,t):null,d=i?this._getTexture(n.occlusionTex,e,t):null,u=i?this._getTexture(n.normalTex,e,t):null;const r=[l,c,h,d,u].map(e=>e?.loadPromise??null);a=Promise.all(r)}i.push(new Ke(a,l,c,h,d,u))}}catch(s){throw i.forEach(e=>e.cleanup()),s}return i}async _createRenderableMain(e,t){if(this.destroyed||this.destroying)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderableMain called after destroy");const i=new Array,r=e.desc,s=e.data.buffer,o=r.prims.length,n=j(...r.origin),a=this.view.basemapTerrain.spatialReference,l=this.view.state.isGlobal;let c=g;if(l){const e=y();k(I,n,e,a),c=p(b(),e)}if(null==r.obb)throw new Error("meshData.desc.obb undefined");const h=Ye(r.obb),d=l?D(this.view.spatialReference).radius:0,u=new Array;try{for(let i=0;i<o;i++){const e=r.prims[i],o=t[i];this._dbgFlags.has(2)&&this._dbg(2,JSON.stringify(e));if(null==ge[e.ptype]){this._dbg(2,"[Unsupported Feature] Unsupported primitive mode ("+e.ptype+"). Skipping primitive."),o.cleanup();continue}const{positionView:n,normalsData:a,colorView:l,texCoord0Data:c,indicesView:h}=this.getBufferViews(e,s);if(null==n||null==h){o.cleanup();continue}const d=n.count,m=(e,t)=>null==e||e===d||(this._dbg(3,`${t} !== numPos. Skipping primitive.`),!1);m(null!=c?c.length/2:void 0,"numTexcoord")&&m(l?.count,"numColors")&&m(a?.length,"normals")?u.push({componentIndex:i,positionView:n,indicesView:h,texCoord0Data:c,colorView:l,normalsData:a}):o.cleanup()}const e=c!==g,m=e?f(b(),c)??g:g,{vertexProcessingOutputs:p,obbHalfSizeAccumulator:y,elevationRange:_}=await this._workerHandle.processTiles3DVertices(u,n,d,l,c,h,this._imVertexNormals&&!this._isUsedAsGroundLayer);if(this.destroyed)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderableMain aborted due to destroyed instance");const v=r.materials;if(await Promise.all(t.map(e=>e.materialPromise)),this.destroyed)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderableMain aborted due to destroyed instance");p.length>0&&h.setHalfSize(y);for(const s of p){const{componentIndex:o,positionView:l,indicesView:c,layout:d,textureCoordinateType:u,interleavedVertexData:p,indices:f}=s,b=r.prims[o],g=t[o],y=h.clone(),_=Re(d),w=new Uint32Array([0,c.typedBuffer.length]),C=new Me(_,this._imShading?2:0,u,e?2:0),x=new Oe({interleavedVertexData:p,vertexCount:p.byteLength/_[0].stride,indexData:f},{positions:l.typedBuffer,indices:c.typedBuffer},w,C),j=this.view.renderSpatialReference,E=T(),R=[1,1,1];L(n,j,R,a)||this._dbg(3,"Unsupported coordinate system for IM overlay"),A(n,j,E,a);const M=v&&null!=b.materialId?v[b.materialId]:null,S=this._createComponentMaterialInitParameters(M,g);S.baseColorTexture||this._dbg(3,"No colour texture 1");const V=this._collection.createObject({toMapSpace:O(E[0],E[1],R[0],R[1]),transform:new Se(n,m),obb:y,geometry:x,elevationAlignable:!1},S);i.push(V)}const{fullExtent:w}=this.layer;return w?.hasZ&&w.zmax&&w.zmin&&(_.minElevation=Math.max(_.minElevation,w.zmin),_.maxElevation=Math.min(_.maxElevation,w.zmax)),{tileObb:h,componentObjects:i,elevationRange:_}}catch(m){throw i.forEach(e=>this._collection.destroyObject(e)),m}}_createComponentMaterialInitParameters(e,t){const i="Pbr"===(null!=e?e.lightingModel:"Unlit");let r=V,s=Be,o=1,n=!1,a=2,l=M(0,0,0);const c=E(De),h=t.baseColorTexture,d=t.metallicRoughnessTexture,u=t.emissionTexture,m=t.occlusionTexture,p=t.normalTexture;return e&&(r=S(e.baseColorFactor),s=e.alphaCutoff??Be,i&&(x(c,e.metallicFactor,e.roughnessFactor,0),e.emissiveFactor&&(l=e.emissiveFactor)),o=ye[e.alphaMode],n=e.isDoubleSided,a=_e[e.faceCulling??"NotSet"]),{isIntegratedMesh:!0,baseColor:r,textureAlphaCutoff:s,mrrFactors:c,baseColorTexture:h,metallicRoughnessTexture:d,normalTexture:p,occlusionTexture:m,emissionTexture:u,hasParametersFromSource:!1,sphereDepthInterpolate:this.layer.hasGoogleUrl,alphaDiscardMode:o,doubleSided:n,cullFace:a,isGround:this.layer.replacesTerrain,emissiveBaseColor:l,usePBR:i,slicePlaneEnabled:this.slicePlaneEnabled,opacity:this.fullOpacity,polygonOffset:0,ellipsoidMode:1,applySSAO:this._applySSAO}}freeRenderable(e){const t=this._lyrHandleToObjects.get(e);t?(t.isLoaded?(this._loadedObjects.delete(t),this._visibleObjects.delete(t),this._intersectionHandler.removeTile(t),this._usedMemory-=t.usedMemory):this._cacheMemory-=t.usedMemory,this.freeObject(t),this._lyrHandleToObjects.delete(e)):this._dbg(3,`freeRendedrable on non-existent renderable ${e}`)}freeObject(e){const t=ne(e.handle);this._memCache.pop(t),e.textures.forEach(e=>this._stage.removeTexture(e)),e.componentObjects.forEach(e=>this._collection.destroyObject(e))}setRenderableVisibility(e,t,i){if(this.destroyed||this.destroying)return;const r=this._frustum,s=new Array;let o=!1,n=!1;for(let a=0;a<i;++a){if(!t[a])continue;const i=e[a],l=this._lyrHandleToObjects.get(i);if(l){if(l.isLoaded){this._dbg(3,`Already loaded object marked loaded again ${l.stableNodeId}`);continue}o=!0,l.isLoaded=!0,this._loadedObjects.add(l),this._intersectionHandler.addTile(l),this._usedMemory+=l.usedMemory,this._cacheMemory-=l.usedMemory;const e=l.obb?.intersectsFrustum(r)??!0;l.isVisible=e,e&&(this._visibleObjects.add(l),n||=this._isVisibileElevationRangeModifiedByChangedTileVisbility(e,l.elevationRange)),s.push(l.obb),l.componentObjects.forEach(t=>{this._collection.setObjectVisibility(t,e)}),this._memCache.pop(ne(i))}else this._dbg(3,`Tried to mark Non existent object ${i} as loaded`)}for(let a=0;a<i;++a){const i=e[a];if(t[a])continue;const r=this._lyrHandleToObjects.get(i);if(r){if(!r.isLoaded){this._dbg(3,`Tried to unload not-loaded object ${r.stableNodeId}`);continue}const e=r.isVisible;this._visibleObjects.delete(r),r.isVisible=!1,r.isLoaded=!1,this._loadedObjects.delete(r),this._intersectionHandler.removeTile(r),e&&(this._visibleGeometryChanged(),n||=this._isVisibileElevationRangeModifiedByChangedTileVisbility(!1,r.elevationRange)),this._usedMemory-=r.usedMemory,this._cacheMemory+=r.usedMemory,s.push(r.obb),r.componentObjects.forEach(e=>{this._collection.setObjectVisibility(e,!1)}),this._memCache.put(ne(i),r)}else this._dbg(3,`Tried to mark Non existent object ${i} as not loaded`)}o&&this._visibleGeometryChanged(),s.length>0&&this._elevationProvider.notifyObjectsChanged(s),n&&this._setVisibleElevationRangeDirty()}setLodPixelThreshold(e){this._wasm?.setLodPixelThreshold(this,e)}_isVisibileElevationRangeModifiedByChangedTileVisbility(e,t){const{visibleElevationRange:i}=this,{minElevation:r,maxElevation:s}=t;return e?r<i.minElevation||s>i.maxElevation:r===i.minElevation||s===i.maxElevation}_getTexture(e,t,i){const r=e&&t.desc?.images?.[e.imageId];if(!r||!t.data?.buffer)return null;const s=i.get(r)??this._createTexture(e,t,i);return s?new Ve(this._stage.renderView.textures,s.id):null}_createTexture(e,t,i){const r=e&&t.desc?.images?.[e.imageId];if(!r||!t.data?.buffer)return null;const s=this._stage.renderView.renderingContext.parameters.maxMaxAnisotropy,o=!!r.mipCount||s>1,n=ve[e.wrapMode??"None"];let a=r.alpha?6408:6407;const l=new Uint8Array(t.data.buffer,r.data.byteOffset,r.data.byteCount);let c=null,h=null,d=null;switch(r.format){case"Raw":"R8"===r.pixelFormat?(c=l,a=6403,h=""):"Rg8"===r.pixelFormat||"Ga8"===r.pixelFormat?(c=l,a=33319,h=""):"Rgb8"===r.pixelFormat?(c=l,a=6407,h=""):"Rgba8"===r.pixelFormat&&(c=l,a=6408,h="");break;case"Dxt1":c=l,a=6407,h="image/vnd-ms.dds";break;case"Dxt5":c=l,a=6408,h="image/vnd-ms.dds";break;case"Basis":c=l,a=6407,h="image/ktx2";break;case"Png":h="image/png",d=document.createElement("img");break;case"Jpeg":h="image/jpeg",d=document.createElement("img");break;case"Etc2":h="image/ktx",d=document.createElement("img");break;case"Astc":this._dbg(3,"Astc texture not supported");break;case"Pvrtc":this._dbg(3,"Pvrtc texture not supported")}if(d&&h){const e=new Blob([l],{type:h});d.src=URL.createObjectURL(e),c=d}if(c&&null!=h){const e=has("enable-feature:esri-compress-IM-textures")?{compressionTracker:this._compressionTracker}:void 0,t=We(a,h,r.format),l=new Ue(c,{mipmap:o,maxAnisotropy:s,encoding:h,wrap:n,pixelFormat:a,internalFormat:t??void 0,immutable:null!=t,compressionOptions:e,noUnpackFlip:!0,width:r.mip0Width,height:r.mip0Height});return this._stage.addTexture(l),i.set(r,l),l}return null}getBufferViews(e,t){let i,r,s,o,n;for(let l=0;l<e.atrbs.length;l++){const n=e.atrbs[l],{view:c}=n,h=void 0,d=c.byteOffset+c.byteCount;try{switch(n.sem){case"Position":3!==c.ncomp||"F32"!==c.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Position ("+c+")"):i=new J(t,c.byteOffset,h,d);break;case"Normal":if(3!==c.ncomp||"F32"!==c.type)this._dbg(3,"[Unsupported Feature] Unsupported view for Normal ("+c+")");else{const e=new J(t,c.byteOffset,h,d);o=new Uint32Array(e.count),He(e.typedBuffer,new Int16Array(o.buffer,o.byteOffset,2*o.length))}break;case"TexCoord":2!==c.ncomp||"F32"!==c.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Texcoord ("+c+")"):void 0===s&&(s=new ee(t,c.byteOffset,h,d).typedBuffer);break;case"Color":4===c.ncomp?("F32"===c.type&&(r=new $(t,c.byteOffset,h,d)),"U8"===c.type&&(r=new Z(t,c.byteOffset,h,d)),"U16"===c.type&&(r=new Y(t,c.byteOffset,h,d))):3===c.ncomp&&("F32"===c.type&&(r=new J(t,c.byteOffset,h,d)),"U8"===c.type&&(r=new K(t,c.byteOffset,h,d)),"U16"===c.type&&(r=new Q(t,c.byteOffset,h,d))),null==r&&this._dbg(2,"[Unsupported Feature] Unsupported view for Color ("+c+")");break;case"FeatureIndex":break;default:this._dbg(2,"[Unsupported Feature] Unsupported semantic ("+n.sem+"). Skipping vertex attribute.")}}catch(a){this._dbg(2,"Error Creating buffer ("+a+"). Skipping vertex attribute.")}}if(e.index){const i=e.index.view,r=void 0,s=i.byteOffset+i.byteCount;switch(e.index.view.type){case"U16":n=new ie(t,i.byteOffset,r,s);break;case"U32":n=new te(t,i.byteOffset,r,s);break;default:this._dbg(3,"[Unsupported Feature] index type not supported ("+i.type+").")}}if(null==n&&null!=i){const e=i.count;n=n=e<65535?new ie(new Uint16Array(e).buffer):new te(new Uint32Array(e).buffer);for(let t=0;t<e;t++)n.set(t,t)}return{positionView:i,colorView:r,texCoord0Data:s,indicesView:n,normalsData:o}}_loadModifications(){if(this.removeHandles("modifications"),null==this.layer.modifications)return void(this._modifications=[]);const e=this.layer.modifications;this.addHandles(this._updatingHandles.addOnCollectionChange(()=>e,()=>{this._modifications=e.filter(e=>!(this.layer.isUsedAsGroundLayer&&"replace"!==e.type)).toArray(),this._modifications.length<e.length&&t.getLogger(this).info("Ground layers only support replace modifications. Other modification types have been ignored.")},n),"modifications")}_deletePerObjectData(e){this._wasm?.onRenderableEvicted(this,e.handle,e.usedMemory),this.freeRenderable(e.handle)}_dbg(e,i){this._dbgFlags.has(e)&&(3===e?t.getLogger(this).error(i):t.getLogger(this).warn(i))}};e([u()],qe.prototype,"fullOpacity",null),e([u({readOnly:!0})],qe.prototype,"ready",null),e([u({type:[re]})],qe.prototype,"_modifications",void 0),e([u()],qe.prototype,"_visibleGeometryChangedSchedulerHandle",void 0),e([u()],qe.prototype,"layer",void 0),e([u({readOnly:!0})],qe.prototype,"visibleAtCurrentScale",null),e([u({readOnly:!0})],qe.prototype,"_collection",null),e([u()],qe.prototype,"elevationOffset",null),e([u({readOnly:!0})],qe.prototype,"visibleElevationRange",null),e([u()],qe.prototype,"fullExtentInLocalViewSpatialReference",void 0),qe=e([m("esri.views.3d.layers.IntegratedMesh3DTilesLayerView3D")],qe);const Xe=qe;class $e{constructor(e,t,i,r,s,o,n,a,l,c){this.handle=e,this.componentObjects=t,this.textures=i,this.cpuMemoryUsage=r,this.vboMemoryUsage=s,this.textureMemoryUsage=o,this.obb=n,this.stableNodeId=a,this.nodeDepth=l,this.elevationRange=c,this.bvhIntersectionGeneration=0,this.isLoaded=!1,this.isVisible=!1;const h=T();n?.getCenter(h),this._obbCenterX=h[0],this._obbCenterY=h[1],this._obbCenterZ=h[2];const d=n?.radius??-1;this._obbRadius=d,this._obbRadiusSquared=d*d,this._obbShortestHalfsize=n?Math.min(n.halfSizeX,n.halfSizeY,n.halfSizeZ):0,this._mbsCenter=n?n.getCenter(T()):R}get usedMemory(){return this.textureMemoryUsage+this.vboMemoryUsage+this.cpuMemoryUsage}get mbsRadius(){return this._obbRadius}get mbsCenter(){return this._mbsCenter}boundingVolumeIntersectsRay(e,t){if(!this.obb)return!0;const{_obbCenterX:i,_obbCenterY:r,_obbCenterZ:s}=this,o=i-e[0],n=r-e[1],a=s-e[2],l=o*t[0]+n*t[1]+a*t[2];return o*o+n*n+a*a-l*l<=this._obbRadiusSquared&&this.obb.intersectRay(e,t)}boundingVolumeIntersectsSphere(e){const t=this._obbRadius;if(t<0)return!0;const i=e.center,r=e.radius,s=t+r,o=this._obbCenterX-i[0];if(o>s)return!1;const n=this._obbCenterY-i[1];if(n>s)return!1;const a=this._obbCenterZ-i[2];if(a>s)return!1;const l=o*o+n*n+a*a;if(l>s*s)return!1;if(l<=(this._obbShortestHalfsize+r)**2)return!0;const c=r-t;return c>0&&l<=c*c||(this.obb?.intersectSphere(e)??!0)}}function Ze(e){return Math.round(e/1048.576)/1e3}function Ye(e){return new Ee(e.center,e.halfSize,_(...e.quaternion))}const Je=new Array;class Ke{constructor(e,t,i,r,s,o){this.materialPromise=e,this.baseColorTexture=t,this.metallicRoughnessTexture=i,this.emissionTexture=r,this.occlusionTexture=s,this.normalTexture=o}cleanup(){this.baseColorTexture?.dispose(),this.metallicRoughnessTexture?.dispose(),this.emissionTexture?.dispose(),this.occlusionTexture?.dispose(),this.normalTexture?.dispose()}}export{Xe as default};
2
+ import{__decorate as e}from"tslib";import has from"../../../core/has.js";import t from"../../../core/Logger.js";import{abortMaybe as i,destroyMaybe as r,removeMaybe as s}from"../../../core/maybe.js";import{throwIfAborted as o}from"../../../core/promiseUtils.js";import{initial as n,watch as a,when as l}from"../../../core/reactiveUtils.js";import{schedule as c}from"../../../core/scheduling.js";import{unitFromRESTJSON as h,convertUnit as d}from"../../../core/units.js";import{property as u,subclass as m}from"../../../core/accessorSupport/decorators.js";import{fromMat4 as p,invert as f}from"../../../core/libs/gl-matrix-2/math/mat3.js";import{create as b,IDENTITY as g}from"../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{create as y}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{fromValues as _}from"../../../core/libs/gl-matrix-2/factories/quatf64.js";import{normalize as v,sub as w,dot as C,set as x}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as T,freeze as j,clone as E,ZEROS as R,fromValues as M}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{fromValues as O,clone as S,ONES as V}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{isMoon as U,isMars as H,getReferenceEllipsoid as D,SphericalECEFSpatialReferenceLike as I}from"../../../geometry/ellipsoidUtils.js";import P from"../../../geometry/HeightModelInfo.js";import{computeTranslationToOriginAndRotation as k}from"../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{localLinearScaleFactors as L}from"../../../geometry/projection/localLinearScaleFactors.js";import{projectVectorToVector as A}from"../../../geometry/projection/projectVectorToVector.js";import{create as F}from"../../../geometry/support/aaBoundingRect.js";import{isCompatible as G}from"../../../geometry/support/heightModelInfoUtils.js";import{isPlateCarree as z,isWebMercator as B,equals as N,isGeographic as W,isCGCS2000 as q}from"../../../geometry/support/spatialReferenceUtils.js";import X from"../../../geometry/support/WKIDUnitConversion.js";import{BufferViewVec4f as $,BufferViewVec4u8 as Z,BufferViewVec4u16 as Y,BufferViewVec3f as J,BufferViewVec3u8 as K,BufferViewVec3u16 as Q,BufferViewVec2f as ee,BufferViewUint32 as te,BufferViewUint16 as ie}from"../../../geometry/support/buffer/BufferView.js";import re from"../../../layers/support/SceneModification.js";import{getHeightModelInfoFromVCS as se,validateMeshData as oe,makeCacheKey as ne}from"../../../layers/support/tiles3DUtils.js";import{getElevationOffsetInMeters as ae}from"../../../support/elevationInfoUtils.js";import{IntegratedMesh3DTilesLayerWorkerHandle as le}from"./IntegratedMesh3DTilesLayerWorkerHandle.js";import{LayerView3D as ce}from"./LayerView3D.js";import{Lyr3DViewPerformanceInfo as he}from"./Lyr3DViewPerformanceInfo.js";import{addLayerViewToWasm as de,removeLayerViewFromWasm as ue,getLyr3DWasm as me}from"./Lyr3DWasm.js";import{toWasmModification as pe}from"./SceneLayerWorkerHandle.js";import{LayerElevationProvider as fe}from"./i3s/LayerElevationProvider.js";import{IntegratedMesh3DTilesLayerView3DSymbol as be}from"./support/integratedMesh3DTilesLayerViewInstanceUtils.js";import{primTypeConversion as ge,alphaModeConversion as ye,faceCullingConversion as _e,wrapModeConversion as ve}from"./support/lyr3dTypeConversions.js";import{makeScheduleFunction as we}from"./support/makeScheduleFunction.js";import{Tiles3DMeshIntersectionHandler as Ce}from"./support/Tiles3DMeshIntersectionHandler.js";import{Frustum as xe}from"../state/Frustum.js";import{ElevationRange as Te}from"../support/ElevationRange.js";import{toBoundingRect as je}from"../support/extentUtils.js";import{Obb as Ee}from"../support/orientedBoundingBox.js";import{glLayout as Re}from"../support/buffer/glUtil.js";import{ComponentGeometryParameters as Me,SourceGeometry as Oe}from"../webgl-engine/collections/Component/SourceGeometry.js";import{Transform as Se}from"../webgl-engine/collections/Component/Transform.js";import{RenderTexture as Ve}from"../webgl-engine/core/material/RenderTexture.js";import{ManagedTexture as Ue}from"../webgl-engine/lib/ManagedTexture.js";import{compressNormals as He}from"../webgl-engine/lib/Normals.js";import{advancedMRRFactors as De}from"../webgl-engine/materials/pbrUtils.js";import Ie from"../../layers/LayerView.js";import{spatialReferenceIncompatibleError as Pe,isInEffectiveScaleRange as ke,validateScaleRange as Le}from"../../support/layerViewUtils.js";import{TaskPriority as Ae}from"../../support/Scheduler.js";import{TextureCompressionTracker as Fe}from"../../support/TextureCompressionTracker.js";import{CompressedTextureFormat as Ge,SizedPixelFormat as ze}from"../../webgl/enums.js";import{alphaCutoff as Be}from"../../../webscene/support/AlphaCutoff.js";var Ne;function We(e,t,i){if("image/vnd-ms.dds"===t)switch(i){case"Dxt1":return Ge.COMPRESSED_RGB_S3TC_DXT1_EXT;case"Dxt5":return Ge.COMPRESSED_RGBA_S3TC_DXT5_EXT;default:return null}if("image/ktx2"===t)return null;switch(e){case 33319:return ze.RG8;case 6407:return ze.RGB8;case 6408:return ze.RGBA8;case 6403:return ze.R8;default:return null}}let qe=class extends(ce(Ie)){static{Ne=be}constructor(e){super(e),this[Ne]=!0,this.type="integrated-mesh-3dtiles",this._modifications=new Array,this._visibleGeometryChangedSchedulerHandle=null,this._initializationController=null,this._wasmLayerId=-1,this._metersPerVCSUnit=1,this.ignoresMemoryFactor=!1,this._usedMemory=0,this._cacheMemory=0,this._useEsriCrs=!1,this.drapeTargetType=1,this.fullExtentInLocalViewSpatialReference=null,this._replacesTerrain=!1,this._isUsedAsGroundLayer=!1,this._applySSAO=!has("disable-feature:im-ssao"),this._imShading=!!has("enable-feature:im-shading"),this._imVertexNormals=!!has("enable-feature:im-vertex-normals"),this._lyrHandleToObjects=new Map,this._visibleObjects=new Set,this._loadedObjects=new Set,this._compressionTracker=new Fe,this._dbgFlags=new Set;const t=e.view.resourceController;this._memCache=t.memoryController.newCache(`IM3DTiles-${this.uid}`,e=>this._deletePerObjectData(e)),this._replacesTerrain=e.layer.replacesTerrain,this._isUsedAsGroundLayer=e.layer.isUsedAsGroundLayer,this._frameTask=t.scheduler.registerTask(Ae.TILES3D,this),this._frustum=new xe(e.view.renderCoordsHelper)}tryRecycleWith(e,t){return this.canRecycleWith(e)?e.load(t).then(()=>{o(t);const i=this.layer.queryElevationCallback;this.layer=e,this.layer.queryElevationCallback=i}):null}canRecycleWith(e){return e.url===this.layer.url&&"integrated-mesh-3dtiles"===e.type&&e.replacesTerrain===this._replacesTerrain&&e.isUsedAsGroundLayer===this._isUsedAsGroundLayer}initialize(){this._dbg(2,"Tiles3DLayerView3D initialize() called");const{view:e}=this;if(this._workerHandle=new le(we(e.resourceController)),this._updatingHandles.add(()=>this.layer.modifications,()=>this._loadModifications(),n),!this._canProjectWithoutEngine())throw Pe("layer",this.layer.spatialReference.wkid,e.renderSpatialReference?.wkid);this._initializationController=new AbortController;const t=de(this,this._initializationController.signal).then(t=>{o(this._initializationController.signal),this._wasmLayerId=t,this._intersectionHandler=new Ce(this),e.sceneIntersectionHelper.addIntersectionHandler(this._intersectionHandler),this._updatingHandles.add(()=>this.slicePlaneEnabled,e=>this._slicePlaneEnabledChange(e)),this._updatingHandles.add(()=>this._modifications,()=>this._modificationsChanged()),this._updatingHandles.add(()=>this.fullOpacity,()=>this._opacityChange()),this._updatingHandles.add(()=>e.clippingArea,()=>this._clippingAreaChanged(),n),this._updatingHandles.add(()=>e.state.contentCamera,()=>this._cameraChanged(),n),this._elevationProvider=new fe({view:e,layerElevationSource:this,intersectionHandler:this._intersectionHandler});const i=this._replacesTerrain?0:1;e.elevationProvider.register(i,this._elevationProvider),e.overlayManager.registerDrapeTarget(this),this.addHandles([a(()=>this.layer.elevationInfo,e=>this._elevationInfoChanged(e)),l(()=>this.fullOpacity,()=>this._opacityChange()),a(()=>this.suspended,e=>this._wasm?.setEnabled(this,!e),n)]),this._initializationController=null});this.layer.queryElevationCallback=(e,t)=>this._wasm.queryElevation(this,e,t),this.addResolvingPromise(t)}destroy(){if(this._initializationController=i(this._initializationController),this._dbg(2,"Tiles3DLayerView3D destroy() called"),this._workerHandle?.destroyContextAndSelf(this.uid),ue(this),this.layer.queryElevationCallback=null,this._intersectionHandler&&(this.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler),this._intersectionHandler.destroy(),this._intersectionHandler=null),this._elevationProvider){const e=Array.from(this._lyrHandleToObjects.values()),t=e.reduce((e,{componentObjects:t})=>e+t.length,0);this._elevationProvider.notifyObjectsChangedFunctional(t,t=>{for(const{componentObjects:i}of e)for(const{obb:e}of i)if(!t(e))return}),this.view.elevationProvider.unregister(this._elevationProvider),this._elevationProvider=null}this.view.overlayManager.unregisterDrapeTarget(this),this._lyrHandleToObjects.forEach(e=>this.freeObject(e)),this._lyrHandleToObjects.clear(),this._visibleObjects.clear(),this._loadedObjects.clear(),this._usedMemory=0,this._cacheMemory=0,this._memCache.destroy(),this._frameTask.remove(),this._updatingHandles=r(this._updatingHandles),this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=s(this._visibleGeometryChangedSchedulerHandle)}get fullOpacity(){return this.layer.replacesTerrain?this.view.map.ground.opacity:1}get hasModifications(){return this._modifications&&this._modifications.length>0}_opacityChange(){const{fullOpacity:e}=this;this.forEachComponentObject(t=>this._collection.updateObjectOpacity(t,e))}_cameraChanged(){const e=this._frustum;e.update(this.view.state.contentCamera);const t=this._visibleObjects;let i=!1;this._loadedObjects.forEach(r=>{const s=r.obb?.intersectsFrustum(e)??!1;s!==r.isVisible&&(r.isVisible=s,s?t.add(r):t.delete(r),r.componentObjects.forEach(e=>this._collection.setObjectVisibility(e,s)),i||=this._isVisibileElevationRangeModifiedByChangedTileVisbility(s,r.elevationRange))}),i&&this._setVisibleElevationRangeDirty()}intersect(e,t,i,r){this._intersectionHandler.intersectRay(e,t,i,r,null,!1)}get ready(){return!this.layer.replacesTerrain||!!this._wasm?.isTerrainReady}_modificationsChanged(){const e=this.useEsriCrs?this.layer.supportedSpatialReferences[1]:this.layer.supportedSpatialReferences[0],t=pe(this._layerClippingArea,this._modifications,e,this.view.state.isGlobal);this._wasm?.setMeshModifications(this,t)}_clippingAreaChanged(){const e=this.layer.spatialReference,t=F();this._layerClippingArea=je(this.view.clippingArea,t,e)?t:null,this._modificationsChanged()}_visibleGeometryChanged(){this._visibleGeometryChangedSchedulerHandle??=c(()=>{this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=null})}_slicePlaneEnabledChange(e){this._intersectionHandler&&(this._intersectionHandler.slicePlaneEnabled=e&&!this.layer.replacesTerrain),this.forEachComponentObject(t=>t.updateMaterial({slicePlaneEnabled:e}))}_elevationInfoChanged(e){this._wasm?.setLayerOffset(this,ae(e))}get _wasm(){return me(this.view)}get wasmLayerId(){return this._wasmLayerId}get metersPerVCSUnit(){return this._metersPerVCSUnit}get usedMemory(){return this._usedMemory}get unloadedMemory(){return 0}get cachedMemory(){return this._cacheMemory}get useEsriCrs(){return this._useEsriCrs}get visibleAtCurrentScale(){return this.layer.isUsedAsGroundLayer||ke(this.layer.effectiveScaleRange,this.view.scale)}canResume(){const e=this.layer&&"effectiveScaleRange"in this.layer?this.layer.effectiveScaleRange:null;return this.visible&&this.layer?.loaded&&this.parent&&!this.parent.suspended&&this.view?.ready&&(this.layer.isUsedAsGroundLayer||Le(e)&&this.visibleAtCurrentScale)&&this.visibleAtCurrentTimeExtent||!1}get performanceInfo(){let e=0,t=0,i=0,r=0,s=0,o=0;return this._lyrHandleToObjects.forEach(n=>{n.isLoaded?(e+=n.textureMemoryUsage,t+=n.vboMemoryUsage,s++):(i+=n.textureMemoryUsage,r+=n.vboMemoryUsage,o++)}),new he(this.usedMemory,s,o,Ze(t),Ze(e),Ze(r),Ze(i))}_canProjectWithoutEngine(){if(1===this.view.state.viewingMode)return!0;if(z(this.view.renderSpatialReference)||B(this.view.renderSpatialReference))return!0;if(this.layer.esriCrsSpatialReference&&N(this.layer.esriCrsSpatialReference,this.view.renderSpatialReference)){if(115700===this.layer.esriCrsSpatialReference.vcsWkid)return!1;let e=se(this.layer.esriCrsSpatialReference);if(!e){const t=this.layer.esriCrsSpatialReference;let i="meters";!W(t)&&t.wkid&&-1!==t.wkid&&(i=h(X.units[X[t.wkid]])),i&&(e=new P({heightModel:"gravity-related-height",heightUnit:i}))}const t=this.view.heightModelInfo;return this._useEsriCrs=0===G(e,t,!1),this._useEsriCrs&&(e&&(this._metersPerVCSUnit=d(1,e.heightUnit,"meters")),this.fullExtentInLocalViewSpatialReference=this.layer.esriCrsFullExtent),this._useEsriCrs}return!1}get _stage(){return this.view.stage}get _collection(){return this._stage.renderView.componentObjectCollection}get elevationProvider(){return this._elevationProvider}get elevationOffset(){return ae(this.layer.elevationInfo)}get elevationRange(){const e=this.fullExtent;return e?.zmin&&e?.zmax?new Te(e.zmin,e.zmax):null}getElevationRange(e){return this._intersectionHandler.getElevationRange(e)}get visibleElevationRange(){const e=new Te;0===this._visibleObjects.size?e.setElevationRangeValues(0,0):(e.setElevationRangeValues(1/0,-1/0),this._forEachRelevantVisibleTile(t=>e.expandElevationRange(t.elevationRange)),e.minElevation===1/0&&e.setElevationRangeValues(0,0));const t=this._get("visibleElevationRange");return t&&t.minElevation===e.minElevation&&t.maxElevation===e.maxElevation?t:e}_setVisibleElevationRangeDirty(){this.notifyChange("visibleElevationRange")}_forEachRelevantVisibleTile(e){const{view:t}=this,{spatialReference:i}=t,r=i.isWGS84||i.isWebMercator||q(i)||U(i)||H(i);if(this.view.state.isGlobal||!r)return this.forEachVisibleTile(e);const s=D(i).radius,{eye:o,viewForward:n,near:a}=t.state.camera,l=v(T(),n),c=500,h=Math.max(o[2],c),d=h+s,u=Math.sqrt(d**2-s**2),m=Math.abs(Math.atan2(u,s))*s,p=h>.5*s?.5*Math.PI*s:m,f=T();this.forEachVisibleTile(t=>{const{mbsRadius:i,mbsCenter:r}=t;if(i<0)return;w(f,r,o);const s=C(f,l);Math.abs(s)<p&&s+i>a&&s-i<p&&e(t)})}get fullExtent(){return this.layer.fullExtent}forEachComponentObject(e){this._forEachObject(this._lyrHandleToObjects.values(),e)}forEachVisibleTile(e){for(const t of this._visibleObjects)e(t)}forEachTile(e){for(const t of this._loadedObjects)e(t)}forEachVisibleComponentObject(e){this._forEachObject(this._visibleObjects,e)}_forEachObject(e,t){for(const{componentObjects:i}of e)for(const e of i)t(e)}isUpdating(){const e=this._wasm;return this._wasmLayerId>=0&&null!=e&&(e.isUpdating(this._wasmLayerId)||this._compressionTracker.compressing)}get readyToRun(){return!!this._frameTask?.readyToRun}runTask(e){this._frameTask.processQueue(e)}updatingFlagChanged(){this.notifyChange("updating")}async createRenderable(e){if(this.destroyed||this.destroying)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderable called after destroy");const{meshData:t}=e;if(!oe(t))throw new Error("meshData not valid");const i=new Map;let r;try{r=this._createPrimitiveTextureBundles(t,i)}catch(o){throw i.forEach(e=>this._stage?.removeTexture(e)),o}let s=null;try{if(s=await this._createRenderableMain(t,r),this.destroyed)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderable aborted due to destroyed instance");const{tileObb:o,componentObjects:n,elevationRange:a}=s;let l=0,c=0,h=0;for(const e of n){const{texture:t,textureMetallicRoughness:i,textureEmissive:r,textureOcclusion:s,textureNormal:o}=e.renderable.drawParameters;l+=(t?.usedMemory??0)+(i?.usedMemory??0)+(r?.usedMemory??0)+(s?.usedMemory??0)+(o?.usedMemory??0),c+=this._collection.getObjectGPUMemoryUsage(e),h+=e.intersectionGeometry.usedMemory}const d=Array.from(i.values()),u=new $e(e.handle,n,d,h,c,l,o,e.stableNodeId,e.nodeDepth,a);return this._lyrHandleToObjects.set(e.handle,u),()=>{this._memCache.put(ne(u.handle),u);const{usedMemory:e}=u;return this._cacheMemory+=e,{memUsageBytes:e}}}catch(o){throw r.forEach(e=>e.cleanup()),s?.componentObjects.forEach(e=>this._collection.destroyObject(e)),i.forEach(e=>this._stage?.removeTexture(e)),o}}_createPrimitiveTextureBundles(e,t){const i=new Array,r=e.desc.prims.length;try{const s=e.desc;for(let o=0;o<r;o++){const r=s.prims[o].materialId,n=s.materials&&null!=r?s.materials[r]:null;let a=Promise.resolve(Je),l=null,c=null,h=null,d=null,u=null;if(n){const i="Pbr"===n.lightingModel;l=this._getTexture(n.baseColorTex,e,t),c=i?this._getTexture(n.metalTex,e,t):null,h=i?this._getTexture(n.emissiveTex,e,t):null,d=i?this._getTexture(n.occlusionTex,e,t):null,u=i?this._getTexture(n.normalTex,e,t):null;const r=[l,c,h,d,u].map(e=>e?.loadPromise??null);a=Promise.all(r)}i.push(new Ke(a,l,c,h,d,u))}}catch(s){throw i.forEach(e=>e.cleanup()),s}return i}async _createRenderableMain(e,t){if(this.destroyed||this.destroying)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderableMain called after destroy");const i=new Array,r=e.desc,s=e.data.buffer,o=r.prims.length,n=j(...r.origin),a=this.view.basemapTerrain.spatialReference,l=this.view.state.isGlobal;let c=g;if(l){const e=y();k(I,n,e,a),c=p(b(),e)}if(null==r.obb)throw new Error("meshData.desc.obb undefined");const h=Ye(r.obb),d=l?D(this.view.spatialReference).radius:0,u=new Array;try{for(let i=0;i<o;i++){const e=r.prims[i],o=t[i];this._dbgFlags.has(2)&&this._dbg(2,JSON.stringify(e));if(null==ge[e.ptype]){this._dbg(2,"[Unsupported Feature] Unsupported primitive mode ("+e.ptype+"). Skipping primitive."),o.cleanup();continue}const{positionView:n,normalsData:a,colorView:l,texCoord0Data:c,indicesView:h}=this.getBufferViews(e,s);if(null==n||null==h){o.cleanup();continue}const d=n.count,m=(e,t)=>null==e||e===d||(this._dbg(3,`${t} !== numPos. Skipping primitive.`),!1);m(null!=c?c.length/2:void 0,"numTexcoord")&&m(l?.count,"numColors")&&m(a?.length,"normals")?u.push({componentIndex:i,positionView:n,indicesView:h,texCoord0Data:c,colorView:l,normalsData:a}):o.cleanup()}const e=c!==g,m=e?f(b(),c)??g:g,{vertexProcessingOutputs:p,obbHalfSizeAccumulator:y,elevationRange:_}=await this._workerHandle.processTiles3DVertices(u,n,d,l,c,h,this._imVertexNormals&&!this._isUsedAsGroundLayer);if(this.destroyed)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderableMain aborted due to destroyed instance");const v=r.materials;if(await Promise.all(t.map(e=>e.materialPromise)),this.destroyed)throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderableMain aborted due to destroyed instance");p.length>0&&h.setHalfSize(y);for(const s of p){const{componentIndex:o,positionView:l,indicesView:c,layout:d,textureCoordinateType:u,interleavedVertexData:p,indices:f}=s,b=r.prims[o],g=t[o],y=h.clone(),_=Re(d),w=new Uint32Array([0,c.typedBuffer.length]),C=new Me(_,this._imShading?2:0,u,e?2:0),x=new Oe({interleavedVertexData:p,vertexCount:p.byteLength/_[0].stride,indexData:f},{positions:l.typedBuffer,indices:c.typedBuffer},w,C),j=this.view.renderSpatialReference,E=T(),R=[1,1,1];L(n,j,R,a)||this._dbg(3,"Unsupported coordinate system for IM overlay"),A(n,j,E,a);const M=v&&null!=b.materialId?v[b.materialId]:null,S=this._createComponentMaterialInitParameters(M,g);S.baseColorTexture||this._dbg(3,"No colour texture 1");const V=this._collection.createObject({toMapSpace:O(E[0],E[1],R[0],R[1]),transform:new Se(n,m),obb:y,geometry:x,elevationAlignable:!1},S);i.push(V)}const{fullExtent:w}=this.layer;return w?.hasZ&&w.zmax&&w.zmin&&(_.minElevation=Math.max(_.minElevation,w.zmin),_.maxElevation=Math.min(_.maxElevation,w.zmax)),{tileObb:h,componentObjects:i,elevationRange:_}}catch(m){throw i.forEach(e=>this._collection.destroyObject(e)),m}}_createComponentMaterialInitParameters(e,t){const i="Pbr"===(null!=e?e.lightingModel:"Unlit");let r=V,s=Be,o=1,n=!1,a=2,l=M(0,0,0);const c=E(De),h=t.baseColorTexture,d=t.metallicRoughnessTexture,u=t.emissionTexture,m=t.occlusionTexture,p=t.normalTexture;return e&&(r=S(e.baseColorFactor),s=e.alphaCutoff??Be,i&&(x(c,e.metallicFactor,e.roughnessFactor,0),e.emissiveFactor&&(l=e.emissiveFactor)),o=ye[e.alphaMode],n=e.isDoubleSided,a=_e[e.faceCulling??"NotSet"]),{isIntegratedMesh:!0,baseColor:r,textureAlphaCutoff:s,mrrFactors:c,baseColorTexture:h,metallicRoughnessTexture:d,normalTexture:p,occlusionTexture:m,emissionTexture:u,hasParametersFromSource:!1,sphereDepthInterpolate:this.layer.hasGoogleUrl,alphaDiscardMode:o,doubleSided:n,cullFace:a,isGround:this.layer.replacesTerrain,emissiveBaseColor:l,usePBR:i,slicePlaneEnabled:this.slicePlaneEnabled,opacity:this.fullOpacity,polygonOffset:0,ellipsoidMode:1,applySSAO:this._applySSAO}}freeRenderable(e){const t=this._lyrHandleToObjects.get(e);t?(t.isLoaded?(this._loadedObjects.delete(t),this._visibleObjects.delete(t),this._intersectionHandler.removeTile(t),this._usedMemory-=t.usedMemory):this._cacheMemory-=t.usedMemory,this.freeObject(t),this._lyrHandleToObjects.delete(e)):this._dbg(3,`freeRendedrable on non-existent renderable ${e}`)}freeObject(e){const t=ne(e.handle);this._memCache.pop(t),e.textures.forEach(e=>this._stage.removeTexture(e)),e.componentObjects.forEach(e=>this._collection.destroyObject(e))}setRenderableVisibility(e,t,i){if(this.destroyed||this.destroying)return;const r=this._frustum,s=new Array;let o=!1,n=!1;for(let a=0;a<i;++a){if(!t[a])continue;const i=e[a],l=this._lyrHandleToObjects.get(i);if(l){if(l.isLoaded){this._dbg(3,`Already loaded object marked loaded again ${l.stableNodeId}`);continue}o=!0,l.isLoaded=!0,this._loadedObjects.add(l),this._intersectionHandler.addTile(l),this._usedMemory+=l.usedMemory,this._cacheMemory-=l.usedMemory;const e=l.obb?.intersectsFrustum(r)??!0;l.isVisible=e,e&&(this._visibleObjects.add(l),n||=this._isVisibileElevationRangeModifiedByChangedTileVisbility(e,l.elevationRange)),s.push(l.obb),l.componentObjects.forEach(t=>{this._collection.setObjectVisibility(t,e)}),this._memCache.pop(ne(i))}else this._dbg(3,`Tried to mark Non existent object ${i} as loaded`)}for(let a=0;a<i;++a){const i=e[a];if(t[a])continue;const r=this._lyrHandleToObjects.get(i);if(r){if(!r.isLoaded){this._dbg(3,`Tried to unload not-loaded object ${r.stableNodeId}`);continue}const e=r.isVisible;this._visibleObjects.delete(r),r.isVisible=!1,r.isLoaded=!1,this._loadedObjects.delete(r),this._intersectionHandler.removeTile(r),e&&(this._visibleGeometryChanged(),n||=this._isVisibileElevationRangeModifiedByChangedTileVisbility(!1,r.elevationRange)),this._usedMemory-=r.usedMemory,this._cacheMemory+=r.usedMemory,s.push(r.obb),r.componentObjects.forEach(e=>{this._collection.setObjectVisibility(e,!1)}),this._memCache.put(ne(i),r)}else this._dbg(3,`Tried to mark Non existent object ${i} as not loaded`)}o&&this._visibleGeometryChanged(),s.length>0&&this._elevationProvider.notifyObjectsChanged(s),n&&this._setVisibleElevationRangeDirty()}setLodPixelThreshold(e){this._wasm?.setLodPixelThreshold(this,e)}_isVisibileElevationRangeModifiedByChangedTileVisbility(e,t){const{visibleElevationRange:i}=this,{minElevation:r,maxElevation:s}=t;return e?r<i.minElevation||s>i.maxElevation:r===i.minElevation||s===i.maxElevation}_getTexture(e,t,i){const r=e&&t.desc?.images?.[e.imageId];if(!r||!t.data?.buffer)return null;const s=i.get(r)??this._createTexture(e,t,i);return s?new Ve(this._stage.renderView.textures,s.id):null}_createTexture(e,t,i){const r=e&&t.desc?.images?.[e.imageId];if(!r||!t.data?.buffer)return null;const s=this._stage.renderView.renderingContext.parameters.maxMaxAnisotropy,o=!!r.mipCount||s>1,n=ve[e.wrapMode??"None"];let a=r.alpha?6408:6407;const l=new Uint8Array(t.data.buffer,r.data.byteOffset,r.data.byteCount);let c=null,h=null,d=null;switch(r.format){case"Raw":"R8"===r.pixelFormat?(c=l,a=6403,h=""):"Rg8"===r.pixelFormat||"Ga8"===r.pixelFormat?(c=l,a=33319,h=""):"Rgb8"===r.pixelFormat?(c=l,a=6407,h=""):"Rgba8"===r.pixelFormat&&(c=l,a=6408,h="");break;case"Dxt1":c=l,a=6407,h="image/vnd-ms.dds";break;case"Dxt5":c=l,a=6408,h="image/vnd-ms.dds";break;case"Basis":c=l,a=6407,h="image/ktx2";break;case"Png":h="image/png",d=document.createElement("img");break;case"Jpeg":h="image/jpeg",d=document.createElement("img");break;case"Etc2":h="image/ktx",d=document.createElement("img");break;case"Astc":this._dbg(3,"Astc texture not supported");break;case"Pvrtc":this._dbg(3,"Pvrtc texture not supported")}if(d&&h){const e=new Blob([l],{type:h});d.src=URL.createObjectURL(e),c=d}if(c&&null!=h){const e=has("enable-feature:esri-compress-IM-textures")?{compressionTracker:this._compressionTracker}:void 0,t=We(a,h,r.format),l=new Ue(c,{mipmap:o,maxAnisotropy:s,encoding:h,wrap:n,pixelFormat:a,internalFormat:t??void 0,immutable:null!=t,compressionOptions:e,noUnpackFlip:!0,width:r.mip0Width,height:r.mip0Height});return this._stage.addTexture(l),i.set(r,l),l}return null}getBufferViews(e,t){let i,r,s,o,n;for(let l=0;l<e.atrbs.length;l++){const n=e.atrbs[l],{view:c}=n,h=void 0,d=c.byteOffset+c.byteCount;try{switch(n.sem){case"Position":3!==c.ncomp||"F32"!==c.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Position ("+c+")"):i=new J(t,c.byteOffset,h,d);break;case"Normal":if(3!==c.ncomp||"F32"!==c.type)this._dbg(3,"[Unsupported Feature] Unsupported view for Normal ("+c+")");else{const e=new J(t,c.byteOffset,h,d);o=new Uint32Array(e.count),He(e.typedBuffer,new Int16Array(o.buffer,o.byteOffset,2*o.length))}break;case"TexCoord":2!==c.ncomp||"F32"!==c.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Texcoord ("+c+")"):void 0===s&&(s=new ee(t,c.byteOffset,h,d).typedBuffer);break;case"Color":4===c.ncomp?("F32"===c.type&&(r=new $(t,c.byteOffset,h,d)),"U8"===c.type&&(r=new Z(t,c.byteOffset,h,d)),"U16"===c.type&&(r=new Y(t,c.byteOffset,h,d))):3===c.ncomp&&("F32"===c.type&&(r=new J(t,c.byteOffset,h,d)),"U8"===c.type&&(r=new K(t,c.byteOffset,h,d)),"U16"===c.type&&(r=new Q(t,c.byteOffset,h,d))),null==r&&this._dbg(2,"[Unsupported Feature] Unsupported view for Color ("+c+")");break;case"FeatureIndex":break;default:this._dbg(2,"[Unsupported Feature] Unsupported semantic ("+n.sem+"). Skipping vertex attribute.")}}catch(a){this._dbg(2,"Error Creating buffer ("+a+"). Skipping vertex attribute.")}}if(e.index){const i=e.index.view,r=void 0,s=i.byteOffset+i.byteCount;switch(e.index.view.type){case"U16":n=new ie(t,i.byteOffset,r,s);break;case"U32":n=new te(t,i.byteOffset,r,s);break;default:this._dbg(3,"[Unsupported Feature] index type not supported ("+i.type+").")}}if(null==n&&null!=i){const e=i.count;n=n=e<65535?new ie(new Uint16Array(e).buffer):new te(new Uint32Array(e).buffer);for(let t=0;t<e;t++)n.set(t,t)}return{positionView:i,colorView:r,texCoord0Data:s,indicesView:n,normalsData:o}}_loadModifications(){if(this.removeHandles("modifications"),null==this.layer.modifications)return void(this._modifications=[]);const e=this.layer.modifications;this.addHandles(this._updatingHandles.addOnCollectionChange(()=>e,()=>{this._modifications=e.filter(e=>!(this.layer.isUsedAsGroundLayer&&"replace"!==e.type)).toArray(),this._modifications.length<e.length&&t.getLogger(this).info("Ground layers only support replace modifications. Other modification types have been ignored.")},n),"modifications")}_deletePerObjectData(e){this._wasm?.onRenderableEvicted(this,e.handle,e.usedMemory),this.freeRenderable(e.handle)}_dbg(e,i){this._dbgFlags.has(e)&&(3===e?t.getLogger(this).error(i):t.getLogger(this).warn(i))}};e([u()],qe.prototype,"fullOpacity",null),e([u({readOnly:!0})],qe.prototype,"ready",null),e([u({type:[re]})],qe.prototype,"_modifications",void 0),e([u()],qe.prototype,"_visibleGeometryChangedSchedulerHandle",void 0),e([u()],qe.prototype,"layer",void 0),e([u({readOnly:!0})],qe.prototype,"visibleAtCurrentScale",null),e([u({readOnly:!0})],qe.prototype,"_collection",null),e([u()],qe.prototype,"elevationOffset",null),e([u({readOnly:!0})],qe.prototype,"visibleElevationRange",null),e([u()],qe.prototype,"fullExtentInLocalViewSpatialReference",void 0),qe=e([m("esri.views.3d.layers.IntegratedMesh3DTilesLayerView3D")],qe);const Xe=qe;class $e{constructor(e,t,i,r,s,o,n,a,l,c){this.handle=e,this.componentObjects=t,this.textures=i,this.cpuMemoryUsage=r,this.vboMemoryUsage=s,this.textureMemoryUsage=o,this.obb=n,this.stableNodeId=a,this.nodeDepth=l,this.elevationRange=c,this.bvhIntersectionGeneration=0,this.isLoaded=!1,this.isVisible=!1;const h=T();n?.getCenter(h),this._obbCenterX=h[0],this._obbCenterY=h[1],this._obbCenterZ=h[2];const d=n?.radius??-1;this._obbRadius=d,this._obbRadiusSquared=d*d,this._obbShortestHalfsize=n?Math.min(n.halfSizeX,n.halfSizeY,n.halfSizeZ):0,this._mbsCenter=n?n.getCenter(T()):R}get usedMemory(){return this.textureMemoryUsage+this.vboMemoryUsage+this.cpuMemoryUsage}get mbsRadius(){return this._obbRadius}get mbsCenter(){return this._mbsCenter}boundingVolumeIntersectsRay(e,t){if(!this.obb)return!0;const{_obbCenterX:i,_obbCenterY:r,_obbCenterZ:s}=this,o=i-e[0],n=r-e[1],a=s-e[2],l=o*t[0]+n*t[1]+a*t[2];return o*o+n*n+a*a-l*l<=this._obbRadiusSquared&&this.obb.intersectRay(e,t)}boundingVolumeIntersectsSphere(e){const t=this._obbRadius;if(t<0)return!0;const i=e.center,r=e.radius,s=t+r,o=this._obbCenterX-i[0];if(o>s)return!1;const n=this._obbCenterY-i[1];if(n>s)return!1;const a=this._obbCenterZ-i[2];if(a>s)return!1;const l=o*o+n*n+a*a;if(l>s*s)return!1;if(l<=(this._obbShortestHalfsize+r)**2)return!0;const c=r-t;return c>0&&l<=c*c||(this.obb?.intersectSphere(e)??!0)}}function Ze(e){return Math.round(e/1048.576)/1e3}function Ye(e){return new Ee(e.center,e.halfSize,_(...e.quaternion))}const Je=new Array;class Ke{constructor(e,t,i,r,s,o){this.materialPromise=e,this.baseColorTexture=t,this.metallicRoughnessTexture=i,this.emissionTexture=r,this.occlusionTexture=s,this.normalTexture=o}cleanup(){this.baseColorTexture?.dispose(),this.metallicRoughnessTexture?.dispose(),this.emissionTexture?.dispose(),this.occlusionTexture?.dispose(),this.normalTexture?.dispose()}}export{Xe as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import t from"../../../core/Logger.js";import s from"../../../core/PooledArray.js";import{create as e}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{WorkerHandle as o}from"../../../core/workers/WorkerHandle.js";import{canProjectWithoutEngine as i}from"../../../geometry/projectionUtils.js";import{projectVectorToVector as n}from"../../../geometry/projection/projectVectorToVector.js";class r{constructor(t,s,e,o,i,n){this.layout=t,this.interleavedVertexData=s,this.indices=e,this.hasColors=o,this.hasModifications=i,this.positionData=n}}class h{constructor(t,s,e,o,i,n,r,h,a){this.componentOffsets=t,this.featureIds=s,this.anchorIds=e,this.anchors=o,this.transformedGeometry=i,this.globalTrafo=n,this.obb=r,this.geometryMinElevation=h,this.geometryMaxElevation=a}}class a extends o{constructor(t){super("SceneLayerWorker","process",{process:t=>[t.geometryBuffer],project:t=>[t.positions.buffer],transformNormals:t=>[t.normals.buffer]},t,{hasInitialize:!0}),this._schemasByContext=new Map,this._modificationsByContext=new Map}_onClientConnected(t){for(const[s,e]of this._schemasByContext)t.invoke("setLegacySchema",{context:s,jsonSchema:e}).catch(()=>{});for(const s of this._modificationsByContext.values())t.invoke("setModifications",s).catch(()=>{})}setModifications(t,s,e){const o={context:t,modifications:s,isGeodetic:e};return this._modificationsByContext.set(t,o),this.broadcast(o,"setModifications")}setLegacySchema(t,s){const e=JSON.stringify(s);return this._schemasByContext.set(t,e),this.broadcast({context:t,jsonSchema:e},"setLegacySchema")}destroyContext(t){return this._schemasByContext.delete(t),this._modificationsByContext.delete(t),this.broadcast(t,"destroyContext")}async destroyContextAndSelf(t){await this.destroyContext(t),this.destroy()}project(t,s){return this.invokeMethod("project",t,s)}transformNormals(t,s){return this.invokeMethod("transformNormals",t,s)}}const c=new s({deallocator:null}),p=e();function u(s,e,o){c.clear();let r=1/0,h=1/0,a=-1/0,u=-1/0,l=!1;for(const m of e){const s="clip"===m.type?2:"mask"===m.type?1:0,e=m.geometry;let f=t=>t;if(e.spatialReference){if(!i(e.spatialReference,o)){t.getLogger("esri.views.3d.layers.SceneLayerWorkerHandle").warn("im-modification-projection-failed","Can't project modification polygon into layer spatial reference, ignoring modification",{polygon:e});continue}f=t=>(n(t,e.spatialReference,p,o),p)}l=l||1===s;const g=e.rings.length,d=e.rings.some(t=>t.length<3);if(0===g||d)t.getLogger("esri.views.3d.layers.SceneLayerWorkerHandle").warn("im-modification-invalid-polygon","Ignoring invalid modification polygon (no rings or rings with less than 3 vertices).",{polygon:e});else{c.push(s),c.push(g);for(const t of e.rings){c.push(t.length);for(const s of t){const t=f(s);c.push(t[0]),c.push(t[1]),c.push(t[2]??0),r=Math.min(r,t[0]),h=Math.min(h,t[1]),a=Math.max(a,t[0]),u=Math.max(u,t[1])}}}}if(null!=s)if(l){const t=1e-4;c.push(2),c.push(2),c.push(4),c.push(r-t),c.push(h-t),c.push(0),c.push(a+t),c.push(h-t),c.push(0),c.push(a+t),c.push(u+t),c.push(0),c.push(r-t),c.push(u+t),c.push(0),c.push(4),c.push(s[0]),c.push(s[1]),c.push(0),c.push(s[2]),c.push(s[1]),c.push(0),c.push(s[2]),c.push(s[3]),c.push(0),c.push(s[0]),c.push(s[3]),c.push(0)}else c.push(1),c.push(1),c.push(4),c.push(s[0]),c.push(s[1]),c.push(0),c.push(s[2]),c.push(s[1]),c.push(0),c.push(s[2]),c.push(s[3]),c.push(0),c.push(s[0]),c.push(s[3]),c.push(0);c.push(3);const f=new Float64Array(c.length);for(let t=0;t<c.length;++t)f[t]=c.at(t);return f}function l(t,s){let e=0;for(const o of s){const s=o.geometry,i=s.rings.length,n=s.rings.some(t=>t.length<3);if(0!==i&&!n){e+=1,e+=1;for(let o=0;o<s.rings.length;++o){const i=s.rings[o];e+=1;for(let n=0;n<i.length;++n){const i=[t[e+0],t[e+1],t[e+2]];e+=3,s.setPoint(o,n,i)}}}}}export{a as SceneLayerWorkerHandle,h as TransformedData,r as TransformedGeometry,l as fromWasmModification,u as toWasmModification};
2
+ import t from"../../../core/Logger.js";import o from"../../../core/PooledArray.js";import{create as e}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{WorkerHandle as s}from"../../../core/workers/WorkerHandle.js";import n from"../../../geometry/Polygon.js";import{canProjectWithoutEngine as i}from"../../../geometry/projectionUtils.js";import{projectVectorToVector as r}from"../../../geometry/projection/projectVectorToVector.js";import{normalizeCentralMeridianSync as a}from"../../../geometry/support/normalizeUtilsSync.js";class c{constructor(t,o,e,s,n,i){this.layout=t,this.interleavedVertexData=o,this.indices=e,this.hasColors=s,this.hasModifications=n,this.positionData=i}}class h{constructor(t,o,e,s,n,i,r,a,c){this.componentOffsets=t,this.featureIds=o,this.anchorIds=e,this.anchors=s,this.transformedGeometry=n,this.globalTrafo=i,this.obb=r,this.geometryMinElevation=a,this.geometryMaxElevation=c}}class p extends s{constructor(t){super("SceneLayerWorker","process",{process:t=>[t.geometryBuffer],project:t=>[t.positions.buffer],transformNormals:t=>[t.normals.buffer]},t,{hasInitialize:!0}),this._schemasByContext=new Map,this._modificationsByContext=new Map}_onClientConnected(t){for(const[o,e]of this._schemasByContext)t.invoke("setLegacySchema",{context:o,jsonSchema:e}).catch(()=>{});for(const o of this._modificationsByContext.values())t.invoke("setModifications",o).catch(()=>{})}setModifications(t,o,e){const s={context:t,modifications:o,isGeodetic:e};return this._modificationsByContext.set(t,s),this.broadcast(s,"setModifications")}setLegacySchema(t,o){const e=JSON.stringify(o);return this._schemasByContext.set(t,e),this.broadcast({context:t,jsonSchema:e},"setLegacySchema")}destroyContext(t){return this._schemasByContext.delete(t),this._modificationsByContext.delete(t),this.broadcast(t,"destroyContext")}async destroyContextAndSelf(t){await this.destroyContext(t),this.destroy()}project(t,o){return this.invokeMethod("project",t,o)}transformNormals(t,o){return this.invokeMethod("transformNormals",t,o)}}const l=new o({deallocator:null}),u=e();function f(o,e,s,r=!1){l.clear();let c=1/0,h=1/0,p=-1/0,u=-1/0,f=!1;for(const y of e){const o="clip"===y.type?2:"mask"===y.type?1:0,e=y.geometry,d=e.spatialReference??s;if(d!==s&&!i(d,s)){t.getLogger("esri.views.3d.layers.SceneLayerWorkerHandle").warn("im-modification-projection-failed","Can't project modification polygon into layer spatial reference, ignoring modification",{polygon:e});continue}let x=e.rings;if(d!==s){const o=m(e.rings,d,s);if(null==o){t.getLogger("esri.views.3d.layers.SceneLayerWorkerHandle").warn("im-modification-projection-failed","Can't project modification polygon into layer spatial reference, ignoring modification",{polygon:e});continue}x=o}const j=x;if(r){const t=a(new n({rings:x,spatialReference:s}));null!=t&&(x=t.rings)}const C=1===j.length&&x.length>1?[...x.map(t=>[t]),j]:[x];if(C.some(t=>0===t.length||t.some(t=>t.length<3||t.some(t=>!g(t)))))t.getLogger("esri.views.3d.layers.SceneLayerWorkerHandle").warn("im-modification-invalid-polygon","Ignoring invalid modification polygon (empty ring, fewer than 3 vertices, or non-finite coordinates).",{polygon:e});else{f||=1===o;for(const t of C){l.push(o),l.push(t.length);for(const o of t){l.push(o.length);for(const t of o){const o=t[2]??0;l.push(t[0]),l.push(t[1]),l.push(o),c=Math.min(c,t[0]),h=Math.min(h,t[1]),p=Math.max(p,t[0]),u=Math.max(u,t[1])}}}}}if(null!=o)if(f){const t=1e-4;l.push(2),l.push(2),l.push(4),l.push(c-t),l.push(h-t),l.push(0),l.push(p+t),l.push(h-t),l.push(0),l.push(p+t),l.push(u+t),l.push(0),l.push(c-t),l.push(u+t),l.push(0),l.push(4),l.push(o[0]),l.push(o[1]),l.push(0),l.push(o[2]),l.push(o[1]),l.push(0),l.push(o[2]),l.push(o[3]),l.push(0),l.push(o[0]),l.push(o[3]),l.push(0)}else l.push(1),l.push(1),l.push(4),l.push(o[0]),l.push(o[1]),l.push(0),l.push(o[2]),l.push(o[1]),l.push(0),l.push(o[2]),l.push(o[3]),l.push(0),l.push(o[0]),l.push(o[3]),l.push(0);l.push(3);const d=new Float64Array(l.length);for(let t=0;t<l.length;++t)d[t]=l.at(t);return d}function m(t,o,e){const s=[];for(const n of t){const t=[];for(const s of n){if(!r(s,o,u,e)||!g(u))return null;t.push([u[0],u[1],u[2]])}s.push(t)}return s}function g(t){return Number.isFinite(t[0])&&Number.isFinite(t[1])&&(null==t[2]||Number.isFinite(t[2]))}function d(t,o){let e=0;for(const s of o){const o=s.geometry,n=o.rings.length,i=o.rings.some(t=>t.length<3);if(0!==n&&!i){e+=1,e+=1;for(let s=0;s<o.rings.length;++s){const n=o.rings[s];e+=1;for(let i=0;i<n.length;++i){const n=[t[e+0],t[e+1],t[e+2]];e+=3,o.setPoint(s,i,n)}}}}}export{p as SceneLayerWorkerHandle,h as TransformedData,c as TransformedGeometry,d as fromWasmModification,f as toWasmModification};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as t}from"tslib";import e from"../../../../core/Accessor.js";import has from"../../../../core/has.js";import{destroyMaybe as i}from"../../../../core/maybe.js";import{property as s,subclass as n}from"../../../../core/accessorSupport/decorators.js";import{PooledRBush as r}from"../../../../core/libs/rbush/PooledRBush.js";import{fromRect as o}from"../../../../geometry/support/aaBoundingBox.js";import{getObjectId as a}from"../../../../layers/graphics/dehydratedFeatures.js";let d=class extends e{constructor(t){super(t),this._index=new r(9,has("esri-csp-restrictions")?t=>({minX:t.extent[0],minY:t.extent[1],maxX:t.extent[2],maxY:t.extent[3]}):[".extent[0]",".extent[1]",".extent[2]",".extent[3]"]),this._missing=new Set,this._boundsByFeature=new Map,this.spatialReference=null,this.hasZ=null,this.hasM=null,this.objectIdField=null,this.updating=!1}setup(t){this._addMany(t)}destroy(){this._missing.clear(),this._index=i(this._index),this._boundsByFeature.clear(),this._boundsByFeature=null}update(){this._missing.size>0&&(this._addMany(Array.from(this._missing.values())),this.updating=!1,this._missing.clear())}get updatingRemaining(){return this._missing.size}queryGraphicUIDsInExtent(t,e,i){null!=e&&e.equals(this.spatialReference)&&(h.minX=t[0],h.minY=t[1],h.maxX=t[2],h.maxY=t[3],this.update(),this._index.search(h,t=>i(t.graphic.uid)))}add(t){this._missing.add(t),this.updating=!0}remove(t){if(this._missing.delete(t))return void(this.updating=this._missing.size>0);if(!t.extent)return;this._index.remove(t);const e=a(t.graphic,this._get("objectIdField"));null!=e&&this._boundsByFeature.delete(e)}_addMany(t){if(0===t.length)return;const e=this._get("objectIdField");for(const i of t){i.computeExtent(this.spatialReference);const t=a(i.graphic,e);null!=t&&this._boundsByFeature.set(t,i.extent)}this._index.load(t)}clear(){this._index.clear(),this._missing.clear(),this._boundsByFeature.clear(),this.updating=!1}forEachInBounds(t,e){h.minX=t[0],h.minY=t[1],h.maxX=t[2],h.maxY=t[3],this.update(),this._index.search(h,t=>{e(t)})}getBounds(t,e){this.update();const i=this._boundsByFeature.get(t);return i?o(e,i):null}};t([s({constructOnly:!0})],d.prototype,"spatialReference",void 0),t([s({constructOnly:!0})],d.prototype,"hasZ",void 0),t([s({constructOnly:!0})],d.prototype,"hasM",void 0),t([s({constructOnly:!0})],d.prototype,"objectIdField",void 0),t([s()],d.prototype,"updating",void 0),t([s({readOnly:!0})],d.prototype,"updatingRemaining",null),d=t([n("esri.views.3d.layers.graphics.SpatialIndex2D")],d);const h={minX:0,minY:0,maxX:0,maxY:0};export{d as SpatialIndex2D};
2
+ import{__decorate as t}from"tslib";import e from"../../../../core/Accessor.js";import has from"../../../../core/has.js";import{destroyMaybe as i}from"../../../../core/maybe.js";import{property as s,subclass as n}from"../../../../core/accessorSupport/decorators.js";import{PooledRBush as r}from"../../../../core/libs/rbush/PooledRBush.js";import{fromRect as o}from"../../../../geometry/support/aaBoundingBox.js";import{fromValues as a,create as d}from"../../../../geometry/support/aaBoundingRect.js";import{getInfo as u}from"../../../../geometry/support/spatialReferenceUtils.js";import{getObjectId as h}from"../../../../layers/graphics/dehydratedFeatures.js";let c=class extends e{constructor(t){super(t),this._index=new r(9,has("esri-csp-restrictions")?t=>({minX:t.extent[0],minY:t.extent[1],maxX:t.extent[2],maxY:t.extent[3]}):[".extent[0]",".extent[1]",".extent[2]",".extent[3]"]),this._missing=new Set,this._boundsByFeature=new Map,this.spatialReference=null,this.hasZ=null,this.hasM=null,this.objectIdField=null,this.updating=!1}setup(t){this._addMany(t)}destroy(){this._missing.clear(),this._index=i(this._index),this._boundsByFeature.clear(),this._boundsByFeature=null}update(){this._missing.size>0&&(this._addMany(Array.from(this._missing.values())),this.updating=!1,this._missing.clear())}get updatingRemaining(){return this._missing.size}queryGraphicUIDsInExtent(t,e,i){null!=e&&e.equals(this.spatialReference)&&(this.update(),this._forEachInBounds(t,t=>i(t.graphic.uid)))}add(t){this._missing.add(t),this.updating=!0}remove(t){if(this._missing.delete(t))return void(this.updating=this._missing.size>0);if(!t.extent)return;this._index.remove(t);const e=h(t.graphic,this._get("objectIdField"));null!=e&&this._boundsByFeature.delete(e)}_addMany(t){if(0===t.length)return;const e=this._get("objectIdField");for(const i of t){i.computeExtent(this.spatialReference);const t=h(i.graphic,e);null!=t&&this._boundsByFeature.set(t,i.extent)}this._index.load(t)}clear(){this._index.clear(),this._missing.clear(),this._boundsByFeature.clear(),this.updating=!1}forEachInBounds(t,e){this.update(),this._forEachInBounds(t,e)}_forEachInBounds(t,e){const i=u(this.spatialReference);if(null==i)return void l(this._index,t,e);const s=i.valid;if(t[0]>s[0]&&t[2]<s[1])return void l(this._index,t,e);const n=new Set,r=t=>{const{uid:i}=t.graphic;n.has(i)||(n.add(i),e(t))},o=s[1]-s[0];l(this._index,t,r),t[0]<=s[0]&&l(this._index,m(t,o,g),r),t[2]>=s[1]&&l(this._index,m(t,-o,_),r)}getBounds(t,e){this.update();const i=this._boundsByFeature.get(t);return i?o(e,i):null}};t([s({constructOnly:!0})],c.prototype,"spatialReference",void 0),t([s({constructOnly:!0})],c.prototype,"hasZ",void 0),t([s({constructOnly:!0})],c.prototype,"hasM",void 0),t([s({constructOnly:!0})],c.prototype,"objectIdField",void 0),t([s()],c.prototype,"updating",void 0),t([s({readOnly:!0})],c.prototype,"updatingRemaining",null),c=t([n("esri.views.3d.layers.graphics.SpatialIndex2D")],c);const p={minX:0,minY:0,maxX:0,maxY:0};function l(t,e,i){p.minX=e[0],p.minY=e[1],p.maxX=e[2],p.maxY=e[3],t.search(p,i)}function m(t,e,i){return a(t[0]+e,t[1],t[2]+e,t[3],i)}const g=d(),_=d();export{c as SpatialIndex2D};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{EventedAccessor as t}from"../../../../core/Evented.js";import r from"../../../../core/Logger.js";import{property as i,subclass as n}from"../../../../core/accessorSupport/decorators.js";import{fromQuat as o}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as s}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/quatf64.js";import{set as l,transformMat4 as c}from"../../../../core/libs/gl-matrix-2/math/vec3.js";import{create as m}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{projectBoundingSphere as p}from"../../../../geometry/projection/projectBoundingSphere.js";import{empty as h,expand as u}from"../../../../geometry/support/aaBoundingRect.js";import{Sphere as f}from"../../../../geometry/support/sphere.js";import{ElevationRange as v}from"../../support/ElevationRange.js";import{ElevationUpdateEvent as d}from"../../terrain/ElevationUpdateEvent.js";import{Intersector as g}from"../../webgl-engine/lib/Intersector.js";let E=class extends t{constructor(e){super(e),this._tmpEvent=new d,this._renderCoordsHelper=e.view.renderCoordsHelper,this._renderSR=this._renderCoordsHelper.spatialReference,this._layerElevationSource=e.layerElevationSource}initialize(){this._intersector=new g(this.view.state.viewingMode),this._intersector.options.store=0,this._intersector.options.normalRequired=!1,this._tmpEvent.context=this.intersectionHandler.isGround?"ground":"scene"}get spatialReference(){return this.view?.elevationProvider?.spatialReference}getElevation(e,t,i,n){const o=this._renderCoordsHelper,s=l(R,e,t,i);if(!o.toRenderCoords(s,n,s))return r.getLogger(this).error("could not project point to compute elevation"),null;const{layerElevationSource:a,_intersector:c,intersectionHandler:m}=this,p=a.fullExtent,h=null!=p&&Number.isFinite(p.xmin)&&Number.isFinite(p.xmax)&&Number.isFinite(p.ymin)&&Number.isFinite(p.ymax)&&Number.isFinite(p.zmin)&&Number.isFinite(p.zmax)?new v(p.zmin,p.zmax):a.elevationRange;if(null==h)return null;const u=a.elevationOffset,f=h.minElevation+u,d=h.maxElevation+u,g=o.setAltitude(y,d,s),E=o.setAltitude(j,f,s);return c.reset(g,E,this.view.state.camera),m.intersectRay(c,null,g,E,null,!0),c.results.min.getIntersectionPoint(s)?o.getAltitude(s):null}getElevations(e,t,r){const{groundSpatialReference:i}=this.view;for(let n=0;n<t;++n){const t=3*n,o=e[t],s=e[t+1];r(n,this.getElevation(o,s,0,i))}}getSphereElevationRange(e,t){return p(e,t,_,this._renderSR),this._layerElevationSource.getElevationRange(_)}getRootElevationRange(){const e=this.layerElevationSource.fullExtent;return e?.hasZ?new v(e.zmin,e.zmax):null}notifyObjectsChanged(e){this.spatialReference&&(this._computeLayerExtent(t=>{for(const r of e)t(r)},this._tmpEvent.extent),this._tmpEvent.spatialReference=this.spatialReference,this.emit("elevation-change",this._tmpEvent))}notifyObjectsChangedFunctional(e){this.spatialReference&&(this._computeLayerExtent(e,this._tmpEvent.extent),this._tmpEvent.spatialReference=this.spatialReference,this.emit("elevation-change",this._tmpEvent))}notifyObjectChanged(e){this.spatialReference&&(this._computeObjectExtent(e,this._tmpEvent.extent),this._tmpEvent.spatialReference=this.spatialReference,this.emit("elevation-change",this._tmpEvent))}_computeObjectExtent(e,t){h(t),this._expandExtent(e,t)}_computeLayerExtent(e,t){h(t),e(e=>{this._expandExtent(e,t)})}_expandExtent(e,t){const r=this.spatialReference;if(null==r)return;if(null==e)return;o(x,e.getQuaternion(b)),x[12]=e.centerX,x[13]=e.centerY,x[14]=e.centerZ;const{halfSizeX:i,halfSizeY:n,halfSizeZ:s}=e;for(let o=0;o<8;++o)R[0]=1&o?i:-i,R[1]=2&o?n:-n,R[2]=4&o?s:-s,c(R,R,x),this._renderCoordsHelper.fromRenderCoords(R,R,r),u(t,R,t);for(let o=0;o<2;++o)R[0]=0,R[1]=0,R[2]=0===o?s:-s,c(R,R,x),this._renderCoordsHelper.fromRenderCoords(R,R,r),u(t,R,t)}};e([i({constructOnly:!0})],E.prototype,"layerElevationSource",void 0),e([i({constructOnly:!0})],E.prototype,"intersectionHandler",void 0),e([i({constructOnly:!0})],E.prototype,"view",void 0),e([i()],E.prototype,"spatialReference",null),E=e([n("esri.views.3d.layers.i3s.LayerElevationProvider")],E);const x=s(),_=new f,R=m(),y=m(),j=m(),b=a();export{E as LayerElevationProvider};
2
+ import{__decorate as e}from"tslib";import{EventedAccessor as t}from"../../../../core/Evented.js";import r from"../../../../core/Logger.js";import{property as n,subclass as i}from"../../../../core/accessorSupport/decorators.js";import{fromQuat as o}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as s}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/quatf64.js";import{set as l,transformMat4 as c,transformQuatValues as m}from"../../../../core/libs/gl-matrix-2/math/vec3.js";import{create as u}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{canProjectWithoutEngine as p}from"../../../../geometry/projectionUtils.js";import{projectBoundingRect as h}from"../../../../geometry/projection/projectBoundingRect.js";import{projectBoundingSphere as f}from"../../../../geometry/projection/projectBoundingSphere.js";import{create as d,allFinite as v,fromExtent as g}from"../../../../geometry/support/aaBoundingRect.js";import{getInfo as E}from"../../../../geometry/support/spatialReferenceUtils.js";import{Sphere as j}from"../../../../geometry/support/sphere.js";import{ElevationRange as x}from"../../support/ElevationRange.js";import{ElevationUpdateEvent as y}from"../../support/ElevationUpdateEvent.js";import{ProjectedElevationUpdateExtent as _,calculateElevationUpdateExtents as b,fullWorldElevationUpdateExtent as R,planetCenterProximityToleranceMeters as C}from"../../support/elevationUpdateExtentUtils.js";import{Intersector as S}from"../../webgl-engine/lib/Intersector.js";let w=class extends t{constructor(e){super(e),this._renderCoordsHelper=e.view.renderCoordsHelper,this._renderSR=this._renderCoordsHelper.spatialReference,this._layerElevationSource=e.layerElevationSource,this._projectedExtent=new _(this._renderCoordsHelper)}initialize(){this._intersector=new S(this.view.state.viewingMode),this._intersector.options.store=0,this._intersector.options.normalRequired=!1}get spatialReference(){return this.view?.elevationProvider?.spatialReference}getElevation(e,t,n,i){const o=this._renderCoordsHelper,s=l(F,e,t,n);if(!o.toRenderCoords(s,i,s))return r.getLogger(this).error("could not project point to compute elevation"),null;const{layerElevationSource:a,_intersector:c,intersectionHandler:m}=this,u=a.fullExtent,p=null!=u&&Number.isFinite(u.xmin)&&Number.isFinite(u.xmax)&&Number.isFinite(u.ymin)&&Number.isFinite(u.ymax)&&Number.isFinite(u.zmin)&&Number.isFinite(u.zmax)?new x(u.zmin,u.zmax):a.elevationRange;if(null==p)return null;const h=a.elevationOffset,f=p.minElevation+h,d=p.maxElevation+h,v=o.setAltitude(H,d,s),g=o.setAltitude(M,f,s);return c.reset(v,g,this.view.state.camera),m.intersectRay(c,null,v,g,null,!0),c.results.min.getIntersectionPoint(s)?o.getAltitude(s):null}getElevations(e,t,r){const{groundSpatialReference:n}=this.view;for(let i=0;i<t;++i){const t=3*i,o=e[t],s=e[t+1];r(i,this.getElevation(o,s,0,n))}}getSphereElevationRange(e,t){return f(e,t,O,this._renderSR),this._layerElevationSource.getElevationRange(O)}getRootElevationRange(){const e=this.layerElevationSource.fullExtent;return e?.hasZ?new x(e.zmin,e.zmax):null}notifyObjectsChanged(e){this._notifyObjectsChanged(e.length,t=>{for(const r of e)if(!t(r))break})}notifyObjectsChangedFunctional(e,t){this._notifyObjectsChanged(e,t)}notifyObjectChanged(e){this._notifyObjectsChanged(1,t=>{t(e)})}_notifyObjectsChanged(e,t){if(0===e)return;const r=this.spatialReference;if(null==r)return;if(!p(this._renderSR,r))return void this._emitFullExtentElevationChange(r);const n=new Float64Array(4*e);let i=!1,o=0;t(e=>this._computeObjectExtent(e,n,o,r)?(o++,!0):(i=!0,!1)),i?this._emitFullExtentElevationChange(r):this._emitElevationChangeEvents(n,r)}_computeObjectExtent(e,t,r,n){if(1===this.view.state.viewingMode&&U(e))return!1;const i=this._projectedExtent;return F[0]=e.centerX,F[1]=e.centerY,F[2]=e.centerZ,i.reset(F,e.radius,n),!!this._expandExtent(e,i,n)&&(!!v(i.extent)&&(t.set(i.extent,4*r),!0))}_emitElevationChangeEvents(e,t){for(const r of b(e,t))this._emitElevationChangeEvent(r,t)}_emitFullExtentElevationChange(e){const t=d(),r=this._layerElevationSource.fullExtent;if(null!=r&&h(g(r,Z),r.spatialReference,t,e)&&v(t))return void this._emitElevationChangeEvent(t,e);const n=E(e);null!=n&&this._emitElevationChangeEvent(R(e,n),e)}_emitElevationChangeEvent(e,t){const r=new y(t,e,this.intersectionHandler.isGround?"ground":"scene");this.emit("elevation-change",r)}_expandExtent(e,t,r){o(z,e.getQuaternion(N)),z[12]=e.centerX,z[13]=e.centerY,z[14]=e.centerZ;const{halfSizeX:n,halfSizeY:i,halfSizeZ:s}=e;for(let o=0;o<8;++o)if(F[0]=1&o?n:-n,F[1]=2&o?i:-i,F[2]=4&o?s:-s,c(F,F,z),null==t.addRenderPoint(F,r))return!1;for(let o=0;o<2;++o)if(F[0]=0,F[1]=0,F[2]=0===o?s:-s,c(F,F,z),null==t.addRenderPoint(F,r))return!1;return!0}};e([n({constructOnly:!0})],w.prototype,"layerElevationSource",void 0),e([n({constructOnly:!0})],w.prototype,"intersectionHandler",void 0),e([n({constructOnly:!0})],w.prototype,"view",void 0),e([n()],w.prototype,"spatialReference",null),w=e([i("esri.views.3d.layers.i3s.LayerElevationProvider")],w);const z=s(),O=new j,F=u(),H=u(),M=u(),N=a(),Z=d(),P=u();function U(e){P[0]=-e.centerX,P[1]=-e.centerY,P[2]=-e.centerZ,e.getQuaternion(N),m(P,P,-N[0],-N[1],-N[2],N[3]);const t=Math.max(Math.abs(P[0])-e.halfSizeX,0),r=Math.max(Math.abs(P[1])-e.halfSizeY,0),n=Math.max(Math.abs(P[2])-e.halfSizeZ,0);return t*t+r*r+n*n<=C*C}export{w as LayerElevationProvider};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{EventedAccessor as t}from"../../../../core/Evented.js";import r from"../../../../core/Logger.js";import{getMetersPerVerticalUnitForSR as o}from"../../../../core/units.js";import{property as n,subclass as s}from"../../../../core/accessorSupport/decorators.js";import{create as i}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{empty as a,toRect as l,expandWithVec3 as d}from"../../../../geometry/support/aaBoundingBox.js";import{getMetersPerUnit as c}from"../../../../symbols/support/unitConversionUtils.js";import{ElevationUpdateEvent as h}from"../../terrain/ElevationUpdateEvent.js";import{Intersector as m}from"../../webgl-engine/lib/Intersector.js";import{affectsGeometry as p}from"../../webgl-engine/lib/VertexAttribute.js";const u=1,f=Symbol("layerHandles");let g=class extends t{get spatialReference(){return this.view.spatialReference}constructor(e){super(e),this._elevationOffset=0}initialize(){this._renderCoordsHelper=this.view.renderCoordsHelper,this._intersectLayers=[this.stageLayer],this._intersector=new m(this.view.state.viewingMode),this._intersector.options.store=0;const e=this._computeLayerExtent(this.spatialReference,this.stageLayer);this._zmin=e[2],this._zmax=e[5];const t=this.stageLayer.events;this.addHandles([t.on(["layerObjectAdded","layerObjectRemoved","transformationChanged","shaderTransformationChanged"],e=>this._objectChanged(e)),t.on(["geometryAdded","geometryRemoved"],({object:e})=>this._objectChanged(e)),t.on("attributesChanged",({attribute:e,object:t})=>p(e)&&this._objectChanged(t))],f)}destroy(){this.removeHandles(f)}elevationInfoChanged(){const e=null!=this.layer?this.layer.elevationInfo:null;if(null!=e&&"on-the-ground"!==e.mode){const t=o(this.layer.spatialReference),r=c(e.unit??"meters");this._elevationOffset=(e.offset??0)*r/t}else this._elevationOffset=0}getElevation(e,t,o,n){if(x[0]=e,x[1]=t,x[2]=o,!this._renderCoordsHelper.toRenderCoords(x,n,x))return r.getLogger(this).error("could not project point for elevation alignment"),null;const s=this._elevationOffset,i=this._zmin+s,a=this._zmax+s;this._renderCoordsHelper.setAltitude(b,a,x),this._renderCoordsHelper.setAltitude(j,i,x);const l=e=>!!e.lastValidElevationBB;return this._intersector.reset(b,j,null),this._intersector.intersect(this._intersectLayers,null,u,null,l),this._intersector.results.min.getIntersectionPoint(x)?this._renderCoordsHelper.getAltitude(x):null}_objectChanged(e){const t=this.spatialReference;if(!e.lastValidElevationBB||!t)return;a(_);const r=e.lastValidElevationBB;r.isEmpty()||this._expandExtent(t,r.min,r.max,_);const{min:o,max:n}=e.boundingVolumeWorldSpace;this._expandExtent(t,o,n,_),l(_,v.extent),this._zmin=Math.min(this._zmin,_[2]),this._zmax=Math.max(this._zmax,_[5]),v.spatialReference=t,this.emit("elevation-change",v),v.spatialReference=null,r.assignMinMax(o,n)}_computeLayerExtent(e,t){return a(_),null!=e&&t.objects.forEach(t=>this._expandExtent(e,t.boundingVolumeWorldSpace.min,t.boundingVolumeWorldSpace.max,_)),_}_expandExtent(e,t,r,o){for(let n=0;n<8;++n)x[0]=1&n?t[0]:r[0],x[1]=2&n?t[1]:r[1],x[2]=4&n?t[2]:r[2],this._renderCoordsHelper.fromRenderCoords(x,x,e),d(o,x);return o}};e([n({constructOnly:!0})],g.prototype,"layer",void 0),e([n({constructOnly:!0})],g.prototype,"stageLayer",void 0),e([n({constructOnly:!0})],g.prototype,"view",void 0),e([n()],g.prototype,"spatialReference",null),g=e([s("esri.views.3d.layers.support.StageLayerElevationProvider")],g);const _=a(),v=new h;function y(){v.spatialReference=null}const x=i(),b=i(),j=i();export{g as StageLayerElevationProvider,y as cleanupStageLayerElevationProvider};
2
+ import{__decorate as e}from"tslib";import{EventedAccessor as t}from"../../../../core/Evented.js";import n from"../../../../core/Logger.js";import{getMetersPerVerticalUnitForSR as r}from"../../../../core/units.js";import{property as o,subclass as i}from"../../../../core/accessorSupport/decorators.js";import{dist as s}from"../../../../core/libs/gl-matrix-2/math/vec3.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{allFinite as l}from"../../../../geometry/support/aaBoundingRect.js";import{getInfo as d}from"../../../../geometry/support/spatialReferenceUtils.js";import{getMetersPerUnit as h}from"../../../../symbols/support/unitConversionUtils.js";import{ElevationUpdateEvent as m}from"../../support/ElevationUpdateEvent.js";import{ProjectedElevationUpdateExtent as c,calculateElevationUpdateExtents as p,fullWorldElevationUpdateExtent as u,planetCenterProximityToleranceMeters as g}from"../../support/elevationUpdateExtentUtils.js";import{Intersector as _}from"../../webgl-engine/lib/Intersector.js";import{affectsGeometry as f}from"../../webgl-engine/lib/VertexAttribute.js";const v=1,x=Symbol("layerHandles");let E=class extends t{get spatialReference(){return this.view.spatialReference}constructor(e){super(e),this._elevationOffset=0}initialize(){this._renderCoordsHelper=this.view.renderCoordsHelper,this._projectedExtent=new c(this._renderCoordsHelper),this._intersectLayers=[this.stageLayer],this._intersector=new _(this.view.state.viewingMode),this._intersector.options.store=0;const[e,t]=this._computeLayerElevationRange(this.spatialReference,this.stageLayer);this._zmin=e,this._zmax=t;const n=this.stageLayer.events;this.addHandles([n.on(["layerObjectAdded","layerObjectRemoved","transformationChanged","shaderTransformationChanged"],e=>this._objectChanged(e)),n.on(["geometryAdded","geometryRemoved"],({object:e})=>this._objectChanged(e)),n.on("attributesChanged",({attribute:e,object:t})=>f(e)&&this._objectChanged(t))],x)}destroy(){this.removeHandles(x)}elevationInfoChanged(){const e=null!=this.layer?this.layer.elevationInfo:null;if(null!=e&&"on-the-ground"!==e.mode){const t=r(this.layer.spatialReference),n=h(e.unit??"meters");this._elevationOffset=(e.offset??0)*n/t}else this._elevationOffset=0}getElevation(e,t,r,o){if(R[0]=e,R[1]=t,R[2]=r,!this._renderCoordsHelper.toRenderCoords(R,o,R))return n.getLogger(this).error("could not project point for elevation alignment"),null;const i=this._elevationOffset,s=this._zmin+i,a=this._zmax+i;this._renderCoordsHelper.setAltitude(H,a,R),this._renderCoordsHelper.setAltitude(L,s,R);const l=e=>!!e.lastValidElevationBB;return this._intersector.reset(H,L,null),this._intersector.intersect(this._intersectLayers,null,v,null,l),this._intersector.results.min.getIntersectionPoint(R)?this._renderCoordsHelper.getAltitude(R):null}_objectChanged(e){const t=this.spatialReference;if(!e.lastValidElevationBB||!t)return;const n=e.lastValidElevationBB,{min:r,max:o,bounds:i}=e.boundingVolumeWorldSpace;if(1===this.view.state.viewingMode&&(!n.isEmpty()&&y(n.min,n.max)||y(r,o)))return this._emitFullExtentElevationChange(t),void n.assignMinMax(r,o);const s=!n.isEmpty(),a=new Float64Array(s?8:4);let d=1/0,h=-1/0,m=!1;if(s&&(this._resetProjectedExtent(n.min,n.max,t),this._expandExtent(t,n.min,n.max,M,this._projectedExtent)||(m=!0),l(this._projectedExtent.extent)?(d=Math.min(d,M[0]),h=Math.max(h,M[1]),a.set(this._projectedExtent.extent)):m=!0),this._projectedExtent.reset(i.center,i.radius,t),this._expandExtent(t,r,o,b,this._projectedExtent)||(m=!0),l(this._projectedExtent.extent)?(d=Math.min(d,b[0]),h=Math.max(h,b[1]),a.set(this._projectedExtent.extent,s?4:0)):m=!0,m)return this._emitFullExtentElevationChange(t),void n.assignMinMax(r,o);const c=p(a,t);c.length>0&&(this._zmin=Math.min(this._zmin,d),this._zmax=Math.max(this._zmax,h));for(const l of c)this._emitElevationChangeEvent(l,t);n.assignMinMax(r,o)}_computeLayerElevationRange(e,t){let n=1/0,r=-1/0;return null!=e&&t.objects.forEach(t=>{this._expandExtent(e,t.boundingVolumeWorldSpace.min,t.boundingVolumeWorldSpace.max,C)&&(n=Math.min(n,C[0]),r=Math.max(r,C[1]))}),[n,r]}_expandExtent(e,t,n,r,o=null){r[0]=1/0,r[1]=-1/0;for(let i=0;i<8;++i){R[0]=1&i?t[0]:n[0],R[1]=2&i?t[1]:n[1],R[2]=4&i?t[2]:n[2];const s=null!=o?o.addRenderPoint(R,e):this._renderCoordsHelper.fromRenderCoords(R,R,e);if(null!=s)r[0]=Math.min(r[0],s[2]),r[1]=Math.max(r[1],s[2]);else if(null!=o)return!1}return!0}_emitFullExtentElevationChange(e){const t=d(e);null!=t&&this._emitElevationChangeEvent(u(e,t),e)}_emitElevationChangeEvent(e,t){const n=new m(t,e);this.emit("elevation-change",n)}_resetProjectedExtent(e,t,n){w[0]=.5*(e[0]+t[0]),w[1]=.5*(e[1]+t[1]),w[2]=.5*(e[2]+t[2]),this._projectedExtent.reset(w,.5*s(e,t),n)}};function y(e,t){const n=j(0,e[0],t[0]),r=j(0,e[1],t[1]),o=j(0,e[2],t[2]);return n*n+r*r+o*o<=g*g}function j(e,t,n){return e<t?t-e:e>n?e-n:0}e([o({constructOnly:!0})],E.prototype,"layer",void 0),e([o({constructOnly:!0})],E.prototype,"stageLayer",void 0),e([o({constructOnly:!0})],E.prototype,"view",void 0),e([o()],E.prototype,"spatialReference",null),E=e([i("esri.views.3d.layers.support.StageLayerElevationProvider")],E);const b=new Float64Array(2),C=new Float64Array(2),M=new Float64Array(2),w=a(),R=a(),H=a(),L=a();export{E as StageLayerElevationProvider};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ class t{constructor(t,e,s="scene"){this.spatialReference=t,this.extent=e,this.context=s}}export{t as ElevationUpdateEvent};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{asinClamped as t}from"../../../core/mathUtils.js";import{len as r}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as e}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{empty as n,expand as o,create as i,fromValues as s}from"../../../geometry/support/aaBoundingRect.js";import{getInfo as a,isGeographic as h}from"../../../geometry/support/spatialReferenceUtils.js";const l=1;function m(t,r){const e=r.valid,n=h(t)?90:e[1];return s(e[0],-n,e[1],n)}function c(t,r){const e=a(r);if(null==r||null==e){if(0===t.length)return[];const r=i();return f(t,r),[r]}return 0===t.length?[m(r,e)]:d(t,e)}class u{constructor(t){this._renderCoordsHelper=t,this.extent=n(),this._mapCenterX=NaN,this._worldXWidth=0}reset(e,o,i){n(this.extent),this._mapCenterX=NaN;const s=a(i);if(1!==this._renderCoordsHelper.viewingMode||null==s)return;const h=r(e);if(o>=h)return;const l=Math.asin(o/h),m=t(e[2]/h);if(l>M||Math.abs(m)+l>=Math.PI/2)return;if(null==this._renderCoordsHelper.fromRenderCoords(e,_,i))return;this._mapCenterX=_[0];const c=s.valid;this._worldXWidth=c[1]-c[0]}addRenderPoint(t,r){return null==this._renderCoordsHelper.fromRenderCoords(t,_,r)?null:(Number.isFinite(this._mapCenterX)&&(_[0]+=Math.round((this._mapCenterX-_[0])/this._worldXWidth)*this._worldXWidth),o(this.extent,_,this.extent),_)}}function d(t,r){const e=r.valid,n=e[1]-e[0],o=t[0];let i=1/0,a=1/0,h=-1/0,l=-1/0,m=1/0,c=-1/0;for(let s=0;s<t.length;s+=4){const r=t[s],e=t[s+1],u=t[s+2],d=t[s+3];i=Math.min(i,r),h=Math.max(h,u),a=Math.min(a,e),l=Math.max(l,d);const f=Math.round((o-r)/n),p=r+f*n,M=u+f*n;m=Math.min(m,p),c=Math.max(c,M)}const u=s(i,a,h,l);let d=i,f=h;if(c-m<f-d&&(d=m,f=c),f-d>=n)return u[0]=e[0],u[2]=e[1],[u];const M=p(d,e[0],n);if(d+=M*n,f+=M*n,f<=e[1])return u[0]=d,u[2]=f,[u];u[0]=e[0],u[2]=f-n;return[u,s(d,a,e[1],l)]}function f(t,r){let e=1/0,n=1/0,o=-1/0,i=-1/0;for(let s=0;s<t.length;s+=4){const r=t[s],a=t[s+1],h=t[s+2],l=t[s+3];e=Math.min(e,r),n=Math.min(n,a),o=Math.max(o,h),i=Math.max(i,l)}s(e,n,o,i,r)}function p(t,r,e){return Math.ceil((r-t)/e)}const M=Math.PI/4,_=e();export{u as ProjectedElevationUpdateExtent,c as calculateElevationUpdateExtents,m as fullWorldElevationUpdateExtent,l as planetCenterProximityToleranceMeters};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../Color.js";import{filterInPlace as i,difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import{EventedAccessor as n}from"../../../core/Evented.js";import"../../../core/has.js";import l from"../../../core/Logger.js";import{clamp as o}from"../../../core/mathUtils.js";import{destroyMaybe as h}from"../../../core/maybe.js";import{MemCachePool as d}from"../../../core/MemCachePool.js";import p from"../../../core/ObjectPool.js";import u from"../../../core/PooledArray.js";import{throwIfAborted as c,isAbortError as g,isAborted as m}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as y,sync as f,initial as T}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as v}from"../../../core/units.js";import{property as w,subclass as S}from"../../../core/accessorSupport/decorators.js";import{exactEquals as C,set as b,copy as E}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as x}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as U}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as L,radiusModifier as P}from"../../../geometry/ellipsoidUtils.js";import R from"../../../geometry/SpatialReference.js";import{getProjector as M}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as j}from"../../../geometry/projection/projectVectorToVector.js";import{create as I,equals as k,intersection as V,intersectsSphere as A,empty as B,expand as G}from"../../../geometry/support/aaBoundingRect.js";import{copy as O,create as q}from"../../../geometry/support/frustum.js";import{createSpatialReferenceCyclical as N}from"../../../geometry/support/normalizeUtils.js";import{isPlateCarree as F}from"../../../geometry/support/spatialReferenceUtils.js";import{Sphere as W}from"../../../geometry/support/sphere.js";import{ElevationQueryTileCache as H}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as $}from"../../../layers/support/layerUtils.js";import{queueHighPriority as Q}from"../../../request/queue.js";import{debugFlags as z}from"../support/debugFlags.js";import{ElevationRange as Y}from"../support/ElevationRange.js";import{toBoundingRect as X}from"../support/extentUtils.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{ElevationUpdateEvent as te}from"./ElevationUpdateEvent.js";import{create as ie}from"./ExtentHelper.js";import{LayerClasses as re}from"./LayerClass.js";import{OverlayManager as se}from"./OverlayManager.js";import{PlanarPatch as ae}from"./PlanarPatch.js";import{Queue as ne}from"./Queue.js";import{ScaleRangeQueries as le}from"./ScaleRangeQueries.js";import{SphericalPatch as oe}from"./SphericalPatch.js";import{SplitLimits as he}from"./SplitLimits.js";import{maxRootTiles as de,tooManyRootTilesAfterChangeError as pe,tooManyRootTilesForLayerError as ue,maxTileNeighborLevelDelta as ce,maxMemoryLodBias as ge}from"./TerrainConst.js";import{TerrainRenderer as me}from"./TerrainRenderer.js";import _e from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as ye,isVectorTileLayerView as fe,neighborEdgeIndices as Te,internalAssert as ve,oppositeEdge as we,isSurfaceLayerView as Se,isGroupLayerView as Ce,isMapTileLayerView as be,isBlendableLayerView as Ee,isElevationLayerView as xe,releaseTerrainData as Ue,enableTerrainInternalChecks as Le,oppositeCorner as Pe,enableWaterproofTests as Re,enableInternalTerrainChecks as Me,enableTerrainWaterproofChecks as De,neighborCornerIndices as je}from"./terrainUtils.js";import{Tile as Ie,lijEquals as ke}from"./Tile.js";import{printAllocations as Ve}from"./TilePerLayerInfo.js";import{sortTiles as Ae,IteratorPreorder as Be,IteratorPostorder as Ge,compareTilesByLij as Oe,hasLoadableSiblings as qe,sortTilesByPOI as Ne,traverseTilesPreorder as Fe}from"./tileUtils.js";import{TilingSchemeLogic as We}from"./TilingSchemeLogic.js";import{UpsampleInfo as He}from"./UpsampleInfo.js";import{isCompositeBlendMode as $e,blendModeFromString as Qe}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{hasLayerBasedScaleVisibility as ze}from"../../support/layerViewUtils.js";import{ImmediateTask as Ye,TaskPriority as Xe,noBudget as Ke}from"../../support/Scheduler.js";import{TextureCompressionTracker as Je}from"../../support/TextureCompressionTracker.js";import{Yield as Ze}from"../../support/Yield.js";var et;let tt=class extends n{static{et=this}get allTilesCreated(){return this._allTilesCreated}get allTiles(){return a(this._allTiles)}get renderedTiles(){return Ae(i(this._allTiles.toArray(),e=>e.visible&&e.rendered))}get demResolution(){const{_allTiles:e,tilingScheme:t}=this;if(0===e.length)return{min:1,max:1};const i=v(t.spatialReference);let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const a of e){const e=t.resolutionAtLevel(a.level)*i;r=Math.min(r,e),s=Math.max(s,e)}return{min:r,max:s}}constructor(e){super(e),this.terrainTextureCompressionTracker=new Je,this._iteratorPool=new p(()=>new Be,e=>e.remove=()=>this._iteratorPool.release(e)),this._postorderIterator=new Ge,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._allTilesCreated=!1,this._usedMemory=null,this._performanceInfo=new _e,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=x(),this._eyePosSurfaceSR=x(),this._splitLimits=new he,this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new U,this._frameTask=Ye,this._allTiles=new u,this._upsampleInfoPool=new p(()=>new He),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=I(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=R.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationRange=new Y(1/0,-1/0),this._rootTileElevationRange=new Y(1/0,-1/0),this._projectorCache=new Map,this._tilingSchemeSpatialReference=null,this._updatingRootTiles=!1,this._pendingTilesForElevationUpdateEvent=new Set,this._pendingTilesToUpdate=new Set,this.totalGeometryUpdates=0,this.totalTileUpdates=0,this._oneBatchPerFrameTask=!0,this._layerViewsDirty=!1,this.unloadedMemory=0,this.ignoresMemoryFactor=!1,this._isWebMercator=!1,this._isWebMercatorOnPlateCarree=!1,this.enabled=!0;const{view:t}=e;this.overlayManager=new se({...e,terrainSurface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?oe:ae,this._ellipsoid=L(t.spatialReference),this._renderer=new me(this.overlayManager.renderer,t.stage,this._allTiles,this.terrainTextureCompressionTracker,t.resourceController.memoryController),ze()||(this._scaleRangeQueries=new le)}initialize(){const{view:e}=this,{resourceController:t}=e,{memoryController:i}=t;this._tileCache=new d((e,t)=>i.newCache(e,t),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",({tile:e})=>e.unloadMapData()),this._elevationQueryCache=new H(i.newCache("elevation-query"));const r=this.overlayManager;this.addHandles([_(()=>r.renderer.isEmpty,()=>this._evaluateTransparency()),_(()=>this.renderer.visible,e=>this.suspended=!e),_(()=>this.heading,e=>{this._renderer.updateHeading(e),this._updateTileTextures(0)},y),_(()=>({heading:e.camera?.heading,state:e.state?.mode}),({heading:e,state:t})=>{if(null==e)return;if(this.isGlobal&&this.isGeographic||this.isWebMercatorOnPlateCarree)return void(this.heading=90*Math.round(e/90)%360);const i=Math.round(e)%360,r=Math.abs(i-this.heading);(2===t||Math.min(r,360-r)>=30)&&(this.heading=i)})],"overlayManager"),this.addHandles([_(()=>this.baseOpacity,()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?1:2)},y),_(()=>this.hasCompositeBlendMode,()=>this._updateTileTextures(this._evaluateTransparency()?1:2),y),_(()=>this.backgroundColor,(e,t)=>{e?.equals(t)||(this._handleLayerViewChanges(),this._renderer.updateTileBackground(e))},f),_(()=>this.snapLevel,()=>this._viewChanged=!0,f),_(()=>this.view.pointsOfInterest,e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add(()=>e.focus?.renderLocation,()=>this._allTilesSorted=!1,{equals:C})}),_(()=>z.TERRAIN_TILE_TREE_SHOW_TILES,t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then(({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&z.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))}):t||(this._treeDebugger=h(this._treeDebugger))},T)]);const{spatialReference:a}=e;this._extentHelper=ie(this.viewingMode,{layers:e.map.allLayers,layerViews:e.allLayerViews,viewSpatialReference:a});const n=new s({getCollections:()=>e.defaultsFromMap?.mapCollections?.map(({layers:e})=>e),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),l=new We({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme();const o=t.scheduler;this._frameTask=o.registerTask(Xe.TERRAIN_SURFACE,this),this.addHandles([_(()=>this._extentHelper.stencilEnabledExtents,e=>this._renderer.setStencilEnabledLayerExtents(e),T),_(()=>this.tilingSchemeLogic.tilingScheme,()=>this._updateTilingScheme(),f),_(()=>this.groundExtent,()=>this._updateRootTiles(),T),e.on("resize",()=>this._viewChangeUpdate()),_(()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]},()=>this._viewChangeUpdate(),y),_(()=>e.qualitySettings?.fadeDuration,e=>this._renderer.textureFadingEnabled=e>0,T),_(()=>e.qualitySettings?.physicallyBasedRenderingEnabled,e=>this._renderer.pbrMode=e?5:0,T),_(()=>e.qualitySettings?.tiledSurface.elevationLevelDelta,()=>this._updateAllTileGeometries()),_(()=>this.userClippingExtent,()=>this._updateClippingExtent(),f)]),this.addHandles(e.allLayerViews.on("after-changes",()=>this._layerViewsDirty=!0)),this._layerViewsDirty=!0,this._handleLayerViewChanges(),this._renderer.updateTileBackground(this.backgroundColor)}clearHandles(){this._watchUpdatingTracking?.removeAll(),this.removeAllHandles(),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear()}destroy(){this._frameTask.remove(),this._frameTask=Ye,this._watchUpdatingTracking?.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear(),this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),this._allTiles.prune(),Ie.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroyed||this._renderer.destroy(),this._renderer=null,this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),Ve(),this._layerViews.forEach(e=>e.length=0),this._performanceInfo=null}get renderer(){return this._renderer}get frustum(){return this.view.state.camera.frustum}get snapLevel(){return this.lodSnappingEnabled?this.view.terrainLevel:null}get lodSnappingEnabled(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get hasStencilEnabledExtents(){return this._extentHelper.stencilEnabledExtents.length>0}get userClippingExtent(){const{spatialReference:e}=this,t=this.view?.clippingArea;if(null==t||null==e)return null;const i=I(),r=X(t,i,e)?i:null,s=this._get("userClippingExtent");return k(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get groundExtent(){const e=V(this.fullGroundExtent,this.userClippingExtent,I()),t=this._get("groundExtent");return k(e,t)?t:e}get fullGroundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),this.enabled&&!!((this.readyToRun||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get readyToRun(){return this.enabled&&(this._hasPendingUpdates||this._viewChanged||this._allTilesDirty||!this._allTilesSorted||this._hasElevationSourceUpdates||this._layerViewsDirty||this._scaleRangeQueries?.updating||this._frameTask.updating)&&this.ready&&!this.suspended}get _hasElevationSourceUpdates(){return this._allTiles.some(e=>e.needsElevationSourceUpdate())}get updatingProgressValue(){return this._maxNumUpdating=Math.max(this._pendingUpdates,this._maxNumUpdating),1-this._pendingUpdates/this._maxNumUpdating}get baseOpacity(){return this.view?.map?.ground?.opacity??1}set baseOpacity(e){this.view.map.ground.opacity=e}get viewingMode(){return this.view.state.viewingMode}get ready(){return!this.enabled||null!=this._rootTiles}get rootTiles(){return this._rootTiles}get spatialReference(){return this.tilingScheme?.spatialReference??null}get backgroundColor(){return this.view?.map?.ground?.surfaceColor}set backgroundColor(e){this.view.map.ground.surfaceColor=e}set slicePlaneEnabled(e){this._renderer.slicePlaneEnabled=e,this._set("slicePlaneEnabled",e),this._evaluateTransparency()}get tilingSchemeLocked(){return this.tilingSchemeLogic?.tilingSchemeLocked??!1}get wireframe(){return this._renderer?.wireframe}set wireframe(e){e!==this._renderer.wireframe&&(this._renderer.wireframe=e,this._updateAllTileGeometries())}get opaque(){return 0===this._renderer.transparency}get invisible(){return 3===this._renderer.transparency}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get fadeDuration(){return this.view.qualitySettings.fadeDuration??0}intersect(e,t,i,r){this._renderer.intersectRay(e,t,i,r)}getElevationLevelDelta(e){return e<4?3:this.view.qualitySettings.tiledSurface.elevationLevelDelta}get _xNormalizer(){return N(this._spatialReference)}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length||!this.enabled)return null;if(0===s[0].layerInfo[0].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=M(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return l.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const n=b(rt,e,t,i);a(n,0,n,0);return ht(s,this._xNormalizer?.normalize(n[0])??n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[0].length:0;if(r?.length&&0!==s&&this.enabled)for(let a=0;a<t;++a){const t=3*a;i(a,ht(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getLayerIndexByUID(e,t){return this._layerIndexByUid[e].get(t)}getScale(e){if(!this.tilingScheme)return null;if(!D(e,rt,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getScale(): could not project given point to tiling scheme coordinate system"),null;const t=this._rootTiles;if(null!=t)for(const i of t)if(i?.containsPoint(rt)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;rt[0]>t[2]&&(i+=1),rt[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}_ensureProjector(e){const t=this._projectorCache.get(e);if(t)return t;const i=M(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationRange(e,t){if(!this.enabled||null==this._rootTiles)return null;const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationRange(): could not project given point to tiling scheme coordinate system"),null;st.copyFrom(e),i(st.center,0,st.center,0);const r=new Y,s=this._rootTiles;if(null!=s){const e=[];for(const i of s)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,st))continue;const s=i.children;if(null==s[0]||i.rendered)r.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of s)e.push(t)}}return r}getRootElevationRange(){return this.enabled&&null!=this._rootTiles?new Y(this._rootTileElevationRange.minElevation,this._rootTileElevationRange.maxElevation):null}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationRange.minElevation)*P;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,st.center,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;st.radius=t;let i=null;const r=e=>{if(e&&A(e.extent,st)){const t=e.children;if(t[0]&&!e.rendered)for(const e of t)r(e);else{const t=this._getLodBiasCorrectedScale(e.level);i=null==i?t:Math.min(i,t)}}},s=this._rootTiles;if(null!=s)for(const a of s)r(a);return i}queryVisibleScaleRange(e,t,i,r){if(!this._scaleRangeQueries)return;const s=t?this.tilingScheme.levelAtScale(t):0,a=i?this.tilingScheme.levelAtScale(i):1/0,n=this._lodBias;this._scaleRangeQueries.queryVisibleLevelRange(e,s+n,a+n,r)}_evaluateTransparency(){const e=this.baseOpacity,t=this.overlayManager.renderer.isEmpty,i=this._renderer.transparency,r=this._isFullyTransparent?t?3:2:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?0:1;return this._renderer.transparency=r,i!==r&&(this.notifyChange("opaque"),this.notifyChange("invisible"),!0)}_updateTilingScheme(){const{tilingScheme:e}=this.tilingSchemeLogic;if(!(e!==this.tilingScheme))return;ye(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??R.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&F(this.view?.renderSpatialReference),this._isGeographic=t?.isGeographic??!1,this._set("tilingScheme",e),this._tilingSchemeSpatialReference=this.tilingScheme?.spatialReference,this._projectorCache.clear(),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.tileSize=e.pixelSize,this.overlayManager.spatialReference=e.spatialReference,this._updateRootTiles())}static{this._tileMemcacheKey="TerrainTileMemcache"}_acquireTile(e,t,i,r){const s=this._tileCache.pop(et._tileMemcacheKey);return s?(s.init(e,t,i,r,this),s):new this._tileConstructor(e,t,i,r,this)}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{groundExtent:e,tilingScheme:t}=this;if(!t)return;if(!this.enabled)return void this._setRootTiles(null);const i=at;let s=t.rootTilesInExtent(e,i,5*de);if(null!=this._rootTiles){if(s.length>de)return void l.getLogger(this).warn(pe);const e=this._rootTiles.map(e=>e.lij),t=r(e,s,ke);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter(e=>!(t.removed.findIndex(t=>ke(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>de&&(l.getLogger(this).warn(ue),s=t.rootTilesInExtent(e,i,de)),this._setRootTiles(s.map(e=>this._newRootTile(e)));k(i,this._rootTilesExtent)||(this._rootTilesExtent=I(i)),this.renderer.visible=!0,this._viewChangeUpdate(),this.overlayManager.setPlacementDirty(),this.notifyChange("ready"),this._updateAllTileGeometries(),this._updatingRootTiles=!1,this.checkAllTilesWaterproofness()}_updateAllTileGeometries(){const e=this._allTiles.filter(e=>this._canUpdateTileGeometry(e));0!==e.length?(e.sort(Oe),e.forEach(e=>this._renderer.updateTileGeometryState(e)),e.forEach(e=>e.renderData.updateNeighborData()),this._updateTilesGeometries(e),this._pendingTilesToUpdate.clear()):this._pendingTilesToUpdate.clear()}_updateTilesGeometries(e){const t=e.filter(e=>this._canUpdateTileGeometry(e));if(0===t.length)return;const i=this.renderer;for(const r of t)i.updateGeometryIfNeeded(r);for(const r of t)this._pendingTilesForElevationUpdateEvent.add(r)}_canUpdateTileGeometry(e){return e.loaded&&e.intersectsClippingArea&&e.hasGeometryState}_shouldSplit(e){return 1===e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(1),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationRange(),t}_setRootTiles(e){if(this._rootTiles=e,this._allTiles.clear(),null!=e){const t=this._iteratorPool.acquire();for(t.reset(e);!t.done;)this._allTiles.push(t.next());t.remove()}this._renderer.setRootTiles(this._rootTiles),this._updateTilesVisibility(e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this.renderer.visible&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.groundExtent)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=qe(e),i=this.visibleElevationRange;let r=t?i.minElevation:1/0,s=t?i.maxElevation:-1/0;const a=this.groundExtent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty(!1);const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBoundsMin,r),s=Math.max(e.elevationBoundsMax,s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._updatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.minElevation!==r||i.maxElevation!==s)&&(this.visibleElevationRange=new J(r,s))}_updateRootTileElevationRange(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach(({elevationBoundsMin:i,elevationBoundsMax:r})=>{e=Math.min(e,i),t=Math.max(t,r)});const r=this._rootTileElevationRange;r.minElevation===e&&r.maxElevation===t||(this._rootTileElevationRange=new J(e,t))}_updateViewDependentParameters(){const{camera:e,contentCamera:t}=this.view.state,i=Math.tan(.5*t.fovX),r=Math.tan(.5*t.fovY),s=this.tilingScheme.pixelSize,a=2**-this._lodBias*e.pixelRatio;this._splitLimits.aboveGround=e.aboveGround,this._splitLimits.fovX=i,this._splitLimits.fovY=r,this._splitLimits.relativeWidthLimit=s/e.width*this.maxTextureScale*a,this._splitLimits.relativeHeightLimit=s/e.height*this.maxTextureScale*a,this._splitLimits.maxLod=this.tilingScheme.getMaxLod(),this._splitLimits.angledSplitBias=this.view.qualitySettings.tiledSurface.angledSplitBias,this.view.state.fixedContentCamera?this._splitLimits.frustum=O(this._splitLimits.frustum??q(),t.frustum):this._splitLimits.frustum=null,E(this._eyePosRenderSR,t.eye),j(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateTileGeometryState(e){e.updateVisibility();const t=this._renderer.updateTileGeometryState(e);e.needsElevationSourceUpdate()&&(e.updateAgents(0),e.markElevationSourceUpdateRequested(),this.requestUpdate()),t&&this._markTileToUpdate(e),this.setMemoryDirty()}_markAllTileNeighborsForUpdate(e){e.forEachLoadedNeighbor(e=>{this._layerViews[1].some(fe)&&e.setPendingUpdate(32),this._pendingTilesToUpdate.add(e)})}_updateTileTexture(e,t){const i=e.resetPendingUpdate(32)?32:!!e.resetPendingUpdate(16)&&16;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=lt.extent;B(e),this._pendingTilesForElevationUpdateEvent.forEach(t=>G(e,t.extent,e)),this._pendingTilesForElevationUpdateEvent.clear(),lt.spatialReference=this.spatialReference,this.emit("elevation-change",lt),this._shouldEmitChangeEvent=!1}runTask(e){this._handleLayerViewChanges(e),this._frameTask.processQueue(e),this.renderer.processScaleRangeQueries(this._scaleRangeQueries,e),this._inFrameTask=!0,this._pendingUpdates=0,this._hasPendingUpdates=!1,this._updateAllTilesStatus(e),this._sortTiles(e);const t=!this.view.state.fixedContentCamera;this._mergeAndSplit(e,t),this._updateElevation(e),this._updateElevationSources(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty();const i=this._pendingTilesToUpdate.size>0,r=i&&this._hasPendingGeometryWithoutIndices();if(e.done&&!r||this._updatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&(e.hasProgressed||i&&!r)&&this.requestUpdate(),this.notifyChange("updatingProgressValue"),Le&&this._checkTileInvariant(),!e.hasProgressed)return Ze}_checkTileInvariant(){const e=new Map;this._allTiles.forAll(t=>e.set(t,new Set)),this._allTiles.forAll(t=>{if(ye(t.rendered===t.leaf,` rendered ${t.rendered} != ${t.leaf} leaf`),!t.leaf){const e=e=>0===e.unmergableChildCount&&0===e.maxLevelDeltaNeighborCount,i=t.children.reduce((t,i)=>t+(e(i)?0:1),0);if(ye(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(4)){ye(!t.hasPendingUpdate(1),"Tile can be both split and merge at the same time");for(const e of t.children)ye(e.leaf||e.hasPendingUpdate(4),"Child of tile to merge must also merge")}}for(let i=0;i<4;++i){if(t.rendered){const e=t.renderData?.geometryState.edgePeerNeighbors[i];if(null!=e){{const r=t.level-e.level<=ce;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ce} (edge[${i}])`),ye(r,`tile level delta [${t.level}] vs [${e.level}] > ${ce}`))}ye(t.level-e.level<=ce,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ce,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(Te[i],s);if(null!=a){if(t.leaf&&t.level>=ce){let i=a;for(;t.level-i.level<ce;)i=i.parent;const s=[r,t.lij[1]>>ce,t.lij[2]>>ce];if(!ke(s,i.lij)){const r=e.get(i);ye(!r.has(t),"Cannot already have neighbor"),r.add(t)}}ye(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),ye(t.level-a.level<=ce,`Tile level delta [${t.level}] vs [${a.level}] > ${ce}`)}}}),this._allTiles.forAll(t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);ye(i===r.size,`Tile[${t.lij.toString()}] merge-blocker mismatch: actual ${i} vs ${r.size}`)})}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;let t=!1;const i=new ne(this._allTiles.length);i.pushAll(this._rootTiles);const r=this.snapLevel,s=this._splitLimits,a=this._eyePosRenderSR;this._allTiles.forAll(e=>{e.maxLevelDeltaNeighborCount=0,e.unmergableChildCount=0});const n=this.view.state.contentCamera.viewProjectionMatrix;for(;!i.empty;){const e=i.pop(),l=e.parent,o=l?.hasPendingUpdate(4),h=o?4:e.shouldSplit(s,a,r),d=1===h;e.leaf?dt(e,d):i.pushAll(e.children),o?(e.resetPendingUpdate(1),e.leaf||(e.setPendingUpdate(4),t=!0),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(n)):d?(e.resetPendingUpdate(4),e.leaf&&(e.setPendingUpdate(1),t=!0)):(e.resetPendingUpdate(1)&&e.updateAgentSuspension(),2===h&&e.updateAgents(0),e.leaf||(e.setPendingUpdate(4),e.resetPendingUpdate(1),t=!0))}this._allTilesDirty=t,this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||!this.view.pointsOfInterest?.focus||(Ne(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger?.update(),e.madeProgress())}_markTileToUpdate(e){ve(e.loaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForUpdate(e))}_hasPendingGeometryWithoutIndices(){for(const e of this._pendingTilesToUpdate)if(e.loaded&&e.intersectsClippingArea&&null==e.renderData?.vao?.indexBuffer)return!0;return!1}_updatePendingTileGeometries(){const e=this._pendingTilesToUpdate,t=[];if(e.forEach(e=>{this._canUpdateTileGeometry(e)&&t.push(e)}),0===t.length)return void e.clear();const i=(i,r)=>{!r||!this._canUpdateTileGeometry(r)||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Oe);const r=t.length;for(let s=0;s<r;++s){const r=t[s];ve(r.loaded),ve(r.intersectsClippingArea);const a=r.renderData;if(!a?.geometryState)continue;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=je[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(Pe(t),e=>e.loaded))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(we(Te[t]),t=>!!this._canUpdateTileGeometry(t)&&(ve(e.has(t)||Oe(r,t)<0),i(r,t),!0)),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,Le&&Re&&this.checkAllTilesWaterproofness()}_mergeAndSplit(e,t){if(this.suspended||e.done||!this._allTilesDirty)return;this._allTilesDirty=!1,this.requestUpdate();let i=!1;const r=this.view.state.fixedContentCamera;let s=!1;for(;!e.done;){s=!0;let a=!1;const n=!this._allTiles.some(s=>{if(!i&&!r&&!s.visible)return e.done;let n=s;if(s.hasPendingUpdate(4)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(4);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(4);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(1)){let t=!0;const i=s.level;if(i>=ce){const e=e=>e.leaf||i-e.level<ce;for(let r=0;r<4;++r){const a=s.findNeighborTile(Te[r],e);null!=a&&i-a.level===ce&&(t=!1,Le&&(ve(a.leaf),ve(a.hasPendingUpdate(1))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(1)}return e.done});if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries()),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries(),this._allTilesCreated=!this.allTiles.some(e=>e.hasPendingUpdate(1)||e.hasPendingUpdate(4)&&0===e.unmergableChildCount),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some(t=>(t.resetPendingUpdate(8)&&(this._updateTileGeometryState(t),e.madeProgress()),e.done)),!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries())}_updateElevationSources(e){e.done||this._allTiles.some(t=>(t.needsElevationSourceUpdate()&&(t.updateAgents(0),t.markElevationSourceUpdateRequested(),e.madeProgress()),e.done))}_updateTextures(e){e.done||this._allTiles.some(t=>(this._updateTileTexture(t,e),e.done))}_updateClippingExtent(){this.spatialReference&&(this.updateOverlayParameters(),this.requestRender(1),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){return this.view.qualitySettings.tiledSurface.lodBias-(1-this.view.quality)*ge}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=o(e-this._lodBias,0,t.length-1),r=i-Math.floor(i);return t[Math.floor(i)].scale*(1-r)+t[Math.ceil(i)].scale*r}_removeAllTiles(){this._pendingTilesToUpdate.clear(),this._pendingTilesForElevationUpdateEvent.clear(),null!=this._rootTiles&&(this._rootTiles.forEach(e=>this._purgeTile(e)),this._setRootTiles(null),this.notifyChange("ready")),this._allTiles.clear(),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),this.renderer.visible=!1}_purgeSubtree(e){const t=e.children;t[0]&&(this._purgeTile(t[0]),this._purgeTile(t[1]),this._purgeTile(t[2]),this._purgeTile(t[3]),e.clearChildren())}_purgeTile(e){e.leaf?ut(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(et._tileMemcacheKey,e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){ye(e.leaf,"Tile that is already split should not be split again!"),ye(e.rendered,"Tile marked to split is not rendered"),ut(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),ye(e.rendered,"parent should be rendered"),t.forEach(e=>this._loadTile(e)),t.forEach(e=>this._pendingTilesToUpdate.add(e)),this._unloadTile(e),this._markAllTileNeighborsForUpdate(e),this._emitTileScaleChange(e,e.level+1),this._allTilesDirty=!0,this._shortBatches&&this._updatePendingTileGeometries(),t.forEach(e=>dt(e,e.hasPendingUpdate(1))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){ot.spatialReference=this.spatialReference,ot.extent=e.extent,ot.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",ot)}createTile(e,t,i,r){ye(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.groundExtent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(1),s}get _shortBatches(){return 2!==this.view.state.mode}_mergeTile(e){ye(!e.hasPendingUpdate(1),"_mergeTile sanity check"),ye(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),ye(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),dt(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&e.updateOverlayParameters(this.overlayManager)}_handleLayerViewChanges(e=Ke){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(let s=this.view.allLayerViews.length-1;s>=0;s--){const e=this.view.allLayerViews.items[s];if(i.add(e.uid),Se(e)||Ce(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Ce(e)){const i=this._layerClassFromLayerView(e),s=this.getLayerIndexByUID(i,e.uid);null!=s&&((s<r||null==r)&&(t=!0),r=s)}else this._registerTiledLayerView(e),e.layer.loaded&&(t=!0)}this._basemapLayerViewHandles.forEach((e,r)=>{i.has(r)||(this._unregisterTiledLayerView(r),t=!0)}),t&&this._updateTiledLayers(),this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._evaluateTransparency(),e.madeProgress()}get _isFullyTransparent(){if(this.view.map?.ground?.opacity>0)return!1;for(const e of this.view.allLayerViews.items)if(be(e)&&!$(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((Ee(e)||Ce(e))&&$e(Qe[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return xe(e)?0:1}_registerTiledLayerView(e){const t=[];if((Ee(e)||Ce(e))&&t.push(_(()=>e.layer.blendMode,()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(2)})),!Ce(e)){const i=this._layerClassFromLayerView(e);t.push(_(()=>!e.destroyed&&e.suspended,()=>this._updateTiledLayers())),t.push(_(()=>!e.destroyed&&e.fullOpacity,()=>this._updateTileTextures(2)));const{layer:r}=e;"effectiveScaleRange"in r&&t.push(_(()=>!e.destroyed&&r.effectiveScaleRange,()=>this._restartAllAgents(i))),t.push(e.on("data-changed",()=>{const t=this.getLayerIndexByUID(i,e.uid);null!=t&&this._invalidateLayerData(t,i)}))}this._unregisterTiledLayerView(e.uid),this._basemapLayerViewHandles.set(e.uid,t)}_unregisterTiledLayerView(e){const t=this._basemapLayerViewHandles.get(e);if(t){for(const e of t)e.remove();this._basemapLayerViewHandles.delete(e)}}_updateTiledLayers(){if(!this.tilingScheme||this.view.suspended)return;const e=this.view.allLayerViews,t=[[],[]];let i=null;e.forEach(e=>{if(!e.layer||e.suspended||!Se(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(1===r){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)});for(const r of re){const e=this._layerViews[r],i=t[r];i.reverse();const s=i.length;let a=e.length!==s;const n=new Array(s),l=new Array(e.length);this._layerIndexByUid[r].clear();for(let t=0;t<s;t++){const s=i[t].uid;this._layerIndexByUid[r].set(s,t);const o=e.indexOf(i[t]);n[t]=o,t!==o&&(a=!0),o>-1&&(l[o]=t)}if(a){const e=this._postorderIterator;for(e.reset(this._rootTiles);!e.done;)e.next().modifyLayers(l,n,r);this._layerViews[r]=i,this._restartAllAgents(r),this._updateTilesVisibility(this._rootTiles)}}this.tilingScheme.ensureMaxLod(i)&&(this._viewChangeUpdate(),this.notifyChange("tilingScheme"))}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),0===e&&i.computeElevationBounds()}this._updateRootTileElevationRange()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll(t=>{t.updateAgents(1),1===e?this.renderer.updateTileTexture(t,16):t.updateRenderData(1,e)}),this._evaluateTransparency()}_invalidateLayerData(e,t){null!=this._rootTiles&&(Fe(this._rootTiles,i=>i.removeLayerAgent(e,t)),Fe(this._rootTiles,i=>{i.invalidateLayerData(e,t),i.restartAgents(t)}))}setTileTreeDirty(e){this._allTilesDirty=!0,e&&(this._allTilesCreated=!1)}requestRender(e=1){this.renderer.setNeedsRender(e)}requestUpdate(){1===++this._pendingUpdates&&(this._hasPendingUpdates=!0)}requestTileData(e,t,i,r){const s=this.layerViewByIndex(t,i),a=s.layer;return!a.tilemapCache||fe(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.level,e.lij[1],e.lij[2],{...r,timeout:6e3}).then(()=>--this._asyncWorkItems).catch(t=>{throw--this._asyncWorkItems,c(r),g(t)||this._dataMissing(e,i,s),t}).then(()=>this._frameTask.schedule(()=>this._requestTileData(e,i,s,r),r.signal)))}_requestTileData(e,t,i,r){if(this.destroying)return Promise.resolve();return 0===t?xe(i)?this._requestElevationTileData(e,i,r):Promise.reject():be(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!m(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{g(i)||(l.getLogger(this).error(`Tile ${e.lij.toString()} layer 0/${t.uid} error ${i}`),this._dataMissing(e,0,t),this.requestUpdate())};return t.fetchElevationTile(e,{...Q,...i}).then(e=>this._frameTask.schedule(()=>r(e)),s).finally(()=>--this._asyncWorkItems)}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[0].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",0,e.lij.toString());const s=new Z(e.lij,e.extent,i);e.dataArrived(r,0,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:0});const a=[e],n=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,n),e.computeElevationBounds()}0===n&&this._updateRootTileElevationRange(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{Ue(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer 1/${t.uid} error ${r}`),this._dataMissing(e,1,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule(()=>{this.requestUpdate(),m(i)?Ue(r):this._mapTileDataArrived(e,t,r)},i.signal,s(r)).catch(s(r)),n=(e,t=null)=>this._frameTask.schedule(()=>r(e,t));return t.fetchTile(e.lij,i).then(a,n).finally(()=>--this._asyncWorkItems)}_mapTileDataArrived(e,t,i){const r=this.getLayerIndexByUID(1,t.uid);if(null==r)return Ue(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,1,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:1})}_dataMissing(e,t,i){const r=this.getLayerIndexByUID(t,i.uid);null!=r?(e.dataMissing(r,t),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:t})):l.getLogger(this).warn("TerrainSurface: received data from unknown layer")}get performanceInfo(){const e=this._performanceInfo;return e.numNodes=this._allTiles.length,e.numLeaves=e.numVisible=e.numRendered=e.numLoadedPerLevel.length=e.numRenderedPerLevel.length=0,this._allTiles.forAll(t=>{t.leaf&&e.numLeaves++;const i=t.level;t.renderData&&(e.numLoadedPerLevel[i]=(e.numLoadedPerLevel[i]||0)+1),t.visible&&(e.numVisible++,t.rendered&&(e.numRenderedPerLevel[i]=(e.numRenderedPerLevel[i]||0)+1,e.numRendered++))}),e}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this.tilingScheme?(null==this._usedMemory&&(this._usedMemory=this._recalculateUsedMemory()),this._usedMemory??0):0}_recalculateUsedMemory(){return this.tilingScheme?Math.round(this._allTiles.reduce((e,t)=>e+t.usedMemory,0)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this.getLayerIndexByUID(i,e.uid);return null!=r&&this._allTiles.forAll(e=>t+=e.getUsedMemoryForLayer(i,r)),t}get renderPatchBorders(){return this._renderer.renderPatchBorders}set renderPatchBorders(e){this._renderer.renderPatchBorders=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!Re)return;const e=this._rootTiles;if(null==e)return;const t=e=>e?.renderData?.geometry?.indices?.length>0,i=(e,i)=>{t(e)&&console.error("Tile[",e.lij,"] has geometry although parent[",i.lij,"] has geom")},r=e=>{if(e.intersectsClippingArea)if(e.renderData&&!e.renderData.geometryState&&console.error("Tile[",e.lij,"] has renderData but not geometryState"),e.renderData&&!e.renderData.geometry&&console.error("Tile[",e.lij,"] has renderData but not geometryInfo"),!e.renderData?.geometry||(e.renderData.geometry.indices?.length??0)>0||console.error("Tile[",e.lij,"] has renderData but no indices - geometryInfo: ",e.renderData.geometry),t(e)){e.checkGeometryWaterproofness();for(const t of e.children)i(t,e)}else if(e.leaf)console.error("Tile[",e.lij,"] has no geometry and no children, from root to leaf");else for(const t of e.children)r(t)},s=e=>{const t=e.parent?.visible??!0,i=e.visible;e.computeVisibility();const r=e.visible;if(i!==r&&t&&console.error(" Tile[",e.lij,"] has out of date visibility: ",i," instead of ",r),!e.leaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isGeographic(){return this._isGeographic}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateCarree(){return this._isWebMercatorOnPlateCarree}isEastEndWrap(e){return this._isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this._isGlobal&&0===e[2]}lijEastEnd(e){return 1<<e+(this._isGeographic?1:0)}wrapEastWest(e){const t=this.lijEastEnd(e[0]),i=e[2];if(0<=i&&i<t)return e;if(!this._isGlobal)return null;const r=(i+(i<0?t:0))%t;return[e[0],e[1],r]}enableInternalChecks(e){Me(e)}enableWaterproofnessChecks(e){De(e)}static cleanupTerrainSurface(){nt.prune()}enable(e){e!==this.enabled&&(this._set("enabled",e),e?(this._updateRootTiles(),this.suspended=!1,this.view.elevationProvider.register(0,this)):(this.view.elevationProvider.unregister(this),this.suspended=!0,this._removeAllTiles(),this._setRootTiles(null)),this.notifyChange("ready"))}updateOverlayParameters(){const{overlayManager:e}=this;this.allTiles.forAll(t=>t.updateOverlayParameters(e))}};e([w()],tt.prototype,"_renderer",void 0),e([w({constructOnly:!0})],tt.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],tt.prototype,"view",void 0),e([w({constructOnly:!0})],tt.prototype,"overlayManager",void 0),e([w({constructOnly:!0})],tt.prototype,"terrainTextureCompressionTracker",void 0),e([w()],tt.prototype,"_hasPendingUpdates",void 0),e([w()],tt.prototype,"_asyncWorkItems",void 0),e([w()],tt.prototype,"_allTilesDirty",void 0),e([w()],tt.prototype,"_allTilesSorted",void 0),e([w()],tt.prototype,"allTilesCreated",null),e([w()],tt.prototype,"_allTilesCreated",void 0),e([w()],tt.prototype,"_viewChanged",void 0),e([w({type:Number})],tt.prototype,"heading",void 0),e([w()],tt.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],tt.prototype,"_watchUpdatingTracking",void 0),e([w()],tt.prototype,"_frameTask",void 0),e([w()],tt.prototype,"demResolution",null),e([w({readOnly:!0})],tt.prototype,"snapLevel",null),e([w({readOnly:!0})],tt.prototype,"lodSnappingEnabled",null),e([w({readOnly:!0})],tt.prototype,"userClippingExtent",null),e([w()],tt.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],tt.prototype,"groundExtent",null),e([w({readOnly:!0})],tt.prototype,"fullGroundExtent",null),e([w({readOnly:!0})],tt.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],tt.prototype,"updating",null),e([w({readOnly:!0})],tt.prototype,"readyToRun",null),e([w(K)],tt.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],tt.prototype,"updatingProgressValue",null),e([w()],tt.prototype,"_maxNumUpdating",void 0),e([w()],tt.prototype,"baseOpacity",null),e([w()],tt.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],tt.prototype,"viewingMode",null),e([w()],tt.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],tt.prototype,"ready",null),e([w({readOnly:!0})],tt.prototype,"rootTiles",null),e([w()],tt.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],tt.prototype,"spatialReference",null),e([w({type:t})],tt.prototype,"backgroundColor",null),e([w({value:!1})],tt.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],tt.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],tt.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],tt.prototype,"tilingSchemeLogic",void 0),e([w()],tt.prototype,"wireframe",null),e([w()],tt.prototype,"opaque",null),e([w()],tt.prototype,"invisible",null),e([w({value:!1})],tt.prototype,"suspended",null),e([w()],tt.prototype,"fadeDuration",null),e([w()],tt.prototype,"_xNormalizer",null),e([w()],tt.prototype,"visibleElevationRange",void 0),e([w()],tt.prototype,"_rootTileElevationRange",void 0),e([w()],tt.prototype,"_layerViewsDirty",void 0),e([w()],tt.prototype,"renderPatchBorders",null),e([w()],tt.prototype,"renderingDisabled",null),e([w({readOnly:!0})],tt.prototype,"enabled",void 0),tt=et=e([S("esri.views.3d.terrain.TerrainSurface")],tt);const it=tt,rt=x(),st=new W,at=I(),nt=new u,lt=new te("ground"),ot={spatialReference:null,extent:null,scale:0};function ht(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}function dt(e,t){!e.leaf||e.level<ce||gt(e,e=>{t&&pt(e);const i=ct(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=ct(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}})}function pt(e){if(e.hasPendingUpdate(1))return;let t=e.parent;for(;t?.resetPendingUpdate(4);)t=t.parent;e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1),e.level<ce||gt(e,e=>{pt(e)})}function ut(e){e.level<ce||gt(e,e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,ct(t));)t=t.parent}})}function ct(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function gt(e,t){if(e.level<ce)return;const i=e.level-ce,r=e.lij[1]>>ce,s=e.lij[2]>>ce,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(Te[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{it as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../Color.js";import{filterInPlace as i,difference as r}from"../../../core/arrayUtils.js";import s from"../../../core/CollectionFlattener.js";import{toConst as a}from"../../../core/compilerUtils.js";import{EventedAccessor as n}from"../../../core/Evented.js";import"../../../core/has.js";import l from"../../../core/Logger.js";import{clamp as o}from"../../../core/mathUtils.js";import{destroyMaybe as h}from"../../../core/maybe.js";import{MemCachePool as d}from"../../../core/MemCachePool.js";import p from"../../../core/ObjectPool.js";import u from"../../../core/PooledArray.js";import{throwIfAborted as c,isAbortError as g,isAborted as m}from"../../../core/promiseUtils.js";import{watch as _,syncAndInitial as y,sync as f,initial as T}from"../../../core/reactiveUtils.js";import{getMetersPerUnitForSR as v}from"../../../core/units.js";import{property as w,subclass as S}from"../../../core/accessorSupport/decorators.js";import{exactEquals as C,set as b,copy as E}from"../../../core/libs/gl-matrix-2/math/vec3.js";import{create as x}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{UpdatingHandles as U}from"../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as L,radiusModifier as P}from"../../../geometry/ellipsoidUtils.js";import R from"../../../geometry/SpatialReference.js";import{getProjector as M}from"../../../geometry/projection/projectors.js";import{projectPointToVector as D}from"../../../geometry/projection/projectPointToVector.js";import{projectVectorToVector as j}from"../../../geometry/projection/projectVectorToVector.js";import{create as I,equals as k,intersection as V,intersectsSphere as A}from"../../../geometry/support/aaBoundingRect.js";import{copy as B,create as G}from"../../../geometry/support/frustum.js";import{createSpatialReferenceCyclical as O}from"../../../geometry/support/normalizeUtils.js";import{isPlateCarree as q}from"../../../geometry/support/spatialReferenceUtils.js";import{Sphere as N}from"../../../geometry/support/sphere.js";import{ElevationQueryTileCache as F}from"../../../layers/support/ElevationQueryTileCache.js";import{isBaseLayer as W}from"../../../layers/support/layerUtils.js";import{queueHighPriority as H}from"../../../request/queue.js";import{debugFlags as $}from"../support/debugFlags.js";import{ElevationRange as Q}from"../support/ElevationRange.js";import{ElevationUpdateEvent as z}from"../support/ElevationUpdateEvent.js";import{calculateElevationUpdateExtents as Y}from"../support/elevationUpdateExtentUtils.js";import{toBoundingRect as X}from"../support/extentUtils.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{LayerClasses as ie}from"./LayerClass.js";import{OverlayManager as re}from"./OverlayManager.js";import{PlanarPatch as se}from"./PlanarPatch.js";import{Queue as ae}from"./Queue.js";import{ScaleRangeQueries as ne}from"./ScaleRangeQueries.js";import{SphericalPatch as le}from"./SphericalPatch.js";import{SplitLimits as oe}from"./SplitLimits.js";import{maxRootTiles as he,tooManyRootTilesAfterChangeError as de,tooManyRootTilesForLayerError as pe,maxTileNeighborLevelDelta as ue,maxMemoryLodBias as ce}from"./TerrainConst.js";import{TerrainRenderer as ge}from"./TerrainRenderer.js";import me from"./TerrainSurfacePerformanceInfo.js";import{weakAssert as _e,isVectorTileLayerView as ye,neighborEdgeIndices as fe,internalAssert as Te,oppositeEdge as ve,isSurfaceLayerView as we,isGroupLayerView as Se,isMapTileLayerView as Ce,isBlendableLayerView as be,isElevationLayerView as Ee,releaseTerrainData as xe,enableTerrainInternalChecks as Ue,oppositeCorner as Le,enableWaterproofTests as Pe,enableInternalTerrainChecks as Re,enableTerrainWaterproofChecks as Me,neighborCornerIndices as De}from"./terrainUtils.js";import{Tile as je,lijEquals as Ie}from"./Tile.js";import{printAllocations as ke}from"./TilePerLayerInfo.js";import{sortTiles as Ve,IteratorPreorder as Ae,IteratorPostorder as Be,compareTilesByLij as Ge,hasLoadableSiblings as Oe,sortTilesByPOI as qe,traverseTilesPreorder as Ne}from"./tileUtils.js";import{TilingSchemeLogic as Fe}from"./TilingSchemeLogic.js";import{UpsampleInfo as We}from"./UpsampleInfo.js";import{isCompositeBlendMode as He,blendModeFromString as $e}from"../webgl-engine/core/shaderLibrary/output/BlendOptions.js";import{hasLayerBasedScaleVisibility as Qe}from"../../support/layerViewUtils.js";import{ImmediateTask as ze,TaskPriority as Ye,noBudget as Xe}from"../../support/Scheduler.js";import{TextureCompressionTracker as Ke}from"../../support/TextureCompressionTracker.js";import{Yield as Je}from"../../support/Yield.js";var Ze;let et=class extends n{static{Ze=this}get allTilesCreated(){return this._allTilesCreated}get allTiles(){return a(this._allTiles)}get renderedTiles(){return Ve(i(this._allTiles.toArray(),e=>e.visible&&e.rendered))}get demResolution(){const{_allTiles:e,tilingScheme:t}=this;if(0===e.length)return{min:1,max:1};const i=v(t.spatialReference);let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const a of e){const e=t.resolutionAtLevel(a.level)*i;r=Math.min(r,e),s=Math.max(s,e)}return{min:r,max:s}}constructor(e){super(e),this.terrainTextureCompressionTracker=new Ke,this._iteratorPool=new p(()=>new Ae,e=>e.remove=()=>this._iteratorPool.release(e)),this._postorderIterator=new Be,this._hasPendingUpdates=!1,this._pendingUpdates=0,this._asyncWorkItems=0,this._allTilesDirty=!0,this._allTilesSorted=!0,this._allTilesCreated=!1,this._usedMemory=null,this._performanceInfo=new me,this._viewChanged=!1,this.heading=0,this._inFrameTask=!1,this._viewChangeUpdateDirty=!1,this._eyePosRenderSR=x(),this._eyePosSurfaceSR=x(),this._splitLimits=new oe,this._layerViews=[new Array,new Array],this._layerIndexByUid=[new Map,new Map],this._basemapLayerViewHandles=new Map,this._watchUpdatingTracking=new U,this._frameTask=ze,this._allTiles=new u,this._upsampleInfoPool=new p(()=>new We),this._shouldEmitChangeEvent=!1,this._rootTilesExtent=I(),this.updatingProgress=.5,this._maxNumUpdating=1,this.maxTextureScale=1.2,this._spatialReference=R.WebMercator,this._elevationProjectorCache=new Map,this.visibleElevationRange=new Q(1/0,-1/0),this._rootTileElevationRange=new Q(1/0,-1/0),this._projectorCache=new Map,this._tilingSchemeSpatialReference=null,this._updatingRootTiles=!1,this._pendingTilesForElevationUpdateEvent=new Set,this._pendingTilesToUpdate=new Set,this.totalGeometryUpdates=0,this.totalTileUpdates=0,this._oneBatchPerFrameTask=!0,this._layerViewsDirty=!1,this.unloadedMemory=0,this.ignoresMemoryFactor=!1,this._isWebMercator=!1,this._isWebMercatorOnPlateCarree=!1,this.enabled=!0;const{view:t}=e;this.overlayManager=new re({...e,terrainSurface:this}),this._isGlobal=!t.state?.isLocal,this._isGeographic=this._spatialReference?.isGeographic??!1,this._tileConstructor=this._isGlobal?le:se,this._ellipsoid=L(t.spatialReference),this._renderer=new ge(this.overlayManager.renderer,t.stage,this._allTiles,this.terrainTextureCompressionTracker,t.resourceController.memoryController),Qe()||(this._scaleRangeQueries=new ne)}initialize(){const{view:e}=this,{resourceController:t}=e,{memoryController:i}=t;this._tileCache=new d((e,t)=>i.newCache(e,t),"terrain-tile"),this._upsampleMapCache=i.newCache("terrain-upsample",({tile:e})=>e.unloadMapData()),this._elevationQueryCache=new F(i.newCache("elevation-query"));const r=this.overlayManager;this.addHandles([_(()=>r.renderer.isEmpty,()=>this._evaluateTransparency()),_(()=>this.renderer.visible,e=>this.suspended=!e),_(()=>this.heading,e=>{this._renderer.updateHeading(e),this._updateTileTextures(0)},y),_(()=>({heading:e.camera?.heading,state:e.state?.mode}),({heading:e,state:t})=>{if(null==e)return;if(this.isGlobal&&this.isGeographic||this.isWebMercatorOnPlateCarree)return void(this.heading=90*Math.round(e/90)%360);const i=Math.round(e)%360,r=Math.abs(i-this.heading);(2===t||Math.min(r,360-r)>=30)&&(this.heading=i)})],"overlayManager"),this.addHandles([_(()=>this.baseOpacity,()=>{this._handleLayerViewChanges(),this._updateTileTextures(this._evaluateTransparency()?1:2)},y),_(()=>this.hasCompositeBlendMode,()=>this._updateTileTextures(this._evaluateTransparency()?1:2),y),_(()=>this.backgroundColor,(e,t)=>{e?.equals(t)||(this._handleLayerViewChanges(),this._renderer.updateTileBackground(e))},f),_(()=>this.snapLevel,()=>this._viewChanged=!0,f),_(()=>this.view.pointsOfInterest,e=>{this._renderer.pointsOfInterest=e,this._watchUpdatingTracking.removeAll(),e&&this._watchUpdatingTracking.add(()=>e.focus?.renderLocation,()=>this._allTilesSorted=!1,{equals:C})}),_(()=>$.TERRAIN_TILE_TREE_SHOW_TILES,t=>{t&&!this._treeDebugger?import("../layers/support/TerrainTileTree3DDebugger.js").then(({TerrainTileTree3DDebugger:t})=>{!this._treeDebugger&&$.TERRAIN_TILE_TREE_SHOW_TILES&&(this._treeDebugger=new t({view:e}))}):t||(this._treeDebugger=h(this._treeDebugger))},T)]);const{spatialReference:a}=e;this._extentHelper=te(this.viewingMode,{layers:e.map.allLayers,layerViews:e.allLayerViews,viewSpatialReference:a});const n=new s({getCollections:()=>e.defaultsFromMap?.mapCollections?.map(({layers:e})=>e),getChildrenFunction:e=>e&&"layers"in e?e.layers:null}),l=new Fe({layers:n,extentHelper:this._extentHelper,viewingMode:this.viewingMode,viewSpatialReference:a});this._set("tilingSchemeLogic",l),this._updateTilingScheme();const o=t.scheduler;this._frameTask=o.registerTask(Ye.TERRAIN_SURFACE,this),this.addHandles([_(()=>this._extentHelper.stencilEnabledExtents,e=>this._renderer.setStencilEnabledLayerExtents(e),T),_(()=>this.tilingSchemeLogic.tilingScheme,()=>this._updateTilingScheme(),f),_(()=>this.groundExtent,()=>this._updateRootTiles(),T),e.on("resize",()=>this._viewChangeUpdate()),_(()=>{const t=e.state;return[this._lodBias,this.lodSnappingEnabled,e.quality,t.camera,t.contentCamera,t.fixedContentCamera]},()=>this._viewChangeUpdate(),y),_(()=>e.qualitySettings?.fadeDuration,e=>this._renderer.textureFadingEnabled=e>0,T),_(()=>e.qualitySettings?.physicallyBasedRenderingEnabled,e=>this._renderer.pbrMode=e?5:0,T),_(()=>e.qualitySettings?.tiledSurface.elevationLevelDelta,()=>this._updateAllTileGeometries()),_(()=>this.userClippingExtent,()=>this._updateClippingExtent(),f)]),this.addHandles(e.allLayerViews.on("after-changes",()=>this._layerViewsDirty=!0)),this._layerViewsDirty=!0,this._handleLayerViewChanges(),this._renderer.updateTileBackground(this.backgroundColor)}clearHandles(){this._watchUpdatingTracking?.removeAll(),this.removeAllHandles(),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear()}destroy(){this._frameTask.remove(),this._frameTask=ze,this._watchUpdatingTracking?.destroy(),this._removeAllTiles(),this._set("tilingSchemeLogic",h(this.tilingSchemeLogic)),this._basemapLayerViewHandles.forEach((e,t)=>this._unregisterTiledLayerView(t)),this._basemapLayerViewHandles.clear(),this._set("overlayManager",h(this.overlayManager)),this._tileCache=h(this._tileCache),this._allTiles.prune(),je.prune(),this._treeDebugger=h(this._treeDebugger),this._renderer.destroyed||this._renderer.destroy(),this._renderer=null,this._iteratorPool=h(this._iteratorPool),this._upsampleMapCache=h(this._upsampleMapCache),this._elevationQueryCache=h(this._elevationQueryCache),this._set("view",null),this._extentHelper=h(this._extentHelper),this._upsampleInfoPool=h(this._upsampleInfoPool),ke(),this._layerViews.forEach(e=>e.length=0),this._performanceInfo=null}get renderer(){return this._renderer}get frustum(){return this.view.state.camera.frustum}get snapLevel(){return this.lodSnappingEnabled?this.view.terrainLevel:null}get lodSnappingEnabled(){return this.view.qualitySettings.tiledSurface.reduceTileLevelDifferences}get upsampleInfoPool(){return this._upsampleInfoPool}get upsampleMapCache(){return this._upsampleMapCache}get elevationQueryCache(){return this._elevationQueryCache}get hasStencilEnabledExtents(){return this._extentHelper.stencilEnabledExtents.length>0}get userClippingExtent(){const{spatialReference:e}=this,t=this.view?.clippingArea;if(null==t||null==e)return null;const i=I(),r=X(t,i,e)?i:null,s=this._get("userClippingExtent");return k(r,s)?s:r}get rootTilesExtent(){return this._rootTilesExtent}get groundExtent(){const e=V(this.fullGroundExtent,this.userClippingExtent,I()),t=this._get("groundExtent");return k(e,t)?t:e}get fullGroundExtent(){return null!=this._tilingSchemeExtent?this._tilingSchemeExtent:this._rootTilesExtent}get _tilingSchemeExtent(){return this.tilingSchemeLogic?.extent}get updating(){return this._hasPendingUpdates||(this._maxNumUpdating=1),this.enabled&&!!((this.readyToRun||this._watchUpdatingTracking?.updating||this._asyncWorkItems>0)&&this.ready&&!this.suspended||this.overlayManager?.updating||this.terrainTextureCompressionTracker.compressing)}get readyToRun(){return this.enabled&&(this._hasPendingUpdates||this._viewChanged||this._allTilesDirty||!this._allTilesSorted||this._hasElevationSourceUpdates||this._layerViewsDirty||this._scaleRangeQueries?.updating||this._frameTask.updating)&&this.ready&&!this.suspended}get _hasElevationSourceUpdates(){return this._allTiles.some(e=>e.needsElevationSourceUpdate())}get updatingProgressValue(){return this._maxNumUpdating=Math.max(this._pendingUpdates,this._maxNumUpdating),1-this._pendingUpdates/this._maxNumUpdating}get baseOpacity(){return this.view?.map?.ground?.opacity??1}set baseOpacity(e){this.view.map.ground.opacity=e}get viewingMode(){return this.view.state.viewingMode}get ready(){return!this.enabled||null!=this._rootTiles}get rootTiles(){return this._rootTiles}get spatialReference(){return this.tilingScheme?.spatialReference??null}get backgroundColor(){return this.view?.map?.ground?.surfaceColor}set backgroundColor(e){this.view.map.ground.surfaceColor=e}set slicePlaneEnabled(e){this._renderer.slicePlaneEnabled=e,this._set("slicePlaneEnabled",e),this._evaluateTransparency()}get tilingSchemeLocked(){return this.tilingSchemeLogic?.tilingSchemeLocked??!1}get wireframe(){return this._renderer?.wireframe}set wireframe(e){e!==this._renderer.wireframe&&(this._renderer.wireframe=e,this._updateAllTileGeometries())}get opaque(){return 0===this._renderer.transparency}get invisible(){return 3===this._renderer.transparency}set suspended(e){this._set("suspended",e),this._viewChangeUpdate()}get fadeDuration(){return this.view.qualitySettings.fadeDuration??0}intersect(e,t,i,r){this._renderer.intersectRay(e,t,i,r)}getElevationLevelDelta(e){return e<4?3:this.view.qualitySettings.tiledSurface.elevationLevelDelta}get _xNormalizer(){return O(this._spatialReference)}getElevation(e,t,i,r){const s=this._rootTiles;if(!s?.length||!this.enabled)return null;if(0===s[0].layerInfo[0].length)return null;let a=this._elevationProjectorCache.get(r);if(void 0===a&&(a=M(r,this._spatialReference)??null,this._elevationProjectorCache.set(r,a)),null==a)return l.getLogger(this).error("TerrainSurface.getElevation(): could not project given point to tiling scheme coordinate system"),null;const n=b(it,e,t,i);a(n,0,n,0);return lt(s,this._xNormalizer?.normalize(n[0])??n[0],n[1])}getElevations(e,t,i){const r=this._rootTiles,s=r?r[0].layerInfo[0].length:0;if(r?.length&&0!==s&&this.enabled)for(let a=0;a<t;++a){const t=3*a;i(a,lt(r,e[t],e[t+1]))}else for(let a=0;a<t;++a)i(a,null)}getLayerIndexByUID(e,t){return this._layerIndexByUid[e].get(t)}getScale(e){if(!this.tilingScheme)return null;if(!D(e,it,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getScale(): could not project given point to tiling scheme coordinate system"),null;const t=this._rootTiles;if(null!=t)for(const i of t)if(i?.containsPoint(it)){let e=i;for(;e.children[0]&&!e.rendered;){const t=e.children[0].extent;let i=0;it[0]>t[2]&&(i+=1),it[1]<t[1]&&(i+=2),e=e.children[i]}return this._getLodBiasCorrectedScale(e.level)}return 1/0}_ensureProjector(e){const t=this._projectorCache.get(e);if(t)return t;const i=M(e,this._tilingSchemeSpatialReference)??null;return this._projectorCache.set(e,i),i}getSphereElevationRange(e,t){if(!this.enabled||null==this._rootTiles)return null;const i=this._ensureProjector(t);if(null==i)return l.getLogger(this).error("TerrainSurface.getSphereElevationRange(): could not project given point to tiling scheme coordinate system"),null;rt.copyFrom(e),i(rt.center,0,rt.center,0);const r=new Q,s=this._rootTiles;if(null!=s){const e=[];for(const i of s)e.push(i);let t=0;for(;t<e.length;){const i=e[t];if(++t,!A(i.extent,rt))continue;const s=i.children;if(null==s[0]||i.rendered)r.expandElevationRangeValues(i.elevationBoundsMin,i.elevationBoundsMax);else for(const t of s)e.push(t)}}return r}getRootElevationRange(){return this.enabled&&null!=this._rootTiles?new Q(this._rootTileElevationRange.minElevation,this._rootTileElevationRange.maxElevation):null}getLowerBoundRadius(){const e=(this._ellipsoid.radius+this.visibleElevationRange.minElevation)*P;return Math.min(e,this._ellipsoid.radius)}getSphereScale(e,t){if(!this.tilingScheme)return null;if(!D(e,rt.center,this.spatialReference))return l.getLogger(this).error("TerrainSurface.getSphereScale(): could not project given point to tiling scheme coordinate system"),null;rt.radius=t;let i=null;const r=e=>{if(e&&A(e.extent,rt)){const t=e.children;if(t[0]&&!e.rendered)for(const e of t)r(e);else{const t=this._getLodBiasCorrectedScale(e.level);i=null==i?t:Math.min(i,t)}}},s=this._rootTiles;if(null!=s)for(const a of s)r(a);return i}queryVisibleScaleRange(e,t,i,r){if(!this._scaleRangeQueries)return;const s=t?this.tilingScheme.levelAtScale(t):0,a=i?this.tilingScheme.levelAtScale(i):1/0,n=this._lodBias;this._scaleRangeQueries.queryVisibleLevelRange(e,s+n,a+n,r)}_evaluateTransparency(){const e=this.baseOpacity,t=this.overlayManager.renderer.isEmpty,i=this._renderer.transparency,r=this._isFullyTransparent?t?3:2:e>=1&&!this.hasCompositeBlendMode&&!this._renderer.slicePlaneEnabled?0:1;return this._renderer.transparency=r,i!==r&&(this.notifyChange("opaque"),this.notifyChange("invisible"),!0)}_updateTilingScheme(){const{tilingScheme:e}=this.tilingSchemeLogic;if(!(e!==this.tilingScheme))return;_e(!!e,"tiling scheme cannot be reset to undefined"),this._isGlobal=!this.view?.state?.isLocal,this.tilingScheme&&this._removeAllTiles();const t=e?.spatialReference??R.WebMercator;this._spatialReference=t,this._isWebMercator=!!t?.isWebMercator,this._isWebMercatorOnPlateCarree=this._isWebMercator&&q(this.view?.renderSpatialReference),this._isGeographic=t?.isGeographic??!1,this._set("tilingScheme",e),this._tilingSchemeSpatialReference=this.tilingScheme?.spatialReference,this._projectorCache.clear(),this._updateClippingExtent(),e&&(this._updateTiledLayers(),this._renderer.tileSize=e.pixelSize,this.overlayManager.spatialReference=e.spatialReference,this._updateRootTiles())}static{this._tileMemcacheKey="TerrainTileMemcache"}_acquireTile(e,t,i,r){const s=this._tileCache.pop(Ze._tileMemcacheKey);return s?(s.init(e,t,i,r,this),s):new this._tileConstructor(e,t,i,r,this)}get updatingRootTiles(){return this._updatingRootTiles}_updateRootTiles(){const{groundExtent:e,tilingScheme:t}=this;if(!t)return;if(!this.enabled)return void this._setRootTiles(null);const i=st;let s=t.rootTilesInExtent(e,i,5*he);if(null!=this._rootTiles){if(s.length>he)return void l.getLogger(this).warn(de);const e=this._rootTiles.map(e=>e.lij),t=r(e,s,Ie);if(this._updatingRootTiles=!0,t.removed.length>0||t.added.length>0){const e=this._rootTiles.filter(e=>!(t.removed.findIndex(t=>Ie(t,e.lij))>-1)||(this._purgeTile(e),!1));t.added.forEach(t=>e.push(this._newRootTile(t))),this._setRootTiles(e)}}else this._updatingRootTiles=!0,s.length>he&&(l.getLogger(this).warn(pe),s=t.rootTilesInExtent(e,i,he)),this._setRootTiles(s.map(e=>this._newRootTile(e)));k(i,this._rootTilesExtent)||(this._rootTilesExtent=I(i)),this.renderer.visible=!0,this._viewChangeUpdate(),this.overlayManager.setPlacementDirty(),this.notifyChange("ready"),this._updateAllTileGeometries(),this._updatingRootTiles=!1,this.checkAllTilesWaterproofness()}_updateAllTileGeometries(){const e=this._allTiles.filter(e=>this._canUpdateTileGeometry(e));0!==e.length?(e.sort(Ge),e.forEach(e=>this._renderer.updateTileGeometryState(e)),e.forEach(e=>e.renderData.updateNeighborData()),this._updateTilesGeometries(e),this._pendingTilesToUpdate.clear()):this._pendingTilesToUpdate.clear()}_updateTilesGeometries(e){const t=e.filter(e=>this._canUpdateTileGeometry(e));if(0===t.length)return;const i=this.renderer;for(const r of t)i.updateGeometryIfNeeded(r);for(const r of t)this._pendingTilesForElevationUpdateEvent.add(r)}_canUpdateTileGeometry(e){return e.loaded&&e.intersectsClippingArea&&e.hasGeometryState}_shouldSplit(e){return 1===e.shouldSplit(this._splitLimits,this._eyePosRenderSR,this.snapLevel)}_newRootTile(e){const t=this._acquireTile(0,e[1],e[2],null);return this._shouldSplit(t)&&t.setPendingUpdate(1),this._loadTile(t),this._markTileToUpdate(t),this._updateRootTileElevationRange(),t}_setRootTiles(e){if(this._rootTiles=e,this._allTiles.clear(),null!=e){const t=this._iteratorPool.acquire();for(t.reset(e);!t.done;)this._allTiles.push(t.next());t.remove()}this._renderer.setRootTiles(this._rootTiles),this._updateTilesVisibility(e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_runViewChangeUpdateIfDirty(){this._viewChangeUpdateDirty&&(this._viewChangeUpdateDirty=!1,this._viewChangeUpdate())}_viewChangeUpdate(){this.view&&!this.suspended&&this.tilingScheme&&this.renderer.visible&&(this._inFrameTask?this._viewChangeUpdateDirty=!0:(this._viewChangeUpdateDirty=!1,this._updateViewDependentParameters(),this._updateTilesVisibility(this._rootTiles)))}_updateClippingStatus(e){e.updateClippingStatus(this.groundExtent)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e)}_updateTilesVisibility(e){if(null==e)return;const t=Oe(e),i=this.visibleElevationRange;let r=t?i.minElevation:1/0,s=t?i.maxElevation:-1/0;const a=this.groundExtent,n=this.view.state.contentCamera.viewProjectionMatrix;this.setTileTreeDirty(!1);const l=this._iteratorPool.acquire();for(l.reset(e);!l.done;){const e=l.next();e.updateClippingStatus(a)&&e.resetPendingUpdate(8)&&this._updateTileGeometryState(e),e.computeVisibility(),e.updateScreenDepth(n),e.renderData&&(r=Math.min(e.elevationBoundsMin,r),s=Math.max(e.elevationBoundsMax,s))}l.remove(),this._viewChanged=!0,this._allTilesDirty=!0,this._updatePendingTileGeometries(),isFinite(r)&&isFinite(s)&&(i.minElevation!==r||i.maxElevation!==s)&&(this.visibleElevationRange=new J(r,s))}_updateRootTileElevationRange(){let e=1/0,t=-1/0;const i=this._rootTiles;null!=i&&i.forEach(({elevationBoundsMin:i,elevationBoundsMax:r})=>{e=Math.min(e,i),t=Math.max(t,r)});const r=this._rootTileElevationRange;r.minElevation===e&&r.maxElevation===t||(this._rootTileElevationRange=new J(e,t))}_updateViewDependentParameters(){const{camera:e,contentCamera:t}=this.view.state,i=Math.tan(.5*t.fovX),r=Math.tan(.5*t.fovY),s=this.tilingScheme.pixelSize,a=2**-this._lodBias*e.pixelRatio;this._splitLimits.aboveGround=e.aboveGround,this._splitLimits.fovX=i,this._splitLimits.fovY=r,this._splitLimits.relativeWidthLimit=s/e.width*this.maxTextureScale*a,this._splitLimits.relativeHeightLimit=s/e.height*this.maxTextureScale*a,this._splitLimits.maxLod=this.tilingScheme.getMaxLod(),this._splitLimits.angledSplitBias=this.view.qualitySettings.tiledSurface.angledSplitBias,this.view.state.fixedContentCamera?this._splitLimits.frustum=B(this._splitLimits.frustum??G(),t.frustum):this._splitLimits.frustum=null,E(this._eyePosRenderSR,t.eye),j(e.eye,this.view.renderSpatialReference,this._eyePosSurfaceSR,this.spatialReference)}_updateTileGeometryState(e){e.updateVisibility();const t=this._renderer.updateTileGeometryState(e);e.needsElevationSourceUpdate()&&(e.updateAgents(0),e.markElevationSourceUpdateRequested(),this.requestUpdate()),t&&this._markTileToUpdate(e),this.setMemoryDirty()}_markAllTileNeighborsForUpdate(e){e.forEachLoadedNeighbor(e=>{this._layerViews[1].some(ye)&&e.setPendingUpdate(32),this._pendingTilesToUpdate.add(e)})}_updateTileTexture(e,t){const i=e.resetPendingUpdate(32)?32:!!e.resetPendingUpdate(16)&&16;i&&(this._renderer.updateTileTexture(e,i),this._usedMemory=null,t.madeProgress())}_emitElevationUpdateEventForTiles(){if(!this._shouldEmitChangeEvent)return;const e=this._pendingTilesForElevationUpdateEvent;if(e.size>0){const t=new Float64Array(4*e.size);let i=0;for(const r of e)t.set(r.extent,4*i),++i;e.clear();for(const e of Y(t,this.spatialReference)){const t=new z(this.spatialReference,e,"ground");this.emit("elevation-change",t)}}this._shouldEmitChangeEvent=!1}runTask(e){this._handleLayerViewChanges(e),this._frameTask.processQueue(e),this.renderer.processScaleRangeQueries(this._scaleRangeQueries,e),this._inFrameTask=!0,this._pendingUpdates=0,this._hasPendingUpdates=!1,this._updateAllTilesStatus(e),this._sortTiles(e);const t=!this.view.state.fixedContentCamera;this._mergeAndSplit(e,t),this._updateElevation(e),this._updateElevationSources(e),this._updateTextures(e),t||this._mergeAndSplit(e,!0),this._inFrameTask=!1,this._runViewChangeUpdateIfDirty();const i=this._pendingTilesToUpdate.size>0,r=i&&this._hasPendingGeometryWithoutIndices();if(e.done&&!r||this._updatePendingTileGeometries(),this._emitElevationUpdateEventForTiles(),e.done&&(e.hasProgressed||i&&!r)&&this.requestUpdate(),this.notifyChange("updatingProgressValue"),Ue&&this._checkTileInvariant(),!e.hasProgressed)return Je}_checkTileInvariant(){const e=new Map;this._allTiles.forAll(t=>e.set(t,new Set)),this._allTiles.forAll(t=>{if(_e(t.rendered===t.leaf,` rendered ${t.rendered} != ${t.leaf} leaf`),!t.leaf){const e=e=>0===e.unmergableChildCount&&0===e.maxLevelDeltaNeighborCount,i=t.children.reduce((t,i)=>t+(e(i)?0:1),0);if(_e(t.unmergableChildCount===i,` Tile[${t.lij.toString()}] unmergeable child count mismatch: actual ${t.unmergableChildCount} vs ${i}`),t.hasPendingUpdate(4)){_e(!t.hasPendingUpdate(1),"Tile can be both split and merge at the same time");for(const e of t.children)_e(e.leaf||e.hasPendingUpdate(4),"Child of tile to merge must also merge")}}for(let i=0;i<4;++i){if(t.rendered){const e=t.renderData?.geometryState.edgePeerNeighbors[i];if(null!=e){{const r=t.level-e.level<=ue;r||(console.log(`tile level delta [${t.lij.toString()}] vs [${e.lij.toString()}] > ${ue} (edge[${i}])`),_e(r,`tile level delta [${t.level}] vs [${e.level}] > ${ue}`))}_e(t.level-e.level<=ue,`Max tile lod delta exceeded: [${t.lij.toString()}] vs [${e.lij.toString()}]`)}}const r=t.level-ue,s=e=>e.leaf||e.level===t.level,a=t.findNeighborTile(fe[i],s);if(null!=a){if(t.leaf&&t.level>=ue){let i=a;for(;t.level-i.level<ue;)i=i.parent;const s=[r,t.lij[1]>>ue,t.lij[2]>>ue];if(!Ie(s,i.lij)){const r=e.get(i);_e(!r.has(t),"Cannot already have neighbor"),r.add(t)}}_e(a.rendered||a.level===t.level,"Non-same-level-neighbor of rendered must be rendered"),_e(t.level-a.level<=ue,`Tile level delta [${t.level}] vs [${a.level}] > ${ue}`)}}}),this._allTiles.forAll(t=>{const i=t.maxLevelDeltaNeighborCount,r=e.get(t);_e(i===r.size,`Tile[${t.lij.toString()}] merge-blocker mismatch: actual ${i} vs ${r.size}`)})}_updateAllTilesStatus(e){if(!this._viewChanged||!this._rootTiles||e.done)return;this._viewChanged=!1;let t=!1;const i=new ae(this._allTiles.length);i.pushAll(this._rootTiles);const r=this.snapLevel,s=this._splitLimits,a=this._eyePosRenderSR;this._allTiles.forAll(e=>{e.maxLevelDeltaNeighborCount=0,e.unmergableChildCount=0});const n=this.view.state.contentCamera.viewProjectionMatrix;for(;!i.empty;){const e=i.pop(),l=e.parent,o=l?.hasPendingUpdate(4),h=o?4:e.shouldSplit(s,a,r),d=1===h;e.leaf?ot(e,d):i.pushAll(e.children),o?(e.resetPendingUpdate(1),e.leaf||(e.setPendingUpdate(4),t=!0),this._updateClippingStatus(e),e.updateVisibility(),e.updateScreenDepth(n)):d?(e.resetPendingUpdate(4),e.leaf&&(e.setPendingUpdate(1),t=!0)):(e.resetPendingUpdate(1)&&e.updateAgentSuspension(),2===h&&e.updateAgents(0),e.leaf||(e.setPendingUpdate(4),e.resetPendingUpdate(1),t=!0))}this._allTilesDirty=t,this.requestUpdate(),(this._shortBatches||!this._oneBatchPerFrameTask)&&this._updatePendingTileGeometries(),e.madeProgress()}_sortTiles(e){e.done||this._allTilesSorted||!this.view.pointsOfInterest?.focus||(qe(this._allTiles,this.view.pointsOfInterest.focus.renderLocation),this._allTilesSorted=!0,this._treeDebugger?.update(),e.madeProgress())}_markTileToUpdate(e){Te(e.loaded),e.intersectsClippingArea&&(this._pendingTilesToUpdate.add(e),this._markAllTileNeighborsForUpdate(e))}_hasPendingGeometryWithoutIndices(){for(const e of this._pendingTilesToUpdate)if(e.loaded&&e.intersectsClippingArea&&null==e.renderData?.vao?.indexBuffer)return!0;return!1}_updatePendingTileGeometries(){const e=this._pendingTilesToUpdate,t=[];if(e.forEach(e=>{this._canUpdateTileGeometry(e)&&t.push(e)}),0===t.length)return void e.clear();const i=(i,r)=>{!r||!this._canUpdateTileGeometry(r)||r.level<i.level||e.has(r)||(e.add(r),t.push(r),r.renderData.updateNeighborData())};t.sort(Ge);const r=t.length;for(let s=0;s<r;++s){const r=t[s];Te(r.loaded),Te(r.intersectsClippingArea);const a=r.renderData;if(!a?.geometryState)continue;a.updateNeighborData();const n=a.dirtyEdgeResolutions,l=a.geometryState,o=e=>{const t=De[e];i(r,l.cornerPeerNeighbors[e]?.findCorner(Le(t),e=>e.loaded))};for(let t=0;t<4;++t)if(n&1<<t){const s=a.geometryState.edgePeerNeighbors[t];s&&s?.level>=r.level&&s.forAllSubtreeOnSide(ve(fe[t]),t=>!!this._canUpdateTileGeometry(t)&&(Te(e.has(t)||Ge(r,t)<0),i(r,t),!0)),o((t+1)%4),o(t)}}e.clear(),this._updateTilesGeometries(t),this._shouldEmitChangeEvent=!0,Ue&&Pe&&this.checkAllTilesWaterproofness()}_mergeAndSplit(e,t){if(this.suspended||e.done||!this._allTilesDirty)return;this._allTilesDirty=!1,this.requestUpdate();let i=!1;const r=this.view.state.fixedContentCamera;let s=!1;for(;!e.done;){s=!0;let a=!1;const n=!this._allTiles.some(s=>{if(!i&&!r&&!s.visible)return e.done;let n=s;if(s.hasPendingUpdate(4)){if(!t||s.unmergableChildCount>0)return e.done;for(s.resetPendingUpdate(4);null!=n.parent&&0===n.parent.unmergableChildCount&&n.parent.resetPendingUpdate(4);)n=n.parent;this._mergeTile(n),a=!0,e.madeProgress()}else if(s.resetPendingUpdate(1)){let t=!0;const i=s.level;if(i>=ue){const e=e=>e.leaf||i-e.level<ue;for(let r=0;r<4;++r){const a=s.findNeighborTile(fe[r],e);null!=a&&i-a.level===ue&&(t=!1,Ue&&(Te(a.leaf),Te(a.hasPendingUpdate(1))))}}t?(this._splitTile(s),e.madeProgress(),a=!0):s.setPendingUpdate(1)}return e.done});if(a&&(this._allTilesSorted=!1,this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries()),n){if(!i){i=!0;continue}if(!a)break}else this._allTilesDirty=!0}s?e.madeProgress():this._allTilesDirty=!0,!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries(),this._allTilesCreated=!this.allTiles.some(e=>e.hasPendingUpdate(1)||e.hasPendingUpdate(4)&&0===e.unmergableChildCount),this._sortTiles(e)}_updateElevation(e){e.done||(this._allTiles.some(t=>(t.resetPendingUpdate(8)&&(this._updateTileGeometryState(t),e.madeProgress()),e.done)),!this._oneBatchPerFrameTask&&this._updatePendingTileGeometries())}_updateElevationSources(e){e.done||this._allTiles.some(t=>(t.needsElevationSourceUpdate()&&(t.updateAgents(0),t.markElevationSourceUpdateRequested(),e.madeProgress()),e.done))}_updateTextures(e){e.done||this._allTiles.some(t=>(this._updateTileTexture(t,e),e.done))}_updateClippingExtent(){this.spatialReference&&(this.updateOverlayParameters(),this.requestRender(1),this.overlayManager.setPlacementDirty(),this._updateRootTiles())}get _lodBias(){return this.view.qualitySettings.tiledSurface.lodBias-(1-this.view.quality)*ce}_getLodBiasCorrectedScale(e){const t=this.tilingScheme.levels,i=o(e-this._lodBias,0,t.length-1),r=i-Math.floor(i);return t[Math.floor(i)].scale*(1-r)+t[Math.ceil(i)].scale*r}_removeAllTiles(){this._pendingTilesToUpdate.clear(),this._pendingTilesForElevationUpdateEvent.clear(),null!=this._rootTiles&&(this._rootTiles.forEach(e=>this._purgeTile(e)),this._setRootTiles(null),this.notifyChange("ready")),this._allTiles.clear(),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),this.renderer.visible=!1}_purgeSubtree(e){const t=e.children;t[0]&&(this._purgeTile(t[0]),this._purgeTile(t[1]),this._purgeTile(t[2]),this._purgeTile(t[3]),e.clearChildren())}_purgeTile(e){e.leaf?dt(e):this._purgeSubtree(e),this._allTiles.removeUnordered(e),this._unloadTile(e),e.dispose(),this._tileCache.put(Ze._tileMemcacheKey,e),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles})}_unloadTile(e){this._pendingTilesToUpdate.delete(e),this._pendingTilesForElevationUpdateEvent.delete(e),e.unload()}_splitTile(e){_e(e.leaf,"Tile that is already split should not be split again!"),_e(e.rendered,"Tile marked to split is not rendered"),dt(e);const t=e.createChildren();this._allTiles.pushArray(t),this.notifyChange("demResolution"),this.emit("tiles-changed",{allTiles:this.allTiles}),e.updateAgentSuspension(),_e(e.rendered,"parent should be rendered"),t.forEach(e=>this._loadTile(e)),t.forEach(e=>this._pendingTilesToUpdate.add(e)),this._unloadTile(e),this._markAllTileNeighborsForUpdate(e),this._emitTileScaleChange(e,e.level+1),this._allTilesDirty=!0,this._shortBatches&&this._updatePendingTileGeometries(),t.forEach(e=>ot(e,e.hasPendingUpdate(1))),++this._performanceInfo.numSplit}_emitTileScaleChange(e,t=e.level){nt.spatialReference=this.spatialReference,nt.extent=e.extent,nt.scale=this._getLodBiasCorrectedScale(t),this.emit("scale-change",nt)}createTile(e,t,i,r){_e(!!r,"createTile sanity check");const s=this._acquireTile(e,t,i,r);return s.updateClippingStatus(this.groundExtent),s.updateScreenDepth(this.view.state.contentCamera.viewProjectionMatrix),this._shouldSplit(s)&&s.setPendingUpdate(1),s}get _shortBatches(){return 2!==this.view.state.mode}_mergeTile(e){_e(!e.hasPendingUpdate(1),"_mergeTile sanity check"),_e(!e.leaf,"Cannot merge a leaf"),e.leaf||(this._purgeSubtree(e),_e(!e.renderData,"Merging tile with existing render data?"),this._loadTile(e),this._markTileToUpdate(e),this._emitTileScaleChange(e),this._shortBatches&&this._updatePendingTileGeometries(),ot(e,!1),this._allTilesDirty=!0,++this._performanceInfo.numMerged)}_loadTile(e){e.load(),this.requestUpdate(),this._allTilesDirty=!0,this.overlayManager?.hasOverlays&&e.updateOverlayParameters(this.overlayManager)}_handleLayerViewChanges(e=Xe){if(!this._layerViewsDirty)return;this._layerViewsDirty=!1;let t=!1;const i=new Set;let r=-1;for(let s=this.view.allLayerViews.length-1;s>=0;s--){const e=this.view.allLayerViews.items[s];if(i.add(e.uid),we(e)||Se(e))if(this._basemapLayerViewHandles.has(e.uid)&&!Se(e)){const i=this._layerClassFromLayerView(e),s=this.getLayerIndexByUID(i,e.uid);null!=s&&((s<r||null==r)&&(t=!0),r=s)}else this._registerTiledLayerView(e),e.layer.loaded&&(t=!0)}this._basemapLayerViewHandles.forEach((e,r)=>{i.has(r)||(this._unregisterTiledLayerView(r),t=!0)}),t&&this._updateTiledLayers(),this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._evaluateTransparency(),e.madeProgress()}get _isFullyTransparent(){if(this.view.map?.ground?.opacity>0)return!1;for(const e of this.view.allLayerViews.items)if(Ce(e)&&!W(e.layer)&&0!==e.fullOpacity)return!1;return!0}_hasCompositeBlendMode(){for(const e of this.view.allLayerViews.items)if((be(e)||Se(e))&&He($e[e.layer.blendMode]))return!0;return!1}_layerClassFromLayerView(e){return Ee(e)?0:1}_registerTiledLayerView(e){const t=[];if((be(e)||Se(e))&&t.push(_(()=>e.layer.blendMode,()=>{this.hasCompositeBlendMode=this._hasCompositeBlendMode(),this._updateTileTextures(2)})),!Se(e)){const i=this._layerClassFromLayerView(e);t.push(_(()=>!e.destroyed&&e.suspended,()=>this._updateTiledLayers())),t.push(_(()=>!e.destroyed&&e.fullOpacity,()=>this._updateTileTextures(2)));const{layer:r}=e;"effectiveScaleRange"in r&&t.push(_(()=>!e.destroyed&&r.effectiveScaleRange,()=>this._restartAllAgents(i))),t.push(e.on("data-changed",()=>{const t=this.getLayerIndexByUID(i,e.uid);null!=t&&this._invalidateLayerData(t,i)}))}this._unregisterTiledLayerView(e.uid),this._basemapLayerViewHandles.set(e.uid,t)}_unregisterTiledLayerView(e){const t=this._basemapLayerViewHandles.get(e);if(t){for(const e of t)e.remove();this._basemapLayerViewHandles.delete(e)}}_updateTiledLayers(){if(!this.tilingScheme||this.view.suspended)return;const e=this.view.allLayerViews,t=[[],[]];let i=null;e.forEach(e=>{if(!e.layer||e.suspended||!we(e)||!e.fullExtent)return;const r=this._layerClassFromLayerView(e);if(1===r){const t=e.displayLevelRange.maxLevel;t!==1/0&&(null===i||t>i)&&(i=t)}t[r].push(e)});for(const r of ie){const e=this._layerViews[r],i=t[r];i.reverse();const s=i.length;let a=e.length!==s;const n=new Array(s),l=new Array(e.length);this._layerIndexByUid[r].clear();for(let t=0;t<s;t++){const s=i[t].uid;this._layerIndexByUid[r].set(s,t);const o=e.indexOf(i[t]);n[t]=o,t!==o&&(a=!0),o>-1&&(l[o]=t)}if(a){const e=this._postorderIterator;for(e.reset(this._rootTiles);!e.done;)e.next().modifyLayers(l,n,r);this._layerViews[r]=i,this._restartAllAgents(r),this._updateTilesVisibility(this._rootTiles)}}this.tilingScheme.ensureMaxLod(i)&&(this._viewChangeUpdate(),this.notifyChange("tilingScheme"))}_restartAllAgents(e){const t=this._postorderIterator;for(t.reset(this._rootTiles);!t.done;){const i=t.next();i.restartAgents(e),0===e&&i.computeElevationBounds()}this._updateRootTileElevationRange()}layerViewByIndex(e,t){return this._layerViews[t][e]}numLayers(e){return this._layerViews[e].length}_updateTileTextures(e){this._allTiles.forAll(t=>{t.updateAgents(1),1===e?this.renderer.updateTileTexture(t,16):t.updateRenderData(1,e)}),this._evaluateTransparency()}_invalidateLayerData(e,t){null!=this._rootTiles&&(Ne(this._rootTiles,i=>i.removeLayerAgent(e,t)),Ne(this._rootTiles,i=>{i.invalidateLayerData(e,t),i.restartAgents(t)}))}setTileTreeDirty(e){this._allTilesDirty=!0,e&&(this._allTilesCreated=!1)}requestRender(e=1){this.renderer.setNeedsRender(e)}requestUpdate(){1===++this._pendingUpdates&&(this._hasPendingUpdates=!0)}requestTileData(e,t,i,r){const s=this.layerViewByIndex(t,i),a=s.layer;return!a.tilemapCache||ye(s)?this._requestTileData(e,i,s,r):(++this._asyncWorkItems,a.tilemapCache.fetchAvailability(e.level,e.lij[1],e.lij[2],{...r,timeout:6e3}).then(()=>--this._asyncWorkItems).catch(t=>{throw--this._asyncWorkItems,c(r),g(t)||this._dataMissing(e,i,s),t}).then(()=>this._frameTask.schedule(()=>this._requestTileData(e,i,s,r),r.signal)))}_requestTileData(e,t,i,r){if(this.destroying)return Promise.resolve();return 0===t?Ee(i)?this._requestElevationTileData(e,i,r):Promise.reject():Ce(i)?this._requestMapTileData(e,i,r):Promise.reject()}_requestElevationTileData(e,t,i){++this._asyncWorkItems;const r=r=>{!m(i)&&r&&(this.setMemoryDirty(),this.requestUpdate(),this._elevationDataArrived(e,t,r))},s=i=>{g(i)||(l.getLogger(this).error(`Tile ${e.lij.toString()} layer 0/${t.uid} error ${i}`),this._dataMissing(e,0,t),this.requestUpdate())};return t.fetchElevationTile(e,{...H,...i}).then(e=>this._frameTask.schedule(()=>r(e)),s).finally(()=>--this._asyncWorkItems)}_elevationDataArrived(e,t,i){const r=this._layerIndexByUid[0].get(t.uid);if(null==r)return void l.getLogger(this).warn("TerrainSurface: received data from unknown layer %d %s",0,e.lij.toString());const s=new Z(e.lij,e.extent,i);e.dataArrived(r,0,s),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:0});const a=[e],n=e.level,o=this._iteratorPool.acquire();for(o.reset(a);!o.done;){const e=o.next();e.findElevationBoundsForLayer(r,n),e.computeElevationBounds()}0===n&&this._updateRootTileElevationRange(),o.remove(),this._updateTilesVisibility(a)}_requestMapTileData(e,t,i){++this._asyncWorkItems;const r=(r,s)=>{xe(s),m(i)||(console.error(`Tile ${e.lij.toString()} layer 1/${t.uid} error ${r}`),this._dataMissing(e,1,t),this.requestUpdate())},s=e=>t=>r(t,e),a=r=>this._frameTask.schedule(()=>{this.requestUpdate(),m(i)?xe(r):this._mapTileDataArrived(e,t,r)},i.signal,s(r)).catch(s(r)),n=(e,t=null)=>this._frameTask.schedule(()=>r(e,t));return t.fetchTile(e.lij,i).then(a,n).finally(()=>--this._asyncWorkItems)}_mapTileDataArrived(e,t,i){const r=this.getLayerIndexByUID(1,t.uid);if(null==r)return xe(i),void l.getLogger(this).warn("TerrainSurface: received data from unknown layer");e.dataArrived(r,1,i),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:1})}_dataMissing(e,t,i){const r=this.getLayerIndexByUID(t,i.uid);null!=r?(e.dataMissing(r,t),this.emit("tile-data-changed",{tile:e,layerIndex:r,layerClass:t})):l.getLogger(this).warn("TerrainSurface: received data from unknown layer")}get performanceInfo(){const e=this._performanceInfo;return e.numNodes=this._allTiles.length,e.numLeaves=e.numVisible=e.numRendered=e.numLoadedPerLevel.length=e.numRenderedPerLevel.length=0,this._allTiles.forAll(t=>{t.leaf&&e.numLeaves++;const i=t.level;t.renderData&&(e.numLoadedPerLevel[i]=(e.numLoadedPerLevel[i]||0)+1),t.visible&&(e.numVisible++,t.rendered&&(e.numRenderedPerLevel[i]=(e.numRenderedPerLevel[i]||0)+1,e.numRendered++))}),e}setMemoryDirty(){this._usedMemory=null}get usedMemory(){return this.tilingScheme?(null==this._usedMemory&&(this._usedMemory=this._recalculateUsedMemory()),this._usedMemory??0):0}_recalculateUsedMemory(){return this.tilingScheme?Math.round(this._allTiles.reduce((e,t)=>e+t.usedMemory,0)):null}getUsedMemoryForLayerView(e){let t=0;const i=this._layerClassFromLayerView(e),r=this.getLayerIndexByUID(i,e.uid);return null!=r&&this._allTiles.forAll(e=>t+=e.getUsedMemoryForLayer(i,r)),t}get renderPatchBorders(){return this._renderer.renderPatchBorders}set renderPatchBorders(e){this._renderer.renderPatchBorders=e}get renderingDisabled(){return this._renderer.renderingDisabled}set renderingDisabled(e){this._renderer.renderingDisabled=e}get test(){}checkAllTilesWaterproofness(){if(!Pe)return;const e=this._rootTiles;if(null==e)return;const t=e=>e?.renderData?.geometry?.indices?.length>0,i=(e,i)=>{t(e)&&console.error("Tile[",e.lij,"] has geometry although parent[",i.lij,"] has geom")},r=e=>{if(e.intersectsClippingArea)if(e.renderData&&!e.renderData.geometryState&&console.error("Tile[",e.lij,"] has renderData but not geometryState"),e.renderData&&!e.renderData.geometry&&console.error("Tile[",e.lij,"] has renderData but not geometryInfo"),!e.renderData?.geometry||(e.renderData.geometry.indices?.length??0)>0||console.error("Tile[",e.lij,"] has renderData but no indices - geometryInfo: ",e.renderData.geometry),t(e)){e.checkGeometryWaterproofness();for(const t of e.children)i(t,e)}else if(e.leaf)console.error("Tile[",e.lij,"] has no geometry and no children, from root to leaf");else for(const t of e.children)r(t)},s=e=>{const t=e.parent?.visible??!0,i=e.visible;e.computeVisibility();const r=e.visible;if(i!==r&&t&&console.error(" Tile[",e.lij,"] has out of date visibility: ",i," instead of ",r),!e.leaf)for(const a of e.children)s(a)};for(const a of e)r(a),s(a)}get isGlobal(){return this._isGlobal}get isGeographic(){return this._isGeographic}get isWebMercator(){return this._isWebMercator}get isWebMercatorOnPlateCarree(){return this._isWebMercatorOnPlateCarree}isEastEndWrap(e){return this._isGlobal&&e[2]===this.lijEastEnd(e[0])-1}isWestEndWrap(e){return this._isGlobal&&0===e[2]}lijEastEnd(e){return 1<<e+(this._isGeographic?1:0)}wrapEastWest(e){const t=this.lijEastEnd(e[0]),i=e[2];if(0<=i&&i<t)return e;if(!this._isGlobal)return null;const r=(i+(i<0?t:0))%t;return[e[0],e[1],r]}enableInternalChecks(e){Re(e)}enableWaterproofnessChecks(e){Me(e)}static cleanupTerrainSurface(){at.prune()}enable(e){e!==this.enabled&&(this._set("enabled",e),e?(this._updateRootTiles(),this.suspended=!1,this.view.elevationProvider.register(0,this)):(this.view.elevationProvider.unregister(this),this.suspended=!0,this._removeAllTiles(),this._setRootTiles(null)),this.notifyChange("ready"))}updateOverlayParameters(){const{overlayManager:e}=this;this.allTiles.forAll(t=>t.updateOverlayParameters(e))}};e([w()],et.prototype,"_renderer",void 0),e([w({constructOnly:!0})],et.prototype,"_scaleRangeQueries",void 0),e([w({constructOnly:!0})],et.prototype,"view",void 0),e([w({constructOnly:!0})],et.prototype,"overlayManager",void 0),e([w({constructOnly:!0})],et.prototype,"terrainTextureCompressionTracker",void 0),e([w()],et.prototype,"_hasPendingUpdates",void 0),e([w()],et.prototype,"_asyncWorkItems",void 0),e([w()],et.prototype,"_allTilesDirty",void 0),e([w()],et.prototype,"_allTilesSorted",void 0),e([w()],et.prototype,"allTilesCreated",null),e([w()],et.prototype,"_allTilesCreated",void 0),e([w()],et.prototype,"_viewChanged",void 0),e([w({type:Number})],et.prototype,"heading",void 0),e([w()],et.prototype,"_splitLimits",void 0),e([w({readOnly:!0})],et.prototype,"_watchUpdatingTracking",void 0),e([w()],et.prototype,"_frameTask",void 0),e([w()],et.prototype,"demResolution",null),e([w({readOnly:!0})],et.prototype,"snapLevel",null),e([w({readOnly:!0})],et.prototype,"lodSnappingEnabled",null),e([w({readOnly:!0})],et.prototype,"userClippingExtent",null),e([w()],et.prototype,"_rootTilesExtent",void 0),e([w({readOnly:!0})],et.prototype,"groundExtent",null),e([w({readOnly:!0})],et.prototype,"fullGroundExtent",null),e([w({readOnly:!0})],et.prototype,"_tilingSchemeExtent",null),e([w({readOnly:!0})],et.prototype,"updating",null),e([w({readOnly:!0})],et.prototype,"readyToRun",null),e([w(K)],et.prototype,"updatingProgress",void 0),e([w({readOnly:!0})],et.prototype,"updatingProgressValue",null),e([w()],et.prototype,"_maxNumUpdating",void 0),e([w()],et.prototype,"baseOpacity",null),e([w()],et.prototype,"hasCompositeBlendMode",void 0),e([w({readOnly:!0})],et.prototype,"viewingMode",null),e([w()],et.prototype,"maxTextureScale",void 0),e([w({readOnly:!0})],et.prototype,"ready",null),e([w({readOnly:!0})],et.prototype,"rootTiles",null),e([w()],et.prototype,"_rootTiles",void 0),e([w({readOnly:!0})],et.prototype,"spatialReference",null),e([w({type:t})],et.prototype,"backgroundColor",null),e([w({value:!1})],et.prototype,"slicePlaneEnabled",null),e([w({readOnly:!0})],et.prototype,"tilingScheme",void 0),e([w({readOnly:!0})],et.prototype,"tilingSchemeLocked",null),e([w({readOnly:!0})],et.prototype,"tilingSchemeLogic",void 0),e([w()],et.prototype,"wireframe",null),e([w()],et.prototype,"opaque",null),e([w()],et.prototype,"invisible",null),e([w({value:!1})],et.prototype,"suspended",null),e([w()],et.prototype,"fadeDuration",null),e([w()],et.prototype,"_xNormalizer",null),e([w()],et.prototype,"visibleElevationRange",void 0),e([w()],et.prototype,"_rootTileElevationRange",void 0),e([w()],et.prototype,"_layerViewsDirty",void 0),e([w()],et.prototype,"renderPatchBorders",null),e([w()],et.prototype,"renderingDisabled",null),e([w({readOnly:!0})],et.prototype,"enabled",void 0),et=Ze=e([S("esri.views.3d.terrain.TerrainSurface")],et);const tt=et,it=x(),rt=new N,st=I(),at=new u,nt={spatialReference:null,extent:null,scale:0};function lt(e,t,i){for(const r of e){if(!r.containsPointXY(t,i))continue;let e=r;for(;e&&!e.renderData;){const r=(t>e.extentMidX?1:0)+(i<e.extentMidY?2:0);e=e.children[r]}const s=e?.renderData?.geometryState.samplerData??null;return ee(t,i,s)}return null}function ot(e,t){!e.leaf||e.level<ue||ut(e,e=>{t&&ht(e);const i=pt(e);if(e.maxLevelDeltaNeighborCount++,i){let t=e.parent;for(;t;){const e=pt(t);if(t.unmergableChildCount++,!e)break;t=t.parent}}})}function ht(e){if(e.hasPendingUpdate(1))return;let t=e.parent;for(;t?.resetPendingUpdate(4);)t=t.parent;e.resetPendingUpdate(4),e.leaf&&e.setPendingUpdate(1),e.level<ue||ut(e,e=>{ht(e)})}function dt(e){e.level<ue||ut(e,e=>{if(e.maxLevelDeltaNeighborCount--,0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount){let t=e.parent;for(;t&&(t.unmergableChildCount--,pt(t));)t=t.parent}})}function pt(e){return 0===e.maxLevelDeltaNeighborCount&&0===e.unmergableChildCount}function ut(e,t){if(e.level<ue)return;const i=e.level-ue,r=e.lij[1]>>ue,s=e.lij[2]>>ue,a=e=>e.leaf||e.level===i;for(let n=0;n<4;++n){const l=e.findNeighborTile(fe[n],a);if(!l||l.level!==i)continue;const o=l.lij;o[1]===r&&o[2]===s||t(l)}}export{tt as default};