@arcgis/core 5.0.0-next.33 → 5.0.0-next.35

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 (220) hide show
  1. package/applications/Components/SketchTooltipControls.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/{f8a5b26e0231244972d8.js → 032444974011118127d7.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{9252854b512237b6a0ef.js → 0446562aee0639c61485.js} +1 -1
  5. package/assets/esri/core/workers/chunks/15c1a48e8cd2a8882d85.js +1 -0
  6. package/assets/esri/core/workers/chunks/{1dd867fa7c58c06b79ea.js → 1bacdd17e199e22b5cd1.js} +1 -1
  7. package/assets/esri/core/workers/chunks/{b56c07c0b43cb1999070.js → 1fa55d4c4b092a98bdd7.js} +1 -1
  8. package/assets/esri/core/workers/chunks/234ffd08c2be03a0b9fe.js +1 -0
  9. package/assets/esri/core/workers/chunks/32d32d3c3b38a215d20d.js +1 -0
  10. package/assets/esri/core/workers/chunks/{e7f4d135ef9665de1468.js → 33431e8131f6017de2f9.js} +1 -1
  11. package/assets/esri/core/workers/chunks/36130910ba141f34531b.js +1 -0
  12. package/assets/esri/core/workers/chunks/{096e5f94eaa226814569.js → 4356274cfa477eb6d749.js} +1 -1
  13. package/assets/esri/core/workers/chunks/48d1a443b324753921de.js +1 -0
  14. package/assets/esri/core/workers/chunks/{3c1e50c3505e5e7c946a.js → 4d5591c1b4ef37075921.js} +1 -1
  15. package/assets/esri/core/workers/chunks/4f4d51181ae7db9fbe6d.js +1 -0
  16. package/assets/esri/core/workers/chunks/{d21ae4980741be98f948.js → 59889855d23baec1adf9.js} +1 -1
  17. package/assets/esri/core/workers/chunks/{fee942ef802a162e0248.js → 5dc0d853c21ccb6054c7.js} +1 -1
  18. package/assets/esri/core/workers/chunks/5f9e64f00329cb646f0c.js +1 -0
  19. package/assets/esri/core/workers/chunks/{d786b17cc9062b1450ac.js → 726a797f5df7eeee0b3d.js} +1 -1
  20. package/assets/esri/core/workers/chunks/768d9b6eaba7bfa18dde.js +1 -0
  21. package/assets/esri/core/workers/chunks/{a4b7ba8aec109beb5b4d.js → 7d3e665613927904ba4f.js} +1 -1
  22. package/assets/esri/core/workers/chunks/{a2cee5ac0d4df0108425.js → 82cc758bddd9f8397b9f.js} +1 -1
  23. package/assets/esri/core/workers/chunks/{433d249c35c56bf15806.js → 97650ee3d0eecb69ccbb.js} +3 -3
  24. package/assets/esri/core/workers/chunks/{866a608d489bf56bc371.js → a372d9af43ade7c6314c.js} +1 -1
  25. package/assets/esri/core/workers/chunks/{add17e95f47e6904bf6d.js → a59dab47a58695c639da.js} +1 -1
  26. package/assets/esri/core/workers/chunks/{f441fc74451330384fb0.js → abb05a903440d97a6a74.js} +1 -1
  27. package/assets/esri/core/workers/chunks/ad138b989c2c7a1168ac.js +1 -0
  28. package/assets/esri/core/workers/chunks/{5baef729beef0199c3d9.js → b536fdb655ad293d9024.js} +1 -1
  29. package/assets/esri/core/workers/chunks/{1d4ea8db272655c0608c.js → c7c721de93bc8688e13c.js} +1 -1
  30. package/assets/esri/core/workers/chunks/{446f76356fc116204ec3.js → c8d2cce4a426c72ab173.js} +1 -1
  31. package/assets/esri/core/workers/chunks/{14feb12826e0c8ba7fb8.js → d14bd320f72d8e8a0ad8.js} +1 -1
  32. package/assets/esri/core/workers/chunks/{4b6a44c6265c8959abd8.js → d3db7244fac7398cc700.js} +1 -1
  33. package/assets/esri/core/workers/chunks/{7aa730e5ac7b268e3c98.js → dd34d56caafa38d4b8e4.js} +1 -1
  34. package/assets/esri/core/workers/chunks/ef5b13ee3362763c1096.js +1 -0
  35. package/assets/esri/core/workers/chunks/{2a17991923abc64c84c6.js → f55328aabf84770c8e6a.js} +1 -1
  36. package/assets/esri/core/workers/chunks/{e32fc0b2c6530d28ce85.js → fa01d1813fa78034526e.js} +1 -1
  37. package/assets/esri/libs/lyr3d/lyr3DMain.wasm +0 -0
  38. package/chunks/ComponentShader.glsl.js +19 -21
  39. package/chunks/Laserlines.glsl.js +1 -1
  40. package/chunks/Terrain.glsl.js +9 -11
  41. package/chunks/boundedPlane.js +1 -1
  42. package/chunks/cameraUtilsSpherical.js +1 -1
  43. package/chunks/lyr3DMain.js +1 -1
  44. package/chunks/vec32.js +1 -1
  45. package/config.js +1 -1
  46. package/core/deprecate.js +1 -1
  47. package/core/has.js +1 -1
  48. package/core/libs/gl-matrix-2/math/quat.js +1 -1
  49. package/core/libs/gl-matrix-2/math/vec3.js +1 -1
  50. package/core/workers/registry.js +1 -1
  51. package/geometry/geometryEngineJSON.js +1 -1
  52. package/geometry/operators/integrateOperator.js +1 -1
  53. package/geometry/support/buffer/BufferView.js +1 -1
  54. package/geometry/support/coordsUtils.js +1 -1
  55. package/geometry/support/curves/curveUtils.js +1 -1
  56. package/geometry/support/curves/interpolateCurve.js +5 -0
  57. package/geometry/support/lineSegment.js +1 -1
  58. package/geometry/support/meshUtils/Metadata.js +1 -1
  59. package/geometry/support/meshUtils/merge.js +1 -1
  60. package/geometry/support/sphere.js +1 -1
  61. package/geometry/support/vector.js +1 -1
  62. package/interfaces.d.ts +71 -445
  63. package/intl/locale.js +1 -1
  64. package/kernel.js +1 -1
  65. package/layers/Lyr3DWasmPerSceneView.js +1 -1
  66. package/layers/SceneLayer.js +1 -1
  67. package/layers/VoxelWasmPerSceneView.js +1 -1
  68. package/layers/graphics/data/QueryEngine.js +1 -1
  69. package/layers/graphics/data/QueryEngineResult.js +1 -1
  70. package/layers/graphics/sources/support/uploadAssets.js +1 -1
  71. package/layers/orientedImagery/transformations/worldToImage.js +1 -1
  72. package/layers/support/layerOriginUtils.js +1 -1
  73. package/layers/voxel/VoxelVolume.js +1 -1
  74. package/package.json +3 -3
  75. package/request/config.js +1 -1
  76. package/request/process.js +1 -1
  77. package/smartMapping/statistics/support/statsWorker.js +1 -1
  78. package/support/revision.js +1 -1
  79. package/views/2d/interactive/SegmentLabels2D.js +5 -0
  80. package/views/3d/analysis/AreaMeasurement/support/MeasurementData.js +1 -1
  81. package/views/3d/analysis/Dimension/lengthDimensionConstraintUtils.js +1 -1
  82. package/views/3d/analysis/Dimension/lengthDimensionUtils.js +1 -1
  83. package/views/3d/analysis/LineOfSight/LineOfSightController.js +1 -1
  84. package/views/3d/analysis/LineOfSight/LineOfSightIntersectionResult.js +1 -1
  85. package/views/3d/analysis/Slice/sliceToolUtils.js +1 -1
  86. package/views/3d/analysis/Viewshed/ViewshedScaleOrientManipulation.js +1 -1
  87. package/views/3d/analysis/Viewshed/ViewshedSubTool.js +1 -1
  88. package/views/3d/analysis/Viewshed/ViewshedSubVisualization.js +1 -1
  89. package/views/3d/analysis/Viewshed/ViewshedTool.js +1 -1
  90. package/views/3d/animation/pointToPoint/Camera.js +1 -1
  91. package/views/3d/camera/constraintUtils/distance.js +1 -1
  92. package/views/3d/camera/constraintUtils/tilt.js +1 -1
  93. package/views/3d/environment/ChapmanAtmosphere.js +1 -1
  94. package/views/3d/environment/CloudsParameters.js +1 -1
  95. package/views/3d/environment/EnvironmentManager.js +1 -1
  96. package/views/3d/environment/MarsAtmosphere.js +1 -1
  97. package/views/3d/interactive/SegmentLabels3D.js +1 -1
  98. package/views/3d/interactive/editingTools/manipulations/MoveZManipulation.js +1 -1
  99. package/views/3d/interactive/editingTools/media/MediaElementManipulator3D.js +1 -1
  100. package/views/3d/interactive/editingTools/reshape/edgeOffsetUtils.js +1 -1
  101. package/views/3d/interactive/visualElements/MeasurementArrowVisualElement.js +1 -1
  102. package/views/3d/interactive/visualElements/RightAngleQuadVisualElement.js +1 -1
  103. package/views/3d/layers/I3SMeshView3D.js +1 -1
  104. package/views/3d/layers/IntegratedMesh3DTilesLayerView3D.js +1 -1
  105. package/views/3d/layers/graphics/objectResourceUtils.js +1 -1
  106. package/views/3d/layers/i3s/I3SViewportQueries.js +1 -1
  107. package/views/3d/layers/i3s/PointCloudRenderer.js +1 -1
  108. package/views/3d/layers/support/FeatureTileMeasurements3D.js +1 -1
  109. package/views/3d/layers/support/FeatureTileVisibility3D.js +1 -1
  110. package/views/3d/state/Frustum.js +1 -1
  111. package/views/3d/state/controllers/FovController.js +1 -1
  112. package/views/3d/state/controllers/GamepadKeyboardController.js +1 -1
  113. package/views/3d/state/controllers/momentum/ZoomPlanarMomentumController.js +1 -1
  114. package/views/3d/state/helpers/SceneIntersectionHelper.js +1 -1
  115. package/views/3d/support/FrustumExtentIntersection.js +1 -1
  116. package/views/3d/support/cameraUtils.js +1 -1
  117. package/views/3d/support/intersectionUtils.js +1 -1
  118. package/views/3d/support/pointsOfInterest/CameraOnSurface.js +1 -1
  119. package/views/3d/support/pointsOfInterest/CenterOnSurface.js +1 -1
  120. package/views/3d/support/pointsOfInterest/Focus.js +1 -1
  121. package/views/3d/support/viewpointUtils.js +1 -1
  122. package/views/3d/terrain/OverlayManager.js +1 -1
  123. package/views/3d/terrain/PatchRenderData.js +1 -1
  124. package/views/3d/terrain/SphericalPatch.js +1 -1
  125. package/views/3d/terrain/Tile.js +1 -1
  126. package/views/3d/webgl/RenderCamera.js +1 -1
  127. package/views/3d/webgl-engine/collections/Component/ComponentObject.js +1 -1
  128. package/views/3d/webgl-engine/collections/Component/Material/ComponentData.glsl.js +63 -0
  129. package/views/3d/webgl-engine/collections/Component/Material/ComponentMaterial.js +1 -1
  130. package/views/3d/webgl-engine/collections/Component/Material/ComponentShader.glsl.js +5 -0
  131. package/views/3d/webgl-engine/collections/Component/Material/ComponentTechnique.js +1 -1
  132. package/views/3d/webgl-engine/collections/Component/Material/ComponentTechniqueConfiguration.js +1 -1
  133. package/views/3d/webgl-engine/collections/Component/Material/{shader/DecodeSymbolColor.glsl.js → DecodeSymbolColor.glsl.js} +1 -1
  134. package/views/3d/webgl-engine/core/shaderLibrary/Slice.glsl.js +1 -1
  135. package/views/3d/webgl-engine/core/shaderLibrary/TextureBackedBuffer.glsl.js +8 -8
  136. package/views/3d/webgl-engine/core/shaderLibrary/TextureBackedBufferFields.glsl.js +7 -12
  137. package/views/3d/webgl-engine/core/shaderModules/Texture2DUintDrawUniform.js +5 -0
  138. package/views/3d/webgl-engine/effects/haze/Haze.js +1 -1
  139. package/views/3d/webgl-engine/lib/GaussianSplatRenderNode.js +1 -1
  140. package/views/3d/webgl-engine/lib/Object3D.js +1 -1
  141. package/views/3d/webgl-engine/lib/ShadowAccumulator.js +1 -1
  142. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBuffer.js +1 -1
  143. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBufferFields.js +1 -1
  144. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBufferLayout.js +1 -1
  145. package/views/3d/webgl-engine/lib/Viewshed.js +1 -1
  146. package/views/3d/webgl-engine/lib/edgeRendering/EdgeView.js +1 -1
  147. package/views/3d/webgl-engine/lib/edgeRendering/bufferLayouts.js +1 -1
  148. package/views/3d/webgl-engine/lib/edgeRendering/edgePreprocessing.js +1 -1
  149. package/views/3d/webgl-engine/lib/geometryDataUtils.js +1 -1
  150. package/views/3d/webgl-engine/lib/triangleIntersectionUtils.js +1 -1
  151. package/views/3d/webgl-engine/materials/DefaultLayouts.js +1 -1
  152. package/views/3d/webgl-engine/materials/HUDMaterial.js +1 -1
  153. package/views/3d/webgl-engine/materials/LineMarkerMaterial.js +1 -1
  154. package/views/3d/webgl-engine/materials/MeasurementArrowMaterial.js +1 -1
  155. package/views/3d/webgl-engine/materials/NativeLineMaterial.js +1 -1
  156. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  157. package/views/3d/webgl-engine/materials/renderers/MergedBuffer.js +1 -1
  158. package/views/3d/webgl-engine/parts/RenderView.js +1 -1
  159. package/views/3d/webgl-engine/shaders/SphereDepthInterpolate.glsl.js +1 -1
  160. package/views/3d/webgl-engine/shaders/sources/edgeRenderer/EdgeUtil.glsl.js +18 -18
  161. package/views/Attribution.js +1 -1
  162. package/views/SelectionManager.js +1 -1
  163. package/views/draw/support/Reshape.js +1 -1
  164. package/views/interactive/GraphicManipulator.js +1 -1
  165. package/views/interactive/SegmentLabels.js +1 -1
  166. package/views/interactive/coordinateHelper.js +1 -1
  167. package/views/interactive/editGeometry/EditGeometry.js +1 -1
  168. package/views/interactive/editGeometry/EditGeometryOperations.js +1 -1
  169. package/views/interactive/editGeometry/operations/OffsetEdgeVertex.js +1 -1
  170. package/views/interactive/editGeometry/operations/SetAllVertexPositions.js +1 -1
  171. package/views/interactive/sketch/constraints.js +1 -1
  172. package/views/interactive/sketch/normalizedPoint.js +1 -1
  173. package/views/interactive/snapping/featureSources/sceneLayerSource/SceneLayerSnappingSourceWorker.js +1 -1
  174. package/views/interactive/snapping/featureSources/sceneLayerSource/sceneLayerSnappingUtils.js +1 -1
  175. package/views/interactive/snapping/hints/LineSnappingHint.js +1 -1
  176. package/views/interactive/tooltip/tooltipCommonUtils.js +1 -1
  177. package/views/navigation/PanSphericalMomentumEstimator.js +1 -1
  178. package/views/support/euclideanAreaMeasurementUtils.js +1 -1
  179. package/views/support/euclideanLengthMeasurementUtils.js +1 -1
  180. package/views/support/geometry3dUtils.js +1 -1
  181. package/views/support/selectionUtils.js +1 -1
  182. package/widgets/Attachments/AttachmentsViewModel.js +1 -1
  183. package/widgets/BuildingExplorer/BuildingExplorerViewModel.js +1 -1
  184. package/widgets/BuildingExplorer/BuildingNumericFilterViewModel.js +1 -1
  185. package/widgets/BuildingExplorer.js +1 -1
  186. package/widgets/Editor/EditorViewModel.js +1 -1
  187. package/widgets/Editor/UpdateFeatureWorkflow.js +1 -1
  188. package/widgets/Editor/Upload.js +1 -1
  189. package/widgets/Editor/components/Settings.js +1 -1
  190. package/widgets/Editor/support/SketchController.js +1 -1
  191. package/widgets/FeatureTable/FeatureTableViewModel.js +1 -1
  192. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  193. package/widgets/ShadowCast/DiscreteOptions.js +1 -1
  194. package/widgets/ShadowCast/DurationOptions.js +1 -1
  195. package/widgets/ShadowCast/ShadowCastViewModel.js +1 -1
  196. package/widgets/ShadowCast/ThresholdOptions.js +1 -1
  197. package/widgets/ShadowCast.js +1 -1
  198. package/widgets/Sketch/SketchViewModel.js +1 -1
  199. package/widgets/Sketch.js +1 -1
  200. package/widgets/support/SelectionList/SelectionListViewModel.js +1 -1
  201. package/widgets/support/SketchTooltipControls.js +1 -1
  202. package/assets/esri/core/workers/chunks/08957e462d06c4dc8ab5.js +0 -1
  203. package/assets/esri/core/workers/chunks/22d66d1c8dfccdbbcf30.js +0 -1
  204. package/assets/esri/core/workers/chunks/484cd728dd17b8dc1f72.js +0 -1
  205. package/assets/esri/core/workers/chunks/6c8f5a56e94fdbe6a4a5.js +0 -1
  206. package/assets/esri/core/workers/chunks/745fc2b89fd7d816f2e0.js +0 -1
  207. package/assets/esri/core/workers/chunks/79c7391f00a55e7bcf6b.js +0 -1
  208. package/assets/esri/core/workers/chunks/7f8b85de079614b9c336.js +0 -1
  209. package/assets/esri/core/workers/chunks/c2596f48b37092dd566c.js +0 -1
  210. package/assets/esri/core/workers/chunks/c6cc3db057da49755d15.js +0 -1
  211. package/assets/esri/core/workers/chunks/d6d03f22c91f528b97e5.js +0 -1
  212. package/assets/esri/core/workers/chunks/ea5bf896acfcc3106bf5.js +0 -1
  213. package/assets/esri/core/workers/chunks/f3127bdf28a1d9b8db27.js +0 -1
  214. package/chunks/geometryEngineJSON.js +0 -5
  215. package/geometry/geometryEngineAsync.d.ts +0 -39
  216. package/geometry/geometryEngineAsync.js +0 -5
  217. package/geometry/geometryEngineWorker.js +0 -5
  218. package/views/3d/webgl-engine/collections/Component/Material/shader/ComponentData.glsl.js +0 -57
  219. package/views/3d/webgl-engine/collections/Component/Material/shader/ComponentDataConstants.js +0 -5
  220. package/views/3d/webgl-engine/collections/Component/Material/shader/ComponentShader.glsl.js +0 -5
package/intl/locale.js CHANGED
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{makeHandle as n}from"../core/handleUtils.js";import"../core/has.js";let e,t;const o=globalThis.esriConfig?.locale??globalThis.dojoConfig?.locale,a=globalThis.document?.documentElement;function r(){const n=a?.getAttribute("lang"),e=globalThis.navigator?.language;return o??n??e??"en"}function l(){return void 0===t&&(t=r()),t}function i(n){e=n||void 0,x()}const c=/^(?<language>[a-z]{2,3})(?:-(?<extlang>[a-z]{3}))?(?:-[A-Z][a-z]{3})?(?:-(?<region>[A-Z]{2}|\d{3}))?(?:-.*)?$/;function s(n=l()){return g(n)?.language}function u(n=l()){const e=g(n);return e?.language&&e?.extlang?n.replace(`${e.language}-`,""):n}function g(n=l()){return c.exec(n)?.groups}function f(n=l()){const e=g(n)?.language;return"he"===e||"ar"===e}const h=[],d=new Map;function p(){const n=Array.from(d.values())[0];d.clear();const e=h.length;if(0!==e)throw h.length=0,new Error(`Unexpected ${e} locale change listeners still active.${n?` For example:\n${n}`:" Set enableListenerTracing in esri/intl/locale.ts to include a stack trace."}`)}function b(e){return h.push(e),n(()=>{h.splice(h.indexOf(e),1)})}const m=[];function v(e){return m.push(e),n(()=>m.splice(m.indexOf(e),1))}function x(){const n=e??r();t!==n&&([...m].forEach(e=>e(n)),t=n,[...h].forEach(e=>e(n)))}if(globalThis.addEventListener?.("languagechange",x),a){new MutationObserver(()=>{x()}).observe(a,{attributeFilter:["lang"]})}export{p as assertNoLocaleChangeListeners,v as beforeLocaleChange,r as getDefaultLocale,l as getLocale,s as getLocaleLanguage,g as getLocaleParts,u as normalizeLocale,b as onLocaleChange,f as prefersRTL,i as setLocale};
5
+ import{makeHandle as n}from"../core/handleUtils.js";import"../core/has.js";let e,t;const a=globalThis.esriConfig?.locale,o=globalThis.document?.documentElement;function r(){const n=o?.getAttribute("lang"),e=globalThis.navigator?.language;return a??n??e??"en"}function i(){return void 0===t&&(t=r()),t}function l(n){e=n||void 0,x()}const c=/^(?<language>[a-z]{2,3})(?:-(?<extlang>[a-z]{3}))?(?:-[A-Z][a-z]{3})?(?:-(?<region>[A-Z]{2}|\d{3}))?(?:-.*)?$/;function u(n=i()){return g(n)?.language}function s(n=i()){const e=g(n);return e?.language&&e?.extlang?n.replace(`${e.language}-`,""):n}function g(n=i()){return c.exec(n)?.groups}function f(n=i()){const e=g(n)?.language;return"he"===e||"ar"===e}const h=[],d=new Map;function p(){const n=Array.from(d.values())[0];d.clear();const e=h.length;if(0!==e)throw h.length=0,new Error(`Unexpected ${e} locale change listeners still active.${n?` For example:\n${n}`:" Set enableListenerTracing in esri/intl/locale.ts to include a stack trace."}`)}function b(e){return h.push(e),n(()=>{h.splice(h.indexOf(e),1)})}const m=[];function v(e){return m.push(e),n(()=>m.splice(m.indexOf(e),1))}function x(){const n=e??r();t!==n&&([...m].forEach(e=>e(n)),t=n,[...h].forEach(e=>e(n)))}if(globalThis.addEventListener?.("languagechange",x),o){new MutationObserver(()=>{x()}).observe(o,{attributeFilter:["lang"]})}export{p as assertNoLocaleChangeListeners,v as beforeLocaleChange,r as getDefaultLocale,i as getLocale,u as getLocaleLanguage,g as getLocaleParts,s as normalizeLocale,b as onLocaleChange,f as prefersRTL,l as setLocale};
package/kernel.js CHANGED
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import has from"./core/has.js";import{addQueryParameter as o}from"./core/urlUtils.js";export{buildDate,commitHash as revision}from"./support/revision.js";Symbol.dispose??=Symbol("Symbol.dispose"),Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");const e="5.0";let s,r=e;function i(o){s=o}function t(e){const r=s?.findCredential(e);return r?.token?o(e,"token",r.token):e}r="5.0.0-next.33",has("host-webworker")||globalThis.$arcgis||Object.defineProperty(globalThis,"$arcgis",{configurable:!1,enumerable:!0,writable:!1,value:{}}),has("host-webworker");export{t as addTokenParameter,r as fullVersion,s as id,i as setId,e as version};
5
+ import has from"./core/has.js";import{addQueryParameter as o}from"./core/urlUtils.js";export{buildDate,commitHash as revision}from"./support/revision.js";Symbol.dispose??=Symbol("Symbol.dispose"),Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");const e="5.0";let s,r=e;function i(o){s=o}function t(e){const r=s?.findCredential(e);return r?.token?o(e,"token",r.token):e}r="5.0.0-next.35",has("host-webworker")||globalThis.$arcgis||Object.defineProperty(globalThis,"$arcgis",{configurable:!1,enumerable:!0,writable:!1,value:{}}),has("host-webworker");export{t as addTokenParameter,r as fullVersion,s as id,i as setId,e as version};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../request.js";import i from"../core/Accessor.js";import s from"../core/Logger.js";import{isAbortError as r}from"../core/promiseUtils.js";import{watch as a}from"../core/reactiveUtils.js";import{addFrameTask as n}from"../core/scheduling.js";import{property as o,subclass as l}from"../core/accessorSupport/decorators.js";import{isGeographic as d}from"../geometry/support/spatialReferenceUtils.js";import h from"../geometry/support/WKIDUnitConversion.js";import{wasmFailedToInit as _,invalidLayerView as u}from"./ILyr3DWasmPerSceneView.js";import{Lyr3DWorkerHandle as y}from"./Lyr3DWorkerHandle.js";import{loadLyr3DMainWASM as c}from"../libs/lyr3d/Lyr3DModule.js";import{getElevationOffsetInMeters as g}from"../support/elevationInfoUtils.js";import{makeScheduleFunction as m}from"../views/3d/layers/support/makeScheduleFunction.js";const w=3857,b=32662,p=4326,f=5773,L=115700;let M=class extends i{constructor(e){super(e),this._lyr3DMainPromise=null,this._lyr3DMain=null,this._layers=new Map,this._viewSR=null,this._lyr3DBusyCount=0,this._debugFlags=new Set,this._debugLevel=2,this._wasmNotLoaded="method requiring WASM was called when WASM isn't loaded",this._pulseTaskHandle=null,this._debugFlags.add(0),this._debugFlags.add(1),this._debugFlags.add(2)}_debugLog(e,t,i,r=!0){if(this._debugFlags.has(e)&&this._debugLevel>=t){const e=r?`[js] ${i}`:`${i}`;0===t||1===t?s.getLogger(this).error(e):2===t&&s.getLogger(this).warn(e),s.getLogger(this).info(e)}}initialize(){this._debugLevel>2&&(s.getLogger(this).level="info"),this._debugLog(0,3,"Lyr3DWasmPerSceneView.initialize()"),this.addHandles([a(()=>this.view.state?.contentCamera,()=>this._updateWasmCamera())]),this._pulseTaskHandle=n({preRender:()=>this._pulseTask()})}destroy(){this._debugLog(0,3,"Lyr3DWasmPerSceneView.destroy()"),this._lyr3DMain&&(this._layers.forEach(e=>{e.abortController.abort()}),this._lyr3DMain.uninitialize_lyr3d_wasm(),this._lyr3DMain=null);const e=this._workerHandle;e&&e.destroyWasm().then(()=>{this._workerHandle?.destroy(),this._workerHandle=null}),this._pulseTaskHandle?.remove(),this._pulseTaskHandle=null}addLayerView(e){return this._lyr3DMain?this._addLayerView(e):(this._debugLog(0,1,"Lyr3DWasmPerSceneView.add3DTilesLayerView() called when WASM wasn't initialized"),{wasmLayerId:_})}removeLayerView(e){if(!this._lyr3DMain)return this._debugLog(0,1,this._wasmNotLoaded),0;this._doRemoveLayerView(e);const t=this._layers.size;return 0===t&&(this._debugLog(0,3,"Lyr3DWasmPerSceneView.remove3DTilesLayerView() no Lyr3D layers left after removing a layer, destroying"),this.destroy()),t}getValidLayerViewCount(){if(!this._lyr3DMain)return this._debugLog(0,1,this._wasmNotLoaded),0;let e=0;return this._layers.forEach(t=>{t.layerView.wasmLayerId>=0&&++e}),e}setEnabled(e,t){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);const i=this._layers.get(e.wasmLayerId);if(i){this._lyr3DMain.set_enabled(e.wasmLayerId,t),i.needMemoryUsageUpdate=!0;const s=this._isUpdating(i);i.needFrame=!0,s||i.layerView.updatingFlagChanged()}}setLayerOffset(e,t){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);this._layers.get(e.wasmLayerId)&&this._lyr3DMain.set_carto_offset_z(e.wasmLayerId,t)}getAttributionText(){if(!this._lyr3DMain)return this._debugLog(0,1,this._wasmNotLoaded),[];return this._lyr3DMain.get_current_attribution_text().split("|")}onRenderableEvicted(e,t,i){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);this._layers.get(e.wasmLayerId)&&this._lyr3DMain.on_renderable_evicted(e.wasmLayerId,t,i)}setMeshModifications(e,t,i){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);const s=this._layers.get(e.wasmLayerId);if(s){const r=this._lyr3DMain._malloc(8*t.length),a=new Float64Array(this._lyr3DMain.HEAPF64.buffer,r,t.length);for(let e=0;e<t.length;++e)a[e]=t[e];this._lyr3DMain.set_mesh_modification_polygons(e.wasmLayerId,r,t.length,i),this._lyr3DMain._free(r);const n=this._isUpdating(s);s.needFrame=!0,n||s.layerView.updatingFlagChanged()}}isUpdating(e){if(!this._lyr3DMain&&this._lyr3DMainPromise)return!0;const t=this._layers.get(e);return!!t&&(t.outstandingJobCount>0||t.outstandingRenderableCount>0||t.needFrame||this._lyr3DBusyCount>0)}initializeWasm(e,t){return this._lyr3DMain?Promise.resolve():this.view.renderSpatialReference?(this._debugLog(0,3,"Lyr3DWasmPerSceneView.initializeWasm()"),this._lyr3DMainPromise||(this._lyr3DMainPromise=c().then(i=>{this._lyr3DMain=i,this._lyr3DMainPromise=null;const s=this._lyr3DMain.addFunction(this._onNewJob.bind(this),"v"),r=this._lyr3DMain.addFunction(this._onNewRenderable.bind(this),"v"),a=this._lyr3DMain.addFunction(this._freeRenderables.bind(this),"viii"),n=this._lyr3DMain.addFunction(this._setRenderableVisibility.bind(this),"viiii"),o=this._lyr3DMain.addFunction(this._onWasmError.bind(this),"viiii");if(!this.view.renderSpatialReference)return void(this._lyr3DMain=null);this._viewSR=this.view.renderSpatialReference?.toJSON();const l="global"===this.view.viewingMode?5:3;if(5===l)this._viewSR.wkid=this._viewSR.latestWkid=p,this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=f;else if(this.view.renderSpatialReference?.isWebMercator)this._viewSR.wkid=this._viewSR.latestWkid=w,this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=f;else if(this.view.renderSpatialReference?.wkid===b)this._viewSR.wkid=this._viewSR.latestWkid=p,this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=f;else if(!this._viewSR.latestVcsWkid&&!this._viewSR.vcsWkid){const e=this.view.heightModelInfo?.heightModel,t=!e||"gravity-related-height"===e;this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=t?f:L}return this._lyr3DMain.initialize_lyr3d_wasm(o,s,r,a,n,e,t,l,this._cleanUpSR(this._makeSRWasmSerializable(this._viewSR)),Math.max(this._debugLevel,0))?(this._workerHandle=new y(m(this.view.resourceController)),this._workerHandle.promise?this._workerHandle.promise:void 0):(this._lyr3DMain=null,void this._debugLog(0,0,"Lyr3d Main WASM failed to initialize",!1))}).catch(e=>{this._debugLog(0,0,`Lyr3d WASM failed to download error = ${e}`,!1)})),this._lyr3DMainPromise):Promise.reject()}setLodPixelThreshold(e,t){this._lyr3DMain?.set_lod_pixel_threshold(t);const i=this._layers.get(e.wasmLayerId);i&&(i.needFrame=!0)}_pulseTask(){if(this._lyr3DMain){let e=0,t=0;this._layers.forEach(i=>{e+=i.layerView.usedMemory,t+=i.layerView.cachedMemory}),e/=1048576,t/=1048576;const i=this.view.resourceController.memoryController,s=i.usedMemory*i.maxMemory-e;this._lyr3DBusyCount=this._lyr3DMain.frame_pulse(i.memoryFactor,e,t,s,i.maxMemory),this._layers.forEach(e=>{e.needFrame=!1,e.layerView.updatingFlagChanged()})}}_isUpdating(e){return e.outstandingJobCount>0||e.outstandingRenderableCount>0||e.needFrame||this._lyr3DBusyCount>0}_incrementJobCount(e){const t=this._isUpdating(e);e.outstandingJobCount+=1,t||e.layerView.updatingFlagChanged()}_decrementJobCount(e){const t=this._isUpdating(e);e.outstandingJobCount-=1;t!==this._isUpdating(e)&&e.layerView.updatingFlagChanged()}_incrementRenderableCount(e){const t=this._isUpdating(e);e.outstandingRenderableCount+=1,t||e.layerView.updatingFlagChanged()}_decrementRenderableCount(e){const t=this._isUpdating(e);e.outstandingRenderableCount-=1;t!==this._isUpdating(e)&&e.layerView.updatingFlagChanged()}_onJobFailed(e,t,i){t.error.length&&this._debugLog(1,1,t.error,!1),this._lyr3DMain&&this._lyr3DMain.on_job_failed(i.jobId,i.desc),this._decrementJobCount(e)}_onJobSucceeded(e,t,i){if(this._lyr3DMain){const e=t.data.byteLength,s=this._lyr3DMain._malloc(e);new Uint8Array(this._lyr3DMain.HEAPU8.buffer,s,e).set(t.data),this._lyr3DMain.on_job_completed(i.jobId,t.jobDescJson,s,e),this._lyr3DMain._free(s)}this._decrementJobCount(e)}_getRequestPromises(e,i,s,r){const a=[];for(const n of e){const e=new URL(n);if("integrated-mesh-3dtiles"===r.type){if(e.origin===s.origin&&e.pathname===s.pathname){if(r.rootTileset){a.push(Promise.resolve(r.rootTileset.slice()));continue}}else r.session&&e.searchParams.append("session",r.session)}a.push(t(e.toString(),i).then(e=>e.data))}return a}_getInitialPromise(e,t,i,s,a,n,o){const l=this._getRequestPromises(e.urls,t,i,s);return Promise.all(l).then(e=>(a.inputs=e,this._workerHandle.invoke(a,n))).then(e=>e).catch(t=>{let i=1;return r(t)?this._debugLog(1,2,`job ${e.jobId} was cancelled.`):o&&400===t.details?.httpStatus?(i=3,this._debugLog(1,2,"Session expired, trying to create new Session.")):this._debugLog(1,1,`job ${e.jobId} failed with error ${t}.`),{status:i,error:"",jobDescJson:"",data:new Uint8Array(0),missingInputUrls:[],inputs:[]}})}async _onNewJob(){const e=this._lyr3DMain.get_next_job(),t=this._layers.get(e.layerId);if(!t)return;this._incrementJobCount(t);const i=t.abortController.signal,s=t.layerView.layer,a="integrated-mesh-3dtiles"===s.type?s.key:null,n="integrated-mesh-3dtiles"===s.type?s.session:null,o={responseType:"array-buffer",signal:i,query:{...t.customParameters,token:t.apiKey,key:a}},l={id:e.jobId,inputs:[],jobDescJson:e.desc.slice(),isMissingResourceCase:!1},d=new URL(s.url),h=a=>{if(1===a.status)this._onJobFailed(t,a,e);else if(0===a.status)this._onJobSucceeded(t,a,e);else if(2===a.status){const n=this._getRequestPromises(a.missingInputUrls,o,d,s);Promise.all(n).then(e=>{l.jobDescJson=a.jobDescJson,a.originalInputs?l.inputs=a.originalInputs:l.inputs=[],l.isMissingResourceCase=!0;for(const t of e)l.inputs.push(t);return this._workerHandle.invoke(l,i)}).then(i=>{1===i.status?this._onJobFailed(t,i,e):0===i.status&&this._onJobSucceeded(t,i,e)}).catch(i=>{this._decrementJobCount(t),r(i)?this._debugLog(1,2,`job ${e.jobId} was cancelled.`):this._debugLog(1,1,`job ${e.jobId} failed with error2 ${i}.`),this._lyr3DMain&&this._lyr3DMain.on_job_failed(e.jobId,e.desc)})}};try{const t=await this._getInitialPromise(e,o,d,s,l,i,n);if(3===t.status&&"integrated-mesh-3dtiles"===s.type){n===s.session&&null!==s.session&&await s.requestRootAndSession(i);h(await this._getInitialPromise(e,o,d,s,l,i,s.session))}else h(t)}catch(_){_&&this._debugLog(1,1,_.toString(),!1),this._lyr3DMain&&this._lyr3DMain.on_job_failed(e.jobId,e.desc),this._decrementJobCount(t)}}_onNewRenderable(){const e=this._lyr3DMain.get_next_renderable(),{meshData:t}=e;if(t.data&&t.data.byteLength>0){const e=t.data.slice();t.data=e}const i=this._layers.get(e.layerId);i&&(this._incrementRenderableCount(i),i.layerView.createRenderable(e).then(t=>{this._lyr3DMain?.on_renderable_created(!0,e.layerId,e.handle,t.memUsageBytes),this._decrementRenderableCount(i)}).catch(t=>{r(t)||this._debugLog(2,1,`createRenderable failed with error ${t}.`),this._lyr3DMain?.on_renderable_created(!1,e.layerId,e.handle,0),this._decrementRenderableCount(i)}))}_freeRenderables(e,t,i){if(i<1)return;const s=this._layers.get(e);if(!s)return;const r=s.layerView,a=[],n=new Uint32Array(this._lyr3DMain.HEAPU32.buffer,t,i);for(let o=0;o<i;++o)a.push(n[o]);for(let o=0;o<i;++o)r.freeRenderable(a[o])}_setRenderableVisibility(e,t,i,s){if(s<1)return;const r=this._layers.get(e);if(!r)return;const a=r.layerView,n=[],o=[],l=new Uint32Array(this._lyr3DMain.HEAPU32.buffer,t,s),d=new Uint8Array(this._lyr3DMain.HEAPU8.buffer,i,s);for(let h=0;h<s;++h)n.push(l[h]),o.push(1===d[h]);a.setRenderableVisibility(n,o,s)}_onWasmError(e,t,i,s){this._lyr3DMain&&this._debugLog(i,s,this._lyr3DMain.UTF8ToString(e,t),!1)}_doRemoveLayerView(e){const t=this._layers.get(e.wasmLayerId);return!!t&&(t.abortController.abort(),this._lyr3DMain.remove_layer(e.wasmLayerId),this._layers.delete(e.wasmLayerId),!0)}_isGaussianSplatLayerView(e){return"gaussian-splat"===e.layer.type}_isGaussianSplatLayer(e){return"gaussian-splat"===e.type}_toWasmQuality(e){switch(e){case"low":return 1;case"medium":return 2;case"high":return 3}}_addLayerView(e){const t=e.layer;if(!t.url||!t.rootTilesetJSON)return{wasmLayerId:u};const i="integrated-mesh-3dtiles"===t.type?0:2,r=this._lyr3DMain.validate_root_tileset(JSON.stringify(t.rootTilesetJSON),i);if(0!==r.errorCode)return{wasmLayerId:u,check:r};const a=this._lyr3DMain.get_next_layer_id(),n=new AbortController;this._layers.set(a,{layerView:e,abortController:n,needMemoryUsageUpdate:!1,outstandingJobCount:0,outstandingRenderableCount:0,customParameters:t.customParameters,apiKey:t.apiKey,needFrame:!0});const o=g(t.elevationInfo),l=this._toWasmQuality(this.view?.qualityProfile),_=e=>s.getLogger(this).error("add-spatial-reference-error","Error when adding SR:",e);let y=!1;if(this._isGaussianSplatLayerView(e)&&this._isGaussianSplatLayer(t)){let i=t.spatialReference;if(e.useEsriCrs&&t.esriCrsSpatialReference){i=t.esriCrsSpatialReference;const s=d(i);let r=1,a=1;!s&&i.wkid&&-1!==i.wkid&&(r=h.values[h[i.wkid]],a=e.metersPerVCSUnit),this._workerHandle.addSpatialReferenceInfo(this._cleanUpSR(this._makeSRWasmSerializable(i)),s,r,a).catch(_)}y=this._lyr3DMain.add_gaussian_splat_layer(l,t.url,a,o)}else y=this._lyr3DMain.add_3dtiles_layer(l,t.url,a,o);return y?(this._updateWasmCamera(),e.updatingFlagChanged(),{wasmLayerId:a}):(this._layers.delete(a),{wasmLayerId:u})}_updateWasmCamera(){const e=this.view.state?.contentCamera;if(!e||!this._lyr3DMain)return;const{eye:t,center:i,up:s,near:r,far:a,fovY:n}=e,o=[e.viewport[2],e.viewport[3]],l=e.width/e.height;this._lyr3DMain.set_camera_parameters({eye:t,center:i,up:s,near:r,far:a,fov:n,aspectRatio:l,viewport:o}),this._layers.forEach(e=>{const t=this._isUpdating(e);e.needFrame=!0,t||e.layerView.updatingFlagChanged()})}_makeSRWasmSerializable(e){return{wkid:e?.wkid??-1,latestWkid:e?.latestWkid??-1,vcsWkid:e?.vcsWkid??-1,latestVcsWkid:e?.latestVcsWkid??-1,wkt:e?.wkt??""}}_cleanUpSR(e){return-1===e?.wkid&&e.latestWkid&&-1!==e.latestWkid?e.wkid=e.latestWkid:-1===e?.latestWkid&&e.wkid&&-1!==e.wkid&&(e.latestWkid=e.wkid),-1===e?.vcsWkid&&e.latestVcsWkid&&-1!==e.latestVcsWkid?e.vcsWkid=e.latestVcsWkid:-1===e?.latestVcsWkid&&e.vcsWkid&&-1!==e.vcsWkid&&(e.latestVcsWkid=e.vcsWkid),e}};e([o({constructOnly:!0})],M.prototype,"view",void 0),M=e([l("esri.layers.Lyr3DWasmPerSceneView")],M);const D=M;export{D as default};
5
+ import{__decorate as e}from"tslib";import t from"../request.js";import i from"../core/Accessor.js";import s from"../core/Logger.js";import{isAbortError as r}from"../core/promiseUtils.js";import{watch as a}from"../core/reactiveUtils.js";import{addFrameTask as n}from"../core/scheduling.js";import{property as o,subclass as l}from"../core/accessorSupport/decorators.js";import{clone as d}from"../core/libs/gl-matrix-2/factories/vec3f64.js";import{B as h}from"../chunks/vec32.js";import{canProjectWithoutEngine as _}from"../geometry/projectionUtils.js";import{projectBuffer as u}from"../geometry/projection/projectBuffer.js";import{containsXY as y}from"../geometry/support/aaBoundingRect.js";import{earth as c}from"../geometry/support/Ellipsoid.js";import{isGeographic as g}from"../geometry/support/spatialReferenceUtils.js";import m from"../geometry/support/WKIDUnitConversion.js";import{wasmFailedToInit as w,invalidLayerView as p}from"./ILyr3DWasmPerSceneView.js";import{Lyr3DWorkerHandle as f}from"./Lyr3DWorkerHandle.js";import{loadLyr3DMainWASM as b}from"../libs/lyr3d/Lyr3DModule.js";import{getElevationOffsetInMeters as v}from"../support/elevationInfoUtils.js";import{makeScheduleFunction as M}from"../views/3d/layers/support/makeScheduleFunction.js";const D=3857,L=32662,k=4326,R=5773,S=115700;let C=class extends i{constructor(e){super(e),this._lyr3DMainPromise=null,this._lyr3DMain=null,this._layers=new Map,this._viewSR=null,this._lyr3DBusyCount=0,this._updateCameraElevation=0,this._debugFlags=new Set,this._debugLevel=2,this._wasmNotLoaded="method requiring WASM was called when WASM isn't loaded",this._pulseTaskHandle=null,this._debugFlags.add(0),this._debugFlags.add(1),this._debugFlags.add(2)}_debugLog(e,t,i,r=!0){if(this._debugFlags.has(e)&&this._debugLevel>=t){const e=r?`[js] ${i}`:`${i}`;0===t||1===t?s.getLogger(this).error(e):2===t&&s.getLogger(this).warn(e),s.getLogger(this).info(e)}}initialize(){this._debugLevel>2&&(s.getLogger(this).level="info"),this._debugLog(0,3,"Lyr3DWasmPerSceneView.initialize()"),this.addHandles([this._createElevationUpdateHandle(),a(()=>this.view.state?.contentCamera,()=>this._updateWasmCamera())]),this._pulseTaskHandle=n({preRender:()=>this._pulseTask()})}destroy(){this._debugLog(0,3,"Lyr3DWasmPerSceneView.destroy()"),this._lyr3DMain&&(this._layers.forEach(e=>{e.abortController.abort()}),this._lyr3DMain.uninitialize_lyr3d_wasm(),this._lyr3DMain=null);const e=this._workerHandle;e&&e.destroyWasm().then(()=>{this._workerHandle?.destroy(),this._workerHandle=null}),this._pulseTaskHandle?.remove(),this._pulseTaskHandle=null}addLayerView(e){return this._lyr3DMain?this._addLayerView(e):(this._debugLog(0,1,"Lyr3DWasmPerSceneView.add3DTilesLayerView() called when WASM wasn't initialized"),{wasmLayerId:w})}removeLayerView(e){if(!this._lyr3DMain)return this._debugLog(0,1,this._wasmNotLoaded),0;this._doRemoveLayerView(e);const t=this._layers.size;return 0===t&&(this._debugLog(0,3,"Lyr3DWasmPerSceneView.remove3DTilesLayerView() no Lyr3D layers left after removing a layer, destroying"),this.destroy()),t}getValidLayerViewCount(){if(!this._lyr3DMain)return this._debugLog(0,1,this._wasmNotLoaded),0;let e=0;return this._layers.forEach(t=>{t.layerView.wasmLayerId>=0&&++e}),e}setEnabled(e,t){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);const i=this._layers.get(e.wasmLayerId);if(i){this._lyr3DMain.set_enabled(e.wasmLayerId,t),i.needMemoryUsageUpdate=!0;const s=this._isUpdating(i);i.needFrame=!0,s||i.layerView.updatingFlagChanged()}}setLayerOffset(e,t){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);this._layers.get(e.wasmLayerId)&&this._lyr3DMain.set_carto_offset_z(e.wasmLayerId,t)}getAttributionText(){if(!this._lyr3DMain)return this._debugLog(0,1,this._wasmNotLoaded),[];return this._lyr3DMain.get_current_attribution_text().split("|")}onRenderableEvicted(e,t,i){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);this._layers.get(e.wasmLayerId)&&this._lyr3DMain.on_renderable_evicted(e.wasmLayerId,t,i)}setMeshModifications(e,t,i){if(!this._lyr3DMain)return void this._debugLog(0,1,this._wasmNotLoaded);const s=this._layers.get(e.wasmLayerId);if(s){const r=this._lyr3DMain._malloc(8*t.length),a=new Float64Array(this._lyr3DMain.HEAPF64.buffer,r,t.length);for(let e=0;e<t.length;++e)a[e]=t[e];this._lyr3DMain.set_mesh_modification_polygons(e.wasmLayerId,r,t.length,i),this._lyr3DMain._free(r);const n=this._isUpdating(s);s.needFrame=!0,n||s.layerView.updatingFlagChanged()}}isUpdating(e){if(!this._lyr3DMain&&this._lyr3DMainPromise)return!0;const t=this._layers.get(e);return!!t&&(t.outstandingJobCount>0||t.outstandingRenderableCount>0||t.needFrame||this._lyr3DBusyCount>0)}initializeWasm(e,t){return this._lyr3DMain?Promise.resolve():this.view.renderSpatialReference?(this._debugLog(0,3,"Lyr3DWasmPerSceneView.initializeWasm()"),this._lyr3DMainPromise||(this._lyr3DMainPromise=b().then(i=>{this._lyr3DMain=i,this._lyr3DMainPromise=null;const s=this._lyr3DMain.addFunction(this._onNewJob.bind(this),"v"),r=this._lyr3DMain.addFunction(this._onNewRenderable.bind(this),"v"),a=this._lyr3DMain.addFunction(this._freeRenderables.bind(this),"viii"),n=this._lyr3DMain.addFunction(this._setRenderableVisibility.bind(this),"viiii"),o=this._lyr3DMain.addFunction(this._onWasmError.bind(this),"viiii");if(!this.view.renderSpatialReference)return void(this._lyr3DMain=null);this._viewSR=this.view.renderSpatialReference?.toJSON();const l="global"===this.view.viewingMode?5:3;if(5===l)this._viewSR.wkid=this._viewSR.latestWkid=k,this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=R;else if(this.view.renderSpatialReference?.isWebMercator)this._viewSR.wkid=this._viewSR.latestWkid=D,this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=R;else if(this.view.renderSpatialReference?.wkid===L)this._viewSR.wkid=this._viewSR.latestWkid=k,this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=R;else if(!this._viewSR.latestVcsWkid&&!this._viewSR.vcsWkid){const e=this.view.heightModelInfo?.heightModel,t=!e||"gravity-related-height"===e;this._viewSR.vcsWkid=this._viewSR.latestVcsWkid=t?R:S}return this._lyr3DMain.initialize_lyr3d_wasm(o,s,r,a,n,e,t,l,this._cleanUpSR(this._makeSRWasmSerializable(this._viewSR)),Math.max(this._debugLevel,0))?(this._workerHandle=new f(M(this.view.resourceController)),this._workerHandle.promise?this._workerHandle.promise:void 0):(this._lyr3DMain=null,void this._debugLog(0,0,"Lyr3d Main WASM failed to initialize",!1))}).catch(e=>{this._debugLog(0,0,`Lyr3d WASM failed to download error = ${e}`,!1)})),this._lyr3DMainPromise):Promise.reject()}setLodPixelThreshold(e,t){this._lyr3DMain?.set_lod_pixel_threshold(t);const i=this._layers.get(e.wasmLayerId);i&&(i.needFrame=!0)}_pulseTask(){if(this._lyr3DMain){if(this._updateCameraElevation>0){let e=null;const t=this.view.state?.contentCamera;if(t&&this.view.renderSpatialReference){const{eye:i}=t,s=this.view.groundView.getElevation(i[0],i[1],i[2],this.view.renderSpatialReference);if(s){const t=h(i);e="global"===this.view.viewingMode?t-(c.radius+s):i[2]-s}}e?(this._lyr3DMain.set_camera_altitude(e),this._updateCameraElevation=0):(this._updateCameraElevation-=1,this._updateCameraElevation<=0&&(this._lyr3DMain.set_camera_altitude(0),this._updateCameraElevation=0))}let e=0,t=0;this._layers.forEach(i=>{e+=i.layerView.usedMemory,t+=i.layerView.cachedMemory}),e/=1048576,t/=1048576;const i=this.view.resourceController.memoryController,s=i.usedMemory*i.maxMemory-e;this._lyr3DBusyCount=this._lyr3DMain.frame_pulse(i.memoryFactor,e,t,s,i.maxMemory),this._layers.forEach(e=>{0===this._updateCameraElevation&&(e.needFrame=!1),e.layerView.updatingFlagChanged()})}}_isUpdating(e){return e.outstandingJobCount>0||e.outstandingRenderableCount>0||e.needFrame||this._lyr3DBusyCount>0}_incrementJobCount(e){const t=this._isUpdating(e);e.outstandingJobCount+=1,t||e.layerView.updatingFlagChanged()}_decrementJobCount(e){const t=this._isUpdating(e);e.outstandingJobCount-=1;t!==this._isUpdating(e)&&e.layerView.updatingFlagChanged()}_incrementRenderableCount(e){const t=this._isUpdating(e);e.outstandingRenderableCount+=1,t||e.layerView.updatingFlagChanged()}_decrementRenderableCount(e){const t=this._isUpdating(e);e.outstandingRenderableCount-=1;t!==this._isUpdating(e)&&e.layerView.updatingFlagChanged()}_onJobFailed(e,t,i){t.error.length&&this._debugLog(1,1,t.error,!1),this._lyr3DMain&&this._lyr3DMain.on_job_failed(i.jobId,i.desc),this._decrementJobCount(e)}_onJobSucceeded(e,t,i){if(this._lyr3DMain){if(e.layerView.destroyed)return void this._lyr3DMain.on_job_failed(i.jobId,i.desc);const s=t.data.byteLength,r=this._lyr3DMain._malloc(s);new Uint8Array(this._lyr3DMain.HEAPU8.buffer,r,s).set(t.data),this._lyr3DMain.on_job_completed(i.jobId,t.jobDescJson,r,s),this._lyr3DMain._free(r)}this._decrementJobCount(e)}_getRequestPromises(e,i,s,r){const a=[];for(const n of e){const e=new URL(n);if("integrated-mesh-3dtiles"===r.type){if(e.origin===s.origin&&e.pathname===s.pathname){if(r.rootTileset){a.push(Promise.resolve(r.rootTileset.slice()));continue}}else r.session&&e.searchParams.append("session",r.session)}a.push(t(e.toString(),i).then(e=>e.data))}return a}_getInitialPromise(e,t,i,s,a,n,o){const l=this._getRequestPromises(e.urls,t,i,s);return Promise.all(l).then(e=>(a.inputs=e,this._workerHandle.invoke(a,n))).then(e=>e).catch(t=>{let i=1;return r(t)?this._debugLog(1,2,`job ${e.jobId} was cancelled.`):o&&400===t.details?.httpStatus?(i=3,this._debugLog(1,2,"Session expired, trying to create new Session.")):this._debugLog(1,1,`job ${e.jobId} failed with error ${t}.`),{status:i,error:"",jobDescJson:"",data:new Uint8Array(0),missingInputUrls:[],inputs:[]}})}async _onNewJob(){const e=this._lyr3DMain.get_next_job(),t=this._layers.get(e.layerId);if(!t)return;this._incrementJobCount(t);const i=t.abortController.signal,s=t.layerView.layer,a="integrated-mesh-3dtiles"===s.type?s.key:null,n="integrated-mesh-3dtiles"===s.type?s.session:null,o={responseType:"array-buffer",signal:i,query:{...t.customParameters,token:t.apiKey,key:a}},l={id:e.jobId,inputs:[],jobDescJson:e.desc.slice(),isMissingResourceCase:!1},d=new URL(s.url),h=a=>{if(1===a.status)this._onJobFailed(t,a,e);else if(0===a.status)this._onJobSucceeded(t,a,e);else if(2===a.status){const n=this._getRequestPromises(a.missingInputUrls,o,d,s);Promise.all(n).then(e=>{l.jobDescJson=a.jobDescJson,a.originalInputs?l.inputs=a.originalInputs:l.inputs=[],l.isMissingResourceCase=!0;for(const t of e)l.inputs.push(t);return this._workerHandle.invoke(l,i)}).then(i=>{1===i.status?this._onJobFailed(t,i,e):0===i.status&&this._onJobSucceeded(t,i,e)}).catch(i=>{this._decrementJobCount(t),r(i)?this._debugLog(1,2,`job ${e.jobId} was cancelled.`):this._debugLog(1,1,`job ${e.jobId} failed with error2 ${i}.`),this._lyr3DMain&&this._lyr3DMain.on_job_failed(e.jobId,e.desc)})}};try{const t=await this._getInitialPromise(e,o,d,s,l,i,n);if(3===t.status&&"integrated-mesh-3dtiles"===s.type){n===s.session&&null!==s.session&&await s.requestRootAndSession(i);h(await this._getInitialPromise(e,o,d,s,l,i,s.session))}else h(t)}catch(_){_&&this._debugLog(1,1,_.toString(),!1),this._lyr3DMain&&this._lyr3DMain.on_job_failed(e.jobId,e.desc),this._decrementJobCount(t)}}_onNewRenderable(){const e=this._lyr3DMain.get_next_renderable(),{meshData:t}=e;if(t.data&&t.data.byteLength>0){const e=t.data.slice();t.data=e}const i=this._layers.get(e.layerId);i&&(this._incrementRenderableCount(i),i.layerView.createRenderable(e).then(t=>{this._lyr3DMain?.on_renderable_created(!0,e.layerId,e.handle,t.memUsageBytes),this._decrementRenderableCount(i)}).catch(t=>{r(t)||this._debugLog(2,1,`createRenderable failed with error ${t}.`),this._lyr3DMain?.on_renderable_created(!1,e.layerId,e.handle,0),this._decrementRenderableCount(i)}))}_freeRenderables(e,t,i){if(i<1)return;const s=this._layers.get(e);if(!s)return;const r=s.layerView,a=[],n=new Uint32Array(this._lyr3DMain.HEAPU32.buffer,t,i);for(let o=0;o<i;++o)a.push(n[o]);for(let o=0;o<i;++o)r.freeRenderable(a[o])}_setRenderableVisibility(e,t,i,s){if(s<1)return;const r=this._layers.get(e);if(!r)return;const a=r.layerView,n=[],o=[],l=new Uint32Array(this._lyr3DMain.HEAPU32.buffer,t,s),d=new Uint8Array(this._lyr3DMain.HEAPU8.buffer,i,s);for(let h=0;h<s;++h)n.push(l[h]),o.push(1===d[h]);a.setRenderableVisibility(n,o,s)}_onWasmError(e,t,i,s){this._lyr3DMain&&this._debugLog(i,s,this._lyr3DMain.UTF8ToString(e,t),!1)}_doRemoveLayerView(e){const t=this._layers.get(e.wasmLayerId);return!!t&&(t.abortController.abort(),this._lyr3DMain.remove_layer(e.wasmLayerId),this._layers.delete(e.wasmLayerId),!0)}_isGaussianSplatLayerView(e){return"gaussian-splat"===e.layer.type}_isGaussianSplatLayer(e){return"gaussian-splat"===e.type}_toWasmQuality(e){switch(e){case"low":return 1;case"medium":return 2;case"high":return 3}}_addLayerView(e){const t=e.layer;if(!t.url||!t.rootTilesetJSON)return{wasmLayerId:p};const i="integrated-mesh-3dtiles"===t.type?0:2,r=this._lyr3DMain.validate_root_tileset(JSON.stringify(t.rootTilesetJSON),i);if(0!==r.errorCode)return{wasmLayerId:p,check:r};const a=this._lyr3DMain.get_next_layer_id(),n=new AbortController;this._layers.set(a,{layerView:e,abortController:n,needMemoryUsageUpdate:!1,outstandingJobCount:0,outstandingRenderableCount:0,customParameters:t.customParameters,apiKey:t.apiKey,needFrame:!0});const o=v(t.elevationInfo),l=this._toWasmQuality(this.view?.qualityProfile),d=e=>s.getLogger(this).error("add-spatial-reference-error","Error when adding SR:",e);let h=!1;if(this._isGaussianSplatLayerView(e)&&this._isGaussianSplatLayer(t)){let i=t.spatialReference;if(e.useEsriCrs&&t.esriCrsSpatialReference){i=t.esriCrsSpatialReference;const s=g(i);let r=1,a=1;!s&&i.wkid&&-1!==i.wkid&&(r=m.values[m[i.wkid]],a=e.metersPerVCSUnit),this._workerHandle.addSpatialReferenceInfo(this._cleanUpSR(this._makeSRWasmSerializable(i)),s,r,a).catch(d)}h=this._lyr3DMain.add_gaussian_splat_layer(l,t.url,a,o)}else h=this._lyr3DMain.add_3dtiles_layer(l,t.url,a,o);return h?(this._updateWasmCamera(),e.updatingFlagChanged(),{wasmLayerId:a}):(this._layers.delete(a),{wasmLayerId:p})}_createElevationUpdateHandle(){const e=(e,t)=>{const i=this.view.state?.contentCamera;if(!i||!this._lyr3DMain)return;const s=d(i.eye);if(!_(this.view.renderSpatialReference,t))return;u(s,this.view.renderSpatialReference,0,s,t,0,1);y(e,s[0],s[1])&&(this._updateCameraElevation=5,this._layers.forEach(e=>{const t=this._isUpdating(e);e.needFrame=!0,t||e.layerView.updatingFlagChanged()}))};return this.view.groundView.on("elevation-change",({extent:t,spatialReference:i})=>e(t,i))}_updateWasmCamera(){const e=this.view.state?.contentCamera;if(!e||!this._lyr3DMain)return;const{eye:t,center:i,up:s,near:r,far:a,fovY:n}=e,o=[e.viewport[2],e.viewport[3]],l=e.width/e.height;this._lyr3DMain.set_camera_parameters({eye:t,center:i,up:s,near:r,far:a,fov:n,aspectRatio:l,viewport:o}),this._layers.forEach(e=>{const t=this._isUpdating(e);e.needFrame=!0,t||e.layerView.updatingFlagChanged()})}_makeSRWasmSerializable(e){return{wkid:e?.wkid??-1,latestWkid:e?.latestWkid??-1,vcsWkid:e?.vcsWkid??-1,latestVcsWkid:e?.latestVcsWkid??-1,wkt:e?.wkt??""}}_cleanUpSR(e){return-1===e?.wkid&&e.latestWkid&&-1!==e.latestWkid?e.wkid=e.latestWkid:-1===e?.latestWkid&&e.wkid&&-1!==e.wkid&&(e.latestWkid=e.wkid),-1===e?.vcsWkid&&e.latestVcsWkid&&-1!==e.latestVcsWkid?e.vcsWkid=e.latestVcsWkid:-1===e?.latestVcsWkid&&e.vcsWkid&&-1!==e.vcsWkid&&(e.latestVcsWkid=e.vcsWkid),e}};e([o({constructOnly:!0})],C.prototype,"view",void 0),C=e([l("esri.layers.Lyr3DWasmPerSceneView")],C);const W=C;export{W 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/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../Graphic.js";import r from"../PopupTemplate.js";import{ClonableMixin as i}from"../core/Clonable.js";import s from"../core/Collection.js";import{deprecated as o}from"../core/deprecate.js";import a from"../core/Error.js";import{abortHandle as n}from"../core/handleUtils.js";import l from"../core/Logger.js";import{destroyMaybe as p}from"../core/maybe.js";import{MultiOriginJSONMixin as d}from"../core/MultiOriginJSONSupport.js";import{throwIfAbortError as y,throwIfAborted as u,isAbortError as c,throwIfNotAbortError as h}from"../core/promiseUtils.js";import{whenOnce as f}from"../core/reactiveUtils.js";import{property as m,subclass as g}from"../core/accessorSupport/decorators.js";import{getProperties as v}from"../core/accessorSupport/utils.js";import b from"../geometry/Point.js";import{projectWithZConversion as w}from"../geometry/projectionUtils.js";import I from"../graphic/SceneGraphicOrigin.js";import L from"./Layer.js";import{NoModelError as j,MultipleModelsError as F}from"./graphics/sources/support/uploadAssetErrors.js";import{APIKeyMixin as S}from"./mixins/APIKeyMixin.js";import{ArcGISService as O}from"./mixins/ArcGISService.js";import{CustomParametersMixin as _}from"./mixins/CustomParametersMixin.js";import{EditBusLayer as P}from"./mixins/EditBusLayer.js";import{OperationalLayer as T}from"./mixins/OperationalLayer.js";import{PortalLayer as A}from"./mixins/PortalLayer.js";import{ScaleRangeLayer as x}from"./mixins/ScaleRangeLayer.js";import{SceneService as E}from"./mixins/SceneService.js";import{useViewTimeProperty as D}from"./mixins/TemporalLayer.js";import{TemporalSceneLayer as U}from"./mixins/TemporalSceneLayer.js";import{isHostedAgolService as R}from"./support/arcgisLayerUrl.js";import{findAssociatedFeatureService as q}from"./support/associatedFeatureServiceUtils.js";import{zeroCapabilities as C}from"./support/capabilities.js";import{elevationInfo as N,labelsVisible as G,legendEnabled as Q,popupEnabled as V,attributeTableTemplate as M,screenSizePerspectiveEnabled as k}from"./support/commonProperties.js";import{getFieldDomain as K,computeEffectiveEditingEnabled as $,getGlobalIdToObjectIdMap as H}from"./support/featureLayerUtils.js";import{FeatureReduction as z}from"./support/FeatureReduction.js";import W from"./support/FeatureReductionSelection.js";import{defineFieldProperties as Z}from"./support/fieldProperties.js";import B from"./support/FieldsIndex.js";import{fixRendererFields as J,unpackFieldNames as X}from"./support/fieldUtils.js";import{I3SNodePageDefinition as Y,I3SMaterialDefinition as ee,I3STextureSetDefinition as te,I3SGeometryDefinition as re}from"./support/I3SLayerDefinitions.js";import{isFileEditFormat as ie,isFileSupported as se}from"./support/infoFor3D.js";import oe from"./support/LabelClass.js";import{reader as ae}from"./support/labelingInfo.js";import ne from"./support/LayerFloorInfo.js";import{layerLookupMap as le}from"./support/lazyLayerLoader.js";import{getMeshTransformForMetersToSpatialReference as pe}from"./support/meshSpatialReferenceScaleUtils.js";import{RangeInfo as de}from"./support/RangeInfo.js";import ye from"./support/SceneFilter.js";import{cacheIsOutOfSync as ue}from"./support/sceneLayerCacheUtils.js";import{fetchStatistics as ce}from"./support/sceneLayerStatistics.js";import{loadStyleRenderer as he}from"../renderers/support/styleUtils.js";import{webSceneRendererTypes as fe}from"../renderers/support/typeUtils.js";import me from"../rest/support/Query.js";import{logInvalidElevationInfoWarning as ge,elevationModeUnsupportedMessage as ve,featureExpressionUnsupportedMessage as be}from"../support/elevationInfoUtils.js";import{createPopupTemplate as we}from"../support/popupUtils.js";import{extractZipFiles as Ie}from"../support/zipUtils.js";import{queryAttributesFromCachedAttributesId as Le}from"../views/3d/layers/i3s/I3SUtil.js";import{getRequiredFields as je,getFetchPopupTemplate as Fe}from"../views/layers/support/popupUtils.js";import{transparencyToOpacity as Se}from"../webdoc/support/opacityUtils.js";import{reader as Oe}from"../core/accessorSupport/decorators/reader.js";const _e=new Set(["3DObject","Point"]),Pe=Z();let Te=class extends(U(P(E(O(T(A(x(d(_(S(i(L)))))))))))){constructor(...e){super(...e),this.featureReduction=null,this.rangeInfos=null,this.operationalLayerType="ArcGISSceneServiceLayer",this.type="scene",this.fields=null,this.graphicOrigin=new I(this),this.floorInfo=null,this.outFields=null,this.nodePages=null,this.materialDefinitions=null,this.textureSetDefinitions=null,this.geometryDefinitions=null,this.serviceUpdateTimeStamp=null,this.excludeObjectIds=new s,this.definitionExpression=null,this.filter=null,this.path=null,this.labelsVisible=!0,this.labelingInfo=null,this.legendEnabled=!0,this.priority=null,this.semantic=null,this.cachedDrawingInfo={color:!1},this.popupEnabled=!0,this.popupTemplate=null,this.attributeTableTemplate=null,this.objectIdField=null,this.globalIdField=null,this._fieldUsageInfo={},this.screenSizePerspectiveEnabled=!0,this.serviceItemId=void 0}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}destroy(){this._set("renderer",null),this.associatedLayer=p(this.associatedLayer)}getField(e){return this.fieldsIndex.get(e)}getFieldDomain(e,t){const r=this.getField(e)?.domain??null;return this.associatedLayer?K(this.associatedLayer,e,t,r):r}getFeatureType(e){return e&&this.associatedLayer?this.associatedLayer.getFeatureType(e):null}get types(){return this.associatedLayer?.types??[]}get typeIdField(){return this.associatedLayer?.typeIdField??null}get templates(){return this.associatedLayer?.templates??null}get formTemplate(){return this.associatedLayer?.formTemplate??null}get fieldsIndex(){return new B(this.fields)}readNodePages(e,t,r){return"Point"===t.layerType&&(e=t.pointNodePages),null==e||"object"!=typeof e?null:Y.fromJSON(e,r)}set elevationInfo(e){this._set("elevationInfo",e),this.loaded&&this._validateElevationInfo()}get effectiveCapabilities(){return this._capabilitiesFromAssociatedFeatureLayer(this.associatedLayer?.effectiveCapabilities)}get effectiveEditingEnabled(){return null!=this.associatedLayer&&$(this.associatedLayer)}get geometryType(){return xe[this.profile]||"mesh"}set renderer(e){J(e,this.fieldsIndex),this._set("renderer",e)}readCachedDrawingInfo(e){return null!=e&&"object"==typeof e||(e={}),null==e.color&&(e.color=!1),e}get capabilities(){return this._capabilitiesFromAssociatedFeatureLayer(this.associatedLayer?.capabilities)}_capabilitiesFromAssociatedFeatureLayer(e){e=null!=e?e:C;const{query:t,queryRelated:r,editing:{supportsGlobalId:i,supportsRollbackOnFailure:s,supportsUploadWithItemId:o,supportsGeometryUpdate:a,supportsReturnServiceEditsInSourceSpatialReference:n},data:{supportsZ:l,supportsM:p,isVersioned:d,supportsAttachment:y},operations:{supportsEditing:u,supportsAdd:c,supportsUpdate:h,supportsDelete:f,supportsQuery:m,supportsQueryAttachments:g,supportsAsyncConvert3D:v}}=e,b=e.operations.supportsChangeTracking,w=!!this.associatedLayer?.infoFor3D;return{query:t,queryRelated:r,editing:{supportsGlobalId:i,supportsReturnServiceEditsInSourceSpatialReference:n,supportsRollbackOnFailure:s,supportsGeometryUpdate:w&&a,supportsUploadWithItemId:o},data:{supportsAttachment:y,supportsZ:l,supportsM:p,isVersioned:d},operations:{supportsQuery:m,supportsQueryAttachments:g,supportsEditing:u&&b,supportsAdd:w&&c&&b,supportsDelete:w&&f&&b,supportsUpdate:h&&b,supportsAsyncConvert3D:v}}}get editingEnabled(){return this._isOverridden("editingEnabled")?this._get("editingEnabled"):this.associatedLayer?.editingEnabled??!1}set editingEnabled(e){this._overrideIfSome("editingEnabled",e)}get infoFor3D(){return this.associatedLayer?.infoFor3D??null}get relationships(){return this.associatedLayer?.relationships}get defaultPopupTemplate(){return this.associatedLayer||this.attributeStorageInfo?this.createPopupTemplate():null}readObjectIdField(e,t){return!e&&t.fields&&t.fields.some(t=>("esriFieldTypeOID"===t.type&&(e=t.name),!!e)),e||void 0}readGlobalIdField(e,t){return!e&&t.fields&&t.fields.some(t=>("esriFieldTypeGlobalID"===t.type&&(e=t.name),!!e)),e||void 0}get displayField(){return this.associatedLayer?.displayField??null}readProfile(e,t){const r=t.store.profile;return null!=r&&Ae[r]?Ae[r]:(l.getLogger(this).error("Unknown or missing profile",{profile:r,layer:this}),"mesh-pyramids")}get useViewTime(){return this.associatedLayer?.useViewTime??!0}set useViewTime(e){this._override("useViewTime",e)}load(e){return this.addResolvingPromise(this._load(e)),Promise.resolve(this)}async _load(e){const t=e?.signal;await this.loadFromPortal({supportedTypes:["Scene Service"]},e).catch(y),await this._fetchService(t),await Promise.all([this._fetchIndexAndUpdateExtent(this.nodePages,t),this._setAssociatedFeatureLayer(t),this._loadFilterGeometries()]),this._validateElevationInfo(),this._applyAssociatedLayerOverrides(),this._populateFieldUsageInfo(),await this.loadTimeInfoFromService(e),await he(this,{origin:"service"},t),J(this.renderer,this.fieldsIndex),await this.finishLoadEditablePortalLayer(e)}async beforeSave(){null!=this.filter&&(this.filter=this.filter.clone(),await this.load())}async _loadFilterGeometries(){if(this.filter)try{await this.filter.loadGeometries(this.spatialReference)}catch(e){l.getLogger(this).error("#_loadFilterGeometries()",this,"Failed to load filter geometries. Geometry filter will not be applied for this layer.",{error:e}),this.filter=null}}createQuery(){const e=new me;return"mesh"===this.geometryType?this.capabilities.query.supportsReturnMesh&&(e.returnGeometry=!0):(e.returnGeometry=!0,e.returnZ=!0),e.where=this.definitionExpression||"1=1",e.sqlFormat="standard",e.outFields=["*"],e}queryExtent(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryExtent(e||this.createQuery(),t))}queryFeatureCount(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryFeatureCount(e||this.createQuery(),t))}queryFeatures(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryFeatures(e||this.createQuery(),t)).then(e=>{if(e?.features)for(const t of e.features)t.layer=this,t.sourceLayer=this,t.origin=this.graphicOrigin;return e})}async queryRelatedFeatures(e,t){if(await this.load(),!this.associatedLayer)throw new a("scenelayer:query-not-available","SceneLayer queries are not available without an associated feature layer",{layer:this});return this.associatedLayer.queryRelatedFeatures(e,t)}async queryRelatedFeaturesCount(e,t){if(await this.load(),!this.associatedLayer)throw new a("scenelayer:query-not-available","SceneLayer queries are not available without an associated feature layer",{layer:this});return this.associatedLayer.queryRelatedFeaturesCount(e,t)}async queryCachedAttributes(e,t){const r=X(this.fieldsIndex,await je(this,Fe(this)));return Le(this.parsedUrl?.path??"",this.attributeStorageInfo??[],e,t,r,this.apiKey,this.customParameters)}async queryCachedFeature(e,r){const i=await this.queryCachedAttributes(e,[r]);if(!i||0===i.length)throw new a("scenelayer:feature-not-in-cached-data","Feature not found in cached data");const s=new t;return s.attributes=i[0],s.layer=this,s.sourceLayer=this,s.origin=this.graphicOrigin,s}queryObjectIds(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryObjectIds(e||this.createQuery(),t))}queryAttachments(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryAttachments(e,t))}getFieldUsageInfo(e){const t={supportsLabelingInfo:!1,supportsRenderer:!1,supportsPopupTemplate:!1,supportsLayerQuery:!1};return this.loaded?this._fieldUsageInfo[e]||t:(l.getLogger(this).error("#getFieldUsageInfo()","Unavailable until layer is loaded"),t)}createPopupTemplate(e){return we(this,e)}_getAssociatedLayerForQuery(){const e=this.associatedLayer;return e?.loaded?Promise.resolve(e):this._loadAssociatedLayerForQuery()}async _loadAssociatedLayerForQuery(){if(await this.load(),!this.associatedLayer)throw new a("scenelayer:query-not-available","SceneLayer queries are not available without an associated feature layer",{layer:this});try{await this.associatedLayer.load()}catch(e){throw new a("scenelayer:query-not-available","SceneLayer associated feature layer could not be loaded",{layer:this,error:e})}return this.associatedLayer}hasCachedStatistics(e){return null!=this.statisticsInfo&&this.statisticsInfo.some(t=>t.name===e)}async queryCachedStatistics(e,t){return await this.load(t),await this.fetchStatistics(e,t)}async saveAs(e,t){return this._debouncedSaveOperations(1,{...t,getTypeKeywords:()=>this._getTypeKeywords(),portalItemLayerType:"scene"},e)}async save(){const e={getTypeKeywords:()=>this._getTypeKeywords(),portalItemLayerType:"scene"};return this._debouncedSaveOperations(0,e)}async applyEdits(e,t){const{applyEdits:r}=await import("./graphics/editingSupport.js");let i=t;await this.load();const s=this.associatedLayer;if(!s)throw new a(`${this.type}-layer:not-editable`,"Service is not editable");await s.load();const{globalIdField:o}=s,n=!!s.infoFor3D,l=i?.globalIdUsed??!0;if(n&&null==o)throw new a(`${this.type}-layer:not-editable`,"Valid globalIdField expected on editable SceneLayer");if(n&&!l)throw new a(`${this.type}-layer:globalid-required`,"globalIdUsed must not be false for SceneLayer editing as globalIds are required.");return R(s.url)&&n&&null!=e.deleteFeatures&&null!=o&&(i={...i,globalIdToObjectId:await H(s,e.deleteFeatures,o)}),r(this,s.source,e,i)}async uploadAssets(e,t){if(await this.load(),null==this.associatedLayer)throw new a(`${this.type}-layer:not-editable`,"Service is not editable");return await this.associatedLayer.load(),this.associatedLayer.uploadAssets(e,t)}async convertMesh(e,t){t??={},null!=t.location&&o(l.getLogger(this),"The 'location' option of convertMesh() has been deprecated in favour of 'origin'.",{version:"4.34",replacement:"origin",warnOnce:!0});const r=e=>{throw l.getLogger(this).error(".convertMesh()",e.message),e};await this.load(t),this.infoFor3D||r(new a("invalid:layer","SceneLayer has no capability for mesh conversion"));const i=await this.extractAndFilterFiles(e);u(t);const s=i.reduce((e,t)=>ie(this.infoFor3D,t)?e+1:e,0);0===s&&r(new j),s>1&&r(new F);const n=this.spatialReference,p=t.origin??t.location,d=await w(p??t.defaultOrigin??new b({x:0,y:0,z:0,spatialReference:n}),n,t),y=d.spatialReference.isGeographic?"local":"georeferenced",{default:c}=await import("../geometry/Mesh.js");u(t);const h=c.createWithExternalSource(d,{type:"client",files:i},{vertexSpace:y,transform:pe(d.spatialReference),unitConversionDisabled:!0}),[f]=await this.uploadAssets([h],{...t,useAssetOrigin:!p});return f}async extractAndFilterFiles(e){await this.load();const t=this.infoFor3D;if(!t)return e;return(await Ie(e)).filter(e=>se(t,e))}validateLayer(e){if(e.layerType&&!_e.has(e.layerType))throw new a("scenelayer:layer-type-not-supported","SceneLayer does not support this layer type",{layerType:e.layerType});if(isNaN(this.version.major)||isNaN(this.version.minor))throw new a("layer:service-version-not-supported","Service version is not supported.",{serviceVersion:this.version.versionString,supportedVersions:"1.x, 2.x"});if(this.version.major>2)throw new a("layer:service-version-too-new","Service version is too new.",{serviceVersion:this.version.versionString,supportedVersions:"1.x, 2.x"});function t(e,t){let r=!1,i=!1;if(null==e)r=!0,i=!0;else{const s=t&&t.isGeographic;switch(e){case"east-north-up":case"earth-centered":r=!0,i=s;break;case"vertex-reference-frame":r=!0,i=!s;break;default:r=!1}}if(!r)throw new a("scenelayer:unsupported-normal-reference-frame","Normal reference frame is invalid.");if(!i)throw new a("scenelayer:incompatible-normal-reference-frame","Normal reference frame is incompatible with layer spatial reference.")}t(this.normalReferenceFrame,this.spatialReference)}_getTypeKeywords(){const e=[];if("points"===this.profile)e.push("Point");else{if("mesh-pyramids"!==this.profile)throw new a("scenelayer:unknown-profile","SceneLayer:save() encountered an unknown SceneLayer profile: "+this.profile);e.push("3DObject")}return e}_populateFieldUsageInfo(){if(this._fieldUsageInfo={},this.fields)for(const e of this.fields){const t=!!this.attributeStorageInfo?.some(t=>t.name===e.name),r=!!this.associatedLayer?.fields?.some(t=>t&&e.name===t.name),i={supportsLabelingInfo:t,supportsRenderer:t,supportsPopupTemplate:t||r,supportsLayerQuery:r};this._fieldUsageInfo[e.name]=i}}_applyAssociatedLayerOverrides(){this._applyAssociatedLayerFieldsOverrides(),this._applyAssociatedLayerPropertyOverrides(),this._applyAssociatedLayerExtentOverride(),this._applyAssociatedLayerPrivileges()}_applyAssociatedLayerFieldsOverrides(){if(!this.associatedLayer?.fields)return;let e=null;for(const t of this.associatedLayer.fields){const r=this.getField(t.name);r?(!r.domain&&t.domain&&(r.domain=t.domain.clone()),r.editable=t.editable,r.nullable=t.nullable,r.length=t.length):(e||(e=this.fields?this.fields.slice():[]),e.push(t.clone()))}e&&this._set("fields",e)}_applyAssociatedLayerPropertyOverrides(){if(!this.associatedLayer)return;const e=["popupTemplate","popupEnabled","attributeTableTemplate"],t=v(this);for(let r=0;r<e.length;r++){const i=e[r],s=this.originIdOf(i),o=this.associatedLayer.originIdOf(i);s<o&&(2===o||3===o)&&t.setAtOrigin(i,this.associatedLayer[i],o)}}_applyAssociatedLayerExtentOverride(){const e=this.associatedLayer?.getAtOrigin("fullExtent","service");if(null==this.associatedLayer?.infoFor3D||!e||!R(this.associatedLayer?.url)||!ue(this))return;v(this).setAtOrigin("fullExtent",e.clone(),2)}_applyAssociatedLayerPrivileges(){const e=this.associatedLayer;e&&(this._set("userHasEditingPrivileges",e.userHasEditingPrivileges),this._set("userHasFullEditingPrivileges",e.userHasFullEditingPrivileges),this._set("userHasUpdateItemPrivileges",e.userHasUpdateItemPrivileges))}async _setAssociatedFeatureLayer(e){if(["mesh-pyramids","points"].includes(this.profile))try{const{serverUrl:t,layerId:r,portalItem:i}=await q(`${this.url}/layers/${this.layerId}`,{sceneLayerItem:this.portalItem,customParameters:this.customParameters,apiKey:this.apiKey,signal:e}),s=await le.FeatureLayer();this.associatedLayer=new s({url:t,customParameters:this.customParameters,layerId:r,portalItem:i}),await this.associatedLayer.load()}catch(t){c(t)||this._logWarningOnPopupEnabled()}}async _logWarningOnPopupEnabled(){const e=new AbortController;this.addHandles(n(e));try{await f(()=>this.popupEnabled&&null!=this.popupTemplate,e.signal)}catch(r){return void h(r)}const t=`this SceneLayer: ${this.title}`;null==this.attributeStorageInfo?l.getLogger(this).warn(`Associated FeatureLayer could not be loaded and no binary attributes found. Popups will not work on ${t}`):l.getLogger(this).info(`Associated FeatureLayer could not be loaded. Falling back to binary attributes for Popups on ${t}`)}_validateElevationInfo(){const e=this.elevationInfo;"mesh-pyramids"===this.profile&&ge(l.getLogger(this),ve("Mesh scene layers","relative-to-scene",e)),ge(l.getLogger(this),be("Scene layers",e))}async fetchStatistics(e,t){return await ce({fieldName:e,statisticsInfo:this.statisticsInfo,errorContext:"scenelayer",fieldsIndex:this.fieldsIndex,path:this.parsedUrl?.path??"",customParameters:this.customParameters,apiKey:this.apiKey,signal:t?.signal})}};e([m({types:{key:"type",base:z,typeMap:{selection:W}},json:{origins:{"web-scene":{name:"layerDefinition.featureReduction",write:{allowNull:!0}},"portal-item":{name:"layerDefinition.featureReduction",write:{allowNull:!0}}}}})],Te.prototype,"featureReduction",void 0),e([m({type:[de],json:{read:!1,origins:{"web-scene":{name:"layerDefinition.rangeInfos",write:!0},"portal-item":{name:"layerDefinition.rangeInfos",write:!0}}},clonable:!1})],Te.prototype,"rangeInfos",void 0),e([m({json:{read:!1}})],Te.prototype,"associatedLayer",void 0),e([m({type:["show","hide"]})],Te.prototype,"listMode",void 0),e([m({type:["ArcGISSceneServiceLayer"]})],Te.prototype,"operationalLayerType",void 0),e([m({json:{read:!1},readOnly:!0})],Te.prototype,"type",void 0),e([m({...Pe.fields,readOnly:!0,json:{read:!1,origins:{service:{read:!0}}}})],Te.prototype,"fields",void 0),e([m()],Te.prototype,"types",null),e([m()],Te.prototype,"typeIdField",null),e([m()],Te.prototype,"templates",null),e([m()],Te.prototype,"formTemplate",null),e([m({readOnly:!0})],Te.prototype,"graphicOrigin",void 0),e([m({readOnly:!0,clonable:!1})],Te.prototype,"fieldsIndex",null),e([m({type:ne,json:{read:{source:"layerDefinition.floorInfo"},write:{target:"layerDefinition.floorInfo"}}})],Te.prototype,"floorInfo",void 0),e([m(Pe.outFields)],Te.prototype,"outFields",void 0),e([m({type:Y,readOnly:!0,json:{read:!1},clonable:!1})],Te.prototype,"nodePages",void 0),e([Oe("service","nodePages",["nodePages","pointNodePages"])],Te.prototype,"readNodePages",null),e([m({type:[ee],readOnly:!0,clonable:!1})],Te.prototype,"materialDefinitions",void 0),e([m({type:[te],readOnly:!0,clonable:!1})],Te.prototype,"textureSetDefinitions",void 0),e([m({type:[re],readOnly:!0,clonable:!1})],Te.prototype,"geometryDefinitions",void 0),e([m({readOnly:!0})],Te.prototype,"serviceUpdateTimeStamp",void 0),e([m({readOnly:!0})],Te.prototype,"attributeStorageInfo",void 0),e([m({readOnly:!0})],Te.prototype,"statisticsInfo",void 0),e([m({type:s.ofType(Number),nonNullable:!0,json:{origins:{service:{read:!1,write:!1}},name:"layerDefinition.excludeObjectIds",write:{enabled:!0}}})],Te.prototype,"excludeObjectIds",void 0),e([m({type:String,json:{origins:{service:{read:!1,write:!1}},name:"layerDefinition.definitionExpression",write:{enabled:!0,allowNull:!0}}})],Te.prototype,"definitionExpression",void 0),e([m({type:ye,json:{name:"layerDefinition.polygonFilter",write:{enabled:!0,allowNull:!0},origins:{service:{read:!1,write:!1}}}})],Te.prototype,"filter",void 0),e([m({type:String,json:{origins:{"web-scene":{read:!0,write:!0}},read:!1}})],Te.prototype,"path",void 0),e([m(N)],Te.prototype,"elevationInfo",null),e([m({readOnly:!0,json:{read:!1}})],Te.prototype,"effectiveCapabilities",null),e([m({readOnly:!0})],Te.prototype,"effectiveEditingEnabled",null),e([m({type:String})],Te.prototype,"geometryType",null),e([m(G)],Te.prototype,"labelsVisible",void 0),e([m({type:[oe],json:{origins:{service:{name:"drawingInfo.labelingInfo",read:{reader:ae},write:!1}},name:"layerDefinition.drawingInfo.labelingInfo",read:{reader:ae},write:!0}})],Te.prototype,"labelingInfo",void 0),e([m(Q)],Te.prototype,"legendEnabled",void 0),e([m({type:Number,json:{origins:{"web-document":{default:1,write:{enabled:!0,target:{opacity:{type:Number},"layerDefinition.drawingInfo.transparency":{type:Number}}},read:{source:["opacity","layerDefinition.drawingInfo.transparency"],reader(e,t){if("number"==typeof e&&e>=0&&e<=1)return e;const r=t.layerDefinition?.drawingInfo?.transparency;return void 0!==r?Se(r):void 0}}},"portal-item":{write:!0},service:{read:!1}}}})],Te.prototype,"opacity",void 0),e([m({type:["Low","High"],readOnly:!0,json:{read:!1,origins:{service:{read:!0}}}})],Te.prototype,"priority",void 0),e([m({type:["Labels"],readOnly:!0,json:{read:!1,origins:{service:{read:!0}}}})],Te.prototype,"semantic",void 0),e([m({types:fe,json:{origins:{service:{read:{source:"drawingInfo.renderer"}}},name:"layerDefinition.drawingInfo.renderer",write:!0},value:null})],Te.prototype,"renderer",null),e([m({json:{read:!1}})],Te.prototype,"cachedDrawingInfo",void 0),e([Oe("service","cachedDrawingInfo")],Te.prototype,"readCachedDrawingInfo",null),e([m({readOnly:!0,json:{read:!1}})],Te.prototype,"capabilities",null),e([m({type:Boolean,json:{read:!1}})],Te.prototype,"editingEnabled",null),e([m({readOnly:!0,json:{write:!1,read:!1}})],Te.prototype,"infoFor3D",null),e([m({readOnly:!0,json:{write:!1,read:!1}})],Te.prototype,"relationships",null),e([m(V)],Te.prototype,"popupEnabled",void 0),e([m({type:r,json:{name:"popupInfo",write:!0}})],Te.prototype,"popupTemplate",void 0),e([m({readOnly:!0,json:{read:!1}})],Te.prototype,"defaultPopupTemplate",null),e([m(M)],Te.prototype,"attributeTableTemplate",void 0),e([m({type:String,json:{read:!1}})],Te.prototype,"objectIdField",void 0),e([Oe("service","objectIdField",["objectIdField","fields"])],Te.prototype,"readObjectIdField",null),e([m({type:String,json:{read:!1}})],Te.prototype,"globalIdField",void 0),e([Oe("service","globalIdField",["globalIdField","fields"])],Te.prototype,"readGlobalIdField",null),e([m({readOnly:!0,type:String,json:{read:!1}})],Te.prototype,"displayField",null),e([m({type:String,json:{read:!1}})],Te.prototype,"profile",void 0),e([Oe("service","profile",["store.profile"])],Te.prototype,"readProfile",null),e([m({readOnly:!0,type:String,json:{origins:{service:{read:{source:"store.normalReferenceFrame"}}},read:!1}})],Te.prototype,"normalReferenceFrame",void 0),e([m(k)],Te.prototype,"screenSizePerspectiveEnabled",void 0),e([m({json:{read:!1,origins:{service:{read:!0}}}})],Te.prototype,"serviceItemId",void 0),e([m(D)],Te.prototype,"useViewTime",null),Te=e([g("esri.layers.SceneLayer")],Te);const Ae={"mesh-pyramids":"mesh-pyramids",meshpyramids:"mesh-pyramids","features-meshes":"mesh-pyramids",points:"points","features-points":"points",lines:"lines","features-lines":"lines",polygons:"polygons","features-polygons":"polygons"},xe={"mesh-pyramids":"mesh",points:"point"},Ee=Te;export{Ee as default};
5
+ import{__decorate as e}from"tslib";import t from"../Graphic.js";import r from"../PopupTemplate.js";import{ClonableMixin as i}from"../core/Clonable.js";import s from"../core/Collection.js";import o from"../core/Error.js";import{abortHandle as a}from"../core/handleUtils.js";import n from"../core/Logger.js";import{destroyMaybe as l}from"../core/maybe.js";import{MultiOriginJSONMixin as p}from"../core/MultiOriginJSONSupport.js";import{throwIfAbortError as d,throwIfAborted as y,isAbortError as u,throwIfNotAbortError as c}from"../core/promiseUtils.js";import{whenOnce as h}from"../core/reactiveUtils.js";import{property as f,subclass as m}from"../core/accessorSupport/decorators.js";import{getProperties as g}from"../core/accessorSupport/utils.js";import v from"../geometry/Point.js";import{projectWithZConversion as b}from"../geometry/projectionUtils.js";import w from"../graphic/SceneGraphicOrigin.js";import I from"./Layer.js";import{NoModelError as L,MultipleModelsError as j}from"./graphics/sources/support/uploadAssetErrors.js";import{APIKeyMixin as F}from"./mixins/APIKeyMixin.js";import{ArcGISService as S}from"./mixins/ArcGISService.js";import{CustomParametersMixin as O}from"./mixins/CustomParametersMixin.js";import{EditBusLayer as _}from"./mixins/EditBusLayer.js";import{OperationalLayer as P}from"./mixins/OperationalLayer.js";import{PortalLayer as A}from"./mixins/PortalLayer.js";import{ScaleRangeLayer as T}from"./mixins/ScaleRangeLayer.js";import{SceneService as x}from"./mixins/SceneService.js";import{useViewTimeProperty as E}from"./mixins/TemporalLayer.js";import{TemporalSceneLayer as D}from"./mixins/TemporalSceneLayer.js";import{isHostedAgolService as U}from"./support/arcgisLayerUrl.js";import{findAssociatedFeatureService as q}from"./support/associatedFeatureServiceUtils.js";import{zeroCapabilities as R}from"./support/capabilities.js";import{elevationInfo as C,labelsVisible as N,legendEnabled as G,popupEnabled as Q,attributeTableTemplate as V,screenSizePerspectiveEnabled as M}from"./support/commonProperties.js";import{getFieldDomain as k,computeEffectiveEditingEnabled as K,getGlobalIdToObjectIdMap as $}from"./support/featureLayerUtils.js";import{FeatureReduction as H}from"./support/FeatureReduction.js";import z from"./support/FeatureReductionSelection.js";import{defineFieldProperties as W}from"./support/fieldProperties.js";import Z from"./support/FieldsIndex.js";import{fixRendererFields as B,unpackFieldNames as J}from"./support/fieldUtils.js";import{I3SNodePageDefinition as X,I3SMaterialDefinition as Y,I3STextureSetDefinition as ee,I3SGeometryDefinition as te}from"./support/I3SLayerDefinitions.js";import{isFileEditFormat as re,isFileSupported as ie}from"./support/infoFor3D.js";import se from"./support/LabelClass.js";import{reader as oe}from"./support/labelingInfo.js";import ae from"./support/LayerFloorInfo.js";import{layerLookupMap as ne}from"./support/lazyLayerLoader.js";import{getMeshTransformForMetersToSpatialReference as le}from"./support/meshSpatialReferenceScaleUtils.js";import{RangeInfo as pe}from"./support/RangeInfo.js";import de from"./support/SceneFilter.js";import{cacheIsOutOfSync as ye}from"./support/sceneLayerCacheUtils.js";import{fetchStatistics as ue}from"./support/sceneLayerStatistics.js";import{loadStyleRenderer as ce}from"../renderers/support/styleUtils.js";import{webSceneRendererTypes as he}from"../renderers/support/typeUtils.js";import fe from"../rest/support/Query.js";import{logInvalidElevationInfoWarning as me,elevationModeUnsupportedMessage as ge,featureExpressionUnsupportedMessage as ve}from"../support/elevationInfoUtils.js";import{createPopupTemplate as be}from"../support/popupUtils.js";import{extractZipFiles as we}from"../support/zipUtils.js";import{queryAttributesFromCachedAttributesId as Ie}from"../views/3d/layers/i3s/I3SUtil.js";import{getRequiredFields as Le,getFetchPopupTemplate as je}from"../views/layers/support/popupUtils.js";import{transparencyToOpacity as Fe}from"../webdoc/support/opacityUtils.js";import{reader as Se}from"../core/accessorSupport/decorators/reader.js";const Oe=new Set(["3DObject","Point"]),_e=W();let Pe=class extends(D(_(x(S(P(A(T(p(O(F(i(I)))))))))))){constructor(...e){super(...e),this.featureReduction=null,this.rangeInfos=null,this.operationalLayerType="ArcGISSceneServiceLayer",this.type="scene",this.fields=null,this.graphicOrigin=new w(this),this.floorInfo=null,this.outFields=null,this.nodePages=null,this.materialDefinitions=null,this.textureSetDefinitions=null,this.geometryDefinitions=null,this.serviceUpdateTimeStamp=null,this.excludeObjectIds=new s,this.definitionExpression=null,this.filter=null,this.path=null,this.labelsVisible=!0,this.labelingInfo=null,this.legendEnabled=!0,this.priority=null,this.semantic=null,this.cachedDrawingInfo={color:!1},this.popupEnabled=!0,this.popupTemplate=null,this.attributeTableTemplate=null,this.objectIdField=null,this.globalIdField=null,this._fieldUsageInfo={},this.screenSizePerspectiveEnabled=!0,this.serviceItemId=void 0}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}destroy(){this._set("renderer",null),this.associatedLayer=l(this.associatedLayer)}getField(e){return this.fieldsIndex.get(e)}getFieldDomain(e,t){const r=this.getField(e)?.domain??null;return this.associatedLayer?k(this.associatedLayer,e,t,r):r}getFeatureType(e){return e&&this.associatedLayer?this.associatedLayer.getFeatureType(e):null}get types(){return this.associatedLayer?.types??[]}get typeIdField(){return this.associatedLayer?.typeIdField??null}get templates(){return this.associatedLayer?.templates??null}get formTemplate(){return this.associatedLayer?.formTemplate??null}get fieldsIndex(){return new Z(this.fields)}readNodePages(e,t,r){return"Point"===t.layerType&&(e=t.pointNodePages),null==e||"object"!=typeof e?null:X.fromJSON(e,r)}set elevationInfo(e){this._set("elevationInfo",e),this.loaded&&this._validateElevationInfo()}get effectiveCapabilities(){return this._capabilitiesFromAssociatedFeatureLayer(this.associatedLayer?.effectiveCapabilities)}get effectiveEditingEnabled(){return null!=this.associatedLayer&&K(this.associatedLayer)}get geometryType(){return Te[this.profile]||"mesh"}set renderer(e){B(e,this.fieldsIndex),this._set("renderer",e)}readCachedDrawingInfo(e){return null!=e&&"object"==typeof e||(e={}),null==e.color&&(e.color=!1),e}get capabilities(){return this._capabilitiesFromAssociatedFeatureLayer(this.associatedLayer?.capabilities)}_capabilitiesFromAssociatedFeatureLayer(e){e=null!=e?e:R;const{query:t,queryRelated:r,editing:{supportsGlobalId:i,supportsRollbackOnFailure:s,supportsUploadWithItemId:o,supportsGeometryUpdate:a,supportsReturnServiceEditsInSourceSpatialReference:n},data:{supportsZ:l,supportsM:p,isVersioned:d,supportsAttachment:y},operations:{supportsEditing:u,supportsAdd:c,supportsUpdate:h,supportsDelete:f,supportsQuery:m,supportsQueryAttachments:g,supportsAsyncConvert3D:v}}=e,b=e.operations.supportsChangeTracking,w=!!this.associatedLayer?.infoFor3D;return{query:t,queryRelated:r,editing:{supportsGlobalId:i,supportsReturnServiceEditsInSourceSpatialReference:n,supportsRollbackOnFailure:s,supportsGeometryUpdate:w&&a,supportsUploadWithItemId:o},data:{supportsAttachment:y,supportsZ:l,supportsM:p,isVersioned:d},operations:{supportsQuery:m,supportsQueryAttachments:g,supportsEditing:u&&b,supportsAdd:w&&c&&b,supportsDelete:w&&f&&b,supportsUpdate:h&&b,supportsAsyncConvert3D:v}}}get editingEnabled(){return this._isOverridden("editingEnabled")?this._get("editingEnabled"):this.associatedLayer?.editingEnabled??!1}set editingEnabled(e){this._overrideIfSome("editingEnabled",e)}get infoFor3D(){return this.associatedLayer?.infoFor3D??null}get relationships(){return this.associatedLayer?.relationships}get defaultPopupTemplate(){return this.associatedLayer||this.attributeStorageInfo?this.createPopupTemplate():null}readObjectIdField(e,t){return!e&&t.fields&&t.fields.some(t=>("esriFieldTypeOID"===t.type&&(e=t.name),!!e)),e||void 0}readGlobalIdField(e,t){return!e&&t.fields&&t.fields.some(t=>("esriFieldTypeGlobalID"===t.type&&(e=t.name),!!e)),e||void 0}get displayField(){return this.associatedLayer?.displayField??null}readProfile(e,t){const r=t.store.profile;return null!=r&&Ae[r]?Ae[r]:(n.getLogger(this).error("Unknown or missing profile",{profile:r,layer:this}),"mesh-pyramids")}get useViewTime(){return this.associatedLayer?.useViewTime??!0}set useViewTime(e){this._override("useViewTime",e)}load(e){return this.addResolvingPromise(this._load(e)),Promise.resolve(this)}async _load(e){const t=e?.signal;await this.loadFromPortal({supportedTypes:["Scene Service"]},e).catch(d),await this._fetchService(t),await Promise.all([this._fetchIndexAndUpdateExtent(this.nodePages,t),this._setAssociatedFeatureLayer(t),this._loadFilterGeometries()]),this._validateElevationInfo(),this._applyAssociatedLayerOverrides(),this._populateFieldUsageInfo(),await this.loadTimeInfoFromService(e),await ce(this,{origin:"service"},t),B(this.renderer,this.fieldsIndex),await this.finishLoadEditablePortalLayer(e)}async beforeSave(){null!=this.filter&&(this.filter=this.filter.clone(),await this.load())}async _loadFilterGeometries(){if(this.filter)try{await this.filter.loadGeometries(this.spatialReference)}catch(e){n.getLogger(this).error("#_loadFilterGeometries()",this,"Failed to load filter geometries. Geometry filter will not be applied for this layer.",{error:e}),this.filter=null}}createQuery(){const e=new fe;return"mesh"===this.geometryType?this.capabilities.query.supportsReturnMesh&&(e.returnGeometry=!0):(e.returnGeometry=!0,e.returnZ=!0),e.where=this.definitionExpression||"1=1",e.sqlFormat="standard",e.outFields=["*"],e}queryExtent(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryExtent(e||this.createQuery(),t))}queryFeatureCount(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryFeatureCount(e||this.createQuery(),t))}queryFeatures(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryFeatures(e||this.createQuery(),t)).then(e=>{if(e?.features)for(const t of e.features)t.layer=this,t.sourceLayer=this,t.origin=this.graphicOrigin;return e})}async queryRelatedFeatures(e,t){if(await this.load(),!this.associatedLayer)throw new o("scenelayer:query-not-available","SceneLayer queries are not available without an associated feature layer",{layer:this});return this.associatedLayer.queryRelatedFeatures(e,t)}async queryRelatedFeaturesCount(e,t){if(await this.load(),!this.associatedLayer)throw new o("scenelayer:query-not-available","SceneLayer queries are not available without an associated feature layer",{layer:this});return this.associatedLayer.queryRelatedFeaturesCount(e,t)}async queryCachedAttributes(e,t){const r=J(this.fieldsIndex,await Le(this,je(this)));return Ie(this.parsedUrl?.path??"",this.attributeStorageInfo??[],e,t,r,this.apiKey,this.customParameters)}async queryCachedFeature(e,r){const i=await this.queryCachedAttributes(e,[r]);if(!i||0===i.length)throw new o("scenelayer:feature-not-in-cached-data","Feature not found in cached data");const s=new t;return s.attributes=i[0],s.layer=this,s.sourceLayer=this,s.origin=this.graphicOrigin,s}queryObjectIds(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryObjectIds(e||this.createQuery(),t))}queryAttachments(e,t){return this._getAssociatedLayerForQuery().then(r=>r.queryAttachments(e,t))}getFieldUsageInfo(e){const t={supportsLabelingInfo:!1,supportsRenderer:!1,supportsPopupTemplate:!1,supportsLayerQuery:!1};return this.loaded?this._fieldUsageInfo[e]||t:(n.getLogger(this).error("#getFieldUsageInfo()","Unavailable until layer is loaded"),t)}createPopupTemplate(e){return be(this,e)}_getAssociatedLayerForQuery(){const e=this.associatedLayer;return e?.loaded?Promise.resolve(e):this._loadAssociatedLayerForQuery()}async _loadAssociatedLayerForQuery(){if(await this.load(),!this.associatedLayer)throw new o("scenelayer:query-not-available","SceneLayer queries are not available without an associated feature layer",{layer:this});try{await this.associatedLayer.load()}catch(e){throw new o("scenelayer:query-not-available","SceneLayer associated feature layer could not be loaded",{layer:this,error:e})}return this.associatedLayer}hasCachedStatistics(e){return null!=this.statisticsInfo&&this.statisticsInfo.some(t=>t.name===e)}async queryCachedStatistics(e,t){return await this.load(t),await this.fetchStatistics(e,t)}async saveAs(e,t){return this._debouncedSaveOperations(1,{...t,getTypeKeywords:()=>this._getTypeKeywords(),portalItemLayerType:"scene"},e)}async save(){const e={getTypeKeywords:()=>this._getTypeKeywords(),portalItemLayerType:"scene"};return this._debouncedSaveOperations(0,e)}async applyEdits(e,t){const{applyEdits:r}=await import("./graphics/editingSupport.js");let i=t;await this.load();const s=this.associatedLayer;if(!s)throw new o(`${this.type}-layer:not-editable`,"Service is not editable");await s.load();const{globalIdField:a}=s,n=!!s.infoFor3D,l=i?.globalIdUsed??!0;if(n&&null==a)throw new o(`${this.type}-layer:not-editable`,"Valid globalIdField expected on editable SceneLayer");if(n&&!l)throw new o(`${this.type}-layer:globalid-required`,"globalIdUsed must not be false for SceneLayer editing as globalIds are required.");return U(s.url)&&n&&null!=e.deleteFeatures&&null!=a&&(i={...i,globalIdToObjectId:await $(s,e.deleteFeatures,a)}),r(this,s.source,e,i)}async uploadAssets(e,t){if(await this.load(),null==this.associatedLayer)throw new o(`${this.type}-layer:not-editable`,"Service is not editable");return await this.associatedLayer.load(),this.associatedLayer.uploadAssets(e,t)}async convertMesh(e,t){t??={};const r=e=>{throw n.getLogger(this).error(".convertMesh()",e.message),e};await this.load(t),this.infoFor3D||r(new o("invalid:layer","SceneLayer has no capability for mesh conversion"));const i=await this.extractAndFilterFiles(e);y(t);const s=i.reduce((e,t)=>re(this.infoFor3D,t)?e+1:e,0);0===s&&r(new L),s>1&&r(new j);const a=this.spatialReference,l=t.origin,p=await b(l??t.defaultOrigin??new v({x:0,y:0,z:0,spatialReference:a}),a,t),d=a.isGeographic?"local":"georeferenced",{default:u}=await import("../geometry/Mesh.js");y(t);const c=u.createWithExternalSource(p,{type:"client",files:i},{vertexSpace:d,transform:le(a),unitConversionDisabled:!0}),[h]=await this.uploadAssets([c],{...t,useAssetOrigin:!l});return h}async extractAndFilterFiles(e){await this.load();const t=this.infoFor3D;if(!t)return e;return(await we(e)).filter(e=>ie(t,e))}validateLayer(e){if(e.layerType&&!Oe.has(e.layerType))throw new o("scenelayer:layer-type-not-supported","SceneLayer does not support this layer type",{layerType:e.layerType});if(isNaN(this.version.major)||isNaN(this.version.minor))throw new o("layer:service-version-not-supported","Service version is not supported.",{serviceVersion:this.version.versionString,supportedVersions:"1.x, 2.x"});if(this.version.major>2)throw new o("layer:service-version-too-new","Service version is too new.",{serviceVersion:this.version.versionString,supportedVersions:"1.x, 2.x"});function t(e,t){let r=!1,i=!1;if(null==e)r=!0,i=!0;else{const s=t&&t.isGeographic;switch(e){case"east-north-up":case"earth-centered":r=!0,i=s;break;case"vertex-reference-frame":r=!0,i=!s;break;default:r=!1}}if(!r)throw new o("scenelayer:unsupported-normal-reference-frame","Normal reference frame is invalid.");if(!i)throw new o("scenelayer:incompatible-normal-reference-frame","Normal reference frame is incompatible with layer spatial reference.")}t(this.normalReferenceFrame,this.spatialReference)}_getTypeKeywords(){const e=[];if("points"===this.profile)e.push("Point");else{if("mesh-pyramids"!==this.profile)throw new o("scenelayer:unknown-profile","SceneLayer:save() encountered an unknown SceneLayer profile: "+this.profile);e.push("3DObject")}return e}_populateFieldUsageInfo(){if(this._fieldUsageInfo={},this.fields)for(const e of this.fields){const t=!!this.attributeStorageInfo?.some(t=>t.name===e.name),r=!!this.associatedLayer?.fields?.some(t=>t&&e.name===t.name),i={supportsLabelingInfo:t,supportsRenderer:t,supportsPopupTemplate:t||r,supportsLayerQuery:r};this._fieldUsageInfo[e.name]=i}}_applyAssociatedLayerOverrides(){this._applyAssociatedLayerFieldsOverrides(),this._applyAssociatedLayerPropertyOverrides(),this._applyAssociatedLayerExtentOverride(),this._applyAssociatedLayerPrivileges()}_applyAssociatedLayerFieldsOverrides(){if(!this.associatedLayer?.fields)return;let e=null;for(const t of this.associatedLayer.fields){const r=this.getField(t.name);r?(!r.domain&&t.domain&&(r.domain=t.domain.clone()),r.editable=t.editable,r.nullable=t.nullable,r.length=t.length):(e||(e=this.fields?this.fields.slice():[]),e.push(t.clone()))}e&&this._set("fields",e)}_applyAssociatedLayerPropertyOverrides(){if(!this.associatedLayer)return;const e=["popupTemplate","popupEnabled","attributeTableTemplate"],t=g(this);for(let r=0;r<e.length;r++){const i=e[r],s=this.originIdOf(i),o=this.associatedLayer.originIdOf(i);s<o&&(2===o||3===o)&&t.setAtOrigin(i,this.associatedLayer[i],o)}}_applyAssociatedLayerExtentOverride(){const e=this.associatedLayer?.getAtOrigin("fullExtent","service");if(null==this.associatedLayer?.infoFor3D||!e||!U(this.associatedLayer?.url)||!ye(this))return;g(this).setAtOrigin("fullExtent",e.clone(),2)}_applyAssociatedLayerPrivileges(){const e=this.associatedLayer;e&&(this._set("userHasEditingPrivileges",e.userHasEditingPrivileges),this._set("userHasFullEditingPrivileges",e.userHasFullEditingPrivileges),this._set("userHasUpdateItemPrivileges",e.userHasUpdateItemPrivileges))}async _setAssociatedFeatureLayer(e){if(["mesh-pyramids","points"].includes(this.profile))try{const{serverUrl:t,layerId:r,portalItem:i}=await q(`${this.url}/layers/${this.layerId}`,{sceneLayerItem:this.portalItem,customParameters:this.customParameters,apiKey:this.apiKey,signal:e}),s=await ne.FeatureLayer();this.associatedLayer=new s({url:t,customParameters:this.customParameters,layerId:r,portalItem:i}),await this.associatedLayer.load()}catch(t){u(t)||this._logWarningOnPopupEnabled()}}async _logWarningOnPopupEnabled(){const e=new AbortController;this.addHandles(a(e));try{await h(()=>this.popupEnabled&&null!=this.popupTemplate,e.signal)}catch(r){return void c(r)}const t=`this SceneLayer: ${this.title}`;null==this.attributeStorageInfo?n.getLogger(this).warn(`Associated FeatureLayer could not be loaded and no binary attributes found. Popups will not work on ${t}`):n.getLogger(this).info(`Associated FeatureLayer could not be loaded. Falling back to binary attributes for Popups on ${t}`)}_validateElevationInfo(){const e=this.elevationInfo;"mesh-pyramids"===this.profile&&me(n.getLogger(this),ge("Mesh scene layers","relative-to-scene",e)),me(n.getLogger(this),ve("Scene layers",e))}async fetchStatistics(e,t){return await ue({fieldName:e,statisticsInfo:this.statisticsInfo,errorContext:"scenelayer",fieldsIndex:this.fieldsIndex,path:this.parsedUrl?.path??"",customParameters:this.customParameters,apiKey:this.apiKey,signal:t?.signal})}};e([f({types:{key:"type",base:H,typeMap:{selection:z}},json:{origins:{"web-scene":{name:"layerDefinition.featureReduction",write:{allowNull:!0}},"portal-item":{name:"layerDefinition.featureReduction",write:{allowNull:!0}}}}})],Pe.prototype,"featureReduction",void 0),e([f({type:[pe],json:{read:!1,origins:{"web-scene":{name:"layerDefinition.rangeInfos",write:!0},"portal-item":{name:"layerDefinition.rangeInfos",write:!0}}},clonable:!1})],Pe.prototype,"rangeInfos",void 0),e([f({json:{read:!1}})],Pe.prototype,"associatedLayer",void 0),e([f({type:["show","hide"]})],Pe.prototype,"listMode",void 0),e([f({type:["ArcGISSceneServiceLayer"]})],Pe.prototype,"operationalLayerType",void 0),e([f({json:{read:!1},readOnly:!0})],Pe.prototype,"type",void 0),e([f({..._e.fields,readOnly:!0,json:{read:!1,origins:{service:{read:!0}}}})],Pe.prototype,"fields",void 0),e([f()],Pe.prototype,"types",null),e([f()],Pe.prototype,"typeIdField",null),e([f()],Pe.prototype,"templates",null),e([f()],Pe.prototype,"formTemplate",null),e([f({readOnly:!0})],Pe.prototype,"graphicOrigin",void 0),e([f({readOnly:!0,clonable:!1})],Pe.prototype,"fieldsIndex",null),e([f({type:ae,json:{read:{source:"layerDefinition.floorInfo"},write:{target:"layerDefinition.floorInfo"}}})],Pe.prototype,"floorInfo",void 0),e([f(_e.outFields)],Pe.prototype,"outFields",void 0),e([f({type:X,readOnly:!0,json:{read:!1},clonable:!1})],Pe.prototype,"nodePages",void 0),e([Se("service","nodePages",["nodePages","pointNodePages"])],Pe.prototype,"readNodePages",null),e([f({type:[Y],readOnly:!0,clonable:!1})],Pe.prototype,"materialDefinitions",void 0),e([f({type:[ee],readOnly:!0,clonable:!1})],Pe.prototype,"textureSetDefinitions",void 0),e([f({type:[te],readOnly:!0,clonable:!1})],Pe.prototype,"geometryDefinitions",void 0),e([f({readOnly:!0})],Pe.prototype,"serviceUpdateTimeStamp",void 0),e([f({readOnly:!0})],Pe.prototype,"attributeStorageInfo",void 0),e([f({readOnly:!0})],Pe.prototype,"statisticsInfo",void 0),e([f({type:s.ofType(Number),nonNullable:!0,json:{origins:{service:{read:!1,write:!1}},name:"layerDefinition.excludeObjectIds",write:{enabled:!0}}})],Pe.prototype,"excludeObjectIds",void 0),e([f({type:String,json:{origins:{service:{read:!1,write:!1}},name:"layerDefinition.definitionExpression",write:{enabled:!0,allowNull:!0}}})],Pe.prototype,"definitionExpression",void 0),e([f({type:de,json:{name:"layerDefinition.polygonFilter",write:{enabled:!0,allowNull:!0},origins:{service:{read:!1,write:!1}}}})],Pe.prototype,"filter",void 0),e([f({type:String,json:{origins:{"web-scene":{read:!0,write:!0}},read:!1}})],Pe.prototype,"path",void 0),e([f(C)],Pe.prototype,"elevationInfo",null),e([f({readOnly:!0,json:{read:!1}})],Pe.prototype,"effectiveCapabilities",null),e([f({readOnly:!0})],Pe.prototype,"effectiveEditingEnabled",null),e([f({type:String})],Pe.prototype,"geometryType",null),e([f(N)],Pe.prototype,"labelsVisible",void 0),e([f({type:[se],json:{origins:{service:{name:"drawingInfo.labelingInfo",read:{reader:oe},write:!1}},name:"layerDefinition.drawingInfo.labelingInfo",read:{reader:oe},write:!0}})],Pe.prototype,"labelingInfo",void 0),e([f(G)],Pe.prototype,"legendEnabled",void 0),e([f({type:Number,json:{origins:{"web-document":{default:1,write:{enabled:!0,target:{opacity:{type:Number},"layerDefinition.drawingInfo.transparency":{type:Number}}},read:{source:["opacity","layerDefinition.drawingInfo.transparency"],reader(e,t){if("number"==typeof e&&e>=0&&e<=1)return e;const r=t.layerDefinition?.drawingInfo?.transparency;return void 0!==r?Fe(r):void 0}}},"portal-item":{write:!0},service:{read:!1}}}})],Pe.prototype,"opacity",void 0),e([f({type:["Low","High"],readOnly:!0,json:{read:!1,origins:{service:{read:!0}}}})],Pe.prototype,"priority",void 0),e([f({type:["Labels"],readOnly:!0,json:{read:!1,origins:{service:{read:!0}}}})],Pe.prototype,"semantic",void 0),e([f({types:he,json:{origins:{service:{read:{source:"drawingInfo.renderer"}}},name:"layerDefinition.drawingInfo.renderer",write:!0},value:null})],Pe.prototype,"renderer",null),e([f({json:{read:!1}})],Pe.prototype,"cachedDrawingInfo",void 0),e([Se("service","cachedDrawingInfo")],Pe.prototype,"readCachedDrawingInfo",null),e([f({readOnly:!0,json:{read:!1}})],Pe.prototype,"capabilities",null),e([f({type:Boolean,json:{read:!1}})],Pe.prototype,"editingEnabled",null),e([f({readOnly:!0,json:{write:!1,read:!1}})],Pe.prototype,"infoFor3D",null),e([f({readOnly:!0,json:{write:!1,read:!1}})],Pe.prototype,"relationships",null),e([f(Q)],Pe.prototype,"popupEnabled",void 0),e([f({type:r,json:{name:"popupInfo",write:!0}})],Pe.prototype,"popupTemplate",void 0),e([f({readOnly:!0,json:{read:!1}})],Pe.prototype,"defaultPopupTemplate",null),e([f(V)],Pe.prototype,"attributeTableTemplate",void 0),e([f({type:String,json:{read:!1}})],Pe.prototype,"objectIdField",void 0),e([Se("service","objectIdField",["objectIdField","fields"])],Pe.prototype,"readObjectIdField",null),e([f({type:String,json:{read:!1}})],Pe.prototype,"globalIdField",void 0),e([Se("service","globalIdField",["globalIdField","fields"])],Pe.prototype,"readGlobalIdField",null),e([f({readOnly:!0,type:String,json:{read:!1}})],Pe.prototype,"displayField",null),e([f({type:String,json:{read:!1}})],Pe.prototype,"profile",void 0),e([Se("service","profile",["store.profile"])],Pe.prototype,"readProfile",null),e([f({readOnly:!0,type:String,json:{origins:{service:{read:{source:"store.normalReferenceFrame"}}},read:!1}})],Pe.prototype,"normalReferenceFrame",void 0),e([f(M)],Pe.prototype,"screenSizePerspectiveEnabled",void 0),e([f({json:{read:!1,origins:{service:{read:!0}}}})],Pe.prototype,"serviceItemId",void 0),e([f(E)],Pe.prototype,"useViewTime",null),Pe=e([m("esri.layers.SceneLayer")],Pe);const Ae={"mesh-pyramids":"mesh-pyramids",meshpyramids:"mesh-pyramids","features-meshes":"mesh-pyramids",points:"points","features-points":"points",lines:"lines","features-lines":"lines",polygons:"polygons","features-polygons":"polygons"},Te={"mesh-pyramids":"mesh",points:"point"},xe=Pe;export{xe 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/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../request.js";import has from"../core/has.js";import s from"../core/Logger.js";import{isAbortError as i}from"../core/promiseUtils.js";import{watch as r,initial as a}from"../core/reactiveUtils.js";import{convertTime as n}from"../core/timeUtils.js";import{property as l,subclass as o}from"../core/accessorSupport/decorators.js";import{C as h}from"../chunks/vec32.js";import{create as d}from"../core/libs/gl-matrix-2/factories/vec3f64.js";import{renderSRFromViewSR as u}from"../geometry/support/coordinateSystem.js";import{loadVoxelWASM as _}from"../libs/vxl/VxlModule.js";import{VoxelGraphic as c}from"../views/3d/layers/VoxelGraphic.js";import{VoxelTarget as m}from"../views/3d/layers/i3s/Intersector.js";import{Frustum as g}from"../views/3d/state/Frustum.js";import{RenderCoordsHelper as f}from"../views/3d/support/RenderCoordsHelper.js";import{SyncRenderPlugin as p}from"../views/3d/webgl-engine/effects/RenderPlugin.js";import{IntersectorResult as y}from"../views/3d/webgl-engine/lib/IntersectorResult.js";let x=class extends p{constructor(e){super(e),this._halfIntTexturesAvailable=!1,this._textureFloatLinearAvailable=!1,this._havePreparedWithAllLayers=!1,this._renderPluginContext=null,this._vxlPromise=null,this._vxl=null,this._pluginIsActive=!1,this._moreToLoad=!1,this._viewportWidth=-1,this._viewportHeight=-1,this._newLayers=[],this._layers=new Map,this._rctx=null,this._renderTargetToRestore=null,this._lastFrameWasStationary=!1,this._wasmMemBlockSizes=[512,1024,2048,4096,8192,16384,32768,65536],this._wasmMemBlocks=new Map,this._dbgFlags=new Set,this._captureFrustum=!1,this._frustum=null,this._frustumRenderableId=-1,this._renderCoordsHelper=null,this.produces=new Map([[20,()=>!!this._vxl&&"local"===this.view.viewingMode]]),this.type=9,this.slicePlaneEnabled=!0,this.isGround=!1,this.layerViewUid=[]}_dbg(e,t){this._dbgFlags.has(e)&&(4===e?s.getLogger(this).error(t):s.getLogger(this).warn(t))}_removeRenderPlugin(){this._pluginIsActive&&this.view.stage&&(this._dbg(1,"--removeRenderPlugin--"),this.view.stage.removeRenderPlugin(this)),this._pluginIsActive=!1}initialize(){this._dbg(1,"--initialize--");for(const e of this._wasmMemBlockSizes)this._wasmMemBlocks.set(e,0);this.addHandles([r(()=>this.view.ready,e=>{e&&"local"===this.view.viewingMode?(this._dbg(1,"view ready status changed to ready on a local view, calling addRenderPlugin"),this.view.stage.addRenderPlugin(this),this._pluginIsActive=!0):(this._dbg(1,"view ready status changed, not ready or not a local view!"),this._removeRenderPlugin())},a),r(()=>this.view?.qualityProfile,e=>{this._dbg(3,"qualityProfile changed to "+e),this._vxl&&this._vxl.set_quality(this._toWasmQuality(e))},a),r(()=>this.view?.timeExtent,()=>{if(this._vxl){const e=this._getTimeArgs(this.view?.timeExtent);this._dbg(3,"sceneView timeExtent changed to useTime="+e.hasTime+" st="+e.startTime+" et="+e.endTime),this._vxl.set_scene_time_extent(e.startTime,e.endTime,e.hasTime),this._renderPluginContext.requestRender()}},a),r(()=>this.view?.stationary,e=>{this._vxl&&e&&!this._lastFrameWasStationary&&this._renderPluginContext.requestRender()})])}initializeRenderContext(e){this._dbg(1,"--initializeRenderContext--");const t=e.renderContext.rctx;this._renderPluginContext=e,this._rctx=e.renderContext.rctx,this._halfIntTexturesAvailable=!!this._rctx.capabilities.textureNorm16,this._textureFloatLinearAvailable=this._rctx.capabilities.textureFloatLinear,this._initializeWasm(t.gl)}uninitializeRenderContext(){this._renderPluginContext=null,this._rctx=null,this._dbg(1,"--uninitializeRenderContext--")}_restoreFramebuffer(){if(!this._renderTargetToRestore)return;const e=this._renderTargetToRestore.fbo;if(!!!this._rctx)return void this._dbg(4,"no context in restoreFramebuffer!");this._rctx.bindFramebuffer(e,!0);const t=this._renderTargetToRestore.viewport;this._rctx.setViewport(t.x,t.y,t.width,t.height)}_bindPreviousDepthToSlot(e,t){const s=!!this._rctx,i=!!this._renderTargetToRestore;if(!s||!i)return 0;const r=this._renderTargetToRestore.fbo.depthStencilTexture;return r?(0===t?this._rctx.bindTexture(null,e,!0):this._rctx.bindTexture(r,e,!0),1):(this._dbg(4,"no depth/stencil texture exists!"),0)}_modifyResourceCount(e,t,s){if(!this._rctx)return void this._dbg(4,"modifyAllocation callback has no rendering context!");const i=e;1===s?this._rctx.instanceCounter.increment(i,t):this._rctx.instanceCounter.decrement(i,t)}_setBlendState(e,t,s,i){this._rctx?(this._rctx.setBlendingEnabled(1===e),this._rctx.setBlendFunction(t,s),this._rctx.setBlendEquation(i)):this._dbg(4,"setBlendState callback has no rendering context!")}_setFrontFace(e){this._rctx?this._rctx.setFrontFace(e):this._dbg(4,"setFrontFace callback has no rendering context!")}_setDepthStencilStateFunction(e,t,s){this._rctx?(this._rctx.setDepthFunction(s),this._rctx.setDepthTestEnabled(1===e),this._rctx.setDepthWriteEnabled(1===t),this._rctx.setStencilTestEnabled(!1),this._rctx.setStencilFunction(519,0,255),this._rctx.setStencilOpSeparate(1028,7680,7682,7680),this._rctx.setStencilOpSeparate(1029,7680,7683,7680)):this._dbg(4,"setDepthStencilStateFunction callback has no rendering context!")}_setRasterizerState(e){if(this._rctx)switch(e){case 1:this._rctx.setFaceCullingEnabled(!1);break;case 3:this._rctx.setCullFace(1029),this._rctx.setFaceCullingEnabled(!0);break;case 2:this._rctx.setCullFace(1028),this._rctx.setFaceCullingEnabled(!0)}else this._dbg(4,"setRasterizerState callback has no rendering context!")}_setViewport(e,t,s,i){this._rctx?this._rctx.setViewport(e,t,s,i):this._dbg(4,"setViewport callback has no rendering context!")}_updateMemoryUsage(){this._layers.forEach((e,t)=>{if(e.needMemoryUsageUpdate){const s=this._vxl.estimate_memory_usage(t);s>=0&&(e.needMemoryUsageUpdate=!1,e.layerView.setUsedMemory(s))}})}_syncRequestsResponses(){this._layers.forEach((e,s)=>{const r=[];e.responses.forEach((t,i)=>{r.push(i),this._dbg(2,"responding for requestID:"+i+" size:"+t.size),this._vxl.respond(s,i,t),0!==t.requestType&&4!==t.requestType||(e.needMemoryUsageUpdate=!0)});const a=e.responses;for(const t of r)a.delete(t);const n=this._vxl.get_new_requests(s),l=e.abortController.signal;for(const o in n){e.outstandingRequestCount+=1,1===e.outstandingRequestCount&&e.layerView.updatingFlagChanged();const s=n[o],r={responseType:"array-buffer",signal:l,query:{...e.layerView.layer.customParameters,token:e.layerView.layer.apiKey}};this._dbg(2,"making requestID:"+o+" url:"+s.url),t(s.url,r).then(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),this._dbg(2,"have response for requestID:"+o);let i=0;if(t.data.byteLength>0){i=this._vxl._malloc(t.data.byteLength);const e=new Uint8Array(this._vxl.HEAPU8.buffer,i,t.data.byteLength),s=new Uint8Array(t.data);for(let i=0;i<t.data.byteLength;++i)e[i]=s[i]}a.set(+o,{responseType:s.responseType,ptr:i,size:t.data.byteLength,success:!0,requestType:s.requestType})}).catch(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),i(t)||(this._dbg(4,`requestID:${o} failed, error=${t.toString()}`),a.set(+o,{responseType:s.responseType,ptr:0,size:0,success:!1,requestType:s.requestType}))})}})}updateWasmCamera(e){this._vxl.set_projection_matrix.apply(this._vxl,e.projectionMatrix),this._vxl.set_view_matrix.apply(this._vxl,e.viewMatrix),this._vxl.set_near_far(e.near,e.far)}isUpdating(e){if(!this._vxl&&this._vxlPromise)return!0;const t=this._layers.get(e);return!!t&&t.outstandingRequestCount>0}getLayerTimes(e){const t=[];return this._layers.forEach((s,i)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const s=this._vxl.get_layer_epoch_times(i,e.layer.currentVariableId);for(let e=0;e<s.length;++e)t.push(s[e])}}),t}getCurrentLayerTimeIndex(e){let t=0;return this._layers.forEach((s,i)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(t=this._vxl.get_layer_current_time_id(i))}),t}setEnabled(e,t){this._layers.forEach((s,i)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl.set_enabled(i,t),s.needMemoryUsageUpdate=!0,this._renderPluginContext.requestRender())})}setIsInScaleRange(e,t){const s=this._layers.get(e.wasmLayerId);s&&t!==s.isInScaleRange&&(s.isInScaleRange=t,this._vxl.set_is_in_scale_range(e.wasmLayerId,t),s.needMemoryUsageUpdate=!t,this._renderPluginContext.requestRender())}setStaticSections(e,t){const s={mask:1,staticSections:t};return this._doMaskedUIUpdate(e,s,!0)}setCurrentVariable(e,t){const s={mask:1024,currentVariable:t};return this._doMaskedUIUpdate(e,s,!0)}setRenderMode(e,t){const s={mask:8192,renderMode:t};return this._doMaskedUIUpdate(e,s,!0)}setVerticalExaggerationAndOffset(e,t,s,i){const r={mask:256,volStyleDesc:{volumeId:t,verticalExaggeration:s,verticalOffset:i}};return this._doMaskedUIUpdate(e,r,!0)}setVariableStyles(e,t){const s={mask:32768,variableStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setVolumeStyles(e,t){const s={mask:65536,volumeStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setEnableDynamicSections(e,t){const s={mask:4096,containerIsVisible:t,container:1};return this._doMaskedUIUpdate(e,s,!0)}setEnableIsosurfaces(e,t){const s={mask:4096,containerIsVisible:t,container:0};return this._doMaskedUIUpdate(e,s,!0)}setEnableSections(e,t){const s={mask:4096,containerIsVisible:t,container:2};return this._doMaskedUIUpdate(e,s,!0)}setAnalysisSlice(e,t,s,i){const r={mask:131072,analysisSlice:{point:s,normal:i,enabled:t}};return this._doMaskedUIUpdate(e,r,!0)}updateLayerTimeProperties(e){if(!this._vxl)return;const t=this._layers.get(e.wasmLayerId);if(t){const s=t.layerView.layer;let i=0;s.timeOffset&&(i=n(s.timeOffset.value,s.timeOffset.unit,"seconds"));const r=this._getTimeArgs(s.timeExtent);this._vxl.set_layer_time_properties(e.wasmLayerId,r.startTime,r.endTime,r.hasTime,s.useViewTime,i),this._renderPluginContext.requestRender()}}_doMaskedUIUpdate(e,t,s){if(!this._vxl)return!1;let i=!1;return this._layers.forEach((s,r)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const e={str:JSON.stringify(t),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(i=1===this._vxl.handle_masked_ui_update(r,e.ptr,e.byteCount),e.isReusable||this._vxl._free(e.ptr))}}),i&&s&&this._renderPluginContext.requestRender(),i}_addTriangleToWasmBuffer(e,t,s,i,r){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],e[3*(t+=1)]=i[0],e[3*t+1]=i[1],e[3*t+2]=i[2],e[3*(t+=1)]=r[0],e[3*t+1]=r[1],e[3*t+2]=r[2],t+=1}_addNormalToWasmBuffer(e,t,s){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],t+=1}_doCaptureFrustum(){if(!this._vxl)return;const e=36,t=e/3,s=this._vxl._malloc(3*e*Float32Array.BYTES_PER_ELEMENT),i=new Float32Array(this._vxl.HEAPF32.buffer,s,3*e),r=this._vxl._malloc(3*t*Float32Array.BYTES_PER_ELEMENT),a=new Float32Array(this._vxl.HEAPF32.buffer,r,e),n=this._frustum.points[0],l=this._frustum.points[1],o=this._frustum.points[2],h=this._frustum.points[3],d=this._frustum.points[4],u=this._frustum.points[5],_=this._frustum.points[6],c=this._frustum.points[7];let m=0,g=0;const f=this._frustum.planes[4];m=this._addTriangleToWasmBuffer(i,m,o,l,n),g=this._addNormalToWasmBuffer(a,g,f),m=this._addTriangleToWasmBuffer(i,m,n,h,o),g=this._addNormalToWasmBuffer(a,g,f);const p=this._frustum.planes[5];m=this._addTriangleToWasmBuffer(i,m,d,u,_),g=this._addNormalToWasmBuffer(a,g,p),m=this._addTriangleToWasmBuffer(i,m,_,c,d),g=this._addNormalToWasmBuffer(a,g,p);const y=this._frustum.planes[3];m=this._addTriangleToWasmBuffer(i,m,_,o,h),g=this._addNormalToWasmBuffer(a,g,y),m=this._addTriangleToWasmBuffer(i,m,h,c,_),g=this._addNormalToWasmBuffer(a,g,y);const x=this._frustum.planes[2];m=this._addTriangleToWasmBuffer(i,m,n,l,u),g=this._addNormalToWasmBuffer(a,g,x),m=this._addTriangleToWasmBuffer(i,m,u,d,n),g=this._addNormalToWasmBuffer(a,g,x);const v=this._frustum.planes[0];m=this._addTriangleToWasmBuffer(i,m,h,n,d),g=this._addNormalToWasmBuffer(a,g,v),m=this._addTriangleToWasmBuffer(i,m,d,c,h),g=this._addNormalToWasmBuffer(a,g,v);const b=this._frustum.planes[1];m=this._addTriangleToWasmBuffer(i,m,o,_,u),g=this._addNormalToWasmBuffer(a,g,b),m=this._addTriangleToWasmBuffer(i,m,u,l,o),g=this._addNormalToWasmBuffer(a,g,b),-1!==this._frustumRenderableId&&this._vxl.remove_generic_mesh(this._frustumRenderableId),this._frustumRenderableId=this._vxl.add_generic_mesh(s,3*e,r,e,255,0,0,64),this._vxl._free(s),this._vxl._free(r),this._captureFrustum=!1,this._renderPluginContext.requestRender()}captureFrustum(){null===this._renderCoordsHelper&&(this._renderCoordsHelper=f.create(2,u(!1,this.view.spatialReference))),null===this._frustum&&(this._frustum=new g(this._renderCoordsHelper)),this._captureFrustum=!0,null!==this._renderPluginContext&&this._renderPluginContext.requestRender()}toggleFullVolumeExtentDraw(e){this._vxl&&this._layers.forEach((t,s)=>{t.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl.toggle_full_volume_extent_draw(s),this._renderPluginContext.requestRender())})}dropQueryRenderTarget(){this._vxl&&this._vxl.drop_query_rt()}addVoxelLayer(e){if(!this._vxl){const t={layerView:e,resolveCallback:null,rejectCallback:null},s=new Promise((e,s)=>{t.resolveCallback=e,t.rejectCallback=s});return this._newLayers.push(t),s}const t=this._addVoxelLayer(e);return t<0?Promise.reject(-1):Promise.resolve(t)}removeVoxelLayer(e){if(!this._vxl){const t=this._newLayers.findIndex(t=>e.uid===t.layerView.uid);t>=0&&(this._newLayers[t].resolveCallback(-1),this._newLayers.splice(t,1));const s=this._newLayers.length;return 0===s&&(this._dbg(1," no voxel layers left after removing a layer, removing RenderPlugin and destroying"),this.destroy()),s}let t=-1;this._layers.forEach((s,i)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){t=i,s.abortController.abort(),this._vxl.remove_layer(t);const r=this.layerViewUid.indexOf(e.uid);-1!==r&&this.layerViewUid.splice(r,1)}}),t>=0&&this._layers.delete(t);const s=this._layers.size;return 0===s&&(this._dbg(1," no voxel layers left after removing a layer, removing RenderPlugin and destroying"),this.destroy()),s}_getBlockSize(e){for(const t of this._wasmMemBlockSizes)if(e<t)return t;return-1}_allocateBlock(e){e.byteCount=this._vxl.lengthBytesUTF8(e.str)+1;const t=this._getBlockSize(e.byteCount);return t<0?(e.isReusable=!1,e.ptr=this._vxl._malloc(e.byteCount)):(e.isReusable=!0,e.ptr=this._wasmMemBlocks.get(t),0===e.ptr&&(e.ptr=this._vxl._malloc(t),this._wasmMemBlocks.set(t,e.ptr))),0!==e.ptr&&(this._vxl.stringToUTF8(e.str,e.ptr,e.byteCount),!0)}_getTimeArgs(e){let t=-Number.MAX_VALUE,s=Number.MAX_VALUE,i=!1;return null!=e&&(e.isAllTime?i=!0:(null!=e.start&&(i=!0,t=e.start.getTime()/1e3),null!=e.end&&(i=!0,s=e.end.getTime()/1e3))),{startTime:t,endTime:s,hasTime:i}}_addVoxelLayer(e){const t=e.layer;let i=-1;const r=t.getConfiguration();if(r.length<1)return-1;const a={str:r,byteCount:0,ptr:0,isReusable:!1};if(!this._allocateBlock(a))return-1;const l=this._getTimeArgs(t.timeExtent),o=this.view.spatialReference.isWGS84&&t.spatialReference.isWGS84?111319.49079327357:1;let h=0;if(t.timeOffset&&(h=n(t.timeOffset.value,t.timeOffset.unit,"seconds")),i=this._vxl.add_layer(t.serviceRoot,a.ptr,a.byteCount,o,o,l.startTime,l.endTime,l.hasTime,t.useViewTime,h,this._toWasmQuality(this.view.qualityProfile)),a.isReusable||this._vxl._free(a.ptr),i>=0){t.test?.constantUpscaling&&(this._setUpscalingLimits(0,.25,.25),this._setUpscalingLimits(1,.5,.5),this._setUpscalingLimits(2,.75,.75));const r=new AbortController;if(this._layers.set(i,{layerView:e,responses:new Map,outstandingRequestCount:0,abortController:r,needMemoryUsageUpdate:!1,isInScaleRange:!0}),this.layerViewUid.push(e.uid),!this._halfIntTexturesAvailable||has("mac")){const t=[];let i="";for(const s of e.layer.variables)"Int16"!==s.renderingFormat.type&&"UInt16"!==s.renderingFormat.type||(t.push(s.name),s.id===e.layer.currentVariableId&&(i=s.name));""!==i&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${i}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}if(!this._textureFloatLinearAvailable){const t=[];let i="";for(const s of e.layer.variables)"Float32"===s.renderingFormat.type&&(t.push(s.name),s.id===e.layer.currentVariableId&&(i=s.name));""!==i&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${i}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}return has("esri-mobile")&&s.getLogger(this).warnOnce("Mobile support differs across devices. Voxel layer might not display as expected."),i}return-1}prepareRender(e){if(!this._vxl)return;const t=e.bind.camera.viewForward,s=e.bind.camera.eye;this._vxl.update_camera_pos_and_direction(s[0],s[1],s[2],t[0],t[1],t[2]);const i=this._vxl.cull();this._dbg(2,"missingResourceCount="+i),this._moreToLoad=i>0,this._havePreparedWithAllLayers=0===this._newLayers.length,this._updateMemoryUsage()}acquireTechniques(){return[]}render(e){if(!this._vxl)return;for(const s of this._newLayers){const e=this._addVoxelLayer(s.layerView);-1===e?s.rejectCallback(-1):s.resolveCallback(e)}if(this._newLayers=[],0===this._layers.size)return void this._dbg(4,"No voxel layers but RenderPlugin instance is being asked to render!");this._lastFrameWasStationary=this.view.stationary,this._syncRequestsResponses(),this._beforeDraw(),this._vxl.begin_color_frame(!this.view.stage.renderer.isFeatureEnabled(2),e.bind.lighting.mainLight.direction[0],e.bind.lighting.mainLight.direction[1],e.bind.lighting.mainLight.direction[2]);const t=this._renderTargetToRestore.viewport;t.width===this._viewportWidth&&t.height===this._viewportHeight||(this._viewportWidth=t.width,this._viewportHeight=t.height,this._vxl.set_viewport(t.width,t.height),this._layers.forEach(e=>{e.needMemoryUsageUpdate=!0})),0===t.x&&0===t.y||this._dbg(4,"Unsupported viewport parameters detected!"),this.updateWasmCamera(e.bind.camera),this._captureFrustum&&(this._frustum.update(e.bind.camera),this._doCaptureFrustum()),this._vxl.draw(),this._afterDraw(),(this._moreToLoad||!this._havePreparedWithAllLayers&&this._layers.size>0)&&this._renderPluginContext.requestRender()}destroy(){this._dbg(1,"--destroy--"),this._vxl&&(this._layers.forEach(e=>{e.abortController.abort()}),this._wasmMemBlocks.forEach(e=>{0!==e&&this._vxl._free(e)}),this._vxl.uninitialize_voxel_wasm(),this._removeRenderPlugin(),this._vxl=null)}_initializeWasm(e){return this._vxl?Promise.resolve():(this._vxlPromise||(this._vxlPromise=_(e).then(t=>{if(t.specialHTMLTargets.jsAPI3DRenderingContext=e,this._vxl=t,this._vxlPromise=null,this._newLayers.length<=0)return this._dbg(1," no voxel layers left after WASM downloaded, removing RenderPlugin and destroying"),void this.destroy();const s=this._getTimeArgs(this.view?.timeExtent),i=this._vxl.addFunction(this._restoreFramebuffer.bind(this),"v"),r=this._vxl.addFunction(this._setBlendState.bind(this),"viiii"),a=this._vxl.addFunction(this._setFrontFace.bind(this),"vi"),n=this._vxl.addFunction(this._setRasterizerState.bind(this),"vi"),l=this._vxl.addFunction(this._setDepthStencilStateFunction.bind(this),"viii"),o=this._vxl.addFunction(this._setViewport.bind(this),"viiii"),h=this._vxl.addFunction(this._bindPreviousDepthToSlot.bind(this),"iii"),d=this._vxl.addFunction(this._modifyResourceCount.bind(this),"viii"),u=this._halfIntTexturesAvailable&&!has("mac"),_=this._textureFloatLinearAvailable;this._vxl.initialize_voxel_wasm(i,r,a,n,l,o,h,d,s.startTime,s.endTime,s.hasTime,u,_),this._renderPluginContext&&this._renderPluginContext.requestRender()}).catch(()=>{for(const e of this._newLayers)e.rejectCallback(-2);this._dbg(4," WASM failed to download, removing RenderPlugin and destroying"),this.destroy()})),this._vxlPromise)}pickDepth(e,t,s){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const i=s.viewport[3]-t;if(e<0||e>s.viewport[2]||t<0||t>s.viewport[3])return this._dbg(4,`[js] pickDepth: outOfRange, screenXY=[${e.toFixed(0)}, ${i.toFixed(0)}]]`),null;this._beforeDraw();const r=s.viewForward,a=s.eye;this._vxl.update_camera_pos_and_direction(a[0],a[1],a[2],r[0],r[1],r[2]),this.updateWasmCamera(s),this._vxl.begin_frame();const n=this._vxl.pick_depth(e,i);if(this._afterDraw(),n.success){return n.distanceToCamera}return null}pickObject(e,t,s,i){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const r=Math.round(e),a=Math.round(t);if(r<0||r>s.viewport[2]||a<0||a>s.viewport[3])return this._dbg(4,`[js] pickObject: outOfRange, screenXY=[${r}, ${a}], vp=[${s.viewport.toString()}]`),null;this._beforeDraw();const n=s.viewForward,l=s.eye;this._vxl.update_camera_pos_and_direction(l[0],l[1],l[2],n[0],n[1],n[2]),this.updateWasmCamera(s),this._vxl.begin_frame();let o=null;if(0===i.length)o=this._vxl.pick_object(r,a,0,0);else{const e={str:JSON.stringify({layerIds:i}),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(o=this._vxl.pick_object(r,a,e.ptr,e.byteCount),e.isReusable||this._vxl._free(e.ptr))}return this._afterDraw(),o}async getOtherFieldPopupValues(e,s){for(const i of e){const e=i.gpuResult;if(!e)continue;const r=this._layers.get(e.layerId);if(!r||!r.layerView.layer.url)continue;const a=r.layerView.layer,n={responseType:"array-buffer",signal:r.abortController.signal,query:{...r.layerView.layer.customParameters,token:r.layerView.layer.apiKey}},l=e.voxelSpacePosition,o=[Math.floor(l[0]/32),Math.floor(l[1]/32),Math.floor(l[2]/32)],h=[-4&o[0],-4&o[1],-4&o[2]];let d=0;if(e.epochTime){const t=this._vxl.get_layer_epoch_times(r.layerView.wasmLayerId,a.currentVariableId);for(let s=0;s<t.length;++s)if(t[s]===e.epochTime/1e3){d=s;break}}const u=[],_={varIds:[],ptrs:[],sizes:[]};for(const i of s){const e=a.variables.findIndex(e=>e.name===i);if(-1===e)continue;const s=a.variables.getItemAt(e)?.id;if(null==s)continue;const r=`${a.url}/variables/${s}/${d}/bundles/0/${h[0]}-${h[1]}-${h[2]}`;u.push(t(r,n).then(e=>e.data)),_.varIds.push(s)}const c=await Promise.allSettled(u),m=c.length;for(let t=0;t<m;++t){const e=c[t];if("fulfilled"===e.status){const t=e.value,s=this._vxl._malloc(t.byteLength);new Uint8Array(this._vxl.HEAPU8.buffer,s,t.byteLength).set(new Uint8Array(t)),_.ptrs.push(s),_.sizes.push(t.byteLength)}else _.varIds.splice(t,1)}const g=this._vxl.get_other_field_popup_values(e,_);for(let t=0;t<_.ptrs.length;++t)this._vxl._free(_.ptrs[t]);if(g.continuousValues)for(const t in g.continuousValues)i.attributes[t]=g.continuousValues[t];if(g.uniqueValues)for(const t in g.uniqueValues)i.attributes[t]=g.uniqueValues[t]}return e}_beforeDraw(){this._renderTargetToRestore={fbo:this._rctx.getBoundFramebufferObject(),viewport:this._rctx.getViewport()},this._rctx.setPolygonOffsetFillEnabled(!1),this._rctx.setScissorTestEnabled(!1),this._rctx.setColorMask(!0,!0,!0,!0)}_afterDraw(){this._renderTargetToRestore.fbo=null,this._rctx.externalTextureUnitUpdate(this._vxl.get_texture_units_bound_in_frame(),this._vxl.get_active_texture_unit()),this._rctx.externalVertexArrayObjectUpdate(),this._rctx.externalVertexBufferUpdate(),this._rctx.externalProgramUpdate()}intersect(e,t,s,i,r){if(!this._vxl||!this._rctx||0===this._layers.size||!e.options.selectionMode||e.options.isFiltered||!e.camera)return;if(null==r||r[0]<0||r[0]>e.camera.viewport[2]||r[1]<0||r[1]>e.camera.viewport[3])return this._dbg(4,r?`[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=[${r[0].toFixed(0)}, ${r[1].toFixed(0)}]`:"[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=null"),null;const a=[];this._layers.forEach(t=>{e.options.filteredLayerViewUids.includes(t.layerView.uid)&&a.push(t.layerView.wasmLayerId)});const n=this.pickObject(r[0],r[1],e.camera,a);if(null==n||-1===n.layerId)return;const l=this._layers.get(n.layerId);if(l){const t=l.layerView.layer.uid,r=n.distanceToCamera/h(s,i),a=d();a[0]=n.worldX,a[1]=n.worldY,a[2]=n.worldZ;const o={},u=l.layerView.layer,_=u.variables.findIndex(e=>e.id===u.currentVariableId);if(_>=0){const e=u.variables.getItemAt(_);null!=e&&(null!=n.continuousValue?o[e.name]=n.continuousValue:null!=n.uniqueValueLabel&&null!=n.uniqueValue?o[e.name]=`${n.uniqueValueLabel} (${n.uniqueValue})`:null!=n.uniqueValue&&(o[e.name]=`${n.uniqueValue}`),e.description.length>0?o["Voxel.CurrentVariable"]=e.description:e.name?.length>0&&(o["Voxel.CurrentVariable"]=e.name))}if(o["Voxel.Position"]=`[${n.voxelSpacePosition.toString()}]`,null!=n.epochTime&&null!=n.nativeTime&&null!=n.nativeTimeUnits){const e=new Date(n.epochTime);o["Voxel.LocalTime"]=e,o["Voxel.SourceTime"]=`${n.nativeTime.toLocaleString()} ${n.nativeTimeUnits}`}null!=n.depth&&(o["Voxel.Depth"]=n.depth);const c=n.faceNormal;o["Voxel.WorldPosition"]=`[${a[0]}, ${a[1]}, ${a[2]}]`;const g=e=>{const s=new m(a,t,()=>this._createVoxelGraphic(l.layerView.layer,o,n));e.set(this.type,s,r,c)},f=e.results,p=2===e.options.store;if((null==f.min.distance||r<f.min.distance)&&g(f.min),(null==f.max.distance||r>f.max.distance)&&g(f.max),p){const t=new y(e.ray);g(t),e.results.all.push(t)}}}_createVoxelGraphic(e,t,s){return new c({layer:e,sourceLayer:e,origin:e.graphicOrigin,attributes:t,gpuResult:s})}_toWasmQuality(e){switch(e){case"low":return 0;case"medium":return 1;case"high":return 2}}_setUpscalingLimits(e,t,s){this._vxl&&this._vxl.set_upscaling_limits(e,t,s)}hasHighlight(){return!1}};e([l({constructOnly:!0})],x.prototype,"view",void 0),x=e([o("esri.layers.VoxelWasmPerSceneView")],x);const v=x;export{v as default};
5
+ import{__decorate as e}from"tslib";import t from"../request.js";import has from"../core/has.js";import s from"../core/Logger.js";import{isAbortError as i}from"../core/promiseUtils.js";import{watch as r,initial as a}from"../core/reactiveUtils.js";import{convertTime as n}from"../core/timeUtils.js";import{property as l,subclass as o}from"../core/accessorSupport/decorators.js";import{D as h}from"../chunks/vec32.js";import{create as d}from"../core/libs/gl-matrix-2/factories/vec3f64.js";import{renderSRFromViewSR as u}from"../geometry/support/coordinateSystem.js";import{loadVoxelWASM as _}from"../libs/vxl/VxlModule.js";import{VoxelGraphic as c}from"../views/3d/layers/VoxelGraphic.js";import{VoxelTarget as m}from"../views/3d/layers/i3s/Intersector.js";import{Frustum as g}from"../views/3d/state/Frustum.js";import{RenderCoordsHelper as f}from"../views/3d/support/RenderCoordsHelper.js";import{SyncRenderPlugin as p}from"../views/3d/webgl-engine/effects/RenderPlugin.js";import{IntersectorResult as y}from"../views/3d/webgl-engine/lib/IntersectorResult.js";let x=class extends p{constructor(e){super(e),this._halfIntTexturesAvailable=!1,this._textureFloatLinearAvailable=!1,this._havePreparedWithAllLayers=!1,this._renderPluginContext=null,this._vxlPromise=null,this._vxl=null,this._pluginIsActive=!1,this._moreToLoad=!1,this._viewportWidth=-1,this._viewportHeight=-1,this._newLayers=[],this._layers=new Map,this._rctx=null,this._renderTargetToRestore=null,this._lastFrameWasStationary=!1,this._wasmMemBlockSizes=[512,1024,2048,4096,8192,16384,32768,65536],this._wasmMemBlocks=new Map,this._dbgFlags=new Set,this._captureFrustum=!1,this._frustum=null,this._frustumRenderableId=-1,this._renderCoordsHelper=null,this.produces=new Map([[20,()=>!!this._vxl&&"local"===this.view.viewingMode]]),this.type=9,this.slicePlaneEnabled=!0,this.isGround=!1,this.layerViewUid=[]}_dbg(e,t){this._dbgFlags.has(e)&&(4===e?s.getLogger(this).error(t):s.getLogger(this).warn(t))}_removeRenderPlugin(){this._pluginIsActive&&this.view.stage&&(this._dbg(1,"--removeRenderPlugin--"),this.view.stage.removeRenderPlugin(this)),this._pluginIsActive=!1}initialize(){this._dbg(1,"--initialize--");for(const e of this._wasmMemBlockSizes)this._wasmMemBlocks.set(e,0);this.addHandles([r(()=>this.view.ready,e=>{e&&"local"===this.view.viewingMode?(this._dbg(1,"view ready status changed to ready on a local view, calling addRenderPlugin"),this.view.stage.addRenderPlugin(this),this._pluginIsActive=!0):(this._dbg(1,"view ready status changed, not ready or not a local view!"),this._removeRenderPlugin())},a),r(()=>this.view?.qualityProfile,e=>{this._dbg(3,"qualityProfile changed to "+e),this._vxl&&this._vxl.set_quality(this._toWasmQuality(e))},a),r(()=>this.view?.timeExtent,()=>{if(this._vxl){const e=this._getTimeArgs(this.view?.timeExtent);this._dbg(3,"sceneView timeExtent changed to useTime="+e.hasTime+" st="+e.startTime+" et="+e.endTime),this._vxl.set_scene_time_extent(e.startTime,e.endTime,e.hasTime),this._renderPluginContext.requestRender()}},a),r(()=>this.view?.stationary,e=>{this._vxl&&e&&!this._lastFrameWasStationary&&this._renderPluginContext.requestRender()})])}initializeRenderContext(e){this._dbg(1,"--initializeRenderContext--");const t=e.renderContext.rctx;this._renderPluginContext=e,this._rctx=e.renderContext.rctx,this._halfIntTexturesAvailable=!!this._rctx.capabilities.textureNorm16,this._textureFloatLinearAvailable=this._rctx.capabilities.textureFloatLinear,this._initializeWasm(t.gl)}uninitializeRenderContext(){this._renderPluginContext=null,this._rctx=null,this._dbg(1,"--uninitializeRenderContext--")}_restoreFramebuffer(){if(!this._renderTargetToRestore)return;const e=this._renderTargetToRestore.fbo;if(!!!this._rctx)return void this._dbg(4,"no context in restoreFramebuffer!");this._rctx.bindFramebuffer(e,!0);const t=this._renderTargetToRestore.viewport;this._rctx.setViewport(t.x,t.y,t.width,t.height)}_bindPreviousDepthToSlot(e,t){const s=!!this._rctx,i=!!this._renderTargetToRestore;if(!s||!i)return 0;const r=this._renderTargetToRestore.fbo.depthStencilTexture;return r?(0===t?this._rctx.bindTexture(null,e,!0):this._rctx.bindTexture(r,e,!0),1):(this._dbg(4,"no depth/stencil texture exists!"),0)}_modifyResourceCount(e,t,s){if(!this._rctx)return void this._dbg(4,"modifyAllocation callback has no rendering context!");const i=e;1===s?this._rctx.instanceCounter.increment(i,t):this._rctx.instanceCounter.decrement(i,t)}_setBlendState(e,t,s,i){this._rctx?(this._rctx.setBlendingEnabled(1===e),this._rctx.setBlendFunction(t,s),this._rctx.setBlendEquation(i)):this._dbg(4,"setBlendState callback has no rendering context!")}_setFrontFace(e){this._rctx?this._rctx.setFrontFace(e):this._dbg(4,"setFrontFace callback has no rendering context!")}_setDepthStencilStateFunction(e,t,s){this._rctx?(this._rctx.setDepthFunction(s),this._rctx.setDepthTestEnabled(1===e),this._rctx.setDepthWriteEnabled(1===t),this._rctx.setStencilTestEnabled(!1),this._rctx.setStencilFunction(519,0,255),this._rctx.setStencilOpSeparate(1028,7680,7682,7680),this._rctx.setStencilOpSeparate(1029,7680,7683,7680)):this._dbg(4,"setDepthStencilStateFunction callback has no rendering context!")}_setRasterizerState(e){if(this._rctx)switch(e){case 1:this._rctx.setFaceCullingEnabled(!1);break;case 3:this._rctx.setCullFace(1029),this._rctx.setFaceCullingEnabled(!0);break;case 2:this._rctx.setCullFace(1028),this._rctx.setFaceCullingEnabled(!0)}else this._dbg(4,"setRasterizerState callback has no rendering context!")}_setViewport(e,t,s,i){this._rctx?this._rctx.setViewport(e,t,s,i):this._dbg(4,"setViewport callback has no rendering context!")}_updateMemoryUsage(){this._layers.forEach((e,t)=>{if(e.needMemoryUsageUpdate){const s=this._vxl.estimate_memory_usage(t);s>=0&&(e.needMemoryUsageUpdate=!1,e.layerView.setUsedMemory(s))}})}_syncRequestsResponses(){this._layers.forEach((e,s)=>{const r=[];e.responses.forEach((t,i)=>{r.push(i),this._dbg(2,"responding for requestID:"+i+" size:"+t.size),this._vxl.respond(s,i,t),0!==t.requestType&&4!==t.requestType||(e.needMemoryUsageUpdate=!0)});const a=e.responses;for(const t of r)a.delete(t);const n=this._vxl.get_new_requests(s),l=e.abortController.signal;for(const o in n){e.outstandingRequestCount+=1,1===e.outstandingRequestCount&&e.layerView.updatingFlagChanged();const s=n[o],r={responseType:"array-buffer",signal:l,query:{...e.layerView.layer.customParameters,token:e.layerView.layer.apiKey}};this._dbg(2,"making requestID:"+o+" url:"+s.url),t(s.url,r).then(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),this._dbg(2,"have response for requestID:"+o);let i=0;if(t.data.byteLength>0){i=this._vxl._malloc(t.data.byteLength);const e=new Uint8Array(this._vxl.HEAPU8.buffer,i,t.data.byteLength),s=new Uint8Array(t.data);for(let i=0;i<t.data.byteLength;++i)e[i]=s[i]}a.set(+o,{responseType:s.responseType,ptr:i,size:t.data.byteLength,success:!0,requestType:s.requestType})}).catch(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),i(t)||(this._dbg(4,`requestID:${o} failed, error=${t.toString()}`),a.set(+o,{responseType:s.responseType,ptr:0,size:0,success:!1,requestType:s.requestType}))})}})}updateWasmCamera(e){this._vxl.set_projection_matrix.apply(this._vxl,e.projectionMatrix),this._vxl.set_view_matrix.apply(this._vxl,e.viewMatrix),this._vxl.set_near_far(e.near,e.far)}isUpdating(e){if(!this._vxl&&this._vxlPromise)return!0;const t=this._layers.get(e);return!!t&&t.outstandingRequestCount>0}getLayerTimes(e){const t=[];return this._layers.forEach((s,i)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const s=this._vxl.get_layer_epoch_times(i,e.layer.currentVariableId);for(let e=0;e<s.length;++e)t.push(s[e])}}),t}getCurrentLayerTimeIndex(e){let t=0;return this._layers.forEach((s,i)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(t=this._vxl.get_layer_current_time_id(i))}),t}setEnabled(e,t){this._layers.forEach((s,i)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl.set_enabled(i,t),s.needMemoryUsageUpdate=!0,this._renderPluginContext.requestRender())})}setIsInScaleRange(e,t){const s=this._layers.get(e.wasmLayerId);s&&t!==s.isInScaleRange&&(s.isInScaleRange=t,this._vxl.set_is_in_scale_range(e.wasmLayerId,t),s.needMemoryUsageUpdate=!t,this._renderPluginContext.requestRender())}setStaticSections(e,t){const s={mask:1,staticSections:t};return this._doMaskedUIUpdate(e,s,!0)}setCurrentVariable(e,t){const s={mask:1024,currentVariable:t};return this._doMaskedUIUpdate(e,s,!0)}setRenderMode(e,t){const s={mask:8192,renderMode:t};return this._doMaskedUIUpdate(e,s,!0)}setVerticalExaggerationAndOffset(e,t,s,i){const r={mask:256,volStyleDesc:{volumeId:t,verticalExaggeration:s,verticalOffset:i}};return this._doMaskedUIUpdate(e,r,!0)}setVariableStyles(e,t){const s={mask:32768,variableStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setVolumeStyles(e,t){const s={mask:65536,volumeStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setEnableDynamicSections(e,t){const s={mask:4096,containerIsVisible:t,container:1};return this._doMaskedUIUpdate(e,s,!0)}setEnableIsosurfaces(e,t){const s={mask:4096,containerIsVisible:t,container:0};return this._doMaskedUIUpdate(e,s,!0)}setEnableSections(e,t){const s={mask:4096,containerIsVisible:t,container:2};return this._doMaskedUIUpdate(e,s,!0)}setAnalysisSlice(e,t,s,i){const r={mask:131072,analysisSlice:{point:s,normal:i,enabled:t}};return this._doMaskedUIUpdate(e,r,!0)}updateLayerTimeProperties(e){if(!this._vxl)return;const t=this._layers.get(e.wasmLayerId);if(t){const s=t.layerView.layer;let i=0;s.timeOffset&&(i=n(s.timeOffset.value,s.timeOffset.unit,"seconds"));const r=this._getTimeArgs(s.timeExtent);this._vxl.set_layer_time_properties(e.wasmLayerId,r.startTime,r.endTime,r.hasTime,s.useViewTime,i),this._renderPluginContext.requestRender()}}_doMaskedUIUpdate(e,t,s){if(!this._vxl)return!1;let i=!1;return this._layers.forEach((s,r)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const e={str:JSON.stringify(t),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(i=1===this._vxl.handle_masked_ui_update(r,e.ptr,e.byteCount),e.isReusable||this._vxl._free(e.ptr))}}),i&&s&&this._renderPluginContext.requestRender(),i}_addTriangleToWasmBuffer(e,t,s,i,r){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],e[3*(t+=1)]=i[0],e[3*t+1]=i[1],e[3*t+2]=i[2],e[3*(t+=1)]=r[0],e[3*t+1]=r[1],e[3*t+2]=r[2],t+=1}_addNormalToWasmBuffer(e,t,s){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],t+=1}_doCaptureFrustum(){if(!this._vxl)return;const e=36,t=e/3,s=this._vxl._malloc(3*e*Float32Array.BYTES_PER_ELEMENT),i=new Float32Array(this._vxl.HEAPF32.buffer,s,3*e),r=this._vxl._malloc(3*t*Float32Array.BYTES_PER_ELEMENT),a=new Float32Array(this._vxl.HEAPF32.buffer,r,e),n=this._frustum.points[0],l=this._frustum.points[1],o=this._frustum.points[2],h=this._frustum.points[3],d=this._frustum.points[4],u=this._frustum.points[5],_=this._frustum.points[6],c=this._frustum.points[7];let m=0,g=0;const f=this._frustum.planes[4];m=this._addTriangleToWasmBuffer(i,m,o,l,n),g=this._addNormalToWasmBuffer(a,g,f),m=this._addTriangleToWasmBuffer(i,m,n,h,o),g=this._addNormalToWasmBuffer(a,g,f);const p=this._frustum.planes[5];m=this._addTriangleToWasmBuffer(i,m,d,u,_),g=this._addNormalToWasmBuffer(a,g,p),m=this._addTriangleToWasmBuffer(i,m,_,c,d),g=this._addNormalToWasmBuffer(a,g,p);const y=this._frustum.planes[3];m=this._addTriangleToWasmBuffer(i,m,_,o,h),g=this._addNormalToWasmBuffer(a,g,y),m=this._addTriangleToWasmBuffer(i,m,h,c,_),g=this._addNormalToWasmBuffer(a,g,y);const x=this._frustum.planes[2];m=this._addTriangleToWasmBuffer(i,m,n,l,u),g=this._addNormalToWasmBuffer(a,g,x),m=this._addTriangleToWasmBuffer(i,m,u,d,n),g=this._addNormalToWasmBuffer(a,g,x);const v=this._frustum.planes[0];m=this._addTriangleToWasmBuffer(i,m,h,n,d),g=this._addNormalToWasmBuffer(a,g,v),m=this._addTriangleToWasmBuffer(i,m,d,c,h),g=this._addNormalToWasmBuffer(a,g,v);const b=this._frustum.planes[1];m=this._addTriangleToWasmBuffer(i,m,o,_,u),g=this._addNormalToWasmBuffer(a,g,b),m=this._addTriangleToWasmBuffer(i,m,u,l,o),g=this._addNormalToWasmBuffer(a,g,b),-1!==this._frustumRenderableId&&this._vxl.remove_generic_mesh(this._frustumRenderableId),this._frustumRenderableId=this._vxl.add_generic_mesh(s,3*e,r,e,255,0,0,64),this._vxl._free(s),this._vxl._free(r),this._captureFrustum=!1,this._renderPluginContext.requestRender()}captureFrustum(){null===this._renderCoordsHelper&&(this._renderCoordsHelper=f.create(2,u(!1,this.view.spatialReference))),null===this._frustum&&(this._frustum=new g(this._renderCoordsHelper)),this._captureFrustum=!0,null!==this._renderPluginContext&&this._renderPluginContext.requestRender()}toggleFullVolumeExtentDraw(e){this._vxl&&this._layers.forEach((t,s)=>{t.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl.toggle_full_volume_extent_draw(s),this._renderPluginContext.requestRender())})}dropQueryRenderTarget(){this._vxl&&this._vxl.drop_query_rt()}addVoxelLayer(e){if(!this._vxl){const t={layerView:e,resolveCallback:null,rejectCallback:null},s=new Promise((e,s)=>{t.resolveCallback=e,t.rejectCallback=s});return this._newLayers.push(t),s}const t=this._addVoxelLayer(e);return t<0?Promise.reject(-1):Promise.resolve(t)}removeVoxelLayer(e){if(!this._vxl){const t=this._newLayers.findIndex(t=>e.uid===t.layerView.uid);t>=0&&(this._newLayers[t].resolveCallback(-1),this._newLayers.splice(t,1));const s=this._newLayers.length;return 0===s&&(this._dbg(1," no voxel layers left after removing a layer, removing RenderPlugin and destroying"),this.destroy()),s}let t=-1;this._layers.forEach((s,i)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){t=i,s.abortController.abort(),this._vxl.remove_layer(t);const r=this.layerViewUid.indexOf(e.uid);-1!==r&&this.layerViewUid.splice(r,1)}}),t>=0&&this._layers.delete(t);const s=this._layers.size;return 0===s&&(this._dbg(1," no voxel layers left after removing a layer, removing RenderPlugin and destroying"),this.destroy()),s}_getBlockSize(e){for(const t of this._wasmMemBlockSizes)if(e<t)return t;return-1}_allocateBlock(e){e.byteCount=this._vxl.lengthBytesUTF8(e.str)+1;const t=this._getBlockSize(e.byteCount);return t<0?(e.isReusable=!1,e.ptr=this._vxl._malloc(e.byteCount)):(e.isReusable=!0,e.ptr=this._wasmMemBlocks.get(t),0===e.ptr&&(e.ptr=this._vxl._malloc(t),this._wasmMemBlocks.set(t,e.ptr))),0!==e.ptr&&(this._vxl.stringToUTF8(e.str,e.ptr,e.byteCount),!0)}_getTimeArgs(e){let t=-Number.MAX_VALUE,s=Number.MAX_VALUE,i=!1;return null!=e&&(e.isAllTime?i=!0:(null!=e.start&&(i=!0,t=e.start.getTime()/1e3),null!=e.end&&(i=!0,s=e.end.getTime()/1e3))),{startTime:t,endTime:s,hasTime:i}}_addVoxelLayer(e){const t=e.layer;let i=-1;const r=t.getConfiguration();if(r.length<1)return-1;const a={str:r,byteCount:0,ptr:0,isReusable:!1};if(!this._allocateBlock(a))return-1;const l=this._getTimeArgs(t.timeExtent),o=this.view.spatialReference.isWGS84&&t.spatialReference.isWGS84?111319.49079327357:1;let h=0;if(t.timeOffset&&(h=n(t.timeOffset.value,t.timeOffset.unit,"seconds")),i=this._vxl.add_layer(t.serviceRoot,a.ptr,a.byteCount,o,o,l.startTime,l.endTime,l.hasTime,t.useViewTime,h,this._toWasmQuality(this.view.qualityProfile)),a.isReusable||this._vxl._free(a.ptr),i>=0){t.test?.constantUpscaling&&(this._setUpscalingLimits(0,.25,.25),this._setUpscalingLimits(1,.5,.5),this._setUpscalingLimits(2,.75,.75));const r=new AbortController;if(this._layers.set(i,{layerView:e,responses:new Map,outstandingRequestCount:0,abortController:r,needMemoryUsageUpdate:!1,isInScaleRange:!0}),this.layerViewUid.push(e.uid),!this._halfIntTexturesAvailable||has("mac")){const t=[];let i="";for(const s of e.layer.variables)"Int16"!==s.renderingFormat.type&&"UInt16"!==s.renderingFormat.type||(t.push(s.name),s.id===e.layer.currentVariableId&&(i=s.name));""!==i&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${i}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}if(!this._textureFloatLinearAvailable){const t=[];let i="";for(const s of e.layer.variables)"Float32"===s.renderingFormat.type&&(t.push(s.name),s.id===e.layer.currentVariableId&&(i=s.name));""!==i&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${i}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}return has("esri-mobile")&&s.getLogger(this).warnOnce("Mobile support differs across devices. Voxel layer might not display as expected."),i}return-1}prepareRender(e){if(!this._vxl)return;const t=e.bind.camera.viewForward,s=e.bind.camera.eye;this._vxl.update_camera_pos_and_direction(s[0],s[1],s[2],t[0],t[1],t[2]);const i=this._vxl.cull();this._dbg(2,"missingResourceCount="+i),this._moreToLoad=i>0,this._havePreparedWithAllLayers=0===this._newLayers.length,this._updateMemoryUsage()}acquireTechniques(){return[]}render(e){if(!this._vxl)return;for(const s of this._newLayers){const e=this._addVoxelLayer(s.layerView);-1===e?s.rejectCallback(-1):s.resolveCallback(e)}if(this._newLayers=[],0===this._layers.size)return void this._dbg(4,"No voxel layers but RenderPlugin instance is being asked to render!");this._lastFrameWasStationary=this.view.stationary,this._syncRequestsResponses(),this._beforeDraw(),this._vxl.begin_color_frame(!this.view.stage.renderer.isFeatureEnabled(2),e.bind.lighting.mainLight.direction[0],e.bind.lighting.mainLight.direction[1],e.bind.lighting.mainLight.direction[2]);const t=this._renderTargetToRestore.viewport;t.width===this._viewportWidth&&t.height===this._viewportHeight||(this._viewportWidth=t.width,this._viewportHeight=t.height,this._vxl.set_viewport(t.width,t.height),this._layers.forEach(e=>{e.needMemoryUsageUpdate=!0})),0===t.x&&0===t.y||this._dbg(4,"Unsupported viewport parameters detected!"),this.updateWasmCamera(e.bind.camera),this._captureFrustum&&(this._frustum.update(e.bind.camera),this._doCaptureFrustum()),this._vxl.draw(),this._afterDraw(),(this._moreToLoad||!this._havePreparedWithAllLayers&&this._layers.size>0)&&this._renderPluginContext.requestRender()}destroy(){this._dbg(1,"--destroy--"),this._vxl&&(this._layers.forEach(e=>{e.abortController.abort()}),this._wasmMemBlocks.forEach(e=>{0!==e&&this._vxl._free(e)}),this._vxl.uninitialize_voxel_wasm(),this._removeRenderPlugin(),this._vxl=null)}_initializeWasm(e){return this._vxl?Promise.resolve():(this._vxlPromise||(this._vxlPromise=_(e).then(t=>{if(t.specialHTMLTargets.jsAPI3DRenderingContext=e,this._vxl=t,this._vxlPromise=null,this._newLayers.length<=0)return this._dbg(1," no voxel layers left after WASM downloaded, removing RenderPlugin and destroying"),void this.destroy();const s=this._getTimeArgs(this.view?.timeExtent),i=this._vxl.addFunction(this._restoreFramebuffer.bind(this),"v"),r=this._vxl.addFunction(this._setBlendState.bind(this),"viiii"),a=this._vxl.addFunction(this._setFrontFace.bind(this),"vi"),n=this._vxl.addFunction(this._setRasterizerState.bind(this),"vi"),l=this._vxl.addFunction(this._setDepthStencilStateFunction.bind(this),"viii"),o=this._vxl.addFunction(this._setViewport.bind(this),"viiii"),h=this._vxl.addFunction(this._bindPreviousDepthToSlot.bind(this),"iii"),d=this._vxl.addFunction(this._modifyResourceCount.bind(this),"viii"),u=this._halfIntTexturesAvailable&&!has("mac"),_=this._textureFloatLinearAvailable;this._vxl.initialize_voxel_wasm(i,r,a,n,l,o,h,d,s.startTime,s.endTime,s.hasTime,u,_),this._renderPluginContext&&this._renderPluginContext.requestRender()}).catch(()=>{for(const e of this._newLayers)e.rejectCallback(-2);this._dbg(4," WASM failed to download, removing RenderPlugin and destroying"),this.destroy()})),this._vxlPromise)}pickDepth(e,t,s){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const i=s.viewport[3]-t;if(e<0||e>s.viewport[2]||t<0||t>s.viewport[3])return this._dbg(4,`[js] pickDepth: outOfRange, screenXY=[${e.toFixed(0)}, ${i.toFixed(0)}]]`),null;this._beforeDraw();const r=s.viewForward,a=s.eye;this._vxl.update_camera_pos_and_direction(a[0],a[1],a[2],r[0],r[1],r[2]),this.updateWasmCamera(s),this._vxl.begin_frame();const n=this._vxl.pick_depth(e,i);if(this._afterDraw(),n.success){return n.distanceToCamera}return null}pickObject(e,t,s,i){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const r=Math.round(e),a=Math.round(t);if(r<0||r>s.viewport[2]||a<0||a>s.viewport[3])return this._dbg(4,`[js] pickObject: outOfRange, screenXY=[${r}, ${a}], vp=[${s.viewport.toString()}]`),null;this._beforeDraw();const n=s.viewForward,l=s.eye;this._vxl.update_camera_pos_and_direction(l[0],l[1],l[2],n[0],n[1],n[2]),this.updateWasmCamera(s),this._vxl.begin_frame();let o=null;if(0===i.length)o=this._vxl.pick_object(r,a,0,0);else{const e={str:JSON.stringify({layerIds:i}),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(o=this._vxl.pick_object(r,a,e.ptr,e.byteCount),e.isReusable||this._vxl._free(e.ptr))}return this._afterDraw(),o}async getOtherFieldPopupValues(e,s){for(const i of e){const e=i.gpuResult;if(!e)continue;const r=this._layers.get(e.layerId);if(!r||!r.layerView.layer.url)continue;const a=r.layerView.layer,n={responseType:"array-buffer",signal:r.abortController.signal,query:{...r.layerView.layer.customParameters,token:r.layerView.layer.apiKey}},l=e.voxelSpacePosition,o=[Math.floor(l[0]/32),Math.floor(l[1]/32),Math.floor(l[2]/32)],h=[-4&o[0],-4&o[1],-4&o[2]];let d=0;if(e.epochTime){const t=this._vxl.get_layer_epoch_times(r.layerView.wasmLayerId,a.currentVariableId);for(let s=0;s<t.length;++s)if(t[s]===e.epochTime/1e3){d=s;break}}const u=[],_={varIds:[],ptrs:[],sizes:[]};for(const i of s){const e=a.variables.findIndex(e=>e.name===i);if(-1===e)continue;const s=a.variables.getItemAt(e)?.id;if(null==s)continue;const r=`${a.url}/variables/${s}/${d}/bundles/0/${h[0]}-${h[1]}-${h[2]}`;u.push(t(r,n).then(e=>e.data)),_.varIds.push(s)}const c=await Promise.allSettled(u),m=c.length;for(let t=0;t<m;++t){const e=c[t];if("fulfilled"===e.status){const t=e.value,s=this._vxl._malloc(t.byteLength);new Uint8Array(this._vxl.HEAPU8.buffer,s,t.byteLength).set(new Uint8Array(t)),_.ptrs.push(s),_.sizes.push(t.byteLength)}else _.varIds.splice(t,1)}const g=this._vxl.get_other_field_popup_values(e,_);for(let t=0;t<_.ptrs.length;++t)this._vxl._free(_.ptrs[t]);if(g.continuousValues)for(const t in g.continuousValues)i.attributes[t]=g.continuousValues[t];if(g.uniqueValues)for(const t in g.uniqueValues)i.attributes[t]=g.uniqueValues[t]}return e}_beforeDraw(){this._renderTargetToRestore={fbo:this._rctx.getBoundFramebufferObject(),viewport:this._rctx.getViewport()},this._rctx.setPolygonOffsetFillEnabled(!1),this._rctx.setScissorTestEnabled(!1),this._rctx.setColorMask(!0,!0,!0,!0)}_afterDraw(){this._renderTargetToRestore.fbo=null,this._rctx.externalTextureUnitUpdate(this._vxl.get_texture_units_bound_in_frame(),this._vxl.get_active_texture_unit()),this._rctx.externalVertexArrayObjectUpdate(),this._rctx.externalVertexBufferUpdate(),this._rctx.externalProgramUpdate()}intersect(e,t,s,i,r){if(!this._vxl||!this._rctx||0===this._layers.size||!e.options.selectionMode||e.options.isFiltered||!e.camera)return;if(null==r||r[0]<0||r[0]>e.camera.viewport[2]||r[1]<0||r[1]>e.camera.viewport[3])return this._dbg(4,r?`[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=[${r[0].toFixed(0)}, ${r[1].toFixed(0)}]`:"[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=null"),null;const a=[];this._layers.forEach(t=>{e.options.filteredLayerViewUids.includes(t.layerView.uid)&&a.push(t.layerView.wasmLayerId)});const n=this.pickObject(r[0],r[1],e.camera,a);if(null==n||-1===n.layerId)return;const l=this._layers.get(n.layerId);if(l){const t=l.layerView.layer.uid,r=n.distanceToCamera/h(s,i),a=d();a[0]=n.worldX,a[1]=n.worldY,a[2]=n.worldZ;const o={},u=l.layerView.layer,_=u.variables.findIndex(e=>e.id===u.currentVariableId);if(_>=0){const e=u.variables.getItemAt(_);null!=e&&(null!=n.continuousValue?o[e.name]=n.continuousValue:null!=n.uniqueValueLabel&&null!=n.uniqueValue?o[e.name]=`${n.uniqueValueLabel} (${n.uniqueValue})`:null!=n.uniqueValue&&(o[e.name]=`${n.uniqueValue}`),e.description.length>0?o["Voxel.CurrentVariable"]=e.description:e.name?.length>0&&(o["Voxel.CurrentVariable"]=e.name))}if(o["Voxel.Position"]=`[${n.voxelSpacePosition.toString()}]`,null!=n.epochTime&&null!=n.nativeTime&&null!=n.nativeTimeUnits){const e=new Date(n.epochTime);o["Voxel.LocalTime"]=e,o["Voxel.SourceTime"]=`${n.nativeTime.toLocaleString()} ${n.nativeTimeUnits}`}null!=n.depth&&(o["Voxel.Depth"]=n.depth);const c=n.faceNormal;o["Voxel.WorldPosition"]=`[${a[0]}, ${a[1]}, ${a[2]}]`;const g=e=>{const s=new m(a,t,()=>this._createVoxelGraphic(l.layerView.layer,o,n));e.set(this.type,s,r,c)},f=e.results,p=2===e.options.store;if((null==f.min.distance||r<f.min.distance)&&g(f.min),(null==f.max.distance||r>f.max.distance)&&g(f.max),p){const t=new y(e.ray);g(t),e.results.all.push(t)}}}_createVoxelGraphic(e,t,s){return new c({layer:e,sourceLayer:e,origin:e.graphicOrigin,attributes:t,gpuResult:s})}_toWasmQuality(e){switch(e){case"low":return 0;case"medium":return 1;case"high":return 2}}_setUpscalingLimits(e,t,s){this._vxl&&this._vxl.set_upscaling_limits(e,t,s)}hasHighlight(){return!1}};e([l({constructOnly:!0})],x.prototype,"view",void 0),x=e([o("esri.layers.VoxelWasmPerSceneView")],x);const v=x;export{v 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/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{indexOf as e,PositionHint as t}from"../../../core/arrayUtils.js";import{toConst as i}from"../../../core/compilerUtils.js";import r from"../../../core/Error.js";import"../../../core/has.js";import{clone as s}from"../../../core/lang.js";import{removeMaybe as a,destroyMaybe as n}from"../../../core/maybe.js";import{signalFromSignalOrOptions as l,throwIfAborted as u}from"../../../core/promiseUtils.js";import{getMetersPerUnitForSR as o}from"../../../core/units.js";import{isSerializable as c}from"../../../core/support/jsonUtils.js";import{isLoaded as y}from"../../../geometry/projectionUtils.js";import{set as h,negativeInfinity as d,create as m,expandWithAABB as f}from"../../../geometry/support/aaBoundingBox.js";import{fromValues as p,create as x}from"../../../geometry/support/aaBoundingRect.js";import{getBoundsXY as g}from"../../../geometry/support/boundsUtils.js";import{fromJSON as _,isExtent as F,isPolygon as w}from"../../../geometry/support/jsonUtils.js";import{normalizeCentralMeridian as Q}from"../../../geometry/support/normalizeUtils.js";import{equals as S,isValid as R}from"../../../geometry/support/spatialReferenceUtils.js";import{convertFromGeometry as I}from"../featureConversionUtils.js";import{getWhereClause as j}from"./attributeSupport.js";import{cleanFromGeometryEngine as b,getGeometry as E}from"./geometryUtils.js";import{project as T,checkProjectionSupport as A,projectMany as v}from"./projectionSupport.js";import{QueryEngineCache as G}from"./QueryEngineCache.js";import{queryCapabilities as k}from"./QueryEngineCapabilities.js";import{QueryEngineResult as C}from"./QueryEngineResult.js";import{queryEngineEmptyResult as O,normalizeAttributeBinsQuery as P,normalizeQueryLike as q,normalizeQuery as z}from"./queryUtils.js";import{validateAttributeBinsQuery as U,validateQuery as B,validateStatisticsQuery as M}from"./queryValidationUtils.js";import{getSpatialQueryOperator as H,canQueryWithRBush as N}from"./spatialQuerySupport.js";import{getTimeExtent as Z,getTimeOperator as J}from"./timeSupport.js";import L from"../../support/FieldsIndex.js";import{ImmediateTask as V}from"../../../views/support/Scheduler.js";const D="unsupported-query";class K{constructor(e,t=null,i,r,s){this.attributes=e,this.geometry=i,this.centroid=r,this.filterFlags=s,this.groupId=-1,this.displayId=t}}class W{constructor(e){this._changeHandle=null,this.capabilities={query:k},this.geometryType=e.geometryType,this.hasM=!!e.hasM,this.hasZ=!!e.hasZ,this.spatialReference=e.spatialReference,this.definitionExpression=e.definitionExpression,this.featureStore=e.featureStore,this.aggregateAdapter=e.aggregateAdapter,this._cache=e.cache??new G,this.timeInfo=e.timeInfo,this.featureIdInfo=e.featureIdInfo,"object-id"===e.featureIdInfo.type&&(this.objectIdField=e.featureIdInfo.fieldName),this._changeHandle=this.featureStore.events.on("changed",()=>this._clearCache()),this.fieldsIndex=c(e.fieldsIndex)?e.fieldsIndex:L.fromJSON(e.fieldsIndex),!e.availableFields||1===e.availableFields.length&&"*"===e.availableFields[0]?this.availableFields=new Set(this.fieldsIndex.fields.map(e=>e.name)):this.availableFields=new Set(e.availableFields.map(e=>this.fieldsIndex.get(e)?.name).filter(e=>null!=e)),e.scheduler&&e.priority?this._frameTask=e.scheduler.registerTask(e.priority):this._frameTask=V}destroy(){this._changeHandle=a(this._changeHandle),this._frameTask=a(this._frameTask),this._clearCache(),n(this._cache)}get featureAdapter(){return this.featureStore.featureAdapter}async executeQuery(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryFeatureSet(e),i)}async executeQueryForCount(e={},t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForCount(e),i)}async executeQueryForExtent(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForExtent(e),i)}async executeQueryForIds(e,t){return Array.from(await this.executeQueryForIdSet(e,t))}async executeQueryForIdSet(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForIdSet(e),i)}async executeQueryForLatestObservations(e,t){const i=l(t);if(!this.timeInfo?.trackIdField)throw new r(D,"Missing timeInfo or timeInfo.trackIdField",{query:e,timeInfo:this.timeInfo});return await this._frameTask.scheduleGenerator(()=>this._executeQueryForLatestObservations(e),i)}async executeQueryForOpaqueFeatures(e,t){const i=l(t);return(await this._frameTask.scheduleGenerator(()=>this._executeQuery(e,{}),i)).items}async executeAttributeBinsQuery(e,t){const i=l(t);return e=s(e),await this._frameTask.scheduleGenerator(()=>this._executeAttributeBinsQuery(e),i)}async executeQueryForSummaryStatistics(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForSummaryStatistics(e,t),r)}async executeQueryForUniqueValues(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForUniqueValues(e,t),r)}async executeQueryForClassBreaks(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForClassBreaks(e,t),r)}async executeQueryForHistogram(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForHistogram(e,t),r)}async executeQueryForSnapping(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForSnapping(e,i),i)}async fetchRecomputedExtents(e){const t=l(e);this._timeExtentPromise||=Z(this.timeInfo,this.featureStore);const[i,r]=await Promise.all([this._getFullExtent(),this._timeExtentPromise]);return u(t),{fullExtent:i,timeExtent:r}}_clearCache(){this._cache.clear(),this._allFeaturesPromise=null,this._timeExtentPromise=null,this._fullExtentPromise=null}async*_executeQueryFeatureSet(e){try{const t=yield*this._executeQuery(e,{});return yield,await t.createQueryResponse()}catch(t){if(t!==O)throw t;return await new C([],e,this).createQueryResponse()}}async*_executeQueryForCount(e){try{const t=yield*this._executeQuery(e,{returnGeometry:!1,returnCentroid:!1,outSR:null});return yield,t.createQueryResponseForCount()}catch(t){if(t!==O)throw t;return 0}}async*_executeQueryForExtent(e){const t=e.outSR;try{const i=yield*this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null});yield;const r=i.size;if(!r)return{count:0,extent:null};const s=await this._getBounds(i.items,i.spatialReference,t??this.spatialReference);return yield,{count:r,extent:s}}catch(i){if(i===O)return{count:0,extent:null};throw i}}async*_executeQueryForIdSet(e){try{const t=yield*this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null});yield;const i=t.items,r=new Set;for(const e of i)r.add(t.featureAdapter.getObjectId(e));return r}catch(t){if(t===O)return new Set;throw t}}async*_executeQueryForLatestObservations(e){try{const t=yield*this._executeQuery(e,{});return yield,this._filterLatest(t),yield,await t.createQueryResponse()}catch(t){if(t!==O)throw t;return await new C([],e,this).createQueryResponse()}}async*_executeAttributeBinsQuery(e){let t;try{e=await P(e,this.definitionExpression,this.spatialReference),yield,e=await U(e,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield;const i=yield*this._executeSceneFilterQuery(e);yield,t=yield*this._executeGeometryQuery(e,i),yield,this._executeAggregateIdsQuery(t),yield,this._executeObjectIdsQuery(t),yield,this._executeTimeQuery(t),yield,this._executeAttributesQuery(t),yield}catch(i){if(i!==O)throw i;t=new C([],e,this)}return await t.createQueryBinsResponse(e)}async*_executeQueryForSummaryStatistics(e={},t){const{field:i,normalizationField:r,valueExpression:s}=t,a=yield*this._executeQueryForStatistics(e,{field:i,normalizationField:r,valueExpression:s});return yield,await a.createSummaryStatisticsResponse(t)}async*_executeQueryForUniqueValues(e={},t){const{field:i,field2:r,field3:s,valueExpression:a}=t,n=yield*this._executeQueryForStatistics(e,{field:i,field2:r,field3:s,valueExpression:a});return yield,await n.createUniqueValuesResponse(t)}async*_executeQueryForClassBreaks(e,t){const{field:i,normalizationField:r,valueExpression:s}=t,a=yield*this._executeQueryForStatistics(e,{field:i,normalizationField:r,valueExpression:s});return yield,await a.createClassBreaksResponse(t)}async*_executeQueryForHistogram(e,t){const{field:i,normalizationField:r,valueExpression:s}=t,a=yield*this._executeQueryForStatistics(e,{field:i,normalizationField:r,valueExpression:s});return yield,await a.createHistogramResponse(t)}async*_executeQueryForSnapping(e,t){const{point:i,distance:r,returnEdge:a,vertexMode:n}=e;if(!a&&"none"===n)return{candidates:[]};let l=s(e.query);l=await q(l,this.definitionExpression,this.spatialReference),yield,l=await B(l,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield;const u=!S(i.spatialReference,this.spatialReference);u&&(await A(i.spatialReference,this.spatialReference),yield);const o="number"==typeof r?r:r.x,c="number"==typeof r?r:r.y,y={xmin:i.x-o,xmax:i.x+o,ymin:i.y-c,ymax:i.y+c,spatialReference:i.spatialReference},h=u?T(y,this.spatialReference):y;if(!h)return{candidates:[]};const d=(await Q(_(i),null,{signal:t}))[0];yield;const m=(await Q(_(h),null,{signal:t}))[0];if(yield,null==d||null==m)return{candidates:[]};const f=await this._searchFeatures(X(m.toJSON()));yield;const p=new C(f,l,this);this._executeObjectIdsQuery(p),yield,this._executeTimeQuery(p),yield,this._executeAttributesQuery(p),yield,yield*this._executeGeometryQueryForSnapping(p),yield;const x=d.toJSON(),g=u?T(x,this.spatialReference):x,F=u?Math.max(h.xmax-h.xmin,h.ymax-h.ymin)/2:r;return p.createSnappingResponse({...e,point:g,distance:F},l.returnZ,i.spatialReference)}async _getBounds(e,t,i){const r=h(m(),d);return await this.featureStore.forEachBounds(e,e=>f(r,e)),Y(r,t,i,this.spatialReference,this.hasZ)}_getFullExtent(){return this._fullExtentPromise||="getFullExtent"in this.featureStore&&this.featureStore.getFullExtent?Promise.resolve(this.featureStore.getFullExtent(this.spatialReference)):this._getAllFeatures().then(e=>this._getBounds(e,this.spatialReference,this.spatialReference)),this._fullExtentPromise}async _getAllFeaturesQueryEngineResult(e){return new C(await this._getAllFeatures(),e,this)}async _getAllFeatures(){if(null==this._allFeaturesPromise){const e=[];this._allFeaturesPromise=(async()=>await this.featureStore.forEach(t=>e.push(t)))().then(()=>i(e))}const e=this._allFeaturesPromise,t=await e;return e===this._allFeaturesPromise?t.slice():this._getAllFeatures()}async*_executeQuery(e,t){e=s(e),e=await z(e,this.definitionExpression,this.spatialReference),yield,e=await B(e,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield,e={...e,...t};const i=yield*this._executeSceneFilterQuery(e);yield;const r=yield*this._executeGeometryQuery(e,i);return yield,this._executeAggregateIdsQuery(r),yield,this._executeObjectIdsQuery(r),yield,this._executeTimeQuery(r),yield,this._executeAttributesQuery(r),r}async*_executeSceneFilterQuery(e){if(null==e.sceneFilter)return null;const{outSR:t,returnGeometry:i,returnCentroid:r}=e,s=this.featureStore.featureSpatialReference,a=e.sceneFilter.geometry,n=null==s||S(s,a.spatialReference)?a:T(a,s);if(!n)return null;const l=i||r,u=R(t)&&!S(this.spatialReference,t)&&l?async e=>this._project(e,t):e=>e;yield;const o=this.featureAdapter,c=await this._searchFeatures(X(n));yield;if("disjoint"===e.sceneFilter.spatialRelationship){if(!c.length)return null;const t=new Set;for(const e of c)t.add(o.getObjectId(e));const i=await this._getAllFeatures();yield;const r=await H("esriSpatialRelDisjoint",n,this.geometryType);yield;const s=e=>!t.has(o.getObjectId(e))||r(o.getGeometry(e)),a=yield*this._runSpatialFilter(i,s);yield;const l=new C(a,e,this);return await u(l)}if(!c.length)return new C([],e,this);if(this._canExecuteSinglePass(n,e))return await u(new C(c,e,this));const y=await H("esriSpatialRelContains",n,this.geometryType);yield;const h=yield*this._runSpatialFilter(c,e=>y(o.getGeometry(e)));return yield,await u(new C(h,e,this))}async*_executeGeometryQuery(i,r){if(null!=r&&0===r.items.length)return r;const{geometry:s,outSR:a,returnGeometry:n,returnCentroid:l}=i,u=r?null:this._getCacheKey(i),o=u?this._cache.get(u):null;if(o)return new C(o,i,this);const c=R(a)&&!S(this.spatialReference,a),y=n||l,h=async e=>(c&&y&&await this._project(e,a),u&&this._cache.put(u,e.items),e),d=this.featureStore.featureSpatialReference,m=!s||null==d||S(d,s.spatialReference)?s:T(s,d);if(!m)return await h(null!=r?r:await this._getAllFeaturesQueryEngineResult(i));yield;const f=this.featureAdapter;let p=await this._searchFeatures(X(s));yield;const x=i.spatialRel??"esriSpatialRelIntersects";if("esriSpatialRelDisjoint"===x){if(!p.length)return await h(null!=r?r:await this._getAllFeaturesQueryEngineResult(i));const e=new Set;for(const i of p)e.add(f.getObjectId(i));let t;null!=r?t=r.items:(yield,t=await this._getAllFeatures(),yield);const s=await H(x,m,this.geometryType);yield;const a=t=>!e.has(f.getObjectId(t))||s(f.getGeometry(t)),n=yield*this._runSpatialFilter(t,a);yield;const l=new C(n,i,this);return await h(l)}if(null!=r){const i=new t;p=p.filter(t=>e(r.items,t,r.items.length,i)>=0)}if(!p.length){const e=new C([],i,this);return u&&this._cache.put(u,e.items),e}if(this._canExecuteSinglePass(m,i))return await h(new C(p,i,this));const g=await H(x,m,this.geometryType);yield;const _=yield*this._runSpatialFilter(p,e=>g(f.getGeometry(e)));return yield,await h(new C(_,i,this))}_executeAggregateIdsQuery(e){if(0===e.items.length||!e.query.aggregateIds?.length||null==this.aggregateAdapter)return;const t=new Set;for(const r of e.query.aggregateIds){this.aggregateAdapter.getFeatureObjectIds(r).forEach(e=>t.add(e))}const i=this.featureAdapter.getObjectId;e.items=e.items.filter(e=>t.has(i(e)))}_executeObjectIdsQuery(e){if(0===e.items.length||!e.query.objectIds?.length)return;const t=new Set(e.query.objectIds),i=this.featureAdapter.getObjectId;e.items=e.items.filter(e=>t.has(i(e)))}_executeTimeQuery(e){if(0===e.items.length)return;const t=J(this.timeInfo,e.query.timeExtent,this.featureAdapter);null!=t&&(e.items=e.items.filter(t))}_executeAttributesQuery(e){if(0===e.items.length)return;const t=j(e.query.where,this.fieldsIndex);if(t){if(!t.isStandardized)throw new TypeError("Where clause is not standardized");e.items=e.items.filter(e=>t.testFeature(e,this.featureAdapter))}}async*_executeGeometryQueryForSnapping(e){const{query:t}=e,{spatialRel:i}=t;if(!e?.items?.length||!t.geometry||!i)return;const r=await H(i,t.geometry,this.geometryType);yield;const s=this.featureAdapter,a=e=>r(s.getGeometry(e)),n=yield*this._runSpatialFilter(e.items,a);e.items=n}*_runSpatialFilter(e,t){if(!t)return e;if(null==this._frameTask)return e.filter(e=>t(e));let i=yield;const r=new Array;for(const s of e)t(s)&&r.push(s),i.madeProgress(),i.done&&(i=yield);return r}_filterLatest(e){const{trackIdField:t,startTimeField:i,endTimeField:r}=this.timeInfo,s=r||i,a=new Map,n=this.featureAdapter.getAttribute;for(const l of e.items){const e=n(l,t),i=n(l,s),r=a.get(e);(!r||i>n(r,s))&&a.set(e,l)}e.items=Array.from(a.values())}_getCacheKey(e){const{geometry:t,spatialRel:i,returnGeometry:r,returnCentroid:s,outSR:a,resultType:n,cacheHint:l}=e;if("tile"!==n&&!l)return null;const u=r||s;return R(a)&&!S(this.spatialReference,a)&&u?JSON.stringify([t,i,a]):JSON.stringify([t,i])}_canExecuteSinglePass(e,t){const{spatialRel:i}=t;return N(e)&&("esriSpatialRelEnvelopeIntersects"===i||"esriGeometryPoint"===this.geometryType&&("esriSpatialRelIntersects"===i||"esriSpatialRelContains"===i))}async _project(e,t){if(!t||S(this.spatialReference,t))return e;const r=this.featureAdapter,s=y()?await this._getFullExtent():void 0,a=await v(e.items.map(e=>E(this.geometryType,r.getGeometry(e))),this.spatialReference,t,{areaOfInterestExtent:s});return e.items=i(a.map((t,i)=>r.cloneWithGeometry(e.items[i],I(t,this.hasZ,this.hasM)))),e}async _searchFeatures(e){const t=new Set;await Promise.all(e.map(e=>this.featureStore.forEachInBounds(e,e=>t.add(e))));const i=Array.from(t.values());return t.clear(),i}async*_executeQueryForStatistics(e,t){e=s(e);try{e=await z(e,this.definitionExpression,this.spatialReference),yield,e=await M(e,t,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield;const i=yield*this._executeSceneFilterQuery(e);yield;const r=yield*this._executeGeometryQuery(e,i);return yield,this._executeAggregateIdsQuery(r),yield,this._executeObjectIdsQuery(r),yield,this._executeTimeQuery(r),yield,this._executeAttributesQuery(r),yield,r}catch(i){if(i!==O)throw i;return new C([],e,this)}}get test(){}}function X(e){if(N(e)){if(F(e))return[p(Math.min(e.xmin,e.xmax),Math.min(e.ymin,e.ymax),Math.max(e.xmin,e.xmax),Math.max(e.ymin,e.ymax))];if(w(e))return e.rings.map(e=>p(Math.min(e[0][0],e[2][0]),Math.min(e[0][1],e[2][1]),Math.max(e[0][0],e[2][0]),Math.max(e[0][1],e[2][1])))}return[g(x(),e)]}function Y(e,t,i,r,s){const a={xmin:e[0],ymin:e[1],xmax:e[3],ymax:e[4],spatialReference:b(r)};s&&isFinite(e[2])&&isFinite(e[5])&&(a.zmin=e[2],a.zmax=e[5],a.hasZ=!0);const n=T(a,t,i);if(n.spatialReference=b(i),n.xmax-n.xmin===0){const e=o(n.spatialReference);n.xmin-=e,n.xmax+=e}if(n.ymax-n.ymin===0){const e=o(n.spatialReference);n.ymin-=e,n.ymax+=e}if(s&&null!=n.zmin&&null!=n.zmax&&n.zmax-n.zmin===0){const e=o(n.spatialReference);n.zmin-=e,n.zmax+=e}return n}export{K as Feature,W as QueryEngine,Y as getQueryResultExtent};
5
+ import{indexOf as e,PositionHint as t}from"../../../core/arrayUtils.js";import{toConst as i}from"../../../core/compilerUtils.js";import r from"../../../core/Error.js";import"../../../core/has.js";import{clone as s}from"../../../core/lang.js";import{removeMaybe as a,destroyMaybe as n}from"../../../core/maybe.js";import{signalFromSignalOrOptions as l,throwIfAborted as u}from"../../../core/promiseUtils.js";import{getMetersPerUnitForSR as o}from"../../../core/units.js";import{isSerializable as c}from"../../../core/support/jsonUtils.js";import{isLoaded as y}from"../../../geometry/projectionUtils.js";import{set as h,create as d,expandWithAABB as m,negativeInfinity as f}from"../../../geometry/support/aaBoundingBox.js";import{fromValues as p,create as x}from"../../../geometry/support/aaBoundingRect.js";import{getBoundsXY as g}from"../../../geometry/support/boundsUtils.js";import{fromJSON as _,isExtent as F,isPolygon as w}from"../../../geometry/support/jsonUtils.js";import{normalizeCentralMeridian as Q}from"../../../geometry/support/normalizeUtils.js";import{equals as S,isValid as R}from"../../../geometry/support/spatialReferenceUtils.js";import{convertFromGeometry as I}from"../featureConversionUtils.js";import{getWhereClause as j}from"./attributeSupport.js";import{getGeometry as b,cleanFromGeometryEngine as E}from"./geometryUtils.js";import{checkProjectionSupport as T,project as A,projectMany as v}from"./projectionSupport.js";import{QueryEngineCache as G}from"./QueryEngineCache.js";import{queryCapabilities as k}from"./QueryEngineCapabilities.js";import{QueryEngineResult as C}from"./QueryEngineResult.js";import{queryEngineEmptyResult as O,normalizeAttributeBinsQuery as P,normalizeQueryLike as q,normalizeQuery as z}from"./queryUtils.js";import{validateAttributeBinsQuery as U,validateQuery as B,validateStatisticsQuery as M}from"./queryValidationUtils.js";import{getSpatialQueryOperator as H,canQueryWithRBush as N}from"./spatialQuerySupport.js";import{getTimeExtent as Z,getTimeOperator as J}from"./timeSupport.js";import L from"../../support/FieldsIndex.js";import{ImmediateTask as V}from"../../../views/support/Scheduler.js";const D="unsupported-query";class K{constructor(e,t=null,i,r,s){this.attributes=e,this.geometry=i,this.centroid=r,this.filterFlags=s,this.groupId=-1,this.displayId=t}}class W{constructor(e){this._changeHandle=null,this.capabilities={query:k},this.geometryType=e.geometryType,this.hasM=!!e.hasM,this.hasZ=!!e.hasZ,this.spatialReference=e.spatialReference,this.definitionExpression=e.definitionExpression,this.featureStore=e.featureStore,this.aggregateAdapter=e.aggregateAdapter,this._cache=e.cache??new G,this.timeInfo=e.timeInfo,this.featureIdInfo=e.featureIdInfo,"object-id"===e.featureIdInfo.type&&(this.objectIdField=e.featureIdInfo.fieldName),this._changeHandle=this.featureStore.events.on("changed",()=>this._clearCache()),this.fieldsIndex=c(e.fieldsIndex)?e.fieldsIndex:L.fromJSON(e.fieldsIndex),!e.availableFields||1===e.availableFields.length&&"*"===e.availableFields[0]?this.availableFields=new Set(this.fieldsIndex.fields.map(e=>e.name)):this.availableFields=new Set(e.availableFields.map(e=>this.fieldsIndex.get(e)?.name).filter(e=>null!=e)),e.scheduler&&e.priority?this._frameTask=e.scheduler.registerTask(e.priority):this._frameTask=V}destroy(){this._changeHandle=a(this._changeHandle),this._frameTask=a(this._frameTask),this._clearCache(),n(this._cache)}get featureAdapter(){return this.featureStore.featureAdapter}async executeQuery(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryFeatureSet(e),i)}async executeQueryForCount(e={},t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForCount(e),i)}async executeQueryForExtent(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForExtent(e),i)}async executeQueryForIds(e,t){return Array.from(await this.executeQueryForIdSet(e,t))}async executeQueryForIdSet(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForIdSet(e),i)}async executeQueryForLatestObservations(e,t){const i=l(t);if(!this.timeInfo?.trackIdField)throw new r(D,"Missing timeInfo or timeInfo.trackIdField",{query:e,timeInfo:this.timeInfo});return await this._frameTask.scheduleGenerator(()=>this._executeQueryForLatestObservations(e),i)}async executeQueryForOpaqueFeatures(e,t){const i=l(t);return(await this._frameTask.scheduleGenerator(()=>this._executeQuery(e,{}),i)).items}async executeAttributeBinsQuery(e,t){const i=l(t);return e=s(e),await this._frameTask.scheduleGenerator(()=>this._executeAttributeBinsQuery(e),i)}async executeQueryForSummaryStatistics(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForSummaryStatistics(e,t),r)}async executeQueryForUniqueValues(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForUniqueValues(e,t),r)}async executeQueryForClassBreaks(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForClassBreaks(e,t),r)}async executeQueryForHistogram(e={},t,i){const r=l(i);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForHistogram(e,t),r)}async executeQueryForSnapping(e,t){const i=l(t);return await this._frameTask.scheduleGenerator(()=>this._executeQueryForSnapping(e,i),i)}async fetchRecomputedExtents(e){const t=l(e);this._timeExtentPromise||=Z(this.timeInfo,this.featureStore);const[i,r]=await Promise.all([this._getFullExtent(),this._timeExtentPromise]);return u(t),{fullExtent:i,timeExtent:r}}_clearCache(){this._cache.clear(),this._allFeaturesPromise=null,this._timeExtentPromise=null,this._fullExtentPromise=null}async*_executeQueryFeatureSet(e){try{const t=yield*this._executeQuery(e,{});return yield,await t.createQueryResponse()}catch(t){if(t!==O)throw t;return await new C([],e,this).createQueryResponse()}}async*_executeQueryForCount(e){try{const t=yield*this._executeQuery(e,{returnGeometry:!1,returnCentroid:!1,outSR:null});return yield,t.createQueryResponseForCount()}catch(t){if(t!==O)throw t;return 0}}async*_executeQueryForExtent(e){const t=e.outSR;try{const i=yield*this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null});yield;const r=i.size;if(!r)return{count:0,extent:null};const s=await this._getBounds(i.items,i.spatialReference,t??this.spatialReference);return yield,{count:r,extent:s}}catch(i){if(i===O)return{count:0,extent:null};throw i}}async*_executeQueryForIdSet(e){try{const t=yield*this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null});yield;const i=t.items,r=new Set;for(const e of i)r.add(t.featureAdapter.getObjectId(e));return r}catch(t){if(t===O)return new Set;throw t}}async*_executeQueryForLatestObservations(e){try{const t=yield*this._executeQuery(e,{});return yield,this._filterLatest(t),yield,await t.createQueryResponse()}catch(t){if(t!==O)throw t;return await new C([],e,this).createQueryResponse()}}async*_executeAttributeBinsQuery(e){let t;try{e=await P(e,this.definitionExpression,this.spatialReference),yield,e=await U(e,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield;const i=yield*this._executeSceneFilterQuery(e);yield,t=yield*this._executeGeometryQuery(e,i),yield,this._executeAggregateIdsQuery(t),yield,this._executeObjectIdsQuery(t),yield,this._executeTimeQuery(t),yield,this._executeAttributesQuery(t),yield}catch(i){if(i!==O)throw i;t=new C([],e,this)}return await t.createQueryBinsResponse(e)}async*_executeQueryForSummaryStatistics(e={},t){const{field:i,normalizationField:r,valueExpression:s}=t,a=yield*this._executeQueryForStatistics(e,{field:i,normalizationField:r,valueExpression:s});return yield,await a.createSummaryStatisticsResponse(t)}async*_executeQueryForUniqueValues(e={},t){const{field:i,field2:r,field3:s,valueExpression:a}=t,n=yield*this._executeQueryForStatistics(e,{field:i,field2:r,field3:s,valueExpression:a});return yield,await n.createUniqueValuesResponse(t)}async*_executeQueryForClassBreaks(e,t){const{field:i,normalizationField:r,valueExpression:s}=t,a=yield*this._executeQueryForStatistics(e,{field:i,normalizationField:r,valueExpression:s});return yield,await a.createClassBreaksResponse(t)}async*_executeQueryForHistogram(e,t){const{field:i,normalizationField:r,valueExpression:s}=t,a=yield*this._executeQueryForStatistics(e,{field:i,normalizationField:r,valueExpression:s});return yield,await a.createHistogramResponse(t)}async*_executeQueryForSnapping(e,t){const{point:i,distance:r,returnEdge:a,vertexMode:n}=e;if(!a&&"none"===n)return{candidates:[]};let l=s(e.query);l=await q(l,this.definitionExpression,this.spatialReference),yield,l=await B(l,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield;const u=!S(i.spatialReference,this.spatialReference);u&&(await T(i.spatialReference,this.spatialReference),yield);const o="number"==typeof r?r:r.x,c="number"==typeof r?r:r.y,y={xmin:i.x-o,xmax:i.x+o,ymin:i.y-c,ymax:i.y+c,spatialReference:i.spatialReference},h=u?A(y,this.spatialReference):y;if(!h)return{candidates:[]};const d=(await Q(_(i),null,{signal:t}))[0];yield;const m=(await Q(_(h),null,{signal:t}))[0];if(yield,null==d||null==m)return{candidates:[]};const f=await this._searchFeatures(X(m.toJSON()));yield;const p=new C(f,l,this);this._executeObjectIdsQuery(p),yield,this._executeTimeQuery(p),yield,this._executeAttributesQuery(p),yield,yield*this._executeGeometryQueryForSnapping(p),yield;const x=d.toJSON(),g=u?A(x,this.spatialReference):x,F=u?Math.max(h.xmax-h.xmin,h.ymax-h.ymin)/2:r;return p.createSnappingResponse({...e,point:g,distance:F},l.returnZ,i.spatialReference)}async _getBounds(e,t,i){const r=h(d(),f);return await this.featureStore.forEachBounds(e,e=>m(r,e)),Y(r,t,i,this.spatialReference,this.hasZ)}_getFullExtent(){return this._fullExtentPromise||="getFullExtent"in this.featureStore&&this.featureStore.getFullExtent?Promise.resolve(this.featureStore.getFullExtent(this.spatialReference)):this._getAllFeatures().then(e=>this._getBounds(e,this.spatialReference,this.spatialReference)),this._fullExtentPromise}async _getAllFeaturesQueryEngineResult(e){return new C(await this._getAllFeatures(),e,this)}async _getAllFeatures(){if(null==this._allFeaturesPromise){const e=[];this._allFeaturesPromise=(async()=>await this.featureStore.forEach(t=>e.push(t)))().then(()=>i(e))}const e=this._allFeaturesPromise,t=await e;return e===this._allFeaturesPromise?t.slice():this._getAllFeatures()}async*_executeQuery(e,t){e=s(e),e=await z(e,this.definitionExpression,this.spatialReference),yield,e=await B(e,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield,e={...e,...t};const i=yield*this._executeSceneFilterQuery(e);yield;const r=yield*this._executeGeometryQuery(e,i);return yield,this._executeAggregateIdsQuery(r),yield,this._executeObjectIdsQuery(r),yield,this._executeTimeQuery(r),yield,this._executeAttributesQuery(r),r}async*_executeSceneFilterQuery(e){if(null==e.sceneFilter)return null;const{outSR:t,returnGeometry:i,returnCentroid:r}=e,s=this.featureStore.featureSpatialReference,a=e.sceneFilter.geometry,n=null==s||S(s,a.spatialReference)?a:A(a,s);if(!n)return null;const l=i||r,u=R(t)&&!S(this.spatialReference,t)&&l?async e=>this._project(e,t):e=>e;yield;const o=this.featureAdapter,c=await this._searchFeatures(X(n));yield;if("disjoint"===e.sceneFilter.spatialRelationship){if(!c.length)return null;const t=new Set;for(const e of c)t.add(o.getObjectId(e));const i=await this._getAllFeatures();yield;const r=await H("esriSpatialRelDisjoint",n,this.geometryType);yield;const s=e=>!t.has(o.getObjectId(e))||r(o.getGeometry(e)),a=yield*this._runSpatialFilter(i,s);yield;const l=new C(a,e,this);return await u(l)}if(!c.length)return new C([],e,this);if(this._canExecuteSinglePass(n,e))return await u(new C(c,e,this));const y=await H("esriSpatialRelContains",n,this.geometryType);yield;const h=yield*this._runSpatialFilter(c,e=>y(o.getGeometry(e)));return yield,await u(new C(h,e,this))}async*_executeGeometryQuery(i,r){if(null!=r&&0===r.items.length)return r;const{geometry:s,outSR:a,returnGeometry:n,returnCentroid:l}=i,u=r?null:this._getCacheKey(i),o=u?this._cache.get(u):null;if(o)return new C(o,i,this);const c=R(a)&&!S(this.spatialReference,a),y=n||l,h=async e=>(c&&y&&await this._project(e,a),u&&this._cache.put(u,e.items),e),d=this.featureStore.featureSpatialReference,m=!s||null==d||S(d,s.spatialReference)?s:A(s,d);if(!m)return await h(null!=r?r:await this._getAllFeaturesQueryEngineResult(i));yield;const f=this.featureAdapter;let p=await this._searchFeatures(X(s));yield;const x=i.spatialRel??"esriSpatialRelIntersects";if("esriSpatialRelDisjoint"===x){if(!p.length)return await h(null!=r?r:await this._getAllFeaturesQueryEngineResult(i));const e=new Set;for(const i of p)e.add(f.getObjectId(i));let t;null!=r?t=r.items:(yield,t=await this._getAllFeatures(),yield);const s=await H(x,m,this.geometryType);yield;const a=t=>!e.has(f.getObjectId(t))||s(f.getGeometry(t)),n=yield*this._runSpatialFilter(t,a);yield;const l=new C(n,i,this);return await h(l)}if(null!=r){const i=new t;p=p.filter(t=>e(r.items,t,r.items.length,i)>=0)}if(!p.length){const e=new C([],i,this);return u&&this._cache.put(u,e.items),e}if(this._canExecuteSinglePass(m,i))return await h(new C(p,i,this));const g=await H(x,m,this.geometryType);yield;const _=yield*this._runSpatialFilter(p,e=>g(f.getGeometry(e)));return yield,await h(new C(_,i,this))}_executeAggregateIdsQuery(e){if(0===e.items.length||!e.query.aggregateIds?.length||null==this.aggregateAdapter)return;const t=new Set;for(const r of e.query.aggregateIds){this.aggregateAdapter.getFeatureObjectIds(r).forEach(e=>t.add(e))}const i=this.featureAdapter.getObjectId;e.items=e.items.filter(e=>t.has(i(e)))}_executeObjectIdsQuery(e){if(0===e.items.length||!e.query.objectIds?.length)return;const t=new Set(e.query.objectIds),i=this.featureAdapter.getObjectId;e.items=e.items.filter(e=>t.has(i(e)))}_executeTimeQuery(e){if(0===e.items.length)return;const t=J(this.timeInfo,e.query.timeExtent,this.featureAdapter);null!=t&&(e.items=e.items.filter(t))}_executeAttributesQuery(e){if(0===e.items.length)return;const t=j(e.query.where,this.fieldsIndex);if(t){if(!t.isStandardized)throw new TypeError("Where clause is not standardized");e.items=e.items.filter(e=>t.testFeature(e,this.featureAdapter))}}async*_executeGeometryQueryForSnapping(e){const{query:t}=e,{spatialRel:i}=t;if(!e?.items?.length||!t.geometry||!i)return;const r=await H(i,t.geometry,this.geometryType);yield;const s=this.featureAdapter,a=e=>r(s.getGeometry(e)),n=yield*this._runSpatialFilter(e.items,a);e.items=n}*_runSpatialFilter(e,t){if(!t)return e;if(null==this._frameTask)return e.filter(e=>t(e));let i=yield;const r=new Array;for(const s of e)t(s)&&r.push(s),i.madeProgress(),i.done&&(i=yield);return r}_filterLatest(e){const{trackIdField:t,startTimeField:i,endTimeField:r}=this.timeInfo,s=r||i,a=new Map,n=this.featureAdapter.getAttribute;for(const l of e.items){const e=n(l,t),i=n(l,s),r=a.get(e);(!r||i>n(r,s))&&a.set(e,l)}e.items=Array.from(a.values())}_getCacheKey(e){const{geometry:t,spatialRel:i,returnGeometry:r,returnCentroid:s,outSR:a,resultType:n,cacheHint:l}=e;if("tile"!==n&&!l)return null;const u=r||s;return R(a)&&!S(this.spatialReference,a)&&u?JSON.stringify([t,i,a]):JSON.stringify([t,i])}_canExecuteSinglePass(e,t){const{spatialRel:i}=t;return N(e)&&("esriSpatialRelEnvelopeIntersects"===i||"esriGeometryPoint"===this.geometryType&&("esriSpatialRelIntersects"===i||"esriSpatialRelContains"===i))}async _project(e,t){if(!t||S(this.spatialReference,t))return e;const r=this.featureAdapter,s=y()?await this._getFullExtent():void 0,a=await v(e.items.map(e=>b(this.geometryType,r.getGeometry(e))),this.spatialReference,t,{areaOfInterestExtent:s});return e.items=i(a.map((t,i)=>r.cloneWithGeometry(e.items[i],I(t,this.hasZ,this.hasM)))),e}async _searchFeatures(e){const t=new Set;await Promise.all(e.map(e=>this.featureStore.forEachInBounds(e,e=>t.add(e))));const i=Array.from(t.values());return t.clear(),i}async*_executeQueryForStatistics(e,t){e=s(e);try{e=await z(e,this.definitionExpression,this.spatialReference),yield,e=await M(e,t,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),yield;const i=yield*this._executeSceneFilterQuery(e);yield;const r=yield*this._executeGeometryQuery(e,i);return yield,this._executeAggregateIdsQuery(r),yield,this._executeObjectIdsQuery(r),yield,this._executeTimeQuery(r),yield,this._executeAttributesQuery(r),yield,r}catch(i){if(i!==O)throw i;return new C([],e,this)}}get test(){}}function X(e){if(N(e)){if(F(e))return[p(Math.min(e.xmin,e.xmax),Math.min(e.ymin,e.ymax),Math.max(e.xmin,e.xmax),Math.max(e.ymin,e.ymax))];if(w(e))return e.rings.map(e=>p(Math.min(e[0][0],e[2][0]),Math.min(e[0][1],e[2][1]),Math.max(e[0][0],e[2][0]),Math.max(e[0][1],e[2][1])))}return[g(x(),e)]}function Y(e,t,i,r,s){const a={xmin:e[0],ymin:e[1],xmax:e[3],ymax:e[4],spatialReference:E(r)};s&&isFinite(e[2])&&isFinite(e[5])&&(a.zmin=e[2],a.zmax=e[5],a.hasZ=!0);const n=A(a,t,i);if(n.spatialReference=E(i),n.xmax-n.xmin===0){const e=o(n.spatialReference);n.xmin-=e,n.xmax+=e}if(n.ymax-n.ymin===0){const e=o(n.spatialReference);n.ymin-=e,n.ymax+=e}if(s&&null!=n.zmin&&null!=n.zmax&&n.zmax-n.zmin===0){const e=o(n.spatialReference);n.zmin-=e,n.zmax+=e}return n}export{K as Feature,W as QueryEngine,Y as getQueryResultExtent};
@@ -2,4 +2,4 @@
2
2
  All material copyright Esri, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{clone as e}from"../../../core/lang.js";import{polygonCentroid as t,extentCentroid as i}from"../../../geometry/support/centroid.js";import{getPolygonExtent as s,getGeometryExtent as a}from"../../../geometry/support/extentUtils.js";import{toQuantizationTransform as n}from"../../../geometry/support/quantizationUtils.js";import{isValid as r,equals as o}from"../../../geometry/support/spatialReferenceUtils.js";import l from"./AttributesBuilder.js";import{cleanFromGeometryEngine as u,getGeometry as c,transformCentroid as m}from"./geometryUtils.js";import{project as d}from"./projectionSupport.js";import{getDateInNumber as f}from"./queryUtils.js";import{SnappingCandidateEdge as p,SnappingCandidateVertex as h}from"./SnappingCandidate.js";import{isDateField as y,isDateOnlyField as g,isTimestampOffsetField as x,isStringField as T,isTimeOnlyField as F}from"../../support/fieldUtils.js";import I from"../../../rest/support/AutoIntervalBinParameters.js";import _ from"../../../rest/support/DateBinParameters.js";import{unitsDict as S}from"../../../rest/support/DateBinUtils.js";import V from"../../../rest/support/FixedBoundariesBinParameters.js";import v from"../../../rest/support/FixedIntervalBinParameters.js";import{calculateStringStatistics as b,calculateStatistics as R,processSummaryStatisticsResult as B,calculateUniqueValuesCount as z,createUVResult as M,calculateClassBreaks as A,resolveCBResult as N,calculateHistogram as w,getAttributeComparator as D,calculatePercentile as P,binIndex as q,getBinParams as j,isNullCountSupported as Z}from"../../../statistics/utils.js";import{utc as G}from"../../../time/constants.js";import{DateTime as C}from"luxon";const O="bin";class E{constructor(e,t,i){this.items=e,this.query=t,this.geometryType=i.geometryType,this.hasM=i.hasM,this.hasZ=i.hasZ,this.fieldsIndex=i.fieldsIndex,this.objectIdField=i.objectIdField,this.spatialReference=i.spatialReference,this.featureAdapter=i.featureAdapter}get size(){return this.items.length}createQueryResponseForCount(){const e=new l(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);const{groupByFieldsForStatistics:t,having:i,outStatistics:s}=this.query,a=t?.length;if(!!!a)return 1;const n=new Map,r=new Map,o=new Set;for(const l of s){const{statisticType:s}=l,a="exceedslimit"!==s?l.onStatisticField:void 0;if(!r.has(a)){const i=[];for(const s of t){const t=this._getAttributeValues(e,s,this.items,n);i.push(t)}r.set(a,this._calculateUniqueValues(i,this.items,e.returnDistinctValues))}const u=r.get(a);for(const t in u){const{data:s,items:a}=u[t],n=s.join(",");i&&!e.validateItems(a,i)||o.add(n)}}return o.size}async createQueryResponse(){let e;if(this.query.outStatistics){e=this.query.outStatistics.some(e=>"exceedslimit"===e.statisticType)?this._createExceedsLimitQueryResponse():await this._createStatisticsQueryResponse(this.query,this.items)}else e=this._createFeatureQueryResponse(this.query);if(this.query.returnQueryGeometry){const t=this.query.geometry;r(this.query.outSR)&&!o(t.spatialReference,this.query.outSR)?e.queryGeometry=u({spatialReference:this.query.outSR,...d(t,t.spatialReference,this.query.outSR)}):e.queryGeometry=u({spatialReference:this.query.outSR,...t})}return e}createSnappingResponse(e,t,i){const s=this.featureAdapter,a=Q(this.hasZ,this.hasM),{point:n,mode:r}=e,o="number"==typeof e.distance?e.distance:e.distance.x,l="number"==typeof e.distance?e.distance:e.distance.y,u={candidates:[]},c="esriGeometryPolygon"===this.geometryType,m="esriGeometryPolyline"===this.geometryType||"esriGeometryPoint"===this.geometryType,d=this._getPointCreator(r,t,this.spatialReference,i),f=new U(null,0),y=new U(null,0),g={x:0,y:0,z:0};for(const x of this.items){const t=s.getGeometry(x);if(null==t)continue;const{coords:i}=t,r=t.isPoint?J:t.lengths;if(f.coords=i,y.coords=i,e.returnEdge){let e=0;for(let t=0;t<r.length;t++){const i=r[t],m=e;for(let t=0;t<i;t++,e+=a){if(!c&&t===i-1)continue;const r=f;r.coordsIndex=e;const h=y;h.coordsIndex=t===i-1?m:e+a;const T=g;if(!H(g,n,r,h))continue;const F=(n.x-T.x)/o,I=(n.y-T.y)/l,_=F*F+I*I;_<=1&&u.candidates.push(new p(s.getObjectId(x),d(T),Math.sqrt(_),d(r),d(h)))}}}if("all"===e.vertexMode){let e=0;for(let t=0;t<r.length;t++){const i=r[t],m=e,p=y;p.coordsIndex=m;for(let t=0;t<i;t++,e+=a){const a=f;if(a.coordsIndex=e,c&&t===i-1&&a.x===p.x&&a.y===p.y)continue;const r=(n.x-a.x)/o,m=(n.y-a.y)/l,y=r*r+m*m;y<=1&&u.candidates.push(new h(s.getObjectId(x),d(a),Math.sqrt(y)))}}}else if(m&&"ends"===e.vertexMode){let e=0;const t=[];for(let i=0;i<r.length;i++){t.push(e);const s=r[i];e+=s*a,!c&&s>1&&t.push(e-a)}for(const i of t){const e=f;e.coordsIndex=i;const t=(n.x-e.x)/o,a=(n.y-e.y)/l,r=t*t+a*a;r<=1&&u.candidates.push(new h(s.getObjectId(x),d(e),Math.sqrt(r)))}}}return u.candidates.sort((e,t)=>e.distance-t.distance),u}_getPointCreator(e,t,i,s){const a=null==s||o(i,s)?e=>e:e=>d(e,i,s),{hasZ:n}=this,r=0;return"3d"===e?n&&t?({x:e,y:t,z:i})=>a({x:e,y:t,z:i}):({x:e,y:t})=>a({x:e,y:t,z:r}):({x:e,y:t})=>a({x:e,y:t})}async createSummaryStatisticsResponse(e){const{field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,minValue:r,maxValue:o,scale:l,timeZone:u,outStatisticTypes:c}=e,m=this.fieldsIndex.get(t),d=y(m)||g(m)||x(m),f=await this._getDataValues({field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,scale:l,timeZone:u},this.items),p=Z({normalizationType:a,normalizationField:s,minValue:r,maxValue:o}),h={value:.5,fieldType:m?.type},F=T(m)?b({values:f,supportsNullCount:p,percentileParams:h,outStatisticTypes:c}):R({values:f,minValue:r,maxValue:o,useSampleStdDev:!a,supportsNullCount:p,percentileParams:h,outStatisticTypes:c});return B(F,c,d)}async createUniqueValuesResponse(e){const{field:t,valueExpression:i,domains:s,returnAllCodedValues:a,scale:n,timeZone:r}=e,o=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:i,scale:n,timeZone:r},this.items,!1),l=z(o);return M(l,s,a,e.fieldDelimiter)}async createClassBreaksResponse(e){const{field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numClasses:c,scale:m,timeZone:d}=e,f=await this._getDataValues({field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,scale:m,timeZone:d},this.items),p=A(f,{field:t,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numClasses:c});return N(p,r)}async createHistogramResponse(e){const{field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numBins:c,scale:m,timeZone:d}=e,f=await this._getDataValues({field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,scale:m,timeZone:d},this.items);return w(f,{field:t,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numBins:c})}_sortFeatures(e,t,i){if(e.length>1&&t?.length)for(const s of t.slice().reverse()){const t=s.split(" "),a=t[0],n=this.fieldsIndex.get(a),r=!!t[1]&&"desc"===t[1].toLowerCase(),o=D(n?.type,r,"case-sensitive");e.sort((e,t)=>{const s=i(e,a,n),r=i(t,a,n);return o(s,r)})}}_createFeatureQueryResponse(e){const{items:t,geometryType:i,hasM:s,hasZ:a,objectIdField:r,spatialReference:o}=this,{outFields:l,outSR:c,quantizationParameters:m,resultRecordCount:d,resultOffset:f,returnZ:p,returnM:h}=e,y=null!=d&&t.length>(f||0)+d,g=l&&(l.includes("*")?[...this.fieldsIndex.fields]:l.map(e=>this.fieldsIndex.get(e)));return{exceededTransferLimit:y,features:this._createFeatures(e,t),fields:g,geometryType:i,hasM:s&&h,hasZ:a&&p,objectIdFieldName:r,spatialReference:u(c||o),transform:m&&n(m)||null}}_createFeatures(e,t){const i=new l(e,this.featureAdapter,this.fieldsIndex),{hasM:s,hasZ:a}=this,{orderByFields:r,quantizationParameters:o,returnGeometry:u,returnCentroid:d,maxAllowableOffset:f,resultOffset:p,resultRecordCount:h,returnZ:y=!1,returnM:g=!1}=e,x=a&&y,T=s&&g;let F=[],I=0;const _=[...t];if(this._sortFeatures(_,r,(e,t,s)=>i.getFieldValue(e,t,s)),this.geometryType&&(u||d)){const e=n(o)??void 0,t="esriGeometryPolygon"===this.geometryType||"esriGeometryPolyline"===this.geometryType;if(u&&!d)for(const s of _){const a=this.featureAdapter.getGeometry(s),n=this._addFeatureJSONMetadata(s,{attributes:i.getAttributes(s),geometry:c(this.geometryType,a,f,e,x,T)});t&&a&&!n.geometry&&(n.centroid=m(this,this.featureAdapter.getCentroid(s,this),e)),F[I++]=n}else if(!u&&d)for(const s of _)F[I++]=this._addFeatureJSONMetadata(s,{attributes:i.getAttributes(s),centroid:m(this,this.featureAdapter.getCentroid(s,this),e)});else for(const s of _)F[I++]=this._addFeatureJSONMetadata(s,{attributes:i.getAttributes(s),centroid:m(this,this.featureAdapter.getCentroid(s,this),e),geometry:c(this.geometryType,this.featureAdapter.getGeometry(s),f,e,x,T)})}else for(const n of _){const e=i.getAttributes(n);e&&(F[I++]=this._addFeatureJSONMetadata(n,{attributes:e}))}const S=p||0;if(null!=h){const e=S+h;F=F.slice(S,Math.min(F.length,e))}return F}_addFeatureJSONMetadata(e,t){const i=this.featureAdapter.getMetadata?.(e);return void 0!==i&&(t.metadata=i),t}_createExceedsLimitQueryResponse(){let e=!1,t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;for(const a of this.query.outStatistics??[])if("exceedslimit"===a.statisticType){t=null!=a.maxPointCount?a.maxPointCount:Number.POSITIVE_INFINITY,i=null!=a.maxRecordCount?a.maxRecordCount:Number.POSITIVE_INFINITY,s=null!=a.maxVertexCount?a.maxVertexCount:Number.POSITIVE_INFINITY;break}if("esriGeometryPoint"===this.geometryType)e=this.items.length>t;else if(this.items.length>i)e=!0;else{const t=Q(this.hasZ,this.hasM),i=this.featureAdapter;e=this.items.reduce((e,t)=>{const s=i.getGeometry(t);return e+(null!=s&&s.coords.length||0)},0)/t>s}return{fields:[{name:"exceedslimit",type:"esriFieldTypeInteger",alias:"exceedslimit",sqlType:"sqlTypeInteger",domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(e)}}]}}async _createStatisticsQueryResponse(e,t,i={attributes:{}}){const s=[],a=new Map,n=new Map,r=new Map,o=new Map,u=new l(e,this.featureAdapter,this.fieldsIndex),c=e.outStatistics,{groupByFieldsForStatistics:m,having:d,orderByFields:f,resultRecordCount:p}=e,h=m?.length,y=!!h,g=y?m[0]:null,x=y&&!this.fieldsIndex.get(g);for(const l of c??[]){const{outStatisticFieldName:e,statisticType:c}=l,f=l,p="exceedslimit"!==c?l.onStatisticField:void 0,F="percentile_disc"===c||"percentile_cont"===c,I="EnvelopeAggregate"===c||"CentroidAggregate"===c||"ConvexHullAggregate"===c,_=y&&1===h&&(p===g||x)&&"count"===c;if(y){if(!r.has(p)){const e=[];for(const i of m){const s=this._getAttributeValues(u,i,t,a);e.push(s)}r.set(p,this._calculateUniqueValues(e,t,!I&&u.returnDistinctValues))}const i=r.get(p);if(!i)continue;const s=Object.keys(i);for(const n of s){const{count:s,data:r,items:l,itemPositions:c}=i[n],h=r.join(",");if(!d||u.validateItems(l,d)){const i=o.get(h)||{attributes:{}};if(I){i.aggregateGeometries||(i.aggregateGeometries={});const{aggregateGeometries:e,outStatisticFieldName:t}=await this._getAggregateGeometry(f,l);i.aggregateGeometries[t]=e}else{let n=null;if(_)n=s;else{const e=this._getAttributeValues(u,p,t,a),i=c.map(t=>e[t]);n=F&&"statisticParameters"in f?this._getPercentileValue(f,i):this._getStatisticValue(f,i,null,u.returnDistinctValues)}i.attributes[e]=n}let n=0;m.forEach((e,t)=>i.attributes[this.fieldsIndex.get(e)?e:"EXPR_"+ ++n]=r[t]),o.set(h,i)}}}else if(I){i.aggregateGeometries||(i.aggregateGeometries={});const{aggregateGeometries:e,outStatisticFieldName:s}=await this._getAggregateGeometry(f,t);i.aggregateGeometries[s]=e}else{const s=this._getAttributeValues(u,p,t,a);i.attributes[e]=F&&"statisticParameters"in f?this._getPercentileValue(f,s):this._getStatisticValue(f,s,n,u.returnDistinctValues)}const S="min"!==c&&"max"!==c||!T(this.fieldsIndex.get(p))&&!this._isAnyDateField(p)?null:this.fieldsIndex.get(p)?.type;s.push({name:e,alias:e,type:S||"esriFieldTypeDouble"})}const F=y?Array.from(o.values()):[i];return this._sortFeatures(F,f,(e,t)=>e.attributes[t]),p&&(F.length=Math.min(p,F.length)),{fields:s,features:F}}_isAnyDateField(e){const t=this.fieldsIndex.get(e);return y(t)||g(t)||x(t)||F(t)}async _getAggregateGeometry(e,n){const{convexHull:r,union:o}=await import("../../../geometry/geometryEngineJSON.js"),{statisticType:l,outStatisticFieldName:u}=e,{featureAdapter:m,spatialReference:d,geometryType:f}=this,p=n.map(e=>c(f,m.getGeometry(e))),h=r(d,p,!0)[0],y={aggregateGeometries:null,outStatisticFieldName:null};if("EnvelopeAggregate"===l){const e=h?s(h):a(o(d,p));y.aggregateGeometries={...e,spatialReference:d},y.outStatisticFieldName=u||"extent"}else if("CentroidAggregate"===l){const e=h?t(h):i(a(o(d,p)));y.aggregateGeometries={x:e[0],y:e[1],spatialReference:d},y.outStatisticFieldName=u||"centroid"}else"ConvexHullAggregate"===l&&(y.aggregateGeometries=h,y.outStatisticFieldName=u||"convexHull");return y}_getStatisticValue(e,t,i,s){const{onStatisticField:a,statisticType:n}=e;let r=null;r=i?.has(a)?i.get(a):T(this.fieldsIndex.get(a))||this._isAnyDateField(a)?b({values:t,returnDistinct:s}):R({values:s?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),i&&i.set(a,r);return r["var"===n?"variance":n]}_getPercentileValue(e,t){const{onStatisticField:i,statisticParameters:s,statisticType:a}=e,{value:n,orderBy:r}=s,o=this.fieldsIndex.get(i);return P(t,{value:n,orderBy:r,fieldType:o?.type,isDiscrete:"percentile_disc"===a})}_getAttributeValues(e,t,i,s){if(s.has(t))return s.get(t);const a=this.fieldsIndex.get(t),n=i.map(i=>e.getFieldValue(i,t,a));return s.set(t,n),n}_calculateUniqueValues(e,t,i){const s={},a=t.length;for(let n=0;n<a;n++){const a=t[n],r=[];for(const t of e)r.push(t[n]);const o=r.join(",");null==s[o]?s[o]={count:1,data:r,items:[a],itemPositions:[n]}:(i||s[o].count++,s[o].items.push(a),s[o].itemPositions.push(n))}return s}async _getDataValues(t,i,s=!0){const a=new l(this.query,this.featureAdapter,this.fieldsIndex),{valueExpression:n,scale:r,timeZone:o}=t;return n?a.getExpressionValues(i,n,{viewingMode:"map",scale:r,spatialReference:this.query.outSR||this.spatialReference},{geometryType:this.geometryType,hasZ:this.hasZ,hasM:this.hasM},o):a.getDataValues(i,e(t),s)}_calculateHistogramBins(e,t,i){if(null==t.min&&null==t.max)return[];const s=t.intervals,a=t.min??0,n=t.max??0,r=s.map(([e,t])=>({minValue:e,maxValue:t,count:0,items:[]}));for(let o=0;o<e.length;o++){const t=e[o],l=i[o];if(null!=t&&t>=a&&t<=n){const e=q(s,t);e>-1&&(r[e].count++,r[e].items.push(l))}}return r}async createQueryBinsResponse(e){const t=e.bin?.splitBy;if(!t)return this._createBinsResponse(e);const{value:i,outAlias:s,valueType:a}=t,n=[],r=[{name:s??i,alias:s??i,type:a??"esriFieldTypeString"},{name:O,alias:O,type:"esriFieldTypeInteger"}],o=new l(e,this.featureAdapter,this.fieldsIndex),u=new Map,c=[...this.items];this._sortFeatures(c,[i],(e,t,i)=>o.getFieldValue(e,t,i));const m=this._getAttributeValues(o,i,c,u),d=this._calculateUniqueValues([m],c,o.returnDistinctValues);for(const l in d){const{items:t}=d[l],a=await this._createBinsResponse(e,t);if(n.push(...a.features.map(e=>({...e,attributes:{...e.attributes,[s??i]:l}}))),a.fields)for(const e of a.fields)r.some(t=>t.name===e.name)||r.push(e)}return{fields:r,features:n}}async _createBinsResponse(e,t){const i=e.bin;switch(t=t??this.items,i.type){case"autoIntervalBin":return this._createAutoIntervalBinsResponse(I.fromJSON(i),e,t);case"dateBin":return this._createDateBinsResponse(_.fromJSON(i),e,t);case"fixedBoundariesBin":return this._createFixedBoundariesBinsResponse(V.fromJSON(i),e,t);case"fixedIntervalBin":return this._createFixedIntervalBinsResponse(v.fromJSON(i),e,t)}}async _createAutoIntervalBinsResponse(e,t,i){const{field:s,normalizationField:a,numBins:n,normalizationType:r,normalizationTotal:o,start:l,end:u}=e,c=await this._getDataValues({field:e.field,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},i),m=j(c,{field:s,normalizationField:a,normalizationType:r,normalizationTotal:o,numBins:n,minValue:f(l,!1),maxValue:f(u,!1)}),d=this._calculateHistogramBins(c,m,i);return this._createFeaturesFromHistogramBins(d,t)}async _createDateBinsResponse(e,t,i){const{field:s,interval:a,start:n,end:r,snapToData:o,returnFullIntervalBin:l}=e,u=a.unit,c=await this._getDataValues({field:e.field,timeZone:t.outTimeReference?.ianaTimeZone},i),m=F(this.fieldsIndex.get(s)),d=S.toJSON(u),p=c.filter(Boolean).sort((e,t)=>e-t),h=null!=n?f(n,m):p[0],y=null!=r?f(r,m):p[p.length-1],g=[];if(null!=h&&null!=y){const e={zone:t.outTimeReference?.ianaTimeZone??G},i=C.fromMillis(h,e),s=C.fromMillis(y,e);if("last"===o){let e=s;for(;e>i;){const t=e.minus({[d]:a.value});if(t<i){g.unshift([l?t.toMillis():i.toMillis(),e.toMillis()]);break}g.unshift([t.toMillis(),e.toMillis()]),e=t}}else{let e="first"===o?i:i.startOf(d);for(;e<=s;){const t=e.plus({[d]:a.value});if(t>s){g.push([e.toMillis(),l?t.toMillis():s.toMillis()]);break}g.push([e.toMillis(),t.toMillis()]),e=t}}}const x=this._calculateHistogramBins(c,{intervals:g,min:h,max:y},i);return this._createFeaturesFromHistogramBins(x,t)}async _createFixedBoundariesBinsResponse(e,t,i){const{field:s}=e,a=await this._getDataValues({field:s,timeZone:t.outTimeReference?.ianaTimeZone},i),n=F(this.fieldsIndex.get(s)),r=e.boundaries.map(e=>f(e,n)).sort((e,t)=>e-t),o=[];for(let c=0;c<r.length-1;c++)o.push([r[c],r[c+1]]);const l={intervals:o,min:r.at(0),max:r.at(-1)},u=this._calculateHistogramBins(a,l,i);return this._createFeaturesFromHistogramBins(u,t)}async _createFixedIntervalBinsResponse(e,t,i){const{field:s,interval:a,start:n,end:r}=e,o=await this._getDataValues({field:e.field,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},i),l=F(this.fieldsIndex.get(s)),u=j(o,{field:s,classificationMethod:"defined-interval",definedInterval:a,minValue:f(n,l),maxValue:f(r,l)},!0),c=this._calculateHistogramBins(o,u,i);return this._createFeaturesFromHistogramBins(c,t)}async _createFeaturesFromHistogramBins(e,t){const{upperBoundaryAlias:i,lowerBoundaryAlias:s}=t,a=s||"lowerBoundary",n=i||"upperBoundary",r=[],o=[{name:a,alias:a,type:"esriFieldTypeDouble"},{name:n,alias:n,type:"esriFieldTypeDouble"}],l=t.bin?.stackBy?.value,u=t.bin?.stackBy?.outAlias;l&&o.push({name:O,alias:O,type:"esriFieldTypeInteger"},{name:u??l,alias:u??l,type:"esriFieldTypeString"});let c=0;const m="dateBin"===t.bin.type,d=t.outTimeReference?.ianaTimeZone;for(const f of e){const{minValue:e,maxValue:i,items:s}=f,p={attributes:{}};let h;if(p.attributes[a]=m&&d&&null!=e?C.fromMillis(e,{zone:d}).toISO():e,p.attributes[n]=m&&d&&null!=i?C.fromMillis(i,{zone:d}).toISO():i,l?(h=await this._createStatisticsQueryResponse({...t,groupByFieldsForStatistics:[l],orderByFields:[l]},s),p.attributes[O]=++c,"flat"===t.bin.jsonStyle?r.push(...h.features.map(({attributes:{EXPR_1:e,...t},...i})=>({...i,attributes:u??e?{...t,[u??e]:e,...p.attributes}:{...t,...p.attributes}}))):(p.stackedAttributes=h.features.map(({attributes:{EXPR_1:e,...t}})=>u??e?{...t,[u??e]:e}:t),r.push(p))):(t.bin?.splitBy&&(p.attributes[O]=++c),h=await this._createStatisticsQueryResponse(t,s,p),r.push(p)),h.fields)for(const t of h.fields)o.some(e=>e.name===t.name)||o.push(t)}return"desc"===t.binOrder&&r.reverse(),{fields:o,features:r}}}function H(e,t,i,s){const a=s.x-i.x,n=s.y-i.y,r=t.x-i.x,o=t.y-i.y,l=a*a+n*n;if(0===l)return!1;const u=r*a+o*n,c=Math.min(1,Math.max(0,u/l));return e.x=i.x+a*c,e.y=i.y+n*c,!0}function Q(e,t){return e?t?4:3:t?3:2}class U{constructor(e,t){this.coords=e,this.coordsIndex=t}get x(){return this.coords[this.coordsIndex]}get y(){return this.coords[this.coordsIndex+1]}get z(){return this.coords[this.coordsIndex+2]}}const J=[1];export{E as QueryEngineResult};
5
+ import{clone as e}from"../../../core/lang.js";import{polygonCentroid as t,extentCentroid as i}from"../../../geometry/support/centroid.js";import{getPolygonExtent as s,getGeometryExtent as a}from"../../../geometry/support/extentUtils.js";import{toQuantizationTransform as n}from"../../../geometry/support/quantizationUtils.js";import{isValid as r,equals as o}from"../../../geometry/support/spatialReferenceUtils.js";import l from"./AttributesBuilder.js";import{cleanFromGeometryEngine as u,getGeometry as c,transformCentroid as m}from"./geometryUtils.js";import{project as d}from"./projectionSupport.js";import{getDateInNumber as f}from"./queryUtils.js";import{SnappingCandidateEdge as p,SnappingCandidateVertex as h}from"./SnappingCandidate.js";import{isDateField as y,isDateOnlyField as g,isTimestampOffsetField as x,isStringField as T,isTimeOnlyField as F}from"../../support/fieldUtils.js";import I from"../../../rest/support/AutoIntervalBinParameters.js";import _ from"../../../rest/support/DateBinParameters.js";import{unitsDict as S}from"../../../rest/support/DateBinUtils.js";import V from"../../../rest/support/FixedBoundariesBinParameters.js";import v from"../../../rest/support/FixedIntervalBinParameters.js";import{isNullCountSupported as b,calculateStringStatistics as R,calculateStatistics as B,processSummaryStatisticsResult as z,calculateUniqueValuesCount as M,createUVResult as A,calculateClassBreaks as N,resolveCBResult as w,calculateHistogram as D,getAttributeComparator as P,calculatePercentile as q,binIndex as j,getBinParams as Z}from"../../../statistics/utils.js";import{utc as G}from"../../../time/constants.js";import{DateTime as C}from"luxon";const O="bin";class E{constructor(e,t,i){this.items=e,this.query=t,this.geometryType=i.geometryType,this.hasM=i.hasM,this.hasZ=i.hasZ,this.fieldsIndex=i.fieldsIndex,this.objectIdField=i.objectIdField,this.spatialReference=i.spatialReference,this.featureAdapter=i.featureAdapter}get size(){return this.items.length}createQueryResponseForCount(){const e=new l(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);const{groupByFieldsForStatistics:t,having:i,outStatistics:s}=this.query,a=t?.length;if(!!!a)return 1;const n=new Map,r=new Map,o=new Set;for(const l of s){const{statisticType:s}=l,a="exceedslimit"!==s?l.onStatisticField:void 0;if(!r.has(a)){const i=[];for(const s of t){const t=this._getAttributeValues(e,s,this.items,n);i.push(t)}r.set(a,this._calculateUniqueValues(i,this.items,e.returnDistinctValues))}const u=r.get(a);for(const t in u){const{data:s,items:a}=u[t],n=s.join(",");i&&!e.validateItems(a,i)||o.add(n)}}return o.size}async createQueryResponse(){let e;if(this.query.outStatistics){e=this.query.outStatistics.some(e=>"exceedslimit"===e.statisticType)?this._createExceedsLimitQueryResponse():await this._createStatisticsQueryResponse(this.query,this.items)}else e=this._createFeatureQueryResponse(this.query);if(this.query.returnQueryGeometry){const t=this.query.geometry;r(this.query.outSR)&&!o(t.spatialReference,this.query.outSR)?e.queryGeometry=u({spatialReference:this.query.outSR,...d(t,t.spatialReference,this.query.outSR)}):e.queryGeometry=u({spatialReference:this.query.outSR,...t})}return e}createSnappingResponse(e,t,i){const s=this.featureAdapter,a=Q(this.hasZ,this.hasM),{point:n,mode:r}=e,o="number"==typeof e.distance?e.distance:e.distance.x,l="number"==typeof e.distance?e.distance:e.distance.y,u={candidates:[]},c="esriGeometryPolygon"===this.geometryType,m="esriGeometryPolyline"===this.geometryType||"esriGeometryPoint"===this.geometryType,d=this._getPointCreator(r,t,this.spatialReference,i),f=new U(null,0),y=new U(null,0),g={x:0,y:0,z:0};for(const x of this.items){const t=s.getGeometry(x);if(null==t)continue;const{coords:i}=t,r=t.isPoint?J:t.lengths;if(f.coords=i,y.coords=i,e.returnEdge){let e=0;for(let t=0;t<r.length;t++){const i=r[t],m=e;for(let t=0;t<i;t++,e+=a){if(!c&&t===i-1)continue;const r=f;r.coordsIndex=e;const h=y;h.coordsIndex=t===i-1?m:e+a;const T=g;if(!H(g,n,r,h))continue;const F=(n.x-T.x)/o,I=(n.y-T.y)/l,_=F*F+I*I;_<=1&&u.candidates.push(new p(s.getObjectId(x),d(T),Math.sqrt(_),d(r),d(h)))}}}if("all"===e.vertexMode){let e=0;for(let t=0;t<r.length;t++){const i=r[t],m=e,p=y;p.coordsIndex=m;for(let t=0;t<i;t++,e+=a){const a=f;if(a.coordsIndex=e,c&&t===i-1&&a.x===p.x&&a.y===p.y)continue;const r=(n.x-a.x)/o,m=(n.y-a.y)/l,y=r*r+m*m;y<=1&&u.candidates.push(new h(s.getObjectId(x),d(a),Math.sqrt(y)))}}}else if(m&&"ends"===e.vertexMode){let e=0;const t=[];for(let i=0;i<r.length;i++){t.push(e);const s=r[i];e+=s*a,!c&&s>1&&t.push(e-a)}for(const i of t){const e=f;e.coordsIndex=i;const t=(n.x-e.x)/o,a=(n.y-e.y)/l,r=t*t+a*a;r<=1&&u.candidates.push(new h(s.getObjectId(x),d(e),Math.sqrt(r)))}}}return u.candidates.sort((e,t)=>e.distance-t.distance),u}_getPointCreator(e,t,i,s){const a=null==s||o(i,s)?e=>e:e=>d(e,i,s),{hasZ:n}=this,r=0;return"3d"===e?n&&t?({x:e,y:t,z:i})=>a({x:e,y:t,z:i}):({x:e,y:t})=>a({x:e,y:t,z:r}):({x:e,y:t})=>a({x:e,y:t})}async createSummaryStatisticsResponse(e){const{field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,minValue:r,maxValue:o,scale:l,timeZone:u,outStatisticTypes:c}=e,m=this.fieldsIndex.get(t),d=y(m)||g(m)||x(m),f=await this._getDataValues({field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,scale:l,timeZone:u},this.items),p=b({normalizationType:a,normalizationField:s,minValue:r,maxValue:o}),h={value:.5,fieldType:m?.type},F=T(m)?R({values:f,supportsNullCount:p,percentileParams:h,outStatisticTypes:c}):B({values:f,minValue:r,maxValue:o,useSampleStdDev:!a,supportsNullCount:p,percentileParams:h,outStatisticTypes:c});return z(F,c,d)}async createUniqueValuesResponse(e){const{field:t,valueExpression:i,domains:s,returnAllCodedValues:a,scale:n,timeZone:r}=e,o=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:i,scale:n,timeZone:r},this.items,!1),l=M(o);return A(l,s,a,e.fieldDelimiter)}async createClassBreaksResponse(e){const{field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numClasses:c,scale:m,timeZone:d}=e,f=await this._getDataValues({field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,scale:m,timeZone:d},this.items),p=N(f,{field:t,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numClasses:c});return w(p,r)}async createHistogramResponse(e){const{field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numBins:c,scale:m,timeZone:d}=e,f=await this._getDataValues({field:t,valueExpression:i,normalizationField:s,normalizationType:a,normalizationTotal:n,scale:m,timeZone:d},this.items);return D(f,{field:t,normalizationField:s,normalizationType:a,normalizationTotal:n,classificationMethod:r,standardDeviationInterval:o,minValue:l,maxValue:u,numBins:c})}_sortFeatures(e,t,i){if(e.length>1&&t?.length)for(const s of t.slice().reverse()){const t=s.split(" "),a=t[0],n=this.fieldsIndex.get(a),r=!!t[1]&&"desc"===t[1].toLowerCase(),o=P(n?.type,r,"case-sensitive");e.sort((e,t)=>{const s=i(e,a,n),r=i(t,a,n);return o(s,r)})}}_createFeatureQueryResponse(e){const{items:t,geometryType:i,hasM:s,hasZ:a,objectIdField:r,spatialReference:o}=this,{outFields:l,outSR:c,quantizationParameters:m,resultRecordCount:d,resultOffset:f,returnZ:p,returnM:h}=e,y=null!=d&&t.length>(f||0)+d,g=l&&(l.includes("*")?[...this.fieldsIndex.fields]:l.map(e=>this.fieldsIndex.get(e)));return{exceededTransferLimit:y,features:this._createFeatures(e,t),fields:g,geometryType:i,hasM:s&&h,hasZ:a&&p,objectIdFieldName:r,spatialReference:u(c||o),transform:m&&n(m)||null}}_createFeatures(e,t){const i=new l(e,this.featureAdapter,this.fieldsIndex),{hasM:s,hasZ:a}=this,{orderByFields:r,quantizationParameters:o,returnGeometry:u,returnCentroid:d,maxAllowableOffset:f,resultOffset:p,resultRecordCount:h,returnZ:y=!1,returnM:g=!1}=e,x=a&&y,T=s&&g;let F=[],I=0;const _=[...t];if(this._sortFeatures(_,r,(e,t,s)=>i.getFieldValue(e,t,s)),this.geometryType&&(u||d)){const e=n(o)??void 0,t="esriGeometryPolygon"===this.geometryType||"esriGeometryPolyline"===this.geometryType;if(u&&!d)for(const s of _){const a=this.featureAdapter.getGeometry(s),n=this._addFeatureJSONMetadata(s,{attributes:i.getAttributes(s),geometry:c(this.geometryType,a,f,e,x,T)});t&&a&&!n.geometry&&(n.centroid=m(this,this.featureAdapter.getCentroid(s,this),e)),F[I++]=n}else if(!u&&d)for(const s of _)F[I++]=this._addFeatureJSONMetadata(s,{attributes:i.getAttributes(s),centroid:m(this,this.featureAdapter.getCentroid(s,this),e)});else for(const s of _)F[I++]=this._addFeatureJSONMetadata(s,{attributes:i.getAttributes(s),centroid:m(this,this.featureAdapter.getCentroid(s,this),e),geometry:c(this.geometryType,this.featureAdapter.getGeometry(s),f,e,x,T)})}else for(const n of _){const e=i.getAttributes(n);e&&(F[I++]=this._addFeatureJSONMetadata(n,{attributes:e}))}const S=p||0;if(null!=h){const e=S+h;F=F.slice(S,Math.min(F.length,e))}return F}_addFeatureJSONMetadata(e,t){const i=this.featureAdapter.getMetadata?.(e);return void 0!==i&&(t.metadata=i),t}_createExceedsLimitQueryResponse(){let e=!1,t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;for(const a of this.query.outStatistics??[])if("exceedslimit"===a.statisticType){t=null!=a.maxPointCount?a.maxPointCount:Number.POSITIVE_INFINITY,i=null!=a.maxRecordCount?a.maxRecordCount:Number.POSITIVE_INFINITY,s=null!=a.maxVertexCount?a.maxVertexCount:Number.POSITIVE_INFINITY;break}if("esriGeometryPoint"===this.geometryType)e=this.items.length>t;else if(this.items.length>i)e=!0;else{const t=Q(this.hasZ,this.hasM),i=this.featureAdapter;e=this.items.reduce((e,t)=>{const s=i.getGeometry(t);return e+(null!=s&&s.coords.length||0)},0)/t>s}return{fields:[{name:"exceedslimit",type:"esriFieldTypeInteger",alias:"exceedslimit",sqlType:"sqlTypeInteger",domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(e)}}]}}async _createStatisticsQueryResponse(e,t,i={attributes:{}}){const s=[],a=new Map,n=new Map,r=new Map,o=new Map,u=new l(e,this.featureAdapter,this.fieldsIndex),c=e.outStatistics,{groupByFieldsForStatistics:m,having:d,orderByFields:f,resultRecordCount:p}=e,h=m?.length,y=!!h,g=y?m[0]:null,x=y&&!this.fieldsIndex.get(g);for(const l of c??[]){const{outStatisticFieldName:e,statisticType:c}=l,f=l,p="exceedslimit"!==c?l.onStatisticField:void 0,F="percentile_disc"===c||"percentile_cont"===c,I="EnvelopeAggregate"===c||"CentroidAggregate"===c||"ConvexHullAggregate"===c,_=y&&1===h&&(p===g||x)&&"count"===c;if(y){if(!r.has(p)){const e=[];for(const i of m){const s=this._getAttributeValues(u,i,t,a);e.push(s)}r.set(p,this._calculateUniqueValues(e,t,!I&&u.returnDistinctValues))}const i=r.get(p);if(!i)continue;const s=Object.keys(i);for(const n of s){const{count:s,data:r,items:l,itemPositions:c}=i[n],h=r.join(",");if(!d||u.validateItems(l,d)){const i=o.get(h)||{attributes:{}};if(I){i.aggregateGeometries||(i.aggregateGeometries={});const{aggregateGeometries:e,outStatisticFieldName:t}=await this._getAggregateGeometry(f,l);i.aggregateGeometries[t]=e}else{let n=null;if(_)n=s;else{const e=this._getAttributeValues(u,p,t,a),i=c.map(t=>e[t]);n=F&&"statisticParameters"in f?this._getPercentileValue(f,i):this._getStatisticValue(f,i,null,u.returnDistinctValues)}i.attributes[e]=n}let n=0;m.forEach((e,t)=>i.attributes[this.fieldsIndex.get(e)?e:"EXPR_"+ ++n]=r[t]),o.set(h,i)}}}else if(I){i.aggregateGeometries||(i.aggregateGeometries={});const{aggregateGeometries:e,outStatisticFieldName:s}=await this._getAggregateGeometry(f,t);i.aggregateGeometries[s]=e}else{const s=this._getAttributeValues(u,p,t,a);i.attributes[e]=F&&"statisticParameters"in f?this._getPercentileValue(f,s):this._getStatisticValue(f,s,n,u.returnDistinctValues)}const S="min"!==c&&"max"!==c||!T(this.fieldsIndex.get(p))&&!this._isAnyDateField(p)?null:this.fieldsIndex.get(p)?.type;s.push({name:e,alias:e,type:S||"esriFieldTypeDouble"})}const F=y?Array.from(o.values()):[i];return this._sortFeatures(F,f,(e,t)=>e.attributes[t]),p&&(F.length=Math.min(p,F.length)),{fields:s,features:F}}_isAnyDateField(e){const t=this.fieldsIndex.get(e);return y(t)||g(t)||x(t)||F(t)}async _getAggregateGeometry(e,n){const{convexHull:r,union:o}=await import("../../../geometry/geometryEngineJSON.js"),{statisticType:l,outStatisticFieldName:u}=e,{featureAdapter:m,spatialReference:d,geometryType:f}=this,p=n.map(e=>c(f,m.getGeometry(e))),h=r(d,p,!0)[0],y={aggregateGeometries:null,outStatisticFieldName:null};if("EnvelopeAggregate"===l){const e=h?s(h):a(o(d,p));y.aggregateGeometries={...e,spatialReference:d},y.outStatisticFieldName=u||"extent"}else if("CentroidAggregate"===l){const e=h?t(h):i(a(o(d,p)));y.aggregateGeometries={x:e[0],y:e[1],spatialReference:d},y.outStatisticFieldName=u||"centroid"}else"ConvexHullAggregate"===l&&(y.aggregateGeometries=h,y.outStatisticFieldName=u||"convexHull");return y}_getStatisticValue(e,t,i,s){const{onStatisticField:a,statisticType:n}=e;let r=null;r=i?.has(a)?i.get(a):T(this.fieldsIndex.get(a))||this._isAnyDateField(a)?R({values:t,returnDistinct:s}):B({values:s?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),i&&i.set(a,r);return r["var"===n?"variance":n]}_getPercentileValue(e,t){const{onStatisticField:i,statisticParameters:s,statisticType:a}=e,{value:n,orderBy:r}=s,o=this.fieldsIndex.get(i);return q(t,{value:n,orderBy:r,fieldType:o?.type,isDiscrete:"percentile_disc"===a})}_getAttributeValues(e,t,i,s){if(s.has(t))return s.get(t);const a=this.fieldsIndex.get(t),n=i.map(i=>e.getFieldValue(i,t,a));return s.set(t,n),n}_calculateUniqueValues(e,t,i){const s={},a=t.length;for(let n=0;n<a;n++){const a=t[n],r=[];for(const t of e)r.push(t[n]);const o=r.join(",");null==s[o]?s[o]={count:1,data:r,items:[a],itemPositions:[n]}:(i||s[o].count++,s[o].items.push(a),s[o].itemPositions.push(n))}return s}async _getDataValues(t,i,s=!0){const a=new l(this.query,this.featureAdapter,this.fieldsIndex),{valueExpression:n,scale:r,timeZone:o}=t;return n?a.getExpressionValues(i,n,{viewingMode:"map",scale:r,spatialReference:this.query.outSR||this.spatialReference},{geometryType:this.geometryType,hasZ:this.hasZ,hasM:this.hasM},o):a.getDataValues(i,e(t),s)}_calculateHistogramBins(e,t,i){if(null==t.min&&null==t.max)return[];const s=t.intervals,a=t.min??0,n=t.max??0,r=s.map(([e,t])=>({minValue:e,maxValue:t,count:0,items:[]}));for(let o=0;o<e.length;o++){const t=e[o],l=i[o];if(null!=t&&t>=a&&t<=n){const e=j(s,t);e>-1&&(r[e].count++,r[e].items.push(l))}}return r}async createQueryBinsResponse(e){const t=e.bin?.splitBy;if(!t)return this._createBinsResponse(e);const{value:i,outAlias:s,valueType:a}=t,n=[],r=[{name:s??i,alias:s??i,type:a??"esriFieldTypeString"},{name:O,alias:O,type:"esriFieldTypeInteger"}],o=new l(e,this.featureAdapter,this.fieldsIndex),u=new Map,c=[...this.items];this._sortFeatures(c,[i],(e,t,i)=>o.getFieldValue(e,t,i));const m=this._getAttributeValues(o,i,c,u),d=this._calculateUniqueValues([m],c,o.returnDistinctValues);for(const l in d){const{items:t}=d[l],a=await this._createBinsResponse(e,t);if(n.push(...a.features.map(e=>({...e,attributes:{...e.attributes,[s??i]:l}}))),a.fields)for(const e of a.fields)r.some(t=>t.name===e.name)||r.push(e)}return{fields:r,features:n}}async _createBinsResponse(e,t){const i=e.bin;switch(t=t??this.items,i.type){case"autoIntervalBin":return this._createAutoIntervalBinsResponse(I.fromJSON(i),e,t);case"dateBin":return this._createDateBinsResponse(_.fromJSON(i),e,t);case"fixedBoundariesBin":return this._createFixedBoundariesBinsResponse(V.fromJSON(i),e,t);case"fixedIntervalBin":return this._createFixedIntervalBinsResponse(v.fromJSON(i),e,t)}}async _createAutoIntervalBinsResponse(e,t,i){const{field:s,normalizationField:a,numBins:n,normalizationType:r,normalizationTotal:o,start:l,end:u}=e,c=await this._getDataValues({field:e.field,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},i),m=Z(c,{field:s,normalizationField:a,normalizationType:r,normalizationTotal:o,numBins:n,minValue:f(l,!1),maxValue:f(u,!1)}),d=this._calculateHistogramBins(c,m,i);return this._createFeaturesFromHistogramBins(d,t)}async _createDateBinsResponse(e,t,i){const{field:s,interval:a,start:n,end:r,snapToData:o,returnFullIntervalBin:l}=e,u=a.unit,c=await this._getDataValues({field:e.field,timeZone:t.outTimeReference?.ianaTimeZone},i),m=F(this.fieldsIndex.get(s)),d=S.toJSON(u),p=c.filter(Boolean).sort((e,t)=>e-t),h=null!=n?f(n,m):p[0],y=null!=r?f(r,m):p[p.length-1],g=[];if(null!=h&&null!=y){const e={zone:t.outTimeReference?.ianaTimeZone??G},i=C.fromMillis(h,e),s=C.fromMillis(y,e);if("last"===o){let e=s;for(;e>i;){const t=e.minus({[d]:a.value});if(t<i){g.unshift([l?t.toMillis():i.toMillis(),e.toMillis()]);break}g.unshift([t.toMillis(),e.toMillis()]),e=t}}else{let e="first"===o?i:i.startOf(d);for(;e<=s;){const t=e.plus({[d]:a.value});if(t>s){g.push([e.toMillis(),l?t.toMillis():s.toMillis()]);break}g.push([e.toMillis(),t.toMillis()]),e=t}}}const x=this._calculateHistogramBins(c,{intervals:g,min:h,max:y},i);return this._createFeaturesFromHistogramBins(x,t)}async _createFixedBoundariesBinsResponse(e,t,i){const{field:s}=e,a=await this._getDataValues({field:s,timeZone:t.outTimeReference?.ianaTimeZone},i),n=F(this.fieldsIndex.get(s)),r=e.boundaries.map(e=>f(e,n)).sort((e,t)=>e-t),o=[];for(let c=0;c<r.length-1;c++)o.push([r[c],r[c+1]]);const l={intervals:o,min:r.at(0),max:r.at(-1)},u=this._calculateHistogramBins(a,l,i);return this._createFeaturesFromHistogramBins(u,t)}async _createFixedIntervalBinsResponse(e,t,i){const{field:s,interval:a,start:n,end:r}=e,o=await this._getDataValues({field:e.field,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},i),l=F(this.fieldsIndex.get(s)),u=Z(o,{field:s,classificationMethod:"defined-interval",definedInterval:a,minValue:f(n,l),maxValue:f(r,l)},!0),c=this._calculateHistogramBins(o,u,i);return this._createFeaturesFromHistogramBins(c,t)}async _createFeaturesFromHistogramBins(e,t){const{upperBoundaryAlias:i,lowerBoundaryAlias:s}=t,a=s||"lowerBoundary",n=i||"upperBoundary",r=[],o=[{name:a,alias:a,type:"esriFieldTypeDouble"},{name:n,alias:n,type:"esriFieldTypeDouble"}],l=t.bin?.stackBy?.value,u=t.bin?.stackBy?.outAlias;l&&o.push({name:O,alias:O,type:"esriFieldTypeInteger"},{name:u??l,alias:u??l,type:"esriFieldTypeString"});let c=0;const m="dateBin"===t.bin.type,d=t.outTimeReference?.ianaTimeZone;for(const f of e){const{minValue:e,maxValue:i,items:s}=f,p={attributes:{}};let h;if(p.attributes[a]=m&&d&&null!=e?C.fromMillis(e,{zone:d}).toISO():e,p.attributes[n]=m&&d&&null!=i?C.fromMillis(i,{zone:d}).toISO():i,l?(h=await this._createStatisticsQueryResponse({...t,groupByFieldsForStatistics:[l],orderByFields:[l]},s),p.attributes[O]=++c,"flat"===t.bin.jsonStyle?r.push(...h.features.map(({attributes:{EXPR_1:e,...t},...i})=>({...i,attributes:u??e?{...t,[u??e]:e,...p.attributes}:{...t,...p.attributes}}))):(p.stackedAttributes=h.features.map(({attributes:{EXPR_1:e,...t}})=>u??e?{...t,[u??e]:e}:t),r.push(p))):(t.bin?.splitBy&&(p.attributes[O]=++c),h=await this._createStatisticsQueryResponse(t,s,p),r.push(p)),h.fields)for(const t of h.fields)o.some(e=>e.name===t.name)||o.push(t)}return"desc"===t.binOrder&&r.reverse(),{fields:o,features:r}}}function H(e,t,i,s){const a=s.x-i.x,n=s.y-i.y,r=t.x-i.x,o=t.y-i.y,l=a*a+n*n;if(0===l)return!1;const u=r*a+o*n,c=Math.min(1,Math.max(0,u/l));return e.x=i.x+a*c,e.y=i.y+n*c,!0}function Q(e,t){return e?t?4:3:t?3:2}class U{constructor(e,t){this.coords=e,this.coordsIndex=t}get x(){return this.coords[this.coordsIndex]}get y(){return this.coords[this.coordsIndex+1]}get z(){return this.coords[this.coordsIndex+2]}}const J=[1];export{E as QueryEngineResult};