@arcgis/core 4.27.2 → 4.27.4

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.
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.27/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import i from"../../../Graphic.js";import{isSome as s,removeUnordered as r}from"../../../core/arrayUtils.js";import{ByteSizeUnit as o}from"../../../core/ByteSizeUnit.js";import a from"../../../core/Collection.js";import has from"../../../core/has.js";import n from"../../../core/Logger.js";import{someMap as l}from"../../../core/MapUtils.js";import{destroyMaybe as d,applySome as h}from"../../../core/maybe.js";import c from"../../../core/PooledArray.js";import{isAbortError as u,throwIfAborted as _,createResolver as m}from"../../../core/promiseUtils.js";import{initial as g,watch as p}from"../../../core/reactiveUtils.js";import{schedule as f}from"../../../core/scheduling.js";import{isArrayBuffer as b}from"../../../core/typedArrayUtil.js";import{getMetersPerVerticalUnitForSR as y}from"../../../core/unitUtils.js";import{property as v}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as I}from"../../../core/accessorSupport/decorators/subclass.js";import{f as M}from"../../../chunks/mat3.js";import{c as C}from"../../../chunks/mat3f64.js";import{m as O,B as x}from"../../../chunks/mat4.js";import{b as E,c as j}from"../../../chunks/mat4f64.js";import{f as w}from"../../../chunks/quatf64.js";import{m as S,s as A,a as T,t as D,c as R,g as N,b as F}from"../../../chunks/vec3.js";import{c as V}from"../../../chunks/vec3f64.js";import{s as P}from"../../../chunks/vec4.js";import{f as H}from"../../../chunks/vec4f64.js";import{getReferenceEllipsoid as U}from"../../../geometry/ellipsoidUtils.js";import{projectBuffer as G,getProjectorName as L,localLinearScaleFactors as k,projectVectorToVector as B,projectBoundingSphere as q}from"../../../geometry/projection.js";import{create as z,empty as K,expandWithBuffer as W,toRect as $}from"../../../geometry/support/aaBoundingBox.js";import{create as Q,intersects as X}from"../../../geometry/support/aaBoundingRect.js";import{newDoubleArray as Y}from"../../../geometry/support/DoubleArray.js";import{compactFloatArray as J}from"../../../geometry/support/FloatArray.js";import{compactIndices as Z}from"../../../geometry/support/Indices.js";import{f as ee}from"../../../chunks/sphere.js";import{newUByteArray as te}from"../../../geometry/support/UByteArray.js";import{fallbackObjectIDAttribute as ie}from"../../../layers/LayerConstants.js";import se from"../../../layers/graphics/controllers/I3SOnDemandController.js";import{fixFields as re}from"../../../layers/support/fieldUtils.js";import oe from"../../../layers/support/SceneModification.js";import{getColor as ae,getOpacity as ne}from"../../../renderers/visualVariables/support/visualVariableUtils.js";import{loadArcade as le}from"../../../support/arcadeOnDemand.js";import de from"../../../symbols/Symbol3D.js";import{getMetersPerUnit as he}from"../../../symbols/support/unitConversionUtils.js";import ce from"./I3SMeshViewLabeler.js";import{I3SMeshWorkerHandle as ue,toWasmModification as _e}from"./I3SMeshWorkerHandle.js";import{ForAllFeaturesReturnType as me,ForAllFeaturesMode as ge}from"./II3SMeshView3D.js";import{initialize as pe,setModificationsSync as fe,filterObbsForModificationsSync as be,interpretObbModificationResults as ye}from"./SceneLayerWorker.js";import{overrideColor as ve}from"./graphics/graphicUtils.js";import{areLabelsVisible as Ie}from"./graphics/Labeler.js";import{TextureUsage as Me,TextureEncoding as Ce}from"./i3s/enums.js";import Oe from"./i3s/Highlights.js";import{I3SAsyncElevationUpdater as xe}from"./i3s/I3SAsyncElevationUpdater.js";import{I3SCrossfadeHelper as Ee,NodeCrossfadeMetaData as je}from"./i3s/I3SCrossfadeHelper.js";import we from"./i3s/I3SElevationProvider.js";import{boundingBoxCornerPoints as Se}from"./i3s/I3SGeometryUtil.js";import{I3SIntersectionHandler as Ae}from"./i3s/I3SIntersectionHandler.js";import{getSupportedEncodings as Te,selectEncoding as De,defaultMaterial as Re,createTexture as Ne,configureMaterial as Fe}from"./i3s/I3SMaterialUtil.js";import{NodeIMModificationImpact as Ve,NodeState as Pe}from"./i3s/I3SNode.js";import{I3SOverrides as He}from"./i3s/I3SOverrides.js";import{computeGlobalTransformation as Ue,getLocalOrigin as Ge}from"./i3s/I3SProjectionUtil.js";import{rendererNeedsTextures as Le,checkSceneLayerValid as ke,checkSceneLayerCompatibleWithView as Be,getCacheKeySuffix as qe,whenGraphicAttributes as ze,computeVisibilityObb as Ke,filterInPlace as We,getCachedAttributeValue as $e,intersectBoundingRectWithMbs as Qe,MbsIntersectResult as Xe,addWraparound as Ye,getSymbolInfo as Je,transparentEdgeMaterial as Ze,getClipRect as et}from"./i3s/I3SUtil.js";import{IDBCache as tt}from"./i3s/IDBCache.js";import{IDBMockCache as it}from"./i3s/IDBMockCache.js";import{attributeLookup as st}from"./support/attributeUtils.js";import{ColorMixModeEnum as rt}from"./support/symbolColorUtils.js";import ot from"../support/debugFlags.js";import{toBoundingRect as at}from"../support/extentUtils.js";import{create as nt,intersectSphere as lt,clone as dt}from"../support/orientedBoundingBox.js";import{updatingProgress as ht}from"../support/updatingProperties.js";import{glLayout as ct}from"../support/buffer/glUtil.js";import{State as ut}from"../webgl-engine/collections/Component/ComponentObject.js";import{createVertexBufferLayout as _t}from"../webgl-engine/collections/Component/SourceGeometry.js";import{TextureCoordinateAttributeType as mt}from"../webgl-engine/core/shaderLibrary/attributes/TextureCoordinateAttribute.glsl.js";import{loadBasis as gt}from"../webgl-engine/lib/BasisUtil.js";import{Transparency as pt}from"../webgl-engine/lib/edgeRendering/interfaces.js";const ft="esri.views.3d.layers.I3SMeshView3D",bt=n.getLogger(ft),yt=[1,1,1,1];class vt extends je{constructor(e,t,i,s,r,o,a,n,l){super(),this.node=e,this.featureIds=t,this.objectHandle=i,this.cachedRendererVersion=s,this.attributeInfo=r,this.material=o,this.textures=a,this.anchorIds=n,this.anchors=l,this.cachedElevationAnchors=null,this.cachedEdgeMaterials=new Array,this.edgeMemoryUsage=0}}var It;!function(e){e[e.CastShadows=4]="CastShadows",e[e.Pickable=5]="Pickable"}(It||(It={}));const Mt=23,Ct=100*o.MEGABYTES,Ot=t=>{let o=class extends t{constructor(...e){super(e),this._nodeId2Meta=new Map,this._nodeId2MetaReloading=new Map,this._i3sWasmLoaded=!1,this._snappingSourcesTrackers=[],this._hasLoadedPBRTextures=!1,this._asyncModuleLoading=0,this._addTasks=new Map,this._currentRenderer=null,this._rendererVersion=0,this._colorVariable=null,this._opacityVariable=null,this._rendererFields=null,this._symbologyFields=null,this._symbologyOverride=null,this._symbologyOverrideFields=null,this._symbolInfos=new Map,this._visibleGeometryChangedSchedulerHandle=null,this._idbCache=has("enable-feature:idb-mock-cache")?new it:new tt("esri-scenelayer-cache","geometries"),this._hasComponentData=!1,this._hasVertexColors=!1,this.updating=!0,this.holeFilling="auto",this._hasColors=!1,this._hasTextures=!1,this._hasData=!1,this.slicePlaneEnabled=!1,this._modifications=new Array,this.ignoresMemoryFactor=!1,this._layerUrl="",this._cacheKeySuffix=null,this._elevationTask=null,this._filters=[],this._arcade=null,this._tmpAttributeOnlyGraphic=new i(null,null,{}),this._crossfadeHelper=new Ee(this)}get lodCrossfadeoutDuration(){return 0}get lodCrossfadeinDuration(){return 0}get lodCrossfadeUncoveredDuration(){return 0}get layerUid(){return this.i3slayer&&this.i3slayer.uid}get sublayerUid(){return null}get layerId(){return this.i3slayer&&this.i3slayer.id}get sublayerId(){return null}get contentVisible(){return!this.suspended&&this._controller?.rootNodeVisible}get legendEnabled(){return this.contentVisible&&!0===this.i3slayer?.legendEnabled}get updatingProgressValue(){return this._controller?.updatingProgress??0}get hasTexturesOrVertexColors(){return this._hasData?this._hasTextures||this._hasColors?"yes":"probably-not":"unknown"}get rendererTextureUsage(){return Le(this._currentRenderer)?this._usePBR||this._hasLoadedPBRTextures?Me.AllTexturesPBR:Me.AllTextures:this._usePBR||this._hasLoadedPBRTextures?Me.GeometryTexturesPBR:Me.GeometryTextures}get elevationOffset(){const e=null!=this.i3slayer?this.i3slayer.elevationInfo:null;if(null!=e&&"absolute-height"===e.mode){const t=y(this.i3slayer.spatialReference),i=he(e.unit);return(e.offset??0)*i/t}return 0}get elevationInfo(){const e=null!=this.i3slayer?this.i3slayer.elevationInfo:null;if(null==e)return{mode:kt.Absolute,offset:0};const t=y(this.i3slayer.spatialReference),i=he(e.unit),s=(e.offset??0)*i/t;switch(e.mode){case"absolute-height":return{mode:kt.Absolute,offset:s};case"relative-to-ground":return{mode:kt.RelativeToGround,offset:s};case"on-the-ground":return{mode:kt.OnTheGround,offset:0};default:return{mode:kt.Absolute,offset:0}}}get supportedTextureEncodings(){return Te(this.view._stage.renderView.capabilities)}get uncompressedTextureDownsamplingEnabled(){const e=this.view?.qualitySettings.sceneService.uncompressedTextureDownsamplingEnabled,t=0==(this.supportedTextureEncodings&Ce.DDS_S3TC);return e&&t}get clientGeometry(){return this.i3sOverrides.geometryOverrides}initialize(){this._preLoadBasis(),this.addResolvingPromise(this.i3slayer.indexInfo);const e=this.view.resourceController,t=e.memoryController;this.i3sOverrides=new He({view:this.view,layer:this.i3slayer,memoryController:t}),this._worker=new ue(Kt(e)),this.addResolvingPromise(this._worker.promise);const i=this.i3slayer.store;this._worker.setLegacySchema(this.uid,i.defaultGeometrySchema),ke(this.i3slayer),Be(this.i3slayer,this.view),this._layerUrl=this.i3slayer.parsedUrl.path,this._controller=new se({layerView:this,worker:this._worker}),this._gpuMemoryEstimate=0,this._texMemoryEstimate=0,this._geoMemoryEstimate=0,this._stage=this.view._stage,this._collection=this._stage.renderView.componentObjectCollection,this.resetHighlights();const s=i.defaultGeometrySchema;if(this._isIntegratedMesh||!s)this._hasComponentData=!1;else{const e=s.featureAttributes;this._hasComponentData=!!(e&&e.faceRange&&e.id)}this._hasVertexColors=null!=(s?.vertexAttributes.color??null)&&(null==this.i3slayer.cachedDrawingInfo||!this.i3slayer.cachedDrawingInfo.color),this._isIntegratedMesh||(this._edgeView=this._stage.renderer.ensureEdgeView());const r=this.view.resourceController.memoryController.newCache(`sl-${this.uid}`,(e=>this._deleteComponentObject(e)));this._memCache=r;const o=e=>null!=this._controller.index&&null!=this._controller.index.rootNode?this._controller.index.traverse(this._controller.index.rootNode,(t=>{const i=t.index,s=this._nodeId2Meta.get(i)||this._nodeId2MetaReloading.get(i);return e(t,null!=s?s.objectHandle:null)})):()=>{};this._intersectionHandler=new Ae({layerUid:this.layerUid,sublayerUid:this.sublayerUid,collection:this._collection,slicePlaneEnabled:this.slicePlaneEnabled,isGround:this._isIntegratedMesh,traverseNodeHierarchy:o}),this.updatingHandles.add((()=>this.layerUid),(e=>this._intersectionHandler.layerUid=e)),this.updatingHandles.add((()=>this.sublayerUid),(e=>this._intersectionHandler.sublayerUid=e)),this._elevationProvider=new we({layerView:this,intersectionHandler:this._intersectionHandler}),this._hasLoadedPBRTextures=this._usePBR,this.updatingHandles.add((()=>this.view.clippingArea),(()=>this._clippingAreaChanged()),g),this.updatingHandles.add((()=>this.fullOpacity),(e=>this._opacityChange(e))),this.updatingHandles.add((()=>this.slicePlaneEnabled),(e=>this._slicePlaneEnabledChange(e))),this.updatingHandles.add((()=>this.elevationOffset),((e,t)=>{this._reloadAll(t),this._controller.invalidateVisibilityObbs()})),this.updatingHandles.add((()=>this.elevationInfo),((e,t)=>this._elevationInfoChanged(e,t)),g),this.updatingHandles.add((()=>this.contentVisible&&this.elevationInfo.mode!==kt.Absolute),((e,t)=>{e?this.handles.add(this.view.basemapTerrain.on("elevation-change",(({extent:e})=>this._ensureElevationTask().addExtent(e))),zt):t&&this.handles.remove(zt)}),g),this.updatingHandles.add((()=>this._usePBR),(e=>this._updatePBR(e)));const a=()=>{this._reloadAll(),this.clearMemCache()};this.updatingHandles.add((()=>this.rendererTextureUsage),a),this.updatingHandles.add((()=>this.uncompressedTextureDownsamplingEnabled),a),this.updatingHandles.add((()=>this.contentVisible),(e=>this._contentVisibleChanged(e)),g),this.updatingHandles.add((()=>this.i3slayer.labelsVisible),(()=>this._labelingChanged()),g),this.updatingHandles.add((()=>this.i3slayer.labelingInfo),(()=>this._labelingChanged()),g),this.updatingHandles.add((()=>this._modifications),(()=>this._modificationsChanged()),g),this.handles.add([p((()=>ot.I3S_TREE_SHOW_TILES),(e=>{if(e&&!this._treeDebugger){const e=this._controller.crsIndex;import("./support/I3STreeDebugger.js").then((({I3STreeDebugger:t})=>{!this._treeDebugger&&ot.I3S_TREE_SHOW_TILES&&(this._treeDebugger=new t({lv:this,view:this.view,nodeSR:e}))}))}else e||ot.I3S_TREE_SHOW_TILES||(this._treeDebugger=d(this._treeDebugger))}),g),p((()=>ot.I3S_SHOW_MODIFICATIONS),(()=>this._showModifications()),g)]),this._cacheKeySuffix=qe(this.i3slayer.spatialReference,this.view.renderSpatialReference),this._idbCache.init().catch((e=>bt.warn(`Failed to initialize IndexedDB cache: ${e}`)))}destroy(){this._clearAddTasks(),this._elevationTask=d(this._elevationTask),this.i3sOverrides=d(this.i3sOverrides),this._elevationProvider&&(this._elevationProvider.layerChanged(),this.view.elevationProvider.unregister(this._elevationProvider),this._elevationProvider=null),this._intersectionHandler&&(this._stage.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler),this._intersectionHandler=null);const e=this._worker;e&&(e.destroyContext(this.uid).then((()=>e.destroy())),this._worker=null),this._removeAllNodeDataFromStage(),this._memCache=d(this._memCache),this._collection=null,this._stage=null,this._edgeView=null,this._labeler=d(this._labeler),this._treeDebugger=d(this._treeDebugger),this._controller=d(this._controller),this._highlights.destroy(),this._nodeId2Meta.clear(),this._nodeId2MetaReloading.clear(),this._crossfadeHelper=d(this._crossfadeHelper),this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle&&(this._visibleGeometryChangedSchedulerHandle.remove(),this._visibleGeometryChangedSchedulerHandle=null)}_memEstimateTextureAdded(e){const t=e.memoryEstimate;return this._gpuMemoryEstimate+=t,this._texMemoryEstimate+=t,t}_memEstimateTextureRemoved(e){if(null!=e){const t=e.memoryEstimate;this._gpuMemoryEstimate-=t,this._texMemoryEstimate-=t}}_memEstimateGeometryAdded(e){const t=this._collection.getObjectGPUMemoryUsage(e);return this._gpuMemoryEstimate+=t,this._geoMemoryEstimate+=t,t}_memEstimateGeometryRemoved(e){const t=this._collection.getObjectGPUMemoryUsage(e);this._gpuMemoryEstimate-=t,this._geoMemoryEstimate-=t}isNodeLoaded(e){return this._nodeId2Meta.has(e)}isNodeReloading(e){return this._nodeId2MetaReloading.has(e)}get usedMemory(){let e=null!=this._labeler?this._labeler.usedMemory:0;return this._nodeId2Meta.forEach((t=>e+=null!=t?t.node.memory:0)),this._nodeId2MetaReloading.forEach((t=>e+=null!=t?t.node.memory:0)),e}get unloadedMemory(){return(null!=this._controller?this._controller.unloadedMemoryEstimate:0)+(null!=this._labeler?this._labeler.unloadedMemoryEstimate:0)}_labelingChanged(){if(!(Ie(this.i3slayer)&&this._supportsLabeling))return void(null!=this._labeler&&(this._labeler.destroy(),this._labeler=null));if(null!=this._labeler)return;const e=new ce({view:this.view,layer:this.i3slayer,collection:this._collection,overrides:this.i3sOverrides});this._nodeId2Meta.forEach((t=>null!=t&&this._addMetaToLabeler(e,t))),this._labeler=e}_loadAsyncModule(e){return++this._asyncModuleLoading,e.then((e=>(--this._asyncModuleLoading,e)),(e=>{throw--this._asyncModuleLoading,e}))}_modificationsChanged(){if(!this._i3sWasmLoaded&&this.hasModifications)return this._i3sWasmLoaded=pe().then((()=>{this._i3sWasmLoaded=!0,this._modificationsChanged(),this.notifyUpdate()})),void this.notifyUpdate();if(!0!==this._i3sWasmLoaded)return;const e=this.uid,t=this.i3slayer.spatialReference;this._worker.setModifications(e,this._layerClippingArea,this._modifications,t);const i=_e(this._layerClippingArea,this._modifications,t);fe({context:e,modifications:i,isGeodetic:t.isGeographic}),this._controller.modificationsChanged();const s=this.hasModifications?new c:null;this._nodeId2Meta.forEach(((e,t)=>{null==e?(this._nodeId2Meta.delete(t),this._controller.updateLoadStatus(t,!1)):e.node.hasModifications?(this._nodeId2Meta.delete(t),this._nodeId2MetaReloading.set(t,e)):null!=s&&s.push(e.node)})),null!=s&&this._nodeId2MetaReloading.forEach((e=>s.push(e.node))),null!=s&&s.length>0&&(this.updateNodeModificationStatus(s),s.forAll((e=>{if(e.imModificationImpact!==Ve.Culled){const t=this._nodeId2Meta.get(e.index);this._controller.invalidateGeometryVisibility(e.index),null!=t?(this._nodeId2Meta.delete(e.index),this._nodeId2MetaReloading.set(e.index,t)):this._nodeId2Meta.has(e.index)&&(this._nodeId2Meta.delete(e.index),this._controller.updateLoadStatus(e.index,!1))}}))),this.clearMemCache(),this._controller.restartNodeLoading(),this._showModifications()}_showModifications(){if(null!=this._modificationGraphics&&(this.view.graphics.removeMany(this._modificationGraphics),this._modificationGraphics=null),!ot.I3S_SHOW_MODIFICATIONS||0===this._modifications.length)return;const e={clip:[227,227,79,.8],mask:[227,139,79,.8],replace:[139,227,79,.8]},t={type:"simple-fill",outline:{color:[255,255,255],width:1}};this._modificationGraphics=new Array;for(const s of this._modifications){const r=s.geometry;r.spatialReference=this.i3slayer.spatialReference;const o={...t,color:e[s.type]};this._modificationGraphics.push(new i({geometry:r,symbol:o}))}this.view.graphics.addMany(this._modificationGraphics)}_addMetaToLabeler(e,t){e.addNodeMeta(t,((e,t)=>this._createAttributes(e,t)))}_contentVisibleChanged(e){e?(this.view.elevationProvider.register(this._elevationContext,this._elevationProvider),this._stage.view.sceneIntersectionHelper.addIntersectionHandler(this._intersectionHandler)):(this._removeAllNodeDataFromStage(),this.view.elevationProvider&&this.view.elevationProvider.unregister(this._elevationProvider),this._stage.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler))}getLoadedAttributes(e){const t=this._nodeId2Meta.get(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.loadedAttributes}getAttributeData(e){const t=this._nodeId2Meta.get(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.attributeData}setAttributeData(e,t){const i=this._nodeId2Meta.get(e);null!=i&&null!=i.attributeInfo&&(i.attributeInfo.attributeData=t,this._attributeValuesChanged(i))}async updateAttributes(e,t,i){const s=this._nodeId2Meta.get(e);null!=s&&(await this.i3sOverrides.applyAttributeOverrides(s.featureIds,t,i),s.attributeInfo=t,this._controller.reschedule((()=>this._attributeValuesChanged(s)),i).catch((e=>{u(e)||bt.warn("Error while updating attribute values. Layer might not display correctly.",e)})))}_attributeValuesChanged(e){e.cachedRendererVersion=this._getInvalidRendererVersion(),e.filteredIds=null,null!=this._labeler&&this._labeler.setNodeMetaAttributes(e,((e,t)=>this._createAttributes(e,t))),this._updateEngineObject(e)}clearMemCache(){null!=this._memCache&&this._memCache.clear()}getVisibleNodes(){const e=new Array;return this._nodeId2Meta.forEach((t=>null!=t&&e.push(t.node))),e}getNodeComponentObb(e){const t=this._nodeId2Meta.get(e.index)??this._nodeId2MetaReloading.get(e.index);return null!=t?this._collection.getComponentObb(t.objectHandle):null}getLoadedNodeIndices(e){this._nodeId2Meta.forEach(((t,i)=>e.push(i))),this._nodeId2MetaReloading.forEach(((t,i)=>e.push(i)))}_preLoadBasis(){!has("disable-feature:i3s-basis")&&0!=(this.supportedTextureEncodings&Ce.Basis)&&h(this.i3slayer.textureSetDefinitions,(e=>e.some((e=>e.formats.some((e=>"basis"===e.format||"ktx2"===e.format))))))&&gt()}_getVertexBufferLayout(e,t){const i={hasTexture:Nt(e.params.material),hasNormals:t.normal,hasRegions:t.uvRegion};return ct(_t(this._getGeometryParameters(i)))}_getObjectIdField(){return this.i3slayer.objectIdField||ie}_getGlobalIdField(){return this.i3slayer.associatedLayer?.globalIdField}_findGraphicNodeAndIndex(e){const t=st(this.i3slayer.fieldsIndex,e.attributes,this._getObjectIdField());let i=null;return l(this._nodeId2Meta,(e=>{if(null==e)return!1;const s=e.featureIds.indexOf(t);return-1!==s&&(i={node:e.node,index:s},!0)})),i}_getGraphicIndices(e,t){const i=this._nodeId2Meta.get(e.index);if(null==i)return[];const s=[],r=this._getObjectIdField(),o=this.i3slayer.fieldsIndex;for(const a of t){const e=st(o,a.attributes,r),t=i.featureIds.indexOf(e);-1!==t&&s.push(t)}return s}whenGraphicBounds(e){const t=this._findGraphicNodeAndIndex(e);if(!t)return Promise.reject();const i=this._getAABB(t.node.index,t.index);return null==i?Promise.reject():Promise.resolve({boundingBox:i,screenSpaceObjects:[]})}getAABBFromIntersectorTarget(e){return null==e.nodeIndex||null==e.componentIndex?null:this._getAABB(e.nodeIndex,e.componentIndex)}_getAABB(e,t){const i=this._nodeId2Meta.get(e);if(null==i||null==i.featureIds||t>=i.featureIds.length)return null;const s=i.objectHandle,r=Se(t,this._collection,s,Y(24),0),o=this.view.renderSpatialReference,a=this.view.spatialReference;if(!G(r,o,0,r,a,0,8))return null;const n=K();return W(n,r,0,8),n}whenGraphicAttributes(e,t){return ze(this.i3slayer,e,this._getObjectIdField(),t,(()=>[...this._nodeId2Meta.values()].filter(s)))}getGraphicFromIntersectorTarget(e){if(null==e.nodeIndex||null==e.componentIndex)return null;const t=this._nodeId2Meta.get(e.nodeIndex);return null==t||null==t.featureIds||e.componentIndex>=t.featureIds.length?null:this._createGraphic(e.componentIndex,t)}_getCacheKey(e){return`${this._layerUrl}/v${Mt}/${e}${this._cacheKeySuffix}`}_getMemCacheKey(e,t=this.elevationOffset){return e+"#"+t}get _idbCacheEnabled(){return!this._controller.disableIDBCache&&!this.hasModifications&&0===this.elevationOffset&&null!=this._cacheKeySuffix}loadCachedGPUData(e){return null!=this._memCache?this._memCache.pop(this._getMemCacheKey(e)):null}deleteCachedGPUData(e){null!=e&&this._deleteComponentObject(e)}_cacheGPUData(e,t=this.elevationOffset){if(null==this._memCache)return void this._deleteComponentObject(e);const i=this._controller.indexDepth-e.node.level;this._memCache.put(this._getMemCacheKey(e.node.index,t),e,e.node.memory,i)}loadMissingTextures(e,t,i,s){const r=e?.filter(((e,i)=>{if(0==(e.usage&this.rendererTextureUsage))return!1;if(null==t)return!0;const s=De(e.encodings,this.supportedTextureEncodings),r=t[i];return!!(null==r||null==r.data||s&&r.encoding!==s.encoding)}))??[];return 0===r.length?Promise.resolve(!1):i(r,s).then((i=>{let s=0;for(let r=0;r<e.length;r++)s<i.length&&i[s].id===e[r].id&&(t[r]=i[s],s++);return!0}))}loadCachedNodeData(e,t,i){return this._idbCacheEnabled?this._idbCache.get(this._getCacheKey(e.id),t).then((s=>null==s?null:s.nodeVersion!==e.version?(this._idbCache.remove(this._getCacheKey(e.id)),null):(this.elevationInfo.mode===kt.Absolute&&(e.geometryObb=s.geometryObb),this.loadMissingTextures(s.requiredTextures,s.textureData,i,t).then((i=>(i&&this._idbCache.initialized&&null!=s.textureData&&(s.byteSize=Pt(s.transformedGeometry,s.textureData),s.textureData.every(Vt)&&Ht(e,s)&&this._idbCache.put(this._getCacheKey(e.id),s).catch((t=>bt.warn(`Failed to update node with textures in IndexedDB cache: ${e.id}: ${t}`)))),_(t),s)))))):Promise.resolve(null)}addNode(e,t,i){return Ft(t)?null==t.geometryBuffer?(this._addNodeMeta(e.index,null),Promise.resolve()):this._addData(e,t.attributeDataInfo,(()=>this._transformNode(e,t,i).then((s=>this._safeReschedule((()=>{if(null==s)return e.hasModifications=!1,this._addCachedNodeData(e,null,i);e.hasModifications=s.transformedGeometry.hasModifications;const{obb:r,componentOffsets:o,featureIds:a,anchorIds:n,anchors:l,transformedGeometry:d}=s,h=this._controller.crsIndex,c=this.view.renderSpatialReference,u=Ue(e.mbs,this.elevationOffset,h,c),_=nt([r.center.x,r.center.y,r.center.z],[r.extents.x,r.extents.y,r.extents.z],w(r.orientation.x,r.orientation.y,r.orientation.z,r.orientation.w));S(_.center,_.center,u),this.elevationInfo.mode===kt.Absolute&&(e.geometryObb=_),t.geometryData.componentOffsets=o,a&&(t.geometryData.featureIds=Array.from(a)),t.geometryData.anchorIds=n,t.geometryData.anchors=l;const m={nodeVersion:e.version,geometryData:t.geometryData,requiredTextures:t.requiredTextures,textureData:t.textureData,transformedGeometry:d,globalTrafo:u,geometryObb:_,byteSize:Pt(d,t.textureData)};if(this._idbCacheEnabled&&this._idbCache.initialized&&Ht(e,m)){const t=null!=m.textureData?m.textureData.map((e=>Vt(e)?e:null)):null;this._idbCache.put(this._getCacheKey(e.id),{...m,textureData:t}).catch((t=>bt.warn(`Failed to store node in IndexedDB cache: ${e.id}: ${t}`)))}return this._addCachedNodeData(e,m,i)}),i))))):Promise.reject()}getElevationRange(e){let t=1/0,i=-1/0;const s=U(this.view.renderCoordsHelper.spatialReference);return this._nodeId2Meta.forEach((r=>{if(null!=r&&null!=r.node.geometryObb){const o=r.node.geometryObb;if(lt(o,e)){const e=this._collection.getObjectTransform(r.objectHandle),o=this.view.renderCoordsHelper.getAltitude(e.position);for(let a=0;a<r.featureIds.length;a++){const e=this._collection.getComponentAabb(r.objectHandle,a,qt);if("local"===this.view.viewingMode)t=Math.min(t,o+e[2]),i=Math.max(i,o+e[5]);else{t=Math.min(t,o+e[2]);const r=Math.max(Math.abs(e[3]),Math.abs(e[0])),a=Math.max(Math.abs(e[4]),Math.abs(e[1])),n=o+e[5]+s.radius;i=Math.max(i,Math.sqrt(r*r+a*a+n*n)-s.radius)}}}}})),{min:t,max:i}}computeVisibilityObb(e){return Ke(e,this.view.renderSpatialReference,this._controller.crsIndex,this.i3slayer.spatialReference,this.elevationOffset,this._modifications)}_transformNode(e,t,i){const s=t.geometryData.geometries??[],r=new Array(s.length);for(let g=0;g<s.length;++g)r[g]=this._getVertexBufferLayout(s[g],t.geometryDescriptor);const o=e.mbs,a=this.elevationOffset,n=this._controller.crsIndex,l=this._controller.crsVertex,d=this.view.renderSpatialReference,h=Ge(o,a,n),c=Ue(o,a,n,d),u=L(n,l),_=L(l,d);if(null==u||null==_)return Promise.resolve(null);const m={context:this.uid,geometryBuffer:t.geometryBuffer,geometryData:t.geometryData,geometryDescriptor:t.geometryDescriptor,layouts:r,localOrigin:h,globalTrafo:c,mbs:o,obb:e.serviceObb,elevationOffset:a,needNormals:!this._isIntegratedMesh&&this._controller.isMeshPyramid,normalReferenceFrame:this.i3slayer.normalReferenceFrame||"none",indexToVertexProjector:u,vertexToRenderProjector:_};return this._worker.invoke(m,i)}get _supportsNodeCrossFading(){return!this.view?._stage?.renderer.shadowsEnabled}get nodeCrossfadingEnabled(){return this._supportsNodeCrossFading&&(this.lodCrossfadeinDuration>0||this.lodCrossfadeoutDuration>0||this.lodCrossfadeUncoveredDuration>0)}get nodeFadeoutEnabled(){return this._supportsNodeCrossFading&&this.lodCrossfadeoutDuration>0}_setNewNodeOpacity(e){const t=this.nodeCrossfadingEnabled?0:this.fullOpacity;this._setNodeOpacity(e,t)}addCachedGPUData(e,t,i){if(this.elevationInfo.mode===kt.Absolute&&(e.geometryObb=dt(this._collection.getComponentObb(t.objectHandle))),!this._controller.isGeometryVisible(e))return void this._cacheGPUData(t);null!=this._labeler&&this._addMetaToLabeler(this._labeler,t);const s=e.index;this._addNodeMeta(s,t),this.updateNodeState(s,i),this._collection.setObjectVisibility(t.objectHandle,ut.Visible),this._updateMaterial(t),this._setNewNodeOpacity(t),this.elevationInfo.mode!==kt.Absolute&&this._ensureElevationTask().schedule(s),this._updateEngineObject(t),this._highlights.objectCreated(t),null!=this._treeDebugger&&this._treeDebugger.update()}addCachedNodeData(e,t,i,s){return this._addData(e,i,(()=>this._addCachedNodeData(e,t,s)))}async deleteCachedNodeData(e){if(this._idbCacheEnabled)return this._idbCache.remove(this._getCacheKey(e))}async _addCachedNodeData(e,t,i){if(!this.contentVisible||!this._controller.isGeometryVisible(e))return void this._removeNodeStageData(e.index,this.elevationOffset,this._nodeId2MetaReloading);if(null==t)return void this._addNodeMeta(e.index,null);const s=this._addTasks.get(e.index),{geometryData:r,transformedGeometry:o,globalTrafo:a}=t;await this.i3sOverrides.applyAttributeOverrides(r.featureIds,s.attributeInfo,i);const n=null!=t.textureData?t.textureData.filter((e=>null!=e&&0!=(e.usage&this.rendererTextureUsage))):[];!has("disable-feature:i3s-basis")&&n.some((e=>null!=e&&(e.encoding===Ce.Basis||e.encoding===Ce.KTX2)))&&await gt(),e.memory=0;const{componentOffsets:l,geometries:d,featureIds:h,anchorIds:c,anchors:u}=r,_=this._collection,m=d[0],{layout:g,indices:p,interleavedVertexData:f,positionData:b,hasColors:y}=o,v=this._materialParameters(m,g),I=l||new Uint32Array([0,p?p.length:f.byteLength/g[0].stride]),w={vertices:{data:f,count:f.byteLength/g[0].stride,layoutParameters:v.geometryParams},positionData:{positions:J(b.data),indices:Z(b.indices)},indices:p,componentOffsets:I},S=m.transformation?E(m.transformation):j();O(S,a,S);const A=x(V(),S),T=M(C(),S),D=this.view.renderSpatialReference,R=this.view.basemapTerrain.spatialReference,N=V(),F=[1,1,1];k(A,D,F,R)||bt.errorOnce("Unsupported coordinate system for IM overlay"),B(A,D,N,R);const P=_.createObject({toMapSpace:H(N[0],N[1],F[0],F[1]),geometry:w,obb:t.geometryObb,transform:{position:A,rotationScale:T}}),U=v.geometryParams.textureCoordinates===mt.Atlas,{textures:G,texturePromise:L}=this._initMaterialAndTextures(P,v.material,n,U);e.memory+=this._memEstimateGeometryAdded(P),e.memory+=G.reduce(((e,t)=>e+(null!=t?this._memEstimateTextureAdded(t):0)),0);const q=!!v.material.hasParametersFromSource,z="blend"!==v.material.alphaMode&&v.material.metallicRoughness.baseColorFactor[3]>=1,K=new vt(e,h,P,this._getInvalidRendererVersion(),s.attributeInfo,{hasParametersFromSource:q,isOpaque:z},G,c,u);s.meta=K,!this._hasTextures&&t.requiredTextures?.some((({usage:e})=>0!=(e&Me.ColorTextures)))&&(this._hasTextures=!0),this._hasData=!0,this._hasColors=this._hasColors||y,this._hasTextures=this._hasTextures||!!e.resources.texture,this.notifyChange("hasTexturesOrVertexColors");const W=this.slicePlaneEnabled;return Promise.all([this._addOrUpdateEdgeRendering(K),L]).then((([t,s])=>(null!=t&&t.updateObjectVisibility(K.objectHandle,!1).catch((e=>xt(e,this.i3slayer.title))),this._safeReschedule((()=>{const i=this._addTasks.get(e.index);if(!i)return;if(this._addNodeMeta(e.index,K),i.meta=null,!this.contentVisible)return void this._removeNodeStageData(e.index,this.elevationOffset);_.setObjectVisibility(P,ut.Visible),null!=t&&t.updateObjectVisibility(K.objectHandle,!0).catch((e=>xt(e,this.i3slayer.title))),K.attributeInfo=i.attributeInfo;const s=K.cachedRendererVersion!==this._rendererVersion,r=W!==this.slicePlaneEnabled;this._updateElevationOffsets(K);const o=K.elevationOffsets;this._updateComponentData(K);const a=this._applyFiltersToNode(K);(s||null!=t&&(r||a||o))&&this._addOrUpdateEdgeRendering(K),null!=this._labeler&&this._addMetaToLabeler(this._labeler,K),this._visibleGeometryChanged(K,Et.ADD),this._highlights.objectCreated(K),this._updateMaterial(K),this._setNewNodeOpacity(K),null!=this._treeDebugger&&this._treeDebugger.update()}),i)))).catch((e=>{throw null!=s.meta&&(this._cacheGPUData(s.meta),s.meta=null),e}))}_addNodeMeta(e,t){if(this._removeNodeStageData(e,this.elevationOffset,this._nodeId2MetaReloading),this._nodeId2Meta.has(e)){bt.error("Removing duplicated node");const t=this._nodeId2Meta.get(e);null!=t&&this._deleteComponentObject(t)}else this._controller.updateLoadStatus(e,!0);null!=t&&(t.lodCrossfadeProgress=null,this.nodeCrossfadingEnabled&&Lt(t.cachedEdgeMaterials,0)),this._nodeId2Meta.set(e,t)}_updateElevationOffsets(e){const t=this.view.renderSpatialReference,i=this._controller.crsIndex,s=this.elevationInfo,r=this.view.basemapTerrain,o=r.spatialReference,a=s.mode;if(null==t||null==o||a===kt.Absolute)return void(e.elevationOffsets=null);const n=this._collection.getObjectTransform(e.objectHandle);e.elevationOffsets=e.elevationOffsets??[];const l=Bt,d=qt,h=a===kt.OnTheGround,c=this.view.renderCoordsHelper,u=e.featureIds.length,_=(()=>{if(e.cachedElevationAnchors)return e.cachedElevationAnchors;const s=Y(3*u);e.cachedElevationAnchors=s;for(let r=0;r<u;r++){const a=3*r,h=e.anchorIds?.indexOf(r)??-1;e.anchors&&h>=0?(A(l,e.anchors[3*h],e.anchors[3*h+1],e.anchors[3*h+2]),T(l,l,e.node.mbs),B(l,i,l,o),s[a]=l[0],s[a+1]=l[1],s[a+2]=c.getAltitude(l)):(this._collection.getComponentAabb(e.objectHandle,r,d,!0),A(l,(d[0]+d[3])/2,(d[1]+d[4])/2,d[2]),D(l,l,n.rotationScale),T(l,l,n.position),s[a+2]=c.getAltitude(l),B(l,t,l,o),s[a]=l[0],s[a+1]=l[1])}return s})(),m=s.offset,g=e.elevationOffsets,p=(e,t)=>{const i=h?_[3*e+2]:0;g[e]=m+(null!=t?t-i:0)};r.getElevations(_,u,p)}_ensureElevationTask(){return null!=this._elevationTask||(this._elevationTask=new xe(this.view.resourceController.scheduler,(e=>{const t=this._controller.updateElevationChanged(e,this.view.basemapTerrain.spatialReference);return null!=t?t.filterInPlace((e=>null!=this._nodeId2Meta.get(e))):null}),(e=>{const t=this._nodeId2Meta.get(e);this._nodeElevationAlignmentChanged(t)}))),this._elevationTask}_elevationInfoChanged(e,t){const i=e.mode!==kt.Absolute,s=!!t&&t!==e&&t.mode!==kt.Absolute;this._intersectionHandler.updateElevationAlignState(i,this.view.state.viewingMode),i&&!s&&this._controller.removeAllGeometryObbs(),this._nodeId2Meta.forEach((e=>this._nodeElevationAlignmentChanged(e)))}_nodeElevationAlignmentChanged(e){null!=e&&(this._updateElevationOffsets(e),this._updateComponentData(e),this._updateEdgeRendering(e),null!=this._labeler&&this._labeler.updateLabelPositions(e),this._updateSnappingSources(e,Et.UPDATE))}_safeReschedule(e,t){return _(t),this._controller.reschedule(e,t)}_materialParameters(e,t){const i=null!=e.params.material?e.params.material:Re(),s=t.some((e=>"uvRegion"===e.name)),r=t.some((e=>"normalCompressed"===e.name)),o=Nt(i);return{geometryParams:this._getGeometryParameters({hasTexture:o,hasNormals:r,hasRegions:s}),material:i}}_initMaterialAndTextures(e,t,i,s){const r=this._stage.renderView,o=i.map((e=>Ne(e,t,s,r)));this._stage.addMany(o);let a=null;return this._collection.updateMaterial(e,(e=>{a=Fe(e,t,o,i,this.view._stage.renderView.textureRepository,{rendererTextureUsage:this.rendererTextureUsage,usePBR:this._usePBR,isIntegratedMesh:this._isIntegratedMesh,slicePlaneEnabled:this.slicePlaneEnabled,viewSpatialReference:this.view.spatialReference}),this._updateMaterialOverlay(e)})),{textures:o,texturePromise:a}}_getGeometryParameters(e){return{textureCoordinates:e.hasTexture?e.hasRegions?mt.Atlas:mt.Default:mt.None,colors:this._hasVertexColors,normals:e.hasNormals&&!this._isIntegratedMesh}}_addData(e,t,i){let s=this._addTasks.get(e.index);return s?s.attributeInfo=t:(s={...m(),attributeInfo:t,meta:null},this._addTasks.set(e.index,s),i().then(s.resolve,s.reject).then((()=>this._addTasks.delete(e.index))).catch((t=>{throw this._addTasks.delete(e.index),t}))),s.promise}_clearAddTasks(){this._addTasks.forEach((e=>{null!=e.meta&&(this._cacheGPUData(e.meta),e.meta=null)})),this._addTasks.clear()}_clippingAreaChanged(){const e=this.view.renderSpatialReference,t=this.i3slayer.spatialReference,i=Q();this._renderClippingArea=at(this.view.clippingArea,i,e)?i:null;const s=Q();this._layerClippingArea=at(this.view.clippingArea,s,t)?s:null,this._filterChange(),this._controller&&this._controller.updateClippingArea(this.view.clippingArea),this._isIntegratedMesh&&this._modificationsChanged()}get hasGeometryFilter(){return!1}_geometryFilterChange(){const e=this.hasGeometryFilter;this._controller.geometryFilterChanged(e),this._applyFilters(e)}_filterChange(){this._applyFilters(this.hasGeometryFilter)}_applyFilters(e){this._filters=this.getFilters(),e?this._controller&&this._controller.requestUpdate():this._nodeId2Meta.forEach((e=>{null!=e&&this._applyFiltersToNode(e)&&(this._addOrUpdateEdgeRendering(e),this._visibleGeometryChanged(e,Et.UPDATE))}))}getFilters(){const e=[],t=this._renderClippingArea;return null!=t&&e.push(((e,i)=>this._boundingRectFilter(e,i,t))),e}addSqlFilter(e,t,i){if(null!=t){const s=t.fieldNames;e.push(((e,r)=>this._sqlFilter(e,r,t,s,i)))}}_sqlFilter(e,t,i,s,r){const o={},a=this._createLayerGraphic(o),n=this.i3slayer.objectIdField,l=t.featureIds,d=null!=t.attributeInfo&&t.attributeInfo.attributeData;s.every((e=>e===n||d&&null!=d[e]))&&We(e,l,(e=>{o[n]=l[e];for(const i of s)i!==n&&(o[i]=d?$e(d[i],e):null);try{return i.testFeature(a)}catch(t){return r(t),!1}}))}_boundingRectNodeTest(e,t){return q(e.node.mbs,this._controller.crsIndex,Rt,this.view.renderSpatialReference),Qe(t,Rt)}_boundingRectFeatureTest(e,t,i){return this._collection.getComponentAabb(e.objectHandle,t,jt),$(jt,wt),X(i,wt)}_boundingRectFilter(e,t,i){const s=this._collection,r=this._boundingRectNodeTest(t,i);if(r===Xe.INSIDE)return;if(r===Xe.OUTSIDE)return void(e.length=0);const o=s.getComponentCount(t.objectHandle);if(o.invisible+o.visible!==t.featureIds.length)return;const a=this._transformClippingArea(St,i,t.objectHandle);We(e,t.featureIds,(e=>this._boundingRectFeatureTest(t,e,a)))}_transformClippingArea(e,t,i){const s=this._collection.getObjectTransform(i),r=s.position,o=s.rotationScale;return e[0]=(t[0]-r[0])/o[0],e[1]=(t[1]-r[1])/o[4],e[2]=(t[2]-r[0])/o[0],e[3]=(t[3]-r[1])/o[4],e}_addOrUpdateEdgeRendering(e,t=!0){const i=this._edgeView;if(null==i)return Promise.resolve(null);const s=e.objectHandle,r=i.hasObject(s),{hasEdges:o,perFeatureEdgeMaterials:a}=this._getFilteredEdgeMaterials(e),n={hasSlicePlane:this.slicePlaneEnabled};if(o&&r){if(this.nodeCrossfadingEnabled){Lt(a,this.getNodeOpacity(e))}return i.updateAllComponentMaterials(s,a,n,t).catch((e=>xt(e,this.i3slayer.title))),i.updateObjectVisibility(s,!0).catch((e=>xt(e,this.i3slayer.title))),i.updateAllVerticalOffsets(s,e.elevationOffsets).catch((e=>xt(e,this.i3slayer.title))),Promise.resolve(i)}return o&&!r?this._collection.addEdges(s,i,a,n).then((t=>(e.edgeMemoryUsage=t,e.node.memory+=t,i.updateAllVerticalOffsets(s,e.elevationOffsets).catch((e=>xt(e,this.i3slayer.title))),i))):(!o&&r&&(e.node.memory-=e.edgeMemoryUsage,e.edgeMemoryUsage=0,i.removeObject(s)),Promise.resolve(null))}_applyFiltersToNode(e){return!!this._applyFiltersToNodeComponents(e)&&(null!=this._labeler&&this._labeler.applyFilterChange(e),!0)}_applyFiltersToNodeComponents(e){const t=this._collection,i=0===t.getComponentCount(e.objectHandle).invisible;if(t.setAllComponentVisibilities(e.objectHandle,"all"),0===this._filters.length)return e.filteredIds=null,!i;if(this._updateCachedFilteredIds(e),e.filteredIds===e.featureIds)return!i;const s=this._computeFilteredComponentIndices(e);return t.setAllComponentVisibilities(e.objectHandle,s),!0}_updateCachedFilteredIds(e){null!=e.filteredIds&&e.appliedFilters===this._filters||(e.filteredIds=this._computeFilteredIds(e),e.appliedFilters=this._filters)}_computeFilteredIds(e){const t=e.featureIds.slice();for(const i of this._filters)if(i(t,e),0===t.length)break;return t.length===e.featureIds.length?e.featureIds:t}_computeFilteredComponentIndices(e){const t=new Array,i=e.filteredIds;return null!=i&&e.featureIds.forEach(((e,s)=>{i[t.length]===e&&t.push(s)})),t}_removeAllNodeDataFromStage(e=this.elevationOffset){this._nodeId2Meta.forEach(((t,i)=>this._removeNodeStageData(i,e))),this._nodeId2MetaReloading.forEach(((t,i)=>this._removeNodeStageData(i,e,this._nodeId2MetaReloading))),this._elevationTask=d(this._elevationTask)}removeNode(e){const t=this.elevationOffset;this._removeNodeStageData(e,t),this._removeNodeStageData(e,t,this._nodeId2MetaReloading),null!=this._elevationTask&&this._elevationTask.remove(e)}_removeNodeStageData(e,t,i=this._nodeId2Meta){i.has(e)&&this._controller.updateLoadStatus(e,!1);const s=i.get(e);null!=s?(this._collection.setObjectVisibility(s.objectHandle,ut.Hidden),null!=this._edgeView&&this._edgeView.hasObject(s.objectHandle)&&this._edgeView.updateObjectVisibility(s.objectHandle,!1).catch((e=>xt(e,this.i3slayer.title))),this._visibleGeometryChanged(s,Et.REMOVE),null!=this._labeler&&this._labeler.removeNodeMeta(s),i.delete(e),this._highlights.objectDeleted(s),i===this._nodeId2Meta?(this._cacheGPUData(s,t),this.nodeCrossfadingEnabled&&this._crossfadeHelper.stopNodeFading(s)):this._deleteComponentObject(s),null!=this._treeDebugger&&this._treeDebugger.update()):i.delete(e)}_deleteComponentObject(e){if(null!=this._edgeView&&this._edgeView.removeObject(e.objectHandle),this._memEstimateGeometryRemoved(e.objectHandle),this._collection.destroyObject(e.objectHandle),e.textures)for(const t of e.textures)this._memEstimateTextureRemoved(t),this._stage.remove(t)}updateNodeState(e,t){const i=this._nodeId2Meta.get(e);null!=i&&this._collection.updateMaterial(i.objectHandle,(e=>e.polygonOffsetEnabled=t===Pe.Hole))}updateNodeIndex(e,t){if(this._nodeId2Meta.has(e)){const i=this._nodeId2Meta.get(e);this._nodeId2Meta.delete(e),this._nodeId2Meta.set(t,i)}const i=this._nodeId2MetaReloading.get(e);i&&(this._nodeId2MetaReloading.delete(e),this._nodeId2MetaReloading.set(t,i))}_invalidateAllSymbols(){this._rendererVersion=Ye(this._rendererVersion,1),this._controller&&this._controller.requestUpdate()}_getInvalidRendererVersion(){return Ye(this._rendererVersion,-1)}async _rendererChange(e){if(this._currentRenderer=e,this.notifyChange("rendererTextureUsage"),this._rendererVersion=Ye(this._rendererVersion,1),this._rendererFields=null,this._colorVariable=null,this._opacityVariable=null,this._invalidateAllSymbols(),e&&(this._rendererFields=await e.getRequiredFields(this.i3slayer.fieldsIndex)),this._updateSymbologyFields(),!this._arcade&&e&&"arcadeRequired"in e&&e.arcadeRequired&&(this._arcade=await le()),e&&"visualVariables"in e&&e.visualVariables)for(const t of e.visualVariables)"color"===t.type?this._colorVariable=t:"opacity"===t.type?this._opacityVariable=t:bt.warn(`Unsupported visual variable type for 3D Object Scene Services: ${t.type}`);if(e)for(const t of e.getSymbols())"mesh-3d"!==t.type&&bt.error(`Symbols of type '${t.type}' are not supported for 3D Object Scene Services.`);this._controller&&this._controller.requestUpdate()}_getCachedEdgeMaterials(e){return this._hasComponentData&&e.cachedRendererVersion!==this._rendererVersion&&this._updateCachedRendererData(e),e.cachedEdgeMaterials}_getComponentParameters(e){this._hasComponentData&&e.cachedRendererVersion!==this._rendererVersion&&this._updateCachedRendererData(e);const t=e.cachedSymbology;return(i,s)=>{const r=5*i;if(P(s.externalColor,t[r]/255,t[r+1]/255,t[r+2]/255,t[r+3]/255),null!=this._stage.renderView.objectAndLayerIdRenderHelper){const t=e.featureIds[i];this._stage.renderView.objectAndLayerIdRenderHelper.setUidToObjectAndLayerId(t,t,this.layerId,this.layerUid+"_"+this.sublayerId,this.layerPopupEnabledAndHasTemplate,e.node.resources.attributes,i,this.sublayerId),s.objectAndLayerIdColor=this._stage.renderView.getObjectAndLayerIdColor({graphicUid:t,layerUid:this.layerUid+"_"+this.sublayerId})}s.externalColorMixMode=t[r+4]&(1<<It.CastShadows)-1,s.castShadows=0!=(t[r+4]&1<<It.CastShadows),s.pickable=0!=(t[r+4]&1<<It.Pickable),s.elevationOffset=e.elevationOffsets?.[i]??0}}_getSymbolInfo(e,t){const i=e&&e.getSymbol(t,{arcade:this._arcade});if(!(i instanceof de))return null;const s=i.id;if(this._symbolInfos.has(s))return this._symbolInfos.get(s);const r=Je(i);return this._symbolInfos.set(s,r),r}_setSymbologyOverride(e,t){this._symbologyOverride!==e&&(this._symbologyOverride=e,this._symbologyOverrideFields=t,this._invalidateAllSymbols(),this._updateSymbologyFields())}_updateSymbologyFields(){this._symbologyFields=null!=this._symbologyOverrideFields&&this._symbologyOverrideFields.length>0?null!=this._rendererFields&&this._rendererFields.length>0?re(this.i3slayer.fieldsIndex,[...this._rendererFields,...this._symbologyOverrideFields]):this._symbologyOverrideFields:this._rendererFields}_updateCachedRendererData(e){if(e.cachedRendererVersion=this._rendererVersion,!this._hasComponentData)return;const t=this._tmpAttributeOnlyGraphic,i={};t.attributes=i;const s=this._currentRenderer,r=e.attributeInfo?.attributeData,o=null!=e.featureIds?this.i3slayer.objectIdField:null,a=null!=r&&null!=this._symbologyFields&&this._symbologyFields.length>0;let n=null,l=null;if(a&&null!=this._symbologyFields){n=[],l=[];for(const e of this._symbologyFields){const t=r[e];t&&(n.push(e),l.push(t))}}e.cachedSymbology||(e.cachedSymbology=te(5*e.featureIds.length));const d={color:Tt,castShadows:!0,pickable:!0,colorMixMode:rt.Multiply,edgeMaterial:null},h=this.fullOpacity,c=this.nodeCrossfadingEnabled?this.getNodeOpacity(e):h;let u=null,_=pt.OPAQUE,m=Ze,g=0;for(let p=0;p<e.featureIds.length;p++){if(null!=o&&(i[o]=e.featureIds[p]),a&&n)for(let e=0;e<n.length;e++)i[n[e]]=$e(l[e],p);const r=s?this._getSymbolInfo(s,t):null;let h=null,f=null;if(s&&"visualVariables"in s){if(this._colorVariable){const e=ae(this._colorVariable,t,{color:Dt,arcade:this._arcade});e&&(h=Tt,h[0]=e.r/255,h[1]=e.g/255,h[2]=e.b/255,this._opacityVariable||null===e.a||(f=e.a))}this._opacityVariable&&(f=ne(this._opacityVariable,t,{arcade:this._arcade}))}if(r&&r.material){const e=r.material;h=null==h||null==f?ve(h,f,e.color,e.alpha,yt,Tt):ve(h,f,null,null,yt,Tt)}if(null==h&&(h=Tt,h[0]=1,h[1]=1,h[2]=1,h[3]=1),d.pickable=!0,d.castShadows=!r||r.castShadows,d.colorMixMode=r&&r.material?r.material.colorMixMode:rt.Multiply,d.edgeMaterial=r?r.edgeMaterial:null,null!=this._symbologyOverride&&(d.color=h,this._symbologyOverride(t,d),h=d.color),null!=d.edgeMaterial){const t=h[3]<=0?pt.INVISIBLE:h[3]>=1&&(e.material.isOpaque||d.colorMixMode===rt.Replace)?pt.OPAQUE:pt.TRANSPARENT;d.edgeMaterial===u&&t===_||(m={...d.edgeMaterial,opacity:c,objectTransparency:t},u=d.edgeMaterial,_=t),e.cachedEdgeMaterials[p]=m}else e.cachedEdgeMaterials[p]=Ze;e.cachedSymbology[g++]=Math.round(255*h[0]),e.cachedSymbology[g++]=Math.round(255*h[1]),e.cachedSymbology[g++]=Math.round(255*h[2]),e.cachedSymbology[g++]=Math.round(255*h[3]),e.cachedSymbology[g++]=d.colorMixMode|+d.castShadows<<It.CastShadows|+d.pickable<<It.Pickable}}_getFilteredEdgeMaterials(e){const t=this._getCachedEdgeMaterials(e);this.nodeCrossfadingEnabled||Lt(t,this.fullOpacity);const i=e.filteredIds;if(null==i){return{hasEdges:t.some((e=>e!==Ze)),perFeatureEdgeMaterials:t}}let s=0,r=!1;const o=t.map(((t,o)=>e.featureIds[o]!==i[s]?Ze:(r=r||t!==Ze,s++,t)));return{hasEdges:r,perFeatureEdgeMaterials:o}}_updateComponentData(e){if(!this._hasComponentData)return;const t=e.objectHandle,i=this._getComponentParameters(e);this._collection.setComponentData(t,i),this._stage.renderView.requestRender()}_reloadAll(e=this.elevationOffset){this._removeAllNodeDataFromStage(e),null!=this._controller&&this._controller.restartNodeLoading()}_opacityChange(e){this.nodeCrossfadingEnabled&&this._crossfadeHelper.stopAllNodeFading(),this._nodeId2Meta.forEach((t=>{null!=t&&(this._collection.updateMaterial(t.objectHandle,(t=>t.objectOpacity=e)),Lt(t.cachedEdgeMaterials,e),this._updateEdgeRendering(t))}))}_updateMaterial(e){this._collection.updateMaterial(e.objectHandle,(e=>{e.commonMaterialParameters.hasSlicePlane=this.slicePlaneEnabled,e.usePBR=this._usePBR,this._updateMaterialOverlay(e)}))}_updateMaterialOverlay(e){}_updateEngineObject(e){this._updateComponentData(e),this._applyFiltersToNode(e),this._addOrUpdateEdgeRendering(e),this._visibleGeometryChanged(e,Et.UPDATE)}_slicePlaneEnabledChange(e){this._intersectionHandler&&(this._intersectionHandler.slicePlaneEnabled=e),null!=this._labeler&&(this._labeler.slicePlaneEnabled=e),this._nodeId2Meta.forEach((t=>{null!=t&&(this._collection.updateMaterial(t.objectHandle,(t=>t.commonMaterialParameters.hasSlicePlane=e)),this._updateEdgeRendering(t,!1))}))}_updatePBR(e){this._nodeId2Meta.forEach((t=>{null!=t&&this._collection.updateMaterial(t.objectHandle,(t=>t.usePBR=e))})),this._hasLoadedPBRTextures=!0}get _usePBR(){return!this._isIntegratedMesh&&this.view.qualitySettings.physicallyBasedRenderingEnabled}_updateEdgeRendering(e,t=!0){null!=this._edgeView&&this._edgeView.hasObject(e.objectHandle)&&this._addOrUpdateEdgeRendering(e,t)}_forAllNodes(e){this._nodeId2Meta.forEach(e)}_ignoreClientNodeOverriddenFeatures(e){return this.i3sOverrides.hasGeometryChanges?e:(t,i,s)=>s.node.index>=0&&this.i3sOverrides.featureHasGeometryChanges(t)?me.CONTINUE:e(t,i,s)}_forAllFeatures(e,t,i){l(this._nodeId2Meta,(s=>{if(null==s)return!1;if(null!=t){switch(t(s)){case me.EXIT:return!0;case me.SKIP:return!1}}let r=me.CONTINUE;switch(i){case ge.ALL:r=this._forAllFeaturesOfNode(s,e);break;case ge.VISIBLE_ONLY:r=this._forAllVisibleFeaturesOfNode(s,e);break;case ge.QUERYABLE:r=this._forAllQueryableFeaturesOfNode(s,e)}return r===me.EXIT}))}_forAllFeaturesOfNode(e,t){let i=me.CONTINUE;const s=e.featureIds;for(let r=0;r<s.length;r++)if(i=t(s[r],r,e),i===me.EXIT)return i;return i}_forAllVisibleFeaturesOfNode(e,t){let i=me.CONTINUE;const s=e.featureIds;return this._collection.forEachVisibleComponent(e.objectHandle,(r=>(i=t(s[r],r,e),i===me.CONTINUE))),i}_forAllQueryableFeaturesOfNode(e,t){const i=this._ignoreClientNodeOverriddenFeatures(t);if(null==this._renderClippingArea)return this._forAllFeaturesOfNode(e,i);const s=this._boundingRectNodeTest(e,this._renderClippingArea);if(s===Xe.OUTSIDE)return me.CONTINUE;if(s===Xe.INSIDE)return this._forAllFeaturesOfNode(e,i);const r=me.CONTINUE,o=e.featureIds,a=e.objectHandle,n=et(this._renderClippingArea,this._collection.getObjectTransform(a));for(let l=0;l<o.length;l++){if(!this._boundingRectFeatureTest(e,l,n))continue;const t=i(o[l],l,e);if(t===me.EXIT)return t}return r}_createAttributes(e,t){const i={};null!=t.featureIds&&(i[this._getObjectIdField()]=t.featureIds[e]);const s=t.attributeInfo?.attributeData;if(null!=s)for(const r of Object.keys(s))i[r]=$e(s[r],e);return i}_createGraphic(e,t){return this._createLayerGraphic(this._createAttributes(e,t))}highlight(e){const t=this._highlights;if("number"==typeof e||e instanceof i?e=[e]:e instanceof a&&(e=e.toArray()),Array.isArray(e)&&e.length>0){if(e[0]instanceof i){const i=e,s=this.i3slayer.fieldsIndex,r=this._getObjectIdField(),o=i.map((e=>st(s,e.attributes,r))),{set:a,handle:n}=t.acquireSet();return t.setFeatureIds(a,o),n}if("number"==typeof e[0]){const i=e,{set:s,handle:r}=t.acquireSet();return t.setFeatureIds(s,i),r}}return Gt}resetHighlights(){d(this._highlights),this._highlights=new Oe({collection:this._collection,forAllFeatures:e=>this._forAllFeatures(e,null,ge.ALL),forAllFeaturesOfNode:(e,t)=>this._forAllFeaturesOfNode(e,t)})}_visibleGeometryChanged(e,t){this._elevationProvider&&(this._elevationProvider.objectChanged(e.node),null==this._visibleGeometryChangedSchedulerHandle&&(this._visibleGeometryChangedSchedulerHandle=f((()=>{this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=null}))),this._updateSnappingSources(e,t))}get performanceInfo(){const e={displayedNumberOfFeatures:0,maximumNumberOfFeatures:0,totalNumberOfFeatures:0,core:null,index:0,nodes:this._nodeId2Meta.size,"Total GPU Memory Estimate":(this._gpuMemoryEstimate/1048576).toFixed(1)+"MB","Geometry Memory Estimate":(this._geoMemoryEstimate/1048576).toFixed(1)+"MB","Texture Memory Estimate":(this._texMemoryEstimate/1048576).toFixed(1)+"MB","Unloaded Memory Estimate":(this.unloadedMemory/1048576).toFixed(1)+"MB"};return null!=this._memCache&&(e.MemCache=Math.round(100*this._memCache.hitRate)+"% hit"),this._controller&&(this._idbCacheEnabled&&(e.IDBCache=Math.round(100*this._idbCache.getHitRate())+"% hit"),this._controller.updateStats(e)),e}get test(){const e=this;return{controller:this._controller,labeler:this._labeler,get visibleObjectIds(){const t=[];return e._forAllFeatures((e=>(t.push(e),me.CONTINUE)),null,ge.VISIBLE_ONLY),t.sort(((e,t)=>e-t)),t},get numNodes(){return e._nodeId2Meta.size},get loadedNodes(){return Array.from(e._nodeId2Meta.keys()).sort(((e,t)=>e-t))}}}getNodeOpacityByIndex(e){const t=this._nodeId2Meta.get(e);return this.getNodeOpacity(t)}getNodeOpacity(e){return null!=e?this._collection.getMaterial(e.objectHandle).objectOpacity:0}isNodeFullyFadedIn(e){return this._crossfadeHelper.isNodeFullyFadedIn(e)}getNodeCrossfadeMetaData(e){return this._nodeId2Meta.get(e)}markNodeToRemove(e){this._controller&&this._controller.markNodeToRemove(e)}removeMarkedNodes(){this._controller&&this._controller.removeMarkedNodes()}foreachCrossfadeNode(e){this._nodeId2Meta.forEach(((t,i)=>e(i,t)))}fadeNode(e,t,i){if(!this.nodeCrossfadingEnabled)return;const s=this._nodeId2Meta.get(e);null!=s&&this._crossfadeHelper.fadeNode(e,s,t,i)}setNodeOpacityByIndex(e,t){const i=this._nodeId2Meta.get(e);null!=i&&this._setNodeOpacity(i,t)}_setNodeOpacity(e,t){this._collection.updateMaterial(e.objectHandle,(e=>e.objectOpacity=t)),this._setNodeEdgeOpacity(e,t)}_setNodeEdgeOpacity(e,t){if(null==this._edgeView||!e.cachedEdgeMaterials)return;Lt(e.cachedEdgeMaterials,t);const i=e.objectHandle;this._edgeView.hasObject(i)&&this._edgeView.updateAllComponentOpacities(i,t).catch((e=>xt(e,this.i3slayer.title)))}get hasModifications(){return this._isIntegratedMesh&&null!=this._layerClippingArea||this._modifications&&this._modifications.length>0}updateNodeModificationStatus(e){const t=e.length;if(!this.hasModifications||t<=0||!0!==this._i3sWasmLoaded)return;const i=this.uid,s=Ut(e);if(null!=s){const t={context:i,buffer:s.buffer};be(t);const r=new Float64Array(s.buffer);e.forAll(((e,t)=>{const i=r[t],s=ye(i);e.imModificationImpact=s,s!==Ve.Unmodified&&this._controller.invalidateGeometryVisibility(e.index)}))}}notifyUpdate(){this.notifyChange("updating")}notifyLODUpdate(){this._controller.notifyLODUpdate()}isUpdating(){return!(!this._controller||!this._controller.updating)||!!this._visibleGeometryChangedSchedulerHandle||null!=this._labeler&&this._labeler.updating||this._crossfadeHelper?.updating||this._i3sWasmLoaded instanceof Promise||this._asyncModuleLoading>0||null!=this._elevationTask&&this._elevationTask.running}trackSnappingSources(e){const t={events:e,fetchEdgeLocations:async(e,t,i)=>{const s=this._nodeId2Meta.get(e);if(null==s)throw new Error("invalid-node");const{origin:r,buffer:o}=await this._collection.extractEdgeInformation(s.objectHandle,t,i);return this._snappingLocationsApplyElevation(s,o,r),{type:"components",objectIds:s.featureIds,locations:o,origin:r}},remove:()=>{r(this._snappingSourcesTrackers,t)}};return this._snappingSourcesTrackers.push(t),this._nodeId2Meta.forEach(((t,i)=>{if(null==t)return;const s=this._controller.getRenderMbs(t.node);null!=s&&e.add(i,s)})),t}_snappingLocationsApplyElevation(e,t,i){if(!e.elevationOffsets||this.elevationInfo.mode===kt.Absolute)return;const s=t.position0,r=t.position1,o=t.componentIndex,a=V(),n=V(),l=(e,t)=>{T(e,e,i),this.view.renderCoordsHelper.worldUpAtPosition(e,n),T(e,e,N(n,n,t)),F(e,e,i)};for(let d=0;d<s.count;d++){const t=e.elevationOffsets[o.get(d)];s.getVec(d,a),l(a,t),s.setVec(d,a),r.getVec(d,a),l(a,t),r.setVec(d,a)}}_updateSnappingSources(e,t){const{index:i}=e.node,s=this._controller.getRenderMbs(e.node);if(null!=s)for(const r of this._snappingSourcesTrackers)t!==Et.REMOVE&&t!==Et.UPDATE||r.events.remove(i),t!==Et.ADD&&t!==Et.UPDATE||r.events.add(i,s)}};return e([v()],o.prototype,"_hasLoadedPBRTextures",void 0),e([v()],o.prototype,"_asyncModuleLoading",void 0),e([v()],o.prototype,"_visibleGeometryChangedSchedulerHandle",void 0),e([v()],o.prototype,"view",void 0),e([v()],o.prototype,"i3slayer",void 0),e([v()],o.prototype,"_controller",void 0),e([v()],o.prototype,"_labeler",void 0),e([v()],o.prototype,"updating",void 0),e([v()],o.prototype,"suspended",void 0),e([v()],o.prototype,"contentVisible",null),e([v({readOnly:!0})],o.prototype,"legendEnabled",null),e([v()],o.prototype,"holeFilling",void 0),e([v(ht)],o.prototype,"updatingProgress",void 0),e([v()],o.prototype,"updatingProgressValue",null),e([v()],o.prototype,"hasTexturesOrVertexColors",null),e([v()],o.prototype,"rendererTextureUsage",null),e([v()],o.prototype,"elevationOffset",null),e([v()],o.prototype,"elevationInfo",null),e([v({type:Boolean})],o.prototype,"slicePlaneEnabled",void 0),e([v()],o.prototype,"supportedTextureEncodings",null),e([v()],o.prototype,"uncompressedTextureDownsamplingEnabled",null),e([v({type:[oe]})],o.prototype,"_modifications",void 0),e([v({readOnly:!0})],o.prototype,"clientGeometry",null),e([v()],o.prototype,"_elevationTask",void 0),e([v({readOnly:!0})],o.prototype,"_usePBR",null),o=e([I(ft)],o),o};function xt(e,t){u(e)||bt.warn("Error while processing edges. Edges on this layer might not display correctly",t,e)}var Et;!function(e){e[e.ADD=0]="ADD",e[e.REMOVE=1]="REMOVE",e[e.UPDATE=2]="UPDATE"}(Et||(Et={}));const jt=z(),wt=Q(),St=Q(),At=nt(),Tt=[0,0,0,0],Dt=new t([0,0,0,0]),Rt=ee(0,0,0,0);function Nt(e){if(null==e)return!1;const t=e.metallicRoughness;return t&&t.baseColorTextureId>=0||t&&t.metallicRoughnessTextureId>=0||e.normalTextureId>=0||e.emissiveTextureId>=0||e.occlusionTextureId>=0}function Ft(e){return"geometryData"in e}function Vt(e){return null!=e&&b(e.data)}function Pt(e,t){let i=1024+e.interleavedVertexData.byteLength+(e.indices?e.indices.byteLength:0)+e.positionData.data.byteLength+e.positionData.indices.byteLength;if(null!=t)for(const s of t)null!=s&&b(s.data)&&(i+=s.data.byteLength);return i}function Ht(e,t){return t.byteSize>Ct?(bt.warn(`Node is too big to store in IndexedDB cache: ${e.id} (${t.byteSize} bytes)`),!1):t.byteSize>0}function Ut(e){if(0===e.length)return null;const t=10*e.length,i=new Float64Array(t);return e.forAll(((e,t)=>{let s=e.serviceObb;null==s&&(s=At,R(s.center,e.mbs),s.halfSize[0]=s.halfSize[1]=s.halfSize[2]=e.mbs[3]);const r=10*t;i[r]=s.center[0],i[r+1]=s.center[1],i[r+2]=s.center[2],i[r+3]=s.halfSize[0],i[r+4]=s.halfSize[1],i[r+5]=s.halfSize[2],i[r+6]=s.quaternion[0],i[r+7]=s.quaternion[1],i[r+8]=s.quaternion[2],i[r+9]=s.quaternion[3]})),i}const Gt={remove(){},pause(){},resume(){}};function Lt(e,t){e.forEach((e=>e.opacity=t))}var kt;!function(e){e[e.Absolute=0]="Absolute",e[e.RelativeToGround=1]="RelativeToGround",e[e.OnTheGround=2]="OnTheGround"}(kt||(kt={}));const Bt=V(),qt=z(),zt="elevation-change";function Kt(e){return t=>{if(e.immediate)return e.immediate.schedule(t);throw console.error("Error no immediate schudler"),new Error("cant find immediate scheduler")}}export{kt as ElevationMode,Ot as I3SMeshView3D};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import i from"../../../Graphic.js";import{isSome as s,removeUnordered as r}from"../../../core/arrayUtils.js";import{ByteSizeUnit as o}from"../../../core/ByteSizeUnit.js";import a from"../../../core/Collection.js";import has from"../../../core/has.js";import n from"../../../core/Logger.js";import{someMap as l}from"../../../core/MapUtils.js";import{destroyMaybe as d,applySome as h}from"../../../core/maybe.js";import c from"../../../core/PooledArray.js";import{isAbortError as u,throwIfAborted as _,createResolver as m}from"../../../core/promiseUtils.js";import{initial as g,watch as p}from"../../../core/reactiveUtils.js";import{schedule as f}from"../../../core/scheduling.js";import{isArrayBuffer as b}from"../../../core/typedArrayUtil.js";import{getMetersPerVerticalUnitForSR as y}from"../../../core/unitUtils.js";import{property as v}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as I}from"../../../core/accessorSupport/decorators/subclass.js";import{f as M}from"../../../chunks/mat3.js";import{c as C}from"../../../chunks/mat3f64.js";import{m as O,B as x}from"../../../chunks/mat4.js";import{b as E,c as j}from"../../../chunks/mat4f64.js";import{f as w}from"../../../chunks/quatf64.js";import{m as S,s as A,a as T,t as D,c as R,g as N,b as F}from"../../../chunks/vec3.js";import{c as V}from"../../../chunks/vec3f64.js";import{s as P}from"../../../chunks/vec4.js";import{f as H}from"../../../chunks/vec4f64.js";import{getReferenceEllipsoid as U}from"../../../geometry/ellipsoidUtils.js";import{projectBuffer as G,getProjectorName as L,localLinearScaleFactors as k,projectVectorToVector as B,projectBoundingSphere as q}from"../../../geometry/projection.js";import{create as z,empty as K,expandWithBuffer as W,toRect as $}from"../../../geometry/support/aaBoundingBox.js";import{create as Q,intersects as X}from"../../../geometry/support/aaBoundingRect.js";import{newDoubleArray as Y}from"../../../geometry/support/DoubleArray.js";import{compactFloatArray as J}from"../../../geometry/support/FloatArray.js";import{compactIndices as Z}from"../../../geometry/support/Indices.js";import{f as ee}from"../../../chunks/sphere.js";import{newUByteArray as te}from"../../../geometry/support/UByteArray.js";import{fallbackObjectIDAttribute as ie}from"../../../layers/LayerConstants.js";import se from"../../../layers/graphics/controllers/I3SOnDemandController.js";import{fixFields as re}from"../../../layers/support/fieldUtils.js";import oe from"../../../layers/support/SceneModification.js";import{getColor as ae,getOpacity as ne}from"../../../renderers/visualVariables/support/visualVariableUtils.js";import{loadArcade as le}from"../../../support/arcadeOnDemand.js";import{isBasemapLayer as de}from"../../../support/basemapUtils.js";import he from"../../../symbols/Symbol3D.js";import{getMetersPerUnit as ce}from"../../../symbols/support/unitConversionUtils.js";import ue from"./I3SMeshViewLabeler.js";import{I3SMeshWorkerHandle as _e,toWasmModification as me}from"./I3SMeshWorkerHandle.js";import{ForAllFeaturesReturnType as ge,ForAllFeaturesMode as pe}from"./II3SMeshView3D.js";import{initialize as fe,setModificationsSync as be,filterObbsForModificationsSync as ye,interpretObbModificationResults as ve}from"./SceneLayerWorker.js";import{overrideColor as Ie}from"./graphics/graphicUtils.js";import{areLabelsVisible as Me}from"./graphics/Labeler.js";import{TextureUsage as Ce,TextureEncoding as Oe}from"./i3s/enums.js";import xe from"./i3s/Highlights.js";import{I3SAsyncElevationUpdater as Ee}from"./i3s/I3SAsyncElevationUpdater.js";import{I3SCrossfadeHelper as je,NodeCrossfadeMetaData as we}from"./i3s/I3SCrossfadeHelper.js";import Se from"./i3s/I3SElevationProvider.js";import{boundingBoxCornerPoints as Ae}from"./i3s/I3SGeometryUtil.js";import{I3SIntersectionHandler as Te}from"./i3s/I3SIntersectionHandler.js";import{getSupportedEncodings as De,selectEncoding as Re,defaultMaterial as Ne,createTexture as Fe,configureMaterial as Ve}from"./i3s/I3SMaterialUtil.js";import{NodeIMModificationImpact as Pe,NodeState as He}from"./i3s/I3SNode.js";import{I3SOverrides as Ue}from"./i3s/I3SOverrides.js";import{computeGlobalTransformation as Ge,getLocalOrigin as Le}from"./i3s/I3SProjectionUtil.js";import{rendererNeedsTextures as ke,checkSceneLayerValid as Be,checkSceneLayerCompatibleWithView as qe,getCacheKeySuffix as ze,whenGraphicAttributes as Ke,computeVisibilityObb as We,filterInPlace as $e,getCachedAttributeValue as Qe,intersectBoundingRectWithMbs as Xe,MbsIntersectResult as Ye,addWraparound as Je,getSymbolInfo as Ze,transparentEdgeMaterial as et,getClipRect as tt}from"./i3s/I3SUtil.js";import{IDBCache as it}from"./i3s/IDBCache.js";import{IDBMockCache as st}from"./i3s/IDBMockCache.js";import{attributeLookup as rt}from"./support/attributeUtils.js";import{ColorMixModeEnum as ot}from"./support/symbolColorUtils.js";import at from"../support/debugFlags.js";import{toBoundingRect as nt}from"../support/extentUtils.js";import{create as lt,intersectSphere as dt,clone as ht}from"../support/orientedBoundingBox.js";import{updatingProgress as ct}from"../support/updatingProperties.js";import{glLayout as ut}from"../support/buffer/glUtil.js";import{State as _t}from"../webgl-engine/collections/Component/ComponentObject.js";import{createVertexBufferLayout as mt}from"../webgl-engine/collections/Component/SourceGeometry.js";import{TextureCoordinateAttributeType as gt}from"../webgl-engine/core/shaderLibrary/attributes/TextureCoordinateAttribute.glsl.js";import{loadBasis as pt}from"../webgl-engine/lib/BasisUtil.js";import{Transparency as ft}from"../webgl-engine/lib/edgeRendering/interfaces.js";const bt="esri.views.3d.layers.I3SMeshView3D",yt=n.getLogger(bt),vt=[1,1,1,1];class It extends we{constructor(e,t,i,s,r,o,a,n,l){super(),this.node=e,this.featureIds=t,this.objectHandle=i,this.cachedRendererVersion=s,this.attributeInfo=r,this.material=o,this.textures=a,this.anchorIds=n,this.anchors=l,this.cachedElevationAnchors=null,this.cachedEdgeMaterials=new Array,this.edgeMemoryUsage=0}}var Mt;!function(e){e[e.CastShadows=4]="CastShadows",e[e.Pickable=5]="Pickable"}(Mt||(Mt={}));const Ct=23,Ot=100*o.MEGABYTES,xt=t=>{let o=class extends t{constructor(...e){super(e),this._nodeId2Meta=new Map,this._nodeId2MetaReloading=new Map,this._i3sWasmLoaded=!1,this._snappingSourcesTrackers=[],this._hasLoadedPBRTextures=!1,this._asyncModuleLoading=0,this._addTasks=new Map,this._currentRenderer=null,this._rendererVersion=0,this._colorVariable=null,this._opacityVariable=null,this._rendererFields=null,this._symbologyFields=null,this._symbologyOverride=null,this._symbologyOverrideFields=null,this._symbolInfos=new Map,this._visibleGeometryChangedSchedulerHandle=null,this._idbCache=has("enable-feature:idb-mock-cache")?new st:new it("esri-scenelayer-cache","geometries"),this._hasComponentData=!1,this._hasVertexColors=!1,this.updating=!0,this.holeFilling="auto",this._hasColors=!1,this._hasTextures=!1,this._hasData=!1,this.slicePlaneEnabled=!1,this._modifications=new Array,this.ignoresMemoryFactor=!1,this._layerUrl="",this._cacheKeySuffix=null,this._elevationTask=null,this._filters=[],this._arcade=null,this._tmpAttributeOnlyGraphic=new i(null,null,{}),this._crossfadeHelper=new je(this)}get lodCrossfadeoutDuration(){return 0}get lodCrossfadeinDuration(){return 0}get lodCrossfadeUncoveredDuration(){return 0}get layerUid(){return this.i3slayer&&this.i3slayer.uid}get sublayerUid(){return null}get layerId(){return this.i3slayer&&this.i3slayer.id}get sublayerId(){return null}get contentVisible(){return!this.suspended&&this._controller?.rootNodeVisible}get legendEnabled(){return this.contentVisible&&!0===this.i3slayer?.legendEnabled}get updatingProgressValue(){return this._controller?.updatingProgress??0}get hasTexturesOrVertexColors(){return this._hasData?this._hasTextures||this._hasColors?"yes":"probably-not":"unknown"}get rendererTextureUsage(){return ke(this._currentRenderer)?this._usePBR||this._hasLoadedPBRTextures?Ce.AllTexturesPBR:Ce.AllTextures:this._usePBR||this._hasLoadedPBRTextures?Ce.GeometryTexturesPBR:Ce.GeometryTextures}get elevationOffset(){const e=null!=this.i3slayer?this.i3slayer.elevationInfo:null;if(null!=e&&"absolute-height"===e.mode){const t=y(this.i3slayer.spatialReference),i=ce(e.unit);return(e.offset??0)*i/t}return 0}get elevationInfo(){const e=null!=this.i3slayer?this.i3slayer.elevationInfo:null;if(null==e)return{mode:Bt.Absolute,offset:0};const t=y(this.i3slayer.spatialReference),i=ce(e.unit),s=(e.offset??0)*i/t;switch(e.mode){case"absolute-height":return{mode:Bt.Absolute,offset:s};case"relative-to-ground":return{mode:Bt.RelativeToGround,offset:s};case"on-the-ground":return{mode:Bt.OnTheGround,offset:0};default:return{mode:Bt.Absolute,offset:0}}}get supportedTextureEncodings(){return De(this.view._stage.renderView.capabilities)}get uncompressedTextureDownsamplingEnabled(){const e=this.view?.qualitySettings.sceneService.uncompressedTextureDownsamplingEnabled,t=0==(this.supportedTextureEncodings&Oe.DDS_S3TC);return e&&t}get clientGeometry(){return this.i3sOverrides.geometryOverrides}initialize(){this._preLoadBasis(),this.addResolvingPromise(this.i3slayer.indexInfo);const e=this.view.resourceController,t=e.memoryController;this.i3sOverrides=new Ue({view:this.view,layer:this.i3slayer,memoryController:t}),this._worker=new _e(Wt(e)),this.addResolvingPromise(this._worker.promise);const i=this.i3slayer.store;this._worker.setLegacySchema(this.uid,i.defaultGeometrySchema),Be(this.i3slayer),qe(this.i3slayer,this.view),this._layerUrl=this.i3slayer.parsedUrl.path,this._controller=new se({layerView:this,worker:this._worker}),this._gpuMemoryEstimate=0,this._texMemoryEstimate=0,this._geoMemoryEstimate=0,this._stage=this.view._stage,this._collection=this._stage.renderView.componentObjectCollection,this.resetHighlights();const s=i.defaultGeometrySchema;if(this._isIntegratedMesh||!s)this._hasComponentData=!1;else{const e=s.featureAttributes;this._hasComponentData=!!(e&&e.faceRange&&e.id)}this._hasVertexColors=null!=(s?.vertexAttributes.color??null)&&(null==this.i3slayer.cachedDrawingInfo||!this.i3slayer.cachedDrawingInfo.color),this._isIntegratedMesh||(this._edgeView=this._stage.renderer.ensureEdgeView());const r=this.view.resourceController.memoryController.newCache(`sl-${this.uid}`,(e=>this._deleteComponentObject(e)));this._memCache=r;const o=e=>null!=this._controller.index&&null!=this._controller.index.rootNode?this._controller.index.traverse(this._controller.index.rootNode,(t=>{const i=t.index,s=this._nodeId2Meta.get(i)||this._nodeId2MetaReloading.get(i);return e(t,null!=s?s.objectHandle:null)})):()=>{};this._intersectionHandler=new Te({layerUid:this.layerUid,sublayerUid:this.sublayerUid,collection:this._collection,slicePlaneEnabled:this.slicePlaneEnabled,isGround:this._isIntegratedMesh,traverseNodeHierarchy:o}),this.updatingHandles.add((()=>this.layerUid),(e=>this._intersectionHandler.layerUid=e)),this.updatingHandles.add((()=>this.sublayerUid),(e=>this._intersectionHandler.sublayerUid=e)),this._elevationProvider=new Se({layerView:this,intersectionHandler:this._intersectionHandler}),this._hasLoadedPBRTextures=this._usePBR,this.updatingHandles.add((()=>this.view.clippingArea),(()=>this._clippingAreaChanged()),g),this.updatingHandles.add((()=>this.fullOpacity),(e=>this._opacityChange(e))),this.updatingHandles.add((()=>this.slicePlaneEnabled),(e=>this._slicePlaneEnabledChange(e))),this.updatingHandles.add((()=>this.elevationOffset),((e,t)=>{this._reloadAll(t),this._controller.invalidateVisibilityObbs()})),this.updatingHandles.add((()=>this.elevationInfo),((e,t)=>this._elevationInfoChanged(e,t)),g),this.updatingHandles.add((()=>this.contentVisible&&this.elevationInfo.mode!==Bt.Absolute),((e,t)=>{e?this.handles.add(this.view.basemapTerrain.on("elevation-change",(({extent:e})=>this._ensureElevationTask().addExtent(e))),Kt):t&&this.handles.remove(Kt)}),g),this.updatingHandles.add((()=>this._usePBR),(e=>this._updatePBR(e)));const a=()=>{this._reloadAll(),this.clearMemCache()};this.updatingHandles.add((()=>this.rendererTextureUsage),a),this.updatingHandles.add((()=>this.uncompressedTextureDownsamplingEnabled),a),this.updatingHandles.add((()=>this.contentVisible),(e=>this._contentVisibleChanged(e)),g),this.updatingHandles.add((()=>this.i3slayer.labelsVisible),(()=>this._labelingChanged()),g),this.updatingHandles.add((()=>this.i3slayer.labelingInfo),(()=>this._labelingChanged()),g),this.updatingHandles.add((()=>this._modifications),(()=>this._modificationsChanged()),g),this.handles.add([p((()=>at.I3S_TREE_SHOW_TILES),(e=>{if(e&&!this._treeDebugger){const e=this._controller.crsIndex;import("./support/I3STreeDebugger.js").then((({I3STreeDebugger:t})=>{!this._treeDebugger&&at.I3S_TREE_SHOW_TILES&&(this._treeDebugger=new t({lv:this,view:this.view,nodeSR:e}))}))}else e||at.I3S_TREE_SHOW_TILES||(this._treeDebugger=d(this._treeDebugger))}),g),p((()=>at.I3S_SHOW_MODIFICATIONS),(()=>this._showModifications()),g)]),this._cacheKeySuffix=ze(this.i3slayer.spatialReference,this.view.renderSpatialReference),this._idbCache.init().catch((e=>yt.warn(`Failed to initialize IndexedDB cache: ${e}`)))}destroy(){this._clearAddTasks(),this._elevationTask=d(this._elevationTask),this.i3sOverrides=d(this.i3sOverrides),this._elevationProvider&&(this._elevationProvider.layerChanged(),this.view.elevationProvider.unregister(this._elevationProvider),this._elevationProvider=null),this._intersectionHandler&&(this._stage.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler),this._intersectionHandler=null);const e=this._worker;e&&(e.destroyContext(this.uid).then((()=>e.destroy())),this._worker=null),this._removeAllNodeDataFromStage(),this._memCache=d(this._memCache),this._collection=null,this._stage=null,this._edgeView=null,this._labeler=d(this._labeler),this._treeDebugger=d(this._treeDebugger),this._controller=d(this._controller),this._highlights.destroy(),this._nodeId2Meta.clear(),this._nodeId2MetaReloading.clear(),this._crossfadeHelper=d(this._crossfadeHelper),this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle&&(this._visibleGeometryChangedSchedulerHandle.remove(),this._visibleGeometryChangedSchedulerHandle=null)}_memEstimateTextureAdded(e){const t=e.memoryEstimate;return this._gpuMemoryEstimate+=t,this._texMemoryEstimate+=t,t}_memEstimateTextureRemoved(e){if(null!=e){const t=e.memoryEstimate;this._gpuMemoryEstimate-=t,this._texMemoryEstimate-=t}}_memEstimateGeometryAdded(e){const t=this._collection.getObjectGPUMemoryUsage(e);return this._gpuMemoryEstimate+=t,this._geoMemoryEstimate+=t,t}_memEstimateGeometryRemoved(e){const t=this._collection.getObjectGPUMemoryUsage(e);this._gpuMemoryEstimate-=t,this._geoMemoryEstimate-=t}isNodeLoaded(e){return this._nodeId2Meta.has(e)}isNodeReloading(e){return this._nodeId2MetaReloading.has(e)}get usedMemory(){let e=null!=this._labeler?this._labeler.usedMemory:0;return this._nodeId2Meta.forEach((t=>e+=null!=t?t.node.memory:0)),this._nodeId2MetaReloading.forEach((t=>e+=null!=t?t.node.memory:0)),e}get unloadedMemory(){return(null!=this._controller?this._controller.unloadedMemoryEstimate:0)+(null!=this._labeler?this._labeler.unloadedMemoryEstimate:0)}_labelingChanged(){if(!(Me(this.i3slayer)&&this._supportsLabeling))return void(null!=this._labeler&&(this._labeler.destroy(),this._labeler=null));if(null!=this._labeler)return;const e=new ue({view:this.view,layer:this.i3slayer,collection:this._collection,overrides:this.i3sOverrides});this._nodeId2Meta.forEach((t=>null!=t&&this._addMetaToLabeler(e,t))),this._labeler=e}_loadAsyncModule(e){return++this._asyncModuleLoading,e.then((e=>(--this._asyncModuleLoading,e)),(e=>{throw--this._asyncModuleLoading,e}))}_modificationsChanged(){if(!this._i3sWasmLoaded&&this.hasModifications)return this._i3sWasmLoaded=fe().then((()=>{this._i3sWasmLoaded=!0,this._modificationsChanged(),this.notifyUpdate()})),void this.notifyUpdate();if(!0!==this._i3sWasmLoaded)return;const e=this.uid,t=this.i3slayer.spatialReference;this._worker.setModifications(e,this._layerClippingArea,this._modifications,t);const i=me(this._layerClippingArea,this._modifications,t);be({context:e,modifications:i,isGeodetic:t.isGeographic}),this._controller.modificationsChanged();const s=this.hasModifications?new c:null;this._nodeId2Meta.forEach(((e,t)=>{null==e?(this._nodeId2Meta.delete(t),this._controller.updateLoadStatus(t,!1)):e.node.hasModifications?(this._nodeId2Meta.delete(t),this._nodeId2MetaReloading.set(t,e)):null!=s&&s.push(e.node)})),null!=s&&this._nodeId2MetaReloading.forEach((e=>s.push(e.node))),null!=s&&s.length>0&&(this.updateNodeModificationStatus(s),s.forAll((e=>{if(e.imModificationImpact!==Pe.Culled){const t=this._nodeId2Meta.get(e.index);this._controller.invalidateGeometryVisibility(e.index),null!=t?(this._nodeId2Meta.delete(e.index),this._nodeId2MetaReloading.set(e.index,t)):this._nodeId2Meta.has(e.index)&&(this._nodeId2Meta.delete(e.index),this._controller.updateLoadStatus(e.index,!1))}}))),this.clearMemCache(),this._controller.restartNodeLoading(),this._showModifications()}_showModifications(){if(null!=this._modificationGraphics&&(this.view.graphics.removeMany(this._modificationGraphics),this._modificationGraphics=null),!at.I3S_SHOW_MODIFICATIONS||0===this._modifications.length)return;const e={clip:[227,227,79,.8],mask:[227,139,79,.8],replace:[139,227,79,.8]},t={type:"simple-fill",outline:{color:[255,255,255],width:1}};this._modificationGraphics=new Array;for(const s of this._modifications){const r=s.geometry;r.spatialReference=this.i3slayer.spatialReference;const o={...t,color:e[s.type]};this._modificationGraphics.push(new i({geometry:r,symbol:o}))}this.view.graphics.addMany(this._modificationGraphics)}_addMetaToLabeler(e,t){e.addNodeMeta(t,((e,t)=>this._createAttributes(e,t)))}_contentVisibleChanged(e){e?(this.view.elevationProvider.register(this._elevationContext,this._elevationProvider),this._stage.view.sceneIntersectionHelper.addIntersectionHandler(this._intersectionHandler)):(this._removeAllNodeDataFromStage(),this.view.elevationProvider&&this.view.elevationProvider.unregister(this._elevationProvider),this._stage.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler))}getLoadedAttributes(e){const t=this._nodeId2Meta.get(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.loadedAttributes}getAttributeData(e){const t=this._nodeId2Meta.get(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.attributeData}setAttributeData(e,t){const i=this._nodeId2Meta.get(e);null!=i&&null!=i.attributeInfo&&(i.attributeInfo.attributeData=t,this._attributeValuesChanged(i))}async updateAttributes(e,t,i){const s=this._nodeId2Meta.get(e);null!=s&&(await this.i3sOverrides.applyAttributeOverrides(s.featureIds,t,i),s.attributeInfo=t,this._controller.reschedule((()=>this._attributeValuesChanged(s)),i).catch((e=>{u(e)||yt.warn("Error while updating attribute values. Layer might not display correctly.",e)})))}_attributeValuesChanged(e){e.cachedRendererVersion=this._getInvalidRendererVersion(),e.filteredIds=null,null!=this._labeler&&this._labeler.setNodeMetaAttributes(e,((e,t)=>this._createAttributes(e,t))),this._updateEngineObject(e)}clearMemCache(){null!=this._memCache&&this._memCache.clear()}getVisibleNodes(){const e=new Array;return this._nodeId2Meta.forEach((t=>null!=t&&e.push(t.node))),e}getNodeComponentObb(e){const t=this._nodeId2Meta.get(e.index)??this._nodeId2MetaReloading.get(e.index);return null!=t?this._collection.getComponentObb(t.objectHandle):null}getLoadedNodeIndices(e){this._nodeId2Meta.forEach(((t,i)=>e.push(i))),this._nodeId2MetaReloading.forEach(((t,i)=>e.push(i)))}_preLoadBasis(){!has("disable-feature:i3s-basis")&&0!=(this.supportedTextureEncodings&Oe.Basis)&&h(this.i3slayer.textureSetDefinitions,(e=>e.some((e=>e.formats.some((e=>"basis"===e.format||"ktx2"===e.format))))))&&pt()}_getVertexBufferLayout(e,t){const i={hasTexture:Ft(e.params.material),hasNormals:t.normal,hasRegions:t.uvRegion};return ut(mt(this._getGeometryParameters(i)))}_getObjectIdField(){return this.i3slayer.objectIdField||ie}_getGlobalIdField(){return this.i3slayer.associatedLayer?.globalIdField}_findGraphicNodeAndIndex(e){const t=rt(this.i3slayer.fieldsIndex,e.attributes,this._getObjectIdField());let i=null;return l(this._nodeId2Meta,(e=>{if(null==e)return!1;const s=e.featureIds.indexOf(t);return-1!==s&&(i={node:e.node,index:s},!0)})),i}_getGraphicIndices(e,t){const i=this._nodeId2Meta.get(e.index);if(null==i)return[];const s=[],r=this._getObjectIdField(),o=this.i3slayer.fieldsIndex;for(const a of t){const e=rt(o,a.attributes,r),t=i.featureIds.indexOf(e);-1!==t&&s.push(t)}return s}whenGraphicBounds(e){const t=this._findGraphicNodeAndIndex(e);if(!t)return Promise.reject();const i=this._getAABB(t.node.index,t.index);return null==i?Promise.reject():Promise.resolve({boundingBox:i,screenSpaceObjects:[]})}getAABBFromIntersectorTarget(e){return null==e.nodeIndex||null==e.componentIndex?null:this._getAABB(e.nodeIndex,e.componentIndex)}_getAABB(e,t){const i=this._nodeId2Meta.get(e);if(null==i||null==i.featureIds||t>=i.featureIds.length)return null;const s=i.objectHandle,r=Ae(t,this._collection,s,Y(24),0),o=this.view.renderSpatialReference,a=this.view.spatialReference;if(!G(r,o,0,r,a,0,8))return null;const n=K();return W(n,r,0,8),n}whenGraphicAttributes(e,t){return Ke(this.i3slayer,e,this._getObjectIdField(),t,(()=>[...this._nodeId2Meta.values()].filter(s)))}getGraphicFromIntersectorTarget(e){if(null==e.nodeIndex||null==e.componentIndex)return null;const t=this._nodeId2Meta.get(e.nodeIndex);return null==t||null==t.featureIds||e.componentIndex>=t.featureIds.length?null:this._createGraphic(e.componentIndex,t)}_getCacheKey(e){return`${this._layerUrl}/v${Ct}/${e}${this._cacheKeySuffix}`}_getMemCacheKey(e,t=this.elevationOffset){return e+"#"+t}get _idbCacheEnabled(){return!this._controller.disableIDBCache&&!this.hasModifications&&0===this.elevationOffset&&null!=this._cacheKeySuffix}loadCachedGPUData(e){return null!=this._memCache?this._memCache.pop(this._getMemCacheKey(e)):null}deleteCachedGPUData(e){null!=e&&this._deleteComponentObject(e)}_cacheGPUData(e,t=this.elevationOffset){if(null==this._memCache)return void this._deleteComponentObject(e);const i=this._controller.indexDepth-e.node.level;this._memCache.put(this._getMemCacheKey(e.node.index,t),e,e.node.memory,i)}loadMissingTextures(e,t,i,s){const r=e?.filter(((e,i)=>{if(0==(e.usage&this.rendererTextureUsage))return!1;if(null==t)return!0;const s=Re(e.encodings,this.supportedTextureEncodings),r=t[i];return!!(null==r||null==r.data||s&&r.encoding!==s.encoding)}))??[];return 0===r.length?Promise.resolve(!1):i(r,s).then((i=>{let s=0;for(let r=0;r<e.length;r++)s<i.length&&i[s].id===e[r].id&&(t[r]=i[s],s++);return!0}))}loadCachedNodeData(e,t,i){return this._idbCacheEnabled?this._idbCache.get(this._getCacheKey(e.id),t).then((s=>null==s?null:s.nodeVersion!==e.version?(this._idbCache.remove(this._getCacheKey(e.id)),null):(this.elevationInfo.mode===Bt.Absolute&&(e.geometryObb=s.geometryObb),this.loadMissingTextures(s.requiredTextures,s.textureData,i,t).then((i=>(i&&this._idbCache.initialized&&null!=s.textureData&&(s.byteSize=Ht(s.transformedGeometry,s.textureData),s.textureData.every(Pt)&&Ut(e,s)&&this._idbCache.put(this._getCacheKey(e.id),s).catch((t=>yt.warn(`Failed to update node with textures in IndexedDB cache: ${e.id}: ${t}`)))),_(t),s)))))):Promise.resolve(null)}addNode(e,t,i){return Vt(t)?null==t.geometryBuffer?(this._addNodeMeta(e.index,null),Promise.resolve()):this._addData(e,t.attributeDataInfo,(()=>this._transformNode(e,t,i).then((s=>this._safeReschedule((()=>{if(null==s)return e.hasModifications=!1,this._addCachedNodeData(e,null,i);e.hasModifications=s.transformedGeometry.hasModifications;const{obb:r,componentOffsets:o,featureIds:a,anchorIds:n,anchors:l,transformedGeometry:d}=s,h=this._controller.crsIndex,c=this.view.renderSpatialReference,u=Ge(e.mbs,this.elevationOffset,h,c),_=lt([r.center.x,r.center.y,r.center.z],[r.extents.x,r.extents.y,r.extents.z],w(r.orientation.x,r.orientation.y,r.orientation.z,r.orientation.w));S(_.center,_.center,u),this.elevationInfo.mode===Bt.Absolute&&(e.geometryObb=_),t.geometryData.componentOffsets=o,a&&(t.geometryData.featureIds=Array.from(a)),t.geometryData.anchorIds=n,t.geometryData.anchors=l;const m={nodeVersion:e.version,geometryData:t.geometryData,requiredTextures:t.requiredTextures,textureData:t.textureData,transformedGeometry:d,globalTrafo:u,geometryObb:_,byteSize:Ht(d,t.textureData)};if(this._idbCacheEnabled&&this._idbCache.initialized&&Ut(e,m)){const t=null!=m.textureData?m.textureData.map((e=>Pt(e)?e:null)):null;this._idbCache.put(this._getCacheKey(e.id),{...m,textureData:t}).catch((t=>yt.warn(`Failed to store node in IndexedDB cache: ${e.id}: ${t}`)))}return this._addCachedNodeData(e,m,i)}),i))))):Promise.reject()}getElevationRange(e){let t=1/0,i=-1/0;const s=U(this.view.renderCoordsHelper.spatialReference);return this._nodeId2Meta.forEach((r=>{if(null!=r&&null!=r.node.geometryObb){const o=r.node.geometryObb;if(dt(o,e)){const e=this._collection.getObjectTransform(r.objectHandle),o=this.view.renderCoordsHelper.getAltitude(e.position);for(let a=0;a<r.featureIds.length;a++){const e=this._collection.getComponentAabb(r.objectHandle,a,zt);if("local"===this.view.viewingMode)t=Math.min(t,o+e[2]),i=Math.max(i,o+e[5]);else{t=Math.min(t,o+e[2]);const r=Math.max(Math.abs(e[3]),Math.abs(e[0])),a=Math.max(Math.abs(e[4]),Math.abs(e[1])),n=o+e[5]+s.radius;i=Math.max(i,Math.sqrt(r*r+a*a+n*n)-s.radius)}}}}})),{min:t,max:i}}computeVisibilityObb(e){return We(e,this.view.renderSpatialReference,this._controller.crsIndex,this.i3slayer.spatialReference,this.elevationOffset,this._modifications)}_transformNode(e,t,i){const s=t.geometryData.geometries??[],r=new Array(s.length);for(let g=0;g<s.length;++g)r[g]=this._getVertexBufferLayout(s[g],t.geometryDescriptor);const o=e.mbs,a=this.elevationOffset,n=this._controller.crsIndex,l=this._controller.crsVertex,d=this.view.renderSpatialReference,h=Le(o,a,n),c=Ge(o,a,n,d),u=L(n,l),_=L(l,d);if(null==u||null==_)return Promise.resolve(null);const m={context:this.uid,geometryBuffer:t.geometryBuffer,geometryData:t.geometryData,geometryDescriptor:t.geometryDescriptor,layouts:r,localOrigin:h,globalTrafo:c,mbs:o,obb:e.serviceObb,elevationOffset:a,needNormals:!this._isIntegratedMesh&&this._controller.isMeshPyramid,normalReferenceFrame:this.i3slayer.normalReferenceFrame||"none",indexToVertexProjector:u,vertexToRenderProjector:_};return this._worker.invoke(m,i)}get _supportsNodeCrossFading(){return!this.view?._stage?.renderer.shadowsEnabled}get nodeCrossfadingEnabled(){return this._supportsNodeCrossFading&&(this.lodCrossfadeinDuration>0||this.lodCrossfadeoutDuration>0||this.lodCrossfadeUncoveredDuration>0)}get nodeFadeoutEnabled(){return this._supportsNodeCrossFading&&this.lodCrossfadeoutDuration>0}_setNewNodeOpacity(e){const t=this.nodeCrossfadingEnabled?0:this.fullOpacity;this._setNodeOpacity(e,t)}addCachedGPUData(e,t,i){if(this.elevationInfo.mode===Bt.Absolute&&(e.geometryObb=ht(this._collection.getComponentObb(t.objectHandle))),!this._controller.isGeometryVisible(e))return void this._cacheGPUData(t);null!=this._labeler&&this._addMetaToLabeler(this._labeler,t);const s=e.index;this._addNodeMeta(s,t),this.updateNodeState(s,i),this._collection.setObjectVisibility(t.objectHandle,_t.Visible),this._updateMaterial(t),this._setNewNodeOpacity(t),this.elevationInfo.mode!==Bt.Absolute&&this._ensureElevationTask().schedule(s),this._updateEngineObject(t),this._highlights.objectCreated(t),null!=this._treeDebugger&&this._treeDebugger.update()}addCachedNodeData(e,t,i,s){return this._addData(e,i,(()=>this._addCachedNodeData(e,t,s)))}async deleteCachedNodeData(e){if(this._idbCacheEnabled)return this._idbCache.remove(this._getCacheKey(e))}async _addCachedNodeData(e,t,i){if(!this.contentVisible||!this._controller.isGeometryVisible(e))return void this._removeNodeStageData(e.index,this.elevationOffset,this._nodeId2MetaReloading);if(null==t)return void this._addNodeMeta(e.index,null);const s=this._addTasks.get(e.index),{geometryData:r,transformedGeometry:o,globalTrafo:a}=t;await this.i3sOverrides.applyAttributeOverrides(r.featureIds,s.attributeInfo,i);const n=null!=t.textureData?t.textureData.filter((e=>null!=e&&0!=(e.usage&this.rendererTextureUsage))):[];!has("disable-feature:i3s-basis")&&n.some((e=>null!=e&&(e.encoding===Oe.Basis||e.encoding===Oe.KTX2)))&&await pt(),e.memory=0;const{componentOffsets:l,geometries:d,featureIds:h,anchorIds:c,anchors:u}=r,_=this._collection,m=d[0],{layout:g,indices:p,interleavedVertexData:f,positionData:b,hasColors:y}=o,v=this._materialParameters(m,g),I=l||new Uint32Array([0,p?p.length:f.byteLength/g[0].stride]),w={vertices:{data:f,count:f.byteLength/g[0].stride,layoutParameters:v.geometryParams},positionData:{positions:J(b.data),indices:Z(b.indices)},indices:p,componentOffsets:I},S=m.transformation?E(m.transformation):j();O(S,a,S);const A=x(V(),S),T=M(C(),S),D=this.view.renderSpatialReference,R=this.view.basemapTerrain.spatialReference,N=V(),F=[1,1,1];k(A,D,F,R)||yt.errorOnce("Unsupported coordinate system for IM overlay"),B(A,D,N,R);const P=_.createObject({toMapSpace:H(N[0],N[1],F[0],F[1]),geometry:w,obb:t.geometryObb,transform:{position:A,rotationScale:T}}),U=v.geometryParams.textureCoordinates===gt.Atlas,{textures:G,texturePromise:L}=this._initMaterialAndTextures(P,v.material,n,U);e.memory+=this._memEstimateGeometryAdded(P),e.memory+=G.reduce(((e,t)=>e+(null!=t?this._memEstimateTextureAdded(t):0)),0);const q=!!v.material.hasParametersFromSource,z="blend"!==v.material.alphaMode&&v.material.metallicRoughness.baseColorFactor[3]>=1,K=new It(e,h,P,this._getInvalidRendererVersion(),s.attributeInfo,{hasParametersFromSource:q,isOpaque:z},G,c,u);s.meta=K,!this._hasTextures&&t.requiredTextures?.some((({usage:e})=>0!=(e&Ce.ColorTextures)))&&(this._hasTextures=!0),this._hasData=!0,this._hasColors=this._hasColors||y,this._hasTextures=this._hasTextures||!!e.resources.texture,this.notifyChange("hasTexturesOrVertexColors");const W=this.slicePlaneEnabled;return Promise.all([this._addOrUpdateEdgeRendering(K),L]).then((([t,s])=>(null!=t&&t.updateObjectVisibility(K.objectHandle,!1).catch((e=>Et(e,this.i3slayer.title))),this._safeReschedule((()=>{const i=this._addTasks.get(e.index);if(!i)return;if(this._addNodeMeta(e.index,K),i.meta=null,!this.contentVisible)return void this._removeNodeStageData(e.index,this.elevationOffset);_.setObjectVisibility(P,_t.Visible),null!=t&&t.updateObjectVisibility(K.objectHandle,!0).catch((e=>Et(e,this.i3slayer.title))),K.attributeInfo=i.attributeInfo;const s=K.cachedRendererVersion!==this._rendererVersion,r=W!==this.slicePlaneEnabled;this._updateElevationOffsets(K);const o=K.elevationOffsets;this._updateComponentData(K);const a=this._applyFiltersToNode(K);(s||null!=t&&(r||a||o))&&this._addOrUpdateEdgeRendering(K),null!=this._labeler&&this._addMetaToLabeler(this._labeler,K),this._visibleGeometryChanged(K,jt.ADD),this._highlights.objectCreated(K),this._updateMaterial(K),this._setNewNodeOpacity(K),null!=this._treeDebugger&&this._treeDebugger.update()}),i)))).catch((e=>{throw null!=s.meta&&(this._cacheGPUData(s.meta),s.meta=null),e}))}_addNodeMeta(e,t){if(this._removeNodeStageData(e,this.elevationOffset,this._nodeId2MetaReloading),this._nodeId2Meta.has(e)){yt.error("Removing duplicated node");const t=this._nodeId2Meta.get(e);null!=t&&this._deleteComponentObject(t)}else this._controller.updateLoadStatus(e,!0);null!=t&&(t.lodCrossfadeProgress=null,this.nodeCrossfadingEnabled&&kt(t.cachedEdgeMaterials,0)),this._nodeId2Meta.set(e,t)}_updateElevationOffsets(e){const t=this.view.renderSpatialReference,i=this._controller.crsIndex,s=this.elevationInfo,r=this.view.basemapTerrain,o=r.spatialReference,a=s.mode;if(null==t||null==o||a===Bt.Absolute)return void(e.elevationOffsets=null);const n=this._collection.getObjectTransform(e.objectHandle);e.elevationOffsets=e.elevationOffsets??[];const l=qt,d=zt,h=a===Bt.OnTheGround,c=this.view.renderCoordsHelper,u=e.featureIds.length,_=(()=>{if(e.cachedElevationAnchors)return e.cachedElevationAnchors;const s=Y(3*u);e.cachedElevationAnchors=s;for(let r=0;r<u;r++){const a=3*r,h=e.anchorIds?.indexOf(r)??-1;e.anchors&&h>=0?(A(l,e.anchors[3*h],e.anchors[3*h+1],e.anchors[3*h+2]),T(l,l,e.node.mbs),B(l,i,l,o),s[a]=l[0],s[a+1]=l[1],s[a+2]=c.getAltitude(l)):(this._collection.getComponentAabb(e.objectHandle,r,d,!0),A(l,(d[0]+d[3])/2,(d[1]+d[4])/2,d[2]),D(l,l,n.rotationScale),T(l,l,n.position),s[a+2]=c.getAltitude(l),B(l,t,l,o),s[a]=l[0],s[a+1]=l[1])}return s})(),m=s.offset,g=e.elevationOffsets,p=(e,t)=>{const i=h?_[3*e+2]:0;g[e]=m+(null!=t?t-i:0)};r.getElevations(_,u,p)}_ensureElevationTask(){return null!=this._elevationTask||(this._elevationTask=new Ee(this.view.resourceController.scheduler,(e=>{const t=this._controller.updateElevationChanged(e,this.view.basemapTerrain.spatialReference);return null!=t?t.filterInPlace((e=>null!=this._nodeId2Meta.get(e))):null}),(e=>{const t=this._nodeId2Meta.get(e);this._nodeElevationAlignmentChanged(t)}))),this._elevationTask}_elevationInfoChanged(e,t){const i=e.mode!==Bt.Absolute,s=!!t&&t!==e&&t.mode!==Bt.Absolute;this._intersectionHandler.updateElevationAlignState(i,this.view.state.viewingMode),i&&!s&&this._controller.removeAllGeometryObbs(),this._nodeId2Meta.forEach((e=>this._nodeElevationAlignmentChanged(e)))}_nodeElevationAlignmentChanged(e){null!=e&&(this._updateElevationOffsets(e),this._updateComponentData(e),this._updateEdgeRendering(e),null!=this._labeler&&this._labeler.updateLabelPositions(e),this._updateSnappingSources(e,jt.UPDATE))}_safeReschedule(e,t){return _(t),this._controller.reschedule(e,t)}_materialParameters(e,t){const i=null!=e.params.material?e.params.material:Ne(),s=t.some((e=>"uvRegion"===e.name)),r=t.some((e=>"normalCompressed"===e.name)),o=Ft(i);return{geometryParams:this._getGeometryParameters({hasTexture:o,hasNormals:r,hasRegions:s}),material:i}}_initMaterialAndTextures(e,t,i,s){const r=this._stage.renderView,o=i.map((e=>Fe(e,t,s,r)));this._stage.addMany(o);let a=null;return this._collection.updateMaterial(e,(e=>{a=Ve(e,t,o,i,this.view._stage.renderView.textureRepository,{rendererTextureUsage:this.rendererTextureUsage,usePBR:this._usePBR,isIntegratedMesh:this._isIntegratedMesh,slicePlaneEnabled:this.slicePlaneEnabled,viewSpatialReference:this.view.spatialReference}),this._updateMaterialOverlay(e)})),{textures:o,texturePromise:a}}_getGeometryParameters(e){return{textureCoordinates:e.hasTexture?e.hasRegions?gt.Atlas:gt.Default:gt.None,colors:this._hasVertexColors,normals:e.hasNormals&&!this._isIntegratedMesh}}_addData(e,t,i){let s=this._addTasks.get(e.index);return s?s.attributeInfo=t:(s={...m(),attributeInfo:t,meta:null},this._addTasks.set(e.index,s),i().then(s.resolve,s.reject).then((()=>this._addTasks.delete(e.index))).catch((t=>{throw this._addTasks.delete(e.index),t}))),s.promise}_clearAddTasks(){this._addTasks.forEach((e=>{null!=e.meta&&(this._cacheGPUData(e.meta),e.meta=null)})),this._addTasks.clear()}_clippingAreaChanged(){const e=this.view.renderSpatialReference,t=this.i3slayer.spatialReference,i=Q();this._renderClippingArea=nt(this.view.clippingArea,i,e)?i:null;const s=Q();this._layerClippingArea=nt(this.view.clippingArea,s,t)?s:null,this._filterChange(),this._controller&&this._controller.updateClippingArea(this.view.clippingArea),this._isIntegratedMesh&&this._modificationsChanged()}get hasGeometryFilter(){return!1}_geometryFilterChange(){const e=this.hasGeometryFilter;this._controller.geometryFilterChanged(e),this._applyFilters(e)}_filterChange(){this._applyFilters(this.hasGeometryFilter)}_applyFilters(e){this._filters=this.getFilters(),e?this._controller&&this._controller.requestUpdate():this._nodeId2Meta.forEach((e=>{null!=e&&this._applyFiltersToNode(e)&&(this._addOrUpdateEdgeRendering(e),this._visibleGeometryChanged(e,jt.UPDATE))}))}getFilters(){const e=[],t=this._renderClippingArea;return null!=t&&e.push(((e,i)=>this._boundingRectFilter(e,i,t))),e}addSqlFilter(e,t,i){if(null!=t){const s=t.fieldNames;e.push(((e,r)=>this._sqlFilter(e,r,t,s,i)))}}_sqlFilter(e,t,i,s,r){const o={},a=this._createLayerGraphic(o),n=this.i3slayer.objectIdField,l=t.featureIds,d=null!=t.attributeInfo&&t.attributeInfo.attributeData;s.every((e=>e===n||d&&null!=d[e]))&&$e(e,l,(e=>{o[n]=l[e];for(const i of s)i!==n&&(o[i]=d?Qe(d[i],e):null);try{return i.testFeature(a)}catch(t){return r(t),!1}}))}_boundingRectNodeTest(e,t){return q(e.node.mbs,this._controller.crsIndex,Nt,this.view.renderSpatialReference),Xe(t,Nt)}_boundingRectFeatureTest(e,t,i){return this._collection.getComponentAabb(e.objectHandle,t,wt),$(wt,St),X(i,St)}_boundingRectFilter(e,t,i){const s=this._collection,r=this._boundingRectNodeTest(t,i);if(r===Ye.INSIDE)return;if(r===Ye.OUTSIDE)return void(e.length=0);const o=s.getComponentCount(t.objectHandle);if(o.invisible+o.visible!==t.featureIds.length)return;const a=this._transformClippingArea(At,i,t.objectHandle);$e(e,t.featureIds,(e=>this._boundingRectFeatureTest(t,e,a)))}_transformClippingArea(e,t,i){const s=this._collection.getObjectTransform(i),r=s.position,o=s.rotationScale;return e[0]=(t[0]-r[0])/o[0],e[1]=(t[1]-r[1])/o[4],e[2]=(t[2]-r[0])/o[0],e[3]=(t[3]-r[1])/o[4],e}_addOrUpdateEdgeRendering(e,t=!0){const i=this._edgeView;if(null==i)return Promise.resolve(null);const s=e.objectHandle,r=i.hasObject(s),{hasEdges:o,perFeatureEdgeMaterials:a}=this._getFilteredEdgeMaterials(e),n={hasSlicePlane:this.slicePlaneEnabled};if(o&&r){if(this.nodeCrossfadingEnabled){kt(a,this.getNodeOpacity(e))}return i.updateAllComponentMaterials(s,a,n,t).catch((e=>Et(e,this.i3slayer.title))),i.updateObjectVisibility(s,!0).catch((e=>Et(e,this.i3slayer.title))),i.updateAllVerticalOffsets(s,e.elevationOffsets).catch((e=>Et(e,this.i3slayer.title))),Promise.resolve(i)}return o&&!r?this._collection.addEdges(s,i,a,n).then((t=>(e.edgeMemoryUsage=t,e.node.memory+=t,i.updateAllVerticalOffsets(s,e.elevationOffsets).catch((e=>Et(e,this.i3slayer.title))),i))):(!o&&r&&(e.node.memory-=e.edgeMemoryUsage,e.edgeMemoryUsage=0,i.removeObject(s)),Promise.resolve(null))}_applyFiltersToNode(e){return!!this._applyFiltersToNodeComponents(e)&&(null!=this._labeler&&this._labeler.applyFilterChange(e),!0)}_applyFiltersToNodeComponents(e){const t=this._collection,i=0===t.getComponentCount(e.objectHandle).invisible;if(t.setAllComponentVisibilities(e.objectHandle,"all"),0===this._filters.length)return e.filteredIds=null,!i;if(this._updateCachedFilteredIds(e),e.filteredIds===e.featureIds)return!i;const s=this._computeFilteredComponentIndices(e);return t.setAllComponentVisibilities(e.objectHandle,s),!0}_updateCachedFilteredIds(e){null!=e.filteredIds&&e.appliedFilters===this._filters||(e.filteredIds=this._computeFilteredIds(e),e.appliedFilters=this._filters)}_computeFilteredIds(e){const t=e.featureIds.slice();for(const i of this._filters)if(i(t,e),0===t.length)break;return t.length===e.featureIds.length?e.featureIds:t}_computeFilteredComponentIndices(e){const t=new Array,i=e.filteredIds;return null!=i&&e.featureIds.forEach(((e,s)=>{i[t.length]===e&&t.push(s)})),t}_removeAllNodeDataFromStage(e=this.elevationOffset){this._nodeId2Meta.forEach(((t,i)=>this._removeNodeStageData(i,e))),this._nodeId2MetaReloading.forEach(((t,i)=>this._removeNodeStageData(i,e,this._nodeId2MetaReloading))),this._elevationTask=d(this._elevationTask)}removeNode(e){const t=this.elevationOffset;this._removeNodeStageData(e,t),this._removeNodeStageData(e,t,this._nodeId2MetaReloading),null!=this._elevationTask&&this._elevationTask.remove(e)}_removeNodeStageData(e,t,i=this._nodeId2Meta){i.has(e)&&this._controller.updateLoadStatus(e,!1);const s=i.get(e);null!=s?(this._collection.setObjectVisibility(s.objectHandle,_t.Hidden),null!=this._edgeView&&this._edgeView.hasObject(s.objectHandle)&&this._edgeView.updateObjectVisibility(s.objectHandle,!1).catch((e=>Et(e,this.i3slayer.title))),this._visibleGeometryChanged(s,jt.REMOVE),null!=this._labeler&&this._labeler.removeNodeMeta(s),i.delete(e),this._highlights.objectDeleted(s),i===this._nodeId2Meta?(this._cacheGPUData(s,t),this.nodeCrossfadingEnabled&&this._crossfadeHelper.stopNodeFading(s)):this._deleteComponentObject(s),null!=this._treeDebugger&&this._treeDebugger.update()):i.delete(e)}_deleteComponentObject(e){if(null!=this._edgeView&&this._edgeView.removeObject(e.objectHandle),this._memEstimateGeometryRemoved(e.objectHandle),this._collection.destroyObject(e.objectHandle),e.textures)for(const t of e.textures)this._memEstimateTextureRemoved(t),this._stage.remove(t)}updateNodeState(e,t){const i=this._nodeId2Meta.get(e);null!=i&&this._collection.updateMaterial(i.objectHandle,(e=>e.polygonOffsetEnabled=t===He.Hole))}updateNodeIndex(e,t){if(this._nodeId2Meta.has(e)){const i=this._nodeId2Meta.get(e);this._nodeId2Meta.delete(e),this._nodeId2Meta.set(t,i)}const i=this._nodeId2MetaReloading.get(e);i&&(this._nodeId2MetaReloading.delete(e),this._nodeId2MetaReloading.set(t,i))}_invalidateAllSymbols(){this._rendererVersion=Je(this._rendererVersion,1),this._controller&&this._controller.requestUpdate()}_getInvalidRendererVersion(){return Je(this._rendererVersion,-1)}async _rendererChange(e){if(this._currentRenderer=e,this.notifyChange("rendererTextureUsage"),this._rendererVersion=Je(this._rendererVersion,1),this._rendererFields=null,this._colorVariable=null,this._opacityVariable=null,this._invalidateAllSymbols(),e&&(this._rendererFields=await e.getRequiredFields(this.i3slayer.fieldsIndex)),this._updateSymbologyFields(),!this._arcade&&e&&"arcadeRequired"in e&&e.arcadeRequired&&(this._arcade=await le()),e&&"visualVariables"in e&&e.visualVariables)for(const t of e.visualVariables)"color"===t.type?this._colorVariable=t:"opacity"===t.type?this._opacityVariable=t:yt.warn(`Unsupported visual variable type for 3D Object Scene Services: ${t.type}`);if(e)for(const t of e.getSymbols())"mesh-3d"!==t.type&&yt.error(`Symbols of type '${t.type}' are not supported for 3D Object Scene Services.`);this._controller&&this._controller.requestUpdate()}_getCachedEdgeMaterials(e){return this._hasComponentData&&e.cachedRendererVersion!==this._rendererVersion&&this._updateCachedRendererData(e),e.cachedEdgeMaterials}_getComponentParameters(e){this._hasComponentData&&e.cachedRendererVersion!==this._rendererVersion&&this._updateCachedRendererData(e);const t=e.cachedSymbology;return(i,s)=>{const r=5*i;if(P(s.externalColor,t[r]/255,t[r+1]/255,t[r+2]/255,t[r+3]/255),null!=this._stage.renderView.objectAndLayerIdRenderHelper){const t=e.featureIds[i],r=de(this.view.map,this.layerUid);this._stage.renderView.objectAndLayerIdRenderHelper.setUidToObjectAndLayerId(t,t,this.layerId,this.layerUid+"_"+this.sublayerId,this.layerPopupEnabledAndHasTemplate&&!r,e.node.resources.attributes,i,this.sublayerId),s.objectAndLayerIdColor=this._stage.renderView.getObjectAndLayerIdColor({graphicUid:t,layerUid:this.layerUid+"_"+this.sublayerId})}s.externalColorMixMode=t[r+4]&(1<<Mt.CastShadows)-1,s.castShadows=0!=(t[r+4]&1<<Mt.CastShadows),s.pickable=0!=(t[r+4]&1<<Mt.Pickable),s.elevationOffset=e.elevationOffsets?.[i]??0}}_getSymbolInfo(e,t){const i=e&&e.getSymbol(t,{arcade:this._arcade});if(!(i instanceof he))return null;const s=i.id;if(this._symbolInfos.has(s))return this._symbolInfos.get(s);const r=Ze(i);return this._symbolInfos.set(s,r),r}_setSymbologyOverride(e,t){this._symbologyOverride!==e&&(this._symbologyOverride=e,this._symbologyOverrideFields=t,this._invalidateAllSymbols(),this._updateSymbologyFields())}_updateSymbologyFields(){this._symbologyFields=null!=this._symbologyOverrideFields&&this._symbologyOverrideFields.length>0?null!=this._rendererFields&&this._rendererFields.length>0?re(this.i3slayer.fieldsIndex,[...this._rendererFields,...this._symbologyOverrideFields]):this._symbologyOverrideFields:this._rendererFields}_updateCachedRendererData(e){if(e.cachedRendererVersion=this._rendererVersion,!this._hasComponentData)return;const t=this._tmpAttributeOnlyGraphic,i={};t.attributes=i;const s=this._currentRenderer,r=e.attributeInfo?.attributeData,o=null!=e.featureIds?this.i3slayer.objectIdField:null,a=null!=r&&null!=this._symbologyFields&&this._symbologyFields.length>0;let n=null,l=null;if(a&&null!=this._symbologyFields){n=[],l=[];for(const e of this._symbologyFields){const t=r[e];t&&(n.push(e),l.push(t))}}e.cachedSymbology||(e.cachedSymbology=te(5*e.featureIds.length));const d={color:Dt,castShadows:!0,pickable:!0,colorMixMode:ot.Multiply,edgeMaterial:null},h=this.fullOpacity,c=this.nodeCrossfadingEnabled?this.getNodeOpacity(e):h;let u=null,_=ft.OPAQUE,m=et,g=0;for(let p=0;p<e.featureIds.length;p++){if(null!=o&&(i[o]=e.featureIds[p]),a&&n)for(let e=0;e<n.length;e++)i[n[e]]=Qe(l[e],p);const r=s?this._getSymbolInfo(s,t):null;let h=null,f=null;if(s&&"visualVariables"in s){if(this._colorVariable){const e=ae(this._colorVariable,t,{color:Rt,arcade:this._arcade});e&&(h=Dt,h[0]=e.r/255,h[1]=e.g/255,h[2]=e.b/255,this._opacityVariable||null===e.a||(f=e.a))}this._opacityVariable&&(f=ne(this._opacityVariable,t,{arcade:this._arcade}))}if(r&&r.material){const e=r.material;h=null==h||null==f?Ie(h,f,e.color,e.alpha,vt,Dt):Ie(h,f,null,null,vt,Dt)}if(null==h&&(h=Dt,h[0]=1,h[1]=1,h[2]=1,h[3]=1),d.pickable=!0,d.castShadows=!r||r.castShadows,d.colorMixMode=r&&r.material?r.material.colorMixMode:ot.Multiply,d.edgeMaterial=r?r.edgeMaterial:null,null!=this._symbologyOverride&&(d.color=h,this._symbologyOverride(t,d),h=d.color),null!=d.edgeMaterial){const t=h[3]<=0?ft.INVISIBLE:h[3]>=1&&(e.material.isOpaque||d.colorMixMode===ot.Replace)?ft.OPAQUE:ft.TRANSPARENT;d.edgeMaterial===u&&t===_||(m={...d.edgeMaterial,opacity:c,objectTransparency:t},u=d.edgeMaterial,_=t),e.cachedEdgeMaterials[p]=m}else e.cachedEdgeMaterials[p]=et;e.cachedSymbology[g++]=Math.round(255*h[0]),e.cachedSymbology[g++]=Math.round(255*h[1]),e.cachedSymbology[g++]=Math.round(255*h[2]),e.cachedSymbology[g++]=Math.round(255*h[3]),e.cachedSymbology[g++]=d.colorMixMode|+d.castShadows<<Mt.CastShadows|+d.pickable<<Mt.Pickable}}_getFilteredEdgeMaterials(e){const t=this._getCachedEdgeMaterials(e);this.nodeCrossfadingEnabled||kt(t,this.fullOpacity);const i=e.filteredIds;if(null==i){return{hasEdges:t.some((e=>e!==et)),perFeatureEdgeMaterials:t}}let s=0,r=!1;const o=t.map(((t,o)=>e.featureIds[o]!==i[s]?et:(r=r||t!==et,s++,t)));return{hasEdges:r,perFeatureEdgeMaterials:o}}_updateComponentData(e){if(!this._hasComponentData)return;const t=e.objectHandle,i=this._getComponentParameters(e);this._collection.setComponentData(t,i),this._stage.renderView.requestRender()}_reloadAll(e=this.elevationOffset){this._removeAllNodeDataFromStage(e),null!=this._controller&&this._controller.restartNodeLoading()}_opacityChange(e){this.nodeCrossfadingEnabled&&this._crossfadeHelper.stopAllNodeFading(),this._nodeId2Meta.forEach((t=>{null!=t&&(this._collection.updateMaterial(t.objectHandle,(t=>t.objectOpacity=e)),kt(t.cachedEdgeMaterials,e),this._updateEdgeRendering(t))}))}_updateMaterial(e){this._collection.updateMaterial(e.objectHandle,(e=>{e.commonMaterialParameters.hasSlicePlane=this.slicePlaneEnabled,e.usePBR=this._usePBR,this._updateMaterialOverlay(e)}))}_updateMaterialOverlay(e){}_updateEngineObject(e){this._updateComponentData(e),this._applyFiltersToNode(e),this._addOrUpdateEdgeRendering(e),this._visibleGeometryChanged(e,jt.UPDATE)}_slicePlaneEnabledChange(e){this._intersectionHandler&&(this._intersectionHandler.slicePlaneEnabled=e),null!=this._labeler&&(this._labeler.slicePlaneEnabled=e),this._nodeId2Meta.forEach((t=>{null!=t&&(this._collection.updateMaterial(t.objectHandle,(t=>t.commonMaterialParameters.hasSlicePlane=e)),this._updateEdgeRendering(t,!1))}))}_updatePBR(e){this._nodeId2Meta.forEach((t=>{null!=t&&this._collection.updateMaterial(t.objectHandle,(t=>t.usePBR=e))})),this._hasLoadedPBRTextures=!0}get _usePBR(){return!this._isIntegratedMesh&&this.view.qualitySettings.physicallyBasedRenderingEnabled}_updateEdgeRendering(e,t=!0){null!=this._edgeView&&this._edgeView.hasObject(e.objectHandle)&&this._addOrUpdateEdgeRendering(e,t)}_forAllNodes(e){this._nodeId2Meta.forEach(e)}_ignoreClientNodeOverriddenFeatures(e){return this.i3sOverrides.hasGeometryChanges?e:(t,i,s)=>s.node.index>=0&&this.i3sOverrides.featureHasGeometryChanges(t)?ge.CONTINUE:e(t,i,s)}_forAllFeatures(e,t,i){l(this._nodeId2Meta,(s=>{if(null==s)return!1;if(null!=t){switch(t(s)){case ge.EXIT:return!0;case ge.SKIP:return!1}}let r=ge.CONTINUE;switch(i){case pe.ALL:r=this._forAllFeaturesOfNode(s,e);break;case pe.VISIBLE_ONLY:r=this._forAllVisibleFeaturesOfNode(s,e);break;case pe.QUERYABLE:r=this._forAllQueryableFeaturesOfNode(s,e)}return r===ge.EXIT}))}_forAllFeaturesOfNode(e,t){let i=ge.CONTINUE;const s=e.featureIds;for(let r=0;r<s.length;r++)if(i=t(s[r],r,e),i===ge.EXIT)return i;return i}_forAllVisibleFeaturesOfNode(e,t){let i=ge.CONTINUE;const s=e.featureIds;return this._collection.forEachVisibleComponent(e.objectHandle,(r=>(i=t(s[r],r,e),i===ge.CONTINUE))),i}_forAllQueryableFeaturesOfNode(e,t){const i=this._ignoreClientNodeOverriddenFeatures(t);if(null==this._renderClippingArea)return this._forAllFeaturesOfNode(e,i);const s=this._boundingRectNodeTest(e,this._renderClippingArea);if(s===Ye.OUTSIDE)return ge.CONTINUE;if(s===Ye.INSIDE)return this._forAllFeaturesOfNode(e,i);const r=ge.CONTINUE,o=e.featureIds,a=e.objectHandle,n=tt(this._renderClippingArea,this._collection.getObjectTransform(a));for(let l=0;l<o.length;l++){if(!this._boundingRectFeatureTest(e,l,n))continue;const t=i(o[l],l,e);if(t===ge.EXIT)return t}return r}_createAttributes(e,t){const i={};null!=t.featureIds&&(i[this._getObjectIdField()]=t.featureIds[e]);const s=t.attributeInfo?.attributeData;if(null!=s)for(const r of Object.keys(s))i[r]=Qe(s[r],e);return i}_createGraphic(e,t){return this._createLayerGraphic(this._createAttributes(e,t))}highlight(e){const t=this._highlights;if("number"==typeof e||e instanceof i?e=[e]:e instanceof a&&(e=e.toArray()),Array.isArray(e)&&e.length>0){if(e[0]instanceof i){const i=e,s=this.i3slayer.fieldsIndex,r=this._getObjectIdField(),o=i.map((e=>rt(s,e.attributes,r))),{set:a,handle:n}=t.acquireSet();return t.setFeatureIds(a,o),n}if("number"==typeof e[0]){const i=e,{set:s,handle:r}=t.acquireSet();return t.setFeatureIds(s,i),r}}return Lt}resetHighlights(){d(this._highlights),this._highlights=new xe({collection:this._collection,forAllFeatures:e=>this._forAllFeatures(e,null,pe.ALL),forAllFeaturesOfNode:(e,t)=>this._forAllFeaturesOfNode(e,t)})}_visibleGeometryChanged(e,t){this._elevationProvider&&(this._elevationProvider.objectChanged(e.node),null==this._visibleGeometryChangedSchedulerHandle&&(this._visibleGeometryChangedSchedulerHandle=f((()=>{this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=null}))),this._updateSnappingSources(e,t))}get performanceInfo(){const e={displayedNumberOfFeatures:0,maximumNumberOfFeatures:0,totalNumberOfFeatures:0,core:null,index:0,nodes:this._nodeId2Meta.size,"Total GPU Memory Estimate":(this._gpuMemoryEstimate/1048576).toFixed(1)+"MB","Geometry Memory Estimate":(this._geoMemoryEstimate/1048576).toFixed(1)+"MB","Texture Memory Estimate":(this._texMemoryEstimate/1048576).toFixed(1)+"MB","Unloaded Memory Estimate":(this.unloadedMemory/1048576).toFixed(1)+"MB"};return null!=this._memCache&&(e.MemCache=Math.round(100*this._memCache.hitRate)+"% hit"),this._controller&&(this._idbCacheEnabled&&(e.IDBCache=Math.round(100*this._idbCache.getHitRate())+"% hit"),this._controller.updateStats(e)),e}get test(){const e=this;return{controller:this._controller,labeler:this._labeler,get visibleObjectIds(){const t=[];return e._forAllFeatures((e=>(t.push(e),ge.CONTINUE)),null,pe.VISIBLE_ONLY),t.sort(((e,t)=>e-t)),t},get numNodes(){return e._nodeId2Meta.size},get loadedNodes(){return Array.from(e._nodeId2Meta.keys()).sort(((e,t)=>e-t))}}}getNodeOpacityByIndex(e){const t=this._nodeId2Meta.get(e);return this.getNodeOpacity(t)}getNodeOpacity(e){return null!=e?this._collection.getMaterial(e.objectHandle).objectOpacity:0}isNodeFullyFadedIn(e){return this._crossfadeHelper.isNodeFullyFadedIn(e)}getNodeCrossfadeMetaData(e){return this._nodeId2Meta.get(e)}markNodeToRemove(e){this._controller&&this._controller.markNodeToRemove(e)}removeMarkedNodes(){this._controller&&this._controller.removeMarkedNodes()}foreachCrossfadeNode(e){this._nodeId2Meta.forEach(((t,i)=>e(i,t)))}fadeNode(e,t,i){if(!this.nodeCrossfadingEnabled)return;const s=this._nodeId2Meta.get(e);null!=s&&this._crossfadeHelper.fadeNode(e,s,t,i)}setNodeOpacityByIndex(e,t){const i=this._nodeId2Meta.get(e);null!=i&&this._setNodeOpacity(i,t)}_setNodeOpacity(e,t){this._collection.updateMaterial(e.objectHandle,(e=>e.objectOpacity=t)),this._setNodeEdgeOpacity(e,t)}_setNodeEdgeOpacity(e,t){if(null==this._edgeView||!e.cachedEdgeMaterials)return;kt(e.cachedEdgeMaterials,t);const i=e.objectHandle;this._edgeView.hasObject(i)&&this._edgeView.updateAllComponentOpacities(i,t).catch((e=>Et(e,this.i3slayer.title)))}get hasModifications(){return this._isIntegratedMesh&&null!=this._layerClippingArea||this._modifications&&this._modifications.length>0}updateNodeModificationStatus(e){const t=e.length;if(!this.hasModifications||t<=0||!0!==this._i3sWasmLoaded)return;const i=this.uid,s=Gt(e);if(null!=s){const t={context:i,buffer:s.buffer};ye(t);const r=new Float64Array(s.buffer);e.forAll(((e,t)=>{const i=r[t],s=ve(i);e.imModificationImpact=s,s!==Pe.Unmodified&&this._controller.invalidateGeometryVisibility(e.index)}))}}notifyUpdate(){this.notifyChange("updating")}notifyLODUpdate(){this._controller.notifyLODUpdate()}isUpdating(){return!(!this._controller||!this._controller.updating)||!!this._visibleGeometryChangedSchedulerHandle||null!=this._labeler&&this._labeler.updating||this._crossfadeHelper?.updating||this._i3sWasmLoaded instanceof Promise||this._asyncModuleLoading>0||null!=this._elevationTask&&this._elevationTask.running}trackSnappingSources(e){const t={events:e,fetchEdgeLocations:async(e,t,i)=>{const s=this._nodeId2Meta.get(e);if(null==s)throw new Error("invalid-node");const{origin:r,buffer:o}=await this._collection.extractEdgeInformation(s.objectHandle,t,i);return this._snappingLocationsApplyElevation(s,o,r),{type:"components",objectIds:s.featureIds,locations:o,origin:r}},remove:()=>{r(this._snappingSourcesTrackers,t)}};return this._snappingSourcesTrackers.push(t),this._nodeId2Meta.forEach(((t,i)=>{if(null==t)return;const s=this._controller.getRenderMbs(t.node);null!=s&&e.add(i,s)})),t}_snappingLocationsApplyElevation(e,t,i){if(!e.elevationOffsets||this.elevationInfo.mode===Bt.Absolute)return;const s=t.position0,r=t.position1,o=t.componentIndex,a=V(),n=V(),l=(e,t)=>{T(e,e,i),this.view.renderCoordsHelper.worldUpAtPosition(e,n),T(e,e,N(n,n,t)),F(e,e,i)};for(let d=0;d<s.count;d++){const t=e.elevationOffsets[o.get(d)];s.getVec(d,a),l(a,t),s.setVec(d,a),r.getVec(d,a),l(a,t),r.setVec(d,a)}}_updateSnappingSources(e,t){const{index:i}=e.node,s=this._controller.getRenderMbs(e.node);if(null!=s)for(const r of this._snappingSourcesTrackers)t!==jt.REMOVE&&t!==jt.UPDATE||r.events.remove(i),t!==jt.ADD&&t!==jt.UPDATE||r.events.add(i,s)}};return e([v()],o.prototype,"_hasLoadedPBRTextures",void 0),e([v()],o.prototype,"_asyncModuleLoading",void 0),e([v()],o.prototype,"_visibleGeometryChangedSchedulerHandle",void 0),e([v()],o.prototype,"view",void 0),e([v()],o.prototype,"i3slayer",void 0),e([v()],o.prototype,"_controller",void 0),e([v()],o.prototype,"_labeler",void 0),e([v()],o.prototype,"updating",void 0),e([v()],o.prototype,"suspended",void 0),e([v()],o.prototype,"contentVisible",null),e([v({readOnly:!0})],o.prototype,"legendEnabled",null),e([v()],o.prototype,"holeFilling",void 0),e([v(ct)],o.prototype,"updatingProgress",void 0),e([v()],o.prototype,"updatingProgressValue",null),e([v()],o.prototype,"hasTexturesOrVertexColors",null),e([v()],o.prototype,"rendererTextureUsage",null),e([v()],o.prototype,"elevationOffset",null),e([v()],o.prototype,"elevationInfo",null),e([v({type:Boolean})],o.prototype,"slicePlaneEnabled",void 0),e([v()],o.prototype,"supportedTextureEncodings",null),e([v()],o.prototype,"uncompressedTextureDownsamplingEnabled",null),e([v({type:[oe]})],o.prototype,"_modifications",void 0),e([v({readOnly:!0})],o.prototype,"clientGeometry",null),e([v()],o.prototype,"_elevationTask",void 0),e([v({readOnly:!0})],o.prototype,"_usePBR",null),o=e([I(bt)],o),o};function Et(e,t){u(e)||yt.warn("Error while processing edges. Edges on this layer might not display correctly",t,e)}var jt;!function(e){e[e.ADD=0]="ADD",e[e.REMOVE=1]="REMOVE",e[e.UPDATE=2]="UPDATE"}(jt||(jt={}));const wt=z(),St=Q(),At=Q(),Tt=lt(),Dt=[0,0,0,0],Rt=new t([0,0,0,0]),Nt=ee(0,0,0,0);function Ft(e){if(null==e)return!1;const t=e.metallicRoughness;return t&&t.baseColorTextureId>=0||t&&t.metallicRoughnessTextureId>=0||e.normalTextureId>=0||e.emissiveTextureId>=0||e.occlusionTextureId>=0}function Vt(e){return"geometryData"in e}function Pt(e){return null!=e&&b(e.data)}function Ht(e,t){let i=1024+e.interleavedVertexData.byteLength+(e.indices?e.indices.byteLength:0)+e.positionData.data.byteLength+e.positionData.indices.byteLength;if(null!=t)for(const s of t)null!=s&&b(s.data)&&(i+=s.data.byteLength);return i}function Ut(e,t){return t.byteSize>Ot?(yt.warn(`Node is too big to store in IndexedDB cache: ${e.id} (${t.byteSize} bytes)`),!1):t.byteSize>0}function Gt(e){if(0===e.length)return null;const t=10*e.length,i=new Float64Array(t);return e.forAll(((e,t)=>{let s=e.serviceObb;null==s&&(s=Tt,R(s.center,e.mbs),s.halfSize[0]=s.halfSize[1]=s.halfSize[2]=e.mbs[3]);const r=10*t;i[r]=s.center[0],i[r+1]=s.center[1],i[r+2]=s.center[2],i[r+3]=s.halfSize[0],i[r+4]=s.halfSize[1],i[r+5]=s.halfSize[2],i[r+6]=s.quaternion[0],i[r+7]=s.quaternion[1],i[r+8]=s.quaternion[2],i[r+9]=s.quaternion[3]})),i}const Lt={remove(){},pause(){},resume(){}};function kt(e,t){e.forEach((e=>e.opacity=t))}var Bt;!function(e){e[e.Absolute=0]="Absolute",e[e.RelativeToGround=1]="RelativeToGround",e[e.OnTheGround=2]="OnTheGround"}(Bt||(Bt={}));const qt=V(),zt=z(),Kt="elevation-change";function Wt(e){return t=>{if(e.immediate)return e.immediate.schedule(t);throw console.error("Error no immediate schudler"),new Error("cant find immediate scheduler")}}export{Bt as ElevationMode,xt as I3SMeshView3D};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.27/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Graphic.js";import{binaryIndexOf as r}from"../../../core/arrayUtils.js";import i from"../../../core/Logger.js";import{destroyMaybe as s}from"../../../core/maybe.js";import{initial as o,watch as a}from"../../../core/reactiveUtils.js";import{estimateSize as n}from"../../../core/typedArrayUtil.js";import{property as l}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as d}from"../../../core/accessorSupport/decorators/subclass.js";import{s as u}from"../../../chunks/vec3.js";import{c as h}from"../../../chunks/vec3f64.js";import{projectBuffer as c,projectVectorToVector as p}from"../../../geometry/projection.js";import{extentContainsCoords3D as g,extentContainsCoords2D as m}from"../../../geometry/support/contains.js";import{newDoubleArray as y,doubleArrayFrom as f}from"../../../geometry/support/DoubleArray.js";import{getGeometryZScaler as _}from"../../../geometry/support/zscale.js";import{fallbackObjectIDAttribute as b}from"../../../layers/LayerConstants.js";import{makeDehydratedPoint as v,estimateSize as E}from"../../../layers/graphics/dehydratedFeatures.js";import{hydrateGraphic as x}from"../../../layers/graphics/hydratedFeatures.js";import I from"../../../layers/graphics/controllers/I3SOnDemandController.js";import w from"../../../layers/support/FeatureFilter.js";import N from"../../../rest/support/Query.js";import{I3SPointsWorkerHandle as O}from"./I3SPointsWorkerHandle.js";import{LayerView3D as C}from"./LayerView3D.js";import F from"./graphics/Graphics3DFeatureProcessor.js";import{QueryEngine as D}from"./graphics/QueryEngine.js";import{createInteractiveEditSession as j,processAttributeEdits as S}from"./i3s/featureEditing.js";import{I3SGraphicsMap as G}from"./i3s/I3SGraphicsMap.js";import{I3SOverrides as A}from"./i3s/I3SOverrides.js";import{checkRecyclable as L,checkSpatialReferences as P,containsDraco as V,whenGraphicAttributes as M,getCachedAttributeValue as R}from"./i3s/I3SUtil.js";import{DefinitionExpressionSceneLayerView as H}from"./support/DefinitionExpressionSceneLayerView.js";import{defineFieldProperties as q}from"./support/fieldProperties.js";import{PopupSceneLayerView as U}from"./support/PopupSceneLayerView.js";import{SceneLayerViewRequiredFields as Q}from"./support/SceneLayerViewRequiredFields.js";import T from"../support/debugFlags.js";import{compute as B}from"../support/orientedBoundingBox.js";import{updatingProgress as k}from"../support/updatingProperties.js";import{Attribute as z}from"../webgl-engine/lib/Attribute.js";import{UpdatePolicy as W}from"../webgl-engine/lib/UpdatePolicy.js";import Z from"../../layers/SceneLayerView.js";import{hasPopupTemplate as K}from"../../layers/support/popupUtils.js";import{TaskPriority as Y}from"../../support/Scheduler.js";const $=q();class J{constructor(e,t,r,i){this.graphics=e,this.featureIds=t,this.attributeInfo=r,this.node=i}}let X=class extends(H(U(C(Z)))){constructor(){super(...arguments),this.type="scene-layer-graphics-3d",this._queryEngine=null,this._memCache=null,this._interactiveEditingSessions=new Map,this.loadedGraphics=new G(((e,t,r)=>ie(e,t,r)),(e=>this.processor.graphicsCore.recreateGraphics(e))),this.holeFilling="always",this.progressiveLoadFactor=1,this.supportsHeightUnitConversion=!0,this._coordinatesOutsideExtentErrors=0,this._maxCoordinatesOutsideExtentErrors=20}tryRecycleWith(e,t){return e.url===this.layer.url&&this._i3sOverrides.isEmpty?e.load(t).then((()=>{L(this.layer,e,this._i3sOverrides),this.layer=e,this._i3sOverrides.destroy();const t=this.view.resourceController?.memoryController;this._i3sOverrides=new A({view:this.view,layer:e,memoryController:t}),s(this._queryEngine),this._setupQueryEngine(),this.processor.resetObjectStates()})):null}initialize(){this.addResolvingPromise(this.layer.indexInfo);const e=this.view.resourceController?.memoryController;this._i3sOverrides=new A({view:this.view,layer:this.layer,memoryController:e}),P(this.layer,this.view.spatialReference,this.view.viewingMode),this._fieldsHelper=new Q({layerView:this}),this.updatingHandles.add((()=>this.layer.rangeInfos),(e=>this._rangeInfosChanged(e)),o),this.updatingHandles.add((()=>this.layer.renderer),((e,t)=>this._rendererChange(e,t))),this.updatingHandles.add((()=>[this.parsedDefinitionExpression,this._excludeObjectIdsSorted]),(()=>this._filterChange())),this.handles.add(a((()=>T.I3S_TREE_SHOW_TILES),(e=>{if(e&&!this._treeDebugger){const e=this._controller.crsIndex;import("./support/I3STreeDebugger.js").then((({I3STreeDebugger:t})=>{!this._treeDebugger&&T.I3S_TREE_SHOW_TILES&&(this._treeDebugger=new t({lv:this,view:this.view,nodeSR:e}))}))}else e||!this._treeDebugger||T.I3S_TREE_SHOW_TILES||(this._treeDebugger.destroy(),this._treeDebugger=null)}),o)),this._set("processor",new F({owner:this,preferredUpdatePolicy:W.ASYNC,scaleVisibilityEnabled:!0,filterVisibilityEnabled:!0,timeExtentEnabled:!1,frustumVisibilityEnabled:!1,elevationAlignmentEnabled:!0,elevationFeatureExpressionEnabled:!1,setUidToIdOnAdd:!1,dataExtent:this.layer.fullExtent,updateClippingExtent:e=>this._updateClippingExtent(e)})),this.processor.elevationAlignment?.events.on("invalidate-elevation",(e=>this._controller.updateElevationChanged(e.extent,e.spatialReference))),this.supportsHeightUnitConversion&&(this._verticalScale=_("point",this.layer.spatialReference,this.view.spatialReference)),this.addResolvingPromise(this.processor.initializePromise),this._memCache=this.view.resourceController.memoryController.newCache(`psl-${this.uid}`),this._controller=new I({layerView:this,scaleVisibilityEnabled:!1}),V(this.layer.geometryDefinitions)&&(this._worker=new O((e=>this.view.resourceController.immediate.schedule(e)))),this.handles.add(this.layer.on("apply-edits",(e=>this.updatingHandles.addPromise(e.result)))),this.handles.add(this.layer.on("edits",(e=>this._handleEdits(e)))),this.when((()=>{this._setupQueryEngine(),this.updatingHandles.add((()=>this.maximumNumberOfFeatures),(e=>this._controller.featureTarget=e),o),this.updatingHandles.add((()=>this.suspended),(e=>{e&&this._removeAllNodeData()}))}))}destroy(){this._treeDebugger=s(this._treeDebugger),this._i3sOverrides=s(this._i3sOverrides),this._set("processor",s(this.processor)),this._controller=s(this._controller),this._queryEngine=s(this._queryEngine),this._worker=s(this._worker),this._memCache=s(this._memCache),this.loadedGraphics.clear(),this._fieldsHelper=s(this._fieldsHelper)}get i3slayer(){return this.layer}get updatingProgressValue(){return this._controller?.updatingProgress??1}get requiredFields(){return this._fieldsHelper?.requiredFields??[]}get maximumNumberOfFeatures(){const e=this.processor?.graphicsCore?.displayFeatureLimit;return e?.maximumNumberOfFeatures??0}set maximumNumberOfFeatures(e){null!=e?(this._override("maximumNumberOfFeatures",e),this._controller.fixedFeatureTarget=!0):(this._clearOverride("maximumNumberOfFeatures"),this._controller.fixedFeatureTarget=!1)}get maximumNumberOfFeaturesExceeded(){return!this.suspended&&(!!this._controller?.useMaximumNumberOfFeatures&&!this._controller.leavesReached)}get _excludeObjectIdsSorted(){const e=this.layer.excludeObjectIds;return e.length?e.toArray().sort(((e,t)=>e-t)):null}get lodFactor(){return"Labels"===this.layer.semantic?1:this.view.qualitySettings.sceneService.point.lodFactor}get hasM(){return!1}get hasZ(){return!0}get contentVisible(){return!this.suspended&&!!this._controller?.rootNodeVisible}get legendEnabled(){return this.contentVisible&&!0===this.i3slayer?.legendEnabled}async whenGraphicAttributes(e,t){return M(this.layer,e,this._getObjectIdField(),t,(()=>[...this.loadedGraphics.nodes()]))}getHit(e){if(!this.loadedGraphics)return null;const t=x(this.loadedGraphics.find((t=>t.uid===e)),this.layer),r=this._getObjectIdField();return t&&t.attributes&&t.attributes[r]?(t.layer=this.layer,t.sourceLayer=this.layer,{type:"graphic",graphic:t,layer:t.layer}):null}whenGraphicBounds(e,t){return this.processor.whenGraphicBounds(e,t)}computeAttachmentOrigin(e,t){return this.processor.computeAttachmentOrigin(e,t)}isUpdating(){return!!(this._controller?.updating||this.processor?.updating||this._fieldsHelper?.updating||this.layerFilterUpdating)}highlight(e){return this.processor.highlight(e,this.layer.objectIdField)}get updatePolicy(){return this.processor.graphicsCore.effectiveUpdatePolicy}createInteractiveEditSession(e){return j(this._attributeEditingContext,e)}async _decompressBinaryPointData(e,t){const r={geometryBuffer:e.geometryBuffer};null==this._worker&&(this._worker=new O((e=>this.view.resourceController.immediate.schedule(e))));const i=await this._worker.invoke(r,t);if(null==i)throw new Error("Failed to decompress Draco point data");return{positionData:i.positions,featureIds:i.featureIds}}async addNode(e,t,r){if(!re(t)&&!te(t))throw new Error;if(this.loadedGraphics.hasNode(e.index))return void i.getLogger(this).error("I3S node "+e.id+" already added");const s=null!=this.layer.fullExtent?oe(this.layer.fullExtent.clone(),.5):null,o=[],{featureIds:a,pointPositions:n}=re(t)?await this._extractBinaryPointPositions(e,t,r):this._extractLegacyPointPositions(t);this._validatePositions(e,a,n,s,o);const l=this._controller.crsVertex,d=this.view.spatialReference;c(n,l,0,n,d,0,a.length);const u=re(t)?e.level:0,h=this._createGraphics(a,n,e.index,u),p=new J(h,a,t.attributeDataInfo,e);if(await this._i3sOverrides.applyAttributeOverrides(p.featureIds,t.attributeDataInfo,r),e.numFeatures=p.graphics.length,this._updateNodeMemory(e),se(p),o.length>0&&(this._computeObb(e,o,l),this._controller.updateVisibility(e.index)),!this._controller.isGeometryVisible(e))return void this._cacheNodeData(p);if(null!=this._verticalScale)for(const i of p.graphics)this._verticalScale(i.geometry);const g=this.view._stage.renderView.objectAndLayerIdRenderHelper;if(null!=g)for(let i=0;i<p.featureIds.length;i++){const e=p.featureIds[i];g.setUidToObjectAndLayerId(e,p.graphics[i].uid,this.layer.id,this.layer.uid,this.layer.popupEnabled&&K(this.layer,this.view.popup?.defaultPopupTemplateEnabled),p.node.resources.attributes,i)}this.loadedGraphics.addNode(e.index,p),this._controller.updateLoadStatus(e.index,!0),this._filterNode(p),this._treeDebugger&&this._treeDebugger.update()}_computeObb(e,t,r){const i=this._controller.crsIndex,s=i.isGeographic?this.view.renderSpatialReference:i;c(t,r,0,t,s,0,t.length/3),e.serviceObb=B(new z(t,3)),i.isGeographic&&p(e.serviceObb.center,s,e.serviceObb.center,i)}isNodeLoaded(e){return this.loadedGraphics.hasNode(e)}isNodeReloading(){return!1}updateNodeState(){}async _extractBinaryPointPositions(e,t,r){const i=await this._decompressBinaryPointData(t,r),s=i.positionData,o=3,a=s.length/o,n=y(3*a),l=null!=e.serviceObb?e.serviceObb.center:[0,0,0],d=Math.abs(l[2])*2**-20;for(let u=0;u<a;u++){const e=u*o;n[e]=s[e]+l[0],n[e+1]=s[e+1]+l[1],n[e+2]=s[e+2]+l[2],Math.abs(n[e+2])<d&&(n[e+2]=0)}return{featureIds:i.featureIds?f(i.featureIds):[],pointPositions:n}}_extractLegacyPointPositions(e){const t=e.pointData.length,r=y(3*t),i=new Array;for(let s=0;s<t;s++){const t=e.pointData[s],o=t.featureDataPosition,a=o.length,n=t.geometries?.[0]??ae[a],l=t.featureIds[0];if("Embedded"!==n.type||"points"!==n.params.type||a<2||a>3)continue;const d=n.params.vertexAttributes?.position??[0,0,0],u=3*i.length;r[u]=o[0]+d[0],r[u+1]=o[1]+d[1],r[u+2]=3===a?o[2]+d[2]:NaN,i.push(l)}return{featureIds:i,pointPositions:r}}_validatePositions(e,t,r,s,o){if(null==s&&e.serviceObb)return;const a=t.length,n=3;for(let l=0;l<a;l++){const t=l*n;u(ne,r[t],r[t+1],r[t+2]);const a=!Number.isNaN(r[2]);null==s||(a?g(s,ne):m(s,ne))||(this._coordinatesOutsideExtentErrors<this._maxCoordinatesOutsideExtentErrors&&i.getLogger(this).error("Service Error: Coordinates outside of layer extent"),this._coordinatesOutsideExtentErrors+1===this._maxCoordinatesOutsideExtentErrors&&i.getLogger(this).error("Maximum number of errors reached. Further errors are ignored."),this._coordinatesOutsideExtentErrors++),e.serviceObb||o.push(ne[0],ne[1],ne[2])}}_createGraphics(e,r,i,s){const o=e.length,a=3,n=this._getObjectIdField(),l=this.processor.graphicsCore,d=new Array,u=this.view.spatialReference;for(let h=0;h<o;h++){const o=e[h],c={};null!=o&&(c[n]=o);const p=o??t.generateUID(),g=h*a,m=isNaN(r[g+2])?void 0:r[g+2],y=v(r[g],r[g+1],m,u),f=this.loadedGraphics.get(p);if(null!=f)(null==f.level||f.level<s)&&(le.property="geometry",le.graphic=f,le.oldValue=f.geometry,le.newValue=y,f.geometry=y,f.level=s,l.graphicUpdateHandler(le)),d.push(f);else{const e=t.generateUID();d.push({objectId:p,uid:e,geometry:y,attributes:c,visible:!0,nodeIndex:i,level:s})}}return d}_updateNodeMemory(e){e.memory=4096+(null!=e.numFeatures?e.numFeatures*this.processor.graphicsCore.usedMemoryPerGraphic:0)}_cacheNodeData(e){const t=e.graphics.reduce(((e,t)=>E(t)+e),n(e.featureIds)+1024);this._memCache.put(this._getMemCacheKey(e.node),e,t)}_getMemCacheKey(e){return`${e.index}`}_removeAllNodeData(){this.loadedGraphics.forEachNode(((e,t)=>{if(e){const t=e.node;this._updateNodeMemory(t),this._cacheNodeData(e)}this._controller.updateLoadStatus(t,!1)})),this._treeDebugger&&this._treeDebugger.update(),this.loadedGraphics.clear()}removeNode(e){const t=this._removeNodeStageData(e);t&&(this._updateNodeMemory(t.node),this._cacheNodeData(t))}_removeNodeStageData(e){const t=this.loadedGraphics.getNode(e);return null==t?null:(this._controller.updateLoadStatus(e,!1),this.loadedGraphics.removeNode(e),this._treeDebugger&&this._treeDebugger.update(),t)}async loadCachedNodeData(e){return this._memCache?.pop(this._getMemCacheKey(e))}async addCachedNodeData(e,t,r,s){this.loadedGraphics.hasNode(e.index)?i.getLogger(this).error("I3S node "+e.id+" already added"):(await this._i3sOverrides.applyAttributeOverrides(t.featureIds,r,s),this.loadedGraphics.addNode(e.index,t),this._controller.updateLoadStatus(e.index,!0),this._updateNodeMemory(e),t.attributeInfo=r,this._attributeValuesChanged(t),this._filterNode(t),this._treeDebugger&&this._treeDebugger.update())}getLoadedNodeIds(){const e=[];return this.loadedGraphics.forEachNode((t=>e.push(t.node.id))),e.sort()}getVisibleNodes(){const e=new Array;return this.loadedGraphics.forEachNode((t=>e.push(t.node))),e}getLoadedNodeIndices(e){this.loadedGraphics.forEachNode(((t,r)=>e.push(r)))}getLoadedAttributes(e){const t=this.loadedGraphics.getNode(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.loadedAttributes}getAttributeData(e){const t=this.loadedGraphics.getNode(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.attributeData}_setAttributeData(e,t){const r=this.loadedGraphics.getNode(e);null!=r&&null!=r.attributeInfo&&(r.attributeInfo.attributeData=t,this._attributeValuesChanged(r))}async updateAttributes(e,t,r){const i=this.loadedGraphics.getNode(e);null!=i&&(await this._i3sOverrides.applyAttributeOverrides(i.featureIds,t,r),i.attributeInfo=t,this._attributeValuesChanged(i))}_attributeValuesChanged(e){if(se(e),this._filterNode(e),this.processor.graphicsCore.labelsEnabled){const t=e.graphics.map((e=>e.uid));this.processor.graphicsCore.updateLabelingInfo(t)}}_updateClippingExtent(e){return this._controller&&this._controller.updateClippingArea(e),!1}_getObjectIdField(){return this.layer.objectIdField||b}_getGlobalIdField(){return this.layer.associatedLayer?.globalIdField}async _rendererChange(e,t){const{layer:{fieldsIndex:r}}=this,i=new Set;let s,o;e?(await e.collectRequiredFields(i,r),s=Array.from(i).sort()):s=[],i.clear(),t?(await t.collectRequiredFields(i,r),o=Array.from(i).sort()):o=[],s.length===o.length&&s.every(((e,t)=>s[t]===o[t]))||this._reloadAllNodes()}_rangeInfosChanged(e){null!=e&&e.length>0&&i.getLogger(this).warn("Unsupported property: rangeInfos are currently only serialized to and from web scenes but do not affect rendering.")}_filterChange(){this.loadedGraphics.forEachNode((e=>this._filterNode(e)))}_reloadAllNodes(){this._removeAllNodeData(),this._controller&&this._controller.restartNodeLoading()}_filterNode(e){const t=this.parsedDefinitionExpression,i=this._excludeObjectIdsSorted,s=this._getObjectIdField();for(const o of e.graphics){const e=o.visible,a=!t||this._evaluateClause(t,o),n=null==i||r(i,o.attributes[s])<0;o.visible=a&&n,e!==o.visible&&(le.graphic=o,le.property="visible",le.oldValue=e,le.newValue=o.visible,this.processor.graphicsCore.graphicUpdateHandler(le))}}createQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference};return null!=this.filter?this.filter.createQuery(e):new N(e)}queryFeatures(e,t){return this._queryEngine.executeQuery(this._ensureQuery(e),t?.signal)}queryObjectIds(e,t){return this._queryEngine.executeQueryForIds(this._ensureQuery(e),t?.signal)}queryFeatureCount(e,t){return this._queryEngine.executeQueryForCount(this._ensureQuery(e),t?.signal)}queryExtent(e,t){return this._queryEngine.executeQueryForExtent(this._ensureQuery(e),t?.signal)}_ensureQuery(e){return this._addDefinitionExpressionToQuery(null==e?this.createQuery():N.from(e))}_setupQueryEngine(){const e=()=>this.processor.featureStore;this._queryEngine=new D({context:{spatialReference:this.view.spatialReference,layer:this.layer,scheduler:this.view.resourceController.scheduler,get featureStore(){return e()},hasZ:this.hasZ,hasM:this.hasM},priority:Y.FEATURE_QUERY_ENGINE})}get usedMemory(){return this.processor?.graphicsCore?.usedMemory??0}get unloadedMemory(){return.8*((this._controller?.unloadedMemoryEstimate??0)+(this.processor?.graphicsCore?.unprocessedMemoryEstimate??0))}get ignoresMemoryFactor(){return this._controller&&this._controller.fixedFeatureTarget}_handleEdits(e){S(this._attributeEditingContext,e)}get _attributeEditingContext(){const e=this._getObjectIdField(),t=this._getGlobalIdField();return{sessions:this._interactiveEditingSessions,fieldsIndex:this.layer.fieldsIndex,objectIdField:e,globalIdField:t,forEachNode:e=>this.loadedGraphics.forEachNode((t=>e(t.node,t.featureIds))),attributeStorageInfo:this.i3slayer.attributeStorageInfo??[],i3sOverrides:this._i3sOverrides,getAttributeData:e=>this.getAttributeData(e),setAttributeData:(t,r,i)=>{this._setAttributeData(t,r);const s=this.loadedGraphics.getNode(t);if(null!=i){const t=this.loadedGraphics.get(i.attributes[e]);null!=t&&this.processor.graphicsCore.recreateGraphics([t])}else null!=s&&this.processor.graphicsCore.recreateGraphics(s.graphics)},clearMemCache:()=>{}}}get performanceInfo(){const e={displayedNumberOfFeatures:this.loadedGraphics.length,maximumNumberOfFeatures:this.maximumNumberOfFeatures,totalNumberOfFeatures:-1,nodes:this.loadedGraphics.nodeCount,core:this.processor.graphicsCore.performanceInfo};return this._controller&&this._controller.updateStats(e),e}get test(){return{controller:this._controller,numNodes:this.loadedGraphics.nodeCount,loadedGraphics:this.loadedGraphics}}};e([l()],X.prototype,"processor",void 0),e([l({type:w})],X.prototype,"filter",void 0),e([l()],X.prototype,"loadedGraphics",void 0),e([l()],X.prototype,"i3slayer",null),e([l()],X.prototype,"_controller",void 0),e([l()],X.prototype,"updating",void 0),e([l()],X.prototype,"suspended",void 0),e([l()],X.prototype,"holeFilling",void 0),e([l(k)],X.prototype,"updatingProgress",void 0),e([l()],X.prototype,"updatingProgressValue",null),e([l($.requiredFields)],X.prototype,"requiredFields",null),e([l($.availableFields)],X.prototype,"availableFields",void 0),e([l()],X.prototype,"_fieldsHelper",void 0),e([l({type:Number})],X.prototype,"maximumNumberOfFeatures",null),e([l({readOnly:!0})],X.prototype,"maximumNumberOfFeaturesExceeded",null),e([l()],X.prototype,"_excludeObjectIdsSorted",null),e([l({readOnly:!0})],X.prototype,"lodFactor",null),e([l({readOnly:!0})],X.prototype,"hasM",null),e([l({readOnly:!0})],X.prototype,"hasZ",null),e([l()],X.prototype,"contentVisible",null),e([l({readOnly:!0})],X.prototype,"legendEnabled",null),X=e([d("esri.views.3d.layers.SceneLayerGraphicsView3D")],X);const ee=X;function te(e){return"pointData"in e}function re(e){return"geometryBuffer"in e&&null!==e.geometryBuffer}function ie(e,t,r){const i=t.attributeInfo;if(null==i||null==i.loadedAttributes||null==i.attributeData)return!1;let s=!1;for(const{name:o}of i.loadedAttributes)if(i.attributeData[o]){const t=R(i.attributeData[o],r);t!==e.attributes[o]&&(e.attributes[o]=t,s=!0)}return s}function se(e){const t=e.attributeInfo,r=e.node.index;if(null!=t&&null!=t.loadedAttributes&&null!=t.attributeData)for(let i=0;i<e.graphics.length;i++){const s=e.graphics[i];if(s.nodeIndex===r){s.attributes||(s.attributes={});for(const{name:e}of t.loadedAttributes)t.attributeData[e]&&(s.attributes[e]=R(t.attributeData[e],i))}}}function oe(e,t){return e.xmin-=t,e.ymin-=t,e.xmax+=t,e.ymax+=t,null!=e.zmin&&null!=e.zmax&&(e.zmin-=t,e.zmax+=t),null!=e.mmin&&null!=e.mmax&&(e.mmin-=t,e.mmax+=t),e}const ae={2:{type:"Embedded",params:{type:"points",vertexAttributes:{position:[0,0]}}},3:{type:"Embedded",params:{type:"points",vertexAttributes:{position:[0,0,0]}}}},ne=h(),le={graphic:null,property:null,oldValue:null,newValue:null};export{ee as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Graphic.js";import{binaryIndexOf as r}from"../../../core/arrayUtils.js";import i from"../../../core/Logger.js";import{destroyMaybe as s}from"../../../core/maybe.js";import{initial as o,watch as a}from"../../../core/reactiveUtils.js";import{estimateSize as n}from"../../../core/typedArrayUtil.js";import{property as l}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as d}from"../../../core/accessorSupport/decorators/subclass.js";import{s as u}from"../../../chunks/vec3.js";import{c as h}from"../../../chunks/vec3f64.js";import{projectBuffer as c,projectVectorToVector as p}from"../../../geometry/projection.js";import{extentContainsCoords3D as g,extentContainsCoords2D as m}from"../../../geometry/support/contains.js";import{newDoubleArray as y,doubleArrayFrom as f}from"../../../geometry/support/DoubleArray.js";import{getGeometryZScaler as _}from"../../../geometry/support/zscale.js";import{fallbackObjectIDAttribute as b}from"../../../layers/LayerConstants.js";import{makeDehydratedPoint as v,estimateSize as E}from"../../../layers/graphics/dehydratedFeatures.js";import{hydrateGraphic as x}from"../../../layers/graphics/hydratedFeatures.js";import I from"../../../layers/graphics/controllers/I3SOnDemandController.js";import w from"../../../layers/support/FeatureFilter.js";import N from"../../../rest/support/Query.js";import{isBasemapLayer as O}from"../../../support/basemapUtils.js";import{I3SPointsWorkerHandle as C}from"./I3SPointsWorkerHandle.js";import{LayerView3D as F}from"./LayerView3D.js";import D from"./graphics/Graphics3DFeatureProcessor.js";import{QueryEngine as j}from"./graphics/QueryEngine.js";import{createInteractiveEditSession as S,processAttributeEdits as G}from"./i3s/featureEditing.js";import{I3SGraphicsMap as A}from"./i3s/I3SGraphicsMap.js";import{I3SOverrides as L}from"./i3s/I3SOverrides.js";import{checkRecyclable as P,checkSpatialReferences as V,containsDraco as M,whenGraphicAttributes as R,getCachedAttributeValue as H}from"./i3s/I3SUtil.js";import{DefinitionExpressionSceneLayerView as U}from"./support/DefinitionExpressionSceneLayerView.js";import{defineFieldProperties as q}from"./support/fieldProperties.js";import{PopupSceneLayerView as Q}from"./support/PopupSceneLayerView.js";import{SceneLayerViewRequiredFields as T}from"./support/SceneLayerViewRequiredFields.js";import B from"../support/debugFlags.js";import{compute as k}from"../support/orientedBoundingBox.js";import{updatingProgress as z}from"../support/updatingProperties.js";import{Attribute as W}from"../webgl-engine/lib/Attribute.js";import{UpdatePolicy as Z}from"../webgl-engine/lib/UpdatePolicy.js";import K from"../../layers/SceneLayerView.js";import{hasPopupTemplate as Y}from"../../layers/support/popupUtils.js";import{TaskPriority as $}from"../../support/Scheduler.js";const J=q();class X{constructor(e,t,r,i){this.graphics=e,this.featureIds=t,this.attributeInfo=r,this.node=i}}let ee=class extends(U(Q(F(K)))){constructor(){super(...arguments),this.type="scene-layer-graphics-3d",this._queryEngine=null,this._memCache=null,this._interactiveEditingSessions=new Map,this.loadedGraphics=new A(((e,t,r)=>se(e,t,r)),(e=>this.processor.graphicsCore.recreateGraphics(e))),this.holeFilling="always",this.progressiveLoadFactor=1,this.supportsHeightUnitConversion=!0,this._coordinatesOutsideExtentErrors=0,this._maxCoordinatesOutsideExtentErrors=20}tryRecycleWith(e,t){return e.url===this.layer.url&&this._i3sOverrides.isEmpty?e.load(t).then((()=>{P(this.layer,e,this._i3sOverrides),this.layer=e,this._i3sOverrides.destroy();const t=this.view.resourceController?.memoryController;this._i3sOverrides=new L({view:this.view,layer:e,memoryController:t}),s(this._queryEngine),this._setupQueryEngine(),this.processor.resetObjectStates()})):null}initialize(){this.addResolvingPromise(this.layer.indexInfo);const e=this.view.resourceController?.memoryController;this._i3sOverrides=new L({view:this.view,layer:this.layer,memoryController:e}),V(this.layer,this.view.spatialReference,this.view.viewingMode),this._fieldsHelper=new T({layerView:this}),this.updatingHandles.add((()=>this.layer.rangeInfos),(e=>this._rangeInfosChanged(e)),o),this.updatingHandles.add((()=>this.layer.renderer),((e,t)=>this._rendererChange(e,t))),this.updatingHandles.add((()=>[this.parsedDefinitionExpression,this._excludeObjectIdsSorted]),(()=>this._filterChange())),this.handles.add(a((()=>B.I3S_TREE_SHOW_TILES),(e=>{if(e&&!this._treeDebugger){const e=this._controller.crsIndex;import("./support/I3STreeDebugger.js").then((({I3STreeDebugger:t})=>{!this._treeDebugger&&B.I3S_TREE_SHOW_TILES&&(this._treeDebugger=new t({lv:this,view:this.view,nodeSR:e}))}))}else e||!this._treeDebugger||B.I3S_TREE_SHOW_TILES||(this._treeDebugger.destroy(),this._treeDebugger=null)}),o)),this._set("processor",new D({owner:this,preferredUpdatePolicy:Z.ASYNC,scaleVisibilityEnabled:!0,filterVisibilityEnabled:!0,timeExtentEnabled:!1,frustumVisibilityEnabled:!1,elevationAlignmentEnabled:!0,elevationFeatureExpressionEnabled:!1,setUidToIdOnAdd:!1,dataExtent:this.layer.fullExtent,updateClippingExtent:e=>this._updateClippingExtent(e)})),this.processor.elevationAlignment?.events.on("invalidate-elevation",(e=>this._controller.updateElevationChanged(e.extent,e.spatialReference))),this.supportsHeightUnitConversion&&(this._verticalScale=_("point",this.layer.spatialReference,this.view.spatialReference)),this.addResolvingPromise(this.processor.initializePromise),this._memCache=this.view.resourceController.memoryController.newCache(`psl-${this.uid}`),this._controller=new I({layerView:this,scaleVisibilityEnabled:!1}),M(this.layer.geometryDefinitions)&&(this._worker=new C((e=>this.view.resourceController.immediate.schedule(e)))),this.handles.add(this.layer.on("apply-edits",(e=>this.updatingHandles.addPromise(e.result)))),this.handles.add(this.layer.on("edits",(e=>this._handleEdits(e)))),this.when((()=>{this._setupQueryEngine(),this.updatingHandles.add((()=>this.maximumNumberOfFeatures),(e=>this._controller.featureTarget=e),o),this.updatingHandles.add((()=>this.suspended),(e=>{e&&this._removeAllNodeData()}))}))}destroy(){this._treeDebugger=s(this._treeDebugger),this._i3sOverrides=s(this._i3sOverrides),this._set("processor",s(this.processor)),this._controller=s(this._controller),this._queryEngine=s(this._queryEngine),this._worker=s(this._worker),this._memCache=s(this._memCache),this.loadedGraphics.clear(),this._fieldsHelper=s(this._fieldsHelper)}get i3slayer(){return this.layer}get updatingProgressValue(){return this._controller?.updatingProgress??1}get requiredFields(){return this._fieldsHelper?.requiredFields??[]}get maximumNumberOfFeatures(){const e=this.processor?.graphicsCore?.displayFeatureLimit;return e?.maximumNumberOfFeatures??0}set maximumNumberOfFeatures(e){null!=e?(this._override("maximumNumberOfFeatures",e),this._controller.fixedFeatureTarget=!0):(this._clearOverride("maximumNumberOfFeatures"),this._controller.fixedFeatureTarget=!1)}get maximumNumberOfFeaturesExceeded(){return!this.suspended&&(!!this._controller?.useMaximumNumberOfFeatures&&!this._controller.leavesReached)}get _excludeObjectIdsSorted(){const e=this.layer.excludeObjectIds;return e.length?e.toArray().sort(((e,t)=>e-t)):null}get lodFactor(){return"Labels"===this.layer.semantic?1:this.view.qualitySettings.sceneService.point.lodFactor}get hasM(){return!1}get hasZ(){return!0}get contentVisible(){return!this.suspended&&!!this._controller?.rootNodeVisible}get legendEnabled(){return this.contentVisible&&!0===this.i3slayer?.legendEnabled}async whenGraphicAttributes(e,t){return R(this.layer,e,this._getObjectIdField(),t,(()=>[...this.loadedGraphics.nodes()]))}getHit(e){if(!this.loadedGraphics)return null;const t=x(this.loadedGraphics.find((t=>t.uid===e)),this.layer),r=this._getObjectIdField();return t&&t.attributes&&t.attributes[r]?(t.layer=this.layer,t.sourceLayer=this.layer,{type:"graphic",graphic:t,layer:t.layer}):null}whenGraphicBounds(e,t){return this.processor.whenGraphicBounds(e,t)}computeAttachmentOrigin(e,t){return this.processor.computeAttachmentOrigin(e,t)}isUpdating(){return!!(this._controller?.updating||this.processor?.updating||this._fieldsHelper?.updating||this.layerFilterUpdating)}highlight(e){return this.processor.highlight(e,this.layer.objectIdField)}get updatePolicy(){return this.processor.graphicsCore.effectiveUpdatePolicy}createInteractiveEditSession(e){return S(this._attributeEditingContext,e)}async _decompressBinaryPointData(e,t){const r={geometryBuffer:e.geometryBuffer};null==this._worker&&(this._worker=new C((e=>this.view.resourceController.immediate.schedule(e))));const i=await this._worker.invoke(r,t);if(null==i)throw new Error("Failed to decompress Draco point data");return{positionData:i.positions,featureIds:i.featureIds}}async addNode(e,t,r){if(!ie(t)&&!re(t))throw new Error;if(this.loadedGraphics.hasNode(e.index))return void i.getLogger(this).error("I3S node "+e.id+" already added");const s=null!=this.layer.fullExtent?ae(this.layer.fullExtent.clone(),.5):null,o=[],{featureIds:a,pointPositions:n}=ie(t)?await this._extractBinaryPointPositions(e,t,r):this._extractLegacyPointPositions(t);this._validatePositions(e,a,n,s,o);const l=this._controller.crsVertex,d=this.view.spatialReference;c(n,l,0,n,d,0,a.length);const u=ie(t)?e.level:0,h=this._createGraphics(a,n,e.index,u),p=new X(h,a,t.attributeDataInfo,e);if(await this._i3sOverrides.applyAttributeOverrides(p.featureIds,t.attributeDataInfo,r),e.numFeatures=p.graphics.length,this._updateNodeMemory(e),oe(p),o.length>0&&(this._computeObb(e,o,l),this._controller.updateVisibility(e.index)),!this._controller.isGeometryVisible(e))return void this._cacheNodeData(p);if(null!=this._verticalScale)for(const i of p.graphics)this._verticalScale(i.geometry);const g=this.view._stage.renderView.objectAndLayerIdRenderHelper;if(null!=g){const e=O(this.view.map,this.layer.uid);for(let t=0;t<p.featureIds.length;t++){const r=p.featureIds[t];g.setUidToObjectAndLayerId(r,p.graphics[t].uid,this.layer.id,this.layer.uid,this.layer.popupEnabled&&!e&&Y(this.layer,this.view.popup?.defaultPopupTemplateEnabled),p.node.resources.attributes,t)}}this.loadedGraphics.addNode(e.index,p),this._controller.updateLoadStatus(e.index,!0),this._filterNode(p),this._treeDebugger&&this._treeDebugger.update()}_computeObb(e,t,r){const i=this._controller.crsIndex,s=i.isGeographic?this.view.renderSpatialReference:i;c(t,r,0,t,s,0,t.length/3),e.serviceObb=k(new W(t,3)),i.isGeographic&&p(e.serviceObb.center,s,e.serviceObb.center,i)}isNodeLoaded(e){return this.loadedGraphics.hasNode(e)}isNodeReloading(){return!1}updateNodeState(){}async _extractBinaryPointPositions(e,t,r){const i=await this._decompressBinaryPointData(t,r),s=i.positionData,o=3,a=s.length/o,n=y(3*a),l=null!=e.serviceObb?e.serviceObb.center:[0,0,0],d=Math.abs(l[2])*2**-20;for(let u=0;u<a;u++){const e=u*o;n[e]=s[e]+l[0],n[e+1]=s[e+1]+l[1],n[e+2]=s[e+2]+l[2],Math.abs(n[e+2])<d&&(n[e+2]=0)}return{featureIds:i.featureIds?f(i.featureIds):[],pointPositions:n}}_extractLegacyPointPositions(e){const t=e.pointData.length,r=y(3*t),i=new Array;for(let s=0;s<t;s++){const t=e.pointData[s],o=t.featureDataPosition,a=o.length,n=t.geometries?.[0]??ne[a],l=t.featureIds[0];if("Embedded"!==n.type||"points"!==n.params.type||a<2||a>3)continue;const d=n.params.vertexAttributes?.position??[0,0,0],u=3*i.length;r[u]=o[0]+d[0],r[u+1]=o[1]+d[1],r[u+2]=3===a?o[2]+d[2]:NaN,i.push(l)}return{featureIds:i,pointPositions:r}}_validatePositions(e,t,r,s,o){if(null==s&&e.serviceObb)return;const a=t.length,n=3;for(let l=0;l<a;l++){const t=l*n;u(le,r[t],r[t+1],r[t+2]);const a=!Number.isNaN(r[2]);null==s||(a?g(s,le):m(s,le))||(this._coordinatesOutsideExtentErrors<this._maxCoordinatesOutsideExtentErrors&&i.getLogger(this).error("Service Error: Coordinates outside of layer extent"),this._coordinatesOutsideExtentErrors+1===this._maxCoordinatesOutsideExtentErrors&&i.getLogger(this).error("Maximum number of errors reached. Further errors are ignored."),this._coordinatesOutsideExtentErrors++),e.serviceObb||o.push(le[0],le[1],le[2])}}_createGraphics(e,r,i,s){const o=e.length,a=3,n=this._getObjectIdField(),l=this.processor.graphicsCore,d=new Array,u=this.view.spatialReference;for(let h=0;h<o;h++){const o=e[h],c={};null!=o&&(c[n]=o);const p=o??t.generateUID(),g=h*a,m=isNaN(r[g+2])?void 0:r[g+2],y=v(r[g],r[g+1],m,u),f=this.loadedGraphics.get(p);if(null!=f)(null==f.level||f.level<s)&&(de.property="geometry",de.graphic=f,de.oldValue=f.geometry,de.newValue=y,f.geometry=y,f.level=s,l.graphicUpdateHandler(de)),d.push(f);else{const e=t.generateUID();d.push({objectId:p,uid:e,geometry:y,attributes:c,visible:!0,nodeIndex:i,level:s})}}return d}_updateNodeMemory(e){e.memory=4096+(null!=e.numFeatures?e.numFeatures*this.processor.graphicsCore.usedMemoryPerGraphic:0)}_cacheNodeData(e){const t=e.graphics.reduce(((e,t)=>E(t)+e),n(e.featureIds)+1024);this._memCache.put(this._getMemCacheKey(e.node),e,t)}_getMemCacheKey(e){return`${e.index}`}_removeAllNodeData(){this.loadedGraphics.forEachNode(((e,t)=>{if(e){const t=e.node;this._updateNodeMemory(t),this._cacheNodeData(e)}this._controller.updateLoadStatus(t,!1)})),this._treeDebugger&&this._treeDebugger.update(),this.loadedGraphics.clear()}removeNode(e){const t=this._removeNodeStageData(e);t&&(this._updateNodeMemory(t.node),this._cacheNodeData(t))}_removeNodeStageData(e){const t=this.loadedGraphics.getNode(e);return null==t?null:(this._controller.updateLoadStatus(e,!1),this.loadedGraphics.removeNode(e),this._treeDebugger&&this._treeDebugger.update(),t)}async loadCachedNodeData(e){return this._memCache?.pop(this._getMemCacheKey(e))}async addCachedNodeData(e,t,r,s){this.loadedGraphics.hasNode(e.index)?i.getLogger(this).error("I3S node "+e.id+" already added"):(await this._i3sOverrides.applyAttributeOverrides(t.featureIds,r,s),this.loadedGraphics.addNode(e.index,t),this._controller.updateLoadStatus(e.index,!0),this._updateNodeMemory(e),t.attributeInfo=r,this._attributeValuesChanged(t),this._filterNode(t),this._treeDebugger&&this._treeDebugger.update())}getLoadedNodeIds(){const e=[];return this.loadedGraphics.forEachNode((t=>e.push(t.node.id))),e.sort()}getVisibleNodes(){const e=new Array;return this.loadedGraphics.forEachNode((t=>e.push(t.node))),e}getLoadedNodeIndices(e){this.loadedGraphics.forEachNode(((t,r)=>e.push(r)))}getLoadedAttributes(e){const t=this.loadedGraphics.getNode(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.loadedAttributes}getAttributeData(e){const t=this.loadedGraphics.getNode(e);if(null!=t&&null!=t.attributeInfo)return t.attributeInfo.attributeData}_setAttributeData(e,t){const r=this.loadedGraphics.getNode(e);null!=r&&null!=r.attributeInfo&&(r.attributeInfo.attributeData=t,this._attributeValuesChanged(r))}async updateAttributes(e,t,r){const i=this.loadedGraphics.getNode(e);null!=i&&(await this._i3sOverrides.applyAttributeOverrides(i.featureIds,t,r),i.attributeInfo=t,this._attributeValuesChanged(i))}_attributeValuesChanged(e){if(oe(e),this._filterNode(e),this.processor.graphicsCore.labelsEnabled){const t=e.graphics.map((e=>e.uid));this.processor.graphicsCore.updateLabelingInfo(t)}}_updateClippingExtent(e){return this._controller&&this._controller.updateClippingArea(e),!1}_getObjectIdField(){return this.layer.objectIdField||b}_getGlobalIdField(){return this.layer.associatedLayer?.globalIdField}async _rendererChange(e,t){const{layer:{fieldsIndex:r}}=this,i=new Set;let s,o;e?(await e.collectRequiredFields(i,r),s=Array.from(i).sort()):s=[],i.clear(),t?(await t.collectRequiredFields(i,r),o=Array.from(i).sort()):o=[],s.length===o.length&&s.every(((e,t)=>s[t]===o[t]))||this._reloadAllNodes()}_rangeInfosChanged(e){null!=e&&e.length>0&&i.getLogger(this).warn("Unsupported property: rangeInfos are currently only serialized to and from web scenes but do not affect rendering.")}_filterChange(){this.loadedGraphics.forEachNode((e=>this._filterNode(e)))}_reloadAllNodes(){this._removeAllNodeData(),this._controller&&this._controller.restartNodeLoading()}_filterNode(e){const t=this.parsedDefinitionExpression,i=this._excludeObjectIdsSorted,s=this._getObjectIdField();for(const o of e.graphics){const e=o.visible,a=!t||this._evaluateClause(t,o),n=null==i||r(i,o.attributes[s])<0;o.visible=a&&n,e!==o.visible&&(de.graphic=o,de.property="visible",de.oldValue=e,de.newValue=o.visible,this.processor.graphicsCore.graphicUpdateHandler(de))}}createQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference};return null!=this.filter?this.filter.createQuery(e):new N(e)}queryFeatures(e,t){return this._queryEngine.executeQuery(this._ensureQuery(e),t?.signal)}queryObjectIds(e,t){return this._queryEngine.executeQueryForIds(this._ensureQuery(e),t?.signal)}queryFeatureCount(e,t){return this._queryEngine.executeQueryForCount(this._ensureQuery(e),t?.signal)}queryExtent(e,t){return this._queryEngine.executeQueryForExtent(this._ensureQuery(e),t?.signal)}_ensureQuery(e){return this._addDefinitionExpressionToQuery(null==e?this.createQuery():N.from(e))}_setupQueryEngine(){const e=()=>this.processor.featureStore;this._queryEngine=new j({context:{spatialReference:this.view.spatialReference,layer:this.layer,scheduler:this.view.resourceController.scheduler,get featureStore(){return e()},hasZ:this.hasZ,hasM:this.hasM},priority:$.FEATURE_QUERY_ENGINE})}get usedMemory(){return this.processor?.graphicsCore?.usedMemory??0}get unloadedMemory(){return.8*((this._controller?.unloadedMemoryEstimate??0)+(this.processor?.graphicsCore?.unprocessedMemoryEstimate??0))}get ignoresMemoryFactor(){return this._controller&&this._controller.fixedFeatureTarget}_handleEdits(e){G(this._attributeEditingContext,e)}get _attributeEditingContext(){const e=this._getObjectIdField(),t=this._getGlobalIdField();return{sessions:this._interactiveEditingSessions,fieldsIndex:this.layer.fieldsIndex,objectIdField:e,globalIdField:t,forEachNode:e=>this.loadedGraphics.forEachNode((t=>e(t.node,t.featureIds))),attributeStorageInfo:this.i3slayer.attributeStorageInfo??[],i3sOverrides:this._i3sOverrides,getAttributeData:e=>this.getAttributeData(e),setAttributeData:(t,r,i)=>{this._setAttributeData(t,r);const s=this.loadedGraphics.getNode(t);if(null!=i){const t=this.loadedGraphics.get(i.attributes[e]);null!=t&&this.processor.graphicsCore.recreateGraphics([t])}else null!=s&&this.processor.graphicsCore.recreateGraphics(s.graphics)},clearMemCache:()=>{}}}get performanceInfo(){const e={displayedNumberOfFeatures:this.loadedGraphics.length,maximumNumberOfFeatures:this.maximumNumberOfFeatures,totalNumberOfFeatures:-1,nodes:this.loadedGraphics.nodeCount,core:this.processor.graphicsCore.performanceInfo};return this._controller&&this._controller.updateStats(e),e}get test(){return{controller:this._controller,numNodes:this.loadedGraphics.nodeCount,loadedGraphics:this.loadedGraphics}}};e([l()],ee.prototype,"processor",void 0),e([l({type:w})],ee.prototype,"filter",void 0),e([l()],ee.prototype,"loadedGraphics",void 0),e([l()],ee.prototype,"i3slayer",null),e([l()],ee.prototype,"_controller",void 0),e([l()],ee.prototype,"updating",void 0),e([l()],ee.prototype,"suspended",void 0),e([l()],ee.prototype,"holeFilling",void 0),e([l(z)],ee.prototype,"updatingProgress",void 0),e([l()],ee.prototype,"updatingProgressValue",null),e([l(J.requiredFields)],ee.prototype,"requiredFields",null),e([l(J.availableFields)],ee.prototype,"availableFields",void 0),e([l()],ee.prototype,"_fieldsHelper",void 0),e([l({type:Number})],ee.prototype,"maximumNumberOfFeatures",null),e([l({readOnly:!0})],ee.prototype,"maximumNumberOfFeaturesExceeded",null),e([l()],ee.prototype,"_excludeObjectIdsSorted",null),e([l({readOnly:!0})],ee.prototype,"lodFactor",null),e([l({readOnly:!0})],ee.prototype,"hasM",null),e([l({readOnly:!0})],ee.prototype,"hasZ",null),e([l()],ee.prototype,"contentVisible",null),e([l({readOnly:!0})],ee.prototype,"legendEnabled",null),ee=e([d("esri.views.3d.layers.SceneLayerGraphicsView3D")],ee);const te=ee;function re(e){return"pointData"in e}function ie(e){return"geometryBuffer"in e&&null!==e.geometryBuffer}function se(e,t,r){const i=t.attributeInfo;if(null==i||null==i.loadedAttributes||null==i.attributeData)return!1;let s=!1;for(const{name:o}of i.loadedAttributes)if(i.attributeData[o]){const t=H(i.attributeData[o],r);t!==e.attributes[o]&&(e.attributes[o]=t,s=!0)}return s}function oe(e){const t=e.attributeInfo,r=e.node.index;if(null!=t&&null!=t.loadedAttributes&&null!=t.attributeData)for(let i=0;i<e.graphics.length;i++){const s=e.graphics[i];if(s.nodeIndex===r){s.attributes||(s.attributes={});for(const{name:e}of t.loadedAttributes)t.attributeData[e]&&(s.attributes[e]=H(t.attributeData[e],i))}}}function ae(e,t){return e.xmin-=t,e.ymin-=t,e.xmax+=t,e.ymax+=t,null!=e.zmin&&null!=e.zmax&&(e.zmin-=t,e.zmax+=t),null!=e.mmin&&null!=e.mmax&&(e.mmin-=t,e.mmax+=t),e}const ne={2:{type:"Embedded",params:{type:"points",vertexAttributes:{position:[0,0]}}},3:{type:"Embedded",params:{type:"points",vertexAttributes:{position:[0,0,0]}}}},le=h(),de={graphic:null,property:null,oldValue:null,newValue:null};export{te as default};