@arcgis/core 5.0.0-next.23 → 5.0.0-next.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/01b8e680befff83e7d3e.js +1 -0
  3. package/assets/esri/core/workers/chunks/0ef9641069433fef3826.js +1 -0
  4. package/assets/esri/core/workers/chunks/155d74b9c0ef31dc2316.js +1 -0
  5. package/assets/esri/core/workers/chunks/19820cddba13a3585c0b.js +1 -0
  6. package/assets/esri/core/workers/chunks/{02cd03ffd024d3ac1aa7.js → 27ec791318e81285c222.js} +1 -1
  7. package/assets/esri/core/workers/chunks/2921f05a40fda12f9f81.js +1 -0
  8. package/assets/esri/core/workers/chunks/31b5747a254d13acc58e.js +1 -0
  9. package/assets/esri/core/workers/chunks/3777b41b4fa2f1418402.js +1 -0
  10. package/assets/esri/core/workers/chunks/3bacd904cd93c8013f6a.js +1 -0
  11. package/assets/esri/core/workers/chunks/41a00c77e6f7ce61e476.js +1 -0
  12. package/assets/esri/core/workers/chunks/45729d006db6a569715f.js +1 -0
  13. package/assets/esri/core/workers/chunks/58bbc8bc886c071b8ff3.js +1 -0
  14. package/assets/esri/core/workers/chunks/592afe1a41bed3b0cc31.js +1 -0
  15. package/assets/esri/core/workers/chunks/5aeda8a1f2ccabfdf40f.js +1 -0
  16. package/assets/esri/core/workers/chunks/{1e5efacbbc8960f13472.js → 748ab87a25f23d94b662.js} +1 -1
  17. package/assets/esri/core/workers/chunks/7e6fae3660e7a6a0fa16.js +1 -0
  18. package/assets/esri/core/workers/chunks/7ffef8a19166f6b564d8.js +1 -0
  19. package/assets/esri/core/workers/chunks/83aa39fbb1fad3b9d143.js +1 -0
  20. package/assets/esri/core/workers/chunks/8e9a5d38da40702def80.js +1 -0
  21. package/assets/esri/core/workers/chunks/aac313257a8b1ae75b75.js +1 -0
  22. package/assets/esri/core/workers/chunks/b48bb38e5d60fc7a9097.js +1 -0
  23. package/assets/esri/core/workers/chunks/b4c0a53c46ce4671d4c3.js +1 -0
  24. package/assets/esri/core/workers/chunks/bd58c027408dc858f23c.js +1 -0
  25. package/assets/esri/core/workers/chunks/be06c8a58c217a17451b.js +1 -0
  26. package/assets/esri/core/workers/chunks/ccde4f65377228b017a8.js +1 -0
  27. package/assets/esri/core/workers/chunks/d56548a994753b08403c.js +1 -0
  28. package/assets/esri/core/workers/chunks/{6e9c88f66bcfc3476b44.js → db0f9267fbda893de043.js} +1 -1
  29. package/assets/esri/core/workers/chunks/e08a1934d98e7324776d.js +1 -0
  30. package/assets/esri/core/workers/chunks/e0b70652da4a7f672cfc.js +1 -0
  31. package/assets/esri/core/workers/chunks/{bfc171f630da9314d860.js → e5baa30944061418cb13.js} +1 -1
  32. package/assets/esri/core/workers/chunks/e689a4849f5af3f2f641.js +1 -0
  33. package/assets/esri/core/workers/chunks/e6df4327ac1d9b65b80d.js +1 -0
  34. package/assets/esri/core/workers/chunks/f4919950a9a3703d9da3.js +1 -0
  35. package/assets/esri/core/workers/chunks/f4eb5de69ad9b7763582.js +1 -0
  36. package/assets/esri/core/workers/chunks/f6ce485c082d0d640b01.js +1 -0
  37. package/assets/esri/core/workers/chunks/fd9ef4b8c969962cf72b.js +1 -0
  38. package/assets/esri/libs/lyr3d/lyr3DMain.wasm +0 -0
  39. package/assets/esri/rest/knowledgeGraph/wasmInterface/arcgis-knowledge-client-core-simd.wasm +0 -0
  40. package/assets/esri/rest/knowledgeGraph/wasmInterface/arcgis-knowledge-client-core.wasm +0 -0
  41. package/assets/esri/themes/base/widgets/_FeatureTable.scss +0 -1
  42. package/assets/esri/themes/dark/main.css +1 -1
  43. package/assets/esri/themes/light/main.css +1 -1
  44. package/assets/esri/themes/light/view.css +1 -1
  45. package/assets/esri/widgets/support/GridControls/t9n/GridControls.json +1 -1
  46. package/assets/esri/widgets/support/GridControls/t9n/GridControls_en.json +1 -1
  47. package/chunks/arcgis-knowledge-client-core-simd.js +1 -1
  48. package/chunks/arcgis-knowledge-client-core.js +1 -1
  49. package/config.js +1 -1
  50. package/kernel.js +1 -1
  51. package/layers/BaseDynamicLayer.js +1 -1
  52. package/layers/BaseElevationLayer.js +1 -1
  53. package/layers/Lyr3DWasmPerSceneView.js +1 -1
  54. package/layers/graphics/sources/support/QueryTask.js +1 -1
  55. package/layers/support/PublishingInfo.js +1 -1
  56. package/layers/support/RasterBandInfo.js +1 -1
  57. package/layers/support/RasterSensorInfo.js +1 -1
  58. package/layers/support/vectorTileLayerLoader.js +1 -1
  59. package/layers/voxel/VoxelVariable.js +1 -1
  60. package/package.json +1 -1
  61. package/rest/support/FindImagesResult.js +1 -1
  62. package/rest/support/ImageAreaResult.js +1 -1
  63. package/rest/support/ImageBoundaryResult.js +1 -1
  64. package/rest/support/ImageDistanceResult.js +1 -1
  65. package/rest/support/ImageGPSInfoResult.js +1 -1
  66. package/rest/support/ImageHeightResult.js +1 -1
  67. package/rest/support/ImageIdentifyResult.js +1 -1
  68. package/rest/support/ImagePixelLocationResult.js +1 -1
  69. package/rest/support/ImagePointResult.js +1 -1
  70. package/rest/support/ImageSampleResult.js +1 -1
  71. package/rest/support/ImageUrlResult.js +1 -1
  72. package/rest/support/ImageVolumeResult.js +1 -1
  73. package/rest/support/MeasureAreaFromImageResult.js +1 -1
  74. package/rest/support/MeasureLengthFromImageResult.js +1 -1
  75. package/support/revision.js +1 -1
  76. package/symbols/cim/CIMEffects.js +1 -1
  77. package/symbols/cim/CIMSymbolDrawHelper.js +1 -1
  78. package/symbols/cim/CIMSymbolHelper.js +1 -1
  79. package/symbols/cim/placements/PlacementAtMeasuredUnits.js +1 -1
  80. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/GradientStrokeShader.js +1 -1
  81. package/views/3d/layers/IntegratedMesh3DTilesLayerView3D.js +1 -1
  82. package/views/3d/layers/PointCloudLayerView3D.js +1 -1
  83. package/views/LinkChartView.js +1 -1
  84. package/views/draw/support/Reshape.js +1 -1
  85. package/views/input/Input.js +1 -1
  86. package/views/layers/BuildingComponentSublayerView.js +1 -1
  87. package/views/layers/SceneLayerView.js +1 -1
  88. package/widgets/Editor/SplitFeatureWorkflow.js +1 -1
  89. package/widgets/Editor/UpdateFeatureWorkflow.js +1 -1
  90. package/widgets/Editor/workflowUtils.js +1 -1
  91. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  92. package/widgets/OrientedImageryViewer/adapters/sketch/TriangulatedMeasurementAdapter.js +1 -1
  93. package/widgets/OrientedImageryViewer/adapters/view/MapViewAdapter.js +1 -1
  94. package/widgets/OrientedImageryViewer/imageMeasurementUtils.js +1 -1
  95. package/widgets/OrientedImageryViewer/mixins/TriangulatedImageMeasurementMixin.js +1 -1
  96. package/widgets/ScaleRangeSlider/ScaleRanges.js +1 -1
  97. package/widgets/Sketch/SketchViewModel.js +1 -1
  98. package/widgets/Sketch/support/ResponsiveToolbar/ResponsiveToolbar.js +1 -1
  99. package/widgets/Sketch.js +1 -1
  100. package/widgets/VideoPlayer/VideoPlayerViewModel.js +1 -1
  101. package/widgets/support/GridControls.js +1 -1
  102. package/widgets/support/SelectionToolbar.js +1 -1
  103. package/assets/esri/core/workers/chunks/038eba6d3a6bcf8ccd67.js +0 -1
  104. package/assets/esri/core/workers/chunks/11fdcb8a74a80e9a47a3.js +0 -1
  105. package/assets/esri/core/workers/chunks/13b47c217d1e9b61bcbf.js +0 -1
  106. package/assets/esri/core/workers/chunks/174972870db79189200b.js +0 -1
  107. package/assets/esri/core/workers/chunks/1b9f93ab226232c5019a.js +0 -1
  108. package/assets/esri/core/workers/chunks/221691ad0b2912827e14.js +0 -1
  109. package/assets/esri/core/workers/chunks/2719865e28d577da7b2a.js +0 -1
  110. package/assets/esri/core/workers/chunks/42747a028fc404ac55f4.js +0 -1
  111. package/assets/esri/core/workers/chunks/443931ac4b4ee5ccb932.js +0 -1
  112. package/assets/esri/core/workers/chunks/48ca09958c3d50de48dc.js +0 -1
  113. package/assets/esri/core/workers/chunks/5cc023e1066641f9f20c.js +0 -1
  114. package/assets/esri/core/workers/chunks/6b8a923fe5f800f703e3.js +0 -1
  115. package/assets/esri/core/workers/chunks/7749801f30a99b60753e.js +0 -1
  116. package/assets/esri/core/workers/chunks/7d9773c87650856f2d9e.js +0 -1
  117. package/assets/esri/core/workers/chunks/800c282a7335b2e6c7cd.js +0 -1
  118. package/assets/esri/core/workers/chunks/8a8192e6a9fd7a6d8060.js +0 -1
  119. package/assets/esri/core/workers/chunks/8af47cc9cee2f3031162.js +0 -1
  120. package/assets/esri/core/workers/chunks/8f0c53feead87457b7eb.js +0 -1
  121. package/assets/esri/core/workers/chunks/9f6d82ce8f680abb79bb.js +0 -1
  122. package/assets/esri/core/workers/chunks/9f9e20321ee44675e107.js +0 -1
  123. package/assets/esri/core/workers/chunks/a02ffa7916cf9da55608.js +0 -1
  124. package/assets/esri/core/workers/chunks/a7dc1928d46dd6b69868.js +0 -1
  125. package/assets/esri/core/workers/chunks/b6d21a2b5c1be8bee57c.js +0 -1
  126. package/assets/esri/core/workers/chunks/c35a22becf5c470ff6a2.js +0 -1
  127. package/assets/esri/core/workers/chunks/cd1d9f638af5b63a1292.js +0 -1
  128. package/assets/esri/core/workers/chunks/dcd6ee9e00ebd519c4a7.js +0 -1
  129. package/assets/esri/core/workers/chunks/e2d2a55aedd3ce9cb47b.js +0 -1
  130. package/assets/esri/core/workers/chunks/e3c8fac5fe638d548e34.js +0 -1
  131. package/assets/esri/core/workers/chunks/e45940d342b18983a5ef.js +0 -1
  132. package/assets/esri/core/workers/chunks/e5208898910c1222b7e6.js +0 -1
  133. package/assets/esri/core/workers/chunks/fa4f788abfbfd3dee882.js +0 -1
  134. package/assets/esri/core/workers/chunks/fbbf25629e0dab486887.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t,__param as e}from"tslib";import has from"../../../../../../../core/has.js";import{location as i,uniform as o,input as r,UniformGroup as s}from"../../GraphShaderModule.js";import{ifElse as n,greaterThan as a,Float as l,dot as d,min as p,length as m,mix as c,Vec2 as u,clamp as h,texture2D as y,step as g,Vec4 as v}from"../../graph/glsl.js";import{bitset as f}from"../line/gradientStrokeConstants.js";import{BaseHittestVertexInput as w}from"./AFeatureShader.js";import{LineShader as b,getLineVertexData as x,getLineAntialiasing as S,LineVertexInput as L,LineFragmentInput as j}from"./LineShader.js";import{MosaicInfo as A}from"./MosaicInfo.js";import{getBit as D,getBitBool as z,oneMinus as C}from"./utils.js";function F(t){return g(new l(0),t).multiply(2).subtract(1)}class G extends L{}t([i(9,l)],G.prototype,"accumulatedDistance",void 0),t([i(10,l)],G.prototype,"totalLength",void 0),t([i(11,l)],G.prototype,"gradientSize",void 0),t([i(12,u)],G.prototype,"segmentDirection",void 0),t([i(13,v)],G.prototype,"tlbr",void 0);class I extends j{}class P extends s{}t([o(l)],P.prototype,"isColorPass",void 0);class k extends b{constructor(){super(...arguments),this.type="GradientStrokeShader"}vertex(t,e){const{totalLength:i,gradientSize:o,segmentDirection:r,tlbr:s}=t,p=x(this,t),m=D(t.bitset,f.isAlongLine),c=i.divide(this.view.displayZoomFactor),u=n(z(t.bitset,f.isAbsoluteSize),()=>{const t=n(a(m,new l(.5)),c,p.halfWidth);return o.divide(t)},o),h=t.accumulatedDistance.add(d(r,p.scaledOffset).divide(c)),y=s.divide(this.mosaicInfo.size.xyxy);return{...p,tlbr:y,relativePositionAlongLine:h,relativeGradientSize:u,isAlongLine:D(t.bitset,f.isAlongLine),isDiscrete:D(t.bitset,f.isDiscrete),...this.maybeRunHittest(t,e,p.halfWidth)}}fragment(t){const{isAlongLine:e,isDiscrete:i,relativePositionAlongLine:o,relativeGradientSize:r,normal:s,tlbr:d}=t,v=S(t,this.antialiasingControls.blur),f=F(s.y).multiply(p(m(s),new l(1))),w=new l(.5).multiply(f).add(new l(.5)),b=n(a(e,new l(.5)),o,w),x=n(a(i,new l(.5)),r.subtract(1),new l(0)),L=C(b.add(x).divide(r)),j=c(d.xy,d.zw,new u(h(L,new l(0),new l(1)),.5)),A=y(this.mosaicInfo.texture,j),D=t.opacity.multiply(v),z=this.getFragmentOutput(A.multiply(D),t),G=g(new l(.5),this.technique.isColorPass).multiply(has("gradient-depth-epsilon")),I=g(new l(0),s.y).multiply(new l(has("gradient-depth-bias")).subtract(G));return z.glFragDepth=h(m(s).add(I),new l(0),new l(1)),z}}t([o(A)],k.prototype,"mosaicInfo",void 0),t([o(P)],k.prototype,"technique",void 0),t([e(0,r(G)),e(1,r(w))],k.prototype,"vertex",null);export{I as GradientStrokeFragmentInput,k as GradientStrokeShader,G as GradientStrokeVertexInput};
5
+ import{__decorate as t,__param as e}from"tslib";import has from"../../../../../../../core/has.js";import{location as i,uniform as o,input as r,UniformGroup as s}from"../../GraphShaderModule.js";import{ifElse as n,greaterThan as a,Float as l,dot as d,min as p,length as m,mix as c,Vec2 as u,clamp as h,texture2D as y,step as g,Vec4 as v}from"../../graph/glsl.js";import{bitset as f}from"../line/gradientStrokeConstants.js";import{BaseHittestVertexInput as w}from"./AFeatureShader.js";import{LineShader as b,getLineVertexData as x,getLineAntialiasing as S,LineVertexInput as L,LineFragmentInput as j}from"./LineShader.js";import{MosaicInfo as A}from"./MosaicInfo.js";import{getBit as D,getBitBool as z,oneMinus as C}from"./utils.js";function F(t){return g(new l(0),t).multiply(2).subtract(1)}class G extends L{}t([i(9,l)],G.prototype,"accumulatedDistance",void 0),t([i(10,l)],G.prototype,"totalLength",void 0),t([i(11,l)],G.prototype,"gradientSize",void 0),t([i(12,u)],G.prototype,"segmentDirection",void 0),t([i(13,v)],G.prototype,"tlbr",void 0);class I extends j{}class P extends s{}t([o(l)],P.prototype,"isColorPass",void 0);class k extends b{constructor(){super(...arguments),this.type="GradientStrokeShader"}vertex(t,e){const{totalLength:i,gradientSize:o,segmentDirection:r,tlbr:s}=t,p=x(this,t),m=D(t.bitset,f.isAlongLine),c=i.divide(this.view.displayZoomFactor),u=n(z(t.bitset,f.isAbsoluteSize),()=>{const t=n(a(m,new l(.5)),c,p.halfWidth);return o.divide(t)},o),h=t.accumulatedDistance.add(d(r,p.scaledOffset).divide(c)),y=s.divide(this.mosaicInfo.size.xyxy);return{...p,tlbr:y,relativePositionAlongLine:h,relativeGradientSize:u,isAlongLine:D(t.bitset,f.isAlongLine),isDiscrete:D(t.bitset,f.isDiscrete),...this.maybeRunHittest(t,e,p.halfWidth)}}fragment(t){const{isAlongLine:e,isDiscrete:i,relativePositionAlongLine:o,relativeGradientSize:r,normal:s,tlbr:d}=t,v=S(t,this.antialiasingControls.blur),f=F(s.y).multiply(p(m(s),new l(1))),w=new l(.5).multiply(f).add(new l(.5)),b=n(a(e,new l(.5)),o,w),x=n(a(i,new l(.5)),r.subtract(1),new l(0));let L=b.add(x).divide(r);L=n(a(e,new l(.5)),L,C(L));const j=c(d.xy,d.zw,new u(h(L,new l(0),new l(1)),.5)),A=y(this.mosaicInfo.texture,j),D=t.opacity.multiply(v),z=this.getFragmentOutput(A.multiply(D),t),G=g(new l(.5),this.technique.isColorPass).multiply(has("gradient-depth-epsilon")),I=g(new l(0),s.y).multiply(new l(has("gradient-depth-bias")).subtract(G));return z.glFragDepth=h(m(s).add(I),new l(0),new l(1)),z}}t([o(A)],k.prototype,"mosaicInfo",void 0),t([o(P)],k.prototype,"technique",void 0),t([e(0,r(G)),e(1,r(w))],k.prototype,"vertex",null);export{I as GradientStrokeFragmentInput,k as GradientStrokeShader,G as GradientStrokeVertexInput};
@@ -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 has from"../../../core/has.js";import t from"../../../core/Logger.js";import{destroyMaybe as i,removeMaybe as r}from"../../../core/maybe.js";import{initial as s,watch as o,when as n}from"../../../core/reactiveUtils.js";import{schedule as a}from"../../../core/scheduling.js";import{property as l,subclass as c}from"../../../core/accessorSupport/decorators.js";import{fromMat4 as d,invert as h}from"../../../core/libs/gl-matrix-2/math/mat3.js";import{create as m,IDENTITY as u}from"../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{create as p}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{fromValues as f}from"../../../core/libs/gl-matrix-2/factories/quatf64.js";import{o as g,g as y,a as b,f as _}from"../../../chunks/vec32.js";import{fromArray as w,clone as v,create as j}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{fromValues as M}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{SphericalECEFSpatialReferenceLike as x}from"../../../geometry/ellipsoidUtils.js";import{computeTranslationToOriginAndRotation as O}from"../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{localLinearScaleFactors as C}from"../../../geometry/projection/localLinearScaleFactors.js";import{projectVectorToVector as T}from"../../../geometry/projection/projectVectorToVector.js";import{create as U}from"../../../geometry/support/aaBoundingRect.js";import{BufferViewVec2f as P,BufferViewVec4f as H,BufferViewVec4u8 as E,BufferViewVec4u16 as S,BufferViewVec3f as R,BufferViewVec3u8 as V,BufferViewVec3u16 as A,BufferViewInt16 as k,BufferViewUint32 as F,BufferViewUint16 as I}from"../../../geometry/support/buffer/BufferView.js";import D from"../../../layers/support/SceneModification.js";import{getElevationOffsetInMeters as L}from"../../../support/elevationInfoUtils.js";import{toWasmModification as B}from"./I3SMeshWorkerHandle.js";import{LayerView3D as G}from"./LayerView3D.js";import{Lyr3DViewPerformanceInfo as z}from"./Lyr3DViewPerformanceInfo.js";import{addLayerViewToWasm as N,removeLayerViewFromWasm as W,getLyr3DWasm as $}from"./Lyr3DWasm.js";import{LayerElevationProvider as q}from"./i3s/LayerElevationProvider.js";import{primTypeConversion as J,alphaModeConversion as K,faceCullingConversion as Q,wrapModeConversion as X,lyr3DTypeToByteSize as Y}from"./support/lyr3dTypeConversions.js";import{Tiles3DIntersectionHandler as Z}from"./support/Tiles3DIntersectionHandler.js";import{ElevationRange as ee}from"../support/ElevationRange.js";import{toBoundingRect as te}from"../support/extentUtils.js";import{Obb as ie,compute as re}from"../support/orientedBoundingBox.js";import{ObjectParameters as se}from"../webgl-engine/collections/Component/ObjectParameters.js";import{GeometryParameters as oe,createVertexBufferLayout as ne,SourceGeometry as ae}from"../webgl-engine/collections/Component/SourceGeometry.js";import{Transform as le}from"../webgl-engine/collections/Component/Transform.js";import{RenderTexture as ce}from"../webgl-engine/core/material/RenderTexture.js";import{getEllipsoidMode as de}from"../webgl-engine/core/shaderLibrary/util/EllipsoidMode.js";import{Attribute as he}from"../webgl-engine/lib/Attribute.js";import{ManagedTexture as me}from"../webgl-engine/lib/ManagedTexture.js";import{compressAndTransformNormals as ue}from"../webgl-engine/lib/Normals.js";import{writeAttribute as pe,writeBufferVec2 as fe}from"../webgl-engine/materials/internal/bufferWriterUtils.js";import ge from"../../layers/LayerView.js";import{spatialReferenceIncompatibleError as ye,isInEffectiveScaleRange as be}from"../../support/layerViewUtils.js";import{TextureCompressionTracker as _e}from"../../support/TextureCompressionTracker.js";import{alphaCutoff as we}from"../../../webscene/support/AlphaCutoff.js";class ve{constructor(e,t,i,r,s,o,n){this.handle=e,this.componentObjects=t,this.textures=i,this.cpuMemoryUsage=r,this.vboMemoryUsage=s,this.textureMemoryUsage=o,this.obb=n,this.isVisible=!1,this.usedMemory=this.textureMemoryUsage+this.vboMemoryUsage+this.cpuMemoryUsage;const a=j();n?.getCenter(a),this._obbCenter=a,this._obbRadiusSquared=n?n?.radius**2:0}boundingVolumeIntersectsRay(e,t){if(!this.obb)return!0;const i=b(je,this._obbCenter,e),r=_(i,t);return _(i,i)-r*r<=this._obbRadiusSquared&&this.obb.intersectRay(e,t)}}const je=j();function Me(e){return Math.round(e/1048.576)/1e3}let xe=class extends(G(ge)){get hasModifications(){return this._modifications&&this._modifications.length>0}constructor(e){super(e),this.type="integrated-mesh-3dtiles",this._compressionTracker=new _e,this._modifications=new Array,this._visibleGeometryChangedSchedulerHandle=null,this._wasmLayerId=-1,this.ignoresMemoryFactor=!1,this._usedMemory=0,this._cacheMemory=0,this.drapeTargetType=1,this._applySSAO=!has("disable-feature:im-ssao"),this._shadeNormals=!!has("enable-feature:im-shading"),this._lyrHandleToObjects=new Map,this._visibleObjects=new Set,this._suspendedHandle=null,this._dbgFlags=new Set,this._memCache=e.view.resourceController.memoryController.newCache(`IM3DTiles-${this.uid}`,e=>this._deletePerObjectData(e))}initialize(){this._dbgFlags.add(3),this._dbg(2,"Tiles3DLayerView3D initialize() called");const{view:e}=this;if(this._updatingHandles.add(()=>this.layer.modifications,()=>this._loadModifications(),s),!this._canProjectWithoutEngine())throw ye("layer",this.layer.spatialReference.wkid,e.renderSpatialReference?.wkid);const t=N(this).then(t=>{this._wasmLayerId=t,this._intersectionHandler=new Z(this),e.sceneIntersectionHelper.addIntersectionHandler(this._intersectionHandler),this._updatingHandles.add(()=>this.slicePlaneEnabled,e=>this._slicePlaneEnabledChange(e)),this._updatingHandles.add(()=>this._modifications,()=>this._modificationsChanged(),s),this._updatingHandles.add(()=>this.fullOpacity,()=>this._opacityChange()),this._updatingHandles.add(()=>e.clippingArea,()=>this._clippingAreaChanged(),s),this._elevationProvider=new q({view:e,layerElevationSource:this,intersectionHandler:this._intersectionHandler}),e.elevationProvider.register(1,this._elevationProvider),e.overlayManager.registerDrapeTarget(this),this.addHandles([o(()=>this.layer.elevationInfo,e=>this._elevationInfoChanged(e))]),this._suspendedHandle=o(()=>this.suspended,e=>this._wasm?.setEnabled(this,!e),s)});this.addResolvingPromise(t),this._replacesTerrain&&this.addHandles(n(()=>this.view.map.ground.opacity,()=>{this._opacityChange()}))}get _replacesTerrain(){return this.layer.replacesTerrain&&!!this.view.map.basemap?.groundLayers.includes(this.layer)}get fullOpacity(){return this._replacesTerrain?this.view.map.ground.opacity:1}get opacity(){return 1}_opacityChange(){const{fullOpacity:e}=this;this.forEachComponentObject(t=>{this._collection.getMaterial(t).objectOpacity=e})}intersect(e,t,i,r){this._intersectionHandler.intersect(e,t,i,r,null,!1)}get ready(){return!0}destroy(){this._dbg(2,"Tiles3DLayerView3D destroy() called"),W(this),this._suspendedHandle&&(this._suspendedHandle.remove(),this._suspendedHandle=null),this._intersectionHandler&&(this.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler),this._intersectionHandler=null),this._elevationProvider&&(this._elevationProvider.notifyObjectsChangedFunctional(e=>this.forEachComponentObject(t=>e(t.obb))),this.view.elevationProvider.unregister(this._elevationProvider),this._elevationProvider=null),this.view.overlayManager.unregisterDrapeTarget(this),this._lyrHandleToObjects.forEach(e=>this.freeObject(e)),this._lyrHandleToObjects.clear(),this._visibleObjects.clear(),this._usedMemory=this._cacheMemory=0,this._memCache.destroy(),this._updatingHandles=i(this._updatingHandles),this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=r(this._visibleGeometryChangedSchedulerHandle)}_modificationsChanged(){const e=this.layer.spatialReference,t=B(this._layerClippingArea,this._modifications,e);this._wasm?.setMeshModifications(this,t,e.wkid)}_clippingAreaChanged(){const e=this.layer.spatialReference,t=U();this._layerClippingArea=te(this.view.clippingArea,t,e)?t:null,this._modificationsChanged()}_visibleGeometryChanged(){this._visibleGeometryChangedSchedulerHandle??=a(()=>{this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=null})}_slicePlaneEnabledChange(e){this._intersectionHandler&&(this._intersectionHandler.slicePlaneEnabled=e),this.forEachComponentObject(t=>this._collection.getMaterial(t).commonMaterialParameters.hasSlicePlane=e)}_elevationInfoChanged(e){this._wasm?.setLayerOffset(this,L(e))}get _wasm(){return $(this.view)}get wasmLayerId(){return this._wasmLayerId}get usedMemory(){return this._usedMemory}get unloadedMemory(){return 0}get cachedMemory(){return this._cacheMemory}get visibleAtCurrentScale(){return be(this.layer.effectiveScaleRange,this.view.scale)}get performanceInfo(){let e=0,t=0,i=0,r=0,s=0,o=0;return this._lyrHandleToObjects.forEach(n=>{n.isVisible?(e+=n.textureMemoryUsage,t+=n.vboMemoryUsage,s++):(i+=n.textureMemoryUsage,r+=n.vboMemoryUsage,o++)}),new z(this.usedMemory,s,o,Me(t),Me(e),Me(r),Me(i))}_canProjectWithoutEngine(){if(2===this.view.state.viewingMode){const e=this.view.renderSpatialReference?.isWebMercator?3857:this.view.renderSpatialReference?.wkid??-1;if(3857!==e&&32662!==e)return!1}return!0}get _stage(){return this.view.stage}get _collection(){return this._stage.renderView.componentObjectCollection}get elevationProvider(){return this._elevationProvider}get elevationOffset(){return L(this.layer.elevationInfo)}get elevationRange(){const e=this.fullExtent;return e?.zmin&&e?.zmax?new ee(e.zmin,e.zmax):null}getElevationRange(e){return null}get fullExtent(){return this.layer.fullExtent}forEachComponentObject(e){this._forEachObject(this._lyrHandleToObjects.values(),e)}forEachVisibleTile(e){for(const t of this._visibleObjects)e(t)}forEachVisibleComponentObject(e){this._forEachObject(this._visibleObjects,e)}_forEachObject(e,t){for(const i of e)for(const e of i.componentObjects)t(e)}isUpdating(){const e=this._wasm;return!(this._wasmLayerId<0||null==e)&&(e.isUpdating(this._wasmLayerId)||this._compressionTracker.compressing)}updatingFlagChanged(){this.notifyChange("updating")}async createRenderable(e){if(this.destroyed){const e=`IntegratedMesh3DTilesLayerView3D[${this.layer?.title}]: createRenderable called on destroyed instance`;throw new Error(e)}let t=0;const{meshData:i}=e;if(null==i.data)throw new Error("meshData.data undefined");if(i.desc=JSON.parse(i.desc),null==i.desc)throw new Error("meshData.desc undefined");const r=w(i.desc.origin),s=new Array,o=this.view.basemapTerrain.spatialReference;let n,a;if("global"===this.view.viewingMode){const e=p();O(x,r,e,o),n=d(m(),e),a=h(m(),n)}else n=u,a=u;const l=v(r),c=j(),f=Ue(i.desc.obb);let y=0,b=0;const _={textureMemoryUsage:0},U=new Map,H=i.desc.prims.length,E=new Array;try{for(let e=0;e<H;e++){const t=i.desc.prims[e];this._dbg(2,JSON.stringify(t));if(null==J[t.ptype]||null==i.data){this._dbg(2,"[Unsupported Feature] Unsupported primitive mode ("+t.ptype+"). Skipping primitive.");continue}const d=i.desc?.materials&&null!=t.materialId?i.desc.materials[t.materialId]:null,h=null!=d?d.lightingModel:"Unlit",{positionView:m,positionAttr:p,normalsView:w,normalsAttr:v,colorAttr:x,texCoord0Attr:O,indicesView:H}=this.getBufferViews(t,i.data.buffer,n);if(null==p||null==m||null==H)continue;const E=new oe(null!=x,O?1:0,null!=w,this._shadeNormals||this._replacesTerrain,this._applySSAO),S=p.data.length/p.size,R=(e,t)=>!e||e.data.length/e.size===S||(this._dbg(3,`${t} !== numPos. Skipping primitive.`),!1);if(!R(O,"numTexcoord")||!R(x,"numColors")||!R(v,"normals"))continue;const V=ne(E),A=f?.clone()??Te(p,r);if(n!==u)for(let e=0;e<m.count;e++)m.getVec(e,c),g(c,c,n),m.setVec(e,c);const k=V.createBuffer(p.data.length);if(pe("position",p,null,null,k,0),null!=O){const e=k.getField("uv0",P);fe(O,e,0)}null!=x&&pe("color",x,null,null,k,0),null!=v&&pe("normalCompressed",v,null,null,k,0);const F=new Uint32Array([0,H.typedBuffer.length]),I=new ae({data:k.buffer,count:k.byteLength/V.stride,layoutParameters:E},{positions:m.typedBuffer,indices:H.typedBuffer},H.typedBuffer,F);y+=m.count+H.count;const D=this.view.renderSpatialReference,L=j(),B=[1,1,1];C(l,D,B,o)||this._dbg(3,"Unsupported coordinate system for IM overlay"),T(l,D,L,o);let G=()=>{},z=Promise.resolve(He);if(d){const e=e=>this._getTexture(e,i,U,_),t=e(d.baseColorTex),r="Pbr"===h,s=r?e(d.metalTex):null,o=r?e(d.emissiveTex):null,n=r?e(d.occlusionTex):null,a=r?e(d.normalTex):null,l=[t,s,o,n,a].map(e=>e?.loadPromise??null);z=Promise.all(l),G=e=>{e.baseColor=d.baseColorFactor,e.usePBR="Pbr"===h,e.hasParametersFromSource=!1,e.baseColorTexture=t,e.usePBR&&(e.mrrFactors=[d.metallicFactor,d.roughnessFactor,0],e.emissiveBaseColor=d.emissiveFactor??[0,0,0],e.metallicRoughnessTexture=s,e.emissionTexture=o,e.occlusionTexture=n,e.normalTexture=a),e.alphaDiscardMode=K[d.alphaMode],e.objectOpacity=this.fullOpacity,_.textureMemoryUsage+=e.baseColorTexture?.texture?.usedMemory??0,e.usePBR&&(_.textureMemoryUsage+=(e.metallicRoughnessTexture?.texture?.usedMemory??0)+(e.emissionTexture?.texture?.usedMemory??0)+(e.occlusionTexture?.texture?.usedMemory??0)+(e.normalTexture?.texture?.usedMemory??0)),e.commonMaterialParameters.doubleSided=d.isDoubleSided,e.commonMaterialParameters.cullFace=Q[d.faceCulling??"NotSet"],e.commonMaterialParameters.hasSlicePlane=this.slicePlaneEnabled,e.componentParameters.castShadows=0,e.textureAlphaCutoff=d.alphaCutoff??we,e.alphaDiscardMode=K[d.alphaMode],e.isIntegratedMesh=!0,e.sphereDepthInterpolate=this.layer.hasGoogleUrl,e.polygonOffsetEnabled=!1,e.hasOccludees=!1,e.ellipsoidMode=de(this.view.spatialReference)}}const N=z.then(()=>()=>{if(this.destroyed){const e="Trying to add object to destroyed layer view";throw this._dbg(3,`${e} !== numPos. Skipping primitive.`),new Error(e)}const e=this._collection.createObject(new se(M(L[0],L[1],B[0],B[1]),new le(l,a),A,I,!1));return this._collection.updateMaterial(e,G),b+=this._collection.getObjectGPUMemoryUsage(e),e});s.push(N)}if(E.push(...await Promise.all(s)),this.destroyed){throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderable object destroyed during call")}}catch(A){throw U.forEach(e=>this._stage.removeTexture(e)),A}const S=E.map(e=>e()),R=new Array;U.forEach(e=>R.push(e));const V=new ve(e.handle,S,R,y,b,_.textureMemoryUsage,f);return this._lyrHandleToObjects.set(e.handle,V),this._memCache.put(Pe(V.handle),V),t=V.usedMemory,this._cacheMemory+=t,{memUsageBytes:V.usedMemory}}freeRenderable(e){const t=this._lyrHandleToObjects.get(e);t&&(t.isVisible?(this._visibleObjects.delete(t),this._usedMemory-=t.usedMemory):this._cacheMemory-=t.usedMemory,this.freeObject(t),this._lyrHandleToObjects.delete(e))}freeObject(e){const t=Pe(e.handle);this._memCache.pop(t),e.textures.forEach(e=>this._stage.removeTexture(e)),e.componentObjects.forEach(e=>this._collection.destroyObject(e))}setRenderableVisibility(e,t,i){for(let r=0;r<i;++r){const i=t[r];if(!i)continue;const s=e[r],o=this._lyrHandleToObjects.get(s);if(o){if(o.isVisible)continue;this._visibleGeometryChanged(),o.isVisible=!0,this._visibleObjects.add(o),this._usedMemory+=o.usedMemory,this._cacheMemory-=o.usedMemory,o.componentObjects.forEach(e=>{this._collection.setObjectVisibility(e,i),this._elevationProvider.notifyObjectChanged(this._collection.getComponentObb(e))}),this._memCache.pop(Pe(s))}}for(let r=0;r<i;++r){const i=e[r],s=t[r];if(s)continue;const o=this._lyrHandleToObjects.get(i);if(o){if(!o.isVisible)continue;this._visibleGeometryChanged(),o.isVisible=!1,this._visibleObjects.delete(o),this._usedMemory-=o.usedMemory,this._cacheMemory+=o.usedMemory,o.componentObjects.forEach(e=>{this._collection.setObjectVisibility(e,s),this._elevationProvider.notifyObjectChanged(this._collection.getComponentObb(e))}),this._memCache.put(Pe(i),o)}}}setLodPixelThreshold(e){this._wasm?.setLodPixelThreshold(this,e)}_getTexture(e,t,i,r){const s=e&&t.desc?.images?.[e.imageId];if(!s||!t.data?.buffer)return null;const o=i.get(s)??this._createTexture(e,t,i,r);return o?new ce(this._stage.renderView.textures,o.id):null}_createTexture(e,t,i,r){const s=e&&t.desc?.images?.[e.imageId];if(!s||!t.data?.buffer)return null;const o=this._stage,{renderView:n}=o,a=n.renderingContext.parameters.maxMaxAnisotropy,l=!!s.mipCount||a>1,c=X[e.wrapMode??"None"];let d=s.alpha?6408:6407;const h=new Uint8Array(t.data.buffer,s.data.byteOffset,s.data.byteCount);let m=null,u=null,p=null;switch(s.format){case"Raw":"R8"===s.pixelFormat?(m=h,d=6403,u=""):"Rgb8"===s.pixelFormat?(m=h,d=6407,u=""):"Rgba8"===s.pixelFormat&&(m=h,d=6408,u="");break;case"Dxt1":m=h,d=6407,u="image/vnd-ms.dds";break;case"Dxt5":m=h,d=6408,u="image/vnd-ms.dds";break;case"Basis":m=h,d=6407,u="image/ktx2";break;case"Png":u="image/png",p=document.createElement("img");break;case"Jpeg":u="image/jpeg",p=document.createElement("img");break;case"Etc2":u="image/ktx",p=document.createElement("img");break;case"Astc":this._dbg(3,"Astc texture not supported");break;case"Pvrtc":this._dbg(3,"Pvrtc texture not supported")}if(p&&u){const e=new Blob([h],{type:u});p.src=URL.createObjectURL(e),m=p}if(m&&null!=u){const e=has("enable-feature:esri-compress-IM-textures")?{compressionTracker:this._compressionTracker,compressionCallback:e=>{e&&e>0&&(r.textureMemoryUsage-=e)}}:void 0,t=new me(m,{mipmap:l,maxAnisotropy:a,encoding:u,wrap:c,pixelFormat:d,compressionOptions:e,noUnpackFlip:!0,width:s.mip0Width,height:s.mip0Height});return this._stage.addTexture(t),i.set(s,t),t}return null}getBufferViews(e,t,i){let r,s,o,n,a,l,c,d=null;for(let m=0;m<e.atrbs.length;m++){const c=e.atrbs[m],u=c.view,p=void 0,f=u.byteOffset+u.byteCount,g=u.byteCount/Y[u.type],y=[...Array(g).keys()].map(e=>e);try{switch(c.sem){case"Position":3!==u.ncomp||"F32"!==u.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Position ("+u+")"):(r=new R(t,u.byteOffset,p,f),s=new he(r.typedBuffer,y,3));break;case"Normal":if(3!==u.ncomp||"F32"!==u.type)this._dbg(3,"[Unsupported Feature] Unsupported view for Normal ("+u+")");else{const e=new R(t,u.byteOffset,p,f),r=ue(e.typedBuffer,i);a=new k(r.buffer),l=new he(a.typedBuffer,y,2)}break;case"TexCoord":2!==u.ncomp||"F32"!==u.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Texcoord ("+u+")"):void 0===n&&(n=new he(new P(t,u.byteOffset,p,f).typedBuffer,y,2));break;case"Color":4===u.ncomp?("F32"===u.type&&(d=new H(t,u.byteOffset,p,f)),"U8"===u.type&&(d=new E(t,u.byteOffset,p,f)),"U16"===u.type&&(d=new S(t,u.byteOffset,p,f))):3===u.ncomp&&("F32"===u.type&&(d=new R(t,u.byteOffset,p,f)),"U8"===u.type&&(d=new V(t,u.byteOffset,p,f)),"U16"===u.type&&(d=new A(t,u.byteOffset,p,f))),null==d?this._dbg(2,"[Unsupported Feature] Unsupported view for Color ("+u+")"):o=new he(d.typedBuffer,y,u.ncomp);break;case"FeatureIndex":break;default:this._dbg(2,"[Unsupported Feature] Unsupported semantic ("+c.sem+"). Skipping vertex attribute.")}}catch(h){this._dbg(2,"Error Creating buffer ("+h+"). Skipping vertex attribute.")}}if(e.index){const i=e.index.view,r=void 0,s=i.byteOffset+i.byteCount;switch(e.index.view.type){case"U16":c=new I(t,i.byteOffset,r,s);break;case"U32":c=new F(t,i.byteOffset,r,s);break;default:this._dbg(3,"[Unsupported Feature] index type not supported ("+i.type+").")}}if(null==c&&null!=r){const e=r.count;if(e<65535){const t=new Uint16Array(e);c=new I(t.buffer)}else{const t=new Uint32Array(e);c=new F(t.buffer)}for(let t=0;t<e;t++)c.set(t,t)}return{positionView:r,positionAttr:s,colorAttr:o,texCoord0Attr:n,indicesView:c,normalsView:a,normalsAttr:l}}_loadModifications(){if(this.removeHandles("modifications"),null==this.layer.modifications)return void(this._modifications=[]);const e=this.layer.modifications;this.addHandles(this._updatingHandles.addOnCollectionChange(()=>e,()=>this._modifications=e.toArray(),s),"modifications")}_deletePerObjectData(e){this._wasm?.onRenderableEvicted(this,e.handle,e.usedMemory),this.freeRenderable(e.handle)}_dbg(e,i){this._dbgFlags.has(e)&&(3===e?t.getLogger(this).error(i):t.getLogger(this).warn(i))}};e([l()],xe.prototype,"fullOpacity",null),e([l({type:[D]})],xe.prototype,"_modifications",void 0),e([l()],xe.prototype,"_visibleGeometryChangedSchedulerHandle",void 0),e([l()],xe.prototype,"layer",void 0),e([l({readOnly:!0})],xe.prototype,"visibleAtCurrentScale",null),e([l({readOnly:!0})],xe.prototype,"_collection",null),e([l()],xe.prototype,"elevationOffset",null),xe=e([c("esri.views.3d.layers.IntegratedMesh3DTilesLayerView3D")],xe);const Oe=xe,Ce=j();function Te(e,t){const i=re(e);return y(Ce,i.center,t),i.center=Ce,i}function Ue(e){return e?new ie(e.center,e.halfSize,f(...e.quaternion)):null}function Pe(e){return`${e}`}const He=new Array;export{Oe as default};
5
+ import{__decorate as e}from"tslib";import has from"../../../core/has.js";import t from"../../../core/Logger.js";import{destroyMaybe as i,removeMaybe as r}from"../../../core/maybe.js";import{initial as s,watch as o,when as n}from"../../../core/reactiveUtils.js";import{schedule as a}from"../../../core/scheduling.js";import{property as l,subclass as c}from"../../../core/accessorSupport/decorators.js";import{fromMat4 as d,invert as h}from"../../../core/libs/gl-matrix-2/math/mat3.js";import{create as m,IDENTITY as u}from"../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{create as p}from"../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{fromValues as f}from"../../../core/libs/gl-matrix-2/factories/quatf64.js";import{o as g,g as y,a as b,f as _}from"../../../chunks/vec32.js";import{fromArray as w,clone as v,create as j}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{fromValues as M}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{SphericalECEFSpatialReferenceLike as x}from"../../../geometry/ellipsoidUtils.js";import{computeTranslationToOriginAndRotation as O}from"../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{localLinearScaleFactors as C}from"../../../geometry/projection/localLinearScaleFactors.js";import{projectVectorToVector as T}from"../../../geometry/projection/projectVectorToVector.js";import{create as U}from"../../../geometry/support/aaBoundingRect.js";import{BufferViewVec2f as P,BufferViewVec4f as H,BufferViewVec4u8 as E,BufferViewVec4u16 as S,BufferViewVec3f as R,BufferViewVec3u8 as V,BufferViewVec3u16 as A,BufferViewInt16 as k,BufferViewUint32 as I,BufferViewUint16 as F}from"../../../geometry/support/buffer/BufferView.js";import D from"../../../layers/support/SceneModification.js";import{getElevationOffsetInMeters as L}from"../../../support/elevationInfoUtils.js";import{toWasmModification as B}from"./I3SMeshWorkerHandle.js";import{LayerView3D as G}from"./LayerView3D.js";import{Lyr3DViewPerformanceInfo as N}from"./Lyr3DViewPerformanceInfo.js";import{addLayerViewToWasm as z,removeLayerViewFromWasm as W,getLyr3DWasm as $}from"./Lyr3DWasm.js";import{LayerElevationProvider as q}from"./i3s/LayerElevationProvider.js";import{primTypeConversion as J,alphaModeConversion as K,faceCullingConversion as Q,wrapModeConversion as X,lyr3DTypeToByteSize as Y}from"./support/lyr3dTypeConversions.js";import{Tiles3DIntersectionHandler as Z}from"./support/Tiles3DIntersectionHandler.js";import{ElevationRange as ee}from"../support/ElevationRange.js";import{toBoundingRect as te}from"../support/extentUtils.js";import{Obb as ie,compute as re}from"../support/orientedBoundingBox.js";import{ObjectParameters as se}from"../webgl-engine/collections/Component/ObjectParameters.js";import{GeometryParameters as oe,createVertexBufferLayout as ne,SourceGeometry as ae}from"../webgl-engine/collections/Component/SourceGeometry.js";import{Transform as le}from"../webgl-engine/collections/Component/Transform.js";import{RenderTexture as ce}from"../webgl-engine/core/material/RenderTexture.js";import{getEllipsoidMode as de}from"../webgl-engine/core/shaderLibrary/util/EllipsoidMode.js";import{Attribute as he}from"../webgl-engine/lib/Attribute.js";import{ManagedTexture as me}from"../webgl-engine/lib/ManagedTexture.js";import{compressAndTransformNormals as ue}from"../webgl-engine/lib/Normals.js";import{writeAttribute as pe,writeBufferVec2 as fe}from"../webgl-engine/materials/internal/bufferWriterUtils.js";import ge from"../../layers/LayerView.js";import{spatialReferenceIncompatibleError as ye,isInEffectiveScaleRange as be}from"../../support/layerViewUtils.js";import{TextureCompressionTracker as _e}from"../../support/TextureCompressionTracker.js";import{alphaCutoff as we}from"../../../webscene/support/AlphaCutoff.js";class ve{constructor(e,t,i,r,s,o,n,a){this.handle=e,this.componentObjects=t,this.textures=i,this.cpuMemoryUsage=r,this.vboMemoryUsage=s,this.textureMemoryUsage=o,this.obb=n,this.stableNodeId=a,this.isVisible=!1,this.usedMemory=this.textureMemoryUsage+this.vboMemoryUsage+this.cpuMemoryUsage;const l=j();n?.getCenter(l),this._obbCenter=l,this._obbRadiusSquared=n?n?.radius**2:0}boundingVolumeIntersectsRay(e,t){if(!this.obb)return!0;const i=b(je,this._obbCenter,e),r=_(i,t);return _(i,i)-r*r<=this._obbRadiusSquared&&this.obb.intersectRay(e,t)}}const je=j();function Me(e){return Math.round(e/1048.576)/1e3}let xe=class extends(G(ge)){get hasModifications(){return this._modifications&&this._modifications.length>0}constructor(e){super(e),this.type="integrated-mesh-3dtiles",this._compressionTracker=new _e,this._modifications=new Array,this._visibleGeometryChangedSchedulerHandle=null,this._wasmLayerId=-1,this.ignoresMemoryFactor=!1,this._usedMemory=0,this._cacheMemory=0,this.drapeTargetType=1,this._applySSAO=!has("disable-feature:im-ssao"),this._shadeNormals=!!has("enable-feature:im-shading"),this._lyrHandleToObjects=new Map,this._visibleObjects=new Set,this._suspendedHandle=null,this._dbgFlags=new Set,this._memCache=e.view.resourceController.memoryController.newCache(`IM3DTiles-${this.uid}`,e=>this._deletePerObjectData(e))}initialize(){this._dbgFlags.add(3),this._dbg(2,"Tiles3DLayerView3D initialize() called");const{view:e}=this;if(this._updatingHandles.add(()=>this.layer.modifications,()=>this._loadModifications(),s),!this._canProjectWithoutEngine())throw ye("layer",this.layer.spatialReference.wkid,e.renderSpatialReference?.wkid);const t=z(this).then(t=>{this._wasmLayerId=t,this._intersectionHandler=new Z(this),e.sceneIntersectionHelper.addIntersectionHandler(this._intersectionHandler),this._updatingHandles.add(()=>this.slicePlaneEnabled,e=>this._slicePlaneEnabledChange(e)),this._updatingHandles.add(()=>this._modifications,()=>this._modificationsChanged(),s),this._updatingHandles.add(()=>this.fullOpacity,()=>this._opacityChange()),this._updatingHandles.add(()=>e.clippingArea,()=>this._clippingAreaChanged(),s),this._elevationProvider=new q({view:e,layerElevationSource:this,intersectionHandler:this._intersectionHandler}),e.elevationProvider.register(1,this._elevationProvider),e.overlayManager.registerDrapeTarget(this),this.addHandles([o(()=>this.layer.elevationInfo,e=>this._elevationInfoChanged(e))]),this._suspendedHandle=o(()=>this.suspended,e=>this._wasm?.setEnabled(this,!e),s)});this.addResolvingPromise(t),this._replacesTerrain&&this.addHandles(n(()=>this.view.map.ground.opacity,()=>{this._opacityChange()}))}get _replacesTerrain(){return this.layer.replacesTerrain&&!!this.view.map.basemap?.groundLayers.includes(this.layer)}get fullOpacity(){return this._replacesTerrain?this.view.map.ground.opacity:1}get opacity(){return 1}_opacityChange(){const{fullOpacity:e}=this;this.forEachComponentObject(t=>{this._collection.getMaterial(t).objectOpacity=e})}intersect(e,t,i,r){this._intersectionHandler.intersect(e,t,i,r,null,!1)}get ready(){return!0}destroy(){this._dbg(2,"Tiles3DLayerView3D destroy() called"),W(this),this._suspendedHandle&&(this._suspendedHandle.remove(),this._suspendedHandle=null),this._intersectionHandler&&(this.view.sceneIntersectionHelper.removeIntersectionHandler(this._intersectionHandler),this._intersectionHandler=null),this._elevationProvider&&(this._elevationProvider.notifyObjectsChangedFunctional(e=>this.forEachComponentObject(t=>e(t.obb))),this.view.elevationProvider.unregister(this._elevationProvider),this._elevationProvider=null),this.view.overlayManager.unregisterDrapeTarget(this),this._lyrHandleToObjects.forEach(e=>this.freeObject(e)),this._lyrHandleToObjects.clear(),this._visibleObjects.clear(),this._usedMemory=this._cacheMemory=0,this._memCache.destroy(),this._updatingHandles=i(this._updatingHandles),this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=r(this._visibleGeometryChangedSchedulerHandle)}_modificationsChanged(){const e=this.layer.spatialReference,t=B(this._layerClippingArea,this._modifications,e);this._wasm?.setMeshModifications(this,t,e.wkid)}_clippingAreaChanged(){const e=this.layer.spatialReference,t=U();this._layerClippingArea=te(this.view.clippingArea,t,e)?t:null,this._modificationsChanged()}_visibleGeometryChanged(){this._visibleGeometryChangedSchedulerHandle??=a(()=>{this.emit("visible-geometry-changed"),this._visibleGeometryChangedSchedulerHandle=null})}_slicePlaneEnabledChange(e){this._intersectionHandler&&(this._intersectionHandler.slicePlaneEnabled=e),this.forEachComponentObject(t=>this._collection.getMaterial(t).commonMaterialParameters.hasSlicePlane=e)}_elevationInfoChanged(e){this._wasm?.setLayerOffset(this,L(e))}get _wasm(){return $(this.view)}get wasmLayerId(){return this._wasmLayerId}get usedMemory(){return this._usedMemory}get unloadedMemory(){return 0}get cachedMemory(){return this._cacheMemory}get visibleAtCurrentScale(){return be(this.layer.effectiveScaleRange,this.view.scale)}get performanceInfo(){let e=0,t=0,i=0,r=0,s=0,o=0;return this._lyrHandleToObjects.forEach(n=>{n.isVisible?(e+=n.textureMemoryUsage,t+=n.vboMemoryUsage,s++):(i+=n.textureMemoryUsage,r+=n.vboMemoryUsage,o++)}),new N(this.usedMemory,s,o,Me(t),Me(e),Me(r),Me(i))}_canProjectWithoutEngine(){if(2===this.view.state.viewingMode){const e=this.view.renderSpatialReference?.isWebMercator?3857:this.view.renderSpatialReference?.wkid??-1;if(3857!==e&&32662!==e)return!1}return!0}get _stage(){return this.view.stage}get _collection(){return this._stage.renderView.componentObjectCollection}get elevationProvider(){return this._elevationProvider}get elevationOffset(){return L(this.layer.elevationInfo)}get elevationRange(){const e=this.fullExtent;return e?.zmin&&e?.zmax?new ee(e.zmin,e.zmax):null}getElevationRange(e){return null}get fullExtent(){return this.layer.fullExtent}forEachComponentObject(e){this._forEachObject(this._lyrHandleToObjects.values(),e)}forEachVisibleTile(e){for(const t of this._visibleObjects)e(t)}forEachVisibleComponentObject(e){this._forEachObject(this._visibleObjects,e)}_forEachObject(e,t){for(const i of e)for(const e of i.componentObjects)t(e)}isUpdating(){const e=this._wasm;return this._wasmLayerId>=0&&null!=e&&(e.isUpdating(this._wasmLayerId)||this._compressionTracker.compressing)}updatingFlagChanged(){this.notifyChange("updating")}async createRenderable(e){if(this.destroyed){const e=`IntegratedMesh3DTilesLayerView3D[${this.layer?.title}]: createRenderable called on destroyed instance`;throw new Error(e)}let t=0;const{meshData:i}=e;if(null==i.data)throw new Error("meshData.data undefined");if(i.desc=JSON.parse(i.desc),null==i.desc)throw new Error("meshData.desc undefined");const r=w(i.desc.origin),s=new Array,o=this.view.basemapTerrain.spatialReference;let n,a;if("global"===this.view.viewingMode){const e=p();O(x,r,e,o),n=d(m(),e),a=h(m(),n)}else n=u,a=u;const l=v(r),c=j(),f=Ue(i.desc.obb);let y=0,b=0;const _={textureMemoryUsage:0},U=new Map,H=i.desc.prims.length,E=new Array;try{for(let e=0;e<H;e++){const t=i.desc.prims[e];this._dbg(2,JSON.stringify(t));if(null==J[t.ptype]||null==i.data){this._dbg(2,"[Unsupported Feature] Unsupported primitive mode ("+t.ptype+"). Skipping primitive.");continue}const d=i.desc?.materials&&null!=t.materialId?i.desc.materials[t.materialId]:null,h=null!=d?d.lightingModel:"Unlit",{positionView:m,positionAttr:p,normalsView:w,normalsAttr:v,colorAttr:x,texCoord0Attr:O,indicesView:H}=this.getBufferViews(t,i.data.buffer,n);if(null==p||null==m||null==H)continue;const E=new oe(null!=x,O?1:0,null!=w,this._shadeNormals||this._replacesTerrain,this._applySSAO),S=p.data.length/p.size,R=(e,t)=>!e||e.data.length/e.size===S||(this._dbg(3,`${t} !== numPos. Skipping primitive.`),!1);if(!R(O,"numTexcoord")||!R(x,"numColors")||!R(v,"normals"))continue;const V=ne(E),A=f?.clone()??Te(p,r);if(n!==u)for(let e=0;e<m.count;e++)m.getVec(e,c),g(c,c,n),m.setVec(e,c);const k=V.createBuffer(p.data.length);if(pe("position",p,null,null,k,0),null!=O){const e=k.getField("uv0",P);fe(O,e,0)}null!=x&&pe("color",x,null,null,k,0),null!=v&&pe("normalCompressed",v,null,null,k,0);const I=new Uint32Array([0,H.typedBuffer.length]),F=new ae({data:k.buffer,count:k.byteLength/V.stride,layoutParameters:E},{positions:m.typedBuffer,indices:H.typedBuffer},H.typedBuffer,I);y+=m.count+H.count;const D=this.view.renderSpatialReference,L=j(),B=[1,1,1];C(l,D,B,o)||this._dbg(3,"Unsupported coordinate system for IM overlay"),T(l,D,L,o);let G=()=>{},N=Promise.resolve(He);if(d){const e=e=>this._getTexture(e,i,U,_),t=e(d.baseColorTex),r="Pbr"===h,s=r?e(d.metalTex):null,o=r?e(d.emissiveTex):null,n=r?e(d.occlusionTex):null,a=r?e(d.normalTex):null,l=[t,s,o,n,a].map(e=>e?.loadPromise??null);N=Promise.all(l),G=e=>{e.baseColor=d.baseColorFactor,e.usePBR="Pbr"===h,e.hasParametersFromSource=!1,e.baseColorTexture=t,e.usePBR&&(e.mrrFactors=[d.metallicFactor,d.roughnessFactor,0],e.emissiveBaseColor=d.emissiveFactor??[0,0,0],e.metallicRoughnessTexture=s,e.emissionTexture=o,e.occlusionTexture=n,e.normalTexture=a),e.alphaDiscardMode=K[d.alphaMode],e.objectOpacity=this.fullOpacity,_.textureMemoryUsage+=e.baseColorTexture?.texture?.usedMemory??0,e.usePBR&&(_.textureMemoryUsage+=(e.metallicRoughnessTexture?.texture?.usedMemory??0)+(e.emissionTexture?.texture?.usedMemory??0)+(e.occlusionTexture?.texture?.usedMemory??0)+(e.normalTexture?.texture?.usedMemory??0)),e.commonMaterialParameters.doubleSided=d.isDoubleSided,e.commonMaterialParameters.cullFace=Q[d.faceCulling??"NotSet"],e.commonMaterialParameters.hasSlicePlane=this.slicePlaneEnabled,e.componentParameters.castShadows=0,e.textureAlphaCutoff=d.alphaCutoff??we,e.alphaDiscardMode=K[d.alphaMode],e.isIntegratedMesh=!0,e.sphereDepthInterpolate=this.layer.hasGoogleUrl,e.polygonOffsetEnabled=!1,e.hasOccludees=!1,e.ellipsoidMode=de(this.view.spatialReference)}}const z=N.then(()=>()=>{if(this.destroyed){const e="Trying to add object to destroyed layer view";throw this._dbg(3,`${e} !== numPos. Skipping primitive.`),new Error(e)}const e=this._collection.createObject(new se(M(L[0],L[1],B[0],B[1]),new le(l,a),A,F,!1));return this._collection.updateMaterial(e,G),b+=this._collection.getObjectGPUMemoryUsage(e),e});s.push(z)}if(E.push(...await Promise.all(s)),this.destroyed){throw new Error("IntegratedMesh3DTilesLayerView3D: createRenderable object destroyed during call")}}catch(A){throw U.forEach(e=>this._stage.removeTexture(e)),A}const S=E.map(e=>e()),R=new Array;U.forEach(e=>R.push(e));const V=new ve(e.handle,S,R,y,b,_.textureMemoryUsage,f,e.stableNodeId);return this._lyrHandleToObjects.set(e.handle,V),this._memCache.put(Pe(V.handle),V),t=V.usedMemory,this._cacheMemory+=t,{memUsageBytes:V.usedMemory}}freeRenderable(e){const t=this._lyrHandleToObjects.get(e);t&&(t.isVisible?(this._visibleObjects.delete(t),this._usedMemory-=t.usedMemory):this._cacheMemory-=t.usedMemory,this.freeObject(t),this._lyrHandleToObjects.delete(e))}freeObject(e){const t=Pe(e.handle);this._memCache.pop(t),e.textures.forEach(e=>this._stage.removeTexture(e)),e.componentObjects.forEach(e=>this._collection.destroyObject(e))}setRenderableVisibility(e,t,i){for(let r=0;r<i;++r){const i=t[r];if(!i)continue;const s=e[r],o=this._lyrHandleToObjects.get(s);if(o){if(o.isVisible)continue;this._visibleGeometryChanged(),o.isVisible=!0,this._visibleObjects.add(o),this._usedMemory+=o.usedMemory,this._cacheMemory-=o.usedMemory,o.componentObjects.forEach(e=>{this._collection.setObjectVisibility(e,i),this._elevationProvider.notifyObjectChanged(this._collection.getComponentObb(e))}),this._memCache.pop(Pe(s))}}for(let r=0;r<i;++r){const i=e[r],s=t[r];if(s)continue;const o=this._lyrHandleToObjects.get(i);if(o){if(!o.isVisible)continue;this._visibleGeometryChanged(),o.isVisible=!1,this._visibleObjects.delete(o),this._usedMemory-=o.usedMemory,this._cacheMemory+=o.usedMemory,o.componentObjects.forEach(e=>{this._collection.setObjectVisibility(e,s),this._elevationProvider.notifyObjectChanged(this._collection.getComponentObb(e))}),this._memCache.put(Pe(i),o)}}}setLodPixelThreshold(e){this._wasm?.setLodPixelThreshold(this,e)}_getTexture(e,t,i,r){const s=e&&t.desc?.images?.[e.imageId];if(!s||!t.data?.buffer)return null;const o=i.get(s)??this._createTexture(e,t,i,r);return o?new ce(this._stage.renderView.textures,o.id):null}_createTexture(e,t,i,r){const s=e&&t.desc?.images?.[e.imageId];if(!s||!t.data?.buffer)return null;const o=this._stage,{renderView:n}=o,a=n.renderingContext.parameters.maxMaxAnisotropy,l=!!s.mipCount||a>1,c=X[e.wrapMode??"None"];let d=s.alpha?6408:6407;const h=new Uint8Array(t.data.buffer,s.data.byteOffset,s.data.byteCount);let m=null,u=null,p=null;switch(s.format){case"Raw":"R8"===s.pixelFormat?(m=h,d=6403,u=""):"Rgb8"===s.pixelFormat?(m=h,d=6407,u=""):"Rgba8"===s.pixelFormat&&(m=h,d=6408,u="");break;case"Dxt1":m=h,d=6407,u="image/vnd-ms.dds";break;case"Dxt5":m=h,d=6408,u="image/vnd-ms.dds";break;case"Basis":m=h,d=6407,u="image/ktx2";break;case"Png":u="image/png",p=document.createElement("img");break;case"Jpeg":u="image/jpeg",p=document.createElement("img");break;case"Etc2":u="image/ktx",p=document.createElement("img");break;case"Astc":this._dbg(3,"Astc texture not supported");break;case"Pvrtc":this._dbg(3,"Pvrtc texture not supported")}if(p&&u){const e=new Blob([h],{type:u});p.src=URL.createObjectURL(e),m=p}if(m&&null!=u){const e=has("enable-feature:esri-compress-IM-textures")?{compressionTracker:this._compressionTracker,compressionCallback:e=>{e&&e>0&&(r.textureMemoryUsage-=e)}}:void 0,t=new me(m,{mipmap:l,maxAnisotropy:a,encoding:u,wrap:c,pixelFormat:d,compressionOptions:e,noUnpackFlip:!0,width:s.mip0Width,height:s.mip0Height});return this._stage.addTexture(t),i.set(s,t),t}return null}getBufferViews(e,t,i){let r,s,o,n,a,l,c,d=null;for(let m=0;m<e.atrbs.length;m++){const c=e.atrbs[m],u=c.view,p=void 0,f=u.byteOffset+u.byteCount,g=u.byteCount/Y[u.type],y=[...Array(g).keys()].map(e=>e);try{switch(c.sem){case"Position":3!==u.ncomp||"F32"!==u.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Position ("+u+")"):(r=new R(t,u.byteOffset,p,f),s=new he(r.typedBuffer,y,3));break;case"Normal":if(3!==u.ncomp||"F32"!==u.type)this._dbg(3,"[Unsupported Feature] Unsupported view for Normal ("+u+")");else{const e=new R(t,u.byteOffset,p,f),r=ue(e.typedBuffer,i);a=new k(r.buffer),l=new he(a.typedBuffer,y,2)}break;case"TexCoord":2!==u.ncomp||"F32"!==u.type?this._dbg(3,"[Unsupported Feature] Unsupported view for Texcoord ("+u+")"):void 0===n&&(n=new he(new P(t,u.byteOffset,p,f).typedBuffer,y,2));break;case"Color":4===u.ncomp?("F32"===u.type&&(d=new H(t,u.byteOffset,p,f)),"U8"===u.type&&(d=new E(t,u.byteOffset,p,f)),"U16"===u.type&&(d=new S(t,u.byteOffset,p,f))):3===u.ncomp&&("F32"===u.type&&(d=new R(t,u.byteOffset,p,f)),"U8"===u.type&&(d=new V(t,u.byteOffset,p,f)),"U16"===u.type&&(d=new A(t,u.byteOffset,p,f))),null==d?this._dbg(2,"[Unsupported Feature] Unsupported view for Color ("+u+")"):o=new he(d.typedBuffer,y,u.ncomp);break;case"FeatureIndex":break;default:this._dbg(2,"[Unsupported Feature] Unsupported semantic ("+c.sem+"). Skipping vertex attribute.")}}catch(h){this._dbg(2,"Error Creating buffer ("+h+"). Skipping vertex attribute.")}}if(e.index){const i=e.index.view,r=void 0,s=i.byteOffset+i.byteCount;switch(e.index.view.type){case"U16":c=new F(t,i.byteOffset,r,s);break;case"U32":c=new I(t,i.byteOffset,r,s);break;default:this._dbg(3,"[Unsupported Feature] index type not supported ("+i.type+").")}}if(null==c&&null!=r){const e=r.count;if(e<65535){const t=new Uint16Array(e);c=new F(t.buffer)}else{const t=new Uint32Array(e);c=new I(t.buffer)}for(let t=0;t<e;t++)c.set(t,t)}return{positionView:r,positionAttr:s,colorAttr:o,texCoord0Attr:n,indicesView:c,normalsView:a,normalsAttr:l}}_loadModifications(){if(this.removeHandles("modifications"),null==this.layer.modifications)return void(this._modifications=[]);const e=this.layer.modifications;this.addHandles(this._updatingHandles.addOnCollectionChange(()=>e,()=>this._modifications=e.toArray(),s),"modifications")}_deletePerObjectData(e){this._wasm?.onRenderableEvicted(this,e.handle,e.usedMemory),this.freeRenderable(e.handle)}_dbg(e,i){this._dbgFlags.has(e)&&(3===e?t.getLogger(this).error(i):t.getLogger(this).warn(i))}};e([l()],xe.prototype,"fullOpacity",null),e([l({type:[D]})],xe.prototype,"_modifications",void 0),e([l()],xe.prototype,"_visibleGeometryChangedSchedulerHandle",void 0),e([l()],xe.prototype,"layer",void 0),e([l({readOnly:!0})],xe.prototype,"visibleAtCurrentScale",null),e([l({readOnly:!0})],xe.prototype,"_collection",null),e([l()],xe.prototype,"elevationOffset",null),xe=e([c("esri.views.3d.layers.IntegratedMesh3DTilesLayerView3D")],xe);const Oe=xe,Ce=j();function Te(e,t){const i=re(e);return y(Ce,i.center,t),i.center=Ce,i}function Ue(e){return e?new ie(e.center,e.halfSize,f(...e.quaternion)):null}function Pe(e){return`${e}`}const He=new Array;export{Oe 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 i from"../../../request.js";import{isSome as r}from"../../../core/arrayUtils.js";import{result as s,forEach as o}from"../../../core/asyncUtils.js";import"../../../core/has.js";import n from"../../../core/Logger.js";import{destroyMaybe as a,abortMaybe as d}from"../../../core/maybe.js";import{estimateNumberArrayMemory as l,baseObjectMemory as u,estimateNumberMemory as h,estimateFixedArrayMemory as p,baseArrayMemory as c}from"../../../core/memoryEstimations.js";import{isAbortError as _,allSettledValues as m,throwIfAborted as g}from"../../../core/promiseUtils.js";import{initial as f,watch as y,sync as b,syncAndInitial as w}from"../../../core/reactiveUtils.js";import{pt2px as P}from"../../../core/screenUtils.js";import{isArrayBuffer as N}from"../../../core/typedArrayUtil.js";import{property as v,subclass as x}from"../../../core/accessorSupport/decorators.js";import{b as C,g as S,f as I,d as A}from"../../../chunks/vec32.js";import{clone as j}from"../../../core/libs/gl-matrix-2/factories/vec3f32.js";import{fromValues as R}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import k from"../../../geometry/Extent.js";import V from"../../../geometry/Point.js";import{projectBoundingSphere as Q}from"../../../geometry/projection/projectBoundingSphere.js";import{projectVectorToVector as L}from"../../../geometry/projection/projectVectorToVector.js";import{create as F,fromMinMax as O}from"../../../geometry/support/aaBoundingBox.js";import{fromNormalAndOffset as D,create as E}from"../../../geometry/support/plane.js";import{f as U}from"../../../chunks/sphere.js";import M from"../../../layers/graphics/OptimizedGeometry.js";import{QueryEngine as W}from"../../../layers/graphics/data/QueryEngine.js";import{CodedValue as G}from"../../../layers/support/CodedValue.js";import q from"../../../layers/support/CodedValueDomain.js";import"../../../layers/support/Domain.js";import"../../../layers/support/InheritedDomain.js";import"../../../layers/support/RangeDomain.js";import{unpackFieldNames as z}from"../../../layers/support/fieldUtils.js";import{queueAutoPriority as H}from"../../../request/queue.js";import T from"../../../rest/support/FeatureSet.js";import B from"../../../rest/support/Query.js";import{getElevationOffset as J}from"../../../support/elevationInfoUtils.js";import{LayerView3D as $}from"./LayerView3D.js";import{PointCloudLayerViewPerformanceInfo as K,QueuePerformanceInfo as Z}from"./PointCloudLayerViewPerformanceInfo.js";import{PointCloudWorkerHandle as Y}from"./PointCloudWorkerHandle.js";import{I3SQueryFeatureStore as X}from"./i3s/I3SQueryFeatureStore.js";import{checkPointCloudLayerValid as ee,checkPointCloudLayerCompatibleWithView as te}from"./i3s/I3SUtil.js";import{nodeDiff as ie,sortFrontToBack as re,splitWorkEntries as se}from"./i3s/LoDUtil.js";import{PagedNodeIndex as oe}from"./i3s/PagedNodeIndex.js";import{PointCloudGraphic as ne}from"./i3s/PointCloudGraphic.js";import{PointCloudRenderer as ae}from"./i3s/PointCloudRenderer.js";import{isPointRendererNode as de,PointCloudRendererNode as le}from"./i3s/PointCloudRendererNode.js";import{getSplatSizeAlgorithm as ue,getFixedSizeAlgorithm as he,getRendererInfo as pe,getFilterInfo as ce,rendererUsesFixedSizes as _e,getAttributeInfo as me}from"./i3s/PointCloudRendererUtil.js";import{getAttributeValues as ge,readGeometry as fe,elevationFromPositions as ye}from"./i3s/PointCloudWorkerUtil.js";import{normalizeHighlightTarget as be,emptyHighlightHandle as we}from"./support/highlightUtils.js";import{PopupSceneLayerView as Pe}from"./support/PopupSceneLayerView.js";import{projectToBoundingBox as Ne}from"../support/extentUtils.js";import{computeMapPointFromVec3d as ve}from"../support/hitTest.js";import{Obb as xe}from"../support/orientedBoundingBox.js";import{updatingProgress as Ce}from"../support/updatingProperties.js";import Se from"../../layers/LayerView.js";import{PointCloudLayerView as Ie}from"../../layers/PointCloudLayerView.js";import{getHighlightName as Ae}from"../../support/highlightOptionsUtils.js";import{isInEffectiveScaleRange as je}from"../../support/layerViewUtils.js";import{PromiseQueue as Re}from"../../support/PromiseQueue.js";import{TaskPriority as ke}from"../../support/Scheduler.js";const Ve=8,Qe=E();let Le=class extends(Ie(Pe($(Se)))){constructor(){super(...arguments),this.type="point-cloud-3d",this.maximumPointCount=4e6,this.slicePlaneEnabled=!1,this._renderer=null,this._rendererAdded=!1,this._renderedNodes=new Set,this._updateViewNeeded=!0,this._lodFactor=1,this._maxLoggedBoxWarnings=5,this._pageMultiplier=1,this._nodeLoadEpoch=0,this._indexQueue=[],this._workQueue=new Array,this._idleQueue=new Re,this._indexPagesLoading=new Map,this._loadingNodes=new Map,this._recalcWork=!0,this._layerIsVisible=!1,this._codedDomainPopulationPromise=null,this._codedDomainPopulationAbortController=null,this._totalWork=0,this._index=null,this._loadingInitNodePage=!1,this._nodeIdArray=[],this.ignoresMemoryFactor=!1}get baseUrl(){return this.layer.parsedUrl?.path??""}get pointScale(){const e=ue(this.layer?.renderer),t=1;return null!=e?.scaleFactor?e.scaleFactor:t}get useRealWorldSymbolSizes(){const e=he(this.layer?.renderer),t=!1;return null!=e?.useRealWorldSymbolSizes?e.useRealWorldSymbolSizes:t}get pointSize(){const e=he(this.layer?.renderer),t=0;return null!=e?.size?e.size:t}get inverseDensity(){const e=96;return this.layer?.renderer?1*e/this.layer.renderer.pointsPerInch:5}get availableFields(){const e=pe(this.layer),t=new Set;e.primaryAttribute&&t.add(e.primaryAttribute.name),e.modulationAttribute&&t.add(e.modulationAttribute.name);const i=ce(this.layer);if(i)for(const r of i)r.attributeInfo&&t.add(r.attributeInfo.name);if(this.layer.outFields)for(const r of z(this.layer.fieldsIndex,this.layer.outFields))t.add(r);return Array.from(t)}get _clippingBox(){if(!this.view||!this.view.clippingArea)return null;const e=F(),t=this.view.renderSpatialReference;return Ne(this.view.clippingArea,e,t)?e:null}get _elevationOffset(){const e=this.layer&&this.layer.elevationInfo;return e&&"absolute-height"===e.mode?J(e,this.layer.spatialReference):0}get _graphicOrigin(){return this.layer.graphicOrigin}initialize(){const e=this.view.resourceController,t=Ue(e);this._worker=new Y(t),this.addResolvingPromise(this._worker.promise),this.addResolvingPromise(this.layer.rootPagePromise),ee(this.layer),te(this.layer,this.view),this._initRenderer();const i=this._initNodePages(),r=this.view.resourceController.memoryController;this._memCache=r.newCache(`pcl-${this.layer.uid}`),this._queryFeaturesCache=r.newCache(`pcl-query-features-${this.layer.uid};`),this._updatingHandles.add(()=>this._clippingBox,()=>this._setUpdateViewNeeded(),f),this._updatingHandles.add(()=>this._elevationOffset,()=>this._elevationOffsetChanged(),f),this._updatingHandles.add(()=>this.layer.renderer,()=>this._rendererChanged(),f),this._updatingHandles.add(()=>this.layer.filters,()=>this._reload(),f),this._updatingHandles.add(()=>this.layer.outFields,()=>this._reload(),f),this._updatingHandles.add(()=>this.layer.effectiveScaleRange,()=>this._setUpdateViewNeeded()),this._updatingHandles.add(()=>this.view.state.contentCamera,()=>this._setUpdateViewNeeded()),this.addHandles([y(()=>this.view.quality,()=>this._setUpdateViewNeeded(),b)]),this.addResolvingPromise(i),this.when(()=>{this.addHandles([e.scheduler.registerTask(ke.POINT_CLOUD_LAYER,this),y(()=>2===this.view.state.mode,()=>this._setUpdateViewNeeded(),w),this._updatingHandles.add(()=>this.suspended,e=>{e?this._clearNodeState():this._setUpdateViewNeeded()},f)])},()=>{this._updatingHandles.removeAll(),this.removeAllHandles()})}_setUpdateViewNeeded(){this._updateViewNeeded=!0,this._updateLoading()}destroy(){this.cancelLoading(),this._worker=a(this._worker),this._destroyRenderer(),this._memCache=a(this._memCache),this._queryFeaturesCache=a(this._queryFeaturesCache),this._queryEngine=a(this._queryEngine),this._codedDomainPopulationAbortController=d(this._codedDomainPopulationAbortController),this._codedDomainPopulationPromise=null}_initRenderer(){this._renderer=new ae({createGraphic:(e,t,i)=>this._createGraphic(e,t,i)}),this._renderer.layerViewUid=this.uid,this._updatingHandles.add(()=>this._clippingBox,e=>this._renderer.clippingBox=e,f),this._updatingHandles.add(()=>this.suspended,e=>this._setPointsVisible(!e),f),this._updatingHandles.add(()=>this.pointScale,e=>this._renderer.scaleFactor=e,f),this._renderer.minSizePx=Math.sqrt(2),this._updatingHandles.add(()=>this.useRealWorldSymbolSizes,e=>this._renderer.useRealWorldSymbolSizes=e,f),this._updatingHandles.add(()=>this.pointSize,e=>{const t=P(e);this._renderer.size=e,this._renderer.sizePx=t},f),this._updatingHandles.add(()=>this.slicePlaneEnabled,e=>this._renderer.slicePlaneEnabled=e,f),this._updatingHandles.add(()=>this.inverseDensity,()=>this._setUpdateViewNeeded(),f),this._updatingHandles.add(()=>this.maximumPointCount,()=>this._setUpdateViewNeeded(),f),this._updatingHandles.add(()=>this.view.qualitySettings.sceneService.pointCloudLoDFactor,e=>{this._lodFactor=e,this._setUpdateViewNeeded()},f)}_destroyRenderer(){this._renderer.removeAll(),this._setPointsVisible(!1)}_createGraphic(e,t,i,r){const s=null!=e.pointIdFilterMap?e.pointIdFilterMap[t]:t,o=i?"declaredClass"in i?i:ve(this.view,i):null;return r??=this._createGraphicAttributes(e,s),new ne({pointCloudMetadata:{nodeId:e.id,pointIndexInNode:t,attributePointIndexInNode:s,epoch:this._nodeLoadEpoch},geometry:o,attributes:r,layer:this.layer,sourceLayer:this.layer,origin:this._graphicOrigin})}_createGraphicAttributes(e,t){const i={};for(const r of e.attributes)this._encodeGraphicAttribute(r.attributeInfo,r.values,t,i);return i}_getGraphicAttribute(e,t,i){const r=e.storageInfo?.attributeValues,s=r?.valuesPerElement??1;if(1===s)return t[i];if("UInt8"===r?.valueType&&s<=4){let e=0;const r=i*s;for(let i=r;i<r+s;i++)e=(e<<8)+t[i];return e}}_encodeGraphicAttribute(e,t,i,r){r[e.name]=this._getGraphicAttribute(e,t,i)}_setPointsVisible(e){e&&!this._rendererAdded?(this.view.stage.addRenderPlugin(this._renderer),this._rendererAdded=!0):!e&&this._rendererAdded&&(this.view.stage.removeRenderPlugin(this._renderer),this._rendererAdded=!1)}_rendererChanged(){this._renderer.useFixedSizes=_e(this.layer.renderer),this._reload()}_reload(){this._clearNodeState(),this._memCache.clear(),this._setUpdateViewNeeded()}_elevationOffsetChanged(){this._clearNodeState(),this._memCache.clear(),this._initNodePages()}_displayNodes(e){this._workQueue=ie([...this._renderedNodes],e,this._index),re(this._workQueue,this.view.state.contentCamera.viewForward,this._index),se(this._workQueue,Ve,this._index),this._updateQueues(),this._totalWork=this._computeWork(),this._updateLoading(),this._layerIsVisible=e.length>0||this._loadingInitNodePage,this.notifyChange("suspended")}cancelLoading(){this._cancelNodeLoading(),this._cancelIndexLoading()}_cancelNodeLoading(){const e=new Array;this._loadingNodes.forEach(({abortController:t})=>e.push(t)),this._loadingNodes.clear();for(const t of e)t.abort();this._workQueue=[],this._idleQueue.cancelAll(),this._totalWork=this._computeWork(),this._updateLoading()}_updateQueues(){const e=new Set;this._workQueue.forEach(t=>t.load.forEach(t=>e.add(t)));const t=new Array,i=new Map;this._loadingNodes.forEach((r,s)=>{e.has(s)?i.set(s,r):t.push(r)}),this._loadingNodes=i;for(const{abortController:r}of t)r.abort();this._workQueue=this._workQueue.filter(e=>{for(const t of e.load)if(this._loadingNodes.has(t))return this._recalcWork=!0,!1;return!0}),this._totalWork=this._computeWork(),this._updateLoading()}_cancelIndexLoading(){this._indexQueue=[],this._indexPagesLoading.forEach(({abortController:e})=>e.abort()),this._indexPagesLoading.clear(),this._totalWork=this._computeWork(),this._updateLoading()}_clearNodeState(){this._nodeLoadEpoch++,this._renderedNodes.forEach(e=>this._removeFromRenderer(e)),this._cancelNodeLoading()}get readyToRun(){return this.suspended?this._updateViewNeeded:this._updateViewNeeded||this._indexQueue.length>0||this._workQueue.length>0||this._idleQueue.readyToRun}runTask(e){if(this.suspended){if(this._updateViewNeeded){this._updateViewNeeded=!1;const e=this._isRootNodeVisible();e!==this._layerIsVisible&&(this._layerIsVisible=e,this.notifyChange("suspended")),this._updateLoading()}}else{for(e.run(()=>this._updateWorkQueues());this._indexQueue.length>0&&e.run(()=>this._processIndexQueue()););this._processWorkQueue(e),this._idleQueue.runTask(e)}}_processIndexQueue(){const e=this._indexQueue.shift(),t=this._loadNodePage(e);return this._indexPagesLoading.set(e,t),t.promise.then(t=>{this._index.addPage(e,t,this._elevationOffset),this._setUpdateViewNeeded()}).then(()=>{this._indexPagesLoading.delete(e)},()=>{this._indexPagesLoading.delete(e)}),!0}_processWorkQueue(e){for(;!e.done;){const t=this._scheduleWorkEntry();if(null==t)return void e.madeProgress();this._processWorkEntry(t),e.madeProgress()}}_scheduleWorkEntry(){let e=this._workQueue.length;for(;e--;){const e=this._workQueue.shift();if(!e.remove.find(e=>!this._renderedNodes.has(e)))return e;this._workQueue.push(e)}return null}_processWorkEntry(e){if(0!==e.load.length)Promise.all(e.load.map(e=>{const t=new AbortController,i=this._memCache.pop(e.toString());return null!=i?this._loadingNodes.set(e,{abortController:t,promise:Promise.resolve(i)}):this._loadingNodes.has(e)||this._loadingNodes.set(e,{abortController:t,promise:this._loadNode(e,t.signal)}),this._loadingNodes.get(e).promise})).then(t=>{for(let i=0;i<e.load.length;i++)if(t[i]){const r=this._setupRendererData(e.load[i],t[i]);this._addToRenderer(r)}for(const i of e.remove)this._removeFromRenderer(i)}).catch(()=>{}).then(()=>{for(const t of e.load)this._loadingNodes.delete(t);this._updateLoading(),this._recalcWork&&!this._idleQueue.updating&&0===this._indexQueue.length&&0===this._loadingNodes.size&&(this._recalcWork=!1,this._setUpdateViewNeeded())}),this._updateLoading();else for(const t of e.remove)this._removeFromRenderer(t)}async _populateClassCodeCodedDomain(e,t){const i="CLASS_CODE",r=this.layer.fieldsIndex.get(i);if(!r||r.domain)return;if(!e.includes(r.name))return;const o=await s(this.layer.queryCachedStatistics(i,{signal:t}));if(!1===o.ok)return;const n=o.value?.stats?.labels?.labels;n&&Array.isArray(n)&&(r.domain=new q({name:"CLASS_CODE",codedValues:n.map(e=>new G({code:e.value,name:e.label}))}))}async prepareFetchPopupFeatures(e){return this._codedDomainPopulationPromise||(this._codedDomainPopulationAbortController=new AbortController,this._codedDomainPopulationPromise=this._populateClassCodeCodedDomain(e,this._codedDomainPopulationAbortController.signal).then(()=>{this._codedDomainPopulationAbortController=null})),this._codedDomainPopulationPromise}async whenGraphicAttributes(e,t){const i=this._splitGraphicsPerNode(e),s=this.layer.attributeStorageInfo,n=t.map(e=>me(s,e)).filter(r),a=async(e,t)=>{const i=this._index.getNode(t);await o(n,async t=>{const r=t.useElevation?await this._loadElevationAttributeFromGeometry(i.resourceId):await this._loadAndParseAttribute(i,t);if(r)for(const i of e)if(this._isValidPointGraphic(i)){const e=i.pointCloudMetadata.attributePointIndexInNode;this._encodeGraphicAttribute(t,r,e,i.attributes)}})},d=[];return i.forEach((e,t)=>{d.push(a(e,t))}),await Promise.allSettled(d),e}_isValidPointGraphic(e){return e instanceof ne&&e.pointCloudMetadata?.epoch===this._nodeLoadEpoch}_splitGraphicsPerNode(e){const t=new Map;for(const i of e){if(!this._isValidPointGraphic(i))continue;const e=i.pointCloudMetadata,r=t.get(e.nodeId);r?r.push(i):t.set(e.nodeId,[i])}return t}async _loadAndParseAttribute(e,t){const i=await this._loadAttribute(e.resourceId,t,null);return i?ge({attributeInfo:t,buffer:i},null,e.vertexCount):null}async _loadElevationAttributeFromGeometry(e){const t=this.layer.store.defaultGeometrySchema,i=fe(t,await this._loadGeometry(e,null));return ye(i,i.length/3)}highlight(e,i){const r=be(e);if(0===r.length)return we;if(!(r[0]instanceof t))return we;const s=r;return this._renderer.highlight(s.map(e=>this._graphicToPointDefinition(e)),Ae(i))}_graphicToPointDefinition(e){if(!this._isValidPointGraphic(e))return null;const{nodeId:t,pointIndexInNode:i}=e.pointCloudMetadata;return null!=t&&null!=i?{nodeId:t,pointId:i}:null}_computeWork(){let e=0;for(const t of this._workQueue)e+=t.load.length+t.remove.length;return e+=this._loadingNodes.size,e+=(this._indexQueue.length+this._indexPagesLoading.size)*this._index.pageSize,e+=this._loadingInitNodePage?100:0,e+=this._updateViewNeeded?100:0,e}get updatingProgressValue(){if(this.suspended)return this._updateViewNeeded?0:1;const e=this._computeWork();return 1-Math.min(this._totalWork,e)/this._totalWork}_updateLoading(){this.notifyChange("updating"),this.notifyChange("updatingProgressValue")}canResume(){return super.canResume()&&this._layerIsVisible}isUpdating(){return this.suspended?this._updateViewNeeded:this._computeWork()>0}get visibleAtCurrentScale(){return je(this.layer.effectiveScaleRange,this.view.scale)}async queryFeatures(e,i){const r=await this._ensureQueryEngine().executeQuery(this._ensureQueryJSON(e),i?.signal),s=r.features;r.features=[];const o=T.fromJSON(r),n=this.view.spatialReference;return o.features=s.map(e=>{const{attributes:i,metadata:r}=e;if(!r){const i=t.fromJSON(e);return i.geometry&&(i.geometry.spatialReference=o.spatialReference??n),i.layer=this.layer,i.sourceLayer=this.layer,i.origin=this._graphicOrigin,i}const s=e.geometry?V.fromJSON(e.geometry):void 0;return s&&(s.spatialReference=o.spatialReference??n),this._createGraphic(r.node,r.pointId,s,i)}),o}createQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference,returnZ:!0};return new B(e)}async queryFeatureCount(e,t){return await this._ensureQueryEngine().executeQueryForCount(this._ensureQueryJSON(e),t?.signal)}async queryExtent(e,t){const{count:i,extent:r}=await this._ensureQueryEngine().executeQueryForExtent(this._ensureQueryJSON(e),t?.signal);return{count:i,extent:k.fromJSON(r)}}_ensureQueryJSON(e){return null==e?new B({outSpatialReference:this.view.spatialReference}).toJSON():B.from(e).toJSON()}_ensureQueryEngine(){if(this._queryEngine)return this._queryEngine;const{spatialReference:e}=this.view;return this._queryEngine=new W({fieldsIndex:this.layer.fieldsIndex.toJSON(),geometryType:"esriGeometryPoint",spatialReference:e,featureIdInfo:{type:"object-id",fieldName:"objectId"},hasZ:!0,featureStore:new X({sourceSpatialReference:e,viewSpatialReference:e,forAllFeatures:(e,t)=>{let i=!1;this._renderer.forEachNode(r=>{if(i)return;if(t){const e=r.obb,s=U(e.center[0],e.center[1],e.center[2],C(e.halfSize));Q(s,this.view.renderSpatialReference,s,this.view.spatialReference);const o=t(s);if(2===o)return;if(i=0===o,i)return}let s=this._queryFeaturesCache.get(`${r.id}`);s||(s=this._createQueryPointFeatures(r),this._queryFeaturesCache.put(`${r.id}`,s)),s.features.forEach(e)})},getFeatureExtent:({point:e},t)=>O(e,e,t),featureAdapter:{cloneWithGeometry:(e,t)=>new Oe(e.node,e.pointId,t.coords),getAttribute:({node:e,attributePointId:t},i)=>{for(const r of e.attributes)if(r.attributeInfo.name===i)return this._getGraphicAttribute(r.attributeInfo,r.values,t)},getAttributes:({node:e,attributePointId:t})=>this._createGraphicAttributes(e,t),getCentroid:e=>e.getGeometry(),getGeometry:e=>e.getGeometry(),getObjectId:()=>{},getMetadata:e=>e}})}),this._queryEngine}_createQueryPointFeatures(e){const t=e.coordinates,i=new Array;for(let r=0;r<t.length/3;r++){const s=3*r,o=R(t[s+0],t[s+1],t[s+2]);S(o,o,e.origin),L(o,this.view.renderSpatialReference,o,this.view.spatialReference);const n=new Oe(e,r,o);i.push(n)}return new De(i)}async _initNodePages(){const e=this.layer.store.index,t=e.nodesPerPage||e.nodePerIndexBlock;this._index=new oe(this.layer.spatialReference,this.view.renderCoordsHelper.spatialReference,t),this._cancelIndexLoading(),this._traverseVisible=this._index.createVisibilityTraverse(),this._loadingInitNodePage=!0,this._layerIsVisible=!0,this.notifyChange("suspended"),this._updateLoading(),this._pageMultiplier=null!=e.nodesPerPage?1:e.nodePerIndexBlock;const i=await this.layer.rootPagePromise;this._loadingInitNodePage=!1,i?(this._index.addPage(0,this._processJSONNodes(i,0),this._elevationOffset),this._setUpdateViewNeeded()):n.getLogger(this).error("Point cloud layer root page not loaded")}_loadNodePage(e){const t=new AbortController,i=`${this.baseUrl}/nodepages/${e*this._pageMultiplier}`;return{promise:this._requestNodePage(i,t.signal).then(t=>this._processJSONNodes(t,e)),abortController:t}}_processJSONNodes(e,t){const i=t*this._index.pageSize;return e.nodes.map((e,t)=>({resourceId:e.resourceId??i+t,obb:xe.fromJSON(e.obb),obbInRenderSR:new xe,firstChild:e.firstChild,childCount:e.childCount,vertexCount:e.vertexCount??e.pointCount,lodThreshold:e.lodThreshold??e.effectiveArea}))}_updateWorkQueues(){if(!this._updateViewNeeded)return!1;const e=this.view.quality;let t=this.inverseDensity/this._lodFactor*e;const i=this.maximumPointCount*this._lodFactor*e;let r=this._computeNodesForMinimumDensity(t),s=this._computePointCount(r),o=Math.sqrt(s/(.75*i));for(;s>i;)t*=o,r=this._computeNodesForMinimumDensity(t),s=this._computePointCount(r),o=Math.sqrt(2);return this._displayNodes(r),this._updateViewNeeded=!1,this._updateLoading(),!0}_computePointCount(e){let t=0;for(let i=0;i<e.length;i++){const r=this._index.getNode(e[i]);r&&(t+=r.vertexCount)}return t}_isRootNodeVisible(){let e=!1;return this._traverseVisible({frustum:this.view.state.contentCamera.frustum,clippingBox:this._clippingBox},{predicate:(t,i,r)=>(e=r,!1),pageMiss:()=>{}}),e}_computeNodesForMinimumDensity(e){const t=this.view.state.contentCamera,i=t.frustum,r=this._clippingBox,s=t.viewForward,o=I(s,t.eye),n=D(s,-o,Qe),a=t.perScreenPixelRatio/2,d=e*e,l=this._nodeIdArray;l.length=0;const u=e=>l.push(e);return this._traverseVisible({frustum:i,clippingBox:r},{predicate:(e,t,i)=>{if(!i)return!1;if(0===t.childCount)return u(e),!1;const r=this._index.getRenderObb(e);return!(this._computeAveragePixelArea(r,t.lodThreshold,t.vertexCount,n,a)<=d)||(u(e),!1)},pageMiss:(e,t)=>{u(e),this._indexQueue.includes(t)||this._indexQueue.push(t)}}),l}_computeAveragePixelArea(e,t,i,r,s){const o=1e-7,n=Math.max(o,e.minimumDistancePlane(r));return t/(n*n)/(4*s*s)/i}_loadNode(e,t){try{return this._loadNodeAsync(e,t)}catch(i){throw _(i)||n.getLogger(this).error(i),i}}async _loadAdditionalUserAttributes(e,t,i){const s=this.layer.outFields;if(!s)return[];const o=z(this.layer.fieldsIndex,s),n=new Set(e.map(e=>null!=e?e.name:null)),a=this.layer.attributeStorageInfo,d=[];for(const r of o){if(n.has(r))continue;const e=me(a,r);e&&d.push(t(e))}const l=await m(d);return g(i),l.filter(r)}async _loadNodeAsync(e,t){const i=this._index.getNode(e),r=pe(this.layer),s=ce(this.layer),o=i.resourceId,n=async e=>{if(!e)return null;if(e.useElevation)return{attributeInfo:e,buffer:null};const i=await this._loadAttribute(o,e,t);return null!=i?{attributeInfo:e,buffer:i}:null};return this._idleQueue.push(async()=>{const i=this._loadGeometry(o,t),{primaryAttribute:a,modulationAttribute:d}=r,l=n(a),u=n(d),h=s.map(e=>e.attributeInfo),p=h.map(e=>n(e)),c=this._loadAdditionalUserAttributes([a,d,...h],n,t),[_,m,f,y,b]=await Promise.all([i,l,u,Promise.all(p),c]);g(t);const w={geometryBuffer:_,primaryAttributeData:m,modulationAttributeData:f,filterAttributesData:y,userAttributesData:b,schema:this.layer.store.defaultGeometrySchema,rendererInfo:r,filterInfo:s,obbData:this._index.getRenderObb(e).data,elevationOffset:this._elevationOffset,inSR:this.layer.spatialReference.toJSON(),outSR:this.view.renderCoordsHelper.spatialReference.toJSON()};return this._worker.invoke(w,t)},t)}async _loadGeometry(e,t){return this._requestData(`${this.baseUrl}/nodes/${e}/geometries/0`,t)}async _loadAttribute(e,t,i){if(!t?.storageInfo)return null;const r=t.storageInfo.key;return this._requestData(`${this.baseUrl}/nodes/${e}/attributes/${r}`,i)}async _requestNodePage(e,t){const r={f:"json",...this.layer.customParameters,token:this.layer.apiKey},s={...H,query:r,responseType:"json",signal:t};return(await i(e,s)).data}async _requestData(e,t){const r={...this.layer.customParameters,token:this.layer.apiKey},s={...H,query:r,responseType:"array-buffer",signal:t};return(await i(e,s)).data}_removeFromRenderer(e){if(this._renderedNodes.has(e)){const t=this._renderer.removeNode(e);this._renderedNodes.delete(e),this._memCache.put(t.id.toString(),t)}}_addToRenderer(e){this._renderedNodes.has(e.id)||(this._renderedNodes.add(e.id),this._renderer.addNode(e))}_setupRendererData(e,t){const i=this._index.getNode(e),r=Math.sqrt(i.lodThreshold/i.vertexCount),s=this._index.getRenderObb(e);if(de(t))return t.splatSize=r,t.obb=s,A(t.origin,t.obb.center),t;const o=xe.fromData(t.obbData),a=o.halfSize,d=s.halfSize,l=.01*Math.max(d[0],d[1],d[2]);if(a[0]>d[0]+l||a[1]>d[1]+l||a[2]>d[2]+l){if(this._maxLoggedBoxWarnings>0){const t=e=>`[${e.halfSize[0]}, ${e.halfSize[1]}, ${e.halfSize[2]}]`;n.getLogger(this).warn(`Node ${e} reported bounding box too small. got ${t(s)} but points cover ${t(o)}`),0===--this._maxLoggedBoxWarnings&&n.getLogger(this).warn(" Too many bounding box errors, stopping reporting for this layer.")}this._index.setRenderObb(e,o)}return new le(e,r,j(s.center),s,0===i.childCount,t.points,t.rgb,t.attributes,t.pointIdFilterMap)}get usedMemory(){let e=0;return this._renderer.forEachNode(t=>{e+=Ee,e+=l(t.coordinates);for(const i of t.attributes){const t=i.values;N(t.buffer)&&(e+=l(t))}}),e}get unloadedMemory(){const e=this._renderedNodes.size;if(e<4)return 0;const t=[...this._renderedNodes].reduce((e,t)=>e+this._index.getNode(t).vertexCount);let i=this._loadingNodes.size;for(let r=0;r<this._workQueue.length;r++)i+=this._workQueue[r].load.length,i-=this._workQueue[r].remove.length;if(i<0)return 0;return i*t/e*((this.usedMemory-e*Ee)/t)+i*Ee}get performanceInfo(){return new K(this.usedMemory,this._renderedNodes.size,[...this._renderedNodes].reduce((e,t)=>e+this._index.getNode(t).vertexCount,0),this.maximumPointCount,new Z(this._loadingNodes.size,this._indexQueue.length,this._workQueue.length,this._idleQueue.length))}get test(){}};e([v()],Le.prototype,"layer",void 0),e([v()],Le.prototype,"baseUrl",null),e([v()],Le.prototype,"pointScale",null),e([v()],Le.prototype,"useRealWorldSymbolSizes",null),e([v()],Le.prototype,"pointSize",null),e([v()],Le.prototype,"inverseDensity",null),e([v()],Le.prototype,"maximumPointCount",void 0),e([v({readOnly:!0})],Le.prototype,"availableFields",null),e([v({readOnly:!0})],Le.prototype,"_clippingBox",null),e([v({readOnly:!0})],Le.prototype,"_elevationOffset",null),e([v({type:Boolean})],Le.prototype,"slicePlaneEnabled",void 0),e([v()],Le.prototype,"_graphicOrigin",null),e([v()],Le.prototype,"updating",void 0),e([v(Ce)],Le.prototype,"updatingProgress",void 0),e([v({readOnly:!0})],Le.prototype,"updatingProgressValue",null),e([v({readOnly:!0})],Le.prototype,"visibleAtCurrentScale",null),Le=e([x("esri.views.3d.layers.PointCloudLayerView3D")],Le);const Fe=Le;class Oe{constructor(e,t,i){this.node=e,this.pointId=t,this.point=i}getGeometry(){return new M([],Array.from(this.point),!0,!1)}get attributePointId(){const{node:e,pointId:t}=this;return null!=e.pointIdFilterMap?e.pointIdFilterMap[t]:t}get usedMemory(){return u+u+h+p(this.point,h)}}class De{constructor(e){this.features=e}get usedMemory(){return this.features.reduce((e,t)=>e+t.usedMemory,u+c)}}const Ee=160;function Ue(e){return t=>e.immediate.schedule(t)}export{Fe as default};
5
+ import{__decorate as e}from"tslib";import t from"../../../Graphic.js";import i from"../../../request.js";import{isSome as r}from"../../../core/arrayUtils.js";import{result as s,forEach as o}from"../../../core/asyncUtils.js";import"../../../core/has.js";import n from"../../../core/Logger.js";import{destroyMaybe as a,abortMaybe as d}from"../../../core/maybe.js";import{estimateNumberArrayMemory as l,baseObjectMemory as u,estimateNumberMemory as h,estimateFixedArrayMemory as p,baseArrayMemory as c}from"../../../core/memoryEstimations.js";import{isAbortError as _,allSettledValues as m,throwIfAborted as g}from"../../../core/promiseUtils.js";import{initial as f,watch as y,sync as b,syncAndInitial as w}from"../../../core/reactiveUtils.js";import{pt2px as P}from"../../../core/screenUtils.js";import{isArrayBuffer as N}from"../../../core/typedArrayUtil.js";import{property as v,subclass as x}from"../../../core/accessorSupport/decorators.js";import{b as C,g as S,f as I,d as A}from"../../../chunks/vec32.js";import{clone as j}from"../../../core/libs/gl-matrix-2/factories/vec3f32.js";import{fromValues as R}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import k from"../../../geometry/Extent.js";import V from"../../../geometry/Point.js";import{projectBoundingSphere as Q}from"../../../geometry/projection/projectBoundingSphere.js";import{projectVectorToVector as F}from"../../../geometry/projection/projectVectorToVector.js";import{create as E,fromMinMax as O}from"../../../geometry/support/aaBoundingBox.js";import{fromNormalAndOffset as D,create as L}from"../../../geometry/support/plane.js";import{f as U}from"../../../chunks/sphere.js";import W from"../../../layers/graphics/OptimizedGeometry.js";import{QueryEngine as G}from"../../../layers/graphics/data/QueryEngine.js";import{CodedValue as M}from"../../../layers/support/CodedValue.js";import q from"../../../layers/support/CodedValueDomain.js";import"../../../layers/support/Domain.js";import"../../../layers/support/InheritedDomain.js";import"../../../layers/support/RangeDomain.js";import{unpackFieldNames as z}from"../../../layers/support/fieldUtils.js";import{queueAutoPriority as H}from"../../../request/queue.js";import T from"../../../rest/support/FeatureSet.js";import B from"../../../rest/support/Query.js";import{getElevationOffset as $}from"../../../support/elevationInfoUtils.js";import{LayerView3D as J}from"./LayerView3D.js";import{PointCloudLayerViewPerformanceInfo as K,QueuePerformanceInfo as Z}from"./PointCloudLayerViewPerformanceInfo.js";import{PointCloudWorkerHandle as Y}from"./PointCloudWorkerHandle.js";import{I3SQueryFeatureStore as X}from"./i3s/I3SQueryFeatureStore.js";import{checkPointCloudLayerValid as ee,checkPointCloudLayerCompatibleWithView as te}from"./i3s/I3SUtil.js";import{nodeDiff as ie,sortFrontToBack as re,splitWorkEntries as se}from"./i3s/LoDUtil.js";import{PagedNodeIndex as oe}from"./i3s/PagedNodeIndex.js";import{PointCloudGraphic as ne}from"./i3s/PointCloudGraphic.js";import{PointCloudRenderer as ae}from"./i3s/PointCloudRenderer.js";import{isPointRendererNode as de,PointCloudRendererNode as le}from"./i3s/PointCloudRendererNode.js";import{getSplatSizeAlgorithm as ue,getFixedSizeAlgorithm as he,getRendererInfo as pe,getFilterInfo as ce,rendererUsesFixedSizes as _e,getAttributeInfo as me}from"./i3s/PointCloudRendererUtil.js";import{getAttributeValues as ge,readGeometry as fe,elevationFromPositions as ye}from"./i3s/PointCloudWorkerUtil.js";import{normalizeHighlightTarget as be,emptyHighlightHandle as we}from"./support/highlightUtils.js";import{PopupSceneLayerView as Pe}from"./support/PopupSceneLayerView.js";import{projectToBoundingBox as Ne}from"../support/extentUtils.js";import{computeMapPointFromVec3d as ve}from"../support/hitTest.js";import{Obb as xe}from"../support/orientedBoundingBox.js";import{updatingProgress as Ce}from"../support/updatingProperties.js";import Se from"../../layers/LayerView.js";import{PointCloudLayerView as Ie}from"../../layers/PointCloudLayerView.js";import{getHighlightName as Ae}from"../../support/highlightOptionsUtils.js";import{isInEffectiveScaleRange as je}from"../../support/layerViewUtils.js";import{PromiseQueue as Re}from"../../support/PromiseQueue.js";import{TaskPriority as ke}from"../../support/Scheduler.js";const Ve=8,Qe=L();let Fe=class extends(Ie(Pe(J(Se)))){constructor(){super(...arguments),this.type="point-cloud-3d",this.maximumPointCount=4e6,this.slicePlaneEnabled=!1,this._renderer=null,this._rendererAdded=!1,this._renderedNodes=new Set,this._updateViewNeeded=!0,this._lodFactor=1,this._maxLoggedBoxWarnings=5,this._pageMultiplier=1,this._nodeLoadEpoch=0,this._indexQueue=[],this._workQueue=new Array,this._idleQueue=new Re,this._loadingPages=new Map,this._loadingNodes=new Map,this._recalcWork=!0,this._layerIsVisible=!1,this._codedDomainPopulationPromise=null,this._codedDomainPopulationAbortController=null,this._totalWork=0,this._index=null,this._loadingInitNodePage=!1,this._nodeIdArray=[],this.ignoresMemoryFactor=!1}get baseUrl(){return this.layer.parsedUrl?.path??""}get pointScale(){const e=ue(this.layer?.renderer),t=1;return null!=e?.scaleFactor?e.scaleFactor:t}get useRealWorldSymbolSizes(){const e=he(this.layer?.renderer),t=!1;return null!=e?.useRealWorldSymbolSizes?e.useRealWorldSymbolSizes:t}get pointSize(){const e=he(this.layer?.renderer),t=0;return null!=e?.size?e.size:t}get inverseDensity(){const e=96;return this.layer?.renderer?1*e/this.layer.renderer.pointsPerInch:5}get availableFields(){const e=pe(this.layer),t=new Set;e.primaryAttribute&&t.add(e.primaryAttribute.name),e.modulationAttribute&&t.add(e.modulationAttribute.name);const i=ce(this.layer);if(i)for(const r of i)r.attributeInfo&&t.add(r.attributeInfo.name);if(this.layer.outFields)for(const r of z(this.layer.fieldsIndex,this.layer.outFields))t.add(r);return Array.from(t)}get _clippingBox(){if(!this.view||!this.view.clippingArea)return null;const e=E(),t=this.view.renderSpatialReference;return Ne(this.view.clippingArea,e,t)?e:null}get _elevationOffset(){const e=this.layer&&this.layer.elevationInfo;return e&&"absolute-height"===e.mode?$(e,this.layer.spatialReference):0}get _graphicOrigin(){return this.layer.graphicOrigin}initialize(){const e=this.view.resourceController,t=Ue(e);this._worker=new Y(t),this.addResolvingPromise(this._worker.promise),this.addResolvingPromise(this.layer.rootPagePromise),ee(this.layer),te(this.layer,this.view),this._initRenderer();const i=this._initNodePages(),r=this.view.resourceController.memoryController;this._memCache=r.newCache(`pcl-${this.layer.uid}`),this._queryFeaturesCache=r.newCache(`pcl-query-features-${this.layer.uid};`),this._updatingHandles.add(()=>this._clippingBox,()=>this._setUpdateViewNeeded(),f),this._updatingHandles.add(()=>this._elevationOffset,()=>this._elevationOffsetChanged(),f),this._updatingHandles.add(()=>this.layer.renderer,()=>this._rendererChanged(),f),this._updatingHandles.add(()=>this.layer.filters,()=>this._reload(),f),this._updatingHandles.add(()=>this.layer.outFields,()=>this._reload(),f),this._updatingHandles.add(()=>this.layer.effectiveScaleRange,()=>this._setUpdateViewNeeded()),this._updatingHandles.add(()=>this.view.state.contentCamera,()=>this._setUpdateViewNeeded()),this.addHandles([y(()=>this.view.quality,()=>this._setUpdateViewNeeded(),b)]),this.addResolvingPromise(i),this.when(()=>{this.addHandles([e.scheduler.registerTask(ke.POINT_CLOUD_LAYER,this),y(()=>2===this.view.state.mode,()=>this._setUpdateViewNeeded(),w),this._updatingHandles.add(()=>this.suspended,e=>{e?this._clearNodeState():this._setUpdateViewNeeded()},f)])},()=>{this._updatingHandles.removeAll(),this.removeAllHandles()})}_setUpdateViewNeeded(){this._updateViewNeeded=!0,this._updateLoading()}destroy(){this.cancelLoading(),this._worker=a(this._worker),this._destroyRenderer(),this._memCache=a(this._memCache),this._queryFeaturesCache=a(this._queryFeaturesCache),this._queryEngine=a(this._queryEngine),this._codedDomainPopulationAbortController=d(this._codedDomainPopulationAbortController),this._codedDomainPopulationPromise=null}_initRenderer(){this._renderer=new ae({createGraphic:(e,t,i)=>this._createGraphic(e,t,i)}),this._renderer.layerViewUid=this.uid,this._updatingHandles.add(()=>this._clippingBox,e=>this._renderer.clippingBox=e,f),this._updatingHandles.add(()=>this.suspended,e=>this._setPointsVisible(!e),f),this._updatingHandles.add(()=>this.pointScale,e=>this._renderer.scaleFactor=e,f),this._renderer.minSizePx=Math.sqrt(2),this._updatingHandles.add(()=>this.useRealWorldSymbolSizes,e=>this._renderer.useRealWorldSymbolSizes=e,f),this._updatingHandles.add(()=>this.pointSize,e=>{const t=P(e);this._renderer.size=e,this._renderer.sizePx=t},f),this._updatingHandles.add(()=>this.slicePlaneEnabled,e=>this._renderer.slicePlaneEnabled=e,f),this._updatingHandles.add(()=>this.inverseDensity,()=>this._setUpdateViewNeeded(),f),this._updatingHandles.add(()=>this.maximumPointCount,()=>this._setUpdateViewNeeded(),f),this._updatingHandles.add(()=>this.view.qualitySettings.sceneService.pointCloudLoDFactor,e=>{this._lodFactor=e,this._setUpdateViewNeeded()},f)}_destroyRenderer(){this._renderer.removeAll(),this._setPointsVisible(!1)}_createGraphic(e,t,i,r){const s=null!=e.pointIdFilterMap?e.pointIdFilterMap[t]:t,o=i?"declaredClass"in i?i:ve(this.view,i):null;return r??=this._createGraphicAttributes(e,s),new ne({pointCloudMetadata:{nodeId:e.id,pointIndexInNode:t,attributePointIndexInNode:s,epoch:this._nodeLoadEpoch},geometry:o,attributes:r,layer:this.layer,sourceLayer:this.layer,origin:this._graphicOrigin})}_createGraphicAttributes(e,t){const i={};for(const r of e.attributes)this._encodeGraphicAttribute(r.attributeInfo,r.values,t,i);return i}_getGraphicAttribute(e,t,i){const r=e.storageInfo?.attributeValues,s=r?.valuesPerElement??1;if(1===s)return t[i];if("UInt8"===r?.valueType&&s<=4){let e=0;const r=i*s;for(let i=r;i<r+s;i++)e=(e<<8)+t[i];return e}}_encodeGraphicAttribute(e,t,i,r){r[e.name]=this._getGraphicAttribute(e,t,i)}_setPointsVisible(e){e&&!this._rendererAdded?(this.view.stage.addRenderPlugin(this._renderer),this._rendererAdded=!0):!e&&this._rendererAdded&&(this.view.stage.removeRenderPlugin(this._renderer),this._rendererAdded=!1)}_rendererChanged(){this._renderer.useFixedSizes=_e(this.layer.renderer),this._reload()}_reload(){this._clearNodeState(),this._memCache.clear(),this._setUpdateViewNeeded()}_elevationOffsetChanged(){this._clearNodeState(),this._memCache.clear(),this._initNodePages()}_displayNodes(e){this._workQueue=ie([...this._renderedNodes],e,this._index),re(this._workQueue,this.view.state.contentCamera.viewForward,this._index),se(this._workQueue,Ve,this._index),this._updateQueues(),this._totalWork=this._computeWork(),this._updateLoading(),this._layerIsVisible=e.length>0||this._loadingInitNodePage,this.notifyChange("suspended")}cancelLoading(){this._cancelNodeLoading(),this._cancelIndexLoading()}_cancelNodeLoading(){[...this._loadingNodes.values()].forEach(e=>e.abort()),this._workQueue=[],this._idleQueue.cancelAll(),this._totalWork=this._computeWork(),this._updateLoading()}_updateQueues(){const e=new Set;this._workQueue.forEach(t=>t.load.forEach(t=>e.add(t)));const t=new Array;this._loadingNodes.forEach((i,r)=>{e.has(r)||(this._loadingNodes.delete(r),t.push(i))}),t.forEach(e=>e.abort()),this._workQueue=this._workQueue.filter(e=>{for(const t of e.load)if(this._loadingNodes.has(t))return this._recalcWork=!0,!1;return!0}),this._totalWork=this._computeWork(),this._updateLoading()}_cancelIndexLoading(){this._indexQueue=[],this._loadingPages.forEach(e=>e.abort()),this._loadingPages.clear(),this._totalWork=this._computeWork(),this._updateLoading()}_clearNodeState(){this._nodeLoadEpoch++,this._renderedNodes.forEach(e=>this._removeFromRenderer(e)),this._cancelNodeLoading()}get readyToRun(){return this.suspended?this._updateViewNeeded:this._updateViewNeeded||this._indexQueue.length>0||this._workQueue.length>0||this._idleQueue.readyToRun}runTask(e){if(this.suspended){if(this._updateViewNeeded){this._updateViewNeeded=!1;const e=this._isRootNodeVisible();e!==this._layerIsVisible&&(this._layerIsVisible=e,this.notifyChange("suspended")),this._updateLoading()}}else{for(e.run(()=>this._updateWorkQueues());this._indexQueue.length>0&&!e.done;)this._processIndexQueue(),e.madeProgress();this._processWorkQueue(e),this._idleQueue.runTask(e)}}async _processIndexQueue(){const e=this._indexQueue.shift(),t=new AbortController;this._loadingPages.set(e,t);try{const i=await this._loadNodePage(e,t.signal);this._index.addPage(e,i,this._elevationOffset),this._setUpdateViewNeeded(),this._loadingPages.delete(e)}catch(i){this._loadingPages.get(e)===t&&this._loadingPages.delete(e)}}_processWorkQueue(e){for(;!e.done;){const t=this._scheduleWorkEntry();if(null==t)return void e.madeProgress();this._processWorkEntry(t),e.madeProgress()}}_scheduleWorkEntry(){let e=this._workQueue.length;for(;e--;){const e=this._workQueue.shift();if(!e.remove.find(e=>!this._renderedNodes.has(e)))return e;this._workQueue.push(e)}return null}async _processWorkEntry(e){if(0===e.load.length){for(const t of e.remove)this._removeFromRenderer(t);return}const t=e.load.map(e=>{const t=new AbortController;return this._loadingNodes.set(e,t),t});this._updateLoading();try{const i=await Promise.all(e.load.map((e,i)=>this._memCache.pop(`${e}`)??this._loadNode(e,t[i].signal)));for(let t=0;t<e.load.length;t++)if(i[t]){const r=this._setupRendererData(e.load[t],i[t]);this._addToRenderer(r)}for(const t of e.remove)this._removeFromRenderer(t);for(const t of e.load)this._loadingNodes.delete(t)}catch(i){e.load.forEach((e,i)=>{this._loadingNodes.get(e)===t[i]&&this._loadingNodes.delete(e)})}this._updateLoading(),this._recalcWork&&!this._idleQueue.updating&&0===this._indexQueue.length&&0===this._loadingNodes.size&&(this._recalcWork=!1,this._setUpdateViewNeeded())}async _populateClassCodeCodedDomain(e,t){const i="CLASS_CODE",r=this.layer.fieldsIndex.get(i);if(!r||r.domain)return;if(!e.includes(r.name))return;const o=await s(this.layer.queryCachedStatistics(i,{signal:t}));if(!1===o.ok)return;const n=o.value?.stats?.labels?.labels;n&&Array.isArray(n)&&(r.domain=new q({name:"CLASS_CODE",codedValues:n.map(e=>new M({code:e.value,name:e.label}))}))}async prepareFetchPopupFeatures(e){return this._codedDomainPopulationPromise||(this._codedDomainPopulationAbortController=new AbortController,this._codedDomainPopulationPromise=this._populateClassCodeCodedDomain(e,this._codedDomainPopulationAbortController.signal).then(()=>{this._codedDomainPopulationAbortController=null})),this._codedDomainPopulationPromise}async whenGraphicAttributes(e,t){const i=this._splitGraphicsPerNode(e),s=this.layer.attributeStorageInfo,n=t.map(e=>me(s,e)).filter(r),a=async(e,t)=>{const i=this._index.getNode(t);await o(n,async t=>{const r=t.useElevation?await this._loadElevationAttributeFromGeometry(i.resourceId):await this._loadAndParseAttribute(i,t);if(r)for(const i of e)if(this._isValidPointGraphic(i)){const e=i.pointCloudMetadata.attributePointIndexInNode;this._encodeGraphicAttribute(t,r,e,i.attributes)}})},d=[];return i.forEach((e,t)=>{d.push(a(e,t))}),await Promise.allSettled(d),e}_isValidPointGraphic(e){return e instanceof ne&&e.pointCloudMetadata?.epoch===this._nodeLoadEpoch}_splitGraphicsPerNode(e){const t=new Map;for(const i of e){if(!this._isValidPointGraphic(i))continue;const e=i.pointCloudMetadata,r=t.get(e.nodeId);r?r.push(i):t.set(e.nodeId,[i])}return t}async _loadAndParseAttribute(e,t){const i=await this._loadAttribute(e.resourceId,t,null);return i?ge({attributeInfo:t,buffer:i},null,e.vertexCount):null}async _loadElevationAttributeFromGeometry(e){const t=this.layer.store.defaultGeometrySchema,i=fe(t,await this._loadGeometry(e,null));return ye(i,i.length/3)}highlight(e,i){const r=be(e);if(0===r.length)return we;if(!(r[0]instanceof t))return we;const s=r;return this._renderer.highlight(s.map(e=>this._graphicToPointDefinition(e)),Ae(i))}_graphicToPointDefinition(e){if(!this._isValidPointGraphic(e))return null;const{nodeId:t,pointIndexInNode:i}=e.pointCloudMetadata;return null!=t&&null!=i?{nodeId:t,pointId:i}:null}_computeWork(){let e=0;for(const t of this._workQueue)e+=t.load.length+t.remove.length;return e+=this._loadingNodes.size,e+=(this._indexQueue.length+this._loadingPages.size)*this._index.pageSize,e+=this._loadingInitNodePage?100:0,e+=this._updateViewNeeded?100:0,e}get updatingProgressValue(){if(this.suspended)return this._updateViewNeeded?0:1;const e=this._computeWork();return 1-Math.min(this._totalWork,e)/this._totalWork}_updateLoading(){this.notifyChange("updating"),this.notifyChange("updatingProgressValue")}canResume(){return super.canResume()&&this._layerIsVisible}isUpdating(){return this.suspended?this._updateViewNeeded:this._computeWork()>0}get visibleAtCurrentScale(){return je(this.layer.effectiveScaleRange,this.view.scale)}async queryFeatures(e,i){const r=await this._ensureQueryEngine().executeQuery(this._ensureQueryJSON(e),i?.signal),s=r.features;r.features=[];const o=T.fromJSON(r),n=this.view.spatialReference;return o.features=s.map(e=>{const{attributes:i,metadata:r}=e;if(!r){const i=t.fromJSON(e);return i.geometry&&(i.geometry.spatialReference=o.spatialReference??n),i.layer=this.layer,i.sourceLayer=this.layer,i.origin=this._graphicOrigin,i}const s=e.geometry?V.fromJSON(e.geometry):void 0;return s&&(s.spatialReference=o.spatialReference??n),this._createGraphic(r.node,r.pointId,s,i)}),o}createQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference,returnZ:!0};return new B(e)}async queryFeatureCount(e,t){return await this._ensureQueryEngine().executeQueryForCount(this._ensureQueryJSON(e),t?.signal)}async queryExtent(e,t){const{count:i,extent:r}=await this._ensureQueryEngine().executeQueryForExtent(this._ensureQueryJSON(e),t?.signal);return{count:i,extent:k.fromJSON(r)}}_ensureQueryJSON(e){return null==e?new B({outSpatialReference:this.view.spatialReference}).toJSON():B.from(e).toJSON()}_ensureQueryEngine(){if(this._queryEngine)return this._queryEngine;const{spatialReference:e}=this.view;return this._queryEngine=new G({fieldsIndex:this.layer.fieldsIndex.toJSON(),geometryType:"esriGeometryPoint",spatialReference:e,featureIdInfo:{type:"object-id",fieldName:"objectId"},hasZ:!0,featureStore:new X({sourceSpatialReference:e,viewSpatialReference:e,forAllFeatures:(e,t)=>{let i=!1;this._renderer.forEachNode(r=>{if(i)return;if(t){const e=r.obb,s=U(e.center[0],e.center[1],e.center[2],C(e.halfSize));Q(s,this.view.renderSpatialReference,s,this.view.spatialReference);const o=t(s);if(2===o)return;if(i=0===o,i)return}let s=this._queryFeaturesCache.get(`${r.id}`);s||(s=this._createQueryPointFeatures(r),this._queryFeaturesCache.put(`${r.id}`,s)),s.features.forEach(e)})},getFeatureExtent:({point:e},t)=>O(e,e,t),featureAdapter:{cloneWithGeometry:(e,t)=>new Oe(e.node,e.pointId,t.coords),getAttribute:({node:e,attributePointId:t},i)=>{for(const r of e.attributes)if(r.attributeInfo.name===i)return this._getGraphicAttribute(r.attributeInfo,r.values,t)},getAttributes:({node:e,attributePointId:t})=>this._createGraphicAttributes(e,t),getCentroid:e=>e.getGeometry(),getGeometry:e=>e.getGeometry(),getObjectId:()=>{},getMetadata:e=>e}})}),this._queryEngine}_createQueryPointFeatures(e){const t=e.coordinates,i=new Array;for(let r=0;r<t.length/3;r++){const s=3*r,o=R(t[s+0],t[s+1],t[s+2]);S(o,o,e.origin),F(o,this.view.renderSpatialReference,o,this.view.spatialReference);const n=new Oe(e,r,o);i.push(n)}return new De(i)}async _initNodePages(){const e=this.layer.store.index,t=e.nodesPerPage||e.nodePerIndexBlock;this._index=new oe(this.layer.spatialReference,this.view.renderCoordsHelper.spatialReference,t),this._cancelIndexLoading(),this._traverseVisible=this._index.createVisibilityTraverse(),this._loadingInitNodePage=!0,this._layerIsVisible=!0,this.notifyChange("suspended"),this._updateLoading(),this._pageMultiplier=null!=e.nodesPerPage?1:e.nodePerIndexBlock;const i=await this.layer.rootPagePromise;this._loadingInitNodePage=!1,i?(this._index.addPage(0,this._processJSONNodes(i,0),this._elevationOffset),this._setUpdateViewNeeded()):n.getLogger(this).error("Point cloud layer root page not loaded")}_loadNodePage(e,t){const i=`${this.baseUrl}/nodepages/${e*this._pageMultiplier}`;return this._requestNodePage(i,t).then(t=>this._processJSONNodes(t,e))}_processJSONNodes(e,t){const i=t*this._index.pageSize;return e.nodes.map((e,t)=>({resourceId:e.resourceId??i+t,obb:xe.fromJSON(e.obb),obbInRenderSR:new xe,firstChild:e.firstChild,childCount:e.childCount,vertexCount:e.vertexCount??e.pointCount,lodThreshold:e.lodThreshold??e.effectiveArea}))}_updateWorkQueues(){if(!this._updateViewNeeded)return!1;const e=this.view.quality;let t=this.inverseDensity/this._lodFactor*e;const i=this.maximumPointCount*this._lodFactor*e;let r=this._computeNodesForMinimumDensity(t),s=this._computePointCount(r),o=Math.sqrt(s/(.75*i));for(;s>i;)t*=o,r=this._computeNodesForMinimumDensity(t),s=this._computePointCount(r),o=Math.sqrt(2);return this._displayNodes(r),this._updateViewNeeded=!1,this._updateLoading(),!0}_computePointCount(e){let t=0;for(let i=0;i<e.length;i++){const r=this._index.getNode(e[i]);r&&(t+=r.vertexCount)}return t}_isRootNodeVisible(){let e=!1;return this._traverseVisible({frustum:this.view.state.contentCamera.frustum,clippingBox:this._clippingBox},{predicate:(t,i,r)=>(e=r,!1),pageMiss:()=>{}}),e}_computeNodesForMinimumDensity(e){const t=this.view.state.contentCamera,i=t.frustum,r=this._clippingBox,s=t.viewForward,o=I(s,t.eye),n=D(s,-o,Qe),a=t.perScreenPixelRatio/2,d=e*e,l=this._nodeIdArray;l.length=0;const u=e=>l.push(e);return this._traverseVisible({frustum:i,clippingBox:r},{predicate:(e,t,i)=>{if(!i)return!1;if(0===t.childCount)return u(e),!1;const r=this._index.getRenderObb(e);return!(this._computeAveragePixelArea(r,t.lodThreshold,t.vertexCount,n,a)<=d)||(u(e),!1)},pageMiss:(e,t)=>{u(e),this._indexQueue.includes(t)||this._indexQueue.push(t)}}),l}_computeAveragePixelArea(e,t,i,r,s){const o=1e-7,n=Math.max(o,e.minimumDistancePlane(r));return t/(n*n)/(4*s*s)/i}_loadNode(e,t){try{return this._loadNodeAsync(e,t)}catch(i){throw _(i)||n.getLogger(this).error(i),i}}async _loadAdditionalUserAttributes(e,t,i){const s=this.layer.outFields;if(!s)return[];const o=z(this.layer.fieldsIndex,s),n=new Set(e.map(e=>null!=e?e.name:null)),a=this.layer.attributeStorageInfo,d=[];for(const r of o){if(n.has(r))continue;const e=me(a,r);e&&d.push(t(e))}const l=await m(d);return g(i),l.filter(r)}async _loadNodeAsync(e,t){const i=this._index.getNode(e),r=pe(this.layer),s=ce(this.layer),o=i.resourceId,n=async e=>{if(!e)return null;if(e.useElevation)return{attributeInfo:e,buffer:null};const i=await this._loadAttribute(o,e,t);return null!=i?{attributeInfo:e,buffer:i}:null};return this._idleQueue.push(async()=>{const i=this._loadGeometry(o,t),{primaryAttribute:a,modulationAttribute:d}=r,l=n(a),u=n(d),h=s.map(e=>e.attributeInfo),p=h.map(e=>n(e)),c=this._loadAdditionalUserAttributes([a,d,...h],n,t),[_,m,f,y,b]=await Promise.all([i,l,u,Promise.all(p),c]);g(t);const w={geometryBuffer:_,primaryAttributeData:m,modulationAttributeData:f,filterAttributesData:y,userAttributesData:b,schema:this.layer.store.defaultGeometrySchema,rendererInfo:r,filterInfo:s,obbData:this._index.getRenderObb(e).data,elevationOffset:this._elevationOffset,inSR:this.layer.spatialReference.toJSON(),outSR:this.view.renderCoordsHelper.spatialReference.toJSON()};return this._worker.invoke(w,t)},t)}async _loadGeometry(e,t){return this._requestData(`${this.baseUrl}/nodes/${e}/geometries/0`,t)}async _loadAttribute(e,t,i){if(!t?.storageInfo)return null;const r=t.storageInfo.key;return this._requestData(`${this.baseUrl}/nodes/${e}/attributes/${r}`,i)}async _requestNodePage(e,t){const r={f:"json",...this.layer.customParameters,token:this.layer.apiKey},s={...H,query:r,responseType:"json",signal:t};return(await i(e,s)).data}async _requestData(e,t){const r={...this.layer.customParameters,token:this.layer.apiKey},s={...H,query:r,responseType:"array-buffer",signal:t};return(await i(e,s)).data}_removeFromRenderer(e){if(this._renderedNodes.has(e)){const t=this._renderer.removeNode(e);this._renderedNodes.delete(e),this._memCache.put(`${t.id}`,t)}}_addToRenderer(e){this._renderedNodes.has(e.id)||(this._renderedNodes.add(e.id),this._renderer.addNode(e))}_setupRendererData(e,t){const i=this._index.getNode(e),r=Math.sqrt(i.lodThreshold/i.vertexCount),s=this._index.getRenderObb(e);if(de(t))return t.splatSize=r,t.obb=s,A(t.origin,t.obb.center),t;const o=xe.fromData(t.obbData),a=o.halfSize,d=s.halfSize,l=.01*Math.max(d[0],d[1],d[2]);if(a[0]>d[0]+l||a[1]>d[1]+l||a[2]>d[2]+l){if(this._maxLoggedBoxWarnings>0){const t=e=>`[${e.halfSize[0]}, ${e.halfSize[1]}, ${e.halfSize[2]}]`;n.getLogger(this).warn(`Node ${e} reported bounding box too small. got ${t(s)} but points cover ${t(o)}`),0===--this._maxLoggedBoxWarnings&&n.getLogger(this).warn(" Too many bounding box errors, stopping reporting for this layer.")}this._index.setRenderObb(e,o)}return new le(e,r,j(s.center),s,0===i.childCount,t.points,t.rgb,t.attributes,t.pointIdFilterMap)}get usedMemory(){let e=0;return this._renderer.forEachNode(t=>{e+=Le,e+=l(t.coordinates);for(const i of t.attributes){const t=i.values;N(t.buffer)&&(e+=l(t))}}),e}get unloadedMemory(){const e=this._renderedNodes.size;if(e<4)return 0;const t=[...this._renderedNodes].reduce((e,t)=>e+this._index.getNode(t).vertexCount);let i=this._loadingNodes.size;for(let r=0;r<this._workQueue.length;r++)i+=this._workQueue[r].load.length,i-=this._workQueue[r].remove.length;if(i<0)return 0;return i*t/e*((this.usedMemory-e*Le)/t)+i*Le}get performanceInfo(){return new K(this.usedMemory,this._renderedNodes.size,[...this._renderedNodes].reduce((e,t)=>e+this._index.getNode(t).vertexCount,0),this.maximumPointCount,new Z(this._loadingNodes.size,this._indexQueue.length,this._workQueue.length,this._idleQueue.length))}get test(){}};e([v()],Fe.prototype,"layer",void 0),e([v()],Fe.prototype,"baseUrl",null),e([v()],Fe.prototype,"pointScale",null),e([v()],Fe.prototype,"useRealWorldSymbolSizes",null),e([v()],Fe.prototype,"pointSize",null),e([v()],Fe.prototype,"inverseDensity",null),e([v()],Fe.prototype,"maximumPointCount",void 0),e([v({readOnly:!0})],Fe.prototype,"availableFields",null),e([v({readOnly:!0})],Fe.prototype,"_clippingBox",null),e([v({readOnly:!0})],Fe.prototype,"_elevationOffset",null),e([v({type:Boolean})],Fe.prototype,"slicePlaneEnabled",void 0),e([v()],Fe.prototype,"_graphicOrigin",null),e([v()],Fe.prototype,"updating",void 0),e([v(Ce)],Fe.prototype,"updatingProgress",void 0),e([v({readOnly:!0})],Fe.prototype,"updatingProgressValue",null),e([v({readOnly:!0})],Fe.prototype,"visibleAtCurrentScale",null),Fe=e([x("esri.views.3d.layers.PointCloudLayerView3D")],Fe);const Ee=Fe;class Oe{constructor(e,t,i){this.node=e,this.pointId=t,this.point=i}getGeometry(){return new W([],Array.from(this.point),!0,!1)}get attributePointId(){const{node:e,pointId:t}=this;return null!=e.pointIdFilterMap?e.pointIdFilterMap[t]:t}get usedMemory(){return u+u+h+p(this.point,h)}}class De{constructor(e){this.features=e}get usedMemory(){return this.features.reduce((e,t)=>e+t.usedMemory,u+c)}}const Le=160;function Ue(e){return t=>e.immediate.schedule(t)}export{Ee 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"../WebLinkChart.js";import i from"../core/Collection.js";import r from"../core/Error.js";import{watch as a}from"../core/reactiveUtils.js";import{property as s,subclass as o}from"../core/accessorSupport/decorators.js";import{project as n}from"../geometry/projectionUtils.js";import p from"../geometry/SpatialReference.js";import{MeasuredGrid as h}from"../grids/MeasuredGrid.js";import{startNodeMovement as c}from"../layers/knowledgeGraph/nodeMovementUtils.js";import d from"./View2D.js";import g from"./interactive/snapping/FeatureSnappingLayerSource.js";import{SnappingManager as m}from"./interactive/snapping/SnappingManager.js";import l from"./interactive/snapping/SnappingOptions.js";let u=class extends d{constructor(e){super(e),this.map=null,this.view2dType="linkchart",this._isReshapeActive=!1,this._previousGridSettings=void 0,this._cachedSnappingManager=void 0;const t=e=>{this.spatialReference="geographic-organic-standard"===e?this.map.basemap?.spatialReference??p.WebMercator:p.WGS84};let i=null;this.addHandles(a(()=>this.map,e=>{e&&(i&&i.remove(),i=a(()=>e.linkChartProperties.layoutType,t),this.addHandles(i))},{initial:!0}))}get inGeographicLayout(){return"geographic-organic-standard"===this.map?.linkChartProperties.layoutType}async startNodeMovement(e,t,a){if(this._isReshapeActive)throw new r("LinkChartView:reshape-already-active","Node movement reshape is already active");this._isReshapeActive=!0;const s=new i;for(const i of this.map?.activeLinkChartLayer?.layers??[])if("relationship"===i.graphType){const e=new g({layer:i});s.add(e)}try{let i;a?.useSnappingGrid&&(this._previousGridSettings=this.grid,this.grid||(this.grid=new h({units:"feet",center:this.center,rotateWithMap:!0})),this._cachedSnappingManager?(i=this._cachedSnappingManager,i.options.gridEnabled=a?.useSnappingGrid):(i=new m({options:new l({enabled:!0,featureSources:s,gridEnabled:a?.useSnappingGrid}),view:this}),this._cachedSnappingManager=i));const o=await c({targetEntityId:e,targetEntityType:t,view:this,snappingManager:i});return{commitNodeMovement:async()=>{if(!this._isReshapeActive)throw new r("LinkChartView:reshape-not-active","Node movement reshape is not active");this._isReshapeActive=!1;const t=o.currentReshapeGraphic.sourceLayer?.parent,i=t.getCurrentNodeLocations(),a=n(o.currentReshapeGraphic.geometry,{wkid:4326});return i.set(e,a),await t.applyNewLinkChartLayout(this.map.activeLinkChartLayer?.getCurrentLayout(),{lockedNodeLocations:i}),o.teardownHandle.remove(),this.grid=this._previousGridSettings,a},cancelNodeMovement:()=>{if(!this._isReshapeActive)return;this._isReshapeActive=!1;const e=[];for(const t of o.localEdits.values())t.graphic.geometry=void 0,"knowledge-graph-sublayer"===t.graphic.sourceLayer?.type&&"relationship"===t.graphic.sourceLayer?.graphType&&(t.graphic.sourceLayer.parent.relationshipLinkChartDiagramLookup.set(t.graphic.attributes.ESRI__ID,o.originalRelationshipGeometries.get(t.graphic.attributes.ESRI__ID)??null),e.push(t.graphic.sourceLayer));for(const t of e)t.refreshCachedQueryEngine().then(()=>{t?.emit("refresh",{dataChanged:!0})});o.teardownHandle.remove(),this.grid=this._previousGridSettings}}}catch(o){throw this._isReshapeActive=!1,o}}};e([s()],u.prototype,"inGeographicLayout",null),e([s({type:t})],u.prototype,"map",void 0),e([s({readOnly:!0})],u.prototype,"view2dType",void 0),u=e([o("esri.views.LinkChartView")],u);const y=u;export{y as default};
5
+ import{__decorate as e}from"tslib";import t from"../WebLinkChart.js";import r from"../core/Collection.js";import i from"../core/Error.js";import{watch as a}from"../core/reactiveUtils.js";import{property as o,subclass as s}from"../core/accessorSupport/decorators.js";import{project as n}from"../geometry/projectionUtils.js";import p from"../geometry/SpatialReference.js";import{MeasuredGrid as c}from"../grids/MeasuredGrid.js";import{startNodeMovement as h}from"../layers/knowledgeGraph/nodeMovementUtils.js";import d from"./View2D.js";import g from"./interactive/snapping/FeatureSnappingLayerSource.js";import{SnappingManager as l}from"./interactive/snapping/SnappingManager.js";import m from"./interactive/snapping/SnappingOptions.js";import u from"../webmap/background/ColorBackground.js";let y=class extends d{constructor(e){super(e),this.map=null,this.view2dType="linkchart",this._isReshapeActive=!1,this._previousGridSettings=void 0,this._cachedSnappingManager=void 0;const t=e=>{this.spatialReference="geographic-organic-standard"===e?this.map.basemap?.spatialReference??p.WebMercator:p.WGS84};let r=null;this.addHandles(a(()=>this.map,e=>{e&&(r&&r.remove(),r=a(()=>e.linkChartProperties.layoutType,t),this.addHandles(r))},{initial:!0}))}get background(){return this.map?.initialViewProperties.background??new u({color:[255,255,255,1]})}set background(e){this._override("background",e)}get inGeographicLayout(){return"geographic-organic-standard"===this.map?.linkChartProperties.layoutType}async startNodeMovement(e,t,a){if(this._isReshapeActive)throw new i("LinkChartView:reshape-already-active","Node movement reshape is already active");this._isReshapeActive=!0;const o=new r;for(const r of this.map?.activeLinkChartLayer?.layers??[])if("relationship"===r.graphType){const e=new g({layer:r});o.add(e)}try{let r;a?.useSnappingGrid&&(this._previousGridSettings=this.grid,this.grid||(this.grid=new c({units:"feet",center:this.center,rotateWithMap:!0})),this._cachedSnappingManager?(r=this._cachedSnappingManager,r.options.gridEnabled=a?.useSnappingGrid):(r=new l({options:new m({enabled:!0,featureSources:o,gridEnabled:a?.useSnappingGrid}),view:this}),this._cachedSnappingManager=r));const s=await h({targetEntityId:e,targetEntityType:t,view:this,snappingManager:r});return{commitNodeMovement:async()=>{if(!this._isReshapeActive)throw new i("LinkChartView:reshape-not-active","Node movement reshape is not active");this._isReshapeActive=!1;const t=s.currentReshapeGraphic.sourceLayer?.parent,r=t.getCurrentNodeLocations(),a=n(s.currentReshapeGraphic.geometry,{wkid:4326});return r.set(e,a),await t.applyNewLinkChartLayout(this.map.activeLinkChartLayer?.getCurrentLayout(),{lockedNodeLocations:r}),s.teardownHandle.remove(),this.grid=this._previousGridSettings,a},cancelNodeMovement:()=>{if(!this._isReshapeActive)return;this._isReshapeActive=!1;const e=[];for(const t of s.localEdits.values())t.graphic.geometry=void 0,"knowledge-graph-sublayer"===t.graphic.sourceLayer?.type&&"relationship"===t.graphic.sourceLayer?.graphType&&(t.graphic.sourceLayer.parent.relationshipLinkChartDiagramLookup.set(t.graphic.attributes.ESRI__ID,s.originalRelationshipGeometries.get(t.graphic.attributes.ESRI__ID)??null),e.push(t.graphic.sourceLayer));for(const t of e)t.refreshCachedQueryEngine().then(()=>{t?.emit("refresh",{dataChanged:!0})});s.teardownHandle.remove(),this.grid=this._previousGridSettings}}}catch(s){throw this._isReshapeActive=!1,s}}};e([o({type:u})],y.prototype,"background",null),e([o()],y.prototype,"inGeographicLayout",null),e([o({type:t})],y.prototype,"map",void 0),e([o({readOnly:!0})],y.prototype,"view2dType",void 0),y=e([s("esri.views.LinkChartView")],y);const v=y;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{__decorate as t}from"tslib";import e from"../../../Graphic.js";import{createTask as i}from"../../../core/asyncUtils.js";import s from"../../../core/Collection.js";import o from"../../../core/Error.js";import{EventedAccessor as r}from"../../../core/Evented.js";import n from"../../../core/Logger.js";import{getOrCreateMapValue as a}from"../../../core/MapUtils.js";import{destroyMaybe as h,assertIsSome as p,abortMaybe as c}from"../../../core/maybe.js";import{pausable as l,when as d,watch as m,initial as v,sync as u}from"../../../core/reactiveUtils.js";import{property as y,subclass as _}from"../../../core/accessorSupport/decorators.js";import g from"../../../geometry/Point.js";import f from"../../../geometry/Polyline.js";import{fromGeometry as G,toGeometry as x}from"../../../geometry/operators/support/apiConverter.js";import{closeRingsAndFixWinding as M,geometryToCoordinates as b}from"../../../geometry/support/coordsUtils.js";import{isPoint as C}from"../../../geometry/support/typeUtils.js";import{interpolateCircle as S}from"../../../geometry/support/curves/circleUtils.js";import{deriveCircleFromCircularArc as E,toEllipticArc7 as w}from"../../../geometry/support/curves/circularArcUtils.js";import{getEndpoint as O,isCircularArc as V,isEllipticArc4 as I,isBezierCurve as P,isCoordinate as k,isEllipticArc7 as H}from"../../../geometry/support/curves/curveUtils.js";import{deriveCircleFromEllipticArc4 as R}from"../../../geometry/support/curves/ellipticArc4Utils.js";import{wrapAtan2 as T}from"../../../geometry/support/curves/mathUtils.js";import A from"../../../layers/GraphicsLayer.js";import{SnappingVisualizer2D as L}from"../../2d/interactive/SnappingVisualizer2D.js";import{ConnectedReshapeManager as j}from"./ConnectedReshapeManager.js";import{screenDeltaToMapDelta as U,cloneMove as F}from"./drawUtils.js";import D from"./GraphicMover.js";import z from"./HighlightHelper.js";import{addUniqueLayer as K,isConnectedReshapeSupportedLayer as N}from"./layerUtils.js";import{createTooltipInfos as q,connectTooltip as Z,updateTranslateTooltipInfo as $,updateTranslateVertexTooltipInfo as B}from"./reshapeTooltipUtils.js";import{defaultSymbols as J,createMidpointGraphics as Q,createVertexGraphics as W,createCurveControlPointGraphics as X,createCurveConstructionLineGraphics as Y,attributeKeys as tt,getMidpoint as et,controlPointKinds as it,saveUpdatedCurveOrCoordinate as st,toolIdAttribute as ot,splitCurve as rt,isSingleSegmentCircle as nt,isSingleSegmentEllipse as at}from"./reshapeUtils.js";import{ViewEventPriorities as ht}from"../../input/InputManager.js";import{createCoordinateHelper as pt}from"../../interactive/coordinateHelper.js";import{sketchKeys as ct}from"../../interactive/keybindings.js";import{EditGeometryOperations as lt}from"../../interactive/editGeometry/EditGeometryOperations.js";import dt from"../../interactive/sketch/SketchOptions.js";import{SnappingContext as mt}from"../../interactive/snapping/SnappingContext.js";import{makeTooltip as vt,enterInputModeIfAvailable as ut}from"../../interactive/tooltip/tooltipCommonUtils.js";const yt=Symbol();let _t=class extends r{constructor(t){super(t),this._updateHandlesOnExternalGeometryChange=null,this._activeOperationInfo=null,this._connectedReshapeManager=null,this._editGeometryOperations=null,this._mover=null,this._snappingContext=null,this._snappingGraphicsLayer=null,this._hoverGraphic=null,this._snappingTask=null,this._stagedVertex=null,this.tooltip=null,this.activeTooltipInfo=null,this.callbacks={onReshapeStart(){},onReshape(){},onReshapeStop(){},onMoveStart(){},onMove(){},onMoveStop(){},onGraphicClick(){}},this.connectedReshapeProviders=null,this.enableMidpoints=!0,this.enableCurveOnMidpoint=!1,this.enableMovement=!0,this.enableVertices=!0,this.graphic=null,this.highlightName=null,this.highlightsEnabled=!0,this.layer=null,this.snappingManager=null,this.symbols=J,this.sketchOptions=new dt,this.type="reshape",this.vertexGraphics=new s,this.curveControlPointGraphics=new s,this.constructionLineGraphics=new s,this.midpointGraphics=new s,this.selectedManipulators=new s,this.view=null}initialize(){const t=this.view;this._highlightHelper=new z({view:t}),this._setup(),this._updateHandlesOnExternalGeometryChange=l(()=>this.graphic?.geometry,t=>{if(!t)return;const e=new Set(this.selectedManipulators.map(wt));this._highlightHelper.removeAll(),this._setUpHighlights(),this._setupGraphics(),this._clearSelection(),this.vertexGraphics.filter(t=>e.has(wt(t))).forEach(t=>this._addToSelection(t));const{enableMovement:i,_mover:s,graphic:o,midpointGraphics:r,vertexGraphics:n,curveControlPointGraphics:a}=this,h=n.concat(r,a).items;i&&h.push(o),s?.set("graphics",h)},u),this.tooltip=vt(()=>({view:t,options:this.sketchOptions.tooltips})),this.tooltipInfos=q(this.sketchOptions),this.addHandles([d(()=>t?.ready,()=>{const{layer:t,view:e}=this;K(e,t),this.addHandles(e.on("key-down",t=>this._keyDownHandler(t),ht.TOOL))},{once:!0,initial:!0}),m(()=>this.graphic,()=>this.refresh()),m(()=>this.layer,(t,e)=>{e&&(this._clearSelection(),this._resetGraphics(e)),this.refresh()}),m(()=>[this.highlightsEnabled,this.highlightName],()=>{this._highlightHelper?.removeAll(),this._setUpHighlights()}),m(()=>this.enableMidpoints,()=>this.refresh()),Z(this.tooltip,()=>this._tooltipsContext),m(()=>this.view.effectiveTheme.accentColor,()=>this._updateSymbolsForTheme(),v),this._updateHandlesOnExternalGeometryChange]),this._updateTooltip()}destroy(){this._reset(),this._mover?.destroy(),this._mover=null,this._connectedReshapeManager=h(this._connectedReshapeManager),this.tooltip=h(this.tooltip)}get _coordinateHelper(){return this._editGeometryOperations?.data.coordinateHelper??pt(!!this.graphic.geometry?.hasZ,!!this.graphic.geometry?.hasM,this.view.spatialReference)}get _selectedManipulator(){return 1===this.selectedManipulators.length?this.selectedManipulators.at(0):void 0}get _tooltipsContext(){const{automaticAreaMeasurementUtils:t,automaticLengthMeasurementUtils:e,sketchOptions:i,activeTooltipInfo:s,graphic:o}=this;return{sketchOptions:i,activeTooltipInfo:s,graphic:o,selectedVertex:this._selectedManipulator,automaticAreaMeasurementUtils:t,automaticLengthMeasurementUtils:e,updateGeometry:(t,e,i,s,o)=>{this._setUpGeometryHelper();const r=t===this.graphic;r?this._emitMoveStartEvent(0,0):this._emitReshapeStartEvent(t);const n=!0;if(this._syncGeometryAfterVertexMove(t,e,s,o,n),r){const{view:t}=this,s=t.toScreen(i),o=t.toScreen(e),r=(o?.x??0)-(s?.x??0),n=(o?.y??0)-(s?.y??0);this._emitMoveEvent(r,n),this._emitMoveStopEvent(r,n)}else this._emitReshapeEvent(t),this._emitReshapeStopEvent(t);this._editGeometryOperations=h(this._editGeometryOperations)}}}get state(){const t=this.view.ready,e=!(!this.graphic||!this.layer);return t&&e?"active":t?"ready":"disabled"}isUIGraphic(t){return t===this.graphic||this._isMidpoint(t)||this._isCurveControlPoint(t)||this._isVertex(t)||this._isConstructionLine(t)}refresh(){this._reset(),this._setup()}reset(){this.graphic=null}clearSelection(){this._clearSelection()}removeSelectedVertices(){const{selectedManipulators:t}=this;t.length&&this._removeVertices(t)}_setup(){const{graphic:t,layer:e}=this;if(!e||null==t?.geometry)return;const i=t.geometry;"mesh"!==i.type&&"extent"!==i.type?("polygon"===i.type&&M(i),this._setUpHighlights(),this._setupGraphics(),this._setupMover(),this._setupConnectedReshapeManager()):this._logGeometryTypeError()}_setUpHighlights(){this.highlightsEnabled&&this.graphic&&this._highlightHelper?.add(this.graphic,this.highlightName)}_setUpGeometryHelper(){const t=this.graphic.geometry;null!=t&&"mesh"!==t.type&&"extent"!==t.type?this._editGeometryOperations??=lt.fromGeometry(t,2,{allowCurves:!0}):this._logGeometryTypeError()}_saveSnappingContextForHandle(t,e){this._snappingGraphicsLayer=new A({listMode:"hide",internal:!0,title:"Reshape snapping layer"}),this.view.map.layers.add(this._snappingGraphicsLayer);const i=this._editGeometryOperations;p(i),this._snappingContext=new mt({editGeometryOperations:i,elevationInfo:{mode:"on-the-ground",offset:0},pointer:e.viewEvent?.pointerType||"mouse",excludeFeature:this.graphic,feature:this.graphic,visualizer:new L(this._snappingGraphicsLayer),vertexHandle:this._getVertexFromEditGeometry(t)})}_reset(){this._clearSelection(),this._highlightHelper?.removeAll(),this._updateTooltip(),this._resetGraphics(),this._resetSnappingStateVars(),this._activeOperationInfo=null,this._mover?.destroy(),this._mover=null,this.removeHandles(yt)}_resetSnappingStateVars(){null!=this.snappingManager&&this.snappingManager.doneSnapping(),null!=this._snappingGraphicsLayer&&(this.view?.map&&this.view.map.layers.remove(this._snappingGraphicsLayer),this._snappingGraphicsLayer.destroy()),this._editGeometryOperations=h(this._editGeometryOperations),this._snappingTask=c(this._snappingTask),this._snappingTask=null,this._snappingContext=null,this._stagedVertex=null}_resetGraphics(t){this._removeMidpointGraphics(t),this._removeVertexGraphics(t),this._removeCurveGraphics(t),this._updateTooltip()}_removeMidpointGraphics(t=this.layer){const{midpointGraphics:e}=this;t?.removeMany(e.items),e.drain(h)}_removeVertexGraphics(t=this.layer){const{vertexGraphics:e}=this;t?.removeMany(e.items),e.drain(h)}_removeCurveGraphics(t=this.layer){const{curveControlPointGraphics:e,constructionLineGraphics:i}=this;t?.removeMany(e.items),t?.removeMany(i.items),e.drain(h),i.drain(h)}_setupGraphics(){const t=this.graphic.geometry;if(null!=t&&("polyline"===t.type||"polygon"===t.type||"multipoint"===t.type)){const e=gt(t);this.enableMidpoints&&"multipoint"!==t.type&&this._setUpMidpointGraphics(e),this.enableVertices&&(this._setUpVertexGraphics(e),this._setupCurveGraphics(e))}}_setUpMidpointGraphics(t){this._removeMidpointGraphics();const e=Q(t,this.symbols,this._coordinateHelper,"polygon"===this.graphic.geometry?.type);this.midpointGraphics.addMany(e),this.layer.addMany(e)}_setUpVertexGraphics(t){this._removeVertexGraphics();const e=W(t,this.symbols,this._coordinateHelper);this.vertexGraphics.addMany(e),this._storeRelatedVertexIndices(),this.layer.addMany(e)}_setupCurveGraphics(t){this._removeCurveGraphics();const e=X(t,this.symbols,this._coordinateHelper),i=Y(t,this.symbols,this._coordinateHelper);this.curveControlPointGraphics.addMany(e),this.constructionLineGraphics.addMany(i),this.layer.addMany(i),this.layer.addMany(e)}_updateSymbolsForTheme(){const t=this.view.effectiveTheme.accentColor;this.symbols={vertices:{...this.symbols.vertices,default:this.symbols.vertices.default.clone().set("color",t),hover:this.symbols.vertices.hover?.clone().set("color",t)},controlPoints:{...this.symbols.controlPoints,default:this.symbols.controlPoints.default.clone().set("color",t),hover:this.symbols.controlPoints.hover?.clone().set("color",t)},midpoints:{...this.symbols.midpoints},constructionLines:this.symbols.constructionLines.clone().set("color",t)};for(const e of this.vertexGraphics)this._isSelected(e)?e.symbol=this.symbols.vertices.selected:this._hoverGraphic===e?e.symbol=this.symbols.vertices.hover:e.symbol=this.symbols.vertices.default;for(const e of this.curveControlPointGraphics)this._isSelected(e)?e.symbol=this.symbols.controlPoints.selected:this._hoverGraphic===e?e.symbol=this.symbols.controlPoints.hover:e.symbol=this.symbols.controlPoints.default;for(const e of this.constructionLineGraphics)e.symbol=this.symbols.constructionLines}_storeRelatedVertexIndices(){const t=this.vertexGraphics.items;if(!t)return;const e=t.map(({geometry:t})=>({x:t.x,y:t.y}));for(let i=0;i<e.length;i++){const s=[];for(let t=0;t<e.length;t++){if(i===t)continue;const o=e[i],r=e[t];o.x===r.x&&o.y===r.y&&s.push(t)}t[i].attributes[tt.relatedGraphicIndices]=s}}_setupMover(){const{enableMovement:t,graphic:e,midpointGraphics:i,vertexGraphics:s,view:o}=this,r=s.concat(i,this.curveControlPointGraphics).items;t&&"multipoint"!==e.geometry?.type&&r.push(e),this._mover=new D({enableMoveAllGraphics:!1,highlightsEnabled:!1,indicatorsEnabled:!1,graphics:r,view:o,callbacks:{onGraphicClick:t=>this._onGraphicClickCallback(t),onGraphicMoveStart:t=>this._onGraphicMoveStartCallback(t),onGraphicMove:t=>this._onGraphicMoveCallback(t),onGraphicMoveStop:t=>this._onGraphicMoveStopCallback(t),onGraphicPointerOver:t=>this._onGraphicPointerOverCallback(t),onGraphicPointerOut:t=>this._onGraphicPointerOutCallback(t)}})}_setupConnectedReshapeManager(){const{connectedReshapeProviders:t}=this;null!=t&&0!==t.length&&(this._connectedReshapeManager=new j({providerFactories:t,view:this.view}))}_onGraphicClickCallback(t){t.viewEvent.stopPropagation();const e=t.graphic,i=this._isCurveControlPoint(e);if(e===this.graphic)this.clearSelection(),this.emit("graphic-click",t),this.callbacks.onGraphicClick?.(t);else if(this._isMidpoint(e)){if(2===t.viewEvent.button)return;const i=this.graphic.clone(),s=this._handleMidpointClickOrStartMove(t);this.refresh(),s.length&&this._emitVertexAddEvent([e],i,s)}else if(this._isVertex(e)||i){if(t.viewEvent.stopPropagation(),2===t.viewEvent.button)return void(i||this._removeVertices(e));t.viewEvent.native.shiftKey||this._clearSelection(),this.selectedManipulators.includes(e)?this._removeFromSelection(e,!0):this._addToSelection(e)}}_setUpOperation(t){const{graphic:e,dx:i,dy:s}=t,o=e===this.graphic;this._resetSnappingStateVars(),this._setUpGeometryHelper(),this._saveSnappingContextForHandle(e,t),this._activeOperationInfo={target:this.graphic,mover:e,operationType:o?"move":"reshape",totalDx:i,totalDy:s}}_onGraphicMoveStartCallback(t){const{dx:e,dy:i,graphic:s}=t,o=this._connectedReshapeManager,r=o?Vt(this.graphic):null;if(s===this.graphic){const{geometry:n}=s;return this._setUpOperation(t),this._emitMoveStartEvent(e,i),r&&o?.startFeatureMove([r]),void(null!=n&&"point"===n.type&&this._onHandleMove(s,e,i,t,()=>{this._updateTooltip(this.graphic,t.viewEvent),this._emitMoveEvent(e,i)}))}const{selectedManipulators:n}=this;if(!n.includes(s)){if(this._clearSelection(),this._isMidpoint(s)){const e=this.graphic.clone(),i=this._handleMidpointClickOrStartMove(t);i.length&&(this._emitVertexAddEvent([s],e,i),this._refreshGraphicIndicesAttributes(i[0]))}this._addToSelection(s)}if(this._setUpOperation(t),r){const t=n.filter(t=>this._isVertex(t));o?.startVertexMove(r,It(t))}this._emitReshapeStartEvent(s),this._onHandleMove(s,e,i,t,()=>{this._updateTooltip(s,t.viewEvent),this._emitReshapeEvent(s)})}_onGraphicMoveCallback(t){const e=this._activeOperationInfo;if(!e)return;const{dx:i,dy:s,graphic:o}=t;e.totalDx+=i,e.totalDy+=s;const{operationType:r}=e,{geometry:n}=o;if(null!=n)if("move"!==r)this._onHandleMove(o,i,s,t,()=>{this._updateTooltip(o,t.viewEvent),this._emitReshapeEvent(o)});else if("point"===n.type)this._onHandleMove(o,i,s,t,()=>{this._updateTooltip(this.graphic,t.viewEvent),this._emitMoveEvent(i,s)});else if("polyline"===n.type||"polygon"===n.type){const e=gt(n);this._updateVertexGraphicLocations(e);const{dxMap:o,dyMap:r}=U(i,s,this.view);this._connectedReshapeManager?.translate(o,r,0),this._updateTooltip(this.graphic,t.viewEvent),this._emitMoveEvent(i,s)}}_onGraphicMoveStopCallback(t){const e=this._activeOperationInfo;if(!e)return;const{dx:i,dy:s,graphic:o}=t,{operationType:r}=e;e.totalDx+=i,e.totalDy+=s,this._onHandleMove(o,i,s,t,()=>"move"===r?this._emitMoveStopEvent():this._emitReshapeStopEvent(o)),this._isMidpoint(o)||o.getAttribute(tt.curveFromStraightEdgeFlag)?this.refresh():(this._updateTooltip(this._isVertex(o)?o:null),this._resetSnappingStateVars(),this._connectedReshapeManager?.finish(),this._activeOperationInfo=null)}_updateVertexGraphicLocations(t){const{_coordinateHelper:e}=this;for(const i of this.vertexGraphics){const{pathIndex:s,pointIndex:o}=i.attributes;i.geometry=e.arrayToPoint(O(t[s][o]))}this._updateMidpointGraphicLocations(t),this._updateCurveGraphicLocations(t)}_updateMidpointGraphicLocations(t){const{_coordinateHelper:e}=this;for(const i of this.midpointGraphics){const{pathIndex:s,pointIndexStart:o,pointIndexEnd:r}=i.attributes,n=t[s];i.geometry=et(n[o],n[r],e)}}_updateCurveGraphicLocations(t){const{spatialReference:e}=this._coordinateHelper,i=new Map;for(const s of this.selectedManipulators){const[t,e]=Et(s);null!=t&&null!=e&&s.getAttribute(tt.controlPointKind)&&a(i,t,()=>new Set)?.add(e)}for(const s of this.curveControlPointGraphics){const[e,o]=Et(s);if(i.get(e)?.has(o))continue;const r=t[e][o];if(V(r)||I(r)){const i=O(t[e][o-1]),n=V(r)?E(i,r):R(i,r),[a,h]=S(n,.25);s.geometry=new g({x:a,y:h,spatialReference:this._coordinateHelper.spatialReference})}else if(P(r)){const t=s.getAttribute(tt.controlPointKind),[e,i]=t===it.bezier.cp1?r.b[1]:r.b[2];s.geometry=new g({x:e,y:i,spatialReference:this._coordinateHelper.spatialReference})}}for(const s of this.constructionLineGraphics){const i=s.getAttribute(tt.controlPointKind),[o,r]=Et(s),n=t[o],a=O(n[r-1]),h=O(n[r]),p=t[o][r];i===it.bezier.line1?s.geometry=new f({paths:[[[a[0],a[1]],[...p.b[1]]]],spatialReference:e}):s.geometry=new f({paths:[[[h[0],h[1]],[...p.b[2]]]],spatialReference:e})}}_refreshGraphicIndicesAttributes(t){const{componentIndex:e,vertexIndex:i}=t,s=t=>{const[s,o]=Et(t);s===e&&o>=i&&t.setAttribute(tt.pointIndex,o+1)};this.vertexGraphics.forEach(s),this.curveControlPointGraphics.forEach(s),this.constructionLineGraphics.forEach(s);for(const o of this.midpointGraphics){if(o.getAttribute(tt.pathIndex)!==e)continue;const t=o.getAttribute(tt.pointIndexStart);t>=i&&(o.setAttribute(tt.pointIndexStart,t+1),o.setAttribute(tt.pointIndexEnd,o.getAttribute(tt.pointIndexEnd)+1))}}_getVertexFromEditGeometry(t){const[e,i]=Et(t);return p(this._editGeometryOperations),this._editGeometryOperations.data.parts[e].vertices[i]}_onHandleMove(t,e,s,o,r){c(this._snappingTask);const n=this._snappingContext;if(!n)return;const a=t.geometry,h="graphic-move-stop"===o.type;if(a&&C(a))if(null!=this.snappingManager&&this.selectedManipulators.length<2&&!h){const o=this.snappingManager;this._stagedVertex=o.update({point:a,context:n}),this._syncGeometryAfterVertexMove(t,new g(this._stagedVertex),e,s,h),r(),this._snappingTask=i(async i=>{const p=await o.snap({point:a,context:n,signal:i});p.valid&&(this._stagedVertex=p.apply(),this._syncGeometryAfterVertexMove(t,new g(this._stagedVertex),e,s,h),r())})}else{const i=null!=this._stagedVertex?new g(this._stagedVertex):a;this._syncGeometryAfterVertexMove(t,i,e,s,h),r()}else r()}_syncGeometryAfterVertexMove(t,e,i,s,o=!1){const r=this._editGeometryOperations?.data.geometry;if(!r)return;const{_coordinateHelper:n}=this,a=n.pointToVector(e),h=this._getVertexFromEditGeometry(t);if(h){const t=n.getZ(a),e=a[0]-h.pos[0],i=a[1]-h.pos[1],s=null!=t?t-h.pos[2]:0;"point"!==r.type&&"mesh"!==r.type||this._editGeometryOperations?.moveVertices([h],e,i,s),this._connectedReshapeManager?.translate(e,i,s)}if("point"===r.type)t.geometry=e;else if("mesh"===r.type)t.geometry=r.centerAt(e);else{if(t!==this.graphic){const o=n.spatialReference,[a,h]=Et(t);let p=ft(r);const c=n.pointToArray(e);this._updateGeometryFromGraphic(t,p,a,h,c,o,"polygon"===r.type),this._isVertex(t)||this._isCurveControlPoint(t)?(p=this._moveRelatedCoordinates(p,t,c),p=this._moveSelectedHandleCoordinates(p,t,i,s,"polygon"===r.type),this._updateMidpointGraphicLocations(p),this._updateCurveGraphicLocations(p)):this._isMidpoint(t)&&this._updateCurveGraphicLocations(p),st(r,p)}this._updateGraphicGeometry(r.clone()),this._editGeometryOperations=lt.fromGeometry(r,2,{allowCurves:!0}),o&&(this._mover?this._mover.updateGeometry(this._mover.graphics.indexOf(t),e):t.geometry=e)}}_moveRelatedCoordinates(t,e,i){const{relatedGraphicIndices:s}=e.attributes,o=this._coordinateHelper.spatialReference;if(!s?.length)return t;for(const r of s){const s=this.vertexGraphics.at(r),[n,a]=Et(s);St(t,n,a,i,o),s.geometry=e.geometry}return t}_moveSelectedHandleCoordinates(t,e,i,s,o){const r=this._coordinateHelper.spatialReference;for(const n of this.selectedManipulators)if(n!==e){const[e,a]=Et(n),h=n.getAttribute(tt.relatedGraphicIndices),p=F(n.geometry,i,s,this.view),c=b(p);if(n.geometry=p,this._updateGeometryFromGraphic(n,t,e,a,c,r,o),h?.length)for(const i of h){const e=this.vertexGraphics.at(i),[s,o]=Et(e);St(t,s,o,c,r),e.geometry=p}}return t}_updateGeometryFromGraphic(t,e,i,s,o,r,n){const a=e[i].length-1;this._isCurveControlPoint(t)?xt(e,i,s,[o[0],o[1]],t.getAttribute(tt.controlPointKind)):(St(e,i,s,o,r),n&&(0===s?St(e,i,a,o,r):s===a&&(e[i][0]=o)))}_onGraphicPointerOverCallback(t){const e=t.graphic;this._hoverGraphic=e;const i=this._isVertex(e);i&&!this._isSelected(e)?e.symbol=this.symbols.vertices.hover:this._isCurveControlPoint(e)&&!this._isSelected(e)&&(e.symbol=this.symbols.controlPoints.hover),this._updateTooltip(i?e:null),this._updateHoverCursor(e)}_onGraphicPointerOutCallback(t){const e=t.graphic;this._hoverGraphic=null,this._isVertex(e)&&!this._isSelected(e)&&(e.symbol=this.symbols.vertices.default),this._isCurveControlPoint(e)&&!this._isSelected(e)&&(e.symbol=this.symbols.controlPoints.default),this.removeHandles(yt),this._updateTooltip()}_handleMidpointClickOrStartMove(t){const{graphic:e}=t,i=this.graphic.geometry;if(null==i||"polygon"!==i.type&&"polyline"!==i.type)return[];const s=i.clone(),o=[],{[tt.pathIndex]:r,[tt.pointIndexStart]:n,[tt.pointIndexEnd]:a}=e.attributes,h=b(e.geometry),p=0===a?n+1:a;e.attributes={[tt.tool]:ot,[tt.pathIndex]:r,[tt.pointIndex]:p,[tt.relatedGraphicIndices]:[]};const c=ft(s),l=c[r][a];if(k(l)){if(this.enableCurveOnMidpoint&&t.viewEvent.native.shiftKey){const t=O(c[r][p]);c[r].splice(p,1,{c:[t,[h[0],h[1]]]}),e.setAttribute(tt.controlPointKind,it.circle.interior),e.setAttribute(tt.curveFromStraightEdgeFlag,!0),this.midpointGraphics.remove(e),this.curveControlPointGraphics.push(e),st(s,c)}else c[r].splice(p,0,h),o.push({coordinates:c[r][p],componentIndex:r,vertexIndex:p})}else{const t=O(c[r][n]),e=rt(t,l,.5,this._coordinateHelper);c[r].splice(a,1,...e),o.push({coordinates:O(c[r][p]),componentIndex:r,vertexIndex:p})}return this._updateGraphicGeometry(s),o}_addToSelection(t){const e=Ot(t);for(const i of e)this._isCurveControlPoint(i)?i.symbol=this.symbols.controlPoints.selected:i.symbol=this.symbols.vertices.selected,this.selectedManipulators.add(i),this._updateTooltip(i);this._emitSelectEvent(e)}_removeFromSelection(t,e){if(this._isVertex(t)){const{vertices:i}=this.symbols;t.symbol=e?i.hover:i.default}else if(this._isCurveControlPoint(t)){const{controlPoints:i}=this.symbols;t.symbol=e?i.hover:i.default}this.selectedManipulators.remove(t),this._emitDeselectEvent([t]),this._updateTooltip()}_clearSelection(){const t=this.selectedManipulators.toArray(),{controlPoints:e,vertices:i}=this.symbols;if(t.length>0){for(const s of t)this._isVertex(s)?s.symbol=i.default:this._isCurveControlPoint(s)&&(s.symbol=e.default);this.selectedManipulators.removeAll(),this._emitDeselectEvent(t),this._updateTooltip()}}_keyDownHandler(t){null==this._activeOperationInfo&&ut(t,this.tooltip)||ct.delete.includes(t.key)&&!t.repeat&&this.selectedManipulators.length&&this._removeVertices(this.selectedManipulators)}_removeVertices(t){const e=this.graphic.geometry,i=this.vertexGraphics.length;if(null==e||"polygon"!==e.type&&"polyline"!==e.type&&"multipoint"!==e.type)return;if("polygon"===e.type&&i<4||"multipoint"===e.type&&i<2||"polyline"===e.type&&i<3)return;const s=this.graphic.clone(),o=e.clone();let r=ft(o);const n=[],a=Ot(t);for(const h of a){if(this._isCurveControlPoint(h))continue;const{x:t,y:e}=h.geometry;for(let i=0;i<r.length;i++){const s=r[i];for(let o=0;o<s.length;o++){const[a,h]=O(s[o]);if(t===a&&e===h){n.push({coordinates:O(r[i][o]),componentIndex:i,vertexIndex:o}),r[i].splice(Number(o),1);const t=r[i][o];t&&!k(t)&&(r[i][o]=O(t))}}}}if("polygon"===o.type)r=r.filter(t=>{if(t.length<2)return!1;const[e,i]=O(t[0]),[s,o]=O(t[t.length-1]);return(2!==t.length||e!==s||i!==o)&&(e===s&&i===o||t.push(t[0]),!0)});else if("polyline"===o.type)for(const h of r)1===h.length&&r.splice(r.indexOf(h),1);st(o,r),this._updateGraphicGeometry(o),this.refresh(),this._emitVertexRemoveEvent(a,s,n)}_isVertex(t){return this.vertexGraphics.includes(t)}_isCurveControlPoint(t){return this.curveControlPointGraphics.includes(t)}_isConstructionLine(t){return this.constructionLineGraphics.includes(t)}_isSelected(t){return(this._isVertex(t)||this.curveControlPointGraphics.includes(t))&&this.selectedManipulators.includes(t)}_isMidpoint(t){return this.midpointGraphics.includes(t)}_updateHoverCursor(t){const e=this._isMidpoint(t)?"copy":"move";this.addHandles(this.view.acquireCursor(e,"high"),yt)}_updateTooltip(t,e){let i=null;const{graphic:s,view:o,tooltipInfos:r}=this,n=s?.geometry;"point"===n?.type?i=r.movePoint:this._selectedManipulator?i=r.selectedVertex:t===this.graphic?(i=r.translateGraphic,$(i,o,this._tooltipsContext,e)):t&&this.selectedManipulators.length>1&&(i=r.translateVertices,B(i,o,n,this._tooltipsContext,e)),this.activeTooltipInfo=i}_updateGraphicGeometry(t){this._updateHandlesOnExternalGeometryChange?.pause(),this.graphic.geometry=t,this._updateHandlesOnExternalGeometryChange?.resume()}_emitMoveStartEvent(t,e){const i={type:"move-start",mover:this.graphic,dx:t,dy:e};this.emit("move-start",i),this.callbacks.onMoveStart?.(i)}_emitMoveEvent(t,e){const i={type:"move",mover:this.graphic,dx:t,dy:e};this.emit("move",i),this.callbacks.onMove?.(i)}_emitMoveStopEvent(t,e){if(null==t||null==e){const i=this._activeOperationInfo;if(!i)return;t=i.totalDx,e=i.totalDy}const i={type:"move-stop",mover:this.graphic,dx:t,dy:e};this.emit("move-stop",i),this.callbacks.onMoveStop?.(i)}_emitReshapeStartEvent(t){const e={type:"reshape-start",graphic:this.graphic,mover:t,selected:this.selectedManipulators.toArray()};this.emit("reshape-start",e),this.callbacks.onReshapeStart?.(e)}_emitReshapeEvent(t){const e={type:"reshape",graphic:this.graphic,mover:t,selected:this.selectedManipulators.toArray()};this.emit("reshape",e),this.callbacks.onReshape?.(e)}_emitReshapeStopEvent(t){const e={type:"reshape-stop",graphic:this.graphic,mover:t,selected:this.selectedManipulators.toArray()};this.emit("reshape-stop",e),this.callbacks.onReshapeStop?.(e)}_emitSelectEvent(t){const e={type:"vertex-select",added:t};this.emit("select",e),this.callbacks.onVertexSelect?.(e)}_emitDeselectEvent(t){const e={type:"vertex-deselect",removed:t};this.emit("deselect",e),this.callbacks.onVertexDeselect?.(e)}_emitVertexAddEvent(t,e,i){const s={type:"vertex-add",added:t,graphic:this.graphic,oldGraphic:e,vertices:i};this.emit("vertex-add",s),this.callbacks.onVertexAdd?.(s)}_emitVertexRemoveEvent(t,e,i){const s={type:"vertex-remove",removed:t,graphic:this.graphic,oldGraphic:e,vertices:i};this.emit("vertex-remove",s),this.callbacks.onVertexRemove?.(s)}_logGeometryTypeError(){n.getLogger(this).error(new o("reshape:invalid-geometry","Reshape operation not supported for the provided graphic. The geometry type is not supported."))}};function gt(t){const e=ft(t.clone());if("polygon"===t.type)for(const i of e){const t=i[i.length-1];if(!k(t))continue;const e=i[0];e[0]===t[0]&&e[1]===t[1]&&i.length>2&&i.pop()}return e}function ft(t){return"polygon"===t.type?t.curveRings?.slice()??t.rings.slice():"polyline"===t.type?t.curvePaths?.slice()??t.paths.slice():t.points.map(t=>[t])}function Gt(t,e,i,s){const o=t[e][i];if(V(o))o.c[1]=s;else if(I(o)){const o=O(t[e][i]);t[e][i]={c:[o,s]}}}function xt(t,e,i,s,o){switch(o){case it.circle.interior:Gt(t,e,i,s);break;case it.bezier.cp1:t[e][i].b[1]=s;break;case it.bezier.cp2:t[e][i].b[2]=s}}function Mt(t,e){return t<1e-8*e}function bt(t,{cx:e,cy:i,isInvalid:s,thetaStart:o,thetaEnd:r},n,a){const[h,p]=t,[c,l]=n,d=c-h,m=l-p;e-=h,i-=p;const v=a?o>r:o<r,[u,y]=s?[e,i]:v?[-i,e]:[i,-e],[_,g]=[d,m],[f,G]=[u,y],x=_*G-g*f,M=(d**2+m**2)/2;if(Mt(Math.abs(x),M))return[(h+c)/2,(p+l)/2];const[b,C]=[G/x*M,-f/x*M],S=b**2+C**2,[E,w]=[d/2-b,m/2-C];if(Mt(E**2+w**2,S)){const[t,e]=v?[-C,b]:[C,-b];return[t+b+h,e+C+p]}const O=Math.sqrt((b**2+C**2)/(E**2+w**2))*Math.sign(d*u+m*y);return[E*O+b+h,w*O+C+p]}function Ct(t,e,i){const s=G(new f({curvePaths:[[t,e]],spatialReference:i})),{curvePaths:o}=x(s,i),r=o[0][1];return H(r)?r:w(t,r)}function St(t,e,i,s,o){const r=t[e][i],n=t[e].at(i+1);if(nt(t,e)){const i=t[e][1];return t[e][0]=[...s],void(t[e][1]={a:[[...s],[...i.a[1]],0,0]})}if(at(t,e)){const i=t[e][1],[o,r]=i.a[1],[n,a]=s,h=Math.hypot(n-o,a-r),[p,c]=[n-o,a-r],l=T(c,p);return t[e][0]=[...s],void(t[e][1]={a:[[...s],[...i.a[1]],0,0,l,h,i.a[6]]})}const a=O(r);if(k(r))r.splice(0,r.length,...s);else if(P(r))r.b[0].splice(0,r.b[0].length,...s);else if(V(r)||I(r)){const o=O(t[e][i-1]),n=V(r)?E(o,r):R(o,r);t[e].splice(i,1,{c:[[...s],bt(o,n,s,!0)]})}else if(H(r)){r.a[0].splice(0,r.a[0].length,...s);const n=O(t[e][i-1]);r.a=Ct(n,r,o).a}if(n&&!k(n)&&!P(r))if(V(n)||I(n)){const o=O(n),r=V(n)?E(a,n):R(a,n);t[e].splice(i+1,1,{c:[o,bt(o,r,s,!1)]})}else if(H(n)){const t=O(r);n.a=Ct(t,n,o).a}}function Et({attributes:t}){return[t?.[tt.pathIndex]||0,t?.[tt.pointIndex]||0]}function wt({attributes:t}){return`${t?.[tt.pathIndex]}-${t?.[tt.pointIndex]}`}function Ot(t){return t instanceof e?[t]:[...t]}function Vt(t){const e=t.sourceLayer??t.layer;return N(e)?{graphic:t,layer:e}:null}function It(t){return t.toArray().map(({attributes:t})=>({pathIndex:t[tt.pathIndex],vertexIndex:t[tt.pointIndex]}))}t([y()],_t.prototype,"_activeOperationInfo",void 0),t([y()],_t.prototype,"_connectedReshapeManager",void 0),t([y()],_t.prototype,"_coordinateHelper",null),t([y()],_t.prototype,"_editGeometryOperations",void 0),t([y()],_t.prototype,"tooltip",void 0),t([y()],_t.prototype,"tooltipInfos",void 0),t([y()],_t.prototype,"activeTooltipInfo",void 0),t([y({constructOnly:!0})],_t.prototype,"automaticAreaMeasurementUtils",void 0),t([y({constructOnly:!0})],_t.prototype,"automaticLengthMeasurementUtils",void 0),t([y()],_t.prototype,"_selectedManipulator",null),t([y()],_t.prototype,"_tooltipsContext",null),t([y()],_t.prototype,"callbacks",void 0),t([y()],_t.prototype,"connectedReshapeProviders",void 0),t([y()],_t.prototype,"enableMidpoints",void 0),t([y()],_t.prototype,"enableCurveOnMidpoint",void 0),t([y()],_t.prototype,"enableMovement",void 0),t([y()],_t.prototype,"enableVertices",void 0),t([y()],_t.prototype,"graphic",void 0),t([y()],_t.prototype,"highlightName",void 0),t([y()],_t.prototype,"highlightsEnabled",void 0),t([y()],_t.prototype,"layer",void 0),t([y()],_t.prototype,"snappingManager",void 0),t([y({readOnly:!0})],_t.prototype,"state",null),t([y()],_t.prototype,"symbols",void 0),t([y({type:dt})],_t.prototype,"sketchOptions",void 0),t([y({readOnly:!0})],_t.prototype,"type",void 0),t([y({readOnly:!0})],_t.prototype,"vertexGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"curveControlPointGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"constructionLineGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"midpointGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"selectedManipulators",void 0),t([y()],_t.prototype,"view",void 0),_t=t([_("esri.views.draw.support.Reshape")],_t);const Pt=_t;export{Pt as default};
5
+ import{__decorate as t}from"tslib";import e from"../../../Graphic.js";import{createTask as i}from"../../../core/asyncUtils.js";import s from"../../../core/Collection.js";import o from"../../../core/Error.js";import{EventedAccessor as r}from"../../../core/Evented.js";import n from"../../../core/Logger.js";import{getOrCreateMapValue as a}from"../../../core/MapUtils.js";import{destroyMaybe as h,assertIsSome as p,abortMaybe as c}from"../../../core/maybe.js";import{pausable as l,when as d,watch as m,initial as v,sync as u}from"../../../core/reactiveUtils.js";import{property as y,subclass as _}from"../../../core/accessorSupport/decorators.js";import g from"../../../geometry/Point.js";import f from"../../../geometry/Polyline.js";import{fromGeometry as G,toGeometry as x}from"../../../geometry/operators/support/apiConverter.js";import{closeRingsAndFixWinding as M,geometryToCoordinates as b}from"../../../geometry/support/coordsUtils.js";import{isPoint as C}from"../../../geometry/support/typeUtils.js";import{interpolateCircle as S}from"../../../geometry/support/curves/circleUtils.js";import{deriveCircleFromCircularArc as E,toEllipticArc7 as w}from"../../../geometry/support/curves/circularArcUtils.js";import{getEndpoint as O,isCircularArc as V,isEllipticArc4 as I,isBezierCurve as P,isCoordinate as k,isEllipticArc7 as H}from"../../../geometry/support/curves/curveUtils.js";import{deriveCircleFromEllipticArc4 as R}from"../../../geometry/support/curves/ellipticArc4Utils.js";import{wrapAtan2 as T}from"../../../geometry/support/curves/mathUtils.js";import A from"../../../layers/GraphicsLayer.js";import{SnappingVisualizer2D as L}from"../../2d/interactive/SnappingVisualizer2D.js";import{ConnectedReshapeManager as j}from"./ConnectedReshapeManager.js";import{screenDeltaToMapDelta as U,cloneMove as F}from"./drawUtils.js";import D from"./GraphicMover.js";import z from"./HighlightHelper.js";import{addUniqueLayer as K,isConnectedReshapeSupportedLayer as N}from"./layerUtils.js";import{createTooltipInfos as q,connectTooltip as Z,updateTranslateTooltipInfo as $,updateTranslateVertexTooltipInfo as B}from"./reshapeTooltipUtils.js";import{defaultSymbols as J,createMidpointGraphics as Q,createVertexGraphics as W,createCurveControlPointGraphics as X,createCurveConstructionLineGraphics as Y,attributeKeys as tt,getMidpoint as et,controlPointKinds as it,saveUpdatedCurveOrCoordinate as st,toolIdAttribute as ot,splitCurve as rt,isSingleSegmentCircle as nt,isSingleSegmentEllipse as at}from"./reshapeUtils.js";import{ViewEventPriorities as ht}from"../../input/InputManager.js";import{createCoordinateHelper as pt}from"../../interactive/coordinateHelper.js";import{sketchKeys as ct}from"../../interactive/keybindings.js";import{EditGeometryOperations as lt}from"../../interactive/editGeometry/EditGeometryOperations.js";import dt from"../../interactive/sketch/SketchOptions.js";import{SnappingContext as mt}from"../../interactive/snapping/SnappingContext.js";import{makeTooltip as vt,enterInputModeIfAvailable as ut}from"../../interactive/tooltip/tooltipCommonUtils.js";const yt=Symbol();let _t=class extends r{constructor(t){super(t),this._updateHandlesOnExternalGeometryChange=null,this._activeOperationInfo=null,this._connectedReshapeManager=null,this._editGeometryOperations=null,this._mover=null,this._snappingContext=null,this._snappingGraphicsLayer=null,this._hoverGraphic=null,this._snappingTask=null,this._stagedVertex=null,this.tooltip=null,this.activeTooltipInfo=null,this.callbacks={onReshapeStart(){},onReshape(){},onReshapeStop(){},onMoveStart(){},onMove(){},onMoveStop(){},onGraphicClick(){}},this.connectedReshapeProviders=null,this.enableMidpoints=!0,this.enableCurveOnMidpoint=!1,this.enableMovement=!0,this.enableVertices=!0,this.graphic=null,this.highlightName=null,this.highlightsEnabled=!0,this.layer=null,this.snappingManager=null,this.symbols=J,this.sketchOptions=new dt,this.type="reshape",this.vertexGraphics=new s,this.curveControlPointGraphics=new s,this.constructionLineGraphics=new s,this.midpointGraphics=new s,this.selectedManipulators=new s,this.view=null}initialize(){const t=this.view;this._highlightHelper=new z({view:t}),this._setup(),this._updateHandlesOnExternalGeometryChange=l(()=>this.graphic?.geometry,t=>{if(!t)return;const e=new Set(this.selectedManipulators.map(wt));this._highlightHelper.removeAll(),this._setUpHighlights(),this._setupGraphics(),this._clearSelection(),this.vertexGraphics.filter(t=>e.has(wt(t))).forEach(t=>this._addToSelection(t));const{enableMovement:i,_mover:s,graphic:o,midpointGraphics:r,vertexGraphics:n,curveControlPointGraphics:a}=this,h=n.concat(r,a).items;i&&h.push(o),s?.set("graphics",h)},u),this.tooltip=vt(()=>({view:t,options:this.sketchOptions.tooltips})),this.tooltipInfos=q(this.sketchOptions),this.addHandles([d(()=>t?.ready,()=>{const{layer:t,view:e}=this;K(e,t),this.addHandles(e.on("key-down",t=>this._keyDownHandler(t),ht.TOOL))},{once:!0,initial:!0}),m(()=>this.graphic,()=>this.refresh()),m(()=>this.layer,(t,e)=>{e&&(this._clearSelection(),this._resetGraphics(e)),this.refresh()}),m(()=>[this.highlightsEnabled,this.highlightName],()=>{this._highlightHelper?.removeAll(),this._setUpHighlights()}),m(()=>this.enableMidpoints,()=>this.refresh()),Z(this.tooltip,()=>this._tooltipsContext),m(()=>this.view.effectiveTheme.accentColor,()=>this._updateSymbolsForTheme(),v),this._updateHandlesOnExternalGeometryChange]),this._updateTooltip()}destroy(){this._reset(),this._mover?.destroy(),this._mover=null,this._connectedReshapeManager=h(this._connectedReshapeManager),this.tooltip=h(this.tooltip)}get _coordinateHelper(){return this._editGeometryOperations?.data.coordinateHelper??pt(!!this.graphic.geometry?.hasZ,!!this.graphic.geometry?.hasM,this.view.spatialReference)}get _selectedManipulator(){return 1===this.selectedManipulators.length?this.selectedManipulators.at(0):void 0}get _tooltipsContext(){const{automaticAreaMeasurementUtils:t,automaticLengthMeasurementUtils:e,sketchOptions:i,activeTooltipInfo:s,graphic:o}=this;return{sketchOptions:i,activeTooltipInfo:s,graphic:o,selectedVertex:this._selectedManipulator,automaticAreaMeasurementUtils:t,automaticLengthMeasurementUtils:e,updateGeometry:(t,e,i,s,o)=>{this._setUpGeometryHelper();const r=t===this.graphic;r?this._emitMoveStartEvent(0,0):this._emitReshapeStartEvent(t);const n=!0;if(this._syncGeometryAfterVertexMove(t,e,s,o,n),r){const{view:t}=this,s=t.toScreen(i),o=t.toScreen(e),r=(o?.x??0)-(s?.x??0),n=(o?.y??0)-(s?.y??0);this._emitMoveEvent(r,n),this._emitMoveStopEvent(r,n)}else this._emitReshapeEvent(t),this._emitReshapeStopEvent(t);this._editGeometryOperations=h(this._editGeometryOperations)}}}get state(){const t=this.view.ready,e=!(!this.graphic||!this.layer);return t&&e?"active":t?"ready":"disabled"}isUIGraphic(t){return t===this.graphic||this._isMidpoint(t)||this._isCurveControlPoint(t)||this._isVertex(t)||this._isConstructionLine(t)}refresh(){this._reset(),this._setup()}reset(){this.graphic=null}clearSelection(){this._clearSelection()}removeSelectedVertices(){const{selectedManipulators:t}=this;t.length&&this._removeVertices(t)}_setup(){const{graphic:t,layer:e}=this;if(!e||null==t?.geometry)return;const i=t.geometry;"mesh"!==i.type&&"extent"!==i.type?("polygon"===i.type&&M(i),this._setUpHighlights(),this._setupGraphics(),this._setupMover(),this._setupConnectedReshapeManager()):this._logGeometryTypeError()}_setUpHighlights(){this.highlightsEnabled&&this.graphic&&this._highlightHelper?.add(this.graphic,this.highlightName)}_setUpGeometryHelper(){const t=this.graphic.geometry;null!=t&&"mesh"!==t.type&&"extent"!==t.type?this._editGeometryOperations??=lt.fromGeometry(t,2,{allowCurves:!0}):this._logGeometryTypeError()}_saveSnappingContextForHandle(t,e){this._snappingGraphicsLayer=new A({listMode:"hide",internal:!0,title:"Reshape snapping layer"}),this.view.map.layers.add(this._snappingGraphicsLayer);const i=this._editGeometryOperations;p(i),this._snappingContext=new mt({editGeometryOperations:i,elevationInfo:{mode:"on-the-ground",offset:0},pointer:e.viewEvent?.pointerType||"mouse",excludeFeature:this.graphic,feature:this.graphic,visualizer:new L(this._snappingGraphicsLayer),vertexHandle:this._getVertexFromEditGeometry(t)})}_reset(){this._clearSelection(),this._highlightHelper?.removeAll(),this._updateTooltip(),this._resetGraphics(),this._resetSnappingStateVars(),this._activeOperationInfo=null,this._mover?.destroy(),this._mover=null,this.removeHandles(yt)}_resetSnappingStateVars(){null!=this.snappingManager&&this.snappingManager.doneSnapping(),null!=this._snappingGraphicsLayer&&(this.view?.map&&this.view.map.layers.remove(this._snappingGraphicsLayer),this._snappingGraphicsLayer.destroy()),this._editGeometryOperations=h(this._editGeometryOperations),this._snappingTask=c(this._snappingTask),this._snappingTask=null,this._snappingContext=null,this._stagedVertex=null}_resetGraphics(t){this._removeMidpointGraphics(t),this._removeVertexGraphics(t),this._removeCurveGraphics(t),this._updateTooltip()}_removeMidpointGraphics(t=this.layer){const{midpointGraphics:e}=this;t?.removeMany(e.items),e.drain(h)}_removeVertexGraphics(t=this.layer){const{vertexGraphics:e}=this;t?.removeMany(e.items),e.drain(h)}_removeCurveGraphics(t=this.layer){const{curveControlPointGraphics:e,constructionLineGraphics:i}=this;t?.removeMany(e.items),t?.removeMany(i.items),e.drain(h),i.drain(h)}_setupGraphics(){const t=this.graphic.geometry;if(null!=t&&("polyline"===t.type||"polygon"===t.type||"multipoint"===t.type)){const e=gt(t);this.enableMidpoints&&"multipoint"!==t.type&&this._setUpMidpointGraphics(e),this.enableVertices&&(this._setUpVertexGraphics(e),this._setupCurveGraphics(e))}}_setUpMidpointGraphics(t){this._removeMidpointGraphics();const e=Q(t,this.symbols,this._coordinateHelper,"polygon"===this.graphic.geometry?.type);this.midpointGraphics.addMany(e),this.layer.addMany(e)}_setUpVertexGraphics(t){this._removeVertexGraphics();const e=W(t,this.symbols,this._coordinateHelper);this.vertexGraphics.addMany(e),this._storeRelatedVertexIndices(),this.layer.addMany(e)}_setupCurveGraphics(t){this._removeCurveGraphics();const e=X(t,this.symbols,this._coordinateHelper),i=Y(t,this.symbols,this._coordinateHelper);this.curveControlPointGraphics.addMany(e),this.constructionLineGraphics.addMany(i),this.layer.addMany(i),this.layer.addMany(e)}_updateSymbolsForTheme(){const t=this.view.effectiveTheme.accentColor;this.symbols={vertices:{...this.symbols.vertices,default:this.symbols.vertices.default.clone().set("color",t),hover:this.symbols.vertices.hover?.clone().set("color",t)},controlPoints:{...this.symbols.controlPoints,default:this.symbols.controlPoints.default.clone().set("color",t),hover:this.symbols.controlPoints.hover?.clone().set("color",t)},midpoints:{...this.symbols.midpoints},constructionLines:this.symbols.constructionLines.clone().set("color",t)};for(const e of this.vertexGraphics)this._isSelected(e)?e.symbol=this.symbols.vertices.selected:this._hoverGraphic===e?e.symbol=this.symbols.vertices.hover:e.symbol=this.symbols.vertices.default;for(const e of this.curveControlPointGraphics)this._isSelected(e)?e.symbol=this.symbols.controlPoints.selected:this._hoverGraphic===e?e.symbol=this.symbols.controlPoints.hover:e.symbol=this.symbols.controlPoints.default;for(const e of this.constructionLineGraphics)e.symbol=this.symbols.constructionLines}_storeRelatedVertexIndices(){const t=this.vertexGraphics.items;if(!t)return;const e=t.map(({geometry:t})=>({x:t.x,y:t.y}));for(let i=0;i<e.length;i++){const s=[];for(let t=0;t<e.length;t++){if(i===t)continue;const o=e[i],r=e[t];o.x===r.x&&o.y===r.y&&s.push(t)}t[i].attributes[tt.relatedGraphicIndices]=s}}_setupMover(){const{enableMovement:t,graphic:e,midpointGraphics:i,vertexGraphics:s,view:o}=this,r=s.concat(i,this.curveControlPointGraphics).items;t&&"multipoint"!==e.geometry?.type&&r.push(e),this._mover=new D({enableMoveAllGraphics:!1,highlightsEnabled:!1,indicatorsEnabled:!1,graphics:r,view:o,callbacks:{onGraphicClick:t=>this._onGraphicClickCallback(t),onGraphicMoveStart:t=>this._onGraphicMoveStartCallback(t),onGraphicMove:t=>this._onGraphicMoveCallback(t),onGraphicMoveStop:t=>this._onGraphicMoveStopCallback(t),onGraphicPointerOver:t=>this._onGraphicPointerOverCallback(t),onGraphicPointerOut:t=>this._onGraphicPointerOutCallback(t)}})}_setupConnectedReshapeManager(){const{connectedReshapeProviders:t}=this;null!=t&&0!==t.length&&(this._connectedReshapeManager=new j({providerFactories:t,view:this.view}))}_onGraphicClickCallback(t){t.viewEvent.stopPropagation();const e=t.graphic,i=this._isCurveControlPoint(e);if(e===this.graphic)this.clearSelection(),this.emit("graphic-click",t),this.callbacks.onGraphicClick?.(t);else if(this._isMidpoint(e)){if(2===t.viewEvent.button)return;const i=this.graphic.clone(),s=this._handleMidpointClickOrStartMove(t);this.refresh(),s.length&&this._emitVertexAddEvent([e],i,s)}else if(this._isVertex(e)||i){if(t.viewEvent.stopPropagation(),2===t.viewEvent.button)return void(i||this._removeVertices(e));t.viewEvent.native.shiftKey||this._clearSelection(),this.selectedManipulators.includes(e)?this._removeFromSelection(e,!0):this._addToSelection(e)}}_setUpOperation(t){const{graphic:e,dx:i,dy:s}=t,o=e===this.graphic;this._resetSnappingStateVars(),this._setUpGeometryHelper(),this._saveSnappingContextForHandle(e,t),this._activeOperationInfo={target:this.graphic,mover:e,operationType:o?"move":"reshape",totalDx:i,totalDy:s}}_onGraphicMoveStartCallback(t){const{dx:e,dy:i,graphic:s}=t,o=this._connectedReshapeManager,r=o?Vt(this.graphic):null;if(s===this.graphic){const{geometry:n}=s;return this._setUpOperation(t),this._emitMoveStartEvent(e,i),r&&o?.startFeatureMove([r]),void(null!=n&&"point"===n.type&&this._onHandleMove(s,e,i,t,()=>{this._updateTooltip(this.graphic,t.viewEvent),this._emitMoveEvent(e,i)}))}const{selectedManipulators:n}=this;if(!n.includes(s)){if(this._clearSelection(),this._isMidpoint(s)){const e=this.graphic.clone(),i=this._handleMidpointClickOrStartMove(t);i.length&&(this._emitVertexAddEvent([s],e,i),this._refreshGraphicIndicesAttributes(i[0]))}this._addToSelection(s)}if(this._setUpOperation(t),r){const t=n.filter(t=>this._isVertex(t));o?.startVertexMove(r,It(t))}this._emitReshapeStartEvent(s),this._onHandleMove(s,e,i,t,()=>{this._updateTooltip(s,t.viewEvent),this._emitReshapeEvent(s)})}_onGraphicMoveCallback(t){const e=this._activeOperationInfo;if(!e)return;const{dx:i,dy:s,graphic:o}=t;e.totalDx+=i,e.totalDy+=s;const{operationType:r}=e,{geometry:n}=o;if(null!=n)if("move"!==r)this._onHandleMove(o,i,s,t,()=>{this._updateTooltip(o,t.viewEvent),this._emitReshapeEvent(o)});else if("point"===n.type)this._onHandleMove(o,i,s,t,()=>{this._updateTooltip(this.graphic,t.viewEvent),this._emitMoveEvent(i,s)});else if("polyline"===n.type||"polygon"===n.type){const e=gt(n);this._updateVertexGraphicLocations(e);const{dxMap:o,dyMap:r}=U(i,s,this.view);this._connectedReshapeManager?.translate(o,r,0),this._updateTooltip(this.graphic,t.viewEvent),this._emitMoveEvent(i,s)}}_onGraphicMoveStopCallback(t){const e=this._activeOperationInfo;if(!e)return;const{dx:i,dy:s,graphic:o}=t,{operationType:r}=e;e.totalDx+=i,e.totalDy+=s,this._onHandleMove(o,i,s,t,()=>"move"===r?this._emitMoveStopEvent():this._emitReshapeStopEvent(o)),this._isMidpoint(o)||o.getAttribute(tt.curveFromStraightEdgeFlag)?this.refresh():(this._updateTooltip(this._isVertex(o)?o:null),this._resetSnappingStateVars(),this._connectedReshapeManager?.finish(),this._activeOperationInfo=null)}_updateVertexGraphicLocations(t){const{_coordinateHelper:e}=this;for(const i of this.vertexGraphics){const{pathIndex:s,pointIndex:o}=i.attributes;i.geometry=e.arrayToPoint(O(t[s][o]))}this._updateMidpointGraphicLocations(t),this._updateCurveGraphicLocations(t)}_updateMidpointGraphicLocations(t){const{_coordinateHelper:e}=this;for(const i of this.midpointGraphics){const{pathIndex:s,pointIndexStart:o,pointIndexEnd:r}=i.attributes,n=t[s];i.geometry=et(n[o],n[r],e)}}_updateCurveGraphicLocations(t){const{spatialReference:e}=this._coordinateHelper,i=new Map;for(const s of this.selectedManipulators){const[t,e]=Et(s);null!=t&&null!=e&&s.getAttribute(tt.controlPointKind)&&a(i,t,()=>new Set)?.add(e)}for(const s of this.curveControlPointGraphics){const[e,o]=Et(s);if(i.get(e)?.has(o))continue;const r=t[e][o];if(V(r)||I(r)){const i=O(t[e][o-1]),n=V(r)?E(i,r):R(i,r),[a,h]=S(n,.25);s.geometry=new g({x:a,y:h,spatialReference:this._coordinateHelper.spatialReference})}else if(P(r)){const t=s.getAttribute(tt.controlPointKind),[e,i]=t===it.bezier.cp1?r.b[1]:r.b[2];s.geometry=new g({x:e,y:i,spatialReference:this._coordinateHelper.spatialReference})}}for(const s of this.constructionLineGraphics){const i=s.getAttribute(tt.controlPointKind),[o,r]=Et(s),n=t[o],a=O(n[r-1]),h=O(n[r]),p=t[o][r];i===it.bezier.line1?s.geometry=new f({paths:[[[a[0],a[1]],[...p.b[1]]]],spatialReference:e}):s.geometry=new f({paths:[[[h[0],h[1]],[...p.b[2]]]],spatialReference:e})}}_refreshGraphicIndicesAttributes(t){const{componentIndex:e,vertexIndex:i}=t,s=t=>{const[s,o]=Et(t);s===e&&o>=i&&t.setAttribute(tt.pointIndex,o+1)};this.vertexGraphics.forEach(s),this.curveControlPointGraphics.forEach(s),this.constructionLineGraphics.forEach(s);for(const o of this.midpointGraphics){if(o.getAttribute(tt.pathIndex)!==e)continue;const t=o.getAttribute(tt.pointIndexStart);t>=i&&(o.setAttribute(tt.pointIndexStart,t+1),o.setAttribute(tt.pointIndexEnd,o.getAttribute(tt.pointIndexEnd)+1))}}_getVertexFromEditGeometry(t){const[e,i]=Et(t);return p(this._editGeometryOperations),this._editGeometryOperations.data.parts[e].vertices[i]}_onHandleMove(t,e,s,o,r){c(this._snappingTask);const n=this._snappingContext;if(!n)return;const a=t.geometry,h="graphic-move-stop"===o.type;if(a&&C(a))if(null!=this.snappingManager&&this.selectedManipulators.length<2&&!h){const o=this.snappingManager;this._stagedVertex=o.update({point:a,context:n}),this._syncGeometryAfterVertexMove(t,new g(this._stagedVertex),e,s,h),r(),this._snappingTask=i(async i=>{const p=await o.snap({point:a,context:n,signal:i});p.valid&&(this._stagedVertex=p.apply(),this._syncGeometryAfterVertexMove(t,new g(this._stagedVertex),e,s,h),r())})}else{const i=null!=this._stagedVertex?new g(this._stagedVertex):a;this._syncGeometryAfterVertexMove(t,i,e,s,h),r()}else r()}_syncGeometryAfterVertexMove(t,e,i,s,o=!1){const r=this._editGeometryOperations?.data.geometry;if(!r)return;const{_coordinateHelper:n}=this,a=n.pointToVector(e),h=this._getVertexFromEditGeometry(t);if(h){const t=n.getZ(a),e=a[0]-h.pos[0],i=a[1]-h.pos[1],s=null!=t?t-h.pos[2]:0;"point"!==r.type&&"mesh"!==r.type||this._editGeometryOperations?.moveVertices([h],e,i,s),this._connectedReshapeManager?.translate(e,i,s)}if("point"===r.type)t.geometry=e;else if("mesh"===r.type)t.geometry=r.centerAt(e);else{if(t!==this.graphic){const o=n.spatialReference,[a,h]=Et(t);let p=ft(r);const c=n.pointToArray(e);this._updateGeometryFromGraphic(t,p,a,h,c,o,"polygon"===r.type),this._isVertex(t)||this._isCurveControlPoint(t)?(p=this._moveRelatedCoordinates(p,t,c),p=this._moveSelectedHandleCoordinates(p,t,i,s,"polygon"===r.type),this._updateMidpointGraphicLocations(p),this._updateCurveGraphicLocations(p)):this._isMidpoint(t)&&this._updateCurveGraphicLocations(p),st(r,p)}this._updateGraphicGeometry(r.clone()),this._editGeometryOperations=lt.fromGeometry(r,2,{allowCurves:!0}),o&&(this._mover?this._mover.updateGeometry(this._mover.graphics.indexOf(t),e):t.geometry=e)}}_moveRelatedCoordinates(t,e,i){const{relatedGraphicIndices:s}=e.attributes,o=this._coordinateHelper.spatialReference;if(!s?.length)return t;for(const r of s){const s=this.vertexGraphics.at(r),[n,a]=Et(s);St(t,n,a,i,o),s.geometry=e.geometry}return t}_moveSelectedHandleCoordinates(t,e,i,s,o){const r=this._coordinateHelper.spatialReference;for(const n of this.selectedManipulators)if(n!==e){const[e,a]=Et(n),h=n.getAttribute(tt.relatedGraphicIndices),p=F(n.geometry,i,s,this.view),c=b(p);if(n.geometry=p,this._updateGeometryFromGraphic(n,t,e,a,c,r,o),h?.length)for(const i of h){const e=this.vertexGraphics.at(i),[s,o]=Et(e);St(t,s,o,c,r),e.geometry=p}}return t}_updateGeometryFromGraphic(t,e,i,s,o,r,n){const a=e[i].length-1;this._isCurveControlPoint(t)?xt(e,i,s,[o[0],o[1]],t.getAttribute(tt.controlPointKind)):(St(e,i,s,o,r),n&&(0===s?St(e,i,a,o,r):s===a&&(e[i][0]=o)))}_onGraphicPointerOverCallback(t){const e=t.graphic;this._hoverGraphic=e;const i=this._isVertex(e);i&&!this._isSelected(e)?e.symbol=this.symbols.vertices.hover:this._isCurveControlPoint(e)&&!this._isSelected(e)&&(e.symbol=this.symbols.controlPoints.hover),this._updateTooltip(i?e:null),this._updateHoverCursor(e)}_onGraphicPointerOutCallback(t){const e=t.graphic;this._hoverGraphic=null,this._isVertex(e)&&!this._isSelected(e)&&(e.symbol=this.symbols.vertices.default),this._isCurveControlPoint(e)&&!this._isSelected(e)&&(e.symbol=this.symbols.controlPoints.default),this.removeHandles(yt),this._updateTooltip()}_handleMidpointClickOrStartMove(t){const{graphic:e}=t,i=this.graphic.geometry;if(null==i||"polygon"!==i.type&&"polyline"!==i.type)return[];const s=i.clone(),o=[],{[tt.pathIndex]:r,[tt.pointIndexStart]:n,[tt.pointIndexEnd]:a}=e.attributes,h=b(e.geometry),p=0===a?n+1:a;e.attributes={[tt.tool]:ot,[tt.pathIndex]:r,[tt.pointIndex]:p,[tt.relatedGraphicIndices]:[]};const c=ft(s),l=c[r][a];if(k(l)){if(this.enableCurveOnMidpoint&&t.viewEvent.native.shiftKey){const t=O(c[r][p]);c[r].splice(p,1,{c:[t,[h[0],h[1]]]}),e.setAttribute(tt.controlPointKind,it.circle.interior),e.setAttribute(tt.curveFromStraightEdgeFlag,!0),this.midpointGraphics.remove(e),this.curveControlPointGraphics.push(e),st(s,c)}else c[r].splice(p,0,h),o.push({coordinates:c[r][p],componentIndex:r,vertexIndex:p})}else{const t=O(c[r][n]),e=rt(t,l,.5,this._coordinateHelper);c[r].splice(a,1,...e),o.push({coordinates:O(c[r][p]),componentIndex:r,vertexIndex:p})}return this._updateGraphicGeometry(s),o}_addToSelection(t){const e=Ot(t);for(const i of e)this._isCurveControlPoint(i)?i.symbol=this.symbols.controlPoints.selected:i.symbol=this.symbols.vertices.selected,this.selectedManipulators.add(i),this._updateTooltip(i);this._emitSelectEvent(e)}_removeFromSelection(t,e){if(this._isVertex(t)){const{vertices:i}=this.symbols;t.symbol=e?i.hover:i.default}else if(this._isCurveControlPoint(t)){const{controlPoints:i}=this.symbols;t.symbol=e?i.hover:i.default}this.selectedManipulators.remove(t),this._emitDeselectEvent([t]),this._updateTooltip()}_clearSelection(){const t=this.selectedManipulators.toArray(),{controlPoints:e,vertices:i}=this.symbols;if(t.length>0){for(const s of t)this._isVertex(s)?s.symbol=i.default:this._isCurveControlPoint(s)&&(s.symbol=e.default);this.selectedManipulators.removeAll(),this._emitDeselectEvent(t),this._updateTooltip()}}_keyDownHandler(t){null==this._activeOperationInfo&&ut(t,this.tooltip)||ct.delete.includes(t.key)&&!t.repeat&&this.selectedManipulators.length&&(this._removeVertices(this.selectedManipulators),t.stopPropagation())}_removeVertices(t){const e=this.graphic.geometry,i=this.vertexGraphics.length;if(null==e||"polygon"!==e.type&&"polyline"!==e.type&&"multipoint"!==e.type)return;if("polygon"===e.type&&i<4||"multipoint"===e.type&&i<2||"polyline"===e.type&&i<3)return;const s=this.graphic.clone(),o=e.clone();let r=ft(o);const n=[],a=Ot(t);for(const h of a){if(this._isCurveControlPoint(h))continue;const{x:t,y:e}=h.geometry;for(let i=0;i<r.length;i++){const s=r[i];for(let o=0;o<s.length;o++){const[a,h]=O(s[o]);if(t===a&&e===h){n.push({coordinates:O(r[i][o]),componentIndex:i,vertexIndex:o}),r[i].splice(Number(o),1);const t=r[i][o];t&&!k(t)&&(r[i][o]=O(t))}}}}if("polygon"===o.type)r=r.filter(t=>{if(t.length<2)return!1;const[e,i]=O(t[0]),[s,o]=O(t[t.length-1]);return(2!==t.length||e!==s||i!==o)&&(e===s&&i===o||t.push(t[0]),!0)});else if("polyline"===o.type)for(const h of r)1===h.length&&r.splice(r.indexOf(h),1);st(o,r),this._updateGraphicGeometry(o),this.refresh(),this._emitVertexRemoveEvent(a,s,n)}_isVertex(t){return this.vertexGraphics.includes(t)}_isCurveControlPoint(t){return this.curveControlPointGraphics.includes(t)}_isConstructionLine(t){return this.constructionLineGraphics.includes(t)}_isSelected(t){return(this._isVertex(t)||this.curveControlPointGraphics.includes(t))&&this.selectedManipulators.includes(t)}_isMidpoint(t){return this.midpointGraphics.includes(t)}_updateHoverCursor(t){const e=this._isMidpoint(t)?"copy":"move";this.addHandles(this.view.acquireCursor(e,"high"),yt)}_updateTooltip(t,e){let i=null;const{graphic:s,view:o,tooltipInfos:r}=this,n=s?.geometry;"point"===n?.type?i=r.movePoint:this._selectedManipulator?i=r.selectedVertex:t===this.graphic?(i=r.translateGraphic,$(i,o,this._tooltipsContext,e)):t&&this.selectedManipulators.length>1&&(i=r.translateVertices,B(i,o,n,this._tooltipsContext,e)),this.activeTooltipInfo=i}_updateGraphicGeometry(t){this._updateHandlesOnExternalGeometryChange?.pause(),this.graphic.geometry=t,this._updateHandlesOnExternalGeometryChange?.resume()}_emitMoveStartEvent(t,e){const i={type:"move-start",mover:this.graphic,dx:t,dy:e};this.emit("move-start",i),this.callbacks.onMoveStart?.(i)}_emitMoveEvent(t,e){const i={type:"move",mover:this.graphic,dx:t,dy:e};this.emit("move",i),this.callbacks.onMove?.(i)}_emitMoveStopEvent(t,e){if(null==t||null==e){const i=this._activeOperationInfo;if(!i)return;t=i.totalDx,e=i.totalDy}const i={type:"move-stop",mover:this.graphic,dx:t,dy:e};this.emit("move-stop",i),this.callbacks.onMoveStop?.(i)}_emitReshapeStartEvent(t){const e={type:"reshape-start",graphic:this.graphic,mover:t,selected:this.selectedManipulators.toArray()};this.emit("reshape-start",e),this.callbacks.onReshapeStart?.(e)}_emitReshapeEvent(t){const e={type:"reshape",graphic:this.graphic,mover:t,selected:this.selectedManipulators.toArray()};this.emit("reshape",e),this.callbacks.onReshape?.(e)}_emitReshapeStopEvent(t){const e={type:"reshape-stop",graphic:this.graphic,mover:t,selected:this.selectedManipulators.toArray()};this.emit("reshape-stop",e),this.callbacks.onReshapeStop?.(e)}_emitSelectEvent(t){const e={type:"vertex-select",added:t};this.emit("select",e),this.callbacks.onVertexSelect?.(e)}_emitDeselectEvent(t){const e={type:"vertex-deselect",removed:t};this.emit("deselect",e),this.callbacks.onVertexDeselect?.(e)}_emitVertexAddEvent(t,e,i){const s={type:"vertex-add",added:t,graphic:this.graphic,oldGraphic:e,vertices:i};this.emit("vertex-add",s),this.callbacks.onVertexAdd?.(s)}_emitVertexRemoveEvent(t,e,i){const s={type:"vertex-remove",removed:t,graphic:this.graphic,oldGraphic:e,vertices:i};this.emit("vertex-remove",s),this.callbacks.onVertexRemove?.(s)}_logGeometryTypeError(){n.getLogger(this).error(new o("reshape:invalid-geometry","Reshape operation not supported for the provided graphic. The geometry type is not supported."))}};function gt(t){const e=ft(t.clone());if("polygon"===t.type)for(const i of e){const t=i[i.length-1];if(!k(t))continue;const e=i[0];e[0]===t[0]&&e[1]===t[1]&&i.length>2&&i.pop()}return e}function ft(t){return"polygon"===t.type?t.curveRings?.slice()??t.rings.slice():"polyline"===t.type?t.curvePaths?.slice()??t.paths.slice():t.points.map(t=>[t])}function Gt(t,e,i,s){const o=t[e][i];if(V(o))o.c[1]=s;else if(I(o)){const o=O(t[e][i]);t[e][i]={c:[o,s]}}}function xt(t,e,i,s,o){switch(o){case it.circle.interior:Gt(t,e,i,s);break;case it.bezier.cp1:t[e][i].b[1]=s;break;case it.bezier.cp2:t[e][i].b[2]=s}}function Mt(t,e){return t<1e-8*e}function bt(t,{cx:e,cy:i,isInvalid:s,thetaStart:o,thetaEnd:r},n,a){const[h,p]=t,[c,l]=n,d=c-h,m=l-p;e-=h,i-=p;const v=a?o>r:o<r,[u,y]=s?[e,i]:v?[-i,e]:[i,-e],[_,g]=[d,m],[f,G]=[u,y],x=_*G-g*f,M=(d**2+m**2)/2;if(Mt(Math.abs(x),M))return[(h+c)/2,(p+l)/2];const[b,C]=[G/x*M,-f/x*M],S=b**2+C**2,[E,w]=[d/2-b,m/2-C];if(Mt(E**2+w**2,S)){const[t,e]=v?[-C,b]:[C,-b];return[t+b+h,e+C+p]}const O=Math.sqrt((b**2+C**2)/(E**2+w**2))*Math.sign(d*u+m*y);return[E*O+b+h,w*O+C+p]}function Ct(t,e,i){const s=G(new f({curvePaths:[[t,e]],spatialReference:i})),{curvePaths:o}=x(s,i),r=o[0][1];return H(r)?r:w(t,r)}function St(t,e,i,s,o){const r=t[e][i],n=t[e].at(i+1);if(nt(t,e)){const i=t[e][1];return t[e][0]=[...s],void(t[e][1]={a:[[...s],[...i.a[1]],0,0]})}if(at(t,e)){const i=t[e][1],[o,r]=i.a[1],[n,a]=s,h=Math.hypot(n-o,a-r),[p,c]=[n-o,a-r],l=T(c,p);return t[e][0]=[...s],void(t[e][1]={a:[[...s],[...i.a[1]],0,0,l,h,i.a[6]]})}const a=O(r);if(k(r))r.splice(0,r.length,...s);else if(P(r))r.b[0].splice(0,r.b[0].length,...s);else if(V(r)||I(r)){const o=O(t[e][i-1]),n=V(r)?E(o,r):R(o,r);t[e].splice(i,1,{c:[[...s],bt(o,n,s,!0)]})}else if(H(r)){r.a[0].splice(0,r.a[0].length,...s);const n=O(t[e][i-1]);r.a=Ct(n,r,o).a}if(n&&!k(n)&&!P(r))if(V(n)||I(n)){const o=O(n),r=V(n)?E(a,n):R(a,n);t[e].splice(i+1,1,{c:[o,bt(o,r,s,!1)]})}else if(H(n)){const t=O(r);n.a=Ct(t,n,o).a}}function Et({attributes:t}){return[t?.[tt.pathIndex]||0,t?.[tt.pointIndex]||0]}function wt({attributes:t}){return`${t?.[tt.pathIndex]}-${t?.[tt.pointIndex]}`}function Ot(t){return t instanceof e?[t]:[...t]}function Vt(t){const e=t.sourceLayer??t.layer;return N(e)?{graphic:t,layer:e}:null}function It(t){return t.toArray().map(({attributes:t})=>({pathIndex:t[tt.pathIndex],vertexIndex:t[tt.pointIndex]}))}t([y()],_t.prototype,"_activeOperationInfo",void 0),t([y()],_t.prototype,"_connectedReshapeManager",void 0),t([y()],_t.prototype,"_coordinateHelper",null),t([y()],_t.prototype,"_editGeometryOperations",void 0),t([y()],_t.prototype,"tooltip",void 0),t([y()],_t.prototype,"tooltipInfos",void 0),t([y()],_t.prototype,"activeTooltipInfo",void 0),t([y({constructOnly:!0})],_t.prototype,"automaticAreaMeasurementUtils",void 0),t([y({constructOnly:!0})],_t.prototype,"automaticLengthMeasurementUtils",void 0),t([y()],_t.prototype,"_selectedManipulator",null),t([y()],_t.prototype,"_tooltipsContext",null),t([y()],_t.prototype,"callbacks",void 0),t([y()],_t.prototype,"connectedReshapeProviders",void 0),t([y()],_t.prototype,"enableMidpoints",void 0),t([y()],_t.prototype,"enableCurveOnMidpoint",void 0),t([y()],_t.prototype,"enableMovement",void 0),t([y()],_t.prototype,"enableVertices",void 0),t([y()],_t.prototype,"graphic",void 0),t([y()],_t.prototype,"highlightName",void 0),t([y()],_t.prototype,"highlightsEnabled",void 0),t([y()],_t.prototype,"layer",void 0),t([y()],_t.prototype,"snappingManager",void 0),t([y({readOnly:!0})],_t.prototype,"state",null),t([y()],_t.prototype,"symbols",void 0),t([y({type:dt})],_t.prototype,"sketchOptions",void 0),t([y({readOnly:!0})],_t.prototype,"type",void 0),t([y({readOnly:!0})],_t.prototype,"vertexGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"curveControlPointGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"constructionLineGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"midpointGraphics",void 0),t([y({readOnly:!0})],_t.prototype,"selectedManipulators",void 0),t([y()],_t.prototype,"view",void 0),_t=t([_("esri.views.draw.support.Reshape")],_t);const Pt=_t;export{Pt 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 o}from"tslib";import r from"../../core/Accessor.js";import{property as e,subclass as t}from"../../core/accessorSupport/decorators.js";import s from"./gamepad/GamepadSettings.js";let p=class extends r{constructor(){super(...arguments),this.gamepad=new s}};o([e({readOnly:!0})],p.prototype,"gamepad",void 0),p=o([t("esri.views.input.Input")],p);const a=p;export{a as default};
5
+ import{__decorate as o}from"tslib";import r from"../../core/Accessor.js";import{property as e,subclass as t}from"../../core/accessorSupport/decorators.js";import s from"./gamepad/GamepadSettings.js";let p=class extends r{constructor(o){super(o),this.gamepad=new s}};o([e({readOnly:!0})],p.prototype,"gamepad",void 0),p=o([t("esri.views.input.Input")],p);const a=p;export{a 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 r from"../../core/Accessor.js";import{property as t}from"../../core/accessorSupport/decorators.js";class o extends r{constructor(){super(...arguments),this.sublayer=null}get updating(){return!1}get suspended(){return!1}get availableFields(){return[]}get filter(){return null}set filter(e){throw new Error("Not implemented")}queryFeatures(e,r){throw new Error("Not implemented")}queryObjectIds(e,r){throw new Error("Not implemented")}queryFeatureCount(e,r){throw new Error("Not implemented")}createQuery(){throw new Error("Not implemented")}queryExtent(e,r){throw new Error("Not implemented")}highlight(e){throw new Error("Not implemented")}}e([t()],o.prototype,"sublayer",void 0),e([t()],o.prototype,"availableFields",null),e([t()],o.prototype,"filter",null);export{o as default};
5
+ import{__decorate as e}from"tslib";import r from"../../core/Accessor.js";import{property as t}from"../../core/accessorSupport/decorators.js";class o extends r{constructor(e){super(e),this.sublayer=null}get updating(){return!1}get suspended(){return!1}get availableFields(){return[]}get filter(){return null}set filter(e){throw new Error("Not implemented")}queryFeatures(e,r){throw new Error("Not implemented")}queryObjectIds(e,r){throw new Error("Not implemented")}queryFeatureCount(e,r){throw new Error("Not implemented")}createQuery(){throw new Error("Not implemented")}queryExtent(e,r){throw new Error("Not implemented")}highlight(e){throw new Error("Not implemented")}}e([t()],o.prototype,"sublayer",void 0),e([t()],o.prototype,"availableFields",null),e([t()],o.prototype,"filter",null);export{o as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/5.0/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import{isSome as t}from"../../core/arrayUtils.js";import r from"../../core/Logger.js";import{abortMaybe as o}from"../../core/maybe.js";import{unwrapUpdating as i,updating as n,isUpdating as l}from"../../core/maybeUpdating.js";import{throwIfAbortError as s,throwIfNotAbortError as a}from"../../core/promiseUtils.js";import{whenOnce as m}from"../../core/reactiveUtils.js";import{property as p,subclass as y}from"../../core/accessorSupport/decorators.js";import{project as u,canProjectWithoutEngine as c,isLoaded as g,load as h}from"../../geometry/projectionUtils.js";import d from"./LayerView.js";let f=class extends d{constructor(){super(...arguments),this.layer=null,this.filter=null,this._geometryOperators=null,this._projectionEngineLoaded=!1,this._abortController=new AbortController}get availableFields(){return[]}get maximumNumberOfFeatures(){return 0}set maximumNumberOfFeatures(e){throw new Error("Not implemented")}get maximumNumberOfFeaturesExceeded(){return!1}get layerFilter(){return i(this._layerFilter)}get _layerFilter(){const e=this.layer?.filter;if(null==e||e.geometries.length<1)return null;if(!this._geometryOperators||!this._projectionEngineLoaded&&this._filterNeedsProjectionEngine)return n;const[o,i,l]=this._geometryOperators,s=e.geometries.at(0).spatialReference,a=e.geometries.toArray().map(e=>{let t;try{t=i.execute(e)}catch(o){return r.getLogger(this).warnOncePerTick("Failed to simplify scene filter mask polygon. Polygon will be ignored."),null}if(!t)return null;if(t.spatialReference.equals(s))return t;try{return u(t,s)}catch(o){return r.getLogger(this).warnOncePerTick("Failed to project scene filter mask polygon. Polygon will be ignored."),null}}).filter(t).sort((e,t)=>e.extent.xmin-t.extent.xmin),m=new Set,p=new Array,y=new Array;for(let t of a){const e=t.extent.xmin;if(p.length=0,m.forEach(r=>{if(e>=r.extent.xmax)return y.push(r),void m.delete(r);t.extent.ymin<=r.extent.ymax&&t.extent.ymax>=r.extent.ymin&&o.execute(t,r)&&p.push(r)}),p.length>0){let e;p.push(t);try{e=l.executeMany(p)}catch(c){r.getLogger(this).warnOncePerTick("Failed to unify filter mask polygons. Polygon will be ignored.");continue}p.pop(),e&&(p.forEach(e=>m.delete(e)),t=e)}m.add(t)}return m.forEach(e=>y.push(e)),y.length>0?{spatialRelationship:e.spatialRelationship,geometries:y}:null}get _filterNeedsProjectionEngine(){const e=this.layer.filter;if(null==e||e.geometries.length<=1)return!1;const t=e.geometries.at(0).spatialReference;return e.geometries.some(({spatialReference:e})=>!e.equals(t)&&!c(e,t))}get layerFilterUpdating(){return l(this._layerFilter)}initialize(){const{signal:e}=this._abortController;m(()=>this.destroyed||!this._geometryOperators&&this.layer?.filter?.geometries?.length,e).then(async()=>{s(e),this._geometryOperators=await Promise.all([import("../../geometry/operators/intersectsOperator.js"),import("../../geometry/operators/simplifyOperator.js"),import("../../geometry/operators/unionOperator.js")])}).catch(a),this._projectionEngineLoaded=g(),m(()=>this.destroyed||!this._projectionEngineLoaded&&this._filterNeedsProjectionEngine,e).then(async()=>{s(e),await h(),this._projectionEngineLoaded=!0}).catch(a)}destroy(){this._abortController=o(this._abortController)}highlight(e,t){throw new Error("Not implemented")}queryFeatures(e,t){throw new Error("Not implemented")}queryObjectIds(e,t){throw new Error("Not implemented")}queryFeatureCount(e,t){throw new Error("Not implemented")}createQuery(){throw new Error("Not implemented")}queryExtent(e,t){throw new Error("Not implemented")}};e([p()],f.prototype,"layer",void 0),e([p()],f.prototype,"availableFields",null),e([p()],f.prototype,"maximumNumberOfFeatures",null),e([p({readOnly:!0})],f.prototype,"maximumNumberOfFeaturesExceeded",null),e([p()],f.prototype,"filter",void 0),e([p({readOnly:!0})],f.prototype,"layerFilter",null),e([p({readOnly:!0})],f.prototype,"_layerFilter",null),e([p()],f.prototype,"_geometryOperators",void 0),e([p()],f.prototype,"_projectionEngineLoaded",void 0),e([p()],f.prototype,"_filterNeedsProjectionEngine",null),e([p()],f.prototype,"layerFilterUpdating",null),f=e([y("esri.views.layers.SceneLayerView")],f);export{f as default};
5
+ import{__decorate as e}from"tslib";import{isSome as t}from"../../core/arrayUtils.js";import r from"../../core/Logger.js";import{abortMaybe as o}from"../../core/maybe.js";import{unwrapUpdating as i,updating as n,isUpdating as l}from"../../core/maybeUpdating.js";import{throwIfAbortError as s,throwIfNotAbortError as a}from"../../core/promiseUtils.js";import{whenOnce as m}from"../../core/reactiveUtils.js";import{property as p,subclass as y}from"../../core/accessorSupport/decorators.js";import{project as u,canProjectWithoutEngine as c,isLoaded as g,load as h}from"../../geometry/projectionUtils.js";import d from"./LayerView.js";let f=class extends d{constructor(e){super(e),this.layer=null,this.filter=null,this._geometryOperators=null,this._projectionEngineLoaded=!1,this._abortController=new AbortController}get availableFields(){return[]}get maximumNumberOfFeatures(){return 0}set maximumNumberOfFeatures(e){throw new Error("Not implemented")}get maximumNumberOfFeaturesExceeded(){return!1}get layerFilter(){return i(this._layerFilter)}get _layerFilter(){const e=this.layer?.filter;if(null==e||e.geometries.length<1)return null;if(!this._geometryOperators||!this._projectionEngineLoaded&&this._filterNeedsProjectionEngine)return n;const[o,i,l]=this._geometryOperators,s=e.geometries.at(0).spatialReference,a=e.geometries.toArray().map(e=>{let t;try{t=i.execute(e)}catch(o){return r.getLogger(this).warnOncePerTick("Failed to simplify scene filter mask polygon. Polygon will be ignored."),null}if(!t)return null;if(t.spatialReference.equals(s))return t;try{return u(t,s)}catch(o){return r.getLogger(this).warnOncePerTick("Failed to project scene filter mask polygon. Polygon will be ignored."),null}}).filter(t).sort((e,t)=>e.extent.xmin-t.extent.xmin),m=new Set,p=new Array,y=new Array;for(let t of a){const e=t.extent.xmin;if(p.length=0,m.forEach(r=>{if(e>=r.extent.xmax)return y.push(r),void m.delete(r);t.extent.ymin<=r.extent.ymax&&t.extent.ymax>=r.extent.ymin&&o.execute(t,r)&&p.push(r)}),p.length>0){let e;p.push(t);try{e=l.executeMany(p)}catch(c){r.getLogger(this).warnOncePerTick("Failed to unify filter mask polygons. Polygon will be ignored.");continue}p.pop(),e&&(p.forEach(e=>m.delete(e)),t=e)}m.add(t)}return m.forEach(e=>y.push(e)),y.length>0?{spatialRelationship:e.spatialRelationship,geometries:y}:null}get _filterNeedsProjectionEngine(){const e=this.layer.filter;if(null==e||e.geometries.length<=1)return!1;const t=e.geometries.at(0).spatialReference;return e.geometries.some(({spatialReference:e})=>!e.equals(t)&&!c(e,t))}get layerFilterUpdating(){return l(this._layerFilter)}initialize(){const{signal:e}=this._abortController;m(()=>this.destroyed||!this._geometryOperators&&this.layer?.filter?.geometries?.length,e).then(async()=>{s(e),this._geometryOperators=await Promise.all([import("../../geometry/operators/intersectsOperator.js"),import("../../geometry/operators/simplifyOperator.js"),import("../../geometry/operators/unionOperator.js")])}).catch(a),this._projectionEngineLoaded=g(),m(()=>this.destroyed||!this._projectionEngineLoaded&&this._filterNeedsProjectionEngine,e).then(async()=>{s(e),await h(),this._projectionEngineLoaded=!0}).catch(a)}destroy(){this._abortController=o(this._abortController)}highlight(e,t){throw new Error("Not implemented")}queryFeatures(e,t){throw new Error("Not implemented")}queryObjectIds(e,t){throw new Error("Not implemented")}queryFeatureCount(e,t){throw new Error("Not implemented")}createQuery(){throw new Error("Not implemented")}queryExtent(e,t){throw new Error("Not implemented")}};e([p()],f.prototype,"layer",void 0),e([p()],f.prototype,"availableFields",null),e([p()],f.prototype,"maximumNumberOfFeatures",null),e([p({readOnly:!0})],f.prototype,"maximumNumberOfFeaturesExceeded",null),e([p()],f.prototype,"filter",void 0),e([p({readOnly:!0})],f.prototype,"layerFilter",null),e([p({readOnly:!0})],f.prototype,"_layerFilter",null),e([p()],f.prototype,"_geometryOperators",void 0),e([p()],f.prototype,"_projectionEngineLoaded",void 0),e([p()],f.prototype,"_filterNeedsProjectionEngine",null),e([p()],f.prototype,"layerFilterUpdating",null),f=e([y("esri.views.layers.SceneLayerView")],f);export{f 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"../../core/Error.js";import{makeHandle as i,handlesGroup as r,destroyHandle as a}from"../../core/handleUtils.js";import"../../core/has.js";import{destroyMaybe as o}from"../../core/maybe.js";import{debounce as s}from"../../core/promiseUtils.js";import{watch as n,on as l,whenOnce as p,initial as d}from"../../core/reactiveUtils.js";import{property as u,subclass as c}from"../../core/accessorSupport/decorators.js";import h from"../../layers/GraphicsLayer.js";import{isGraphicsLayer as m}from"../../layers/support/layerUtils.js";import{getDrawHelpMessage as y}from"../../views/draw/support/helpMessageUtils.js";import w from"../../views/draw/support/HighlightHelper.js";import f from"../../views/interactive/snapping/FeatureSnappingLayerSource.js";import{temporaryHighlightName as g}from"../../views/support/HighlightDefaults.js";import v from"./Edits.js";import _ from"./SplitFeatureWorkflowData.js";import F from"./Workflow.js";import{createWorkflowSteps as M,updateFeatureWorkflowInternalGraphicsLayerTitle as b,swapForEditingSession as S,updateGraphicSymbolWhenRequired as k,makeMinimalAttributes as G,whenGraphicDisplayed as T,whenEditorLayerView as V}from"./workflowUtils.js";import{assertViewNot3D as I,assertSplitWorkflowCapabilities as E}from"./support/errors.js";import{getCompatibleSpitterGeometryType as H,ensureSplittableGeometry as j,makeNewFeatureAttributes as x,splitGeometry as C,canSplitByPoint as L,isSplitterGeometry as U}from"./support/splitFeatureUtils.js";import W from"../FeatureForm/FeatureFormViewModel.js";import P from"../Sketch/SketchViewModel.js";import{getDrawToolGeometryTypeFromCreateTool as z}from"../Sketch/support/sketchUtils.js";var A;const O=Symbol(),D=Symbol();let R=A=class extends F{constructor(e){super(e),this.defaultSplitterGeometryType=null,this.type="split-feature",this._activeFeature=null,this._formViewModel=null,this._graphicsLayer=null,this._highlightHelper=null,this._lastSplitterGeometryWasInvalid=!1,this._sketchViewModel=null,this._webStyleCache=new Map}initialize(){const e=this.data.viewModel.view;this._highlightHelper=e?new w({view:e,highlightName:g}):null,this._initializeFormViewModel();const t=this._initializeGraphicsLayer();this._initializeSketchViewModel(t)}destroy(){const e=this._graphicsLayer,{view:t}=this.data.viewModel;t?.destroyed||t?.map.remove(e),this._graphicsLayer=o(this._graphicsLayer),this._formViewModel.destroy(),this._sketchViewModel.destroy(),this._highlightHelper?.destroy()}get activeFeature(){return this._activeFeature}get allowSave(){const{data:e}=this;return null!=e.existingFeatureEdits&&null!=e.newFeatureEdits&&!this.updating}get availableCreateTools(){const e=["polyline","polygon","rectangle","circle","freehandPolyline","freehandPolygon"];switch(this.data.editorItem.layer.geometryType){case"polygon":case"multipoint":return e;case"polyline":return["point",...e];default:return[]}}get formViewModel(){return this._formViewModel}get hasInvalidFormTemplate(){return!!this.data.editorItem?.hasInvalidFormTemplate}get hasPreviousStep(){return null!==this._activeFeature||this._stepIndex>0}get helpMessage(){const{activeCreateToolDrawMode:e,activeTool:t,createGraphic:i}=this._sketchViewModel,r=z(t);if("mesh"!==r)return y(r,i?.geometry,e)}get layer(){return this.data.editorItem.layer}get parent(){return this.data.parent}get updating(){return this._updatingHandles.updating||this._formViewModel.updating||this._sketchViewModel.updating}get noticeMessage(){return this._lastSplitterGeometryWasInvalid?"invalidSplitterGeometry":void 0}async back(e){return this.activeFeature?await this.setActiveFeature(null):await super.back(e)}static create(e){const{applyEdits:i,applyEditsFeatureService:r,defaultSplitterGeometryType:a,startAt:o,...s}=e;if(I(e.viewModel,"split-feature"),E(s.editorItem),"reviewing-features"===o){if(!s.splitterGeometry)throw new t("editing:split-geometry-required","Must provide the split geometry to start at the 'reviewing-features' step.");const e=H(j(s.feature.geometry),s.splitterGeometry.type);if(s.splitterGeometry.type!==e)throw new t("editing:incompatible-split-geometries",`Geometry of type '${s.splitterGeometry.type}' cannot be used to split geometry of type '${s.feature.geometry?.type}'.`)}const n=new A({data:new _(s),defaultSplitterGeometryType:a,onCommit:Z(e.applyEdits)});return n._set("steps",A._createWorkflowSteps(n,o)),n}async enter(){}exit(){if("reviewing-features"!==this.stepId)throw new t("editing:invalid-exit-state","The SplitFeatureWorkflow can only be exited when in the 'reviewing-features' step.")}async setActiveFeature(e){const i=this._activeFeature;if(e===i)return;const r=this.data,a=i?r.getEditsForFeature(i):null;if(a&&(a.submittable=this._formViewModel.submittable),this._activeFeature=e,null==e)return;const o=this.data.getRoleForFeature(e);if(!o)throw new t("editing:unknown-feature","The provided feature is not part of this workflow.");await this._setFeatureOnFormViewModel(e,o)}async start(){return await super.start(),this._makeSketchController()}async _createAndInitializeEdits({newPart:e,remainingPart:t}){const{data:i}=this,r=i.feature,a=this._formViewModel,o=r.clone();o.geometry=t;const s=new v({feature:o});i.existingFeatureEdits=s,s.trackChanges(i.initialFeature),await this._setFeatureOnFormViewModel(o,"existing"),s.submittable=a.submittable;const n=r.clone();n.geometry=e,n.attributes=x(r.attributes,i.editorItem.layer);const l=new v({feature:n});return i.newFeatureEdits=l,l.trackChanges(),await this._setFeatureOnFormViewModel(n,"new"),l.submittable=a.submittable,{featureToCreate:n,featureToUpdate:o}}static _createWorkflowSteps(e,i="drawing-splitter-geometry"){const{data:r}=e;return M(["drawing-splitter-geometry","reviewing-features"],i,{"drawing-splitter-geometry":()=>({id:"drawing-splitter-geometry",async setUp(){const i=j(r.feature.geometry),a=H(i,e.defaultSplitterGeometryType),{snappingManager:o}=r;L(i)&&o&&e.addHandles($(o,e.layer));const s=e._sketchViewModel;e.addHandles([l(()=>s,"create",async i=>{if("start"===i.state&&e._lastSplitterGeometryWasInvalid&&(e._lastSplitterGeometryWasInvalid=!1),"complete"===i.state){e._graphicsLayer.removeAll();const o=i.graphic?.geometry;try{if(!U(o))throw new t("editing:invalid-split-geometry","The geometry produced by the Sketch operation cannot be used for splitting.");r.splitterGeometry=o,r.splitResult=await e._updatingHandles.addPromise(e._executeSplit(o)),await e.next()}catch(a){e._lastSplitterGeometryWasInvalid=!0,await s.create(i.tool)}}}),n(()=>s.activeTool,(t,i)=>{"point"===t&&!e.hasHandles(O)&&o?e.addHandles(q(o,e.layer),O):"point"===i&&e.removeHandles(O)})],this.id),await s.create(a)},async tearDown(){e.removeHandles(this.id)}}),"reviewing-features":()=>({id:"reviewing-features",async setUp(){const i=r.splitterGeometry;if(!i)throw new t("editing:missing-splitter-geometry","The `splitterGeometry` property of the workflow's data must be set in order to start the 'reviewing-features' step.");const a=r.splitResult??await e._executeSplit(i),{featureToCreate:o,featureToUpdate:s}=await e._createAndInitializeEdits(a),n=await e._displayFeatureGraphics(s,o);e.addHandles(n,this.id)},async tearDown(){e.removeHandles(this.id)}})})}async _displayFeatureGraphics(e,t){const{data:a,_graphicsLayer:o}=this,l=a.viewModel.view,p=[];if(!e||!t||!l)return i();const d=s(i=>Promise.all([k(e,this._webStyleCache,i),k(t,this._webStyleCache,i)]));await d("2d"===l.type?l.scale:null),"2d"===l.type&&p.push(n(()=>l.scale,e=>d(e))),o.add(t),p.push(i(()=>o.remove(t)));const{feature:u}=a,c=u.layer,h=m(c)&&c.title===b&&c.internal?await J({editingGraphicsLayer:o,view:l,originalGraphicsLayer:c,editedGraphic:e}):await S(o,l,u,e);return p.push(h),r(p)}async _executeSplit(e){const{data:i}=this,{feature:r}=i,a=r.geometry;if(!a)throw new t("editing:feature-has-no-geometry","Cannot split the provided feature as it has no geometry.");const o=await C(a,e);if(!o||!o.newPart)throw new t("editing:split-failed","The split operation did not produce a valid result.");return o}_initializeFormViewModel(){const{data:e,_webStyleCache:t}=this,i=e.viewModel.view,r=new W({formTemplate:e.editorItem.formTemplate,highlightHelper:this._highlightHelper,map:i?.map,spatialReference:i?.spatialReference,timeZone:e.timeZone});this._formViewModel=r,this.addHandles(l(()=>r,"value-change",({feature:r,fieldName:a,value:o})=>{r&&(e.getEditsForFeature(r)?.setAttribute(a,o),k(r,t,i?.scale))}))}_initializeGraphicsLayer(){const{data:e}=this,{view:t}=e.viewModel,i=new h({elevationInfo:e.editorItem.layer.elevationInfo,internal:!0,listMode:"hide",title:"splitFeatureWorkflow-internal"});return this._graphicsLayer=i,t?.map.add(i),i}_initializeSketchViewModel(e){const{data:t}=this,{view:i}=t.viewModel;this._sketchViewModel=new P({layer:e,creationMode:"single",sketchOptions:t.sketchOptions,snappingManager:t.snappingManager,updateOnGraphicClick:!1,defaultUpdateOptions:{multipleSelectionEnabled:!1},view:i})}_makeSketchController(){return{enter:async()=>this.addHandles(B(this)),exit:()=>this.removeHandles(D),viewModel:this._sketchViewModel}}async _setFeatureOnFormViewModel(e,t){const{data:i}=this,r=this._formViewModel;r.feature=e,"existing"===t?(r.editType="UPDATE",r.overrideInitialFeature(i.initialFeature)):r.editType="INSERT",await p(()=>!r.updating)}get test(){}};e([u()],R.prototype,"activeFeature",null),e([u()],R.prototype,"allowSave",null),e([u()],R.prototype,"availableCreateTools",null),e([u()],R.prototype,"defaultSplitterGeometryType",void 0),e([u()],R.prototype,"formViewModel",null),e([u()],R.prototype,"hasInvalidFormTemplate",null),e([u()],R.prototype,"hasPreviousStep",null),e([u()],R.prototype,"helpMessage",null),e([u()],R.prototype,"layer",null),e([u()],R.prototype,"parent",null),e([u()],R.prototype,"type",void 0),e([u()],R.prototype,"updating",null),e([u()],R.prototype,"noticeMessage",null),e([u()],R.prototype,"_activeFeature",void 0),e([u()],R.prototype,"_formViewModel",void 0),e([u()],R.prototype,"_graphicsLayer",void 0),e([u()],R.prototype,"_highlightHelper",void 0),e([u()],R.prototype,"_lastSplitterGeometryWasInvalid",void 0),e([u()],R.prototype,"_sketchViewModel",void 0),R=A=e([c("esri.widgets.Editor.SplitFeatureWorkflow")],R);const N=R;function Z(e){return async i=>{const{existingFeatureEdits:r,newFeatureEdits:a}=i,o=r?.feature?.cloneShallow(),s=a?.feature?.cloneShallow(),n=i.editorItem.layer;if(null==o||null==s)throw new t("editing:missing-features","Expected both a feature to update and a feature to add for the split operation.");r?.attributesModified||(o.attributes=G(o,i.editorItem.layer)),await e(n,{addFeatures:[s],updateFeatures:[o]})}}function $(e,t){if(e.options.featureSources.some(e=>e.layer===t))return i();const r=new f({enabled:!1,layer:t});return e.options.featureSources.add(r),i(()=>{e.options.featureSources.remove(r),r.destroy()})}function q(e,t){const{options:r}=e,a=r.enabled;r.enabled=!0;const o=r.featureEnabled;r.featureEnabled=!0;const s=r.distance;r.distance=15;const n=new Map;for(const i of r.featureSources)n.set(i,i.enabled),i.layer===t?i.enabled=!0:i.enabled=!1;return i(()=>{r.enabled=a,r.featureEnabled=o,r.distance=s;for(const[e,t]of n)e.enabled=t})}function B(e){const t=e.data,{feature:o,viewModel:s}=t,{view:l}=s;if(!l)return i();const p=new w({view:l}),u=n(()=>e.stepId,e=>{switch(p.removeAll(),e){case"drawing-splitter-geometry":p.add(o);break;case"reviewing-features":p.add(t.existingFeatureEdits?.feature),p.add(t.newFeatureEdits?.feature)}},d),c=new w({view:l,highlightName:g}),h=n(()=>t.temporaryHighlightFeature,(t,i)=>{i&&i!==e.activeFeature&&c.remove(i),t&&c.add(t)}),m=n(()=>e.activeFeature,(e,i)=>{i&&i!==t.temporaryHighlightFeature&&c.remove(i),e&&c.add(e)});return r([u,h,m,a(p),a(c)])}async function J({editingGraphicsLayer:e,view:t,originalGraphicsLayer:a,editedGraphic:o}){function s(e){a.visible=e}return e.add(o),await T(t,o),s(!1),r([i(async()=>{s(!0);try{if(!t.destroyed){const e=await V(t,a).catch(()=>{});e&&!e.destroyed&&await p(()=>!e.updating)}}finally{e.remove(o)}})])}export{N as default};
5
+ import{__decorate as e}from"tslib";import t from"../../core/Error.js";import{makeHandle as i,handlesGroup as r,destroyHandle as a}from"../../core/handleUtils.js";import"../../core/has.js";import{destroyMaybe as o}from"../../core/maybe.js";import{debounce as s}from"../../core/promiseUtils.js";import{watch as l,on as n,whenOnce as p,initial as d}from"../../core/reactiveUtils.js";import{property as u,subclass as h}from"../../core/accessorSupport/decorators.js";import c from"../../layers/GraphicsLayer.js";import{getDrawHelpMessage as m}from"../../views/draw/support/helpMessageUtils.js";import w from"../../views/draw/support/HighlightHelper.js";import y from"../../views/interactive/snapping/FeatureSnappingLayerSource.js";import{temporaryHighlightName as f}from"../../views/support/HighlightDefaults.js";import g from"./Edits.js";import v from"./SplitFeatureWorkflowData.js";import _ from"./Workflow.js";import{createWorkflowSteps as F,swapForEditingSession as M,updateGraphicSymbolWhenRequired as S,makeMinimalAttributes as b}from"./workflowUtils.js";import{assertViewNot3D as k,assertSplitWorkflowCapabilities as T}from"./support/errors.js";import{getCompatibleSpitterGeometryType as V,ensureSplittableGeometry as G,makeNewFeatureAttributes as I,splitGeometry as E,canSplitByPoint as H,isSplitterGeometry as j}from"./support/splitFeatureUtils.js";import x from"../FeatureForm/FeatureFormViewModel.js";import C from"../Sketch/SketchViewModel.js";import{getDrawToolGeometryTypeFromCreateTool as U}from"../Sketch/support/sketchUtils.js";var W;const L=Symbol(),P=Symbol();let z=W=class extends _{constructor(e){super(e),this.defaultSplitterGeometryType=null,this.type="split-feature",this._activeFeature=null,this._formViewModel=null,this._graphicsLayer=null,this._highlightHelper=null,this._lastSplitterGeometryWasInvalid=!1,this._sketchViewModel=null,this._webStyleCache=new Map}initialize(){const e=this.data.viewModel.view;this._highlightHelper=e?new w({view:e,highlightName:f}):null,this._initializeFormViewModel();const t=this._initializeGraphicsLayer();this._initializeSketchViewModel(t)}destroy(){const e=this._graphicsLayer,{view:t}=this.data.viewModel;t?.destroyed||t?.map.remove(e),this._graphicsLayer=o(this._graphicsLayer),this._formViewModel.destroy(),this._sketchViewModel.destroy(),this._highlightHelper?.destroy()}get activeFeature(){return this._activeFeature}get allowSave(){const{data:e}=this;return null!=e.existingFeatureEdits&&null!=e.newFeatureEdits&&!this.updating}get availableCreateTools(){const e=["polyline","polygon","rectangle","circle","freehandPolyline","freehandPolygon"];switch(this.data.editorItem.layer.geometryType){case"polygon":case"multipoint":return e;case"polyline":return["point",...e];default:return[]}}get formViewModel(){return this._formViewModel}get hasInvalidFormTemplate(){return!!this.data.editorItem?.hasInvalidFormTemplate}get hasPreviousStep(){return null!==this._activeFeature||this._stepIndex>0}get helpMessage(){const{activeCreateToolDrawMode:e,activeTool:t,createGraphic:i}=this._sketchViewModel,r=U(t);if("mesh"!==r)return m(r,i?.geometry,e)}get layer(){return this.data.editorItem.layer}get parent(){return this.data.parent}get updating(){return this._updatingHandles.updating||this._formViewModel.updating||this._sketchViewModel.updating}get noticeMessage(){return this._lastSplitterGeometryWasInvalid?"invalidSplitterGeometry":void 0}async back(e){return this.activeFeature?await this.setActiveFeature(null):await super.back(e)}static create(e){const{applyEdits:i,applyEditsFeatureService:r,defaultSplitterGeometryType:a,startAt:o,...s}=e;if(k(e.viewModel,"split-feature"),T(s.editorItem),"reviewing-features"===o){if(!s.splitterGeometry)throw new t("editing:split-geometry-required","Must provide the split geometry to start at the 'reviewing-features' step.");const e=V(G(s.feature.geometry),s.splitterGeometry.type);if(s.splitterGeometry.type!==e)throw new t("editing:incompatible-split-geometries",`Geometry of type '${s.splitterGeometry.type}' cannot be used to split geometry of type '${s.feature.geometry?.type}'.`)}const l=new W({data:new v(s),defaultSplitterGeometryType:a,onCommit:O(e.applyEdits)});return l._set("steps",W._createWorkflowSteps(l,o)),l}async enter(){}exit(){if("reviewing-features"!==this.stepId)throw new t("editing:invalid-exit-state","The SplitFeatureWorkflow can only be exited when in the 'reviewing-features' step.")}async setActiveFeature(e){const i=this._activeFeature;if(e===i)return;const r=this.data,a=i?r.getEditsForFeature(i):null;if(a&&(a.submittable=this._formViewModel.submittable),this._activeFeature=e,null==e)return;const o=this.data.getRoleForFeature(e);if(!o)throw new t("editing:unknown-feature","The provided feature is not part of this workflow.");await this._setFeatureOnFormViewModel(e,o)}async start(){return await super.start(),this._makeSketchController()}async _createAndInitializeEdits({newPart:e,remainingPart:t}){const{data:i}=this,r=i.feature,a=this._formViewModel,o=r.clone();o.geometry=t;const s=new g({feature:o});i.existingFeatureEdits=s,s.trackChanges(i.initialFeature),await this._setFeatureOnFormViewModel(o,"existing"),s.submittable=a.submittable;const l=r.clone();l.geometry=e,l.attributes=I(r.attributes,i.editorItem.layer);const n=new g({feature:l});return i.newFeatureEdits=n,n.trackChanges(),await this._setFeatureOnFormViewModel(l,"new"),n.submittable=a.submittable,{featureToCreate:l,featureToUpdate:o}}static _createWorkflowSteps(e,i="drawing-splitter-geometry"){const{data:r}=e;return F(["drawing-splitter-geometry","reviewing-features"],i,{"drawing-splitter-geometry":()=>({id:"drawing-splitter-geometry",async setUp(){const i=G(r.feature.geometry),a=V(i,e.defaultSplitterGeometryType),{snappingManager:o}=r;H(i)&&o&&e.addHandles(D(o,e.layer));const s=e._sketchViewModel;e.addHandles([n(()=>s,"create",async i=>{if("start"===i.state&&e._lastSplitterGeometryWasInvalid&&(e._lastSplitterGeometryWasInvalid=!1),"complete"===i.state){e._graphicsLayer.removeAll();const o=i.graphic?.geometry;try{if(!j(o))throw new t("editing:invalid-split-geometry","The geometry produced by the Sketch operation cannot be used for splitting.");r.splitterGeometry=o,r.splitResult=await e._updatingHandles.addPromise(e._executeSplit(o)),await e.next()}catch(a){e._lastSplitterGeometryWasInvalid=!0,await s.create(i.tool)}}}),l(()=>s.activeTool,(t,i)=>{"point"===t&&!e.hasHandles(L)&&o?e.addHandles(R(o,e.layer),L):"point"===i&&e.removeHandles(L)})],this.id),await s.create(a)},async tearDown(){e.removeHandles(this.id)}}),"reviewing-features":()=>({id:"reviewing-features",async setUp(){const i=r.splitterGeometry;if(!i)throw new t("editing:missing-splitter-geometry","The `splitterGeometry` property of the workflow's data must be set in order to start the 'reviewing-features' step.");const a=r.splitResult??await e._executeSplit(i),{featureToCreate:o,featureToUpdate:s}=await e._createAndInitializeEdits(a),l=await e._displayFeatureGraphics(s,o);e.addHandles(l,this.id)},async tearDown(){e.removeHandles(this.id)}})})}async _displayFeatureGraphics(e,t){const{data:a,_graphicsLayer:o}=this,n=a.viewModel.view,p=[];if(!e||!t||!n)return i();const d=s(i=>Promise.all([S(e,this._webStyleCache,i),S(t,this._webStyleCache,i)]));return await d("2d"===n.type?n.scale:null),"2d"===n.type&&p.push(l(()=>n.scale,e=>d(e))),o.add(t),p.push(i(()=>o.remove(t))),p.push(await M(o,n,a.feature,e)),r(p)}async _executeSplit(e){const{data:i}=this,{feature:r}=i,a=r.geometry;if(!a)throw new t("editing:feature-has-no-geometry","Cannot split the provided feature as it has no geometry.");const o=await E(a,e);if(!o||!o.newPart)throw new t("editing:split-failed","The split operation did not produce a valid result.");return o}_initializeFormViewModel(){const{data:e,_webStyleCache:t}=this,i=e.viewModel.view,r=new x({formTemplate:e.editorItem.formTemplate,highlightHelper:this._highlightHelper,map:i?.map,spatialReference:i?.spatialReference,timeZone:e.timeZone});this._formViewModel=r,this.addHandles(n(()=>r,"value-change",({feature:r,fieldName:a,value:o})=>{r&&(e.getEditsForFeature(r)?.setAttribute(a,o),S(r,t,i?.scale))}))}_initializeGraphicsLayer(){const{data:e}=this,{view:t}=e.viewModel,i=new c({elevationInfo:e.editorItem.layer.elevationInfo,internal:!0,listMode:"hide",title:"splitFeatureWorkflow-internal"});return this._graphicsLayer=i,t?.map.add(i),i}_initializeSketchViewModel(e){const{data:t}=this,{view:i}=t.viewModel;this._sketchViewModel=new C({layer:e,creationMode:"single",sketchOptions:t.sketchOptions,snappingManager:t.snappingManager,updateOnGraphicClick:!1,defaultUpdateOptions:{multipleSelectionEnabled:!1},view:i})}_makeSketchController(){return{enter:async()=>this.addHandles(N(this)),exit:()=>this.removeHandles(P),viewModel:this._sketchViewModel}}async _setFeatureOnFormViewModel(e,t){const{data:i}=this,r=this._formViewModel;r.feature=e,"existing"===t?(r.editType="UPDATE",r.overrideInitialFeature(i.initialFeature)):r.editType="INSERT",await p(()=>!r.updating)}get test(){}};e([u()],z.prototype,"activeFeature",null),e([u()],z.prototype,"allowSave",null),e([u()],z.prototype,"availableCreateTools",null),e([u()],z.prototype,"defaultSplitterGeometryType",void 0),e([u()],z.prototype,"formViewModel",null),e([u()],z.prototype,"hasInvalidFormTemplate",null),e([u()],z.prototype,"hasPreviousStep",null),e([u()],z.prototype,"helpMessage",null),e([u()],z.prototype,"layer",null),e([u()],z.prototype,"parent",null),e([u()],z.prototype,"type",void 0),e([u()],z.prototype,"updating",null),e([u()],z.prototype,"noticeMessage",null),e([u()],z.prototype,"_activeFeature",void 0),e([u()],z.prototype,"_formViewModel",void 0),e([u()],z.prototype,"_graphicsLayer",void 0),e([u()],z.prototype,"_highlightHelper",void 0),e([u()],z.prototype,"_lastSplitterGeometryWasInvalid",void 0),e([u()],z.prototype,"_sketchViewModel",void 0),z=W=e([h("esri.widgets.Editor.SplitFeatureWorkflow")],z);const A=z;function O(e){return async i=>{const{existingFeatureEdits:r,newFeatureEdits:a}=i,o=r?.feature?.cloneShallow(),s=a?.feature?.cloneShallow(),l=i.editorItem.layer;if(null==o||null==s)throw new t("editing:missing-features","Expected both a feature to update and a feature to add for the split operation.");r?.attributesModified||(o.attributes=b(o,i.editorItem.layer)),await e(l,{addFeatures:[s],updateFeatures:[o]})}}function D(e,t){if(e.options.featureSources.some(e=>e.layer===t))return i();const r=new y({enabled:!1,layer:t});return e.options.featureSources.add(r),i(()=>{e.options.featureSources.remove(r),r.destroy()})}function R(e,t){const{options:r}=e,a=r.enabled;r.enabled=!0;const o=r.featureEnabled;r.featureEnabled=!0;const s=r.distance;r.distance=15;const l=new Map;for(const i of r.featureSources)l.set(i,i.enabled),i.layer===t?i.enabled=!0:i.enabled=!1;return i(()=>{r.enabled=a,r.featureEnabled=o,r.distance=s;for(const[e,t]of l)e.enabled=t})}function N(e){const t=e.data,{feature:o,viewModel:s}=t,{view:n}=s;if(!n)return i();const p=new w({view:n}),u=l(()=>e.stepId,e=>{switch(p.removeAll(),e){case"drawing-splitter-geometry":p.add(o);break;case"reviewing-features":p.add(t.existingFeatureEdits?.feature),p.add(t.newFeatureEdits?.feature)}},d),h=new w({view:n,highlightName:f}),c=l(()=>t.temporaryHighlightFeature,(t,i)=>{i&&i!==e.activeFeature&&h.remove(i),t&&h.add(t)}),m=l(()=>e.activeFeature,(e,i)=>{i&&i!==t.temporaryHighlightFeature&&h.remove(i),e&&h.add(e)});return r([u,c,m,a(p),a(h)])}export{A as default};