@arcgis/core 4.34.0-next.22 → 4.34.0-next.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/applications/Components/arcadeFeatureUtils.d.ts +5 -0
  2. package/applications/Components/arcadeFeatureUtils.js +5 -0
  3. package/arcade/parser.js +1 -1
  4. package/arcade/validation/arcadeValidator.js +1 -1
  5. package/assets/esri/core/workers/RemoteClient.js +1 -1
  6. package/assets/esri/core/workers/chunks/026fbeb0ff5b9e6c74df.js +1 -0
  7. package/assets/esri/core/workers/chunks/0f6203ae32663b2b52db.js +1 -0
  8. package/assets/esri/core/workers/chunks/20bcd2e6cf02e057ad7d.js +1 -0
  9. package/assets/esri/core/workers/chunks/234cbc290b074eeb5dd6.js +1 -0
  10. package/assets/esri/core/workers/chunks/{00eef04fd026adaf0df8.js → 36a2a8b6547604bad2ab.js} +1 -1
  11. package/assets/esri/core/workers/chunks/{63cc4647b7775ff8aedf.js → 44d28849e59f62616e72.js} +1 -1
  12. package/assets/esri/core/workers/chunks/4c47d327815e281c457e.js +1 -0
  13. package/assets/esri/core/workers/chunks/{6bb1ecaa0afc2c7de79e.js → 4cc3eeb0b824c53793d0.js} +1 -1
  14. package/assets/esri/core/workers/chunks/{19ae76283a0cb0fe4dee.js → 4ea96aff38bb301dc40d.js} +1 -1
  15. package/assets/esri/core/workers/chunks/{cab1a1067f44ce374673.js → 7d7f8f2936ddee65e3da.js} +1 -1
  16. package/assets/esri/core/workers/chunks/{b57c0ef7bc57e3c91257.js → 865fccacf44ae5b70eba.js} +1 -1
  17. package/assets/esri/core/workers/chunks/{f43110391f124b8a179c.js → 909a6218db87cba2c9ba.js} +1 -1
  18. package/assets/esri/core/workers/chunks/a273f80298417edecc07.js +1 -0
  19. package/assets/esri/core/workers/chunks/{496e02cfe3d84010f675.js → a2ed7a3cd518dd136ec7.js} +1 -1
  20. package/assets/esri/core/workers/chunks/{1d9e44bdd129cc682ae5.js → ac93b3f1ff15a95d926c.js} +1 -1
  21. package/assets/esri/core/workers/chunks/b32c1b60896a72e0ae90.js +1 -0
  22. package/assets/esri/core/workers/chunks/{6782114a752b9cc59168.js → b6b8272a74a5c24a6b86.js} +1 -1
  23. package/assets/esri/core/workers/chunks/b9f66d735a7e63417b3d.js +1 -0
  24. package/assets/esri/core/workers/chunks/d2ce360961ca4b58666c.js +1 -0
  25. package/assets/esri/core/workers/chunks/{8b19fe829a9dc26fb3fe.js → d915d0a30d9beb24bd3a.js} +1 -1
  26. package/assets/esri/core/workers/chunks/f90573c9dc36e51cd588.js +1 -0
  27. package/assets/esri/core/workers/chunks/fe1902d63f610cebd947.js +1 -0
  28. package/chunks/Bufferer-Dw9Qi4T1.js +1 -1
  29. package/chunks/Envelope.js +1 -1
  30. package/chunks/MultiPathImpl.js +1 -1
  31. package/chunks/OperatorClip.js +1 -1
  32. package/chunks/ProjectionTransformation.js +1 -1
  33. package/chunks/index.js +1 -1
  34. package/config.js +1 -1
  35. package/core/MemCachePool.js +1 -1
  36. package/core/accessorSupport/overrideDefaultsFrom.js +1 -1
  37. package/geometry/operators/gx/operatorOffset.js +1 -1
  38. package/geometry/operators/support/jsonConverter.js +1 -1
  39. package/interfaces.d.ts +157 -31
  40. package/kernel.js +1 -1
  41. package/layers/VideoLayer.js +1 -1
  42. package/layers/orientedImagery/core/ExposurePoint.js +1 -1
  43. package/layers/orientedImagery/core/bestImageUtils.js +1 -1
  44. package/layers/support/ControlPointsGeoreference.js +1 -1
  45. package/layers/support/PixelBlock.js +1 -1
  46. package/layers/support/RasterJobHandler.js +1 -1
  47. package/layers/support/RasterWorker.js +1 -1
  48. package/layers/support/SceneModification.js +1 -1
  49. package/layers/support/SceneModifications.js +1 -1
  50. package/layers/support/rasterDatasets/MRFRaster.js +1 -1
  51. package/layers/support/rasterFunctions/clipUtils.js +1 -1
  52. package/layers/support/rasterFunctions/rasterFunctionHelper.js +1 -1
  53. package/layers/video/VideoController.js +1 -1
  54. package/layers/video/videoUtils.js +1 -1
  55. package/libs/basisu/BasisUEncoder.js +1 -1
  56. package/libs/dxtEncoder/DXTEncoder.js +1 -1
  57. package/libs/i3s/I3SModule.js +1 -1
  58. package/networks/support/UtilityNetworkLookupHelper.js +1 -1
  59. package/networks/support/utils.js +1 -1
  60. package/package.json +1 -1
  61. package/renderers/support/DictionaryControlString.js +1 -1
  62. package/rest/knowledgeGraph/GraphAddFieldIndexResult.js +1 -1
  63. package/rest/knowledgeGraph/GraphAddNamedTypesResult.js +1 -1
  64. package/rest/knowledgeGraph/GraphAddPropertyResult.js +1 -1
  65. package/rest/knowledgeGraph/GraphDataModelOperationResult.d.ts +1 -1
  66. package/rest/knowledgeGraph/GraphDataModelOperationResult.js +1 -1
  67. package/rest/knowledgeGraph/GraphDeleteFieldIndexResult.js +1 -1
  68. package/rest/knowledgeGraph/GraphDeleteNamedTypeResult.js +1 -1
  69. package/rest/knowledgeGraph/GraphDeletePropertyResult.js +1 -1
  70. package/rest/knowledgeGraph/GraphUpdateNamedTypesResult.js +1 -1
  71. package/rest/knowledgeGraph/GraphUpdatePropertyResult.js +1 -1
  72. package/rest/knowledgeGraph/GraphUpdateSearchIndexResult.js +1 -1
  73. package/support/revision.js +1 -1
  74. package/symbols/cim/cimAnalyzer.js +1 -1
  75. package/views/2d/engine/webgl/shaderGraph/techniques/mesh/MeshWriterInputEvaluator.js +1 -1
  76. package/views/2d/layers/VideoLayerView2D.js +1 -1
  77. package/views/2d/layers/features/FeatureContainer.js +1 -1
  78. package/views/2d/layers/features/processor/ClusterStrategy.js +1 -1
  79. package/views/2d/layers/features/processor/TrackStrategy.js +1 -1
  80. package/views/2d/layers/features/sources/strategies/chunks/Overrides.js +1 -1
  81. package/views/2d/layers/features/support/FeatureFilterEvaluator.js +1 -1
  82. package/views/2d/layers/graphics/GraphicsView2D.js +1 -1
  83. package/views/3d/analysis/images/heading-rotate-svg.js +1 -1
  84. package/views/3d/analysis/images/tilt-rotate-svg.js +1 -1
  85. package/views/3d/interactive/editingTools/draw/DrawGraphicTool3D.js +1 -1
  86. package/views/3d/layers/SceneLayerWorker.js +1 -1
  87. package/views/3d/layers/graphics/Graphics3DCore.js +1 -1
  88. package/views/3d/layers/graphics/pipeline/Tile3DManager.js +1 -1
  89. package/views/3d/state/ViewStateManager.js +1 -1
  90. package/views/3d/webgl-engine/effects/highlight/Highlight.js +1 -1
  91. package/views/3d/webgl-engine/lib/Object3D.js +1 -1
  92. package/views/3d/webgl-engine/materials/internal/bufferWriterUtils.js +1 -1
  93. package/views/VideoView.js +1 -1
  94. package/views/draw/DrawScreenTool.js +1 -1
  95. package/views/draw/MultipointDrawAction.js +1 -1
  96. package/views/draw/PointDrawAction.js +1 -1
  97. package/views/draw/PolygonDrawAction.js +1 -1
  98. package/views/draw/PolylineDrawAction.js +1 -1
  99. package/views/magnifier/mask-svg.js +1 -1
  100. package/views/magnifier/overlay-svg.js +1 -1
  101. package/views/support/TextureCompressionHelper.js +1 -1
  102. package/views/support/TextureCompressionWorker.js +1 -1
  103. package/views/support/TextureCompressionWorkerHandle.js +1 -1
  104. package/webmap/Bookmark.js +1 -1
  105. package/webscene/spec-certification/spec.js +1 -1
  106. package/widgets/BasemapLayerList.js +1 -1
  107. package/widgets/BatchAttributeForm/BatchAttributeFormViewModel.js +1 -1
  108. package/widgets/BatchAttributeForm/inputs/EditableInput.js +1 -1
  109. package/widgets/BatchAttributeForm/inputs/GroupInput.js +1 -1
  110. package/widgets/BatchAttributeForm/inputs/InputBase.d.ts +1 -1
  111. package/widgets/BatchAttributeForm/inputs/InputBase.js +1 -1
  112. package/widgets/Editor/support/SketchController.js +1 -1
  113. package/widgets/Editor/workflowUtils.js +1 -1
  114. package/widgets/Editor.js +1 -1
  115. package/widgets/Feature/FeatureExpression/FeatureExpressionViewModel.js +1 -1
  116. package/widgets/Feature/FeatureViewModel.js +1 -1
  117. package/widgets/Feature/support/arcadeFeatureUtils.js +1 -1
  118. package/widgets/LayerList.js +1 -1
  119. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  120. package/widgets/OrientedImageryViewer/components/ImageViewer.js +1 -1
  121. package/widgets/OrientedImageryViewer/components/ImageViewerViewModel.js +1 -1
  122. package/widgets/OrientedImageryViewer/components/OrientedImageryVideoViewModel.js +1 -1
  123. package/widgets/OrientedImageryViewer/navigation/NavigationManager.js +1 -1
  124. package/widgets/OrientedImageryViewer/navigation/queries.js +1 -1
  125. package/widgets/OrientedImageryViewer/navigation/utils.js +1 -1
  126. package/widgets/OrientedImageryViewer.js +1 -1
  127. package/widgets/PanoramicViewer/PanoramicViewerViewModel.js +1 -1
  128. package/widgets/PanoramicViewer.js +1 -1
  129. package/widgets/Print.js +1 -1
  130. package/widgets/Sketch/SketchViewModel.js +1 -1
  131. package/widgets/Slider/SliderViewModel.js +1 -1
  132. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceFeature.js +1 -1
  133. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceFeaturesDrillIn.js +1 -1
  134. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceViewModel.js +1 -1
  135. package/widgets/support/SelectionList.js +1 -1
  136. package/widgets/support/Selector2D/SelectionOperation.js +1 -1
  137. package/widgets/support/UtilityNetworkAssociations/FeatureUtilityNetworkAssociationsViewModel.js +1 -1
  138. package/assets/esri/core/workers/chunks/0ba6177ba118a0f032e2.js +0 -1
  139. package/assets/esri/core/workers/chunks/573a8393bec916dcf16f.js +0 -1
  140. package/assets/esri/core/workers/chunks/58e74681ddef30ba9cb6.js +0 -1
  141. package/assets/esri/core/workers/chunks/81006d9eed65bbb82962.js +0 -1
  142. package/assets/esri/core/workers/chunks/8fa6c938e8dc7bbfaeb7.js +0 -1
  143. package/assets/esri/core/workers/chunks/9f91d519da67714f915f.js +0 -1
  144. package/assets/esri/core/workers/chunks/ad3871f497ecea1a08c9.js +0 -1
  145. package/assets/esri/core/workers/chunks/bbca1b85656d9ba71e4c.js +0 -1
  146. package/assets/esri/core/workers/chunks/cd64181298d82c8d0e9d.js +0 -1
  147. package/assets/esri/core/workers/chunks/e2cb295104ed2f8cd2ff.js +0 -1
  148. package/assets/esri/core/workers/chunks/f3d5d92e0aefc2593208.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import has from"../../../../core/has.js";import{throwIfAborted as e,createResolver as t}from"../../../../core/promiseUtils.js";import{UpdatingHandles as s}from"../../../../core/support/UpdatingHandles.js";import{AFeatureContainer as i}from"../../engine/AFeatureContainer.js";import{WGLDrawPhase as r,FeatureSelection as n,FeatureBatchingStrategy as a}from"../../engine/webgl/enums.js";import o from"../../engine/webgl/shaderGraph/techniques/FeatureInstanceStore.js";import{Techniques as h}from"../../engine/webgl/shaderGraph/techniques/TechniqueRegistry.js";import{TechniqueType as d}from"../../engine/webgl/shaderGraph/techniques/TechniqueType.js";import{RenderState as l}from"./RenderState.js";import{renderHighlight as u}from"../support/util.js";class c{constructor(e,s){this.id=e,this.version=s,this._resolver=t(),this._done=!1}get done(){return this._done}get promise(){return this._resolver.promise}end(){this._resolver.resolve(),this._done=!0}destroy(){this._resolver.reject()}}class _ extends i{constructor(e){super(e.view.featuresTilingScheme),this.updatingHandles=new s,this._hitTestsRequests=[],this._store=new o,this._visibleTiles=new Set,this._subscriptions=new Map,this._updateStatisticsRequests=[],this._lockStatisticUpdates=!1,this._shouldUnlockAttributeView=!1,this._layerView=e,this.addTransitionable(this._layerView.featureEffectView)}renderChildren(e){if(this._updateAttributeView(),this._renderState?.update(this.attributeView.currentEpoch),this._layerView.requestUpdate(),this._renderState){const e=Array.from(this._renderState.tiles()).filter(e=>e.needsUpload);if(e.length){e[Math.floor(Math.random()*e.length)].upload(),e.length>=2&&this.requestRender()}for(const t of this._renderState.tiles())t.tryReady(this.attributeView.currentEpoch)&&(this._subscriptions.get(t.key.id)?.end(),this._layerView.requestUpdate(),this.hasLabels&&this._layerView.view.labelManager.requestUpdate(),this._layerView.view.labelManager.symbolFader.restartDeclutter(),this.requestRender())}const t=this._layerView.subscriptionManager.updateVisibility();this.setVisibleTiles(t);for(const s of this.children)s.setTransform(e.state);switch(super.renderChildren(e),e.drawPhase){case r.MAP:return this._renderMapPhase(e);case r.HIGHLIGHT:return this._renderHighlightPhase(e);case r.LABEL:return this._renderLabelPhase(e)}}subscriptions(){return this._subscriptions.values()}get _instanceStore(){return this._store}get instanceStore(){return this._store}get layerView(){return this._layerView}get hasLabels(){return this._layerView.labelingCollisionInfos.length>0}get hasHighlight(){return this._layerView.hasHighlight}get _layer(){return this._layerView.layer}_getHeatmapInstance(e){if(null==this._instanceStore||!(e.drawPhase&h.heatmap.drawPhase))return null;for(const t of this._instanceStore.values())if(p(t))return t;return null}get tiles(){return this._renderState?.tiles()}get children(){return this._renderState?Array.from(this._renderState.tiles()).filter(e=>this._visibleTiles.has(e.key.id)):[]}updateAttributeView(e){this.requestRender(),this.attributeView.requestUpdate(e),this.hasLabels&&(this._layerView.view.labelManager.requestUpdate(),this._layerView.view.labelManager.symbolFader.restartDeclutter())}updateSubscriptions(e){for(const{tileId:t,version:s}of e.subscribe)if(this._subscriptions.has(t))this._subscriptions.get(t).version=s;else{const e=new c(t,s);this._subscriptions.set(t,e),this.updatingHandles.addPromise(e.promise)}for(const t of e.unsubscribe){const e=this._subscriptions.get(t);e?.destroy(),this._subscriptions.delete(t),this.removeTile(t)}}isDone(e){return!!this._renderState&&this._renderState.isTileDone(e)}async updateRenderState(e){has("esri-2d-update-debug")&&console.debug(`Version[${e}] FeatureContainer.updateRenderState`),this._renderStateNext=new l(()=>this._stage,e=>this._subscriptions.get(e)?.version,e,this.layerView.view.labelManager.symbolFader,this,this.tileInfoView)}getDisplayStatistics(e,t){const s=this._statisticsByLevel.get(e);return s?s.get(t):null}updateStatistics(e,t){if(this._lockStatisticUpdates)return void this._updateStatisticsRequests.push({level:e,statistics:t});let s=this._statisticsByLevel.get(e);s||(s=new Map,this._statisticsByLevel.set(e,s));for(const i of t)s.set(i.fieldName,{minValue:i.minValue,maxValue:i.maxValue})}lockForOverrides(){this._renderState?.lockUploads(),this._lockStatisticUpdates=!0,this.attributeView.locked||(this.attributeView.lockTextureUploads(),this._shouldUnlockAttributeView=!0)}unlockForOverrides(){this._renderState?.unlockUploads(),this._shouldUnlockAttributeView&&(this.attributeView.unlockTextureUploads(),this._shouldUnlockAttributeView=!1),this._lockStatisticUpdates=!1;for(const e of this._updateStatisticsRequests)this.updateStatistics(e.level,e.statistics);this._updateStatisticsRequests=[],this._renderState?.flush(),this.requestRender()}trySwapRenderState(){if(this._renderStateNext){has("esri-2d-update-debug")&&console.debug(`Version[${this._renderStateNext.version}] FeatureContainer.update.swapRenderState`);const e=new Map;for(const t of this._renderState?.tiles()||[])e.set(t.id,t.metricsVisibility);this._renderState?.destroy(),this._renderState=this._renderStateNext,this._renderState.flush();for(const t of this._renderState.tiles())t.copyMetricsVisibility(e.get(t.id)||new Set);this._renderStateNext=null}this.requestRender()}setVisibleTiles(e){this._visibleTiles=e;for(const t of this.tiles??[])t.rendering=e.has(t.key.id)}async onMessage(t,s){e(s);const i=t.inner;if(!this._subscriptions.has(i.id))return;const r=this._subscriptions.get(i.id);if(r.version!==i.subscriptionVesrion){if(has("esri-2d-update-debug")){const e=`${i.subscriptionVesrion} != ${r.version}`;console.debug(`Version[${e}] Tile[${i.id}] FeatureContainer - Dropping message, outdated version]`,i)}return}const n=this._renderStateNext??this._renderState;if(!n)throw new Error("InternalError: No renderState defined");n.version!==i.version&&console.error(`InternalError: Version mismatch. [renderState: ${n.version}, message: ${i.version}]`),n.enqueueUpdate(t),this.requestRender(),this._layerView.view.labelManager.requestUpdate(),this._layerView.requestUpdate()}removeTile(e){(this._renderState||this._renderStateNext)&&(this._renderState&&this._renderState.removeTile(e),this._renderStateNext&&this._renderStateNext.removeTile(e))}hitTest(e){let s=this._hitTestsRequests.find(({x:t,y:s})=>t===e.x&&s===e.y);const i=t();return s?s.resolvers.push(i):(s={x:e.x,y:e.y,resolvers:[i]},this._hitTestsRequests.push(s)),this.requestRender(),i.promise}getSortKeys(e){const t=new Set(e),s=new Map;for(const i of this.children)if(i.getSortKeys(t).forEach((e,t)=>s.set(t,e)),s.size===t.size)break;return s}get hasAnimation(){return this.hasLabels}doRender(e){const{minScale:t,maxScale:s}=this._layer.effectiveScaleRange,i=e.state.scale;i<=(t||1/0)&&i>=s&&super.doRender(e)}afterRender(e){super.afterRender(e),this._hitTestsRequests.length&&this.requestRender()}setStencilReference(e){if(null==this._getHeatmapInstance(e))super.setStencilReference(e);else for(const t of this.children)t.stencilRef=h.heatmap.getStencilReference(t)}_renderMapPhase(e){this._layerView.featureEffectView.hasEffects?(this._renderOutsideEffect(e),this._renderInsideEffect(e)):this._renderFeatures(e,n.All),this._hitTestsRequests.length>0&&this._renderHittest(e)}_renderHighlightPhase(e){this.hasHighlight&&u(e,!1,e=>{this._renderFeatures(e,n.Highlight)})}_renderLabelPhase(e){this._renderFeatures(e,n.All)}_renderInsideEffect(e){const t=e.painter.effects.insideEffect;t.bind(e),this._renderFeatures(e,n.InsideEffect),t.draw(e,this._layerView.featureEffectView.includedEffects),t.unbind()}_renderOutsideEffect(e){const t=e.painter.effects.outsideEffect;t.bind(e),this._renderFeatures(e,n.OutsideEffect),t.draw(e,this._layerView.featureEffectView.excludedEffects),t.unbind()}_renderHittest(e){const{context:t}=e,s=e.painter.effects.hittest,i=t.getBoundFramebufferObject(),a=t.getViewport(),o=e.passOptions,h=e.drawPhase;s.bind(e),e.passOptions=s.createOptions(e,this._hitTestsRequests),e.drawPhase=r.HITTEST;const{distance:d,smallSymbolDistance:l}=e.passOptions,u=Math.max(d,l);for(const r of this.children)r.visible&&r.containsScreenPoint(e.state,e.passOptions.position,2*u)&&this._renderTile(r,e,n.All);s.draw(e),s.unbind(),t.bindFramebuffer(i),t.restoreViewport(a),e.passOptions=o,e.drawPhase=h}_renderFeatures(e,t){const s=this._getHeatmapInstance(e);null!=s?this._renderHeatmapFeatures(e,t,s):this._renderGeometryFeatures(e,t)}_renderGeometryFeatures(e,t){for(const s of this.children)s.visible&&this._renderTile(s,e,t)}_renderHeatmapFeatures(e,t,s){for(const i of this.children)i.visible&&this._renderTile(i,e,t,d.Heatmap);s.techniqueRef.renderResolvePass(e,s)}_renderTile(e,t,s,i){const r=has("featurelayer-strict-draw-order")?a.STRICT_ORDER:has("featurelayer-force-marker-text-draw-order")?a.STRICT_MARKERS_AND_TEXT:a.BATCHING,n=e.getDisplayList(this._instanceStore,r);t.selection=s,n?.render(t,i)}}function p(e){return e.techniqueRef.type===d.Heatmap}export{_ as FeatureContainer};
5
+ import has from"../../../../core/has.js";import{throwIfAborted as e,createResolver as t}from"../../../../core/promiseUtils.js";import{UpdatingHandles as s}from"../../../../core/support/UpdatingHandles.js";import{AFeatureContainer as i}from"../../engine/AFeatureContainer.js";import{WGLDrawPhase as r,FeatureSelection as n,FeatureBatchingStrategy as a}from"../../engine/webgl/enums.js";import o from"../../engine/webgl/shaderGraph/techniques/FeatureInstanceStore.js";import{Techniques as h}from"../../engine/webgl/shaderGraph/techniques/TechniqueRegistry.js";import{TechniqueType as d}from"../../engine/webgl/shaderGraph/techniques/TechniqueType.js";import{RenderState as l}from"./RenderState.js";import{renderHighlight as u}from"../support/util.js";class c{constructor(e,s){this.id=e,this.version=s,this._resolver=t(),this._done=!1}get done(){return this._done}get promise(){return this._resolver.promise}end(){this._resolver.resolve(),this._done=!0}destroy(){this._resolver.reject()}}class _ extends i{constructor(e){super(e.view.featuresTilingScheme),this.updatingHandles=new s,this._hitTestsRequests=[],this._store=new o,this._visibleTiles=new Set,this._subscriptions=new Map,this._updateStatisticsRequests=[],this._lockStatisticUpdates=!1,this._shouldUnlockAttributeView=!1,this._layerView=e,this.addTransitionable(this._layerView.featureEffectView)}renderChildren(e){if(this._updateAttributeView(),this._renderState?.update(this.attributeView.currentEpoch),this._layerView.requestUpdate(),this._renderState){const e=Array.from(this._renderState.tiles()).filter(e=>e.needsUpload);if(e.length){e[Math.floor(Math.random()*e.length)].upload(),e.length>=2&&this.requestRender()}for(const t of this._renderState.tiles())t.tryReady(this.attributeView.currentEpoch)&&(this._subscriptions.get(t.key.id)?.end(),this._layerView.requestUpdate(),this.hasLabels&&this._layerView.view.labelManager.requestUpdate(),this._layerView.view.labelManager.symbolFader.restartDeclutter(),this.requestRender())}const t=this._layerView.subscriptionManager.updateVisibility();this.setVisibleTiles(t);for(const s of this.children)s.setTransform(e.state);switch(super.renderChildren(e),e.drawPhase){case r.MAP:return this._renderMapPhase(e);case r.HIGHLIGHT:return this._renderHighlightPhase(e);case r.LABEL:return this._renderLabelPhase(e)}}subscriptions(){return this._subscriptions.values()}get _instanceStore(){return this._store}get instanceStore(){return this._store}get layerView(){return this._layerView}get hasLabels(){return this._layerView.labelingCollisionInfos.length>0}get hasHighlight(){return this._layerView.hasHighlight}get _layer(){return this._layerView.layer}_getHeatmapInstance(e){if(null==this._instanceStore||!(e.drawPhase&h.heatmap.drawPhase))return null;for(const t of this._instanceStore.values())if(p(t))return t;return null}get tiles(){return this._renderState?.tiles()}get children(){return this._renderState?Array.from(this._renderState.tiles()).filter(e=>this._visibleTiles.has(e.key.id)):[]}updateAttributeView(e){this.requestRender(),this.attributeView.requestUpdate(e),this.hasLabels&&(this._layerView.view.labelManager.requestUpdate(),this._layerView.view.labelManager.symbolFader.restartDeclutter())}updateSubscriptions(e){for(const{tileId:t,version:s}of e.subscribe){if(!this._subscriptions.has(t)){const e=new c(t,s);this._subscriptions.set(t,e),this.updatingHandles.addPromise(e.promise);continue}this._subscriptions.get(t).version=s}for(const t of e.unsubscribe){const e=this._subscriptions.get(t);e?.destroy(),this._subscriptions.delete(t),this.removeTile(t)}}isDone(e){return!!this._renderState&&this._renderState.isTileDone(e)}async updateRenderState(e){has("esri-2d-update-debug")&&console.debug(`Version[${e}] FeatureContainer.updateRenderState`),this._renderStateNext=new l(()=>this._stage,e=>this._subscriptions.get(e)?.version,e,this.layerView.view.labelManager.symbolFader,this,this.tileInfoView)}getDisplayStatistics(e,t){const s=this._statisticsByLevel.get(e);return s?s.get(t):null}updateStatistics(e,t){if(this._lockStatisticUpdates)return void this._updateStatisticsRequests.push({level:e,statistics:t});let s=this._statisticsByLevel.get(e);s||(s=new Map,this._statisticsByLevel.set(e,s));for(const i of t)s.set(i.fieldName,{minValue:i.minValue,maxValue:i.maxValue})}lockForOverrides(){this._renderState?.lockUploads(),this._lockStatisticUpdates=!0,this.attributeView.locked||(this.attributeView.lockTextureUploads(),this._shouldUnlockAttributeView=!0)}unlockForOverrides(){this._renderState?.unlockUploads(),this._shouldUnlockAttributeView&&(this.attributeView.unlockTextureUploads(),this._shouldUnlockAttributeView=!1),this._lockStatisticUpdates=!1;for(const e of this._updateStatisticsRequests)this.updateStatistics(e.level,e.statistics);this._updateStatisticsRequests=[],this._renderState?.flush(),this.requestRender()}trySwapRenderState(){if(this._renderStateNext){has("esri-2d-update-debug")&&console.debug(`Version[${this._renderStateNext.version}] FeatureContainer.update.swapRenderState`);const e=new Map;for(const t of this._renderState?.tiles()||[])e.set(t.id,t.metricsVisibility);this._renderState?.destroy(),this._renderState=this._renderStateNext,this._renderState.flush();for(const t of this._renderState.tiles())t.copyMetricsVisibility(e.get(t.id)||new Set);this._renderStateNext=null}this.requestRender()}setVisibleTiles(e){this._visibleTiles=e;for(const t of this.tiles??[])t.rendering=e.has(t.key.id)}async onMessage(t,s){e(s);const i=t.inner;if(!this._subscriptions.has(i.id))return;const r=this._subscriptions.get(i.id);if(r.version!==i.subscriptionVesrion){if(has("esri-2d-update-debug")){const e=`${i.subscriptionVesrion} != ${r.version}`;console.debug(`Version[${e}] Tile[${i.id}] FeatureContainer - Dropping message, outdated version]`,i)}return}const n=this._renderStateNext??this._renderState;if(!n)throw new Error("InternalError: No renderState defined");n.version!==i.version&&console.error(`InternalError: Version mismatch. [renderState: ${n.version}, message: ${i.version}]`),n.enqueueUpdate(t),this.requestRender(),this._layerView.view.labelManager.requestUpdate(),this._layerView.requestUpdate()}removeTile(e){(this._renderState||this._renderStateNext)&&(this._renderState&&this._renderState.removeTile(e),this._renderStateNext&&this._renderStateNext.removeTile(e))}hitTest(e){let s=this._hitTestsRequests.find(({x:t,y:s})=>t===e.x&&s===e.y);const i=t();return s?s.resolvers.push(i):(s={x:e.x,y:e.y,resolvers:[i]},this._hitTestsRequests.push(s)),this.requestRender(),i.promise}getSortKeys(e){const t=new Set(e),s=new Map;for(const i of this.children)if(i.getSortKeys(t).forEach((e,t)=>s.set(t,e)),s.size===t.size)break;return s}get hasAnimation(){return this.hasLabels}doRender(e){const{minScale:t,maxScale:s}=this._layer.effectiveScaleRange,i=e.state.scale;i<=(t||1/0)&&i>=s&&super.doRender(e)}afterRender(e){super.afterRender(e),this._hitTestsRequests.length&&this.requestRender()}setStencilReference(e){if(null==this._getHeatmapInstance(e))super.setStencilReference(e);else for(const t of this.children)t.stencilRef=h.heatmap.getStencilReference(t)}_renderMapPhase(e){this._layerView.featureEffectView.hasEffects?(this._renderOutsideEffect(e),this._renderInsideEffect(e)):this._renderFeatures(e,n.All),this._hitTestsRequests.length>0&&this._renderHittest(e)}_renderHighlightPhase(e){this.hasHighlight&&u(e,!1,e=>{this._renderFeatures(e,n.Highlight)})}_renderLabelPhase(e){this._renderFeatures(e,n.All)}_renderInsideEffect(e){const t=e.painter.effects.insideEffect;t.bind(e),this._renderFeatures(e,n.InsideEffect),t.draw(e,this._layerView.featureEffectView.includedEffects),t.unbind()}_renderOutsideEffect(e){const t=e.painter.effects.outsideEffect;t.bind(e),this._renderFeatures(e,n.OutsideEffect),t.draw(e,this._layerView.featureEffectView.excludedEffects),t.unbind()}_renderHittest(e){const{context:t}=e,s=e.painter.effects.hittest,i=t.getBoundFramebufferObject(),a=t.getViewport(),o=e.passOptions,h=e.drawPhase;s.bind(e),e.passOptions=s.createOptions(e,this._hitTestsRequests),e.drawPhase=r.HITTEST;const{distance:d,smallSymbolDistance:l}=e.passOptions,u=Math.max(d,l);for(const r of this.children)r.visible&&r.containsScreenPoint(e.state,e.passOptions.position,2*u)&&this._renderTile(r,e,n.All);s.draw(e),s.unbind(),t.bindFramebuffer(i),t.restoreViewport(a),e.passOptions=o,e.drawPhase=h}_renderFeatures(e,t){const s=this._getHeatmapInstance(e);null!=s?this._renderHeatmapFeatures(e,t,s):this._renderGeometryFeatures(e,t)}_renderGeometryFeatures(e,t){for(const s of this.children)s.visible&&this._renderTile(s,e,t)}_renderHeatmapFeatures(e,t,s){for(const i of this.children)i.visible&&this._renderTile(i,e,t,d.Heatmap);s.techniqueRef.renderResolvePass(e,s)}_renderTile(e,t,s,i){const r=has("featurelayer-strict-draw-order")?a.STRICT_ORDER:has("featurelayer-force-marker-text-draw-order")?a.STRICT_MARKERS_AND_TEXT:a.BATCHING,n=e.getDisplayList(this._instanceStore,r);t.selection=s,n?.render(t,i)}}function p(e){return e.techniqueRef.type===d.Heatmap}export{_ as FeatureContainer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{convertToFeature as e}from"../../../../../layers/graphics/featureConversionUtils.js";import{OptimizedFeature as t}from"../../../../../layers/graphics/OptimizedFeature.js";import s from"../../../../../layers/graphics/OptimizedGeometry.js";import i from"../../../../../layers/support/FieldsIndex.js";import{tileSize as r}from"../../../engine/webgl/definitions.js";import{ComputedAggregateField as n}from"../aggregation/ComputedAggregateField.js";import{GridCell as a}from"../aggregation/GridCell.js";import{pixelsPerMapUnit as l}from"../aggregation/GridSpatialIndex.js";import{AAggregateStrategy as o}from"./AAggregateStrategy.js";import{ASendState as d}from"./AProcessorStrategy.js";import{WithDisplayId as u}from"./support/WithDisplayId.js";import{FeatureTileAppendMessage as c}from"../sources/FeatureSourceMessage.js";import{ComputedAttributeStorage as h}from"../support/ComputedAttributeStorage.js";import p from"../support/FeatureFilterEvaluator.js";import{FeatureMetadata as f}from"../support/FeatureMetadata.js";import{FeatureSetReaderJSON as g}from"../support/FeatureSetReaderJSON.js";import _ from"../../../tiling/TileKey.js";const m=128;class y extends d{constructor(e){super(e),this.didSend=!1,this.done=!1}}class S{constructor(e,t,s,i,r){this._level=e,this._scale=t,this._indexOptions=s,this._clusterRadius=i,this._store=r,this._cells=new Map,this._handledChunks=new Set,this._statistics=new Map,this._clusters=new Map}destroy(){this._clearClusters()}_clearClusters(){for(const e of this._clusters.values())this._store.releaseDisplayIdForObjectId(e.inner.id);this._clusters.clear()}*aggregatesWorldSpace(){for(const e of this._clusters.values()){const s=e.inner.getCentroid(null),i=new t(s,e.inner.getAttributes(),null,e.inner.id,e.displayId);yield i}}clusters(){return this._clusters.values()}updateChunks(e,t){let s=!1;for(const a of e){const e=a.queryInfo;if("tileId"in e){if(new _(e.tileId).level!==this._level)continue}if(!this._handledChunks.has(a.normalizedChunkId)){this._handledChunks.add(a.normalizedChunkId),s=!0;a.getAggregateIndex({...this._indexOptions,scale:this._scale}).put(this._cells)}}const i={xMin:1/0,yMin:1/0,xMax:-1/0,yMax:-1/0},r=l(this._indexOptions.spatialReference,this._scale),n=this._indexOptions.cellSize;for(const{subscription:a}of t){const e=a.tile.bounds,t=Math.floor(e[0]*r/n),s=Math.floor(e[1]*r/n),l=Math.ceil(e[2]*r/n),o=Math.ceil(e[3]*r/n);i.xMin=Math.min(i.xMin,t),i.yMin=Math.min(i.yMin,s),i.xMax=Math.max(i.xMax,l),i.yMax=Math.max(i.yMax,o)}return null!=this._lastCellBounds&&i.xMin===this._lastCellBounds.xMin&&i.yMin===this._lastCellBounds.yMin&&i.yMin===this._lastCellBounds.yMin&&i.yMax===this._lastCellBounds.yMax||(s=!0,this._lastCellBounds=i),s&&this._clusterCells(i),s}async updateStatistics(e){let t=!1;for(const s of this._clusters.values())s.inner.count>1&&(t=this._updateAggregateStatistics(this._statistics,s.inner)||t);if(t){const t=Array.from(this._statistics.entries()).map(([e,t])=>({fieldName:e,minValue:t.minValue,maxValue:t.maxValue}));await e.container.updateStatistics(this._level,t)}}createAggregateFeatures(e,i){const n=e.subscription,a=[],l=n.tile.transform;for(const o of this._clusters.values()){let e=o.inner.getCentroidX(l);const i=o.inner.getCentroidY(l),d=n.tile.lod,u=d.wrap?d.worldSize[0]:null,c=1===o.inner.count?o.inner.firstObjectId:o.inner.id,h=o.displayId;if(null!=u)if(1===u){const n=new s([],[e,i]),l=new t(n,o.inner.getAttributes(),null,c,h);l.geometry.coords[0]-=r,a.push(l);const d=new s([],[e,i]),u=new t(d,o.inner.getAttributes(),null,c,h);u.geometry.coords[0]+=r,a.push(u)}else e>r+r/2?e-=u*r:e<-256&&(e+=u*r);if(e<r+m&&e>=-m&&i<r+m&&i>=-m){const r=new s([],[e,i]),n=new t(r,o.inner.getAttributes(),null,c,h);a.push(n)}}return g.fromOptimizedFeatures(a,i,n.tile.transform)}_clusterCells(e){let t=Array.from(this._cells.values());t=t.sort((e,t)=>t.count-e.count);const s=[];for(const a of this._clusters.values())s.push(a.inner.id);this._clusters.clear();const i=this._clusterRadius*(1/l(this._indexOptions.spatialReference,this._scale)),r=1+this._clusterRadius/this._indexOptions.cellSize,n=new Set;for(const l of t){if(n.has(l.id))continue;if(l.gridX<e.xMin||l.gridX>e.xMax||l.gridY<e.yMin||l.gridY>e.yMax)continue;const t=this._store.createDisplayIdForObjectId(l.id),s=new u(l.clone(),t);n.add(l.id),this._clusters.set(l.id,s);const o=l.centroidXWorld,d=l.centroidYWorld;for(let e=l.gridY-r;e<=l.gridY+r;e++)for(let t=l.gridX-r;t<=l.gridX+r;t++){if(e===l.gridY&&t===l.gridX)continue;const r=this._cells.get(a.createId(t,e));if(!r||n.has(r.id))continue;const u=Math.abs(r.centroidXWorld-o),c=Math.abs(r.centroidYWorld-d);u<i&&c<i&&(s.inner.merge(r),n.add(r.id))}}for(const a of s)this._store.releaseDisplayIdForObjectId(a)}_updateAggregateStatistics(e,t){let s=!1;for(const i of t.statistics.values()){if("esriFieldTypeString"===i.field.type)continue;const t=i.value,r=i.field,n=e.get(r.name);if(n){const{minValue:e,maxValue:i}=n,r=Math.min(n.minValue,t),a=Math.max(n.maxValue,t);e===r&&i===a||(n.minValue=r,n.maxValue=a,s=!0)}else e.set(r.name,{minValue:t,maxValue:t}),s=!0}return s}}class x extends o{static async create(e,t,s,i,r,a,l){const o=new h({spatialReference:s}),d={type:"grid",fields:await Promise.all(t.fields.map(async e=>n.create(o,e))),spatialReference:s,featureFilter:t.featureFilter?await p.create({geometryType:i.metadata.geometryType,hasM:!1,hasZ:!1,timeInfo:i.metadata.timeInfo,fieldsIndex:i.metadata.fieldsIndex,spatialReference:s,filterJSON:t.featureFilter}):null,cellSize:t.clusterRadius/4,arcadeContextInfo:a,sqlOptions:l};return new x(e,t.clusterRadius,d,t.fields,i,r,l)}constructor(e,t,s,r,n,a,l){super(n,a,s.spatialReference,s.fields,l),this._connection=e,this._clusterRadius=t,this._indexOptions=s,this._cellsPerScale=new Map,this._metadata=f.createFeature({geometryType:"esriGeometryPoint",featureIdInfo:{type:"object-id",fieldName:"aggregateId"},fieldsIndex:new i([...r,...this._source.metadata.fieldsIndex.fields,{name:"aggregateId",alias:"aggregateId",type:"esriFieldTypeOID"}]).toJSON(),globalIdField:null,spatialReference:n.metadata.spatialReference,outSpatialReference:n.metadata.outSpatialReference,subtypeField:null,subtypes:null,timeInfo:null,timeReferenceUnknownClient:null,dateFieldsTimeZone:null,typeIdField:null,types:null})}get enablePixelBuffering(){return!1}invalidate(){super.invalidate();for(const e of this._cellsPerScale.values())e.destroy();this._cellsPerScale.clear()}onSubscribe(e){super.onSubscribe(e),this._requiredLevel=e.tile.level,this._requiredScale=e.tile.scale}createState(e){return new y(e)}async*applyOverrideUpdate(e){for(const t of this._cellsPerScale.values())t.destroy();this._cellsPerScale.clear();for(const t of this._sendStates.values())t.done=!1}displayMap(e,t,s){const i=new Map(e.map(e=>[t(e),e])),r=[],n=this._getClusterState(this._requiredLevel,this._requiredScale);for(const a of n.clusters()){const e=i.get(a.inner.id);if(null==e){if(1===a.inner.count){const{firstObjectId:e}=a.inner,t=e?i.get(e):null;if(null!=t){const n=s(a.displayId,t,e);r.push(n),i.delete(e)}}}else{const t=s(a.displayId,e,a.inner.id);r.push(t),i.delete(a.inner.id)}}return r}getDisplayFeatures(t){const s=new Set(t),i=new Set,r=[],n=[],a=this._getClusterState(this._requiredLevel,this._requiredScale);for(const l of a.aggregatesWorldSpace())if(s.has(l.displayId)&&!i.has(l.displayId)){const t=e(l,this._metadata.geometryType,!1,!1);if(i.add(l.displayId),1===t.attributes.cluster_count){r.push({...t,displayId:l.displayId});continue}n.push({...t,displayId:l.displayId})}return{features:r,aggregates:n,tracks:[]}}getFeatureObjectIdsForAggregate(e){const t=this._getClusterState(this._requiredLevel,this._requiredScale);for(const s of t.clusters())if(s.inner.id===e)return Array.from(s.inner.containedObjectIds);return[]}async*updateChunks(){const e=this._source.chunks();if(!e.length)return;const t=this._getClusterState(this._requiredLevel,this._requiredScale),s=Array.from(this._sendStates.values()).filter(e=>e.subscription.tile.level===this._requiredLevel);if(t.updateChunks(e,s)||!this._source.updateTracking.updating)for(const n of s)n.subscription.tile.level===this._requiredLevel&&(n.didSend=!1,n.done=!1);const i=Array.from(this._sendStates.values()).filter(e=>e.done).map(e=>e.subscription.tile.key),r=new Set(i);for(const n of this._sendStates.values()){if(this._source.updateTracking.updating){if(i.some(e=>e.containsChild(n.subscription.tile.key)))continue;if(n.subscription.tile.key.getChildKeys().every(e=>r.has(e)))continue}n.didSend||n.subscription.tile.level!==this._requiredLevel||(n.didSend=!0,yield*this._update(n,t,this._source))}await t.updateStatistics(this._connection)}forEachAggregateWorldSpace(e){if(null==this._requiredLevel||null==this._requiredScale)return;const t=this._getClusterState(this._requiredLevel,this._requiredScale);for(const s of t.aggregatesWorldSpace())e(s)}_getClusterState(e,t){if(null==e||null==t)throw new Error("InternalError: Level and scale must be defined");let s=this._cellsPerScale.get(t);return s||(s=new S(e,t,this._indexOptions,this._clusterRadius,this._attributeStore),this._cellsPerScale.set(t,s)),s}async*_update(e,t,s){if(e.done)return;const i=t.createAggregateFeatures(e,this._metadata);this.events.emit("changed"),e.done=!s.updateTracking.updating;const r=i.getCursor(),n=e.subscription.tile.createArcadeEvaluationOptions(this._indexOptions.arcadeContextInfo);for(;r.next();)this._attributeStore.setAttributeData(r.getDisplayId(),r,n,this._sqlOptions);const a=new c(e.subscription,i,!0,e.done,{});yield a}}export{y as ClusterState,x as ClusterStrategy};
5
+ import{convertToFeature as e}from"../../../../../layers/graphics/featureConversionUtils.js";import{OptimizedFeature as t}from"../../../../../layers/graphics/OptimizedFeature.js";import s from"../../../../../layers/graphics/OptimizedGeometry.js";import i from"../../../../../layers/support/FieldsIndex.js";import{tileSize as r}from"../../../engine/webgl/definitions.js";import{ComputedAggregateField as n}from"../aggregation/ComputedAggregateField.js";import{GridCell as a}from"../aggregation/GridCell.js";import{pixelsPerMapUnit as l}from"../aggregation/GridSpatialIndex.js";import{AAggregateStrategy as o}from"./AAggregateStrategy.js";import{ASendState as d}from"./AProcessorStrategy.js";import{WithDisplayId as u}from"./support/WithDisplayId.js";import{FeatureTileAppendMessage as c}from"../sources/FeatureSourceMessage.js";import{ComputedAttributeStorage as h}from"../support/ComputedAttributeStorage.js";import p from"../support/FeatureFilterEvaluator.js";import{FeatureMetadata as f}from"../support/FeatureMetadata.js";import{FeatureSetReaderJSON as g}from"../support/FeatureSetReaderJSON.js";import _ from"../../../tiling/TileKey.js";const m=128;class y extends d{constructor(e){super(e),this.didSend=!1,this.done=!1}}class S{constructor(e,t,s,i,r){this._level=e,this._scale=t,this._indexOptions=s,this._clusterRadius=i,this._store=r,this._cells=new Map,this._handledChunks=new Set,this._statistics=new Map,this._clusters=new Map}destroy(){this._clearClusters()}_clearClusters(){for(const e of this._clusters.values())this._store.releaseDisplayIdForObjectId(e.inner.id);this._clusters.clear()}*aggregatesWorldSpace(){for(const e of this._clusters.values()){const s=e.inner.getCentroid(null),i=new t(s,e.inner.getAttributes(),null,e.inner.id,e.displayId);yield i}}clusters(){return this._clusters.values()}updateChunks(e,t){let s=!1;for(const a of e){const e=a.queryInfo;if("tileId"in e){if(new _(e.tileId).level!==this._level)continue}if(!this._handledChunks.has(a.normalizedChunkId)){this._handledChunks.add(a.normalizedChunkId),s=!0;a.getAggregateIndex({...this._indexOptions,scale:this._scale}).put(this._cells)}}const i={xMin:1/0,yMin:1/0,xMax:-1/0,yMax:-1/0},r=l(this._indexOptions.spatialReference,this._scale),n=this._indexOptions.cellSize;for(const{subscription:a}of t){const e=a.tile.bounds,t=Math.floor(e[0]*r/n),s=Math.floor(e[1]*r/n),l=Math.ceil(e[2]*r/n),o=Math.ceil(e[3]*r/n);i.xMin=Math.min(i.xMin,t),i.yMin=Math.min(i.yMin,s),i.xMax=Math.max(i.xMax,l),i.yMax=Math.max(i.yMax,o)}return null!=this._lastCellBounds&&i.xMin===this._lastCellBounds.xMin&&i.yMin===this._lastCellBounds.yMin&&i.yMin===this._lastCellBounds.yMin&&i.yMax===this._lastCellBounds.yMax||(s=!0,this._lastCellBounds=i),s&&this._clusterCells(i),s}async updateStatistics(e){let t=!1;for(const s of this._clusters.values())s.inner.count>1&&(t=this._updateAggregateStatistics(this._statistics,s.inner)||t);if(t){const t=Array.from(this._statistics.entries()).map(([e,t])=>({fieldName:e,minValue:t.minValue,maxValue:t.maxValue}));await e.container.updateStatistics(this._level,t)}}createAggregateFeatures(e,i){const n=e.subscription,a=[],l=n.tile.transform;for(const o of this._clusters.values()){let e=o.inner.getCentroidX(l);const i=o.inner.getCentroidY(l),d=n.tile.lod,u=d.wrap?d.worldSize[0]:null,c=1===o.inner.count?o.inner.firstObjectId:o.inner.id,h=o.displayId;if(null!=u)if(1===u){const n=new s([],[e,i]),l=new t(n,o.inner.getAttributes(),null,c,h);l.geometry.coords[0]-=r,a.push(l);const d=new s([],[e,i]),u=new t(d,o.inner.getAttributes(),null,c,h);u.geometry.coords[0]+=r,a.push(u)}else e>r+r/2?e-=u*r:e<-256&&(e+=u*r);if(e<r+m&&e>=-m&&i<r+m&&i>=-m){const r=new s([],[e,i]),n=new t(r,o.inner.getAttributes(),null,c,h);a.push(n)}}return g.fromOptimizedFeatures(a,i,n.tile.transform)}_clusterCells(e){let t=Array.from(this._cells.values());t=t.sort((e,t)=>t.count-e.count);const s=[];for(const a of this._clusters.values())s.push(a.inner.id);this._clusters.clear();const i=this._clusterRadius*(1/l(this._indexOptions.spatialReference,this._scale)),r=1+this._clusterRadius/this._indexOptions.cellSize,n=new Set;for(const l of t){if(n.has(l.id))continue;if(l.gridX<e.xMin||l.gridX>e.xMax||l.gridY<e.yMin||l.gridY>e.yMax)continue;const t=this._store.createDisplayIdForObjectId(l.id),s=new u(l.clone(),t);n.add(l.id),this._clusters.set(l.id,s);const o=l.centroidXWorld,d=l.centroidYWorld;for(let e=l.gridY-r;e<=l.gridY+r;e++)for(let t=l.gridX-r;t<=l.gridX+r;t++){if(e===l.gridY&&t===l.gridX)continue;const r=this._cells.get(a.createId(t,e));if(!r||n.has(r.id))continue;const u=Math.abs(r.centroidXWorld-o),c=Math.abs(r.centroidYWorld-d);u<i&&c<i&&(s.inner.merge(r),n.add(r.id))}}for(const a of s)this._store.releaseDisplayIdForObjectId(a)}_updateAggregateStatistics(e,t){let s=!1;for(const i of t.statistics.values()){if("esriFieldTypeString"===i.field.type)continue;const t=i.value,r=i.field,n=e.get(r.name);if(n){const{minValue:e,maxValue:i}=n,r=Math.min(n.minValue,t),a=Math.max(n.maxValue,t);e===r&&i===a||(n.minValue=r,n.maxValue=a,s=!0);continue}e.set(r.name,{minValue:t,maxValue:t}),s=!0}return s}}class x extends o{static async create(e,t,s,i,r,a,l){const o=new h({spatialReference:s}),d={type:"grid",fields:await Promise.all(t.fields.map(async e=>n.create(o,e))),spatialReference:s,featureFilter:t.featureFilter?await p.create({geometryType:i.metadata.geometryType,hasM:!1,hasZ:!1,timeInfo:i.metadata.timeInfo,fieldsIndex:i.metadata.fieldsIndex,spatialReference:s,filterJSON:t.featureFilter}):null,cellSize:t.clusterRadius/4,arcadeContextInfo:a,sqlOptions:l};return new x(e,t.clusterRadius,d,t.fields,i,r,l)}constructor(e,t,s,r,n,a,l){super(n,a,s.spatialReference,s.fields,l),this._connection=e,this._clusterRadius=t,this._indexOptions=s,this._cellsPerScale=new Map,this._metadata=f.createFeature({geometryType:"esriGeometryPoint",featureIdInfo:{type:"object-id",fieldName:"aggregateId"},fieldsIndex:new i([...r,...this._source.metadata.fieldsIndex.fields,{name:"aggregateId",alias:"aggregateId",type:"esriFieldTypeOID"}]).toJSON(),globalIdField:null,spatialReference:n.metadata.spatialReference,outSpatialReference:n.metadata.outSpatialReference,subtypeField:null,subtypes:null,timeInfo:null,timeReferenceUnknownClient:null,dateFieldsTimeZone:null,typeIdField:null,types:null})}get enablePixelBuffering(){return!1}invalidate(){super.invalidate();for(const e of this._cellsPerScale.values())e.destroy();this._cellsPerScale.clear()}onSubscribe(e){super.onSubscribe(e),this._requiredLevel=e.tile.level,this._requiredScale=e.tile.scale}createState(e){return new y(e)}async*applyOverrideUpdate(e){for(const t of this._cellsPerScale.values())t.destroy();this._cellsPerScale.clear();for(const t of this._sendStates.values())t.done=!1}displayMap(e,t,s){const i=new Map(e.map(e=>[t(e),e])),r=[],n=this._getClusterState(this._requiredLevel,this._requiredScale);for(const a of n.clusters()){const e=i.get(a.inner.id);if(null!=e){const t=s(a.displayId,e,a.inner.id);r.push(t),i.delete(a.inner.id);continue}if(1===a.inner.count){const{firstObjectId:e}=a.inner,t=e?i.get(e):null;if(null!=t){const n=s(a.displayId,t,e);r.push(n),i.delete(e)}}}return r}getDisplayFeatures(t){const s=new Set(t),i=new Set,r=[],n=[],a=this._getClusterState(this._requiredLevel,this._requiredScale);for(const l of a.aggregatesWorldSpace())if(s.has(l.displayId)&&!i.has(l.displayId)){const t=e(l,this._metadata.geometryType,!1,!1);if(i.add(l.displayId),1===t.attributes.cluster_count){r.push({...t,displayId:l.displayId});continue}n.push({...t,displayId:l.displayId})}return{features:r,aggregates:n,tracks:[]}}getFeatureObjectIdsForAggregate(e){const t=this._getClusterState(this._requiredLevel,this._requiredScale);for(const s of t.clusters())if(s.inner.id===e)return Array.from(s.inner.containedObjectIds);return[]}async*updateChunks(){const e=this._source.chunks();if(!e.length)return;const t=this._getClusterState(this._requiredLevel,this._requiredScale),s=Array.from(this._sendStates.values()).filter(e=>e.subscription.tile.level===this._requiredLevel);if(t.updateChunks(e,s)||!this._source.updateTracking.updating)for(const n of s)n.subscription.tile.level===this._requiredLevel&&(n.didSend=!1,n.done=!1);const i=Array.from(this._sendStates.values()).filter(e=>e.done).map(e=>e.subscription.tile.key),r=new Set(i);for(const n of this._sendStates.values()){if(this._source.updateTracking.updating){if(i.some(e=>e.containsChild(n.subscription.tile.key)))continue;if(n.subscription.tile.key.getChildKeys().every(e=>r.has(e)))continue}n.didSend||n.subscription.tile.level!==this._requiredLevel||(n.didSend=!0,yield*this._update(n,t,this._source))}await t.updateStatistics(this._connection)}forEachAggregateWorldSpace(e){if(null==this._requiredLevel||null==this._requiredScale)return;const t=this._getClusterState(this._requiredLevel,this._requiredScale);for(const s of t.aggregatesWorldSpace())e(s)}_getClusterState(e,t){if(null==e||null==t)throw new Error("InternalError: Level and scale must be defined");let s=this._cellsPerScale.get(t);return s||(s=new S(e,t,this._indexOptions,this._clusterRadius,this._attributeStore),this._cellsPerScale.set(t,s)),s}async*_update(e,t,s){if(e.done)return;const i=t.createAggregateFeatures(e,this._metadata);this.events.emit("changed"),e.done=!s.updateTracking.updating;const r=i.getCursor(),n=e.subscription.tile.createArcadeEvaluationOptions(this._indexOptions.arcadeContextInfo);for(;r.next();)this._attributeStore.setAttributeData(r.getDisplayId(),r,n,this._sqlOptions);const a=new c(e.subscription,i,!0,e.done,{});yield a}}export{y as ClusterState,x as ClusterStrategy};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{isSome as t}from"../../../../../core/arrayUtils.js";import e from"../../../../../core/Logger.js";import{assertIsSome as s}from"../../../../../core/maybe.js";import{isLoaded as r,load as i,execute as a}from"../../../../../geometry/operators/gx/operatorGeodeticDensify.js";import{geodeticCurveType as o}from"../../../../../geometry/operators/support/geodeticCurveType.js";import{intersectsWithMargin as n,fromValues as l,intersects as c,empty as d,expandPointInPlace as u}from"../../../../../geometry/support/aaBoundingRect.js";import{getClosestDenormalizedXToReference as h}from"../../../../../geometry/support/normalizeUtils.js";import{normalizeCentralMeridianForDisplay as m}from"../../../../../geometry/support/normalizeUtilsSync.js";import{quantizeOptimizedGeometry as p,convertToGeometry as f,convertFromNestedArray as g}from"../../../../../layers/graphics/featureConversionUtils.js";import{OptimizedFeature as _}from"../../../../../layers/graphics/OptimizedFeature.js";import b from"../../../../../layers/graphics/OptimizedGeometry.js";import{internalTrackPartField as y,TrackPart as I,externalTrackLineOidPrefix as k,internalTimeReceivedField as v}from"../../../../../layers/support/streamLayerUtils.js";import{tileSize as F}from"../../../engine/webgl/definitions.js";import{AccumulatedStatistics as j}from"../aggregation/AccumulatedStatistics.js";import{ComputedAggregateField as O}from"../aggregation/ComputedAggregateField.js";import{AAggregateStrategy as T}from"./AAggregateStrategy.js";import{ASendState as x}from"./AProcessorStrategy.js";import{FeatureTileAppendMessage as S}from"../sources/FeatureSourceMessage.js";import{createArcadeEvaluationOptions as R}from"../support/arcadeUtils.js";import{ComputedAttributeStorage as w}from"../support/ComputedAttributeStorage.js";import D from"../support/FeatureFilterEvaluator.js";import{FeatureMetadata as L}from"../support/FeatureMetadata.js";import{FeatureSetReaderIndirect as A}from"../support/FeatureSetReaderIndirect.js";import{FeatureSetReaderJSON as C}from"../support/FeatureSetReaderJSON.js";let G;const P=()=>e.getLogger("esri.views.2d.layers.features.processor.TrackStrategy"),z=32;class M{constructor(t,e,s,r,i){this.chunkIndex=t,this.featureIndex=e,this.objectId=s,this.displayId=r,this.time=i}}class W{static getOid(t){return k+t}constructor(t,e,s,r,i,a,o,n){this._schema=t,this.trackId=e,this.objectId=s,this.displayId=r,this._fields=i,this._spatialReference=a,this._metadata=o,this._isStream=n,this._maxDisplayDuration=this._schema.maxDisplayDuration>0?this._schema.maxDisplayDuration:1/0,this._maxDisplayObservationsPerTrack=this._schema.maxDisplayObservationsPerTrack>=1?this._schema.maxDisplayObservationsPerTrack:1/0,this._observationRecords=[],this._nextObservationRecords=[],this._trackLinePath=[],this._bounds=[],this._trackLineGeometry=new b}get _trackLineAttributes(){const t={...this._latestObservationFeature?.attributes??{},aggregateId:this.objectId,[y]:I.TrackLine};if(null!=this._statistics)for(const e of this._statistics.values())t[e.field.name]=e.value;return t}get _startTimeField(){return this._metadata.timeInfo?.startTimeField}get length(){return this._observationRecords.length}*observations(){yield*this._observationRecords}*previousObservations(){for(let t=0;t<this._observationRecords.length-1;t++)yield this._observationRecords[t]}stageObservation(t,e){this._nextObservationRecords.push(new M(t,e.getIndex(),e.getObjectId(),e.getDisplayId(),null!=this._startTimeField?e.readAttributeAsTimestamp(this._startTimeField):null))}commitObservations(t,e){const r=new Set(this._nextObservationRecords.map(t=>t.objectId)),i=this._observationRecords.filter(t=>!r.has(t.objectId)).map(t=>t.objectId);let a,o;switch(this._observationRecords=[],this._trackLinePath=[],this._isStream||null==this._startTimeField||this._nextObservationRecords.sort((t,e)=>{const s=t.time,r=e.time;return null!=s&&null!=r?s-r:0}),this._schema.timeField){case"startTimeField":a=this._metadata.timeInfo?.startTimeField;break;case"endTimeField":a=this._metadata.timeInfo?.endTimeField;break;case"timeReceived":a=this._isStream?v:null}o=this._isStream?e?.end??Date.now():e?.end??-1/0;const n=t.map(t=>t.reader.getCursor());let l;for(let c=this._nextObservationRecords.length-1;c>=0&&!(this._observationRecords.length>=this._maxDisplayObservationsPerTrack);c--){const t=this._nextObservationRecords[c],e=n[t.chunkIndex];s(e),e.setIndex(t.featureIndex);const r=null!=a?e.readAttributeAsTimestamp(a):null;(null!=r?o-r:0)>=this._maxDisplayDuration||(this._commitObservation(t,e),l??=t)}if(null!=l){const{chunkIndex:t,featureIndex:e,objectId:r,displayId:i}=l,a=n[t];s(a),a.setIndex(e);const o=new _(a.readGeometryWorldSpace(),{...a.readAttributes(),[y]:I.LatestObservation},null,r,i);this._latestObservationFeature=o}else this._latestObservationFeature=null;return this._trackLineGeometry=E(this._trackLineGeometry,this._trackLinePath,this._spatialReference),this._bounds=X(this._trackLineGeometry),this._nextObservationRecords=[],i}updateStatistics(t,e){this._statistics=j.create(this._fields);const r=t.map(t=>t.reader.getCursor());for(const{chunkIndex:i,featureIndex:a}of this._observationRecords){const t=r[i];s(t),t.setIndex(a),this._statistics.insert(t,e)}}overlapsTile(t){for(const e of this._bounds)if(n(e,t.bounds,z))return!0;return!1}getLatestObservationFeatureForTile(t){if(null==this._latestObservationFeature)return null;const{objectId:e,displayId:s,geometry:r,attributes:i}=this._latestObservationFeature,a=new b;p(a,r,!1,!1,this._metadata.geometryType,t.subscription.tile.transform);const o=l(1/0,1/0,-1/0,-1/0);N(a,(t,e)=>u(o,[t,e]));if(!c(o,l(0,0,F,F)))return null;return new _(a,i,null,e,s)}getTrackLineFeatureForTile(t){const e=new b;p(e,this._trackLineGeometry,!1,!1,"esriGeometryPolyline",t.subscription.tile.transform);return new _(e,this._trackLineAttributes,null,this.objectId,this.displayId)}getTrackLineOptimizedFeature(){return new _(this._trackLineGeometry,this._trackLineAttributes,null,this.objectId,this.displayId)}getTrackLineDisplayFeature(){const{_trackLineGeometry:t,_trackLineAttributes:e,displayId:s}=this;return{geometry:f(t,"esriGeometryPolyline",!1,!1),attributes:e,displayId:s}}_commitObservation(t,e){const s=e.readCentroidWorldSpace();let r=s?.coords[0],i=s?.coords[1];null==s&&(r=e.readXWorldSpace(),i=e.readYWorldSpace()),null!=r&&null!=i&&(this._observationRecords.unshift(t),this._trackLinePath.unshift([r,i]))}}class U extends x{constructor(t){super(t),this.done=!1}}class q extends T{static async create(t,e,s,a,o,n){const l=new w({spatialReference:e}),c=await Promise.all(t.fields.map(async t=>O.create(l,t))),d=t.featureFilter?await D.create({geometryType:s.metadata.geometryType,hasM:!1,hasZ:!1,timeInfo:s.metadata.timeInfo,fieldsIndex:s.metadata.fieldsIndex,spatialReference:e,filterJSON:t.featureFilter}):null;return e.isWrappable||r()||await Promise.all([import("../../../../../geometry/operators/support/apiConverter.js"),import("../../../../../geometry/operators/support/jsonConverter.js"),i()]).then(([t,e,s])=>{G={fromGeometryToGXGeometry:e.fromGeometryToGXGeometry,toGeometry:e.toGeometry,fromSpatialReference:t.fromSpatialReference}}),new q(t,s,a,e,c,d,o,n)}constructor(t,e,s,r,i,a,o,n){super(e,s,r,i,n),this._schema=t,this._featureFilter=a,this._arcadeContextInfo=o,this._tracks=new Map,this._handledChunks=new Set,this._metadata=e.metadata.weakCloneWithAdditionalFields([{name:y,alias:"trackPart",type:"esriFieldTypeSmallInteger"}]),this._trackLineMetadata=L.createFeature({geometryType:"esriGeometryPolyline",featureIdInfo:{type:"object-id",fieldName:"aggregateId"},fieldsIndex:{fields:[...this._source.metadata.fieldsIndex.fields,...this.aggregateFields,{name:y,alias:"trackPart",type:"esriFieldTypeSmallInteger"},{name:"aggregateId",alias:"aggregateId",type:"esriFieldTypeOID"}],timeZoneByFieldName:null},globalIdField:null,spatialReference:e.metadata.spatialReference,outSpatialReference:e.metadata.outSpatialReference,subtypeField:null,subtypes:null,timeInfo:e.metadata.timeInfo,timeReferenceUnknownClient:null,dateFieldsTimeZone:null,typeIdField:null,types:null})}get _isStream(){return this._source.isStream}get enablePixelBuffering(){return!0}get isAggregate(){return!1}requiresInvalidation(){const t=new Set(this._source.chunks().map(t=>t.chunkId));for(const e of t)if(!this._handledChunks.has(e))return!0;for(const e of this._handledChunks)if(!t.has(e))return!0;return!1}invalidate(){this._handledChunks.clear(),super.invalidate()}createState(t){return new U(t)}async*applyOverrideUpdate(t){P().error("Applying override to tracks is not supported")}displayMap(t,e,s){const r=new Map(t.map(t=>[e(t),t])),i=[];for(const a of this._tracks.values()){const t=r.get(a.objectId);if(null==t)for(const e of a.observations()){const t=r.get(e.objectId);if(null!=t){const a=s(e.displayId,t,e.objectId);i.push(a),r.delete(e.objectId)}}else{const e=s(a.displayId,t,a.objectId);i.push(e),r.delete(a.objectId)}}return i}getDisplayFeatures(t){const e=new Set(t),s=[],r=[],i=this._source.chunks().map(t=>t.reader.getCursor());for(const a of this._tracks.values()){e.has(a.displayId)&&r.push(a.getTrackLineDisplayFeature());for(const{displayId:t,chunkIndex:r,featureIndex:o}of a.observations())if(e.has(t)){const e=i[r];e.setIndex(o),s.push({displayId:t,attributes:{},...e.readLegacyFeatureWorldSpace()})}}return{features:s,aggregates:[],tracks:r}}getFeatureObjectIdsForAggregate(t){for(const e of this._tracks.values())if(e.objectId===t)return Array.from(e.observations(),t=>t.objectId);return[]}async*updateChunks(){0===this._handledChunks.size&&this._rebuildTracks();for(const t of this._sendStates.values())yield*this._update(t)}forEachAggregateWorldSpace(t){for(const e of this._tracks.values())t(e.getTrackLineOptimizedFeature())}_rebuildTracks(){const t=this._source.chunks();if(!t.length)return;const e=this._metadata.timeInfo?.trackIdField;if(null==e)return;const s=new Set;for(let r=0;r<t.length;r++){const i=t[r];this._handledChunks.add(i.chunkId);const a=i.reader.getCursor();for(;a.next();){const t=a.readAttribute(e),i=a.getObjectId();if(null!=t&&null!=i&&(null===this._featureFilter||this._featureFilter.check(a,this._sqlOptions))){if(a.getDisplayId()||a.setDisplayId(this._attributeStore.createDisplayIdForObjectId(i)),!this._tracks.has(t)){const e=W.getOid(t),s=this._attributeStore.createDisplayIdForObjectId(e),r=new W(this._schema,t,e,s,this.aggregateFields,this.spatialReference,this._source.metadata,this._isStream);this._tracks.set(t,r)}this._tracks.get(t).stageObservation(r,a),s.add(t)}}}for(const r of this._tracks.values())if(s.has(r.trackId)){const e=r.commitObservations(t,this._featureFilter?.timeExtent);for(const t of e)this._attributeStore.releaseDisplayIdForObjectId(t);r.updateStatistics(t,R(1,this._arcadeContextInfo))}else this._removeTrack(r)}_removeTrack(t){this._tracks.delete(t.trackId),this._attributeStore.releaseDisplayIdForObjectId(t.objectId);for(const{objectId:e}of t.observations())this._attributeStore.releaseDisplayIdForObjectId(e)}*_update(e){if(e.done)return;e.done=!this._source.updateTracking.updating;const s=[],r=[];for(const t of this._tracks.values())if(t.length>0){if(this._schema.showLatestObservation){const r=t.getLatestObservationFeatureForTile(e);null!=r&&s.push(r)}this._schema.showTrackLine&&t.overlapsTile(e.subscription.tile)&&r.push(t.getTrackLineFeatureForTile(e))}const i=C.fromOptimizedFeatures(s,this._metadata,e.subscription.tile.transform),a=C.fromOptimizedFeatures(r,this._trackLineMetadata,e.subscription.tile.transform);let o=[];if(this._schema.showPreviousObservations){const s=this._source.chunks().map(()=>[]);for(const t of this._tracks.values())for(const{chunkIndex:e,featureIndex:r}of t.previousObservations())s[e].push(r);o=this._source.chunks().map((t,r)=>{const i=t.getTileReader(e.subscription.tile);if(null==i)return null;const a=A.from(i,s[r]);return a.setProcessorAttributes({[y]:I.PreviousObservation}),"esriGeometryPoint"!==a.geometryType&&null!=a.getInTransform()||a.setTransformForDisplay(e.subscription.tile.transform),a}).filter(t)}this.events.emit("changed");const n=e.subscription.tile.createArcadeEvaluationOptions(this._arcadeContextInfo),l=a.getCursor();for(;l.next();)this._attributeStore.setAttributeData(l.getDisplayId(),l,n,this._sqlOptions);for(const t of o){const e=t.getCursor();for(;e.next();)this._attributeStore.setAttributeData(e.getDisplayId(),e,n,this._sqlOptions)}const c=i.getCursor();for(;c.next();)this._attributeStore.setAttributeData(c.getDisplayId(),c,n,this._sqlOptions);yield new S(e.subscription,a,!1,!1,{});for(const t of o)yield new S(e.subscription,t,!1,!1,{});yield new S(e.subscription,i,!1,e.done,{})}}function E(t,e,s){if(e.length<2)return g(t,[e],!1,!1);if(s.isWrappable){let r=!1;for(let t=1;t<e.length;t++){const i=e[t][0],a=h(i,e[t-1][0],s);i!==a&&(e[t][0]=a,r=!0)}if(r){const r=m({paths:[e],spatialReference:s});if(null!=r)return g(t,r.paths,!1,!1)}return g(t,[e],!1,!1)}const r=G.fromGeometryToGXGeometry({hasM:!1,hasZ:!1,paths:[e]}),i=G.fromSpatialReference(s);if(null!=i){const e=a(r,1e6,i,o.geodesic);if(null!=e){const s=G.toGeometry(e,i);if(null!=s&&"paths"in s)return g(t,s.paths,!1,!1)}}return g(t,[e],!1,!1)}function N(t,e){const s=2,{coords:r,lengths:i}=t;if(!i.length)return void e(r[0],r[1]);let a=0;for(let o=0;o<i.length;o++){const t=i[o];let n=0,l=0;for(let i=0;i<t;i++)n+=r[s*(i+a)],l+=r[s*(i+a)+1],e(n,l);a+=t}}function X(t){const{lengths:e,coords:s}=t,r=2;if(!e.length)return[d()];const i=[];let a=0;for(let o=0;o<e.length;o++){const t=e[o],n=d();i.push(n);for(let e=0;e<t;e++){const t=s[r*(e+a)],i=s[r*(e+a)+1];u(n,[t,i])}a+=t}return i}export{q as TrackStrategy};
5
+ import{isSome as t}from"../../../../../core/arrayUtils.js";import e from"../../../../../core/Logger.js";import{assertIsSome as s}from"../../../../../core/maybe.js";import{isLoaded as r,load as i,execute as a}from"../../../../../geometry/operators/gx/operatorGeodeticDensify.js";import{geodeticCurveType as o}from"../../../../../geometry/operators/support/geodeticCurveType.js";import{intersectsWithMargin as n,fromValues as l,intersects as c,empty as d,expandPointInPlace as u}from"../../../../../geometry/support/aaBoundingRect.js";import{getClosestDenormalizedXToReference as h}from"../../../../../geometry/support/normalizeUtils.js";import{normalizeCentralMeridianForDisplay as m}from"../../../../../geometry/support/normalizeUtilsSync.js";import{quantizeOptimizedGeometry as p,convertToGeometry as f,convertFromNestedArray as g}from"../../../../../layers/graphics/featureConversionUtils.js";import{OptimizedFeature as _}from"../../../../../layers/graphics/OptimizedFeature.js";import b from"../../../../../layers/graphics/OptimizedGeometry.js";import{internalTrackPartField as y,TrackPart as I,externalTrackLineOidPrefix as k,internalTimeReceivedField as v}from"../../../../../layers/support/streamLayerUtils.js";import{tileSize as F}from"../../../engine/webgl/definitions.js";import{AccumulatedStatistics as j}from"../aggregation/AccumulatedStatistics.js";import{ComputedAggregateField as O}from"../aggregation/ComputedAggregateField.js";import{AAggregateStrategy as T}from"./AAggregateStrategy.js";import{ASendState as x}from"./AProcessorStrategy.js";import{FeatureTileAppendMessage as S}from"../sources/FeatureSourceMessage.js";import{createArcadeEvaluationOptions as R}from"../support/arcadeUtils.js";import{ComputedAttributeStorage as w}from"../support/ComputedAttributeStorage.js";import D from"../support/FeatureFilterEvaluator.js";import{FeatureMetadata as L}from"../support/FeatureMetadata.js";import{FeatureSetReaderIndirect as A}from"../support/FeatureSetReaderIndirect.js";import{FeatureSetReaderJSON as C}from"../support/FeatureSetReaderJSON.js";let G;const P=()=>e.getLogger("esri.views.2d.layers.features.processor.TrackStrategy"),z=32;class M{constructor(t,e,s,r,i){this.chunkIndex=t,this.featureIndex=e,this.objectId=s,this.displayId=r,this.time=i}}class W{static getOid(t){return k+t}constructor(t,e,s,r,i,a,o,n){this._schema=t,this.trackId=e,this.objectId=s,this.displayId=r,this._fields=i,this._spatialReference=a,this._metadata=o,this._isStream=n,this._maxDisplayDuration=this._schema.maxDisplayDuration>0?this._schema.maxDisplayDuration:1/0,this._maxDisplayObservationsPerTrack=this._schema.maxDisplayObservationsPerTrack>=1?this._schema.maxDisplayObservationsPerTrack:1/0,this._observationRecords=[],this._nextObservationRecords=[],this._trackLinePath=[],this._bounds=[],this._trackLineGeometry=new b}get _trackLineAttributes(){const t={...this._latestObservationFeature?.attributes??{},aggregateId:this.objectId,[y]:I.TrackLine};if(null!=this._statistics)for(const e of this._statistics.values())t[e.field.name]=e.value;return t}get _startTimeField(){return this._metadata.timeInfo?.startTimeField}get length(){return this._observationRecords.length}*observations(){yield*this._observationRecords}*previousObservations(){for(let t=0;t<this._observationRecords.length-1;t++)yield this._observationRecords[t]}stageObservation(t,e){this._nextObservationRecords.push(new M(t,e.getIndex(),e.getObjectId(),e.getDisplayId(),null!=this._startTimeField?e.readAttributeAsTimestamp(this._startTimeField):null))}commitObservations(t,e){const r=new Set(this._nextObservationRecords.map(t=>t.objectId)),i=this._observationRecords.filter(t=>!r.has(t.objectId)).map(t=>t.objectId);let a,o;switch(this._observationRecords=[],this._trackLinePath=[],this._isStream||null==this._startTimeField||this._nextObservationRecords.sort((t,e)=>{const s=t.time,r=e.time;return null!=s&&null!=r?s-r:0}),this._schema.timeField){case"startTimeField":a=this._metadata.timeInfo?.startTimeField;break;case"endTimeField":a=this._metadata.timeInfo?.endTimeField;break;case"timeReceived":a=this._isStream?v:null}o=this._isStream?e?.end??Date.now():e?.end??-1/0;const n=t.map(t=>t.reader.getCursor());let l;for(let c=this._nextObservationRecords.length-1;c>=0&&!(this._observationRecords.length>=this._maxDisplayObservationsPerTrack);c--){const t=this._nextObservationRecords[c],e=n[t.chunkIndex];s(e),e.setIndex(t.featureIndex);const r=null!=a?e.readAttributeAsTimestamp(a):null;(null!=r?o-r:0)>=this._maxDisplayDuration||(this._commitObservation(t,e),l??=t)}if(null!=l){const{chunkIndex:t,featureIndex:e,objectId:r,displayId:i}=l,a=n[t];s(a),a.setIndex(e);const o=new _(a.readGeometryWorldSpace(),{...a.readAttributes(),[y]:I.LatestObservation},null,r,i);this._latestObservationFeature=o}else this._latestObservationFeature=null;return this._trackLineGeometry=E(this._trackLineGeometry,this._trackLinePath,this._spatialReference),this._bounds=X(this._trackLineGeometry),this._nextObservationRecords=[],i}updateStatistics(t,e){this._statistics=j.create(this._fields);const r=t.map(t=>t.reader.getCursor());for(const{chunkIndex:i,featureIndex:a}of this._observationRecords){const t=r[i];s(t),t.setIndex(a),this._statistics.insert(t,e)}}overlapsTile(t){for(const e of this._bounds)if(n(e,t.bounds,z))return!0;return!1}getLatestObservationFeatureForTile(t){if(null==this._latestObservationFeature)return null;const{objectId:e,displayId:s,geometry:r,attributes:i}=this._latestObservationFeature,a=new b;p(a,r,!1,!1,this._metadata.geometryType,t.subscription.tile.transform);const o=l(1/0,1/0,-1/0,-1/0);N(a,(t,e)=>u(o,[t,e]));if(!c(o,l(0,0,F,F)))return null;return new _(a,i,null,e,s)}getTrackLineFeatureForTile(t){const e=new b;p(e,this._trackLineGeometry,!1,!1,"esriGeometryPolyline",t.subscription.tile.transform);return new _(e,this._trackLineAttributes,null,this.objectId,this.displayId)}getTrackLineOptimizedFeature(){return new _(this._trackLineGeometry,this._trackLineAttributes,null,this.objectId,this.displayId)}getTrackLineDisplayFeature(){const{_trackLineGeometry:t,_trackLineAttributes:e,displayId:s}=this;return{geometry:f(t,"esriGeometryPolyline",!1,!1),attributes:e,displayId:s}}_commitObservation(t,e){const s=e.readCentroidWorldSpace();let r=s?.coords[0],i=s?.coords[1];null==s&&(r=e.readXWorldSpace(),i=e.readYWorldSpace()),null!=r&&null!=i&&(this._observationRecords.unshift(t),this._trackLinePath.unshift([r,i]))}}class U extends x{constructor(t){super(t),this.done=!1}}class q extends T{static async create(t,e,s,a,o,n){const l=new w({spatialReference:e}),c=await Promise.all(t.fields.map(async t=>O.create(l,t))),d=t.featureFilter?await D.create({geometryType:s.metadata.geometryType,hasM:!1,hasZ:!1,timeInfo:s.metadata.timeInfo,fieldsIndex:s.metadata.fieldsIndex,spatialReference:e,filterJSON:t.featureFilter}):null;return e.isWrappable||r()||await Promise.all([import("../../../../../geometry/operators/support/apiConverter.js"),import("../../../../../geometry/operators/support/jsonConverter.js"),i()]).then(([t,e,s])=>{G={fromGeometryToGXGeometry:e.fromGeometryToGXGeometry,toGeometry:e.toGeometry,fromSpatialReference:t.fromSpatialReference}}),new q(t,s,a,e,c,d,o,n)}constructor(t,e,s,r,i,a,o,n){super(e,s,r,i,n),this._schema=t,this._featureFilter=a,this._arcadeContextInfo=o,this._tracks=new Map,this._handledChunks=new Set,this._metadata=e.metadata.weakCloneWithAdditionalFields([{name:y,alias:"trackPart",type:"esriFieldTypeSmallInteger"}]),this._trackLineMetadata=L.createFeature({geometryType:"esriGeometryPolyline",featureIdInfo:{type:"object-id",fieldName:"aggregateId"},fieldsIndex:{fields:[...this._source.metadata.fieldsIndex.fields,...this.aggregateFields,{name:y,alias:"trackPart",type:"esriFieldTypeSmallInteger"},{name:"aggregateId",alias:"aggregateId",type:"esriFieldTypeOID"}],timeZoneByFieldName:null},globalIdField:null,spatialReference:e.metadata.spatialReference,outSpatialReference:e.metadata.outSpatialReference,subtypeField:null,subtypes:null,timeInfo:e.metadata.timeInfo,timeReferenceUnknownClient:null,dateFieldsTimeZone:null,typeIdField:null,types:null})}get _isStream(){return this._source.isStream}get enablePixelBuffering(){return!0}get isAggregate(){return!1}requiresInvalidation(){const t=new Set(this._source.chunks().map(t=>t.chunkId));for(const e of t)if(!this._handledChunks.has(e))return!0;for(const e of this._handledChunks)if(!t.has(e))return!0;return!1}invalidate(){this._handledChunks.clear(),super.invalidate()}createState(t){return new U(t)}async*applyOverrideUpdate(t){P().error("Applying override to tracks is not supported")}displayMap(t,e,s){const r=new Map(t.map(t=>[e(t),t])),i=[];for(const a of this._tracks.values()){const t=r.get(a.objectId);if(null!=t){const e=s(a.displayId,t,a.objectId);i.push(e),r.delete(a.objectId);continue}for(const e of a.observations()){const t=r.get(e.objectId);if(null!=t){const a=s(e.displayId,t,e.objectId);i.push(a),r.delete(e.objectId)}}}return i}getDisplayFeatures(t){const e=new Set(t),s=[],r=[],i=this._source.chunks().map(t=>t.reader.getCursor());for(const a of this._tracks.values()){e.has(a.displayId)&&r.push(a.getTrackLineDisplayFeature());for(const{displayId:t,chunkIndex:r,featureIndex:o}of a.observations())if(e.has(t)){const e=i[r];e.setIndex(o),s.push({displayId:t,attributes:{},...e.readLegacyFeatureWorldSpace()})}}return{features:s,aggregates:[],tracks:r}}getFeatureObjectIdsForAggregate(t){for(const e of this._tracks.values())if(e.objectId===t)return Array.from(e.observations(),t=>t.objectId);return[]}async*updateChunks(){0===this._handledChunks.size&&this._rebuildTracks();for(const t of this._sendStates.values())yield*this._update(t)}forEachAggregateWorldSpace(t){for(const e of this._tracks.values())t(e.getTrackLineOptimizedFeature())}_rebuildTracks(){const t=this._source.chunks();if(!t.length)return;const e=this._metadata.timeInfo?.trackIdField;if(null==e)return;const s=new Set;for(let r=0;r<t.length;r++){const i=t[r];this._handledChunks.add(i.chunkId);const a=i.reader.getCursor();for(;a.next();){const t=a.readAttribute(e),i=a.getObjectId();if(null!=t&&null!=i&&(null===this._featureFilter||this._featureFilter.check(a,this._sqlOptions))){if(a.getDisplayId()||a.setDisplayId(this._attributeStore.createDisplayIdForObjectId(i)),!this._tracks.has(t)){const e=W.getOid(t),s=this._attributeStore.createDisplayIdForObjectId(e),r=new W(this._schema,t,e,s,this.aggregateFields,this.spatialReference,this._source.metadata,this._isStream);this._tracks.set(t,r)}this._tracks.get(t).stageObservation(r,a),s.add(t)}}}for(const r of this._tracks.values())if(s.has(r.trackId)){const e=r.commitObservations(t,this._featureFilter?.timeExtent);for(const t of e)this._attributeStore.releaseDisplayIdForObjectId(t);r.updateStatistics(t,R(1,this._arcadeContextInfo))}else this._removeTrack(r)}_removeTrack(t){this._tracks.delete(t.trackId),this._attributeStore.releaseDisplayIdForObjectId(t.objectId);for(const{objectId:e}of t.observations())this._attributeStore.releaseDisplayIdForObjectId(e)}*_update(e){if(e.done)return;e.done=!this._source.updateTracking.updating;const s=[],r=[];for(const t of this._tracks.values())if(t.length>0){if(this._schema.showLatestObservation){const r=t.getLatestObservationFeatureForTile(e);null!=r&&s.push(r)}this._schema.showTrackLine&&t.overlapsTile(e.subscription.tile)&&r.push(t.getTrackLineFeatureForTile(e))}const i=C.fromOptimizedFeatures(s,this._metadata,e.subscription.tile.transform),a=C.fromOptimizedFeatures(r,this._trackLineMetadata,e.subscription.tile.transform);let o=[];if(this._schema.showPreviousObservations){const s=this._source.chunks().map(()=>[]);for(const t of this._tracks.values())for(const{chunkIndex:e,featureIndex:r}of t.previousObservations())s[e].push(r);o=this._source.chunks().map((t,r)=>{const i=t.getTileReader(e.subscription.tile);if(null==i)return null;const a=A.from(i,s[r]);return a.setProcessorAttributes({[y]:I.PreviousObservation}),"esriGeometryPoint"!==a.geometryType&&null!=a.getInTransform()||a.setTransformForDisplay(e.subscription.tile.transform),a}).filter(t)}this.events.emit("changed");const n=e.subscription.tile.createArcadeEvaluationOptions(this._arcadeContextInfo),l=a.getCursor();for(;l.next();)this._attributeStore.setAttributeData(l.getDisplayId(),l,n,this._sqlOptions);for(const t of o){const e=t.getCursor();for(;e.next();)this._attributeStore.setAttributeData(e.getDisplayId(),e,n,this._sqlOptions)}const c=i.getCursor();for(;c.next();)this._attributeStore.setAttributeData(c.getDisplayId(),c,n,this._sqlOptions);yield new S(e.subscription,a,!1,!1,{});for(const t of o)yield new S(e.subscription,t,!1,!1,{});yield new S(e.subscription,i,!1,e.done,{})}}function E(t,e,s){if(e.length<2)return g(t,[e],!1,!1);if(s.isWrappable){let r=!1;for(let t=1;t<e.length;t++){const i=e[t][0],a=h(i,e[t-1][0],s);i!==a&&(e[t][0]=a,r=!0)}if(r){const r=m({paths:[e],spatialReference:s});if(null!=r)return g(t,r.paths,!1,!1)}return g(t,[e],!1,!1)}const r=G.fromGeometryToGXGeometry({hasM:!1,hasZ:!1,paths:[e]}),i=G.fromSpatialReference(s);if(null!=i){const e=a(r,1e6,i,o.geodesic);if(null!=e){const s=G.toGeometry(e,i);if(null!=s&&"paths"in s)return g(t,s.paths,!1,!1)}}return g(t,[e],!1,!1)}function N(t,e){const s=2,{coords:r,lengths:i}=t;if(!i.length)return void e(r[0],r[1]);let a=0;for(let o=0;o<i.length;o++){const t=i[o];let n=0,l=0;for(let i=0;i<t;i++)n+=r[s*(i+a)],l+=r[s*(i+a)+1],e(n,l);a+=t}}function X(t){const{lengths:e,coords:s}=t,r=2;if(!e.length)return[d()];const i=[];let a=0;for(let o=0;o<e.length;o++){const t=e[o],n=d();i.push(n);for(let e=0;e<t;e++){const t=s[r*(e+a)],i=s[r*(e+a)+1];u(n,[t,i])}a+=t}return i}export{q as TrackStrategy};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{ASourceChunk as e}from"./ASourceChunk.js";import{FeatureSetReaderJSON as t}from"../../../support/FeatureSetReaderJSON.js";const s=1e4,r=1e3;class i{constructor(){this.modified=[],this.removed=[]}modify(e){this.modified.push(e)}remove(e){this.removed.push(e)}get isEmpty(){return 0===this.modified.length&&0===this.removed.length}}class o extends e{constructor(e){super(),this._reader=e,this.chunkId="override",this.normalizedChunkId="override"}static fromFeatures(e,s){const r=t.fromOptimizedFeatures(e,s);return new o(r)}get reader(){return this._reader}get queryInfo(){return{}}get first(){return!1}get end(){return!1}get isTiled(){return!1}getTileReader(e){if(!this._reader.getSize())return null;const t=this.queryFeaturesInBounds(e.bounds);return t.setTransformForDisplay(e.transform),t}}class n{constructor(e,t){this.inner=e,this.isWeak=t,this.lastWeak=null}get isStrong(){return!this.isWeak}}class a{constructor(){this._overrides=new Map,this._update=new i,this._lastCleanup=0}hasOverride(e){return this._overrides.has(e)}onChunkInsert(e){if(this._overrides.size){const t=e.reader.getCursor();for(;t.next();){const e=t.getObjectId(),s=this._overrides.get(e);if(s?.lastWeak&&(s.lastWeak=null),s?.isWeak){const e=t.readOptimizedFeatureWorldSpace();s.inner=e,this._update.modify(e),this.invalidate()}}}e.registerOverrides(this)}apply(e,t){const{updateWeak:s,removeWeak:r,update:i,remove:o,release:a}=e.commands;this.invalidate();for(const d of s){const e=new n(d,!0),t=this._overrides.get(d.objectId);t?.isStrong?t.lastWeak=e:(this._overrides.set(d.objectId,e),this._update.modify(d))}for(const d of i){const e=new n(d,!1),t=this._overrides.get(d.objectId);e.lastWeak=t?.isWeak?t:t?.lastWeak??null,this._overrides.set(d.objectId,e),this._update.modify(d)}for(const d of r){const e=new n(null,!0),t=this._overrides.get(d);t?.isStrong?t.lastWeak=e:(this._overrides.set(d,e),this._update.remove(d))}for(const d of o){const e=new n(null,!1),t=this._overrides.get(d);e.lastWeak=t?.isWeak?t:t?.lastWeak??null,this._overrides.set(d,e),this._update.remove(d)}if(a.length){const e=new Set;for(const t of a){const s=this._overrides.get(t);s?.lastWeak?(this._overrides.set(t,s.lastWeak),null==s.lastWeak.inner?this._update.remove(t):this._update.modify(s.lastWeak.inner)):s&&!s.isWeak&&(this._overrides.delete(t),e.add(t))}t.forEachUnsafe(t=>{const s=t.getObjectId();e.has(s)&&(this._update.modify(t.readOptimizedFeatureWorldSpace()),e.delete(s))});for(const t of e.values())this._update.remove(t)}}clearWeakOverrides(){for(const[e,t]of this._overrides.entries())t.isWeak&&this._overrides.delete(e);this.invalidate()}cleanup(e){if(this._overrides.size<s)return;const t=performance.now();if(t-this._lastCleanup<r)return;this._lastCleanup=t;const i=this._getWeakDeletions();if(!(i.size<s)){for(const t of e){const e=t.reader.withoutOverrides().getCursor();for(;e.next();){const t=e.getObjectId();i.delete(t)}}for(const e of i)this._overrides.delete(e);i.size&&this.invalidate()}}takeOverrideUpdate(){const e=this._update;return e.isEmpty?null:(this._update=new i,e)}asChunk(e){if(!this._chunk){const t=[];for(const e of this._overrides.values())null!=e.inner&&t.push(e.inner);this._chunk=o.fromFeatures(t,e)}return this._chunk}invalidate(){this._chunk=null}putWeakObjectIdsFromGlobalIds(e,t,s){for(const[r,i]of this._overrides.entries())if(i.isWeak&&null!=i.inner){const o=i.inner.attributes[s];o&&t.has(o)&&!e.has(o)&&e.set(o,r)}else if(null!=i.lastWeak&&null!=i.lastWeak.inner){const o=i.lastWeak.inner.attributes[s];o&&t.has(o)&&!e.has(o)&&e.set(o,r)}}_getWeakDeletions(){const e=new Set;for(const[t,s]of this._overrides.entries())s.isWeak&&null==s.inner&&e.add(t);return e}}export{o as OverrideChunk,a as OverrideState,i as OverrideUpdate};
5
+ import{ASourceChunk as e}from"./ASourceChunk.js";import{FeatureSetReaderJSON as t}from"../../../support/FeatureSetReaderJSON.js";const s=1e4,r=1e3;class i{constructor(){this.modified=[],this.removed=[]}modify(e){this.modified.push(e)}remove(e){this.removed.push(e)}get isEmpty(){return 0===this.modified.length&&0===this.removed.length}}class o extends e{constructor(e){super(),this._reader=e,this.chunkId="override",this.normalizedChunkId="override"}static fromFeatures(e,s){const r=t.fromOptimizedFeatures(e,s);return new o(r)}get reader(){return this._reader}get queryInfo(){return{}}get first(){return!1}get end(){return!1}get isTiled(){return!1}getTileReader(e){if(!this._reader.getSize())return null;const t=this.queryFeaturesInBounds(e.bounds);return t.setTransformForDisplay(e.transform),t}}class n{constructor(e,t){this.inner=e,this.isWeak=t,this.lastWeak=null}get isStrong(){return!this.isWeak}}class a{constructor(){this._overrides=new Map,this._update=new i,this._lastCleanup=0}hasOverride(e){return this._overrides.has(e)}onChunkInsert(e){if(this._overrides.size){const t=e.reader.getCursor();for(;t.next();){const e=t.getObjectId(),s=this._overrides.get(e);if(s?.lastWeak&&(s.lastWeak=null),s?.isWeak){const e=t.readOptimizedFeatureWorldSpace();s.inner=e,this._update.modify(e),this.invalidate()}}}e.registerOverrides(this)}apply(e,t){const{updateWeak:s,removeWeak:r,update:i,remove:o,release:a}=e.commands;this.invalidate();for(const d of s){const e=new n(d,!0),t=this._overrides.get(d.objectId);t?.isStrong?t.lastWeak=e:(this._overrides.set(d.objectId,e),this._update.modify(d))}for(const d of i){const e=new n(d,!1),t=this._overrides.get(d.objectId);e.lastWeak=t?.isWeak?t:t?.lastWeak??null,this._overrides.set(d.objectId,e),this._update.modify(d)}for(const d of r){const e=new n(null,!0),t=this._overrides.get(d);t?.isStrong?t.lastWeak=e:(this._overrides.set(d,e),this._update.remove(d))}for(const d of o){const e=new n(null,!1),t=this._overrides.get(d);e.lastWeak=t?.isWeak?t:t?.lastWeak??null,this._overrides.set(d,e),this._update.remove(d)}if(a.length){const e=new Set;for(const t of a){const s=this._overrides.get(t);s?.lastWeak?(this._overrides.set(t,s.lastWeak),null==s.lastWeak.inner?this._update.remove(t):this._update.modify(s.lastWeak.inner)):s&&!s.isWeak&&(this._overrides.delete(t),e.add(t))}t.forEachUnsafe(t=>{const s=t.getObjectId();e.has(s)&&(this._update.modify(t.readOptimizedFeatureWorldSpace()),e.delete(s))});for(const t of e.values())this._update.remove(t)}}clearWeakOverrides(){for(const[e,t]of this._overrides.entries())t.isWeak&&this._overrides.delete(e);this.invalidate()}cleanup(e){if(this._overrides.size<s)return;const t=performance.now();if(t-this._lastCleanup<r)return;this._lastCleanup=t;const i=this._getWeakDeletions();if(!(i.size<s)){for(const t of e){const e=t.reader.withoutOverrides().getCursor();for(;e.next();){const t=e.getObjectId();i.delete(t)}}for(const e of i)this._overrides.delete(e);i.size&&this.invalidate()}}takeOverrideUpdate(){const e=this._update;return e.isEmpty?null:(this._update=new i,e)}asChunk(e){if(!this._chunk){const t=[];for(const e of this._overrides.values())null!=e.inner&&t.push(e.inner);this._chunk=o.fromFeatures(t,e)}return this._chunk}invalidate(){this._chunk=null}putWeakObjectIdsFromGlobalIds(e,t,s){for(const[r,i]of this._overrides.entries()){if(i.isWeak&&null!=i.inner){const o=i.inner.attributes[s];o&&t.has(o)&&!e.has(o)&&e.set(o,r);continue}if(null!=i.lastWeak&&null!=i.lastWeak.inner){const o=i.lastWeak.inner.attributes[s];o&&t.has(o)&&!e.has(o)&&e.set(o,r)}}}_getWeakDeletions(){const e=new Set;for(const[t,s]of this._overrides.entries())s.isWeak&&null==s.inner&&e.add(t);return e}}export{o as OverrideChunk,a as OverrideState,i as OverrideUpdate};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import t from"../../../../../core/Error.js";import e from"../../../../../core/Logger.js";import{create as i}from"../../../../../geometry/support/aaBoundingRect.js";import{getBoundsXY as s}from"../../../../../geometry/support/boundsUtils.js";import{normalizeQueryLike as r}from"../../../../../layers/graphics/data/queryUtils.js";import{getSpatialQueryOperator as o}from"../../../../../layers/graphics/data/spatialQuerySupport.js";import{getTimeOperator as a}from"../../../../../layers/graphics/data/timeSupport.js";import h from"../../../../../rest/support/Query.js";import{FeatureStoreQueryAdapter as l}from"../FeatureStoreQueryAdapter.js";import{createWhereClause as n}from"./whereUtils.js";const m=1,d=2;class p{constructor(t){this._geometryBounds=i(),this._idToVisibility=new Map,this._serviceInfo=t}static async create(t){const e=new p(t);return await e.update(t.filterJSON,t.spatialReference),e}get hash(){return this._hash}check(t,e){return this._applyFilter(t,e)}invalidate(){this._idToVisibility.forEach((t,e)=>{this._idToVisibility.set(e,0)})}setKnownIds(t){for(const e of t)this._idToVisibility.set(e,m)}setTrue(t){const e=[],i=[],s=new Set(t);return this._idToVisibility.forEach((t,r)=>{const o=!!(this._idToVisibility.get(r)&m),a=s.has(r);!o&&a?e.push(r):o&&!a&&i.push(r),this._idToVisibility.set(r,a?m|d:0)}),{show:e,hide:i}}createQuery(){const{geometry:t,spatialRel:e,where:i,timeExtent:s,objectIds:r}=this;return h.fromJSON({geometry:t,spatialRel:e,where:i,timeExtent:s,objectIds:r})}async update(t,e){this._hash=JSON.stringify(t);const i=await r(t,null,e);await Promise.all([this._setGeometryFilter(i),this._setIdFilter(i),this._setAttributeFilter(i),this._setTimeFilter(i)])}async _setAttributeFilter(t){if(!t?.where)return this._clause=null,void(this.where=null);this._clause=await n(t.where,this._serviceInfo.fieldsIndex),this.where=t.where}_setIdFilter(t){this._idsToShow=t?.objectIds&&new Set(t.objectIds),this._idsToHide=t?.hiddenIds&&new Set(t.hiddenIds),this.objectIds=t?.objectIds}async _setGeometryFilter(t){if(!t?.geometry)return this._spatialQueryOperator=null,this.geometry=null,void(this.spatialRel=null);const e=t.geometry,i=t.spatialRel??"esriSpatialRelIntersects",r=await o(i,e,this._serviceInfo.geometryType,this._serviceInfo.hasZ,this._serviceInfo.hasM);s(this._geometryBounds,e),this._spatialQueryOperator=r,this.geometry=e,this.spatialRel=i}_setTimeFilter(i){if(this.timeExtent=this._timeOperator=null,i?.timeExtent)if(this._serviceInfo.timeInfo)this.timeExtent=i.timeExtent,this._timeOperator=a(this._serviceInfo.timeInfo,i.timeExtent,l.Shared);else{const s=new t("feature-layer-view:time-filter-not-available","Unable to apply time filter, as layer doesn't have time metadata.",i.timeExtent);e.getLogger("esri.views.2d.layers.features.controllers.FeatureFilter").error(s)}}_applyFilter(t,e){return this._filterByGeometry(t)&&this._filterById(t)&&this._filterByTime(t)&&this._filterByExpression(t,e)}_filterByExpression(t,e){return!this.where||this._clause(t,e)}_filterById(t){return(!this._idsToHide?.size||!this._idsToHide.has(t.getObjectId()))&&(!this._idsToShow?.size||this._idsToShow.has(t.getObjectId()))}_filterByGeometry(t){if(!this.geometry)return!0;const e=t.readGeometryWorldSpace();return!!e&&this._spatialQueryOperator(e)}_filterByTime(t){return null==this._timeOperator||this._timeOperator(t)}}export{p as default};
5
+ import t from"../../../../../core/Error.js";import e from"../../../../../core/Logger.js";import{create as i}from"../../../../../geometry/support/aaBoundingRect.js";import{getBoundsXY as s}from"../../../../../geometry/support/boundsUtils.js";import{normalizeQueryLike as r}from"../../../../../layers/graphics/data/queryUtils.js";import{getSpatialQueryOperator as o}from"../../../../../layers/graphics/data/spatialQuerySupport.js";import{getTimeOperator as a}from"../../../../../layers/graphics/data/timeSupport.js";import h from"../../../../../rest/support/Query.js";import{FeatureStoreQueryAdapter as l}from"../FeatureStoreQueryAdapter.js";import{createWhereClause as n}from"./whereUtils.js";const m=1,d=2;class p{constructor(t){this._geometryBounds=i(),this._idToVisibility=new Map,this._serviceInfo=t}static async create(t){const e=new p(t);return await e.update(t.filterJSON,t.spatialReference),e}get hash(){return this._hash}check(t,e){return this._applyFilter(t,e)}invalidate(){this._idToVisibility.forEach((t,e)=>{this._idToVisibility.set(e,0)})}setKnownIds(t){for(const e of t)this._idToVisibility.set(e,m)}setTrue(t){const e=[],i=[],s=new Set(t);return this._idToVisibility.forEach((t,r)=>{const o=!!(this._idToVisibility.get(r)&m),a=s.has(r);!o&&a?e.push(r):o&&!a&&i.push(r),this._idToVisibility.set(r,a?m|d:0)}),{show:e,hide:i}}createQuery(){const{geometry:t,spatialRel:e,where:i,timeExtent:s,objectIds:r}=this;return h.fromJSON({geometry:t,spatialRel:e,where:i,timeExtent:s,objectIds:r})}async update(t,e){this._hash=JSON.stringify(t);const i=await r(t,null,e);await Promise.all([this._setGeometryFilter(i),this._setIdFilter(i),this._setAttributeFilter(i),this._setTimeFilter(i)])}async _setAttributeFilter(t){if(!t?.where)return this._clause=null,void(this.where=null);this._clause=await n(t.where,this._serviceInfo.fieldsIndex),this.where=t.where}_setIdFilter(t){this._idsToShow=t?.objectIds&&new Set(t.objectIds),this._idsToHide=t?.hiddenIds&&new Set(t.hiddenIds),this.objectIds=t?.objectIds}async _setGeometryFilter(t){if(!t?.geometry)return this._spatialQueryOperator=null,this.geometry=null,void(this.spatialRel=null);const e=t.geometry,i=t.spatialRel??"esriSpatialRelIntersects",r=await o(i,e,this._serviceInfo.geometryType,this._serviceInfo.hasZ,this._serviceInfo.hasM);s(this._geometryBounds,e),this._spatialQueryOperator=r,this.geometry=e,this.spatialRel=i}_setTimeFilter(i){if(this.timeExtent=this._timeOperator=null,i?.timeExtent){if(!this._serviceInfo.timeInfo){const s=new t("feature-layer-view:time-filter-not-available","Unable to apply time filter, as layer doesn't have time metadata.",i.timeExtent);return void e.getLogger("esri.views.2d.layers.features.controllers.FeatureFilter").error(s)}this.timeExtent=i.timeExtent,this._timeOperator=a(this._serviceInfo.timeInfo,i.timeExtent,l.Shared)}}_applyFilter(t,e){return this._filterByGeometry(t)&&this._filterById(t)&&this._filterByTime(t)&&this._filterByExpression(t,e)}_filterByExpression(t,e){return!this.where||this._clause(t,e)}_filterById(t){return(!this._idsToHide?.size||!this._idsToHide.has(t.getObjectId()))&&(!this._idsToShow?.size||this._idsToShow.has(t.getObjectId()))}_filterByGeometry(t){if(!this.geometry)return!0;const e=t.readGeometryWorldSpace();return!!e&&this._spatialQueryOperator(e)}_filterByTime(t){return null==this._timeOperator||this._timeOperator(t)}}export{p as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import{isSome as s}from"../../../../core/arrayUtils.js";import has from"../../../../core/has.js";import r from"../../../../core/Identifiable.js";import{assertIsSome as i}from"../../../../core/maybe.js";import{ignoreAbortErrors as o,throwIfAborted as a}from"../../../../core/promiseUtils.js";import{watch as n}from"../../../../core/reactiveUtils.js";import{property as h}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import{subclass as d}from"../../../../core/accessorSupport/decorators/subclass.js";import{create as c}from"../../../../geometry/support/aaBoundingRect.js";import{isPolyline as l,isPolygon as p,isExtent as u,getJsonType as m}from"../../../../geometry/support/jsonUtils.js";import g from"../../../../layers/support/FieldsIndex.js";import{symbolToCIM as f,CIMSymbolHelper as y}from"../../../../symbols/cim/CIMSymbolHelper.js";import{OverrideHelper as _}from"../../../../symbols/cim/OverrideHelper.js";import{errorPointSymbol2D as b,errorPolylineSymbol2D as w,errorPolygonSymbol2D as S}from"../../../../symbols/support/defaults.js";import{filterFlag0 as I}from"../../engine/webgl/definitions.js";import{FeatureTile as v}from"../../engine/webgl/FeatureTile.js";import{MeshData as T}from"../../engine/webgl/mesh/MeshData.js";import{ResourceProxy as M}from"../../engine/webgl/mesh/factories/ResourceProxy.js";import{createGraphicSymbolMeshSchemas as R}from"../../engine/webgl/shaderGraph/techniques/createGraphicSymbolMeshSchemas.js";import{createStorageSchema as j}from"../features/schema/processor/StorageSchema.js";import{AttributeStore as x}from"../features/support/AttributeStore.js";import{ComputedAttributeStorage as U}from"../features/support/ComputedAttributeStorage.js";import{GraphicsMetadata as C}from"../features/support/FeatureMetadata.js";import{GraphicsReader as q}from"../features/support/GraphicsReader.js";import G from"./GraphicStore.js";import{FeatureCommandQueue as k}from"../support/FeatureCommandQueue.js";import{UpdateTracking2D as P}from"../support/UpdateTracking2D.js";class F{static getOrCreate(e,t,s){let r=t.get(e.id);return r||(r=new F(e,s),t.set(e.id,r)),r}static fromItems(e,t,s){const r=new F(e,s);for(const i of t)r.append(i);return r}constructor(e,t){this.tile=e,this.metadata=t,this.addedOrModified=[],this.removed=[],this.objectIdMap=null}get reader(){return this._reader||(this._reader=q.from(this.addedOrModified,this.tile,this.metadata)),this._reader}append(e){this.addedOrModified.push(e),e.hasAnimations&&(this.objectIdMap=this.objectIdMap||{},this.objectIdMap[e.displayId]=e.objectId)}}let O=class extends(r.IdentifiableMixin(t)){constructor(e){super(e),this._attached=!1,this._tiles=new Map,this._controller=new AbortController,this._hashToSymbolInfo=new Map,this._lastCleanup=performance.now(),this._cleanupRequired=!0,this.lastUpdateId=-1,this.renderer=null,this._updateTracking=new P({debugName:"GraphicsView2D"}),this.updateRequested=!1,this.defaultPointSymbolEnabled=!0,this._commandQueue=new k({process:e=>{if("update"===e.type)return this._update();throw new Error("InternalError: Unsupported command")}}),this.graphicUpdateHandler=this.graphicUpdateHandler.bind(this)}destroy(){this.container.destroy(),this.view=null,this.renderer=null,this._set("graphics",null),this._controller.abort(),this._graphicStore.clear(),this._graphicStore.destroy(),this._attributeStore=null,this._hashToSymbolInfo.clear(),this._updateTracking.destroy(),this._commandQueue.destroy()}_initAttributeStore(){this._storage=new U({spatialReference:this.view.spatialReference,fields:new g}),this._attributeStore=new x({isLocal:!0,update:e=>{has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView2D.AttributeStoreView.updateStart`,{message:e}),this.container.attributeView.requestUpdate(e),this.container.requestRender(),has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView2D.AttributeStoreView.updateEnd`,{message:e})}});const e=j(null,[]);this._attributeStore.update(e,this._storage,null),this.container.checkHighlight=()=>this._attributeStore.hasHighlight}initialize(){this._initAttributeStore(),this._metadata=C.createGraphics(this.view.spatialReference),this._resourceProxy=new M({fetch:e=>Promise.all(e.map(e=>this.view.stage.textureManager.rasterizeItem(e))),fetchDictionary:e=>{throw new Error("InternalError: Graphics do not support Dictionary requests")}}),this.addHandles([n(()=>this._effectiveRenderer,()=>this._pushUpdate()),this.view.graphicsTileStore.on("update",this._onTileUpdate.bind(this)),this.container.on("attach",()=>{this.addHandles([this.graphics.on("change",()=>this._pushUpdate())]),this._graphicStore?.destroy(),this._graphicStore=new G(this.view.spatialReference,this._cimResourceManager,this.view.featuresTilingScheme,this.view.state.scale,this._attributeStore),this._attached=!0,this.requestUpdate(),this._pushUpdate()})]),this._updateTracking.addUpdateTracking("CommandQueue",this._commandQueue.updateTracking);const e=this.view.graphicsTileStore.tiles;this._onTileUpdate({added:e,removed:[]})}get _effectiveRenderer(){return"function"==typeof this.renderer?this.renderer():this.renderer}get _cimResourceManager(){return this.view.stage.textureManager.resourceManager}get updating(){const e=!this._attached||this._updateTracking.updating;return has("esri-2d-log-updating")&&console.log(`Updating GraphicsView2D: ${e}\n -> attaching ${!this._attached}\n -> updateTracking ${this._updateTracking.updating}`),e}hitTest(e){if(!this.view||this.view.suspended)return[];const{resolution:t,rotation:r}=this.view.state,i=this._graphicStore.hitTest(e.x,e.y,2,t,r),o=new Set(i),a=this.graphics.items.reduce((e,t)=>(o.has(t.uid)&&e.set(t.uid,t),e),new Map);return i.map(e=>a.get(e)).filter(s)}requestUpdate(){this.updateRequested||(this.updateRequested=!0,this.requestUpdateCallback()),this.notifyChange("updating")}processUpdate(e){this.updateRequested&&(this.updateRequested=!1,this.update(e))}viewChange(){this.requestUpdate()}setHighlight(e){const t=[];for(const{objectId:s,highlightFlags:r}of e){const e=this._graphicStore.getItem(s)?.displayId;t.push({objectId:s,highlightFlags:r,displayId:e})}this._attributeStore.setHighlight(t,e),this._pushUpdate()}graphicUpdateHandler(e){this._pushUpdate()}update(e){this.updateRequested=!1,this._attached&&this._graphicStore.updateLevel(e.state.resolution)&&this.pushUpdate()}pushUpdate(){this._pushUpdate()}_pushUpdate(){o(this._commandQueue.push({type:"update"}))}async _update(){try{has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView._update start`);const e=await this._graphicStore.update(this.graphics,e=>this._getSymbolForGraphic(e),e=>this._ensureSymbolResource(e));for(const s of e.updated)this.container.restartAnimation(s.objectId);if(!e.hasAnyUpdate())return void this._attributeStore.sendUpdates();e.removed.length&&(this._cleanupRequired=!0),has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView updateMessage`,e);const t=this._createTileMessages(e);await this._densifyItemsForDisplay(t),await this._fetchResources(t),this._write(t);for(const s of e.added)this._setFilterState(s);for(const s of e.updated)this._setFilterState(s);has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView sendUpdate`,e),this._attributeStore.sendUpdates(),has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView sendUpdate.await`,e)}catch(e){}this._cleanupSharedResources()}_createTileMessages(e){const t=new Map;for(const s of e.added){const e=this.view.graphicsTileStore.getIntersectingTiles(s.symbolBounds);for(const r of e){F.getOrCreate(r,t,this._metadata).append(s)}}for(const s of e.updated){const e=this.view.graphicsTileStore.getIntersectingTiles(s.prevSymbolBounds),r=this.view.graphicsTileStore.getIntersectingTiles(s.symbolBounds);for(const i of e){F.getOrCreate(i,t,this._metadata).removed.push(s.displayId)}for(const i of r){F.getOrCreate(i,t,this._metadata).append(s)}}for(const s of e.removed){const e=this.view.graphicsTileStore.getIntersectingTiles(s.symbolBounds);for(const r of e){F.getOrCreate(r,t,this._metadata).removed.push(s.displayId)}}return Array.from(t.values())}async _densifyItemsForDisplay(e){const t=new Map;for(const s of e)for(const e of s.addedOrModified)t.has(e)||t.set(e,e.densifyCurvedGeometryForDisplay(this.view.spatialReference));await Promise.all(t.values())}async _fetchResources(e){const t={timeZone:null,timeExtent:null};for(const{tile:s,reader:r}of e){has("esri-2d-update-debug")&&console.debug(`Id[${this.layerId}] Tile[${s.id}] GraphicsView fetchResources`,e);const i=r.getCursor();for(;i.next();)for(const e of i.getMeshWriters())e.enqueueRequest(this._resourceProxy,i,s.createArcadeEvaluationOptions(t))}await this._resourceProxy.fetchEnqueuedResources()}_write(e){for(const t of e){has("esri-2d-update-debug")&&console.debug(`Id[${this.layerId}] Tile[${t.tile.id}] GraphicsView write`,t);const e=this._writeMeshes(t);let s=this._tiles.get(t.tile.key);s||(s=this._createFeatureTile(t.tile.key)),has("esri-2d-update-debug")&&console.debug(`Id[${this.layerId}] Tile[${t.tile.id}] GraphicsView onTileData`,t),this.container.onTileData(s,{type:"update",modify:e,remove:t.removed,end:!1,attributeEpoch:this._attributeStore.epoch,objectIdMap:t.objectIdMap}),this.container.requestRender()}}_writeMeshes(e){const t={timeZone:null,timeExtent:null},s=new T(e.tile.id),r=e.reader.getCursor();for(;r.next();){s.entityStart(r.getDisplayId(),r.getZOrder());for(const i of r.getMeshWriters())i.write(s,this._resourceProxy,r,e.tile.createArcadeEvaluationOptions(t),e.tile.level);s.entityEnd()}return{...s.serialize().message,tileId:e.tile.id}}_setFilterState(e){const t=e.displayId,s=this._attributeStore.getHighlightFlags(e.objectId);this._attributeStore.setData(t,0,0,s|(e.visible?I:0))}_getSymbolForGraphic(e){return null!=e.symbol?e.symbol:null!=this._effectiveRenderer?this._effectiveRenderer.getSymbol(e):this._getNullSymbol(e)}async _ensureSymbolResource(e){if(!e.symbol)return;const t=await this._getSymbolInfo(e.symbol);if(!t)return;const s=t.linearCIM.filter(e=>"text"===e.type);if(s.length>0){const r=await this._getTextResources(e,s);e.symbolResource={symbolInfo:t,textInfo:r}}else e.symbolResource={symbolInfo:t}}_getSymbolInfo(e){const t=e.hash();return this._hashToSymbolInfo.has(t)||this._hashToSymbolInfo.set(t,this._createSymbolInfo(t,e).catch(e=>null)),this._hashToSymbolInfo.get(t)}async _createSymbolInfo(e,t){const s=await this._convertToCIMSymbol(t),r=await this._createLinearCIM(s);return{hash:e,cimSymbol:s,linearCIM:r,meshWriters:await this._createMeshWriters(s,r)}}async _convertToCIMSymbol(e){const t=f(e);return"web-style"===t.type?this._convertToCIMSymbol(await t.fetchSymbol({acceptedFormats:["cim","web"]})):t}async _createLinearCIM(e){return await Promise.all(y.fetchResources(e.symbol,this._cimResourceManager,[])),this.view.stage.cimAnalyzer.analyzeSymbolReference(e,!1)}async _createMeshWriters(e,t){a(this._controller.signal);const s=this.container.instanceStore,r=this.view.stage.meshWriterRegistry,i=await R(e,t,s);return Promise.all(i.map(e=>r.createMeshWriter(this._storage,this._resourceProxy,{tileInfo:this.view.featuresTilingScheme.tileInfo},e,null)))}_onTileUpdate(e){if(e.added&&e.added.length>0)for(const t of e.added)this._updateTracking.addPromise(this._addTile(t));if(e.removed&&e.removed.length>0)for(const t of e.removed)this._removeTile(t.key)}_createFeatureTile(e){const t=this.view.featuresTilingScheme.getTileBounds(c(),e),s=this.view.featuresTilingScheme.getTileResolution(e.level),r=new v(e,s,t[0],t[3]);return this._tiles.set(e,r),this.container.addChild(r),r}async _addTile(e){if(!this._attached)return;const t=this._graphicStore.queryItems(e);if(!t.length)return;const s=this._createFeatureTile(e.key),r=F.fromItems(e,t,this._metadata);await this._densifyItemsForDisplay([r]),await this._fetchResources([r]);const i=this._writeMeshes(r);s.onMessage({type:"append",append:i,clear:!1,end:!0,attributeEpoch:this._attributeStore.epoch,objectIdMap:r.objectIdMap})}_removeTile(e){if(!this._tiles.has(e))return;const t=this._tiles.get(e);this.container.removeChild(t),t.destroy(),this._tiles.delete(e)}_getNullSymbol(e){const t=e.geometry;return t?l(t)?w:p(t)||u(t)?S:this.defaultPointSymbolEnabled?b:null:this.defaultPointSymbolEnabled?b:null}async _getTextResources(e,t){const s=new Array,r=new Array;for(let i=0;i<t.length;i++){const o=t[i],{resource:a,overrides:n}=o.textRasterizationParam;if(n?.length>0){const t=_.resolveSymbolOverrides({type:"CIMSymbolReference",primitiveOverrides:n,symbol:{type:"CIMPointSymbol",symbolLayers:[{type:"CIMVectorMarker",enable:!0,size:a.symbol.height,anchorPointUnits:"Relative",frame:{xmin:-5,ymin:-5,xmax:5,ymax:5},markerGraphics:[{type:"CIMMarkerGraphic",geometry:{x:0,y:0},symbol:a.symbol,textString:a.textString}],scaleSymbolsProportionally:!0,respectFrame:!0}]}},e,this.view.spatialReference,null,m(e.projectedGeometry),null,null);t.then(e=>{const t=e.symbolLayers[0],{textString:s}=t.markerGraphics[0];r.push({type:"cim-rasterization-info",resource:{type:"text",textString:s||"",font:a.font}}),o.text=a.textString=s||""}),s.push(t)}else r.push({type:"cim-rasterization-info",resource:a})}s.length>0&&await Promise.all(s);const o=r.map(e=>this.view.stage.textureManager.rasterizeItem(e)),a=await Promise.all(o);i(a);const n=new Map;for(let i=0;i<t.length;i++){const e=t[i];n.set(e.textRasterizationParam.resource.symbol,{text:e.text,glyphMosaicItems:a[i]})}return n}_cleanupSharedResources(){if(!this._cleanupRequired)return;const e=performance.now();if(e-this._lastCleanup<5e3)return;this._cleanupRequired=!1,this._lastCleanup=e;const t=new Set;for(const r of this._graphicStore.items()){const e=r.symbolResource?.symbolInfo.hash;t.add(e)}const s=new Set(this._hashToSymbolInfo.keys());for(const r of s.values())t.has(r)||this._hashToSymbolInfo.delete(r)}};e([h()],O.prototype,"_effectiveRenderer",null),e([h({constructOnly:!0})],O.prototype,"layerId",void 0),e([h({constructOnly:!0})],O.prototype,"requestUpdateCallback",void 0),e([h()],O.prototype,"container",void 0),e([h({constructOnly:!0})],O.prototype,"graphics",void 0),e([h()],O.prototype,"renderer",void 0),e([h()],O.prototype,"_updateTracking",void 0),e([h()],O.prototype,"updating",null),e([h()],O.prototype,"view",void 0),e([h()],O.prototype,"updateRequested",void 0),e([h()],O.prototype,"defaultPointSymbolEnabled",void 0),O=e([d("esri.views.2d.layers.graphics.GraphicsView2D")],O);export{O as default};
5
+ import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import{isSome as s}from"../../../../core/arrayUtils.js";import has from"../../../../core/has.js";import r from"../../../../core/Identifiable.js";import{assertIsSome as i}from"../../../../core/maybe.js";import{ignoreAbortErrors as o,throwIfAborted as a}from"../../../../core/promiseUtils.js";import{watch as n}from"../../../../core/reactiveUtils.js";import{property as h}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import{subclass as d}from"../../../../core/accessorSupport/decorators/subclass.js";import{create as c}from"../../../../geometry/support/aaBoundingRect.js";import{isPolyline as l,isPolygon as p,isExtent as u,getJsonType as m}from"../../../../geometry/support/jsonUtils.js";import g from"../../../../layers/support/FieldsIndex.js";import{symbolToCIM as f,CIMSymbolHelper as y}from"../../../../symbols/cim/CIMSymbolHelper.js";import{OverrideHelper as _}from"../../../../symbols/cim/OverrideHelper.js";import{errorPointSymbol2D as b,errorPolylineSymbol2D as w,errorPolygonSymbol2D as S}from"../../../../symbols/support/defaults.js";import{filterFlag0 as I}from"../../engine/webgl/definitions.js";import{FeatureTile as v}from"../../engine/webgl/FeatureTile.js";import{MeshData as T}from"../../engine/webgl/mesh/MeshData.js";import{ResourceProxy as M}from"../../engine/webgl/mesh/factories/ResourceProxy.js";import{createGraphicSymbolMeshSchemas as R}from"../../engine/webgl/shaderGraph/techniques/createGraphicSymbolMeshSchemas.js";import{createStorageSchema as j}from"../features/schema/processor/StorageSchema.js";import{AttributeStore as x}from"../features/support/AttributeStore.js";import{ComputedAttributeStorage as U}from"../features/support/ComputedAttributeStorage.js";import{GraphicsMetadata as C}from"../features/support/FeatureMetadata.js";import{GraphicsReader as q}from"../features/support/GraphicsReader.js";import G from"./GraphicStore.js";import{FeatureCommandQueue as k}from"../support/FeatureCommandQueue.js";import{UpdateTracking2D as P}from"../support/UpdateTracking2D.js";class F{static getOrCreate(e,t,s){let r=t.get(e.id);return r||(r=new F(e,s),t.set(e.id,r)),r}static fromItems(e,t,s){const r=new F(e,s);for(const i of t)r.append(i);return r}constructor(e,t){this.tile=e,this.metadata=t,this.addedOrModified=[],this.removed=[],this.objectIdMap=null}get reader(){return this._reader||(this._reader=q.from(this.addedOrModified,this.tile,this.metadata)),this._reader}append(e){this.addedOrModified.push(e),e.hasAnimations&&(this.objectIdMap=this.objectIdMap||{},this.objectIdMap[e.displayId]=e.objectId)}}let O=class extends(r.IdentifiableMixin(t)){constructor(e){super(e),this._attached=!1,this._tiles=new Map,this._controller=new AbortController,this._hashToSymbolInfo=new Map,this._lastCleanup=performance.now(),this._cleanupRequired=!0,this.lastUpdateId=-1,this.renderer=null,this._updateTracking=new P({debugName:"GraphicsView2D"}),this.updateRequested=!1,this.defaultPointSymbolEnabled=!0,this._commandQueue=new k({process:e=>{if("update"===e.type)return this._update();throw new Error("InternalError: Unsupported command")}}),this.graphicUpdateHandler=this.graphicUpdateHandler.bind(this)}destroy(){this.container.destroy(),this.view=null,this.renderer=null,this._set("graphics",null),this._controller.abort(),this._graphicStore.clear(),this._graphicStore.destroy(),this._attributeStore=null,this._hashToSymbolInfo.clear(),this._updateTracking.destroy(),this._commandQueue.destroy()}_initAttributeStore(){this._storage=new U({spatialReference:this.view.spatialReference,fields:new g}),this._attributeStore=new x({isLocal:!0,update:e=>{has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView2D.AttributeStoreView.updateStart`,{message:e}),this.container.attributeView.requestUpdate(e),this.container.requestRender(),has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView2D.AttributeStoreView.updateEnd`,{message:e})}});const e=j(null,[]);this._attributeStore.update(e,this._storage,null),this.container.checkHighlight=()=>this._attributeStore.hasHighlight}initialize(){this._initAttributeStore(),this._metadata=C.createGraphics(this.view.spatialReference),this._resourceProxy=new M({fetch:e=>Promise.all(e.map(e=>this.view.stage.textureManager.rasterizeItem(e))),fetchDictionary:e=>{throw new Error("InternalError: Graphics do not support Dictionary requests")}}),this.addHandles([n(()=>this._effectiveRenderer,()=>this._pushUpdate()),this.view.graphicsTileStore.on("update",this._onTileUpdate.bind(this)),this.container.on("attach",()=>{this.addHandles([this.graphics.on("change",()=>this._pushUpdate())]),this._graphicStore?.destroy(),this._graphicStore=new G(this.view.spatialReference,this._cimResourceManager,this.view.featuresTilingScheme,this.view.state.scale,this._attributeStore),this._attached=!0,this.requestUpdate(),this._pushUpdate()})]),this._updateTracking.addUpdateTracking("CommandQueue",this._commandQueue.updateTracking);const e=this.view.graphicsTileStore.tiles;this._onTileUpdate({added:e,removed:[]})}get _effectiveRenderer(){return"function"==typeof this.renderer?this.renderer():this.renderer}get _cimResourceManager(){return this.view.stage.textureManager.resourceManager}get updating(){const e=!this._attached||this._updateTracking.updating;return has("esri-2d-log-updating")&&console.log(`Updating GraphicsView2D: ${e}\n -> attaching ${!this._attached}\n -> updateTracking ${this._updateTracking.updating}`),e}hitTest(e){if(!this.view||this.view.suspended)return[];const{resolution:t,rotation:r}=this.view.state,i=this._graphicStore.hitTest(e.x,e.y,2,t,r),o=new Set(i),a=this.graphics.items.reduce((e,t)=>(o.has(t.uid)&&e.set(t.uid,t),e),new Map);return i.map(e=>a.get(e)).filter(s)}requestUpdate(){this.updateRequested||(this.updateRequested=!0,this.requestUpdateCallback()),this.notifyChange("updating")}processUpdate(e){this.updateRequested&&(this.updateRequested=!1,this.update(e))}viewChange(){this.requestUpdate()}setHighlight(e){const t=[];for(const{objectId:s,highlightFlags:r}of e){const e=this._graphicStore.getItem(s)?.displayId;t.push({objectId:s,highlightFlags:r,displayId:e})}this._attributeStore.setHighlight(t,e),this._pushUpdate()}graphicUpdateHandler(e){this._pushUpdate()}update(e){this.updateRequested=!1,this._attached&&this._graphicStore.updateLevel(e.state.resolution)&&this.pushUpdate()}pushUpdate(){this._pushUpdate()}_pushUpdate(){o(this._commandQueue.push({type:"update"}))}async _update(){try{has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView._update start`);const e=await this._graphicStore.update(this.graphics,e=>this._getSymbolForGraphic(e),e=>this._ensureSymbolResource(e));for(const s of e.updated)this.container.restartAnimation(s.objectId);if(!e.hasAnyUpdate())return void this._attributeStore.sendUpdates();e.removed.length&&(this._cleanupRequired=!0),has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView updateMessage`,e);const t=this._createTileMessages(e);await this._densifyItemsForDisplay(t),await this._fetchResources(t),this._write(t);for(const s of e.added)this._setFilterState(s);for(const s of e.updated)this._setFilterState(s);has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView sendUpdate`,e),this._attributeStore.sendUpdates(),has("esri-2d-update-debug")&&console.debug(`[Id: ${this.layerId}] GraphicsView sendUpdate.await`,e)}catch(e){}this._cleanupSharedResources()}_createTileMessages(e){const t=new Map;for(const s of e.added){const e=this.view.graphicsTileStore.getIntersectingTiles(s.symbolBounds);for(const r of e){F.getOrCreate(r,t,this._metadata).append(s)}}for(const s of e.updated){const e=this.view.graphicsTileStore.getIntersectingTiles(s.prevSymbolBounds),r=this.view.graphicsTileStore.getIntersectingTiles(s.symbolBounds);for(const i of e){F.getOrCreate(i,t,this._metadata).removed.push(s.displayId)}for(const i of r){F.getOrCreate(i,t,this._metadata).append(s)}}for(const s of e.removed){const e=this.view.graphicsTileStore.getIntersectingTiles(s.symbolBounds);for(const r of e){F.getOrCreate(r,t,this._metadata).removed.push(s.displayId)}}return Array.from(t.values())}async _densifyItemsForDisplay(e){const t=new Map;for(const s of e)for(const e of s.addedOrModified)t.has(e)||t.set(e,e.densifyCurvedGeometryForDisplay(this.view.spatialReference));await Promise.all(t.values())}async _fetchResources(e){const t={timeZone:null,timeExtent:null};for(const{tile:s,reader:r}of e){has("esri-2d-update-debug")&&console.debug(`Id[${this.layerId}] Tile[${s.id}] GraphicsView fetchResources`,e);const i=r.getCursor();for(;i.next();)for(const e of i.getMeshWriters())e.enqueueRequest(this._resourceProxy,i,s.createArcadeEvaluationOptions(t))}await this._resourceProxy.fetchEnqueuedResources()}_write(e){for(const t of e){has("esri-2d-update-debug")&&console.debug(`Id[${this.layerId}] Tile[${t.tile.id}] GraphicsView write`,t);const e=this._writeMeshes(t);let s=this._tiles.get(t.tile.key);s||(s=this._createFeatureTile(t.tile.key)),has("esri-2d-update-debug")&&console.debug(`Id[${this.layerId}] Tile[${t.tile.id}] GraphicsView onTileData`,t),this.container.onTileData(s,{type:"update",modify:e,remove:t.removed,end:!1,attributeEpoch:this._attributeStore.epoch,objectIdMap:t.objectIdMap}),this.container.requestRender()}}_writeMeshes(e){const t={timeZone:null,timeExtent:null},s=new T(e.tile.id),r=e.reader.getCursor();for(;r.next();){s.entityStart(r.getDisplayId(),r.getZOrder());for(const i of r.getMeshWriters())i.write(s,this._resourceProxy,r,e.tile.createArcadeEvaluationOptions(t),e.tile.level);s.entityEnd()}return{...s.serialize().message,tileId:e.tile.id}}_setFilterState(e){const t=e.displayId,s=this._attributeStore.getHighlightFlags(e.objectId);this._attributeStore.setData(t,0,0,s|(e.visible?I:0))}_getSymbolForGraphic(e){return null!=e.symbol?e.symbol:null!=this._effectiveRenderer?this._effectiveRenderer.getSymbol(e):this._getNullSymbol(e)}async _ensureSymbolResource(e){if(!e.symbol)return;const t=await this._getSymbolInfo(e.symbol);if(!t)return;const s=t.linearCIM.filter(e=>"text"===e.type);if(s.length>0){const r=await this._getTextResources(e,s);return void(e.symbolResource={symbolInfo:t,textInfo:r})}e.symbolResource={symbolInfo:t}}_getSymbolInfo(e){const t=e.hash();return this._hashToSymbolInfo.has(t)||this._hashToSymbolInfo.set(t,this._createSymbolInfo(t,e).catch(e=>null)),this._hashToSymbolInfo.get(t)}async _createSymbolInfo(e,t){const s=await this._convertToCIMSymbol(t),r=await this._createLinearCIM(s);return{hash:e,cimSymbol:s,linearCIM:r,meshWriters:await this._createMeshWriters(s,r)}}async _convertToCIMSymbol(e){const t=f(e);return"web-style"===t.type?this._convertToCIMSymbol(await t.fetchSymbol({acceptedFormats:["cim","web"]})):t}async _createLinearCIM(e){return await Promise.all(y.fetchResources(e.symbol,this._cimResourceManager,[])),this.view.stage.cimAnalyzer.analyzeSymbolReference(e,!1)}async _createMeshWriters(e,t){a(this._controller.signal);const s=this.container.instanceStore,r=this.view.stage.meshWriterRegistry,i=await R(e,t,s);return Promise.all(i.map(e=>r.createMeshWriter(this._storage,this._resourceProxy,{tileInfo:this.view.featuresTilingScheme.tileInfo},e,null)))}_onTileUpdate(e){if(e.added&&e.added.length>0)for(const t of e.added)this._updateTracking.addPromise(this._addTile(t));if(e.removed&&e.removed.length>0)for(const t of e.removed)this._removeTile(t.key)}_createFeatureTile(e){const t=this.view.featuresTilingScheme.getTileBounds(c(),e),s=this.view.featuresTilingScheme.getTileResolution(e.level),r=new v(e,s,t[0],t[3]);return this._tiles.set(e,r),this.container.addChild(r),r}async _addTile(e){if(!this._attached)return;const t=this._graphicStore.queryItems(e);if(!t.length)return;const s=this._createFeatureTile(e.key),r=F.fromItems(e,t,this._metadata);await this._densifyItemsForDisplay([r]),await this._fetchResources([r]);const i=this._writeMeshes(r);s.onMessage({type:"append",append:i,clear:!1,end:!0,attributeEpoch:this._attributeStore.epoch,objectIdMap:r.objectIdMap})}_removeTile(e){if(!this._tiles.has(e))return;const t=this._tiles.get(e);this.container.removeChild(t),t.destroy(),this._tiles.delete(e)}_getNullSymbol(e){const t=e.geometry;return t?l(t)?w:p(t)||u(t)?S:this.defaultPointSymbolEnabled?b:null:this.defaultPointSymbolEnabled?b:null}async _getTextResources(e,t){const s=new Array,r=new Array;for(let i=0;i<t.length;i++){const o=t[i],{resource:a,overrides:n}=o.textRasterizationParam;if(n?.length>0){const t=_.resolveSymbolOverrides({type:"CIMSymbolReference",primitiveOverrides:n,symbol:{type:"CIMPointSymbol",symbolLayers:[{type:"CIMVectorMarker",enable:!0,size:a.symbol.height,anchorPointUnits:"Relative",frame:{xmin:-5,ymin:-5,xmax:5,ymax:5},markerGraphics:[{type:"CIMMarkerGraphic",geometry:{x:0,y:0},symbol:a.symbol,textString:a.textString}],scaleSymbolsProportionally:!0,respectFrame:!0}]}},e,this.view.spatialReference,null,m(e.projectedGeometry),null,null);t.then(e=>{const t=e.symbolLayers[0],{textString:s}=t.markerGraphics[0];r.push({type:"cim-rasterization-info",resource:{type:"text",textString:s||"",font:a.font}}),o.text=a.textString=s||""}),s.push(t)}else r.push({type:"cim-rasterization-info",resource:a})}s.length>0&&await Promise.all(s);const o=r.map(e=>this.view.stage.textureManager.rasterizeItem(e)),a=await Promise.all(o);i(a);const n=new Map;for(let i=0;i<t.length;i++){const e=t[i];n.set(e.textRasterizationParam.resource.symbol,{text:e.text,glyphMosaicItems:a[i]})}return n}_cleanupSharedResources(){if(!this._cleanupRequired)return;const e=performance.now();if(e-this._lastCleanup<5e3)return;this._cleanupRequired=!1,this._lastCleanup=e;const t=new Set;for(const r of this._graphicStore.items()){const e=r.symbolResource?.symbolInfo.hash;t.add(e)}const s=new Set(this._hashToSymbolInfo.keys());for(const r of s.values())t.has(r)||this._hashToSymbolInfo.delete(r)}};e([h()],O.prototype,"_effectiveRenderer",null),e([h({constructOnly:!0})],O.prototype,"layerId",void 0),e([h({constructOnly:!0})],O.prototype,"requestUpdateCallback",void 0),e([h()],O.prototype,"container",void 0),e([h({constructOnly:!0})],O.prototype,"graphics",void 0),e([h()],O.prototype,"renderer",void 0),e([h()],O.prototype,"_updateTracking",void 0),e([h()],O.prototype,"updating",null),e([h()],O.prototype,"view",void 0),e([h()],O.prototype,"updateRequested",void 0),e([h()],O.prototype,"defaultPointSymbolEnabled",void 0),O=e([d("esri.views.2d.layers.graphics.GraphicsView2D")],O);export{O as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- const I="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgZmlsbD0ibm9uZSIgdmVyc2lvbj0iMi4wIj48c3R5bGUgaWQ9InRoZW1lLXN0eWxlIj4uY29udHJhc3QtZmlsbHtmaWxsOiNmZmZ9LmNvbnRyYXN0LXN0cm9rZXtzdHJva2U6I2ZmZn0uYWNjZW50LWZpbGx7ZmlsbDojZmY3ZjAwO2ZpbGwtb3BhY2l0eTouNX08L3N0eWxlPjxwYXRoIGQ9Ik0yOCAwYTI4IDI4IDAgMSAxIDAgNTYgMjggMjggMCAwIDEgMC01NiIgY2xhc3M9ImFjY2VudC1maWxsIi8+PHBhdGggc3Ryb2tlLXdpZHRoPSI0Ljk5IiBkPSJNMjAuMDUgNDAuODZhMTUuMDUgMTUuMDUgMCAwIDAgMTcuMTQtMS41IDE1LjA1IDE1LjA1IDAgMCAwIDQuNDctMTYuNjUgMTUuMDUgMTUuMDUgMCAwIDAtMjIuNzItNy4xNSAxNS4wNSAxNS4wNSAwIDAgMC01LjUgNy4xNSIgY2xhc3M9ImNvbnRyYXN0LXN0cm9rZSIvPjxwYXRoIGQ9Im0xMC45NyAzNS41NyA1LjM4IDEyLjA3IDcuNzktMTMuNDd6IiBjbGFzcz0iY29udHJhc3QtZmlsbCIvPjwvc3ZnPg==";export{I as default};
5
+ const I="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgZmlsbD0ibm9uZSI+PHN0eWxlIGlkPSJ0aGVtZS1zdHlsZSI+LmNvbnRyYXN0LWZpbGx7ZmlsbDojZmZmfS5jb250cmFzdC1zdHJva2V7c3Ryb2tlOiNmZmZ9LmFjY2VudC1maWxse2ZpbGw6I2ZmN2YwMDtmaWxsLW9wYWNpdHk6LjV9PC9zdHlsZT48cGF0aCBkPSJNMjggMGEyOCAyOCAwIDEgMSAwIDU2IDI4IDI4IDAgMCAxIDAtNTYiIGNsYXNzPSJhY2NlbnQtZmlsbCIvPjxwYXRoIHN0cm9rZS13aWR0aD0iNC45OSIgZD0iTTIwLjA1IDQwLjg2YTE1LjA1IDE1LjA1IDAgMCAwIDE3LjE0LTEuNSAxNS4wNSAxNS4wNSAwIDAgMCA0LjQ3LTE2LjY1IDE1LjA1IDE1LjA1IDAgMCAwLTIyLjcyLTcuMTUgMTUuMDUgMTUuMDUgMCAwIDAtNS41IDcuMTUiIGNsYXNzPSJjb250cmFzdC1zdHJva2UiLz48cGF0aCBkPSJtMTAuOTcgMzUuNTcgNS4zOCAxMi4wNyA3Ljc5LTEzLjQ3eiIgY2xhc3M9ImNvbnRyYXN0LWZpbGwiLz48L3N2Zz4=";export{I as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- const I="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgZmlsbD0ibm9uZSIgdmVyc2lvbj0iMi4wIj48c3R5bGUgaWQ9InRoZW1lLXN0eWxlIj4uY29udHJhc3QtZmlsbHtmaWxsOiNmZmZ9LmNvbnRyYXN0LXN0cm9rZXtzdHJva2U6I2ZmZn0uYWNjZW50LWZpbGx7ZmlsbDojZmY3ZjAwO2ZpbGwtb3BhY2l0eTouNX08L3N0eWxlPjxjaXJjbGUgY3g9IjM5LjQ3OCIgY3k9IjMuMDc4IiByPSIyOCIgY2xhc3M9ImFjY2VudC1maWxsIiB0cmFuc2Zvcm09InJvdGF0ZSg0MC41NDIpIi8+PHBhdGggc3Ryb2tlLXdpZHRoPSI1IiBkPSJtNy4wNzQgMzAuMDUzIDI5LjM5NyAxMS45ODUtMy42NzMtMzMuNDkzIiBjbGFzcz0iY29udHJhc3Qtc3Ryb2tlIi8+PHBhdGggc3Ryb2tlLXdpZHRoPSIyLjk5NiIgZD0iTTI0LjUwNCAyMy4yMDdhMTEuOTggMTEuOTggMCAwIDAtOS44IDcuNTA3IiBjbGFzcz0iY29udHJhc3Qtc3Ryb2tlIGNvbnRyYXN0LWZpbGwiLz48cGF0aCBkPSJtMjkuODE4IDIyLjgwOC02LjE4NCA0LjYtLjU0MS04LjM2NHoiIGNsYXNzPSJjb250cmFzdC1maWxsIi8+PC9zdmc+";export{I as default};
5
+ const I="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgZmlsbD0ibm9uZSI+PHN0eWxlIGlkPSJ0aGVtZS1zdHlsZSI+LmNvbnRyYXN0LWZpbGx7ZmlsbDojZmZmfS5jb250cmFzdC1zdHJva2V7c3Ryb2tlOiNmZmZ9LmFjY2VudC1maWxse2ZpbGw6I2ZmN2YwMDtmaWxsLW9wYWNpdHk6LjV9PC9zdHlsZT48Y2lyY2xlIGN4PSIzOS40NzgiIGN5PSIzLjA3OCIgcj0iMjgiIGNsYXNzPSJhY2NlbnQtZmlsbCIgdHJhbnNmb3JtPSJyb3RhdGUoNDAuNTQyKSIvPjxwYXRoIHN0cm9rZS13aWR0aD0iNSIgZD0ibTcuMDc0IDMwLjA1MyAyOS4zOTcgMTEuOTg1LTMuNjczLTMzLjQ5MyIgY2xhc3M9ImNvbnRyYXN0LXN0cm9rZSIvPjxwYXRoIHN0cm9rZS13aWR0aD0iMi45OTYiIGQ9Ik0yNC41MDQgMjMuMjA3YTExLjk4IDExLjk4IDAgMCAwLTkuOCA3LjUwNyIgY2xhc3M9ImNvbnRyYXN0LXN0cm9rZSBjb250cmFzdC1maWxsIi8+PHBhdGggZD0ibTI5LjgxOCAyMi44MDgtNi4xODQgNC42LS41NDEtOC4zNjR6IiBjbGFzcz0iY29udHJhc3QtZmlsbCIvPjwvc3ZnPg==";export{I as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../../chunks/tslib.es6.js";import{unitRGBAFromColor as t}from"../../../../../core/colorUtils.js";import{handlesGroup as i,makeHandle as s}from"../../../../../core/handleUtils.js";import{destroyMaybe as r}from"../../../../../core/maybe.js";import{watch as o,syncAndInitial as n,initial as a,when as l}from"../../../../../core/reactiveUtils.js";import{property as c}from"../../../../../core/accessorSupport/decorators/property.js";import"../../../../../core/has.js";import"../../../../../core/Logger.js";import"../../../../../core/RandomLCG.js";import{subclass as m}from"../../../../../core/accessorSupport/decorators/subclass.js";import{i as p}from"../../../../../chunks/vec32.js";import{create as h}from"../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{getEffectiveElevationInfo as u,getEffectiveElevationMode as d}from"../../../../../support/elevationInfoUtils.js";import v from"../../../../../symbols/support/ElevationInfo.js";import{SegmentLabels3D as f}from"../../SegmentLabels3D.js";import{SnappingVisualizer3D as g}from"../../SnappingVisualizer3D.js";import{meshTransformFastUpdateHandles as w}from"../meshFastUpdateUtils.js";import{Settings as y}from"../settings.js";import{ExtendedLineVisualElement as V}from"../../visualElements/ExtendedLineVisualElement.js";import{OutlineVisualElement as E}from"../../visualElements/OutlineVisualElement.js";import{VerticesVisualElement as _}from"../../visualElements/VerticesVisualElement.js";import{evaluateElevationAlignmentAtPoint as j}from"../../../layers/graphics/elevationAlignmentUtils.js";import{ElevationContext as L}from"../../../layers/graphics/ElevationContext.js";import{GraphicState as I}from"../../../layers/graphics/GraphicState.js";import{RenderOccludedFlag as S}from"../../../webgl-engine/lib/Material.js";import{DrawGraphicTool as D,geometryTypeToDrawOperationGeometryType as G}from"../../../../draw/DrawGraphicTool.js";import{DrawOperation as x}from"../../../../draw/DrawOperation.js";import{ElevationDrawSurface as C,SceneDrawSurface as O}from"../../../../draw/drawSurfaces.js";import{updateMeshTransformFromTooltipInfo as T}from"../../../../interactive/tooltip/tooltipCommonUtils.js";import{autorun as b}from"../../../../../core/accessorSupport/trackingUtils.js";let z=class extends D{constructor(e){super(e),this._activeVertexVisualElement=null,this._createGraphicState=null,this._outlineVisualElement=null,this._verticesVisualElement=null,this._verticalLineVisualElement=null,this._settings=new y({getTheme:()=>this.view.effectiveTheme}),this.geometryType=null,this.type="draw-3d"}initialize(){const{mode:e,offset:t,unit:i}=this.elevationInfo;this.internalGraphicsLayer.elevationInfo=new v({mode:e,offset:t,unit:i})}normalizeCtorArgs(e){if(!e.elevationInfo){const t=e.hasZ??!0;return{...e,elevationInfo:u(t)}}return e}initializeGraphic(e){const{view:t}=this,s=this._createGraphicState=new I({graphic:e});return i([t.maskOccludee(e),t.trackGraphicState(s),o(()=>({element:this._outlineVisualElement,isDraped:s.isDraped}),({element:e,isDraped:t})=>{e&&(e.isDraped=t)},n),b(()=>{T(this.tooltipInfos.mesh,this.geometryToPlace)}),this._setupLoadingIndicator(s),...w(s)])}makeDrawOperation(){const{geometryType:e}=this,t="circle"!==e&&"rectangle"!==e;return new x({view:this.view,manipulators:this.manipulators,geometryType:G(e),drawingMode:this.mode,hasZ:this.hasZ,defaultZ:this.defaultZ,snapToSceneEnabled:this.snapToScene,drawSurface:new O(this.view,this.elevationInfo,[this.internalGraphicsLayer]),elevationDrawSurface:new C(this.elevationInfo,this.defaultZ,this.view,this.internalGraphicsLayer),hasM:!1,elevationInfo:this.elevationInfo,snappingManager:this.snappingManager,snappingVisualizer:new g,segmentLabels:t?new f:null,labelOptions:this.sketchOptions.labels,isDraped:this._createGraphicState?this._createGraphicState.isDraped:"on-the-ground"===d(this.hasZ,this.elevationInfo),cursor:this.cursor,constraintsEnabled:!0,automaticLengthMeasurementUtils:this.automaticLengthMeasurementUtils})}onActiveVertexChanged(e){const{view:n}=this;if(this._activeVertexVisualElement)return this._activeVertexVisualElement.vertices=[e],this._activeVertexVisualElement.recreate(),this._updateVerticalLineVisualElement(e),s();const l=this._settings,c=l.manipulators.vertex,m=new _({view:n,spatialReference:n.spatialReference,vertices:[e],elevationInfo:this.internalGraphicsLayer.elevationInfo,size:c.size,outlineSize:c.outlineSize,renderOccluded:c.renderOccluded,attached:!1,isDecoration:!0});this._activeVertexVisualElement=m;const p=l.visualElements.zVerticalLine,h=new V({view:n,extensionType:p.extensionType,innerWidth:1,attached:!1,writeDepthEnabled:!1,renderOccluded:S.OccludeAndTransparent,isDecoration:!0});this._verticalLineVisualElement=h;const u=i([o(()=>l.visualElements.zVerticalLine,e=>e.apply(h),a),o(()=>({selectedColor:t(l.colors.selected),outlineColor:t(l.manipulators.vertex.outlineColor)}),({selectedColor:e,outlineColor:t})=>{m.color=e,m.outlineColor=t},a),s(()=>{this._activeVertexVisualElement=r(this._activeVertexVisualElement),this._verticalLineVisualElement=r(this._verticalLineVisualElement)})]);return m.attached=!0,this._updateVerticalLineVisualElement(e),u}_updateVerticalLineVisualElement(e){const t=this._verticalLineVisualElement;if(!t)return;const{renderCoordsHelper:i,elevationProvider:s}=this.view;p(A,e[0],e[1],e[2]),U.setFromElevationInfo(this.elevationInfo),A[2]=j(A,s,U,i);i.toRenderCoords(A,this.view.spatialReference,A)?(t.setStartEndFromWorldDownAtLocation(A),t.attached=!0):t.attached=!1}onOutlineChanged(e){if(this._outlineVisualElement)return this._outlineVisualElement.geometry=e,s();const t=this.internalGraphicsLayer.elevationInfo,{view:n}=this,l=this._settings,c=new E({view:n,geometry:e,elevationInfo:t,isDraped:this._createGraphicState?this._createGraphicState.isDraped:"on-the-ground"===d(this.hasZ,t),attached:!1,isDecoration:!0});this._outlineVisualElement=c;const m=i([o(()=>l.visualElements.lineObjects.outline,e=>e.apply(c),a),o(()=>l.visualElements.lineObjects.shadowStyle,e=>e.apply(c),a),s(()=>{this._outlineVisualElement=r(this._outlineVisualElement)})]);return c.attached=!0,c.laserlineEnabled=!0,m}onRegularVerticesChanged(e){if(this._verticesVisualElement)return this._verticesVisualElement.vertices=e,s();const{view:n}=this,l=this._settings,c=l.manipulators.vertex,m=new _({view:n,spatialReference:n.spatialReference,vertices:e,elevationInfo:this.internalGraphicsLayer.elevationInfo,size:c.size,outlineSize:c.outlineSize,renderOccluded:c.renderOccluded,attached:!1,isDecoration:!0}),p=i([o(()=>({color:t(l.manipulators.vertex.color),outlineColor:t(l.manipulators.vertex.outlineColor)}),({color:e,outlineColor:t})=>{m.color=e,m.outlineColor=t},a),s(()=>{this._verticesVisualElement=r(this._verticesVisualElement)})]);return m.attached=!0,this._verticesVisualElement=m,p}updateGraphicGeometry(e){if("mesh"!==this.geometryType||"point"!==e?.type)super.updateGraphicGeometry(e);else{const t=this.geometryToPlace;t?.centerAt(e),T(this.tooltipInfos.mesh,t);const i=this._graphic;t&&i.geometry===t||(i.geometry=t)}}_setupLoadingIndicator(e){const{drawOperation:t}=this;if(!this.geometryToPlace)return t.loading=!1,null;t.loading=!0;const r=s(()=>{t.loading=!1});let o;const a=()=>o&&cancelAnimationFrame(o);return i([l(()=>e.displaying,()=>{a(),o=requestAnimationFrame(()=>r.remove())},{...n,once:!0}),s(a),r])}};e([c({constructOnly:!0})],z.prototype,"elevationInfo",void 0),e([c({constructOnly:!0})],z.prototype,"geometryType",void 0),e([c()],z.prototype,"type",void 0),e([c({constructOnly:!0})],z.prototype,"view",void 0),z=e([m("esri.views.3d.interactive.editingTools.draw.DrawGraphicTool3D")],z);const U=new L,A=h();export{z as DrawGraphicTool3D};
5
+ import{_ as e}from"../../../../../chunks/tslib.es6.js";import{unitRGBAFromColor as t}from"../../../../../core/colorUtils.js";import{handlesGroup as i,makeHandle as r}from"../../../../../core/handleUtils.js";import{destroyMaybe as s}from"../../../../../core/maybe.js";import{watch as o,syncAndInitial as n,initial as a,when as l}from"../../../../../core/reactiveUtils.js";import{property as c}from"../../../../../core/accessorSupport/decorators/property.js";import"../../../../../core/has.js";import"../../../../../core/Logger.js";import"../../../../../core/RandomLCG.js";import{subclass as m}from"../../../../../core/accessorSupport/decorators/subclass.js";import{i as p}from"../../../../../chunks/vec32.js";import{create as h}from"../../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{getEffectiveElevationInfo as u,getEffectiveElevationMode as d}from"../../../../../support/elevationInfoUtils.js";import v from"../../../../../symbols/support/ElevationInfo.js";import{SegmentLabels3D as f}from"../../SegmentLabels3D.js";import{SnappingVisualizer3D as g}from"../../SnappingVisualizer3D.js";import{meshTransformFastUpdateHandles as w}from"../meshFastUpdateUtils.js";import{Settings as y}from"../settings.js";import{ExtendedLineVisualElement as V}from"../../visualElements/ExtendedLineVisualElement.js";import{OutlineVisualElement as E}from"../../visualElements/OutlineVisualElement.js";import{VerticesVisualElement as _}from"../../visualElements/VerticesVisualElement.js";import{evaluateElevationAlignmentAtPoint as j}from"../../../layers/graphics/elevationAlignmentUtils.js";import{ElevationContext as L}from"../../../layers/graphics/ElevationContext.js";import{GraphicState as I}from"../../../layers/graphics/GraphicState.js";import{RenderOccludedFlag as S}from"../../../webgl-engine/lib/Material.js";import{DrawGraphicTool as D,geometryTypeToDrawOperationGeometryType as G}from"../../../../draw/DrawGraphicTool.js";import{DrawOperation as x}from"../../../../draw/DrawOperation.js";import{ElevationDrawSurface as C,SceneDrawSurface as O}from"../../../../draw/drawSurfaces.js";import{updateMeshTransformFromTooltipInfo as T}from"../../../../interactive/tooltip/tooltipCommonUtils.js";import{autorun as b}from"../../../../../core/accessorSupport/trackingUtils.js";let z=class extends D{constructor(e){super(e),this._activeVertexVisualElement=null,this._createGraphicState=null,this._outlineVisualElement=null,this._verticesVisualElement=null,this._verticalLineVisualElement=null,this._settings=new y({getTheme:()=>this.view.effectiveTheme}),this.geometryType=null,this.type="draw-3d"}initialize(){const{mode:e,offset:t,unit:i}=this.elevationInfo;this.internalGraphicsLayer.elevationInfo=new v({mode:e,offset:t,unit:i})}normalizeCtorArgs(e){if(!e.elevationInfo){const t=e.hasZ??!0;return{...e,elevationInfo:u(t)}}return e}initializeGraphic(e){const{view:t}=this,r=this._createGraphicState=new I({graphic:e});return i([t.maskOccludee(e),t.trackGraphicState(r),o(()=>({element:this._outlineVisualElement,isDraped:r.isDraped}),({element:e,isDraped:t})=>{e&&(e.isDraped=t)},n),b(()=>{T(this.tooltipInfos.mesh,this.geometryToPlace)}),this._setupLoadingIndicator(r),...w(r)])}makeDrawOperation(){const{geometryType:e}=this,t="circle"!==e&&"rectangle"!==e;return new x({view:this.view,manipulators:this.manipulators,geometryType:G(e),drawingMode:this.mode,hasZ:this.hasZ,defaultZ:this.defaultZ,snapToSceneEnabled:this.snapToScene,drawSurface:new O(this.view,this.elevationInfo,[this.internalGraphicsLayer]),elevationDrawSurface:new C(this.elevationInfo,this.defaultZ,this.view,this.internalGraphicsLayer),hasM:!1,elevationInfo:this.elevationInfo,snappingManager:this.snappingManager,snappingVisualizer:new g,segmentLabels:t?new f:null,labelOptions:this.sketchOptions.labels,isDraped:this._createGraphicState?this._createGraphicState.isDraped:"on-the-ground"===d(this.hasZ,this.elevationInfo),cursor:this.cursor,constraintsEnabled:!0,automaticLengthMeasurementUtils:this.automaticLengthMeasurementUtils})}onActiveVertexChanged(e){const{view:n}=this;if(this._activeVertexVisualElement)return this._activeVertexVisualElement.vertices=[e],this._activeVertexVisualElement.recreate(),this._updateVerticalLineVisualElement(e),r();const l=this._settings,c=l.manipulators.vertex,m=new _({view:n,spatialReference:n.spatialReference,vertices:[e],elevationInfo:this.internalGraphicsLayer.elevationInfo,size:c.size,outlineSize:c.outlineSize,renderOccluded:c.renderOccluded,attached:!1,isDecoration:!0});this._activeVertexVisualElement=m;const p=l.visualElements.zVerticalLine,h=new V({view:n,extensionType:p.extensionType,innerWidth:1,attached:!1,writeDepthEnabled:!1,renderOccluded:S.OccludeAndTransparent,isDecoration:!0});this._verticalLineVisualElement=h;const u=i([o(()=>l.visualElements.zVerticalLine,e=>e.apply(h),a),o(()=>({selectedColor:t(l.colors.selected),outlineColor:t(l.manipulators.vertex.outlineColor)}),({selectedColor:e,outlineColor:t})=>{m.color=e,m.outlineColor=t},a),r(()=>{this._activeVertexVisualElement=s(this._activeVertexVisualElement),this._verticalLineVisualElement=s(this._verticalLineVisualElement)})]);return m.attached=!0,this._updateVerticalLineVisualElement(e),u}_updateVerticalLineVisualElement(e){const t=this._verticalLineVisualElement;if(!t)return;const{renderCoordsHelper:i,elevationProvider:r}=this.view;p(A,e[0],e[1],e[2]),U.setFromElevationInfo(this.elevationInfo),A[2]=j(A,r,U,i);i.toRenderCoords(A,this.view.spatialReference,A)?(t.setStartEndFromWorldDownAtLocation(A),t.attached=!0):t.attached=!1}onOutlineChanged(e){if(this._outlineVisualElement)return this._outlineVisualElement.geometry=e,r();const t=this.internalGraphicsLayer.elevationInfo,{view:n}=this,l=this._settings,c=new E({view:n,geometry:e,elevationInfo:t,isDraped:this._createGraphicState?this._createGraphicState.isDraped:"on-the-ground"===d(this.hasZ,t),attached:!1,isDecoration:!0});this._outlineVisualElement=c;const m=i([o(()=>l.visualElements.lineObjects.outline,e=>e.apply(c),a),o(()=>l.visualElements.lineObjects.shadowStyle,e=>e.apply(c),a),r(()=>{this._outlineVisualElement=s(this._outlineVisualElement)})]);return c.attached=!0,c.laserlineEnabled=!0,m}onRegularVerticesChanged(e){if(this._verticesVisualElement)return this._verticesVisualElement.vertices=e,r();const{view:n}=this,l=this._settings,c=l.manipulators.vertex,m=new _({view:n,spatialReference:n.spatialReference,vertices:e,elevationInfo:this.internalGraphicsLayer.elevationInfo,size:c.size,outlineSize:c.outlineSize,renderOccluded:c.renderOccluded,attached:!1,isDecoration:!0}),p=i([o(()=>({color:t(l.manipulators.vertex.color),outlineColor:t(l.manipulators.vertex.outlineColor)}),({color:e,outlineColor:t})=>{m.color=e,m.outlineColor=t},a),r(()=>{this._verticesVisualElement=s(this._verticesVisualElement)})]);return m.attached=!0,this._verticesVisualElement=m,p}updateGraphicGeometry(e){if("mesh"===this.geometryType&&"point"===e?.type){const t=this.geometryToPlace;t?.centerAt(e),T(this.tooltipInfos.mesh,t);const i=this._graphic;return void(t&&i.geometry===t||(i.geometry=t))}super.updateGraphicGeometry(e)}_setupLoadingIndicator(e){const{drawOperation:t}=this;if(!this.geometryToPlace)return t.loading=!1,null;t.loading=!0;const s=r(()=>{t.loading=!1});let o;const a=()=>o&&cancelAnimationFrame(o);return i([l(()=>e.displaying,()=>{a(),o=requestAnimationFrame(()=>s.remove())},{...n,once:!0}),r(a),s])}};e([c({constructOnly:!0})],z.prototype,"elevationInfo",void 0),e([c({constructOnly:!0})],z.prototype,"geometryType",void 0),e([c()],z.prototype,"type",void 0),e([c({constructOnly:!0})],z.prototype,"view",void 0),z=e([m("esri.views.3d.interactive.editingTools.draw.DrawGraphicTool3D")],z);const U=new L,A=h();export{z as DrawGraphicTool3D};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{hasScaling as e}from"../../../core/mathUtils.js";import r from"../../../geometry/SpatialReference.js";import t from"../../../geometry/support/MeshGeoreferencedVertexSpace.js";import o from"../../../geometry/support/MeshLocalVertexSpace.js";import{b as n,n as s}from"../../../chunks/vec3.js";import{IndexType as i}from"../../../libs/i3s/enums.js";import{get as a}from"../../../libs/i3s/I3SModule.js";import{TransformedGeometry as f,TransformedData as c}from"./I3SMeshWorkerHandle.js";import{NodeIMModificationImpact as l}from"./i3s/I3SNode.js";async function u(e){E=await U();const r=[e.geometryBuffer];return{result:A(E,e,r),transferList:r}}async function m(e){E=await U();const r=[e.geometryBuffer],{geometryBuffer:t}=e,o=t.byteLength,n=E._malloc(o),s=new Uint8Array(E.HEAPU8.buffer,n,o);s.set(new Uint8Array(t));const i=E.dracoDecompressPointCloudData(n,s.byteLength);if(E._free(n),i.error.length>0)throw new Error(`i3s.wasm: ${i.error}`);const a=i.featureIds?.length>0?i.featureIds.slice():null,f=i.positions.slice();return a&&r.push(a.buffer),r.push(f.buffer),{result:{positions:f,featureIds:a},transferList:r}}async function y(e){await U(),S(e);const r={buffer:e.buffer};return{result:r,transferList:[r.buffer]}}async function p(e){await U(),j(e)}async function d(e){E=await U(),E.setLegacySchema(e.context,e.jsonSchema)}async function h(e){const{localMatrix:n,origin:s,positions:i,vertexSpace:a}=e,f=r.fromJSON(e.inSpatialReference),c=r.fromJSON(e.outSpatialReference);let l;const[{projectBuffer:u},{initializeProjection:m}]=await Promise.all([import("../../../geometry/projection/projectBuffer.js"),import("../../../geometry/projectionUtils.js")]);await m(f,c);const y=[0,0,0];if(!u(s,f,0,y,c,0))throw new Error("Failed to project");if("georeferenced"===a.type&&null==a.origin){if(l=new Float64Array(i.length),!u(i,f,0,l,c,0,l.length/3))throw new Error("Failed to project")}else{const e="georeferenced"===a.type?t.fromJSON(a):o.fromJSON(a),{projectMeshVertexPositions:r}=await import("../../../geometry/support/meshUtils/projectMeshVertexPositions.js"),s=r({vertexAttributes:{position:i},transform:n?{localMatrix:n}:void 0,vertexSpace:e,spatialReference:f},c);if(!s)throw new Error("Failed to project");l=s}const p=l.length,[d,h,b]=y;for(let r=0;r<p;r+=3)l[r]-=d,l[r+1]-=h,l[r+2]-=b;return{result:{projected:l,original:i,projectedOrigin:y},transferList:[l.buffer,i.buffer]}}async function b({normalMatrix:r,normals:t}){const o=new Float32Array(t.length);return n(o,t,r),e(r)&&s(o,o),{result:{transformed:o,original:t},transferList:[o.buffer,t.buffer]}}function g(e){x(e)}let w,E;function j(e){if(!E)return;const r=e.modifications,t=E._malloc(8*r.length),o=new Float64Array(E.HEAPU8.buffer,t,r.length);for(let n=0;n<r.length;++n)o[n]=r[n];E.setModifications(e.context,t,r.length,e.isGeodetic),E._free(t)}function A(e,r,t){const{context:o,globalTrafo:n,mbs:s,obbData:a,elevationOffset:l,geometryBuffer:u,geometryDescriptor:m,indexToVertexProjector:y,vertexToRenderProjector:p}=r,d=e._malloc(u.byteLength),h=33,b=e._malloc(h*Float64Array.BYTES_PER_ELEMENT),g=new Uint8Array(e.HEAPU8.buffer,d,u.byteLength);g.set(new Uint8Array(u));const w=new Float64Array(e.HEAPU8.buffer,b,h);_(w,[NaN,NaN,NaN]);let E=w.byteOffset+3*w.BYTES_PER_ELEMENT,j=new Float64Array(w.buffer,E);_(j,n),E+=16*w.BYTES_PER_ELEMENT,j=new Float64Array(w.buffer,E),_(j,s),E+=4*w.BYTES_PER_ELEMENT,a&&(j=new Float64Array(w.buffer,E),_(j,a));const A=m,L={isDraco:!1,isLegacy:!1,color:r.layouts.some(e=>e.some(e=>"color"===e.name)),normal:r.needNormals&&r.layouts.some(e=>e.some(e=>"normalCompressed"===e.name)),uv0:r.layouts.some(e=>e.some(e=>"uv0"===e.name)),uvRegion:r.layouts.some(e=>e.some(e=>"uvRegion"===e.name)),featureIndex:A.featureIndex},S=e.process(o,!!r.obbData,d,g.byteLength,A,L,b,l,y,p,r.normalReferenceFrame);if(e._free(b),e._free(d),S.error.length>0)throw new Error(`i3s.wasm: ${S.error}`);if(S.discarded)return null;const x=S.componentOffsets.length>0?S.componentOffsets.slice():null,P=S.featureIds.length>0?S.featureIds.slice():null,U=S.anchorIds.length>0?Array.from(S.anchorIds):null,M=S.anchors.length>0?Array.from(S.anchors):null,N=S.interleavedVertedData.slice().buffer,I=S.indicesType===i.Int16?new Uint16Array(S.indices.buffer,S.indices.byteOffset,S.indices.byteLength/2).slice():new Uint32Array(S.indices.buffer,S.indices.byteOffset,S.indices.byteLength/4).slice(),F=S.positions.slice(),{buffer:T,byteOffset:B,byteLength:O}=S.positionIndices,R=S.positionIndicesType===i.Int16?new Uint16Array(T,B,O/2).slice():new Uint32Array(T,B,O/4).slice(),v=new f(r.layouts[0],N,I,S.hasColors,S.hasModifications,{data:F,indices:R});return P&&t.push(P.buffer),x&&t.push(x.buffer),t.push(N),t.push(I.buffer),t.push(F.buffer),t.push(R.buffer),new c(x,P,U,M,v,n,S.obb)}function L(e){return 0===e?l.Unmodified:1===e?l.PotentiallyModified:2===e?l.Culled:l.Unknown}function S(e){if(!E)return;const{context:r,buffer:t}=e,o=E._malloc(t.byteLength),n=t.byteLength/Float64Array.BYTES_PER_ELEMENT,s=new Float64Array(E.HEAPU8.buffer,o,n),i=new Float64Array(t);s.set(i),E.filterOBBs(r,o,n),i.set(s),E._free(o)}function x(e){E&&0===E.destroy(e)&&(E=null)}function _(e,r){for(let t=0;t<r.length;++t)e[t]=r[t]}async function P(){E||await U()}async function U(){return E||(E=await(w??=a())),E}const M={transform:(e,r)=>E&&A(E,e,r),destroy:x};export{g as destroyContext,m as dracoDecompressPointCloudData,y as filterObbsForModifications,S as filterObbsForModificationsSync,P as initialize,L as interpretObbModificationResults,u as process,h as project,d as setLegacySchema,p as setModifications,j as setModificationsSync,M as test,b as transformNormals};
5
+ import{hasScaling as e}from"../../../core/mathUtils.js";import r from"../../../geometry/SpatialReference.js";import t from"../../../geometry/support/MeshGeoreferencedVertexSpace.js";import o from"../../../geometry/support/MeshLocalVertexSpace.js";import{b as n,n as s}from"../../../chunks/vec3.js";import{IndexType as i}from"../../../libs/i3s/enums.js";import{get as a,cleanup as f}from"../../../libs/i3s/I3SModule.js";import{TransformedGeometry as c,TransformedData as l}from"./I3SMeshWorkerHandle.js";import{NodeIMModificationImpact as u}from"./i3s/I3SNode.js";async function m(e){j=await M();const r=[e.geometryBuffer];return{result:L(j,e,r),transferList:r}}async function y(e){j=await M();const r=[e.geometryBuffer],{geometryBuffer:t}=e,o=t.byteLength,n=j._malloc(o),s=new Uint8Array(j.HEAPU8.buffer,n,o);s.set(new Uint8Array(t));const i=j.dracoDecompressPointCloudData(n,s.byteLength);if(j._free(n),i.error.length>0)throw new Error(`i3s.wasm: ${i.error}`);const a=i.featureIds?.length>0?i.featureIds.slice():null,f=i.positions.slice();return a&&r.push(a.buffer),r.push(f.buffer),{result:{positions:f,featureIds:a},transferList:r}}async function p(e){await M(),x(e);const r={buffer:e.buffer};return{result:r,transferList:[r.buffer]}}async function d(e){await M(),A(e)}async function h(e){j=await M(),j.setLegacySchema(e.context,e.jsonSchema)}async function b(e){const{localMatrix:n,origin:s,positions:i,vertexSpace:a}=e,f=r.fromJSON(e.inSpatialReference),c=r.fromJSON(e.outSpatialReference);let l;const[{projectBuffer:u},{initializeProjection:m}]=await Promise.all([import("../../../geometry/projection/projectBuffer.js"),import("../../../geometry/projectionUtils.js")]);await m(f,c);const y=[0,0,0];if(!u(s,f,0,y,c,0))throw new Error("Failed to project");if("georeferenced"===a.type&&null==a.origin){if(l=new Float64Array(i.length),!u(i,f,0,l,c,0,l.length/3))throw new Error("Failed to project")}else{const e="georeferenced"===a.type?t.fromJSON(a):o.fromJSON(a),{projectMeshVertexPositions:r}=await import("../../../geometry/support/meshUtils/projectMeshVertexPositions.js"),s=r({vertexAttributes:{position:i},transform:n?{localMatrix:n}:void 0,vertexSpace:e,spatialReference:f},c);if(!s)throw new Error("Failed to project");l=s}const p=l.length,[d,h,b]=y;for(let r=0;r<p;r+=3)l[r]-=d,l[r+1]-=h,l[r+2]-=b;return{result:{projected:l,original:i,projectedOrigin:y},transferList:[l.buffer,i.buffer]}}async function g({normalMatrix:r,normals:t}){const o=new Float32Array(t.length);return n(o,t,r),e(r)&&s(o,o),{result:{transformed:o,original:t},transferList:[o.buffer,t.buffer]}}function w(e){_(e)}let E,j;function A(e){if(!j)return;const r=e.modifications,t=j._malloc(8*r.length),o=new Float64Array(j.HEAPU8.buffer,t,r.length);for(let n=0;n<r.length;++n)o[n]=r[n];j.setModifications(e.context,t,r.length,e.isGeodetic),j._free(t)}function L(e,r,t){const{context:o,globalTrafo:n,mbs:s,obbData:a,elevationOffset:f,geometryBuffer:u,geometryDescriptor:m,indexToVertexProjector:y,vertexToRenderProjector:p}=r,d=e._malloc(u.byteLength),h=33,b=e._malloc(h*Float64Array.BYTES_PER_ELEMENT),g=new Uint8Array(e.HEAPU8.buffer,d,u.byteLength);g.set(new Uint8Array(u));const w=new Float64Array(e.HEAPU8.buffer,b,h);P(w,[NaN,NaN,NaN]);let E=w.byteOffset+3*w.BYTES_PER_ELEMENT,j=new Float64Array(w.buffer,E);P(j,n),E+=16*w.BYTES_PER_ELEMENT,j=new Float64Array(w.buffer,E),P(j,s),E+=4*w.BYTES_PER_ELEMENT,a&&(j=new Float64Array(w.buffer,E),P(j,a));const A=m,L={isDraco:!1,isLegacy:!1,color:r.layouts.some(e=>e.some(e=>"color"===e.name)),normal:r.needNormals&&r.layouts.some(e=>e.some(e=>"normalCompressed"===e.name)),uv0:r.layouts.some(e=>e.some(e=>"uv0"===e.name)),uvRegion:r.layouts.some(e=>e.some(e=>"uvRegion"===e.name)),featureIndex:A.featureIndex},S=e.process(o,!!r.obbData,d,g.byteLength,A,L,b,f,y,p,r.normalReferenceFrame);if(e._free(b),e._free(d),S.error.length>0)throw new Error(`i3s.wasm: ${S.error}`);if(S.discarded)return null;const x=S.componentOffsets.length>0?S.componentOffsets.slice():null,_=S.featureIds.length>0?S.featureIds.slice():null,U=S.anchorIds.length>0?Array.from(S.anchorIds):null,M=S.anchors.length>0?Array.from(S.anchors):null,N=S.interleavedVertedData.slice().buffer,I=S.indicesType===i.Int16?new Uint16Array(S.indices.buffer,S.indices.byteOffset,S.indices.byteLength/2).slice():new Uint32Array(S.indices.buffer,S.indices.byteOffset,S.indices.byteLength/4).slice(),F=S.positions.slice(),{buffer:T,byteOffset:B,byteLength:O}=S.positionIndices,R=S.positionIndicesType===i.Int16?new Uint16Array(T,B,O/2).slice():new Uint32Array(T,B,O/4).slice(),v=new c(r.layouts[0],N,I,S.hasColors,S.hasModifications,{data:F,indices:R});return _&&t.push(_.buffer),x&&t.push(x.buffer),t.push(N),t.push(I.buffer),t.push(F.buffer),t.push(R.buffer),new l(x,_,U,M,v,n,S.obb)}function S(e){return 0===e?u.Unmodified:1===e?u.PotentiallyModified:2===e?u.Culled:u.Unknown}function x(e){if(!j)return;const{context:r,buffer:t}=e,o=j._malloc(t.byteLength),n=t.byteLength/Float64Array.BYTES_PER_ELEMENT,s=new Float64Array(j.HEAPU8.buffer,o,n),i=new Float64Array(t);s.set(i),j.filterOBBs(r,o,n),i.set(s),j._free(o)}function _(e){j&&0===j.destroy(e)&&(j=null,E=null,f())}function P(e,r){for(let t=0;t<r.length;++t)e[t]=r[t]}async function U(){j||await M()}async function M(){return j||(j=await(E??=a())),j}const N={transform:(e,r)=>j&&L(j,e,r),destroy:_};export{w as destroyContext,y as dracoDecompressPointCloudData,p as filterObbsForModifications,x as filterObbsForModificationsSync,U as initialize,S as interpretObbModificationResults,m as process,b as project,h as setLegacySchema,d as setModifications,A as setModificationsSync,N as test,g as transformNormals};