@arcgis/core 4.34.0-next.30 → 4.34.0-next.32

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 (83) hide show
  1. package/WebScene.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/0ca8d6516323fc28dd58.js +1 -0
  4. package/assets/esri/core/workers/chunks/{031c4b4bf78079d0002d.js → 36024406932b0a44a74a.js} +1 -1
  5. package/assets/esri/core/workers/chunks/{4e267a813e8b10d10b3b.js → 37bfc1a771792b6697fd.js} +121 -140
  6. package/assets/esri/core/workers/chunks/42c5d957813080143e5a.js +1 -0
  7. package/assets/esri/core/workers/chunks/6269c4bbf0f224a954e9.js +1 -0
  8. package/assets/esri/core/workers/chunks/871da12fb3029177df6f.js +1 -0
  9. package/assets/esri/core/workers/chunks/8abcf9d3343dd8d45103.js +1 -0
  10. package/assets/esri/core/workers/chunks/ac88e0aabbd6c1f1ec98.js +1 -0
  11. package/assets/esri/core/workers/chunks/{e7209654ecdfde926272.js → eec36628e638e244f452.js} +1 -1
  12. package/chunks/ComponentShader.glsl.js +34 -33
  13. package/chunks/DefaultMaterial.glsl.js +25 -25
  14. package/chunks/Path.glsl.js +20 -24
  15. package/chunks/RealisticTree.glsl.js +18 -20
  16. package/chunks/Terrain.glsl.js +32 -33
  17. package/chunks/WaterSurface.glsl.js +16 -16
  18. package/config.js +1 -1
  19. package/core/workers/registry.js +1 -1
  20. package/interfaces.d.ts +22 -25
  21. package/kernel.js +1 -1
  22. package/layers/MapImageLayer.js +1 -1
  23. package/package.json +1 -1
  24. package/portal/schemas/definitions.js +1 -1
  25. package/support/revision.js +1 -1
  26. package/views/2d/layers/support/MediaLayerInteraction.js +1 -1
  27. package/views/3d/environment/Precipitation.js +1 -1
  28. package/views/3d/interactive/measurementTools/areaMeasurement3D/AreaMeasurement3DView.js +1 -1
  29. package/views/3d/interactive/measurementTools/directLineMeasurement3D/DirectLineMeasurement3DView.js +1 -1
  30. package/views/3d/layers/FlowSubView3D.js +1 -1
  31. package/views/3d/layers/I3SMeshView3D.js +1 -1
  32. package/views/3d/layers/MapImageLayerView3D.js +1 -1
  33. package/views/3d/layers/MediaLayerView3D.js +1 -1
  34. package/views/3d/layers/graphics/Labeler.js +1 -1
  35. package/views/3d/layers/support/MediaLayerInteraction.js +1 -1
  36. package/views/3d/state/helpers/SceneIntersectionHelper.js +1 -1
  37. package/views/3d/support/engineContent/line.js +1 -1
  38. package/views/3d/support/flow/FlowSubViewExtent3D.js +1 -1
  39. package/views/3d/support/flow/FlowSubViewTiles3D.js +1 -1
  40. package/views/3d/support/flow/FlowWorker.js +5 -0
  41. package/views/3d/support/flow/FlowWorkerHandle.js +5 -0
  42. package/views/3d/support/flow/geometryUtils.js +1 -1
  43. package/views/3d/support/flow/loadUtils.js +1 -1
  44. package/views/3d/support/hitTest.js +1 -1
  45. package/views/3d/webgl-engine/collections/Component/Material/shader/ComponentShader.glsl.js +1 -1
  46. package/views/3d/webgl-engine/core/material/RenderTexture.js +1 -1
  47. package/views/3d/webgl-engine/core/shaderLibrary/ForwardLinearDepth.glsl.js +3 -5
  48. package/views/3d/webgl-engine/core/shaderLibrary/ForwardLinearDepthToReadShadowMap.glsl.js +7 -0
  49. package/views/3d/webgl-engine/core/shaderLibrary/ForwardLinearDepthToWriteShadowMap.glsl.js +11 -0
  50. package/views/3d/webgl-engine/core/shaderLibrary/Transform.glsl.js +1 -1
  51. package/views/3d/webgl-engine/core/shaderLibrary/default/DefaultMaterialAuxiliaryPasses.glsl.js +1 -1
  52. package/views/3d/webgl-engine/core/shaderLibrary/shading/ReadShadowMap.glsl.js +6 -2
  53. package/views/3d/webgl-engine/lib/TextureRepository.js +1 -1
  54. package/views/3d/webgl-engine/lib/TextureUpdater.js +1 -1
  55. package/views/3d/webgl-engine/lib/lodRendering/LodRenderer.js +1 -1
  56. package/views/3d/webgl-engine/materials/WaterMaterial.js +1 -1
  57. package/views/3d/webgl-engine/parts/RenderView.js +1 -1
  58. package/views/3d/webgl-engine/shaders/DefaultMaterial.glsl.js +1 -1
  59. package/views/3d/webgl-engine/shaders/Path.glsl.js +1 -1
  60. package/views/3d/webgl-engine/shaders/RealisticTree.glsl.js +1 -1
  61. package/views/3d/webgl-engine/shaders/Terrain.glsl.js +1 -1
  62. package/views/3d/webgl-engine/shaders/WaterSurface.glsl.js +1 -1
  63. package/views/SceneView.js +1 -1
  64. package/views/View.js +1 -1
  65. package/views/draw/support/Box.js +1 -1
  66. package/views/draw/support/Reshape.js +1 -1
  67. package/views/webgl/RenderingContext.js +1 -1
  68. package/views/webgl/Util.js +1 -1
  69. package/views/webgl/checkWebGLError.js +1 -1
  70. package/views/webgl/testFloatBufferBlend.js +1 -1
  71. package/widgets/CoordinateConversion/CoordinateConversionViewModel.js +1 -1
  72. package/widgets/Editor/workflowUtils.js +1 -1
  73. package/widgets/ElevationProfile/ElevationProfileInteraction.js +1 -1
  74. package/widgets/ElevationProfile/ElevationProfileLineView.js +1 -1
  75. package/widgets/Feature/support/arcadeFeatureUtils.js +1 -1
  76. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  77. package/widgets/Sketch/SketchViewModel.js +1 -1
  78. package/widgets/UtilityNetworkTrace.js +1 -1
  79. package/assets/esri/core/workers/chunks/278df50f2c557be81808.js +0 -1
  80. package/assets/esri/core/workers/chunks/2931fd6bb123200622c2.js +0 -1
  81. package/assets/esri/core/workers/chunks/4cf2894bda9e38af8790.js +0 -1
  82. package/assets/esri/core/workers/chunks/6a0777cf1270fcab4574.js +0 -1
  83. package/assets/esri/core/workers/chunks/9723512bc9db4a301c72.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as e}from"tslib";import t from"../../../Graphic.js";import{createTask as i}from"../../../core/asyncUtils.js";import s from"../../../core/Collection.js";import o from"../../../core/Error.js";import r from"../../../core/Evented.js";import n from"../../../core/Logger.js";import{destroyMaybe as h,assertIsSome as a,abortMaybe as p}from"../../../core/maybe.js";import{pausable as c,when as l,watch as d,initial as m,sync as v}from"../../../core/reactiveUtils.js";import{property as y}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/RandomLCG.js";import{subclass as _}from"../../../core/accessorSupport/decorators/subclass.js";import g from"../../../geometry/Point.js";import u from"../../../geometry/Polyline.js";import{closeRingsAndFixWinding as f,getMidpoint as x,geometryToCoordinates as G}from"../../../geometry/support/coordsUtils.js";import M from"../../../layers/GraphicsLayer.js";import b from"../../../symbols/SimpleMarkerSymbol.js";import{SnappingVisualizer2D as V}from"../../2d/interactive/SnappingVisualizer2D.js";import{ConnectedReshapeManager as w}from"./ConnectedReshapeManager.js";import{cloneMove as S}from"./drawUtils.js";import E from"./GraphicMover.js";import I from"./HighlightHelper.js";import{addUniqueLayer as O,isConnectedReshapeSupportedLayer as C}from"./layerUtils.js";import{createTooltipInfos as k,connectTooltip as T,updateTranslateTooltipInfo as R,updateTranslateVertexTooltipInfo as H}from"./reshapeTooltipUtils.js";import{settings as j}from"./settings.js";import{ViewEventPriorities as A}from"../../input/InputManager.js";import{createCoordinateHelper as U}from"../../interactive/coordinateHelper.js";import{sketchKeys as L}from"../../interactive/keybindings.js";import{EditGeometryOperations as P}from"../../interactive/editGeometry/EditGeometryOperations.js";import z from"../../interactive/sketch/SketchOptions.js";import{SnappingContext as D}from"../../interactive/snapping/SnappingContext.js";import{makeTooltip as F,enterInputModeIfAvailable as N}from"../../interactive/tooltip/tooltipCommonUtils.js";class Z{constructor(e,t,i){this.graphic=e,this.mover=t,this.selected=i,this.type="reshape-start"}}class X{constructor(e,t,i){this.graphic=e,this.mover=t,this.selected=i,this.type="reshape"}}class Y{constructor(e,t,i){this.graphic=e,this.mover=t,this.selected=i,this.type="reshape-stop"}}class K{constructor(e,t,i){this.mover=e,this.dx=t,this.dy=i,this.type="move-start"}}class q{constructor(e,t,i){this.mover=e,this.dx=t,this.dy=i,this.type="move"}}class B{constructor(e,t,i){this.mover=e,this.dx=t,this.dy=i,this.type="move-stop"}}class J{constructor(e){this.added=e,this.type="vertex-select"}}class Q{constructor(e){this.removed=e,this.type="vertex-deselect"}}class W{constructor(e,t,i,s){this.added=e,this.graphic=t,this.oldGraphic=i,this.vertices=s,this.type="vertex-add"}}class ${constructor(e,t,i,s){this.removed=e,this.graphic=t,this.oldGraphic=i,this.vertices=s,this.type="vertex-remove"}}const ee=j.reshapeGraphics,te={vertices:{default:new b({style:"circle",size:ee.vertex.size,color:ee.vertex.color,outline:{color:ee.vertex.outlineColor,width:1}}),hover:new b({style:"circle",size:ee.vertex.hoverSize,color:ee.vertex.hoverColor,outline:{color:ee.vertex.hoverOutlineColor,width:1}}),selected:new b({style:"circle",size:ee.selected.size,color:ee.selected.color,outline:{color:ee.selected.outlineColor,width:1}})},midpoints:{default:new b({style:"circle",size:ee.midpoint.size,color:ee.midpoint.color,outline:{color:ee.midpoint.outlineColor,width:1}}),hover:new b({style:"circle",size:ee.midpoint.size,color:ee.midpoint.color,outline:{color:ee.midpoint.outlineColor,width:1}})}};let ie=class extends r.EventedAccessor{constructor(e){super(e),this._updateHandlesOnExternalGeometryChange=null,this._activeOperationInfo=null,this._connectedReshapeManager=null,this._editGeometryOperations=null,this._graphicAttributes={esriSketchTool:"box"},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=[],this.enableMidpoints=!0,this.enableMovement=!0,this.enableVertices=!0,this.graphic=null,this.highlightName=null,this.highlightsEnabled=!0,this.layer=null,this.midpointGraphics=new s,this.midpointSymbol=new b({style:"circle",size:6,color:[200,200,200],outline:{color:[100,100,100],width:1}}),this.selectedVertices=new s,this.snappingManager=null,this.symbols=te,this.sketchOptions=new z,this.type="reshape",this.vertexGraphics=new s,this.view=null}initialize(){const e=this.view;this._highlightHelper=new I({view:e}),this._setup(),this._updateHandlesOnExternalGeometryChange=c(()=>this.graphic?.geometry,e=>{if(!e)return;const t=new Set(this.selectedVertices.map(e=>e.attributes?.pointIndex));this._highlightHelper.removeAll(),this._setUpHighlights(),this._setupGraphics(),this._clearSelection(),this.vertexGraphics.filter(e=>t.has(e.attributes.pointIndex)).forEach(e=>this._addToSelection(e));const{enableMovement:i,_mover:s,graphic:o,midpointGraphics:r,vertexGraphics:n}=this,h=n.concat(r).items;i&&h.push(o),s?.set("graphics",h)},v),this.tooltip=F(()=>({view:e,options:this.sketchOptions.tooltips})),this.tooltipInfos=k(this.sketchOptions),this.addHandles([l(()=>e?.ready,()=>{const{layer:e,view:t}=this;O(t,e),this.addHandles(t.on("key-down",e=>this._keyDownHandler(e),A.TOOL))},{once:!0,initial:!0}),d(()=>this.graphic,()=>this.refresh()),d(()=>this.layer,(e,t)=>{t&&(this._clearSelection(),this._resetGraphics(t)),this.refresh()}),d(()=>[this.highlightsEnabled,this.highlightName],()=>{this._highlightHelper?.removeAll(),this._setUpHighlights()}),d(()=>this.enableMidpoints,()=>this.refresh()),T(this.tooltip,()=>this._tooltipsContext),d(()=>this.view.effectiveTheme.accentColor,()=>this._updateSymbolsForTheme(),m),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??U(!!this.graphic.geometry?.hasZ,!!this.graphic.geometry?.hasM,this.view.spatialReference)}get _selectedVertex(){return 1===this.selectedVertices.length?this.selectedVertices.at(0):void 0}get _tooltipsContext(){const{automaticAreaMeasurementUtils:e,automaticLengthMeasurementUtils:t,sketchOptions:i,activeTooltipInfo:s,graphic:o}=this;return{sketchOptions:i,activeTooltipInfo:s,graphic:o,selectedVertex:this._selectedVertex,automaticAreaMeasurementUtils:e,automaticLengthMeasurementUtils:t,updateGeometry:(e,t,i,s,o)=>{this._setUpGeometryHelper();const r=e===this.graphic;r?this._emitMoveStartEvent(0,0):this._emitReshapeStartEvent(e);const n=!0;if(this._syncGeometryAfterVertexMove(e,t,s,o,n),r){const{view:e}=this,s=e.toScreen(i),o=e.toScreen(t),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(e),this._emitReshapeStopEvent(e);this._editGeometryOperations=h(this._editGeometryOperations)}}}get state(){const e=this.view.ready,t=!(!this.graphic||!this.layer);return e&&t?"active":e?"ready":"disabled"}isUIGraphic(e){const t=[];return this.graphic&&t.push(this.graphic),t.concat(this.vertexGraphics.items,this.midpointGraphics.items),t.length>0&&t.includes(e)}refresh(){this._reset(),this._setup()}reset(){this.graphic=null}clearSelection(){this._clearSelection()}removeSelectedVertices(){const{selectedVertices:e}=this;e.length&&this._removeVertices(e)}_setup(){const{graphic:e,layer:t}=this;if(!t||null==e?.geometry)return;const i=e.geometry;"mesh"!==i.type&&"extent"!==i.type?("polygon"===i.type&&f(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 e=this.graphic.geometry;if(null==e||"mesh"===e.type||"extent"===e.type)return void this._logGeometryTypeError();const t="multipoint"===e.type?new u({paths:[e.points],spatialReference:e.spatialReference}):e;this._editGeometryOperations=P.fromGeometry(t,2)}_saveSnappingContextForHandle(e,t){this._snappingGraphicsLayer=new M({listMode:"hide",internal:!0,title:"Reshape snapping layer"}),this.view.map.layers.add(this._snappingGraphicsLayer);const i=this._editGeometryOperations;a(i),this._snappingContext=new D({editGeometryOperations:i,elevationInfo:{mode:"on-the-ground",offset:0},pointer:t.viewEvent?.pointerType||"mouse",excludeFeature:this.graphic,feature:this.graphic,visualizer:new V(this._snappingGraphicsLayer),vertexHandle:this._getVertexFromEditGeometry(e)})}_reset(){this._clearSelection(),this._highlightHelper?.removeAll(),this._updateTooltip(),this._resetGraphics(),this._resetSnappingStateVars(),this._activeOperationInfo=null,this._mover&&this._mover.destroy(),this._mover=null,this.view.cursor="default"}_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=p(this._snappingTask),this._snappingTask=null,this._snappingContext=null,this._stagedVertex=null}_resetGraphics(e){this._removeMidpointGraphics(e),this._removeVertexGraphics(e),this.selectedVertices.removeAll(),this._updateTooltip()}_removeMidpointGraphics(e){const t=e||this.layer;t&&t.removeMany(this.midpointGraphics.items),this.midpointGraphics.items.forEach(e=>e.destroy()),this.midpointGraphics.removeAll()}_removeVertexGraphics(e){const t=e||this.layer;t&&t.removeMany(this.vertexGraphics.items),this.vertexGraphics.items.forEach(e=>e.destroy()),this.vertexGraphics.removeAll()}_setupGraphics(){const e=this.graphic.geometry;if(null!=e&&("polyline"===e.type||"polygon"===e.type)){const t=se(e);this.enableMidpoints&&this._setUpMidpointGraphics(t),this.enableVertices&&this._setUpVertexGraphics(t)}}_setUpMidpointGraphics(e){this._removeMidpointGraphics();const t=this._createMidpointGraphics(e);this.midpointGraphics.addMany(t),this.layer.addMany(t)}_setUpVertexGraphics(e){this._removeVertexGraphics();const t=this._createVertexGraphics(e);this.vertexGraphics.addMany(t),this._storeRelatedVertexIndices(),this.layer.addMany(t)}_createVertexGraphics(e){const{_graphicAttributes:i,symbols:s}=this,o=[];return e?.forEach((e,r)=>{e.forEach((e,n)=>{o.push(new t({geometry:this._coordinateHelper.arrayToPoint(e),symbol:s?.vertices?.default,attributes:{...i,pathIndex:r,pointIndex:n}}))})}),o}_createMidpointGraphics(e){const{_graphicAttributes:i,symbols:s}=this,o=[];for(let r=0;r<e.length;r++){const n=e[r];for(let e=0;e<n.length;e++){const h=(e+1)%n.length;if("polyline"===this.graphic.geometry?.type&&0===h)continue;const a=n[e],p=n[h],c=this._getMidpoint(a,p);o.push(new t({geometry:c,symbol:s.midpoints.default,attributes:{...i,pathIndex:r,pointIndexStart:e,pointIndexEnd:h}}))}}return o}_updateSymbolsForTheme(){const e=this.view.effectiveTheme.accentColor;this.symbols={vertices:{...this.symbols.vertices,default:this.symbols.vertices.default.clone().set("color",e),hover:this.symbols.vertices.hover?.clone().set("color",e)},midpoints:{...this.symbols.midpoints}};for(const t of this.vertexGraphics)this._isSelected(t)?t.symbol=this.symbols.vertices.selected:this._hoverGraphic===t?t.symbol=this.symbols.vertices.hover:t.symbol=this.symbols.vertices.default}_storeRelatedVertexIndices(){const e=this.vertexGraphics.items;if(!e)return;const t=e.map(({geometry:e})=>({x:e.x,y:e.y}));for(let i=0;i<t.length;i++){const s=[];for(let e=0;e<t.length;e++){if(i===e)continue;const o=t[i],r=t[e];o.x===r.x&&o.y===r.y&&s.push(e)}e[i].attributes.relatedGraphicIndices=s}}_setupMover(){const{enableMovement:e,graphic:t,midpointGraphics:i,vertexGraphics:s,view:o}=this,r=s.concat(i).items;e&&r.push(t),this._mover=new E({enableMoveAllGraphics:!1,highlightsEnabled:!1,indicatorsEnabled:!1,graphics:r,view:o,callbacks:{onGraphicClick:e=>this._onGraphicClickCallback(e),onGraphicMoveStart:e=>this._onGraphicMoveStartCallback(e),onGraphicMove:e=>this._onGraphicMoveCallback(e),onGraphicMoveStop:e=>this._onGraphicMoveStopCallback(e),onGraphicPointerOver:e=>this._onGraphicPointerOverCallback(e),onGraphicPointerOut:e=>this._onGraphicPointerOutCallback(e)}})}_setupConnectedReshapeManager(){const{connectedReshapeProviders:e}=this;0!==e.length&&(this._connectedReshapeManager=new w({providerFactories:e,view:this.view}))}_onGraphicClickCallback(e){e.viewEvent.stopPropagation();const t=e.graphic;if(t===this.graphic)this.clearSelection(),this.emit("graphic-click",e),this.callbacks.onGraphicClick?.(e);else if(this._isMidpoint(t)){if(2===e.viewEvent.button)return;const i=this.graphic.clone(),s=this._createVertexFromMidpoint(t);this.refresh(),this._emitVertexAddEvent([t],i,s)}else if(this._isVertex(t))if(e.viewEvent.stopPropagation(),2===e.viewEvent.button)this._removeVertices(t);else{e.viewEvent.native.shiftKey||this._clearSelection(),this.selectedVertices.includes(t)?this._removeFromSelection(t,!0):this._addToSelection(t)}}_setUpOperation(e){const{graphic:t,dx:i,dy:s}=e,o=t===this.graphic;this._resetSnappingStateVars(),this._setUpGeometryHelper(),this._saveSnappingContextForHandle(t,e),this._activeOperationInfo={target:this.graphic,mover:t,operationType:o?"move":"reshape",totalDx:i,totalDy:s}}_onGraphicMoveStartCallback(e){const{dx:t,dy:i,graphic:s}=e,o=this._connectedReshapeManager,r=o?ne(this.graphic):null;if(s===this.graphic){const{geometry:n}=s;return this._setUpOperation(e),this._emitMoveStartEvent(t,i),r&&o?.startFeatureMove([r]),void(null!=n&&"point"===n.type&&this._onHandleMove(s,t,i,e,()=>{this._updateTooltip(this.graphic,e.viewEvent),this._emitMoveEvent(t,i)}))}const{selectedVertices:n}=this;if(!n.includes(s)){if(this._clearSelection(),this._isMidpoint(s)){const e=this.graphic.clone(),t=this._createVertexFromMidpoint(s);this._emitVertexAddEvent([s],e,t)}this._addToSelection(s)}this._setUpOperation(e),r&&o?.startVertexMove(r,he(n)),this._emitReshapeStartEvent(s),this._onHandleMove(s,t,i,e,()=>{this._updateTooltip(s,e.viewEvent),this._emitReshapeEvent(s)})}_onGraphicMoveCallback(e){const t=this._activeOperationInfo;if(!t)return;const{dx:i,dy:s,graphic:o}=e;t.totalDx+=i,t.totalDy+=s;const{operationType:r}=t,{geometry:n}=o;if(null!=n)if("move"!==r)this._onHandleMove(o,i,s,e,()=>{this._updateTooltip(o,e.viewEvent),this._emitReshapeEvent(o)});else if("point"===n.type)this._onHandleMove(o,i,s,e,()=>{this._updateTooltip(this.graphic,e.viewEvent),this._emitMoveEvent(i,s)});else if("polyline"===n.type||"polygon"===n.type){const t=se(n);this._updateVertexGraphicLocations(t);const{dxMap:o,dyMap:r}=ae(i,s,this.view);this._connectedReshapeManager?.translate(o,r,0),this._updateTooltip(this.graphic,e.viewEvent),this._emitMoveEvent(i,s)}}_onGraphicMoveStopCallback(e){const t=this._activeOperationInfo;if(!t)return;const{dx:i,dy:s,graphic:o}=e,{operationType:r}=t;t.totalDx+=i,t.totalDy+=s,this._onHandleMove(o,i,s,e,()=>"move"===r?this._emitMoveStopEvent():this._emitReshapeStopEvent(o)),this._isMidpoint(o)?this.refresh():(this._updateTooltip(this._isVertex(o)?o:null),this._resetSnappingStateVars(),this._connectedReshapeManager?.finish(),this._activeOperationInfo=null)}_updateVertexGraphicLocations(e){const{_coordinateHelper:t}=this;for(const i of this.vertexGraphics){const{pathIndex:s,pointIndex:o}=i.attributes;i.geometry=t.arrayToPoint(e[s][o])}this._updateMidpointGraphicLocations(e)}_updateMidpointGraphicLocations(e){for(const t of this.midpointGraphics){const{pathIndex:i,pointIndexStart:s,pointIndexEnd:o}=t.attributes,r=e[i];t.geometry=this._getMidpoint(r[s],r[o])}}_getMidpoint(e,t){const{_coordinateHelper:i}=this,s=i.arrayToVector(e),o=i.arrayToVector(t),r=i.toXYZ(s),n=i.toXYZ(o),[h,a,p]=x(r,n),c=i.hasM()?0:void 0;return new g({x:h,y:a,z:p,m:c,spatialReference:i.spatialReference})}_getVertexFromEditGeometry(e){const[t,i]=oe(e);return a(this._editGeometryOperations),this._editGeometryOperations.data.components[t].vertices[i]}_onHandleMove(e,t,s,o,r){p(this._snappingTask);const n=this._snappingContext;if(!n)return;const h=e.geometry,a="graphic-move-stop"===o.type;if(null!=this.snappingManager&&this.selectedVertices.length<2&&!a){const o=this.snappingManager;this._stagedVertex=o.update({point:h,context:n}),this._syncGeometryAfterVertexMove(e,new g(this._stagedVertex),t,s,a),r(),this._snappingTask=i(async i=>{const p=await o.snap({point:h,context:n,signal:i});p.valid&&(this._stagedVertex=p.apply(),this._syncGeometryAfterVertexMove(e,new g(this._stagedVertex),t,s,a),r())})}else{const i=null!=this._stagedVertex?new g(this._stagedVertex):h;this._syncGeometryAfterVertexMove(e,i,t,s,a),r()}}_syncGeometryAfterVertexMove(e,t,i,s,o=!1){const r=this._editGeometryOperations?.data.geometry;if(r)if("point"===r.type)e.geometry=t;else if("mesh"===r.type)e.geometry=r.centerAt(t);else{const{_coordinateHelper:n}=this,[h,a]=oe(e);let p=G(r);const c=p[h].length-1,l=n.pointToArray(t);p[h][a]=l,"polygon"===r.type&&(0===a?p[h][c]=l:a===c&&(p[h][0]=l)),this._isVertex(e)&&(p=this._moveRelatedCoordinates(p,e,l),p=this._moveSelectedHandleCoordinates(p,e,i,s,"polygon"===r.type),this._updateMidpointGraphicLocations(p)),this._updateGraphicGeometry(r.clone());const d=n.pointToVector(t),m=this._getVertexFromEditGeometry(e),v=n.getZ(d),y=d[0]-m.pos[0],_=d[1]-m.pos[1],g=null!=v?v-m.pos[2]:0;this._editGeometryOperations?.moveVertices([m],y,_,g),this._connectedReshapeManager?.translate(y,_,g),o&&(this._mover?this._mover.updateGeometry(this._mover.graphics.indexOf(e),t):e.geometry=t)}}_moveRelatedCoordinates(e,t,i){const{relatedGraphicIndices:s}=t.attributes;for(const o of s){const s=this.vertexGraphics.at(o),{pathIndex:r,pointIndex:n}=s.attributes;e[r][n]=i,s.geometry=t.geometry}return e}_moveSelectedHandleCoordinates(e,t,i,s,o){for(const r of this.selectedVertices)if(r!==t){const{pathIndex:t,pointIndex:n,relatedGraphicIndices:h}=r.attributes,a=S(r.geometry,i,s,this.view),p=G(a),c=e[t].length-1;e[t][n]=p,r.geometry=a,o&&(0===n?e[t][c]=p:n===c&&(e[t][0]=p));for(const i of h){const t=this.vertexGraphics.at(i),{pathIndex:s,pointIndex:o}=t.attributes;e[s][o]=p,t.geometry=a}}return e}_onGraphicPointerOverCallback(e){const t=e.graphic;this._hoverGraphic=t;const i=this._isVertex(t);i&&!this._isSelected(t)&&(t.symbol=this.symbols.vertices.hover),this._updateTooltip(i?t:null),this._updateHoverCursor(t)}_onGraphicPointerOutCallback(e){const t=e.graphic;this._hoverGraphic=null,this._isVertex(t)&&!this._isSelected(t)&&(t.symbol=this.symbols.vertices.default),this.view.cursor="default",this._updateTooltip()}_createVertexFromMidpoint(e){const{_graphicAttributes:t,graphic:i}=this,s=i.geometry;if(null==s||"polygon"!==s.type&&"polyline"!==s.type)return[];const o=s.clone(),r=[],{pathIndex:n,pointIndexStart:h,pointIndexEnd:a}=e.attributes,p=G(e.geometry),c=0===a?h+1:a,l=G(o);return l[n].splice(c,0,p),e.attributes={...t,pathIndex:n,pointIndex:c,relatedGraphicIndices:[]},r.push({coordinates:l[n][c],componentIndex:n,vertexIndex:c}),this._updateGraphicGeometry(o),r}_addToSelection(e){const t=re(e);for(const i of t)i.symbol=this.symbols.vertices.selected,this.selectedVertices.add(i),this._updateTooltip(i);this._emitSelectEvent(t)}_removeFromSelection(e,t){const{vertices:i}=this.symbols,s=t?i.hover:i.default;this.selectedVertices.remove(e),e.symbol=s,this._emitDeselectEvent([e]),this._updateTooltip()}_clearSelection(){const e=this.selectedVertices.toArray();if(e.length>0){for(const t of e)t.set("symbol",this.symbols.vertices.default);this.selectedVertices.removeAll(),this._emitDeselectEvent(e),this._updateTooltip()}}_keyDownHandler(e){null==this._activeOperationInfo&&N(e,this.tooltip)||L.delete.includes(e.key)&&!e.repeat&&this.selectedVertices.length&&this._removeVertices(this.selectedVertices)}_removeVertices(e){const t=this.graphic.geometry;if(null==t||"polygon"!==t.type&&"polyline"!==t.type)return;if("polygon"===t.type&&this.vertexGraphics.length<4||this.vertexGraphics.length<3)return;const i=this.graphic.clone(),s=t.clone();let o=G(s);const r=[],n=re(e);for(const h of n){const{x:e,y:t}=h.geometry;for(let i=0;i<o.length;i++){const s=o[i];for(let n=0;n<s.length;n++){const[h,a]=s[n];e===h&&t===a&&(r.push({coordinates:o[i][n],componentIndex:i,vertexIndex:n}),o[i].splice(Number(n),1))}}}if("polygon"===s.type)o=o.filter(e=>{if(e.length<2)return!1;const[t,i]=e[0],[s,o]=e[e.length-1];return(2!==e.length||t!==s||i!==o)&&(t===s&&i===o||e.push(e[0]),!0)}),s.rings=o;else{for(const e of o)1===e.length&&o.splice(o.indexOf(e),1);s.paths=o}this._updateGraphicGeometry(s),this.refresh(),this._emitVertexRemoveEvent(n,i,r)}_isVertex(e){return this.vertexGraphics.includes(e)}_isSelected(e){return this._isVertex(e)&&this.selectedVertices.includes(e)}_isMidpoint(e){return this.midpointGraphics.includes(e)}_updateHoverCursor(e){this.view.cursor=this._isMidpoint(e)?"copy":"move"}_updateTooltip(e,t){let i=null;const{graphic:s,view:o,tooltipInfos:r}=this,n=s?.geometry;"point"===n?.type?i=r.movePoint:this._selectedVertex?i=r.selectedVertex:e===this.graphic?(i=r.translateGraphic,R(i,o,this._tooltipsContext,t)):e&&this.selectedVertices.length>1&&(i=r.translateVertices,H(i,o,n,this._tooltipsContext,t)),this.activeTooltipInfo=i}_updateGraphicGeometry(e){this._updateHandlesOnExternalGeometryChange?.pause(),this.graphic.geometry=e,this._updateHandlesOnExternalGeometryChange?.resume()}_emitMoveStartEvent(e,t){const i=new K(this.graphic,e,t);this.emit("move-start",i),this.callbacks.onMoveStart?.(i)}_emitMoveEvent(e,t){const i=new q(this.graphic,e,t);this.emit("move",i),this.callbacks.onMove?.(i)}_emitMoveStopEvent(e,t){if(null==e||null==t){const i=this._activeOperationInfo;if(!i)return;e=i.totalDx,t=i.totalDy}const i=new B(this.graphic,e,t);this.emit("move-stop",i),this.callbacks.onMoveStop?.(i)}_emitReshapeStartEvent(e){const t=new Z(this.graphic,e,this.selectedVertices.toArray());this.emit("reshape-start",t),this.callbacks.onReshapeStart?.(t)}_emitReshapeEvent(e){const t=new X(this.graphic,e,this.selectedVertices.toArray());this.emit("reshape",t),this.callbacks.onReshape?.(t)}_emitReshapeStopEvent(e){const t=new Y(this.graphic,e,this.selectedVertices.toArray());this.emit("reshape-stop",t),this.callbacks.onReshapeStop?.(t)}_emitSelectEvent(e){const t=new J(e);this.emit("select",t),this.callbacks.onVertexSelect?.(t)}_emitDeselectEvent(e){const t=new Q(e);this.emit("deselect",t),this.callbacks.onVertexDeselect?.(t)}_emitVertexAddEvent(e,t,i){const s=new W(e,this.graphic,t,i);this.emit("vertex-add",s),this.callbacks.onVertexAdd?.(s)}_emitVertexRemoveEvent(e,t,i){const s=new $(e,this.graphic,t,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 se(e){const t=G(e.clone());if("polygon"===e.type)for(const i of t){const e=i[i.length-1];i[0][0]===e[0]&&i[0][1]===e[1]&&i.length>2&&i.pop()}return t}function oe({attributes:e}){return[e?.pathIndex||0,e?.pointIndex||0]}function re(e){return e instanceof t?[e]:[...e]}function ne(e){const t=e.sourceLayer??e.layer;return C(t)?{graphic:e,layer:t}:null}function he(e){return e.toArray().map(e=>({pathIndex:e.attributes.pathIndex,vertexIndex:e.attributes.pointIndex}))}function ae(e,t,i){const s=i.state.inverseTransform;return{dxMap:s[0]*e+s[2]*t,dyMap:s[1]*e+s[3]*t}}e([y()],ie.prototype,"_activeOperationInfo",void 0),e([y()],ie.prototype,"_connectedReshapeManager",void 0),e([y()],ie.prototype,"_coordinateHelper",null),e([y()],ie.prototype,"_editGeometryOperations",void 0),e([y()],ie.prototype,"tooltip",void 0),e([y()],ie.prototype,"tooltipInfos",void 0),e([y()],ie.prototype,"activeTooltipInfo",void 0),e([y({constructOnly:!0})],ie.prototype,"automaticAreaMeasurementUtils",void 0),e([y({constructOnly:!0})],ie.prototype,"automaticLengthMeasurementUtils",void 0),e([y()],ie.prototype,"_selectedVertex",null),e([y()],ie.prototype,"_tooltipsContext",null),e([y()],ie.prototype,"callbacks",void 0),e([y()],ie.prototype,"connectedReshapeProviders",void 0),e([y()],ie.prototype,"enableMidpoints",void 0),e([y()],ie.prototype,"enableMovement",void 0),e([y()],ie.prototype,"enableVertices",void 0),e([y()],ie.prototype,"graphic",void 0),e([y()],ie.prototype,"highlightName",void 0),e([y()],ie.prototype,"highlightsEnabled",void 0),e([y()],ie.prototype,"layer",void 0),e([y({readOnly:!0})],ie.prototype,"midpointGraphics",void 0),e([y()],ie.prototype,"midpointSymbol",void 0),e([y({readOnly:!0})],ie.prototype,"selectedVertices",void 0),e([y()],ie.prototype,"snappingManager",void 0),e([y({readOnly:!0})],ie.prototype,"state",null),e([y()],ie.prototype,"symbols",void 0),e([y({type:z})],ie.prototype,"sketchOptions",void 0),e([y({readOnly:!0})],ie.prototype,"type",void 0),e([y({readOnly:!0})],ie.prototype,"vertexGraphics",void 0),e([y()],ie.prototype,"view",void 0),ie=e([_("esri.views.draw.support.Reshape")],ie);const pe=ie;export{pe as default};
5
+ import{__decorate as e}from"tslib";import t from"../../../Graphic.js";import{createTask as i}from"../../../core/asyncUtils.js";import s from"../../../core/Collection.js";import o from"../../../core/Error.js";import r from"../../../core/Evented.js";import n from"../../../core/Logger.js";import{destroyMaybe as h,assertIsSome as a,abortMaybe as p}from"../../../core/maybe.js";import{pausable as c,when as l,watch as d,initial as m,sync as v}from"../../../core/reactiveUtils.js";import{property as y}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/RandomLCG.js";import{subclass as _}from"../../../core/accessorSupport/decorators/subclass.js";import g from"../../../geometry/Point.js";import u from"../../../geometry/Polyline.js";import{closeRingsAndFixWinding as f,getMidpoint as x,geometryToCoordinates as G}from"../../../geometry/support/coordsUtils.js";import M from"../../../layers/GraphicsLayer.js";import b from"../../../symbols/SimpleMarkerSymbol.js";import{SnappingVisualizer2D as V}from"../../2d/interactive/SnappingVisualizer2D.js";import{ConnectedReshapeManager as S}from"./ConnectedReshapeManager.js";import{cloneMove as w}from"./drawUtils.js";import E from"./GraphicMover.js";import I from"./HighlightHelper.js";import{addUniqueLayer as O,isConnectedReshapeSupportedLayer as C}from"./layerUtils.js";import{createTooltipInfos as k,connectTooltip as T,updateTranslateTooltipInfo as H,updateTranslateVertexTooltipInfo as R}from"./reshapeTooltipUtils.js";import{settings as j}from"./settings.js";import{ViewEventPriorities as A}from"../../input/InputManager.js";import{createCoordinateHelper as U}from"../../interactive/coordinateHelper.js";import{sketchKeys as L}from"../../interactive/keybindings.js";import{EditGeometryOperations as P}from"../../interactive/editGeometry/EditGeometryOperations.js";import z from"../../interactive/sketch/SketchOptions.js";import{SnappingContext as D}from"../../interactive/snapping/SnappingContext.js";import{makeTooltip as F,enterInputModeIfAvailable as N}from"../../interactive/tooltip/tooltipCommonUtils.js";class Z{constructor(e,t,i){this.graphic=e,this.mover=t,this.selected=i,this.type="reshape-start"}}class X{constructor(e,t,i){this.graphic=e,this.mover=t,this.selected=i,this.type="reshape"}}class Y{constructor(e,t,i){this.graphic=e,this.mover=t,this.selected=i,this.type="reshape-stop"}}class q{constructor(e,t,i){this.mover=e,this.dx=t,this.dy=i,this.type="move-start"}}class K{constructor(e,t,i){this.mover=e,this.dx=t,this.dy=i,this.type="move"}}class B{constructor(e,t,i){this.mover=e,this.dx=t,this.dy=i,this.type="move-stop"}}class J{constructor(e){this.added=e,this.type="vertex-select"}}class Q{constructor(e){this.removed=e,this.type="vertex-deselect"}}class W{constructor(e,t,i,s){this.added=e,this.graphic=t,this.oldGraphic=i,this.vertices=s,this.type="vertex-add"}}class ${constructor(e,t,i,s){this.removed=e,this.graphic=t,this.oldGraphic=i,this.vertices=s,this.type="vertex-remove"}}const ee=j.reshapeGraphics,te={vertices:{default:new b({style:"circle",size:ee.vertex.size,color:ee.vertex.color,outline:{color:ee.vertex.outlineColor,width:1}}),hover:new b({style:"circle",size:ee.vertex.hoverSize,color:ee.vertex.hoverColor,outline:{color:ee.vertex.hoverOutlineColor,width:1}}),selected:new b({style:"circle",size:ee.selected.size,color:ee.selected.color,outline:{color:ee.selected.outlineColor,width:1}})},midpoints:{default:new b({style:"circle",size:ee.midpoint.size,color:ee.midpoint.color,outline:{color:ee.midpoint.outlineColor,width:1}}),hover:new b({style:"circle",size:ee.midpoint.size,color:ee.midpoint.color,outline:{color:ee.midpoint.outlineColor,width:1}})}},ie=Symbol();let se=class extends r.EventedAccessor{constructor(e){super(e),this._updateHandlesOnExternalGeometryChange=null,this._activeOperationInfo=null,this._connectedReshapeManager=null,this._editGeometryOperations=null,this._graphicAttributes={esriSketchTool:"box"},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=[],this.enableMidpoints=!0,this.enableMovement=!0,this.enableVertices=!0,this.graphic=null,this.highlightName=null,this.highlightsEnabled=!0,this.layer=null,this.midpointGraphics=new s,this.midpointSymbol=new b({style:"circle",size:6,color:[200,200,200],outline:{color:[100,100,100],width:1}}),this.selectedVertices=new s,this.snappingManager=null,this.symbols=te,this.sketchOptions=new z,this.type="reshape",this.vertexGraphics=new s,this.view=null}initialize(){const e=this.view;this._highlightHelper=new I({view:e}),this._setup(),this._updateHandlesOnExternalGeometryChange=c(()=>this.graphic?.geometry,e=>{if(!e)return;const t=new Set(this.selectedVertices.map(e=>e.attributes?.pointIndex));this._highlightHelper.removeAll(),this._setUpHighlights(),this._setupGraphics(),this._clearSelection(),this.vertexGraphics.filter(e=>t.has(e.attributes.pointIndex)).forEach(e=>this._addToSelection(e));const{enableMovement:i,_mover:s,graphic:o,midpointGraphics:r,vertexGraphics:n}=this,h=n.concat(r).items;i&&h.push(o),s?.set("graphics",h)},v),this.tooltip=F(()=>({view:e,options:this.sketchOptions.tooltips})),this.tooltipInfos=k(this.sketchOptions),this.addHandles([l(()=>e?.ready,()=>{const{layer:e,view:t}=this;O(t,e),this.addHandles(t.on("key-down",e=>this._keyDownHandler(e),A.TOOL))},{once:!0,initial:!0}),d(()=>this.graphic,()=>this.refresh()),d(()=>this.layer,(e,t)=>{t&&(this._clearSelection(),this._resetGraphics(t)),this.refresh()}),d(()=>[this.highlightsEnabled,this.highlightName],()=>{this._highlightHelper?.removeAll(),this._setUpHighlights()}),d(()=>this.enableMidpoints,()=>this.refresh()),T(this.tooltip,()=>this._tooltipsContext),d(()=>this.view.effectiveTheme.accentColor,()=>this._updateSymbolsForTheme(),m),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??U(!!this.graphic.geometry?.hasZ,!!this.graphic.geometry?.hasM,this.view.spatialReference)}get _selectedVertex(){return 1===this.selectedVertices.length?this.selectedVertices.at(0):void 0}get _tooltipsContext(){const{automaticAreaMeasurementUtils:e,automaticLengthMeasurementUtils:t,sketchOptions:i,activeTooltipInfo:s,graphic:o}=this;return{sketchOptions:i,activeTooltipInfo:s,graphic:o,selectedVertex:this._selectedVertex,automaticAreaMeasurementUtils:e,automaticLengthMeasurementUtils:t,updateGeometry:(e,t,i,s,o)=>{this._setUpGeometryHelper();const r=e===this.graphic;r?this._emitMoveStartEvent(0,0):this._emitReshapeStartEvent(e);const n=!0;if(this._syncGeometryAfterVertexMove(e,t,s,o,n),r){const{view:e}=this,s=e.toScreen(i),o=e.toScreen(t),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(e),this._emitReshapeStopEvent(e);this._editGeometryOperations=h(this._editGeometryOperations)}}}get state(){const e=this.view.ready,t=!(!this.graphic||!this.layer);return e&&t?"active":e?"ready":"disabled"}isUIGraphic(e){const t=[];return this.graphic&&t.push(this.graphic),t.concat(this.vertexGraphics.items,this.midpointGraphics.items),t.length>0&&t.includes(e)}refresh(){this._reset(),this._setup()}reset(){this.graphic=null}clearSelection(){this._clearSelection()}removeSelectedVertices(){const{selectedVertices:e}=this;e.length&&this._removeVertices(e)}_setup(){const{graphic:e,layer:t}=this;if(!t||null==e?.geometry)return;const i=e.geometry;"mesh"!==i.type&&"extent"!==i.type?("polygon"===i.type&&f(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 e=this.graphic.geometry;if(null==e||"mesh"===e.type||"extent"===e.type)return void this._logGeometryTypeError();const t="multipoint"===e.type?new u({paths:[e.points],spatialReference:e.spatialReference}):e;this._editGeometryOperations=P.fromGeometry(t,2)}_saveSnappingContextForHandle(e,t){this._snappingGraphicsLayer=new M({listMode:"hide",internal:!0,title:"Reshape snapping layer"}),this.view.map.layers.add(this._snappingGraphicsLayer);const i=this._editGeometryOperations;a(i),this._snappingContext=new D({editGeometryOperations:i,elevationInfo:{mode:"on-the-ground",offset:0},pointer:t.viewEvent?.pointerType||"mouse",excludeFeature:this.graphic,feature:this.graphic,visualizer:new V(this._snappingGraphicsLayer),vertexHandle:this._getVertexFromEditGeometry(e)})}_reset(){this._clearSelection(),this._highlightHelper?.removeAll(),this._updateTooltip(),this._resetGraphics(),this._resetSnappingStateVars(),this._activeOperationInfo=null,this._mover&&this._mover.destroy(),this._mover=null,this.removeHandles(ie)}_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=p(this._snappingTask),this._snappingTask=null,this._snappingContext=null,this._stagedVertex=null}_resetGraphics(e){this._removeMidpointGraphics(e),this._removeVertexGraphics(e),this.selectedVertices.removeAll(),this._updateTooltip()}_removeMidpointGraphics(e){const t=e||this.layer;t&&t.removeMany(this.midpointGraphics.items),this.midpointGraphics.items.forEach(e=>e.destroy()),this.midpointGraphics.removeAll()}_removeVertexGraphics(e){const t=e||this.layer;t&&t.removeMany(this.vertexGraphics.items),this.vertexGraphics.items.forEach(e=>e.destroy()),this.vertexGraphics.removeAll()}_setupGraphics(){const e=this.graphic.geometry;if(null!=e&&("polyline"===e.type||"polygon"===e.type)){const t=oe(e);this.enableMidpoints&&this._setUpMidpointGraphics(t),this.enableVertices&&this._setUpVertexGraphics(t)}}_setUpMidpointGraphics(e){this._removeMidpointGraphics();const t=this._createMidpointGraphics(e);this.midpointGraphics.addMany(t),this.layer.addMany(t)}_setUpVertexGraphics(e){this._removeVertexGraphics();const t=this._createVertexGraphics(e);this.vertexGraphics.addMany(t),this._storeRelatedVertexIndices(),this.layer.addMany(t)}_createVertexGraphics(e){const{_graphicAttributes:i,symbols:s}=this,o=[];return e?.forEach((e,r)=>{e.forEach((e,n)=>{o.push(new t({geometry:this._coordinateHelper.arrayToPoint(e),symbol:s?.vertices?.default,attributes:{...i,pathIndex:r,pointIndex:n}}))})}),o}_createMidpointGraphics(e){const{_graphicAttributes:i,symbols:s}=this,o=[];for(let r=0;r<e.length;r++){const n=e[r];for(let e=0;e<n.length;e++){const h=(e+1)%n.length;if("polyline"===this.graphic.geometry?.type&&0===h)continue;const a=n[e],p=n[h],c=this._getMidpoint(a,p);o.push(new t({geometry:c,symbol:s.midpoints.default,attributes:{...i,pathIndex:r,pointIndexStart:e,pointIndexEnd:h}}))}}return o}_updateSymbolsForTheme(){const e=this.view.effectiveTheme.accentColor;this.symbols={vertices:{...this.symbols.vertices,default:this.symbols.vertices.default.clone().set("color",e),hover:this.symbols.vertices.hover?.clone().set("color",e)},midpoints:{...this.symbols.midpoints}};for(const t of this.vertexGraphics)this._isSelected(t)?t.symbol=this.symbols.vertices.selected:this._hoverGraphic===t?t.symbol=this.symbols.vertices.hover:t.symbol=this.symbols.vertices.default}_storeRelatedVertexIndices(){const e=this.vertexGraphics.items;if(!e)return;const t=e.map(({geometry:e})=>({x:e.x,y:e.y}));for(let i=0;i<t.length;i++){const s=[];for(let e=0;e<t.length;e++){if(i===e)continue;const o=t[i],r=t[e];o.x===r.x&&o.y===r.y&&s.push(e)}e[i].attributes.relatedGraphicIndices=s}}_setupMover(){const{enableMovement:e,graphic:t,midpointGraphics:i,vertexGraphics:s,view:o}=this,r=s.concat(i).items;e&&r.push(t),this._mover=new E({enableMoveAllGraphics:!1,highlightsEnabled:!1,indicatorsEnabled:!1,graphics:r,view:o,callbacks:{onGraphicClick:e=>this._onGraphicClickCallback(e),onGraphicMoveStart:e=>this._onGraphicMoveStartCallback(e),onGraphicMove:e=>this._onGraphicMoveCallback(e),onGraphicMoveStop:e=>this._onGraphicMoveStopCallback(e),onGraphicPointerOver:e=>this._onGraphicPointerOverCallback(e),onGraphicPointerOut:e=>this._onGraphicPointerOutCallback(e)}})}_setupConnectedReshapeManager(){const{connectedReshapeProviders:e}=this;0!==e.length&&(this._connectedReshapeManager=new S({providerFactories:e,view:this.view}))}_onGraphicClickCallback(e){e.viewEvent.stopPropagation();const t=e.graphic;if(t===this.graphic)this.clearSelection(),this.emit("graphic-click",e),this.callbacks.onGraphicClick?.(e);else if(this._isMidpoint(t)){if(2===e.viewEvent.button)return;const i=this.graphic.clone(),s=this._createVertexFromMidpoint(t);this.refresh(),this._emitVertexAddEvent([t],i,s)}else if(this._isVertex(t))if(e.viewEvent.stopPropagation(),2===e.viewEvent.button)this._removeVertices(t);else{e.viewEvent.native.shiftKey||this._clearSelection(),this.selectedVertices.includes(t)?this._removeFromSelection(t,!0):this._addToSelection(t)}}_setUpOperation(e){const{graphic:t,dx:i,dy:s}=e,o=t===this.graphic;this._resetSnappingStateVars(),this._setUpGeometryHelper(),this._saveSnappingContextForHandle(t,e),this._activeOperationInfo={target:this.graphic,mover:t,operationType:o?"move":"reshape",totalDx:i,totalDy:s}}_onGraphicMoveStartCallback(e){const{dx:t,dy:i,graphic:s}=e,o=this._connectedReshapeManager,r=o?he(this.graphic):null;if(s===this.graphic){const{geometry:n}=s;return this._setUpOperation(e),this._emitMoveStartEvent(t,i),r&&o?.startFeatureMove([r]),void(null!=n&&"point"===n.type&&this._onHandleMove(s,t,i,e,()=>{this._updateTooltip(this.graphic,e.viewEvent),this._emitMoveEvent(t,i)}))}const{selectedVertices:n}=this;if(!n.includes(s)){if(this._clearSelection(),this._isMidpoint(s)){const e=this.graphic.clone(),t=this._createVertexFromMidpoint(s);this._emitVertexAddEvent([s],e,t)}this._addToSelection(s)}this._setUpOperation(e),r&&o?.startVertexMove(r,ae(n)),this._emitReshapeStartEvent(s),this._onHandleMove(s,t,i,e,()=>{this._updateTooltip(s,e.viewEvent),this._emitReshapeEvent(s)})}_onGraphicMoveCallback(e){const t=this._activeOperationInfo;if(!t)return;const{dx:i,dy:s,graphic:o}=e;t.totalDx+=i,t.totalDy+=s;const{operationType:r}=t,{geometry:n}=o;if(null!=n)if("move"!==r)this._onHandleMove(o,i,s,e,()=>{this._updateTooltip(o,e.viewEvent),this._emitReshapeEvent(o)});else if("point"===n.type)this._onHandleMove(o,i,s,e,()=>{this._updateTooltip(this.graphic,e.viewEvent),this._emitMoveEvent(i,s)});else if("polyline"===n.type||"polygon"===n.type){const t=oe(n);this._updateVertexGraphicLocations(t);const{dxMap:o,dyMap:r}=pe(i,s,this.view);this._connectedReshapeManager?.translate(o,r,0),this._updateTooltip(this.graphic,e.viewEvent),this._emitMoveEvent(i,s)}}_onGraphicMoveStopCallback(e){const t=this._activeOperationInfo;if(!t)return;const{dx:i,dy:s,graphic:o}=e,{operationType:r}=t;t.totalDx+=i,t.totalDy+=s,this._onHandleMove(o,i,s,e,()=>"move"===r?this._emitMoveStopEvent():this._emitReshapeStopEvent(o)),this._isMidpoint(o)?this.refresh():(this._updateTooltip(this._isVertex(o)?o:null),this._resetSnappingStateVars(),this._connectedReshapeManager?.finish(),this._activeOperationInfo=null)}_updateVertexGraphicLocations(e){const{_coordinateHelper:t}=this;for(const i of this.vertexGraphics){const{pathIndex:s,pointIndex:o}=i.attributes;i.geometry=t.arrayToPoint(e[s][o])}this._updateMidpointGraphicLocations(e)}_updateMidpointGraphicLocations(e){for(const t of this.midpointGraphics){const{pathIndex:i,pointIndexStart:s,pointIndexEnd:o}=t.attributes,r=e[i];t.geometry=this._getMidpoint(r[s],r[o])}}_getMidpoint(e,t){const{_coordinateHelper:i}=this,s=i.arrayToVector(e),o=i.arrayToVector(t),r=i.toXYZ(s),n=i.toXYZ(o),[h,a,p]=x(r,n),c=i.hasM()?0:void 0;return new g({x:h,y:a,z:p,m:c,spatialReference:i.spatialReference})}_getVertexFromEditGeometry(e){const[t,i]=re(e);return a(this._editGeometryOperations),this._editGeometryOperations.data.components[t].vertices[i]}_onHandleMove(e,t,s,o,r){p(this._snappingTask);const n=this._snappingContext;if(!n)return;const h=e.geometry,a="graphic-move-stop"===o.type;if(null!=this.snappingManager&&this.selectedVertices.length<2&&!a){const o=this.snappingManager;this._stagedVertex=o.update({point:h,context:n}),this._syncGeometryAfterVertexMove(e,new g(this._stagedVertex),t,s,a),r(),this._snappingTask=i(async i=>{const p=await o.snap({point:h,context:n,signal:i});p.valid&&(this._stagedVertex=p.apply(),this._syncGeometryAfterVertexMove(e,new g(this._stagedVertex),t,s,a),r())})}else{const i=null!=this._stagedVertex?new g(this._stagedVertex):h;this._syncGeometryAfterVertexMove(e,i,t,s,a),r()}}_syncGeometryAfterVertexMove(e,t,i,s,o=!1){const r=this._editGeometryOperations?.data.geometry;if(r)if("point"===r.type)e.geometry=t;else if("mesh"===r.type)e.geometry=r.centerAt(t);else{const{_coordinateHelper:n}=this,[h,a]=re(e);let p=G(r);const c=p[h].length-1,l=n.pointToArray(t);p[h][a]=l,"polygon"===r.type&&(0===a?p[h][c]=l:a===c&&(p[h][0]=l)),this._isVertex(e)&&(p=this._moveRelatedCoordinates(p,e,l),p=this._moveSelectedHandleCoordinates(p,e,i,s,"polygon"===r.type),this._updateMidpointGraphicLocations(p)),this._updateGraphicGeometry(r.clone());const d=n.pointToVector(t),m=this._getVertexFromEditGeometry(e),v=n.getZ(d),y=d[0]-m.pos[0],_=d[1]-m.pos[1],g=null!=v?v-m.pos[2]:0;this._editGeometryOperations?.moveVertices([m],y,_,g),this._connectedReshapeManager?.translate(y,_,g),o&&(this._mover?this._mover.updateGeometry(this._mover.graphics.indexOf(e),t):e.geometry=t)}}_moveRelatedCoordinates(e,t,i){const{relatedGraphicIndices:s}=t.attributes;for(const o of s){const s=this.vertexGraphics.at(o),{pathIndex:r,pointIndex:n}=s.attributes;e[r][n]=i,s.geometry=t.geometry}return e}_moveSelectedHandleCoordinates(e,t,i,s,o){for(const r of this.selectedVertices)if(r!==t){const{pathIndex:t,pointIndex:n,relatedGraphicIndices:h}=r.attributes,a=w(r.geometry,i,s,this.view),p=G(a),c=e[t].length-1;e[t][n]=p,r.geometry=a,o&&(0===n?e[t][c]=p:n===c&&(e[t][0]=p));for(const i of h){const t=this.vertexGraphics.at(i),{pathIndex:s,pointIndex:o}=t.attributes;e[s][o]=p,t.geometry=a}}return e}_onGraphicPointerOverCallback(e){const t=e.graphic;this._hoverGraphic=t;const i=this._isVertex(t);i&&!this._isSelected(t)&&(t.symbol=this.symbols.vertices.hover),this._updateTooltip(i?t:null),this._updateHoverCursor(t)}_onGraphicPointerOutCallback(e){const t=e.graphic;this._hoverGraphic=null,this._isVertex(t)&&!this._isSelected(t)&&(t.symbol=this.symbols.vertices.default),this.removeHandles(ie),this._updateTooltip()}_createVertexFromMidpoint(e){const{_graphicAttributes:t,graphic:i}=this,s=i.geometry;if(null==s||"polygon"!==s.type&&"polyline"!==s.type)return[];const o=s.clone(),r=[],{pathIndex:n,pointIndexStart:h,pointIndexEnd:a}=e.attributes,p=G(e.geometry),c=0===a?h+1:a,l=G(o);return l[n].splice(c,0,p),e.attributes={...t,pathIndex:n,pointIndex:c,relatedGraphicIndices:[]},r.push({coordinates:l[n][c],componentIndex:n,vertexIndex:c}),this._updateGraphicGeometry(o),r}_addToSelection(e){const t=ne(e);for(const i of t)i.symbol=this.symbols.vertices.selected,this.selectedVertices.add(i),this._updateTooltip(i);this._emitSelectEvent(t)}_removeFromSelection(e,t){const{vertices:i}=this.symbols,s=t?i.hover:i.default;this.selectedVertices.remove(e),e.symbol=s,this._emitDeselectEvent([e]),this._updateTooltip()}_clearSelection(){const e=this.selectedVertices.toArray();if(e.length>0){for(const t of e)t.set("symbol",this.symbols.vertices.default);this.selectedVertices.removeAll(),this._emitDeselectEvent(e),this._updateTooltip()}}_keyDownHandler(e){null==this._activeOperationInfo&&N(e,this.tooltip)||L.delete.includes(e.key)&&!e.repeat&&this.selectedVertices.length&&this._removeVertices(this.selectedVertices)}_removeVertices(e){const t=this.graphic.geometry;if(null==t||"polygon"!==t.type&&"polyline"!==t.type)return;if("polygon"===t.type&&this.vertexGraphics.length<4||this.vertexGraphics.length<3)return;const i=this.graphic.clone(),s=t.clone();let o=G(s);const r=[],n=ne(e);for(const h of n){const{x:e,y:t}=h.geometry;for(let i=0;i<o.length;i++){const s=o[i];for(let n=0;n<s.length;n++){const[h,a]=s[n];e===h&&t===a&&(r.push({coordinates:o[i][n],componentIndex:i,vertexIndex:n}),o[i].splice(Number(n),1))}}}if("polygon"===s.type)o=o.filter(e=>{if(e.length<2)return!1;const[t,i]=e[0],[s,o]=e[e.length-1];return(2!==e.length||t!==s||i!==o)&&(t===s&&i===o||e.push(e[0]),!0)}),s.rings=o;else{for(const e of o)1===e.length&&o.splice(o.indexOf(e),1);s.paths=o}this._updateGraphicGeometry(s),this.refresh(),this._emitVertexRemoveEvent(n,i,r)}_isVertex(e){return this.vertexGraphics.includes(e)}_isSelected(e){return this._isVertex(e)&&this.selectedVertices.includes(e)}_isMidpoint(e){return this.midpointGraphics.includes(e)}_updateHoverCursor(e){const t=this._isMidpoint(e)?"copy":"move";this.addHandles(this.view.acquireCursor(t,"high"),ie)}_updateTooltip(e,t){let i=null;const{graphic:s,view:o,tooltipInfos:r}=this,n=s?.geometry;"point"===n?.type?i=r.movePoint:this._selectedVertex?i=r.selectedVertex:e===this.graphic?(i=r.translateGraphic,H(i,o,this._tooltipsContext,t)):e&&this.selectedVertices.length>1&&(i=r.translateVertices,R(i,o,n,this._tooltipsContext,t)),this.activeTooltipInfo=i}_updateGraphicGeometry(e){this._updateHandlesOnExternalGeometryChange?.pause(),this.graphic.geometry=e,this._updateHandlesOnExternalGeometryChange?.resume()}_emitMoveStartEvent(e,t){const i=new q(this.graphic,e,t);this.emit("move-start",i),this.callbacks.onMoveStart?.(i)}_emitMoveEvent(e,t){const i=new K(this.graphic,e,t);this.emit("move",i),this.callbacks.onMove?.(i)}_emitMoveStopEvent(e,t){if(null==e||null==t){const i=this._activeOperationInfo;if(!i)return;e=i.totalDx,t=i.totalDy}const i=new B(this.graphic,e,t);this.emit("move-stop",i),this.callbacks.onMoveStop?.(i)}_emitReshapeStartEvent(e){const t=new Z(this.graphic,e,this.selectedVertices.toArray());this.emit("reshape-start",t),this.callbacks.onReshapeStart?.(t)}_emitReshapeEvent(e){const t=new X(this.graphic,e,this.selectedVertices.toArray());this.emit("reshape",t),this.callbacks.onReshape?.(t)}_emitReshapeStopEvent(e){const t=new Y(this.graphic,e,this.selectedVertices.toArray());this.emit("reshape-stop",t),this.callbacks.onReshapeStop?.(t)}_emitSelectEvent(e){const t=new J(e);this.emit("select",t),this.callbacks.onVertexSelect?.(t)}_emitDeselectEvent(e){const t=new Q(e);this.emit("deselect",t),this.callbacks.onVertexDeselect?.(t)}_emitVertexAddEvent(e,t,i){const s=new W(e,this.graphic,t,i);this.emit("vertex-add",s),this.callbacks.onVertexAdd?.(s)}_emitVertexRemoveEvent(e,t,i){const s=new $(e,this.graphic,t,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 oe(e){const t=G(e.clone());if("polygon"===e.type)for(const i of t){const e=i[i.length-1];i[0][0]===e[0]&&i[0][1]===e[1]&&i.length>2&&i.pop()}return t}function re({attributes:e}){return[e?.pathIndex||0,e?.pointIndex||0]}function ne(e){return e instanceof t?[e]:[...e]}function he(e){const t=e.sourceLayer??e.layer;return C(t)?{graphic:e,layer:t}:null}function ae(e){return e.toArray().map(e=>({pathIndex:e.attributes.pathIndex,vertexIndex:e.attributes.pointIndex}))}function pe(e,t,i){const s=i.state.inverseTransform;return{dxMap:s[0]*e+s[2]*t,dyMap:s[1]*e+s[3]*t}}e([y()],se.prototype,"_activeOperationInfo",void 0),e([y()],se.prototype,"_connectedReshapeManager",void 0),e([y()],se.prototype,"_coordinateHelper",null),e([y()],se.prototype,"_editGeometryOperations",void 0),e([y()],se.prototype,"tooltip",void 0),e([y()],se.prototype,"tooltipInfos",void 0),e([y()],se.prototype,"activeTooltipInfo",void 0),e([y({constructOnly:!0})],se.prototype,"automaticAreaMeasurementUtils",void 0),e([y({constructOnly:!0})],se.prototype,"automaticLengthMeasurementUtils",void 0),e([y()],se.prototype,"_selectedVertex",null),e([y()],se.prototype,"_tooltipsContext",null),e([y()],se.prototype,"callbacks",void 0),e([y()],se.prototype,"connectedReshapeProviders",void 0),e([y()],se.prototype,"enableMidpoints",void 0),e([y()],se.prototype,"enableMovement",void 0),e([y()],se.prototype,"enableVertices",void 0),e([y()],se.prototype,"graphic",void 0),e([y()],se.prototype,"highlightName",void 0),e([y()],se.prototype,"highlightsEnabled",void 0),e([y()],se.prototype,"layer",void 0),e([y({readOnly:!0})],se.prototype,"midpointGraphics",void 0),e([y()],se.prototype,"midpointSymbol",void 0),e([y({readOnly:!0})],se.prototype,"selectedVertices",void 0),e([y()],se.prototype,"snappingManager",void 0),e([y({readOnly:!0})],se.prototype,"state",null),e([y()],se.prototype,"symbols",void 0),e([y({type:z})],se.prototype,"sketchOptions",void 0),e([y({readOnly:!0})],se.prototype,"type",void 0),e([y({readOnly:!0})],se.prototype,"vertexGraphics",void 0),e([y()],se.prototype,"view",void 0),se=e([_("esri.views.draw.support.Reshape")],se);const ce=se;export{ce as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import has from"../../core/has.js";import{disposeMaybe as t}from"../../core/maybe.js";import{after as e}from"../../core/promiseUtils.js";import{Milliseconds as s}from"../../core/time.js";import{webglDebugEnabled as i,checkWebGLError as a}from"./checkWebGLError.js";import{ContextState as r}from"./ContextState.js";import{ColorAttachment0 as n,baseTextureUnit as l,ResourceType as h,PrimitiveType as f}from"./enums.js";import{InstanceCounter as o}from"./InstanceCounter.js";import{Parameters as u}from"./Parameters.js";import{ProgramCache as c}from"./ProgramCache.js";import{StateTracker as d}from"./renderState.js";import{Texture as _}from"./Texture.js";import{getErrorString as b}from"./Util.js";import{WebGLDriverTest as g}from"./WebGLDriverTest.js";import{Capabilities as p}from"./capabilities/Capabilities.js";let m=class{constructor(t,e){this.gl=t,this.instanceCounter=new o,this._programCache=new c(this),this._transformFeedbackRequestInfo=null,this._state=new r,this._numOfDrawCalls=0,this._numOfTriangles=0,this.configure(e)}configure(e){this._capabilities=new p(this.gl,e),this._parameters=new u(this.gl,this._capabilities,e),_.TEXTURE_UNIT_FOR_UPDATES=this._parameters.maxTextureImageUnits-1;const s=this.gl.getParameter(this.gl.VIEWPORT);this._state=new r,this._state.viewport={x:s[0],y:s[1],width:s[2],height:s[3]},this._stateTracker=new d({setBlending:t=>{if(t){this.setBlendingEnabled(!0),this.setBlendEquationSeparate(t.opRgb,t.opAlpha),this.setBlendFunctionSeparate(t.srcRgb,t.dstRgb,t.srcAlpha,t.dstAlpha);const e=t.color;this.setBlendColor(e.r,e.g,e.b,e.a)}else this.setBlendingEnabled(!1)},setCulling:t=>{t?(this.setFaceCullingEnabled(!0),this.setCullFace(t.face),this.setFrontFace(t.mode)):this.setFaceCullingEnabled(!1)},setPolygonOffset:t=>{t?(this.setPolygonOffsetFillEnabled(!0),this.setPolygonOffset(t.factor,t.units)):this.setPolygonOffsetFillEnabled(!1)},setDepthTest:t=>{t?(this.setDepthTestEnabled(!0),this.setDepthFunction(t.func)):this.setDepthTestEnabled(!1)},setStencilTest:t=>{if(t){this.setStencilTestEnabled(!0);const e=t.function;this.setStencilFunction(e.func,e.ref,e.mask);const s=t.operation;this.setStencilOp(s.fail,s.zFail,s.zPass)}else this.setStencilTestEnabled(!1)},setDepthWrite:t=>{t?(this.setDepthWriteEnabled(!0),this.setDepthRange(t.zNear,t.zFar)):this.setDepthWriteEnabled(!1)},setColorWrite:t=>{t?this.setColorMask(t.r,t.g,t.b,t.a):this.setColorMask(!1,!1,!1,!1)},setStencilWrite:t=>{t?this.setStencilWriteMask(t.mask):this.setStencilWriteMask(0)},setDrawBuffers:t=>{if(t)this.setDrawBuffers(t.buffers);else{const{drawFramebuffer:t}=this._state;null===t?this.setDrawBuffers([1029]):0===t.colorAttachments.length?this.setDrawBuffers([0]):this.setDrawBuffers([n])}}}),this.enforceState(),t(this._driverTest),this._driverTest=new g(this)}updateOptions(t){this._parameters=new u(this.gl,this._capabilities,t)}dispose(){this._driverTest=t(this._driverTest),this._programCache=t(this._programCache),this.bindVAO(null),this.unbindBuffer(34962),this.unbindBuffer(34963),this.unbindBuffer(35345),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(35051),this.unbindBuffer(35052),this.unbindBuffer(36662),this.unbindBuffer(36663),this._state.textureUnitMap.length=0,this._state=null,this._capabilities=null,this._stateTracker=null,i()&&console.log(this.instanceCounter.resourceInformation)}get driverTest(){return this._driverTest}get contextAttributes(){return this.gl.getContextAttributes()}get parameters(){return this._parameters}get programCache(){return this._programCache}setPipelineState(t){this._stateTracker.setPipeline(t)}setBlendingEnabled(t){this._state.blend!==t&&(!0===t?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this._state.blend=t,this._stateTracker.invalidateBlending())}externalProgramUpdate(){this._state.program?.stop(),this._state.program=null}externalTextureUnitUpdate(t,e){for(let s=0;s<t.length;++s)this._state.textureUnitMap[t[s]]=null;e>=0&&(this._state.activeTexture=e)}externalVertexArrayObjectUpdate(){this.gl.bindVertexArray(null),this._state.vertexArrayObject=null,this._state.vertexBuffer=null,this._state.indexBuffer=null}externalVertexBufferUpdate(){this._state.vertexBuffer=null}externalIndexBufferUpdate(){this._state.indexBuffer=null}setBlendColor(t,e,s,i){t===this._state.blendColor.r&&e===this._state.blendColor.g&&s===this._state.blendColor.b&&i===this._state.blendColor.a||(this.gl.blendColor(t,e,s,i),this._state.blendColor.r=t,this._state.blendColor.g=e,this._state.blendColor.b=s,this._state.blendColor.a=i,this._stateTracker.invalidateBlending())}setBlendFunction(t,e){t===this._state.blendFunction.srcRGB&&e===this._state.blendFunction.dstRGB||(this.gl.blendFunc(t,e),this._state.blendFunction.srcRGB=t,this._state.blendFunction.srcAlpha=t,this._state.blendFunction.dstRGB=e,this._state.blendFunction.dstAlpha=e,this._stateTracker.invalidateBlending())}setBlendFunctionSeparate(t,e,s,i){this._state.blendFunction.srcRGB===t&&this._state.blendFunction.srcAlpha===s&&this._state.blendFunction.dstRGB===e&&this._state.blendFunction.dstAlpha===i||(this.gl.blendFuncSeparate(t,e,s,i),this._state.blendFunction.srcRGB=t,this._state.blendFunction.srcAlpha=s,this._state.blendFunction.dstRGB=e,this._state.blendFunction.dstAlpha=i,this._stateTracker.invalidateBlending())}setBlendEquation(t){this._state.blendEquation.mode!==t&&(this.gl.blendEquation(t),this._state.blendEquation.mode=t,this._state.blendEquation.modeAlpha=t,this._stateTracker.invalidateBlending())}setBlendEquationSeparate(t,e){this._state.blendEquation.mode===t&&this._state.blendEquation.modeAlpha===e||(this.gl.blendEquationSeparate(t,e),this._state.blendEquation.mode=t,this._state.blendEquation.modeAlpha=e,this._stateTracker.invalidateBlending())}setColorMask(t,e,s,i){this._state.colorMask.r===t&&this._state.colorMask.g===e&&this._state.colorMask.b===s&&this._state.colorMask.a===i||(this.gl.colorMask(t,e,s,i),this._state.colorMask.r=t,this._state.colorMask.g=e,this._state.colorMask.b=s,this._state.colorMask.a=i,this._stateTracker.invalidateColorWrite())}setClearColor(t,e,s,i){this._state.clearColor.r===t&&this._state.clearColor.g===e&&this._state.clearColor.b===s&&this._state.clearColor.a===i||(this.gl.clearColor(t,e,s,i),this._state.clearColor.r=t,this._state.clearColor.g=e,this._state.clearColor.b=s,this._state.clearColor.a=i)}setFaceCullingEnabled(t){this._state.faceCulling!==t&&(!0===t?this.gl.enable(this.gl.CULL_FACE):this.gl.disable(this.gl.CULL_FACE),this._state.faceCulling=t,this._stateTracker.invalidateCulling())}setPolygonOffsetFillEnabled(t){this._state.polygonOffsetFill!==t&&(!0===t?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL),this._state.polygonOffsetFill=t,this._stateTracker.invalidatePolygonOffset())}setPolygonOffset(t,e){this._state.polygonOffset[0]===t&&this._state.polygonOffset[1]===e||(this._state.polygonOffset[0]=t,this._state.polygonOffset[1]=e,this.gl.polygonOffset(t,e),this._stateTracker.invalidatePolygonOffset())}setCullFace(t){this._state.cullFace!==t&&(this.gl.cullFace(t),this._state.cullFace=t,this._stateTracker.invalidateCulling())}setFrontFace(t){this._state.frontFace!==t&&(this.gl.frontFace(t),this._state.frontFace=t,this._stateTracker.invalidateCulling())}setScissorTestEnabled(t){this._state.scissorTest!==t&&(!0===t?this.gl.enable(this.gl.SCISSOR_TEST):this.gl.disable(this.gl.SCISSOR_TEST),this._state.scissorTest=t)}setScissorRect(t,e,s,i){this._state.scissorRect.x===t&&this._state.scissorRect.y===e&&this._state.scissorRect.width===s&&this._state.scissorRect.height===i||(this.gl.scissor(t,e,s,i),this._state.scissorRect.x=t,this._state.scissorRect.y=e,this._state.scissorRect.width=s,this._state.scissorRect.height=i)}setDepthTestEnabled(t){this._state.depthTest!==t&&(!0===t?this.gl.enable(this.gl.DEPTH_TEST):this.gl.disable(this.gl.DEPTH_TEST),this._state.depthTest=t,this._stateTracker.invalidateDepthTest())}setClearDepth(t){this._state.clearDepth!==t&&(this.gl.clearDepth(t),this._state.clearDepth=t)}setDepthFunction(t){this._state.depthFunction!==t&&(this.gl.depthFunc(t),this._state.depthFunction=t,this._stateTracker.invalidateDepthTest())}setDepthWriteEnabled(t){this._state.depthWrite!==t&&(this.gl.depthMask(t),this._state.depthWrite=t,this._stateTracker.invalidateDepthWrite())}setDepthRange(t,e){this._state.depthRange.zNear===t&&this._state.depthRange.zFar===e||(this.gl.depthRange(t,e),this._state.depthRange.zNear=t,this._state.depthRange.zFar=e,this._stateTracker.invalidateDepthWrite())}setStencilTestEnabled(t){this._state.stencilTest!==t&&(!0===t?this.gl.enable(this.gl.STENCIL_TEST):this.gl.disable(this.gl.STENCIL_TEST),this._state.stencilTest=t,this._stateTracker.invalidateStencilTest())}setClearStencil(t){t!==this._state.clearStencil&&(this.gl.clearStencil(t),this._state.clearStencil=t)}setStencilFunction(t,e,s){this._state.stencilFunction.func===t&&this._state.stencilFunction.ref===e&&this._state.stencilFunction.mask===s||(this.gl.stencilFunc(t,e,s),this._state.stencilFunction.face=1032,this._state.stencilFunction.func=t,this._state.stencilFunction.ref=e,this._state.stencilFunction.mask=s,this._stateTracker.invalidateStencilTest())}setStencilFunctionSeparate(t,e,s,i){this._state.stencilFunction.face===t&&this._state.stencilFunction.func===e&&this._state.stencilFunction.ref===s&&this._state.stencilFunction.mask===i||(this.gl.stencilFuncSeparate(t,e,s,i),this._state.stencilFunction.face=t,this._state.stencilFunction.func=e,this._state.stencilFunction.ref=s,this._state.stencilFunction.mask=i,this._stateTracker.invalidateStencilTest())}setStencilWriteMask(t){this._state.stencilWriteMask!==t&&(this.gl.stencilMask(t),this._state.stencilWriteMask=t,this._stateTracker.invalidateStencilWrite())}setStencilOp(t,e,s){1032===this._state.stencilOperation.face&&this._state.stencilOperation.fail===t&&this._state.stencilOperation.zFail===e&&this._state.stencilOperation.zPass===s||(this.gl.stencilOp(t,e,s),this._state.stencilOperation.face=1032,this._state.stencilOperation.fail=t,this._state.stencilOperation.zFail=e,this._state.stencilOperation.zPass=s,this._stateTracker.invalidateStencilTest())}setStencilOpSeparate(t,e,s,i){this._state.stencilOperation.face===t&&this._state.stencilOperation.fail===e&&this._state.stencilOperation.zFail===s&&this._state.stencilOperation.zPass===i||(this.gl.stencilOpSeparate(t,e,s,i),this._state.stencilOperation.face=t,this._state.stencilOperation.fail=e,this._state.stencilOperation.zFail=s,this._state.stencilOperation.zPass=i,this._stateTracker.invalidateStencilTest())}setActiveTexture(t,e=!1){const s=this._state.activeTexture;return t>=0&&(e||t!==this._state.activeTexture)&&(this.gl.activeTexture(l+t),this._state.activeTexture=t),s}setDrawBuffers(t){const{drawFramebuffer:e}=this._state,s=null===e,i=s?this._state.drawBuffers.defaultFramebuffer:this._state.drawBuffers.fbos.get(e);if(i?.length!==t.length||!i.every((e,s)=>e===t[s]))if(t.length>this.parameters.maxDrawBuffers)console.error("Setting more active draw buffers than GL.MAX_DRAW_BUFFERS allows.");else{if(s){if(t.length>1)return void console.error("The default framebuffer can only have one active draw buffer.");if(1029!==t[0]&&0!==t[0])return void console.error("The default framebuffer can only use the constants GL.BACK or GL.NONE as draw buffers.")}s||!t.includes(1029)?(this.gl.drawBuffers(t),s?this._state.drawBuffers.defaultFramebuffer=t:this._state.drawBuffers.fbos.set(e,t),this._stateTracker.invalidateDrawBuffers()):console.error("A framebuffer object can only use the constants GL.COLOR_ATTACHMENTi or GL.NONE as draw buffers.")}}clear(t,e=255){if(t){if(16384&t){const t=this._state.drawFramebuffer?.colorAttachments;t&&this.setDrawBuffers(t),this.setColorMask(!0,!0,!0,!0)}256&t&&this.setDepthWriteEnabled(!0),1024&t&&this.setStencilWriteMask(e),this.gl.clear(t)}}clearFramebuffer(t,e=!1,s=!1){let i=0;if(t){const e=1e-13,s=Math.max(e,t[3]);this.setClearColor(t[0],t[1],t[2],s),i|=16384}e&&(i|=256),!1===s?s=0:(!0===s&&(s=255),i|=1024),i&&this.clear(i,s)}clearBuffer(t,e,s=6144,i=void 0){this.gl.clearBufferfv(s,t,e,i)}clearBufferInteger(t,e,s=6144,i=void 0){this.gl.clearBufferiv(s,t,e,i)}clearBufferUnsignedInteger(t,e,s=6144,i=void 0){this.gl.clearBufferuiv(s,t,e,i)}drawArrays(t,e,s){if(this._transformFeedbackRequestInfo){if(t!==this._transformFeedbackRequestInfo.primitiveType)throw new Error("DrawArrays called during transform feedback, but primitiveType does not match that of the current transform feedback request");if(null==this._state.program?.hasTransformFeedbackVaryings)throw new Error("DrawArrays called during transform feedback, but the shader program was not linked with a transform feedback varying")}if(i()&&(this._numOfDrawCalls++,this._numOfTriangles+=F(t,s),has("enable-feature:webgl-debug:textureReadWrite"))){const t=this._state.textureUnitMap;for(let e=0;e<t.length;e++){const s=t[e];if(null!=s&&s===this._state.drawFramebuffer?.colorTexture)throw new Error(`Detected readWrite. Texture already bound at index ${e}`)}}this.gl.drawArrays(t,e,s),a(this.gl)}drawArraysInstanced(t,e,s,i){this.gl.drawArraysInstanced(t,e,s,i),a(this.gl)}drawElements(t,e,s,a){if(this._transformFeedbackRequestInfo)throw new Error("Cannot called drawElements during a transform feedback request");if(i()&&(this._numOfDrawCalls++,this._numOfTriangles+=F(t,e)),this.gl.drawElements(t,e,s,a),i()){const i=b(this);if(i){const r=this.getBoundVAO(),n=r?.indexBuffer,l=r?.vertexBuffers,h={indexBuffer:n,vertexBuffers:l},f={mode:t,count:e,type:s,offset:a},o=n?.size??0,u=a+e,c=o<u?`. Buffer is too small. Attempted to draw index ${u} of ${o}`:"";console.error(`drawElements: ${i}${c}`,{args:f,vao:h})}}}drawElementsInstanced(t,e,s,i,r){this.gl.drawElementsInstanced(t,e,s,i,r),a(this.gl)}logInfo(){i()&&console.log(`DrawCalls: ${this._numOfDrawCalls}, Triangles: ${this._numOfTriangles}`)}resetInfo(){i()&&(this._numOfDrawCalls=0,this._numOfTriangles=0)}get capabilities(){return this._capabilities}setViewport(t,e,s,i){s=Math.max(Math.round(s),1),i=Math.max(Math.round(i),1);const a=this._state.viewport;a.x===t&&a.y===e&&a.width===s&&a.height===i||(a.x=t,a.y=e,a.width=s,a.height=i,this.gl.viewport(t,e,s,i))}setViewport4fv(t){this.setViewport(t[0],t[1],t[2],t[3])}restoreViewport({x:t,y:e,width:s,height:i}){this.setViewport(t,e,s,i)}getViewport(){const t=this._state.viewport;return{x:t.x,y:t.y,width:t.width,height:t.height}}useProgram(t){this._state.program!==t&&(this._state.program?.stop(),this._state.program=t,this.gl.useProgram(t?.glName??null))}bindTexture(t,e,s=!1){(e>=this.parameters.maxTextureImageUnits||e<0)&&console.error("Input texture unit is out of range of available units!");const i=this._state.textureUnitMap[e];return null==t?.glName?(null!=i&&(this.setActiveTexture(e,s),this.gl.bindTexture(i.descriptor.target,null)),this._state.textureUnitMap[e]=null,i):s||i!==t?(this.setActiveTexture(e,s),this.gl.bindTexture(t.descriptor.target,t.glName),t.applyChanges(),this._state.textureUnitMap[e]=t,i):(t.isDirty&&(this.setActiveTexture(e,s),t.applyChanges()),i)}unbindTexture(t){if(null!=t)for(let e=0;e<this.parameters.maxTextureImageUnits;e++)this._state.textureUnitMap[e]===t&&(this.bindTexture(null,e),this._state.textureUnitMap[e]=null)}bindFramebuffer(t,e=!1){if(e||this._state.readFramebuffer!==t||this._state.drawFramebuffer!==t){if(this._stateTracker.invalidateDrawBuffers(),null==t)return this.gl.bindFramebuffer(36160,null),void(this._state.readFramebuffer=this._state.drawFramebuffer=null);t.initializeAndBind(36160),this._state.readFramebuffer=t,this._state.drawFramebuffer=t}}bindFramebufferSeparate(t,e,s=!1){const i=36008===e,a=i?this._state.readFramebuffer:this._state.drawFramebuffer;(s||a!==t)&&(null==t?this.gl.bindFramebuffer(e,null):t.initializeAndBind(e),i?this._state.readFramebuffer=t??null:(this._stateTracker.invalidateDrawBuffers(),this._state.drawFramebuffer=t??null))}blitFramebuffer(t,e,s=16384,i=9728,a=0,r=0,n=t.width,l=t.height,h=0,f=0,o=e.width,u=e.height){this.bindFramebufferSeparate(t,36008,!0),this.bindFramebufferSeparate(e,36009,!0),this.gl.blitFramebuffer(a,r,n,l,h,f,o,u,s,i)}bindBuffer(t,e){if(t)switch(e??=t.bufferType,e){case 34962:this._state.vertexBuffer=B(this.gl,t,e,this._state.vertexBuffer);break;case 34963:this._state.indexBuffer=B(this.gl,t,e,this._state.indexBuffer);break;case 35345:this._state.uniformBuffer=B(this.gl,t,e,this._state.uniformBuffer);break;case 35051:this._state.pixelPackBuffer=B(this.gl,t,e,this._state.pixelPackBuffer);break;case 35052:this._state.pixelUnpackBuffer=B(this.gl,t,e,this._state.pixelUnpackBuffer);break;case 36662:this._state.copyReadBuffer=B(this.gl,t,e,this._state.copyReadBuffer);break;case 36663:this._state.copyWriteBuffer=B(this.gl,t,e,this._state.copyWriteBuffer);break;case 35982:this._state.transformFeedbackBuffer=B(this.gl,t,e,this._state.transformFeedbackBuffer)}}bindRenderbuffer(t){const e=this.gl;t||(e.bindRenderbuffer(e.RENDERBUFFER,null),this._state.renderbuffer=null),this._state.renderbuffer!==t&&(e.bindRenderbuffer(e.RENDERBUFFER,t.glName),this._state.renderbuffer=t)}_getBufferBinding(t,e){if(e>=this.parameters.maxUniformBufferBindings||e<0)return console.error("Uniform buffer binding point is out of range!"),null;const s=35345===t?this._state.uniformBufferBindingPoints:this._state.transformBufferBindingPoints;let i=s[e];return null==i&&(i={buffer:null,offset:0,size:0},s[e]=i),i}bindBufferBase(t,e,s){const i=this._getBufferBinding(t,e);null!=i&&(i.buffer===s&&0===i.offset&&0===i.size||(this.gl.bindBufferBase(t,e,s?s.glName:null),i.buffer=s,i.offset=0,i.size=0))}bindBufferRange(t,e,s,i,a){const r=this._getBufferBinding(t,e);null!=r&&(r.buffer===s&&r.offset===i&&r.size===a||(i%this._parameters.uniformBufferOffsetAlignment===0?(this.gl.bindBufferRange(t,e,s.glName,i,a),r.buffer=s,r.offset=i,r.size=a):console.error("Uniform buffer binding offset is not a multiple of the context offset alignment")))}bindUBO(t,e,s,a){null!=e?(i()&&(a??e.byteLength)>this._parameters.maxUniformBlockSize&&console.error("Attempting to bind more data than the maximum uniform block size"),e.initialize(),void 0!==s&&void 0!==a?this.bindBufferRange(35345,t,e.buffer,s,a):this.bindBufferBase(35345,t,e.buffer)):this.bindBufferBase(35345,t,null)}unbindUBO(t){for(let e=0,s=this._state.uniformBufferBindingPoints.length;e<s;e++){const s=this._state.uniformBufferBindingPoints[e];null!=s&&s.buffer===t.buffer&&this.bindBufferBase(35345,e,null)}}unbindBuffer(t){switch(t){case 34962:this._state.vertexBuffer=B(this.gl,null,t,this._state.vertexBuffer);break;case 34963:this._state.indexBuffer=B(this.gl,null,t,this._state.indexBuffer);break;case 35345:this._state.uniformBuffer=B(this.gl,null,t,this._state.uniformBuffer);break;case 35051:this._state.pixelPackBuffer=B(this.gl,null,t,this._state.pixelPackBuffer);break;case 35052:this._state.pixelUnpackBuffer=B(this.gl,null,t,this._state.pixelUnpackBuffer);break;case 36662:this._state.copyReadBuffer=B(this.gl,null,t,this._state.copyReadBuffer);break;case 36663:this._state.copyWriteBuffer=B(this.gl,null,t,this._state.copyWriteBuffer)}}bindVAO(t=null){null!=t?this._state.vertexArrayObject!==t&&(t.bind(),this._state.vertexArrayObject=t):this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null)}bindTransformFeedback(t){const{gl:e}=this;e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,t.glName)}beginTransformFeedback(t,e){if(this._transformFeedbackRequestInfo)throw new Error("Already in a transform feedback request");const{gl:s}=this;s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,t.glName),s.beginTransformFeedback(e),this._transformFeedbackRequestInfo={primitiveType:e}}endTransformFeedback(){if(!this._transformFeedbackRequestInfo)throw new Error("Not in a transform feedback request");const{gl:t}=this;t.endTransformFeedback(),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null),this._transformFeedbackRequestInfo=null}async clientWaitAsync(t=s(10)){const{gl:i}=this,a=i.fenceSync(37143,0);if(!a)throw new Error("Client wait failed, could not create sync object");let r;this.instanceCounter.increment(h.Sync,a),i.flush();do{await e(t),r=i.clientWaitSync(a,0,0)}while(37147===r);if(this.instanceCounter.decrement(h.Sync,a),i.deleteSync(a),37149===r)throw new Error("Client wait failed")}getBoundFramebufferObject(t=36160){return 36008===t?this._state.readFramebuffer:this._state.drawFramebuffer}temporaryBindFramebufferObject(t,e,s=!1){const i=this.getBoundFramebufferObject();try{this.bindFramebuffer(t,s),e()}finally{this.bindFramebuffer(i,s)}}getBoundVAO(){return this._state.vertexArrayObject}resetState(){this.useProgram(null),this.bindVAO(null),this.bindFramebuffer(null,!0),this.unbindBuffer(34962),this.unbindBuffer(34963),this.unbindBuffer(35345),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(35051),this.unbindBuffer(35052),this.unbindBuffer(36662),this.unbindBuffer(36663);for(let t=0;t<this.parameters.maxTextureImageUnits;++t)this.bindTexture(null,t);this.setBlendingEnabled(!1),this.setBlendFunction(1,0),this.setBlendEquation(32774),this.setBlendColor(0,0,0,0),this.setFaceCullingEnabled(!1),this.setCullFace(1029),this.setFrontFace(2305),this.setPolygonOffsetFillEnabled(!1),this.setPolygonOffset(0,0),this.setScissorTestEnabled(!1),this.setScissorRect(0,0,this.gl.canvas.width,this.gl.canvas.height),this.setDepthTestEnabled(!1),this.setDepthFunction(513),this.setDepthRange(0,1),this.setStencilTestEnabled(!1),this.setStencilFunction(519,0,0),this.setStencilOp(7680,7680,7680),this.setClearColor(0,0,0,0),this.setClearDepth(1),this.setClearStencil(0),this.setColorMask(!0,!0,!0,!0),this.setStencilWriteMask(4294967295),this.setDepthWriteEnabled(!0),this.setDrawBuffers([1029]),this.setViewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}enforceState(){const{gl:t}=this;t.bindVertexArray(null);for(let s=0;s<this.parameters.maxVertexAttributes;s++)t.disableVertexAttribArray(s);this._state.vertexBuffer?t.bindBuffer(this._state.vertexBuffer.bufferType,this._state.vertexBuffer.glName):t.bindBuffer(34962,null),this._state.indexBuffer?t.bindBuffer(this._state.indexBuffer.bufferType,this._state.indexBuffer.glName):t.bindBuffer(34963,null),this._state.uniformBuffer?t.bindBuffer(this._state.uniformBuffer.bufferType,this._state.uniformBuffer.glName):t.bindBuffer(35345,null);for(let s=0;s<this._parameters.maxUniformBufferBindings;s++){const e=this._state.uniformBufferBindingPoints[s];if(null!=e){const{buffer:i,offset:a,size:r}=e;null!==i?0===a&&0===r?t.bindBufferBase(35345,s,i.glName):t.bindBufferRange(35345,s,i.glName,a,r):t.bindBufferBase(35345,s,null)}}if(this._state.pixelPackBuffer?t.bindBuffer(this._state.pixelPackBuffer.bufferType,this._state.pixelPackBuffer.glName):t.bindBuffer(35051,null),this._state.pixelUnpackBuffer?t.bindBuffer(this._state.pixelUnpackBuffer.bufferType,this._state.pixelUnpackBuffer.glName):t.bindBuffer(35052,null),this._state.copyReadBuffer?t.bindBuffer(this._state.copyReadBuffer.bufferType,this._state.copyReadBuffer.glName):t.bindBuffer(36662,null),this._state.copyWriteBuffer?t.bindBuffer(this._state.copyWriteBuffer.bufferType,this._state.copyWriteBuffer.glName):t.bindBuffer(36663,null),t.bindFramebuffer(36008,null),t.readBuffer(t.BACK),this._state.readFramebuffer&&(t.bindFramebuffer(36008,this._state.readFramebuffer.glName),t.readBuffer(n)),t.bindFramebuffer(36009,this._state.drawFramebuffer?.glName??null),null===this._state.drawFramebuffer){const e=this._state.drawBuffers.defaultFramebuffer;t.drawBuffers(e??[1029])}else{const e=this._state.drawBuffers.fbos.get(this._state.drawFramebuffer);t.drawBuffers(e??[n])}if(this._state.vertexArrayObject){const t=this._state.vertexArrayObject;this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null),this.bindVAO(t)}t.useProgram(this._state.program?.glName??null),t.blendColor(this._state.blendColor.r,this._state.blendColor.g,this._state.blendColor.b,this._state.blendColor.a),t.bindRenderbuffer(t.RENDERBUFFER,this._state.renderbuffer?.glName??null),!0===this._state.blend?t.enable(this.gl.BLEND):t.disable(this.gl.BLEND),t.blendEquationSeparate(this._state.blendEquation.mode,this._state.blendEquation.modeAlpha),t.blendFuncSeparate(this._state.blendFunction.srcRGB,this._state.blendFunction.dstRGB,this._state.blendFunction.srcAlpha,this._state.blendFunction.dstAlpha),t.clearColor(this._state.clearColor.r,this._state.clearColor.g,this._state.clearColor.b,this._state.clearColor.a),t.clearDepth(this._state.clearDepth),t.clearStencil(this._state.clearStencil),t.colorMask(this._state.colorMask.r,this._state.colorMask.g,this._state.colorMask.b,this._state.colorMask.a),t.cullFace(this._state.cullFace),t.depthFunc(this._state.depthFunction),t.depthRange(this._state.depthRange.zNear,this._state.depthRange.zFar),!0===this._state.depthTest?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),t.depthMask(this._state.depthWrite),t.frontFace(this._state.frontFace),t.lineWidth(1),!0===this._state.faceCulling?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),t.polygonOffset(this._state.polygonOffset[0],this._state.polygonOffset[1]),!0===this._state.polygonOffsetFill?t.enable(t.POLYGON_OFFSET_FILL):t.disable(t.POLYGON_OFFSET_FILL),t.scissor(this._state.scissorRect.x,this._state.scissorRect.y,this._state.scissorRect.width,this._state.scissorRect.height),!0===this._state.scissorTest?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST),t.stencilFunc(this._state.stencilFunction.func,this._state.stencilFunction.ref,this._state.stencilFunction.mask),t.stencilOpSeparate(this._state.stencilOperation.face,this._state.stencilOperation.fail,this._state.stencilOperation.zFail,this._state.stencilOperation.zPass),!0===this._state.stencilTest?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),t.stencilMask(this._state.stencilWriteMask);for(let s=0;s<this.parameters.maxTextureImageUnits;s++){t.activeTexture(l+s),t.bindTexture(3553,null),t.bindTexture(34067,null),t.bindTexture(32879,null),t.bindTexture(35866,null);const e=this._state.textureUnitMap[s];null!=e&&t.bindTexture(e.descriptor.target,e.glName)}t.activeTexture(l+this._state.activeTexture);const e=this._state.viewport;t.viewport(e.x,e.y,e.width,e.height),this.resetInfo()}};function B(t,e,s,i){return e?i!==e&&t.bindBuffer(s,e.glName):t.bindBuffer(s,null),e}function F(t,e){switch(t){case f.POINTS:return 2*e;case f.TRIANGLES:return e/3;case f.TRIANGLE_STRIP:case f.TRIANGLE_FAN:return e-2;default:return 0}}export{m as RenderingContext};
5
+ import has from"../../core/has.js";import{disposeMaybe as t}from"../../core/maybe.js";import{after as e}from"../../core/promiseUtils.js";import{Milliseconds as s}from"../../core/time.js";import{webglDebugEnabled as i,checkWebGLError as a,getErrorMessage as r}from"./checkWebGLError.js";import{ContextState as n}from"./ContextState.js";import{ColorAttachment0 as l,baseTextureUnit as h,ResourceType as f,PrimitiveType as o}from"./enums.js";import{InstanceCounter as u}from"./InstanceCounter.js";import{Parameters as c}from"./Parameters.js";import{ProgramCache as d}from"./ProgramCache.js";import{StateTracker as _}from"./renderState.js";import{Texture as b}from"./Texture.js";import{WebGLDriverTest as g}from"./WebGLDriverTest.js";import{Capabilities as p}from"./capabilities/Capabilities.js";let m=class{constructor(t,e){this.gl=t,this.instanceCounter=new u,this._programCache=new d(this),this._transformFeedbackRequestInfo=null,this._state=new n,this._numOfDrawCalls=0,this._numOfTriangles=0,this.configure(e)}configure(e){this._capabilities=new p(this.gl,e),this._parameters=new c(this.gl,this._capabilities,e),b.TEXTURE_UNIT_FOR_UPDATES=this._parameters.maxTextureImageUnits-1;const s=this.gl.getParameter(this.gl.VIEWPORT);this._state=new n,this._state.viewport={x:s[0],y:s[1],width:s[2],height:s[3]},this._stateTracker=new _({setBlending:t=>{if(t){this.setBlendingEnabled(!0),this.setBlendEquationSeparate(t.opRgb,t.opAlpha),this.setBlendFunctionSeparate(t.srcRgb,t.dstRgb,t.srcAlpha,t.dstAlpha);const e=t.color;this.setBlendColor(e.r,e.g,e.b,e.a)}else this.setBlendingEnabled(!1)},setCulling:t=>{t?(this.setFaceCullingEnabled(!0),this.setCullFace(t.face),this.setFrontFace(t.mode)):this.setFaceCullingEnabled(!1)},setPolygonOffset:t=>{t?(this.setPolygonOffsetFillEnabled(!0),this.setPolygonOffset(t.factor,t.units)):this.setPolygonOffsetFillEnabled(!1)},setDepthTest:t=>{t?(this.setDepthTestEnabled(!0),this.setDepthFunction(t.func)):this.setDepthTestEnabled(!1)},setStencilTest:t=>{if(t){this.setStencilTestEnabled(!0);const e=t.function;this.setStencilFunction(e.func,e.ref,e.mask);const s=t.operation;this.setStencilOp(s.fail,s.zFail,s.zPass)}else this.setStencilTestEnabled(!1)},setDepthWrite:t=>{t?(this.setDepthWriteEnabled(!0),this.setDepthRange(t.zNear,t.zFar)):this.setDepthWriteEnabled(!1)},setColorWrite:t=>{t?this.setColorMask(t.r,t.g,t.b,t.a):this.setColorMask(!1,!1,!1,!1)},setStencilWrite:t=>{t?this.setStencilWriteMask(t.mask):this.setStencilWriteMask(0)},setDrawBuffers:t=>{if(t)this.setDrawBuffers(t.buffers);else{const{drawFramebuffer:t}=this._state;null===t?this.setDrawBuffers([1029]):0===t.colorAttachments.length?this.setDrawBuffers([0]):this.setDrawBuffers([l])}}}),this.enforceState(),t(this._driverTest),this._driverTest=new g(this)}updateOptions(t){this._parameters=new c(this.gl,this._capabilities,t)}dispose(){this._driverTest=t(this._driverTest),this._programCache=t(this._programCache),this.bindVAO(null),this.unbindBuffer(34962),this.unbindBuffer(34963),this.unbindBuffer(35345),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(35051),this.unbindBuffer(35052),this.unbindBuffer(36662),this.unbindBuffer(36663),this._state.textureUnitMap.length=0,this._state=null,this._capabilities=null,this._stateTracker=null,i()&&console.log(this.instanceCounter.resourceInformation)}get driverTest(){return this._driverTest}get contextAttributes(){return this.gl.getContextAttributes()}get parameters(){return this._parameters}get programCache(){return this._programCache}setPipelineState(t){this._stateTracker.setPipeline(t)}setBlendingEnabled(t){this._state.blend!==t&&(!0===t?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this._state.blend=t,this._stateTracker.invalidateBlending())}externalProgramUpdate(){this._state.program?.stop(),this._state.program=null}externalTextureUnitUpdate(t,e){for(let s=0;s<t.length;++s)this._state.textureUnitMap[t[s]]=null;e>=0&&(this._state.activeTexture=e)}externalVertexArrayObjectUpdate(){this.gl.bindVertexArray(null),this._state.vertexArrayObject=null,this._state.vertexBuffer=null,this._state.indexBuffer=null}externalVertexBufferUpdate(){this._state.vertexBuffer=null}externalIndexBufferUpdate(){this._state.indexBuffer=null}setBlendColor(t,e,s,i){t===this._state.blendColor.r&&e===this._state.blendColor.g&&s===this._state.blendColor.b&&i===this._state.blendColor.a||(this.gl.blendColor(t,e,s,i),this._state.blendColor.r=t,this._state.blendColor.g=e,this._state.blendColor.b=s,this._state.blendColor.a=i,this._stateTracker.invalidateBlending())}setBlendFunction(t,e){t===this._state.blendFunction.srcRGB&&e===this._state.blendFunction.dstRGB||(this.gl.blendFunc(t,e),this._state.blendFunction.srcRGB=t,this._state.blendFunction.srcAlpha=t,this._state.blendFunction.dstRGB=e,this._state.blendFunction.dstAlpha=e,this._stateTracker.invalidateBlending())}setBlendFunctionSeparate(t,e,s,i){this._state.blendFunction.srcRGB===t&&this._state.blendFunction.srcAlpha===s&&this._state.blendFunction.dstRGB===e&&this._state.blendFunction.dstAlpha===i||(this.gl.blendFuncSeparate(t,e,s,i),this._state.blendFunction.srcRGB=t,this._state.blendFunction.srcAlpha=s,this._state.blendFunction.dstRGB=e,this._state.blendFunction.dstAlpha=i,this._stateTracker.invalidateBlending())}setBlendEquation(t){this._state.blendEquation.mode!==t&&(this.gl.blendEquation(t),this._state.blendEquation.mode=t,this._state.blendEquation.modeAlpha=t,this._stateTracker.invalidateBlending())}setBlendEquationSeparate(t,e){this._state.blendEquation.mode===t&&this._state.blendEquation.modeAlpha===e||(this.gl.blendEquationSeparate(t,e),this._state.blendEquation.mode=t,this._state.blendEquation.modeAlpha=e,this._stateTracker.invalidateBlending())}setColorMask(t,e,s,i){this._state.colorMask.r===t&&this._state.colorMask.g===e&&this._state.colorMask.b===s&&this._state.colorMask.a===i||(this.gl.colorMask(t,e,s,i),this._state.colorMask.r=t,this._state.colorMask.g=e,this._state.colorMask.b=s,this._state.colorMask.a=i,this._stateTracker.invalidateColorWrite())}setClearColor(t,e,s,i){this._state.clearColor.r===t&&this._state.clearColor.g===e&&this._state.clearColor.b===s&&this._state.clearColor.a===i||(this.gl.clearColor(t,e,s,i),this._state.clearColor.r=t,this._state.clearColor.g=e,this._state.clearColor.b=s,this._state.clearColor.a=i)}setFaceCullingEnabled(t){this._state.faceCulling!==t&&(!0===t?this.gl.enable(this.gl.CULL_FACE):this.gl.disable(this.gl.CULL_FACE),this._state.faceCulling=t,this._stateTracker.invalidateCulling())}setPolygonOffsetFillEnabled(t){this._state.polygonOffsetFill!==t&&(!0===t?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL),this._state.polygonOffsetFill=t,this._stateTracker.invalidatePolygonOffset())}setPolygonOffset(t,e){this._state.polygonOffset[0]===t&&this._state.polygonOffset[1]===e||(this._state.polygonOffset[0]=t,this._state.polygonOffset[1]=e,this.gl.polygonOffset(t,e),this._stateTracker.invalidatePolygonOffset())}setCullFace(t){this._state.cullFace!==t&&(this.gl.cullFace(t),this._state.cullFace=t,this._stateTracker.invalidateCulling())}setFrontFace(t){this._state.frontFace!==t&&(this.gl.frontFace(t),this._state.frontFace=t,this._stateTracker.invalidateCulling())}setScissorTestEnabled(t){this._state.scissorTest!==t&&(!0===t?this.gl.enable(this.gl.SCISSOR_TEST):this.gl.disable(this.gl.SCISSOR_TEST),this._state.scissorTest=t)}setScissorRect(t,e,s,i){this._state.scissorRect.x===t&&this._state.scissorRect.y===e&&this._state.scissorRect.width===s&&this._state.scissorRect.height===i||(this.gl.scissor(t,e,s,i),this._state.scissorRect.x=t,this._state.scissorRect.y=e,this._state.scissorRect.width=s,this._state.scissorRect.height=i)}setDepthTestEnabled(t){this._state.depthTest!==t&&(!0===t?this.gl.enable(this.gl.DEPTH_TEST):this.gl.disable(this.gl.DEPTH_TEST),this._state.depthTest=t,this._stateTracker.invalidateDepthTest())}setClearDepth(t){this._state.clearDepth!==t&&(this.gl.clearDepth(t),this._state.clearDepth=t)}setDepthFunction(t){this._state.depthFunction!==t&&(this.gl.depthFunc(t),this._state.depthFunction=t,this._stateTracker.invalidateDepthTest())}setDepthWriteEnabled(t){this._state.depthWrite!==t&&(this.gl.depthMask(t),this._state.depthWrite=t,this._stateTracker.invalidateDepthWrite())}setDepthRange(t,e){this._state.depthRange.zNear===t&&this._state.depthRange.zFar===e||(this.gl.depthRange(t,e),this._state.depthRange.zNear=t,this._state.depthRange.zFar=e,this._stateTracker.invalidateDepthWrite())}setStencilTestEnabled(t){this._state.stencilTest!==t&&(!0===t?this.gl.enable(this.gl.STENCIL_TEST):this.gl.disable(this.gl.STENCIL_TEST),this._state.stencilTest=t,this._stateTracker.invalidateStencilTest())}setClearStencil(t){t!==this._state.clearStencil&&(this.gl.clearStencil(t),this._state.clearStencil=t)}setStencilFunction(t,e,s){this._state.stencilFunction.func===t&&this._state.stencilFunction.ref===e&&this._state.stencilFunction.mask===s||(this.gl.stencilFunc(t,e,s),this._state.stencilFunction.face=1032,this._state.stencilFunction.func=t,this._state.stencilFunction.ref=e,this._state.stencilFunction.mask=s,this._stateTracker.invalidateStencilTest())}setStencilFunctionSeparate(t,e,s,i){this._state.stencilFunction.face===t&&this._state.stencilFunction.func===e&&this._state.stencilFunction.ref===s&&this._state.stencilFunction.mask===i||(this.gl.stencilFuncSeparate(t,e,s,i),this._state.stencilFunction.face=t,this._state.stencilFunction.func=e,this._state.stencilFunction.ref=s,this._state.stencilFunction.mask=i,this._stateTracker.invalidateStencilTest())}setStencilWriteMask(t){this._state.stencilWriteMask!==t&&(this.gl.stencilMask(t),this._state.stencilWriteMask=t,this._stateTracker.invalidateStencilWrite())}setStencilOp(t,e,s){1032===this._state.stencilOperation.face&&this._state.stencilOperation.fail===t&&this._state.stencilOperation.zFail===e&&this._state.stencilOperation.zPass===s||(this.gl.stencilOp(t,e,s),this._state.stencilOperation.face=1032,this._state.stencilOperation.fail=t,this._state.stencilOperation.zFail=e,this._state.stencilOperation.zPass=s,this._stateTracker.invalidateStencilTest())}setStencilOpSeparate(t,e,s,i){this._state.stencilOperation.face===t&&this._state.stencilOperation.fail===e&&this._state.stencilOperation.zFail===s&&this._state.stencilOperation.zPass===i||(this.gl.stencilOpSeparate(t,e,s,i),this._state.stencilOperation.face=t,this._state.stencilOperation.fail=e,this._state.stencilOperation.zFail=s,this._state.stencilOperation.zPass=i,this._stateTracker.invalidateStencilTest())}setActiveTexture(t,e=!1){const s=this._state.activeTexture;return t>=0&&(e||t!==this._state.activeTexture)&&(this.gl.activeTexture(h+t),this._state.activeTexture=t),s}setDrawBuffers(t){const{drawFramebuffer:e}=this._state,s=null===e,i=s?this._state.drawBuffers.defaultFramebuffer:this._state.drawBuffers.fbos.get(e);if(i?.length!==t.length||!i.every((e,s)=>e===t[s]))if(t.length>this.parameters.maxDrawBuffers)console.error("Setting more active draw buffers than GL.MAX_DRAW_BUFFERS allows.");else{if(s){if(t.length>1)return void console.error("The default framebuffer can only have one active draw buffer.");if(1029!==t[0]&&0!==t[0])return void console.error("The default framebuffer can only use the constants GL.BACK or GL.NONE as draw buffers.")}s||!t.includes(1029)?(this.gl.drawBuffers(t),s?this._state.drawBuffers.defaultFramebuffer=t:this._state.drawBuffers.fbos.set(e,t),this._stateTracker.invalidateDrawBuffers()):console.error("A framebuffer object can only use the constants GL.COLOR_ATTACHMENTi or GL.NONE as draw buffers.")}}clear(t,e=255){if(t){if(16384&t){const t=this._state.drawFramebuffer?.colorAttachments;t&&this.setDrawBuffers(t),this.setColorMask(!0,!0,!0,!0)}256&t&&this.setDepthWriteEnabled(!0),1024&t&&this.setStencilWriteMask(e),this.gl.clear(t)}}clearFramebuffer(t,e=!1,s=!1){let i=0;if(t){const e=1e-13,s=Math.max(e,t[3]);this.setClearColor(t[0],t[1],t[2],s),i|=16384}e&&(i|=256),!1===s?s=0:(!0===s&&(s=255),i|=1024),i&&this.clear(i,s)}clearBuffer(t,e,s=6144,i=void 0){this.gl.clearBufferfv(s,t,e,i)}clearBufferInteger(t,e,s=6144,i=void 0){this.gl.clearBufferiv(s,t,e,i)}clearBufferUnsignedInteger(t,e,s=6144,i=void 0){this.gl.clearBufferuiv(s,t,e,i)}drawArrays(t,e,s){if(this._transformFeedbackRequestInfo){if(t!==this._transformFeedbackRequestInfo.primitiveType)throw new Error("DrawArrays called during transform feedback, but primitiveType does not match that of the current transform feedback request");if(null==this._state.program?.hasTransformFeedbackVaryings)throw new Error("DrawArrays called during transform feedback, but the shader program was not linked with a transform feedback varying")}if(i()&&(this._numOfDrawCalls++,this._numOfTriangles+=F(t,s),has("enable-feature:webgl-debug:textureReadWrite"))){const t=this._state.textureUnitMap;for(let e=0;e<t.length;e++){const s=t[e];if(null!=s&&s===this._state.drawFramebuffer?.colorTexture)throw new Error(`Detected readWrite. Texture already bound at index ${e}`)}}this.gl.drawArrays(t,e,s),a(this.gl)}drawArraysInstanced(t,e,s,i){this.gl.drawArraysInstanced(t,e,s,i),a(this.gl)}drawElements(t,e,s,a){if(this._transformFeedbackRequestInfo)throw new Error("Cannot called drawElements during a transform feedback request");if(i()&&(this._numOfDrawCalls++,this._numOfTriangles+=F(t,e)),this.gl.drawElements(t,e,s,a),i()){const i=r(this.gl);if(i){const r=this.getBoundVAO(),n=r?.indexBuffer,l=r?.vertexBuffers,h={indexBuffer:n,vertexBuffers:l},f={mode:t,count:e,type:s,offset:a},o=n?.size??0,u=a+e,c=o<u?`. Buffer is too small. Attempted to draw index ${u} of ${o}`:"";console.error(`drawElements: ${i}${c}`,{args:f,vao:h})}}}drawElementsInstanced(t,e,s,i,r){this.gl.drawElementsInstanced(t,e,s,i,r),a(this.gl)}logInfo(){i()&&console.log(`DrawCalls: ${this._numOfDrawCalls}, Triangles: ${this._numOfTriangles}`)}resetInfo(){i()&&(this._numOfDrawCalls=0,this._numOfTriangles=0)}get capabilities(){return this._capabilities}setViewport(t,e,s,i){s=Math.max(Math.round(s),1),i=Math.max(Math.round(i),1);const a=this._state.viewport;a.x===t&&a.y===e&&a.width===s&&a.height===i||(a.x=t,a.y=e,a.width=s,a.height=i,this.gl.viewport(t,e,s,i))}setViewport4fv(t){this.setViewport(t[0],t[1],t[2],t[3])}restoreViewport({x:t,y:e,width:s,height:i}){this.setViewport(t,e,s,i)}getViewport(){const t=this._state.viewport;return{x:t.x,y:t.y,width:t.width,height:t.height}}useProgram(t){this._state.program!==t&&(this._state.program?.stop(),this._state.program=t,this.gl.useProgram(t?.glName??null))}bindTexture(t,e,s=!1){(e>=this.parameters.maxTextureImageUnits||e<0)&&console.error("Input texture unit is out of range of available units!");const i=this._state.textureUnitMap[e];return null==t?.glName?(null!=i&&(this.setActiveTexture(e,s),this.gl.bindTexture(i.descriptor.target,null)),this._state.textureUnitMap[e]=null,i):s||i!==t?(this.setActiveTexture(e,s),this.gl.bindTexture(t.descriptor.target,t.glName),t.applyChanges(),this._state.textureUnitMap[e]=t,i):(t.isDirty&&(this.setActiveTexture(e,s),t.applyChanges()),i)}unbindTexture(t){if(null!=t)for(let e=0;e<this.parameters.maxTextureImageUnits;e++)this._state.textureUnitMap[e]===t&&(this.bindTexture(null,e),this._state.textureUnitMap[e]=null)}bindFramebuffer(t,e=!1){if(e||this._state.readFramebuffer!==t||this._state.drawFramebuffer!==t){if(this._stateTracker.invalidateDrawBuffers(),null==t)return this.gl.bindFramebuffer(36160,null),void(this._state.readFramebuffer=this._state.drawFramebuffer=null);t.initializeAndBind(36160),this._state.readFramebuffer=t,this._state.drawFramebuffer=t}}bindFramebufferSeparate(t,e,s=!1){const i=36008===e,a=i?this._state.readFramebuffer:this._state.drawFramebuffer;(s||a!==t)&&(null==t?this.gl.bindFramebuffer(e,null):t.initializeAndBind(e),i?this._state.readFramebuffer=t??null:(this._stateTracker.invalidateDrawBuffers(),this._state.drawFramebuffer=t??null))}blitFramebuffer(t,e,s=16384,i=9728,a=0,r=0,n=t.width,l=t.height,h=0,f=0,o=e.width,u=e.height){this.bindFramebufferSeparate(t,36008,!0),this.bindFramebufferSeparate(e,36009,!0),this.gl.blitFramebuffer(a,r,n,l,h,f,o,u,s,i)}bindBuffer(t,e){if(t)switch(e??=t.bufferType,e){case 34962:this._state.vertexBuffer=B(this.gl,t,e,this._state.vertexBuffer);break;case 34963:this._state.indexBuffer=B(this.gl,t,e,this._state.indexBuffer);break;case 35345:this._state.uniformBuffer=B(this.gl,t,e,this._state.uniformBuffer);break;case 35051:this._state.pixelPackBuffer=B(this.gl,t,e,this._state.pixelPackBuffer);break;case 35052:this._state.pixelUnpackBuffer=B(this.gl,t,e,this._state.pixelUnpackBuffer);break;case 36662:this._state.copyReadBuffer=B(this.gl,t,e,this._state.copyReadBuffer);break;case 36663:this._state.copyWriteBuffer=B(this.gl,t,e,this._state.copyWriteBuffer);break;case 35982:this._state.transformFeedbackBuffer=B(this.gl,t,e,this._state.transformFeedbackBuffer)}}bindRenderbuffer(t){const e=this.gl;t||(e.bindRenderbuffer(e.RENDERBUFFER,null),this._state.renderbuffer=null),this._state.renderbuffer!==t&&(e.bindRenderbuffer(e.RENDERBUFFER,t.glName),this._state.renderbuffer=t)}_getBufferBinding(t,e){if(e>=this.parameters.maxUniformBufferBindings||e<0)return console.error("Uniform buffer binding point is out of range!"),null;const s=35345===t?this._state.uniformBufferBindingPoints:this._state.transformBufferBindingPoints;let i=s[e];return null==i&&(i={buffer:null,offset:0,size:0},s[e]=i),i}bindBufferBase(t,e,s){const i=this._getBufferBinding(t,e);null!=i&&(i.buffer===s&&0===i.offset&&0===i.size||(this.gl.bindBufferBase(t,e,s?s.glName:null),i.buffer=s,i.offset=0,i.size=0))}bindBufferRange(t,e,s,i,a){const r=this._getBufferBinding(t,e);null!=r&&(r.buffer===s&&r.offset===i&&r.size===a||(i%this._parameters.uniformBufferOffsetAlignment===0?(this.gl.bindBufferRange(t,e,s.glName,i,a),r.buffer=s,r.offset=i,r.size=a):console.error("Uniform buffer binding offset is not a multiple of the context offset alignment")))}bindUBO(t,e,s,a){null!=e?(i()&&(a??e.byteLength)>this._parameters.maxUniformBlockSize&&console.error("Attempting to bind more data than the maximum uniform block size"),e.initialize(),void 0!==s&&void 0!==a?this.bindBufferRange(35345,t,e.buffer,s,a):this.bindBufferBase(35345,t,e.buffer)):this.bindBufferBase(35345,t,null)}unbindUBO(t){for(let e=0,s=this._state.uniformBufferBindingPoints.length;e<s;e++){const s=this._state.uniformBufferBindingPoints[e];null!=s&&s.buffer===t.buffer&&this.bindBufferBase(35345,e,null)}}unbindBuffer(t){switch(t){case 34962:this._state.vertexBuffer=B(this.gl,null,t,this._state.vertexBuffer);break;case 34963:this._state.indexBuffer=B(this.gl,null,t,this._state.indexBuffer);break;case 35345:this._state.uniformBuffer=B(this.gl,null,t,this._state.uniformBuffer);break;case 35051:this._state.pixelPackBuffer=B(this.gl,null,t,this._state.pixelPackBuffer);break;case 35052:this._state.pixelUnpackBuffer=B(this.gl,null,t,this._state.pixelUnpackBuffer);break;case 36662:this._state.copyReadBuffer=B(this.gl,null,t,this._state.copyReadBuffer);break;case 36663:this._state.copyWriteBuffer=B(this.gl,null,t,this._state.copyWriteBuffer)}}bindVAO(t=null){null!=t?this._state.vertexArrayObject!==t&&(t.bind(),this._state.vertexArrayObject=t):this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null)}bindTransformFeedback(t){const{gl:e}=this;e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,t.glName)}beginTransformFeedback(t,e){if(this._transformFeedbackRequestInfo)throw new Error("Already in a transform feedback request");const{gl:s}=this;s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,t.glName),s.beginTransformFeedback(e),this._transformFeedbackRequestInfo={primitiveType:e}}endTransformFeedback(){if(!this._transformFeedbackRequestInfo)throw new Error("Not in a transform feedback request");const{gl:t}=this;t.endTransformFeedback(),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null),this._transformFeedbackRequestInfo=null}async clientWaitAsync(t=s(10)){const{gl:i}=this,a=i.fenceSync(37143,0);if(!a)throw new Error("Client wait failed, could not create sync object");let r;this.instanceCounter.increment(f.Sync,a),i.flush();do{await e(t),r=i.clientWaitSync(a,0,0)}while(37147===r);if(this.instanceCounter.decrement(f.Sync,a),i.deleteSync(a),37149===r)throw new Error("Client wait failed")}getBoundFramebufferObject(t=36160){return 36008===t?this._state.readFramebuffer:this._state.drawFramebuffer}temporaryBindFramebufferObject(t,e,s=!1){const i=this.getBoundFramebufferObject();try{this.bindFramebuffer(t,s),e()}finally{this.bindFramebuffer(i,s)}}getBoundVAO(){return this._state.vertexArrayObject}resetState(){this.useProgram(null),this.bindVAO(null),this.bindFramebuffer(null,!0),this.unbindBuffer(34962),this.unbindBuffer(34963),this.unbindBuffer(35345),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(35051),this.unbindBuffer(35052),this.unbindBuffer(36662),this.unbindBuffer(36663);for(let t=0;t<this.parameters.maxTextureImageUnits;++t)this.bindTexture(null,t);this.setBlendingEnabled(!1),this.setBlendFunction(1,0),this.setBlendEquation(32774),this.setBlendColor(0,0,0,0),this.setFaceCullingEnabled(!1),this.setCullFace(1029),this.setFrontFace(2305),this.setPolygonOffsetFillEnabled(!1),this.setPolygonOffset(0,0),this.setScissorTestEnabled(!1),this.setScissorRect(0,0,this.gl.canvas.width,this.gl.canvas.height),this.setDepthTestEnabled(!1),this.setDepthFunction(513),this.setDepthRange(0,1),this.setStencilTestEnabled(!1),this.setStencilFunction(519,0,0),this.setStencilOp(7680,7680,7680),this.setClearColor(0,0,0,0),this.setClearDepth(1),this.setClearStencil(0),this.setColorMask(!0,!0,!0,!0),this.setStencilWriteMask(4294967295),this.setDepthWriteEnabled(!0),this.setDrawBuffers([1029]),this.setViewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}enforceState(){const{gl:t}=this;t.bindVertexArray(null);for(let s=0;s<this.parameters.maxVertexAttributes;s++)t.disableVertexAttribArray(s);this._state.vertexBuffer?t.bindBuffer(this._state.vertexBuffer.bufferType,this._state.vertexBuffer.glName):t.bindBuffer(34962,null),this._state.indexBuffer?t.bindBuffer(this._state.indexBuffer.bufferType,this._state.indexBuffer.glName):t.bindBuffer(34963,null),this._state.uniformBuffer?t.bindBuffer(this._state.uniformBuffer.bufferType,this._state.uniformBuffer.glName):t.bindBuffer(35345,null);for(let s=0;s<this._parameters.maxUniformBufferBindings;s++){const e=this._state.uniformBufferBindingPoints[s];if(null!=e){const{buffer:i,offset:a,size:r}=e;null!==i?0===a&&0===r?t.bindBufferBase(35345,s,i.glName):t.bindBufferRange(35345,s,i.glName,a,r):t.bindBufferBase(35345,s,null)}}if(this._state.pixelPackBuffer?t.bindBuffer(this._state.pixelPackBuffer.bufferType,this._state.pixelPackBuffer.glName):t.bindBuffer(35051,null),this._state.pixelUnpackBuffer?t.bindBuffer(this._state.pixelUnpackBuffer.bufferType,this._state.pixelUnpackBuffer.glName):t.bindBuffer(35052,null),this._state.copyReadBuffer?t.bindBuffer(this._state.copyReadBuffer.bufferType,this._state.copyReadBuffer.glName):t.bindBuffer(36662,null),this._state.copyWriteBuffer?t.bindBuffer(this._state.copyWriteBuffer.bufferType,this._state.copyWriteBuffer.glName):t.bindBuffer(36663,null),t.bindFramebuffer(36008,null),t.readBuffer(t.BACK),this._state.readFramebuffer&&(t.bindFramebuffer(36008,this._state.readFramebuffer.glName),t.readBuffer(l)),t.bindFramebuffer(36009,this._state.drawFramebuffer?.glName??null),null===this._state.drawFramebuffer){const e=this._state.drawBuffers.defaultFramebuffer;t.drawBuffers(e??[1029])}else{const e=this._state.drawBuffers.fbos.get(this._state.drawFramebuffer);t.drawBuffers(e??[l])}if(this._state.vertexArrayObject){const t=this._state.vertexArrayObject;this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null),this.bindVAO(t)}t.useProgram(this._state.program?.glName??null),t.blendColor(this._state.blendColor.r,this._state.blendColor.g,this._state.blendColor.b,this._state.blendColor.a),t.bindRenderbuffer(t.RENDERBUFFER,this._state.renderbuffer?.glName??null),!0===this._state.blend?t.enable(this.gl.BLEND):t.disable(this.gl.BLEND),t.blendEquationSeparate(this._state.blendEquation.mode,this._state.blendEquation.modeAlpha),t.blendFuncSeparate(this._state.blendFunction.srcRGB,this._state.blendFunction.dstRGB,this._state.blendFunction.srcAlpha,this._state.blendFunction.dstAlpha),t.clearColor(this._state.clearColor.r,this._state.clearColor.g,this._state.clearColor.b,this._state.clearColor.a),t.clearDepth(this._state.clearDepth),t.clearStencil(this._state.clearStencil),t.colorMask(this._state.colorMask.r,this._state.colorMask.g,this._state.colorMask.b,this._state.colorMask.a),t.cullFace(this._state.cullFace),t.depthFunc(this._state.depthFunction),t.depthRange(this._state.depthRange.zNear,this._state.depthRange.zFar),!0===this._state.depthTest?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),t.depthMask(this._state.depthWrite),t.frontFace(this._state.frontFace),t.lineWidth(1),!0===this._state.faceCulling?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),t.polygonOffset(this._state.polygonOffset[0],this._state.polygonOffset[1]),!0===this._state.polygonOffsetFill?t.enable(t.POLYGON_OFFSET_FILL):t.disable(t.POLYGON_OFFSET_FILL),t.scissor(this._state.scissorRect.x,this._state.scissorRect.y,this._state.scissorRect.width,this._state.scissorRect.height),!0===this._state.scissorTest?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST),t.stencilFunc(this._state.stencilFunction.func,this._state.stencilFunction.ref,this._state.stencilFunction.mask),t.stencilOpSeparate(this._state.stencilOperation.face,this._state.stencilOperation.fail,this._state.stencilOperation.zFail,this._state.stencilOperation.zPass),!0===this._state.stencilTest?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),t.stencilMask(this._state.stencilWriteMask);for(let s=0;s<this.parameters.maxTextureImageUnits;s++){t.activeTexture(h+s),t.bindTexture(3553,null),t.bindTexture(34067,null),t.bindTexture(32879,null),t.bindTexture(35866,null);const e=this._state.textureUnitMap[s];null!=e&&t.bindTexture(e.descriptor.target,e.glName)}t.activeTexture(h+this._state.activeTexture);const e=this._state.viewport;t.viewport(e.x,e.y,e.width,e.height),this.resetInfo()}};function B(t,e,s,i){return e?i!==e&&t.bindBuffer(s,e.glName):t.bindBuffer(s,null),e}function F(t,e){switch(t){case o.POINTS:return 2*e;case o.TRIANGLES:return e/3;case o.TRIANGLE_STRIP:case o.TRIANGLE_FAN:return e-2;default:return 0}}export{m as RenderingContext};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import"../../core/has.js";import{webglDebugEnabled as e}from"./checkWebGLError.js";import{CompressedTextureFormat as r,SizedPixelFormat as t,SizedDepthStencilFormat as s,SizedDepthFormat as a}from"./enums.js";import{getDataTypeBytes as c}from"./getDataTypeBytes.js";function n(e){const r=e.gl;switch(r.getError()){case r.NO_ERROR:return null;case r.INVALID_ENUM:return"An unacceptable value has been specified for an enumerated argument";case r.INVALID_VALUE:return"An unacceptable value has been specified for an argument";case r.INVALID_OPERATION:return"The specified command is not allowed for the current state";case r.INVALID_FRAMEBUFFER_OPERATION:return"The currently bound framebuffer is not framebuffer complete";case r.OUT_OF_MEMORY:return"Not enough memory is left to execute the command";case r.CONTEXT_LOST_WEBGL:return"WebGL context is lost"}return"Unknown error"}function o(e,r){return(e.vertexBuffers.get(r)?.sizeBytes??0)/i(e.layout.get(r))}function i(e){return e[0].stride}function R(r,t,s,a,o=0){const i=r.gl;r.bindBuffer(s);for(const R of a){const s=t.get(R.name);if(null==s){console.warn(`There is no location for vertex attribute '${R.name}' defined.`);continue}const a=o*R.stride;if(R.count<=4)i.vertexAttribPointer(s,R.count,R.type,R.normalized,R.stride,R.offset+a),i.enableVertexAttribArray(s),R.divisor>0&&r.gl.vertexAttribDivisor(s,R.divisor);else if(9===R.count)for(let e=0;e<3;e++)i.vertexAttribPointer(s+e,3,R.type,R.normalized,R.stride,R.offset+12*e+a),i.enableVertexAttribArray(s+e),R.divisor>0&&r.gl.vertexAttribDivisor(s+e,R.divisor);else if(16===R.count)for(let e=0;e<4;e++)i.vertexAttribPointer(s+e,4,R.type,R.normalized,R.stride,R.offset+16*e+a),i.enableVertexAttribArray(s+e),R.divisor>0&&r.gl?.vertexAttribDivisor(s+e,R.divisor);else console.error("Unsupported vertex attribute element count: "+R.count);if(e()){const e=n(r),t=c(R.type),s=R.offset,o=Math.round(t/s)!==t/s?`. Offset not a multiple of stride. DataType requires ${t} bytes, but descriptor has an offset of ${s}`:"";e&&console.error(`Unable to bind vertex attribute "${R.name}" with baseInstanceOffset ${a}${o}:`,e,R)}}}function u(e,r,t,s){const a=e.gl;e.bindBuffer(t);for(const c of s){const t=r.get(c.name);if(c.count<=4)a.disableVertexAttribArray(t),c.divisor&&c.divisor>0&&e.gl?.vertexAttribDivisor(t,0);else if(9===c.count)for(let r=0;r<3;r++)a.disableVertexAttribArray(t+r),c.divisor&&c.divisor>0&&e.gl?.vertexAttribDivisor(t+r,0);else if(16===c.count)for(let r=0;r<4;r++)a.disableVertexAttribArray(t+r),c.divisor&&c.divisor>0&&e.gl?.vertexAttribDivisor(t+r,0);else console.error("Unsupported vertex attribute element count: "+c.count)}e.unbindBuffer(34962)}function _(e){switch(e){case 6406:case 6409:case 6403:case 36244:case t.R8:case t.R8I:case t.R8UI:case t.R8_SNORM:case 36168:return 1;case 6410:case 33319:case 33320:case t.RGBA4:case t.R16F:case t.R16I:case t.R16UI:case t.RG8:case t.RG8I:case t.RG8UI:case t.RG8_SNORM:case t.RGB565:case t.RGB5_A1:case a.DEPTH_COMPONENT16:return 2;case 6407:case 36248:case t.RGB8:case t.RGB8I:case t.RGB8UI:case t.RGB8_SNORM:case t.SRGB8:case a.DEPTH_COMPONENT24:return 3;case 6408:case 36249:case t.RGBA8:case t.R32F:case t.R11F_G11F_B10F:case t.RG16F:case t.R32I:case t.R32UI:case t.RG16I:case t.RG16UI:case t.RGBA8I:case t.RGBA8UI:case t.RGBA8_SNORM:case t.SRGB8_ALPHA8:case t.RGB9_E5:case t.RGB10_A2UI:case t.RGB10_A2:case a.DEPTH_COMPONENT32F:case s.DEPTH24_STENCIL8:return 4;case s.DEPTH32F_STENCIL8:return 5;case t.RGB16F:case t.RGB16I:case t.RGB16UI:return 6;case t.RG32F:case t.RG32I:case t.RG32UI:case t.RGBA16F:case t.RGBA16I:case t.RGBA16UI:return 8;case t.RGB32F:case t.RGB32I:case t.RGB32UI:return 12;case t.RGBA32F:case t.RGBA32I:case t.RGBA32UI:return 16;case r.COMPRESSED_RGB_S3TC_DXT1_EXT:case r.COMPRESSED_RGBA_S3TC_DXT1_EXT:return.5;case r.COMPRESSED_RGBA_S3TC_DXT3_EXT:case r.COMPRESSED_RGBA_S3TC_DXT5_EXT:return 1;case r.COMPRESSED_R11_EAC:case r.COMPRESSED_SIGNED_R11_EAC:case r.COMPRESSED_RGB8_ETC2:case r.COMPRESSED_SRGB8_ETC2:case r.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:case r.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:return.5;case r.COMPRESSED_RG11_EAC:case r.COMPRESSED_SIGNED_RG11_EAC:case r.COMPRESSED_RGBA8_ETC2_EAC:case r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:return 1}return 0}export{R as bindVertexBufferLayout,_ as getBytesPerElementFormat,n as getErrorString,i as getStride,u as unbindVertexBufferLayout,o as vertexCount};
5
+ import"../../core/has.js";import{webglDebugEnabled as e,getErrorMessage as s}from"./checkWebGLError.js";import{CompressedTextureFormat as t,SizedPixelFormat as r,SizedDepthStencilFormat as a,SizedDepthFormat as c}from"./enums.js";import{getDataTypeBytes as R}from"./getDataTypeBytes.js";function o(e,s){return(e.vertexBuffers.get(s)?.sizeBytes??0)/n(e.layout.get(s))}function n(e){return e[0].stride}function i(t,r,a,c,o=0){const n=t.gl;t.bindBuffer(a);for(const i of c){const a=r.get(i.name);if(null==a){console.warn(`There is no location for vertex attribute '${i.name}' defined.`);continue}const c=o*i.stride;if(i.count<=4)n.vertexAttribPointer(a,i.count,i.type,i.normalized,i.stride,i.offset+c),n.enableVertexAttribArray(a),i.divisor>0&&n.vertexAttribDivisor(a,i.divisor);else if(9===i.count)for(let e=0;e<3;e++)n.vertexAttribPointer(a+e,3,i.type,i.normalized,i.stride,i.offset+12*e+c),n.enableVertexAttribArray(a+e),i.divisor>0&&n.vertexAttribDivisor(a+e,i.divisor);else if(16===i.count)for(let e=0;e<4;e++)n.vertexAttribPointer(a+e,4,i.type,i.normalized,i.stride,i.offset+16*e+c),n.enableVertexAttribArray(a+e),i.divisor>0&&n.vertexAttribDivisor(a+e,i.divisor);else console.error("Unsupported vertex attribute element count: "+i.count);if(e()){const e=s(t.gl),r=R(i.type),a=i.offset,o=Math.round(r/a)!==r/a?`. Offset not a multiple of stride. DataType requires ${r} bytes, but descriptor has an offset of ${a}`:"";e&&console.error(`Unable to bind vertex attribute "${i.name}" with baseInstanceOffset ${c}${o}:`,e,i)}}}function _(e){switch(e){case 6406:case 6409:case 6403:case 36244:case r.R8:case r.R8I:case r.R8UI:case r.R8_SNORM:case 36168:return 1;case 6410:case 33319:case 33320:case r.RGBA4:case r.R16F:case r.R16I:case r.R16UI:case r.RG8:case r.RG8I:case r.RG8UI:case r.RG8_SNORM:case r.RGB565:case r.RGB5_A1:case c.DEPTH_COMPONENT16:return 2;case 6407:case 36248:case r.RGB8:case r.RGB8I:case r.RGB8UI:case r.RGB8_SNORM:case r.SRGB8:case c.DEPTH_COMPONENT24:return 3;case 6408:case 36249:case r.RGBA8:case r.R32F:case r.R11F_G11F_B10F:case r.RG16F:case r.R32I:case r.R32UI:case r.RG16I:case r.RG16UI:case r.RGBA8I:case r.RGBA8UI:case r.RGBA8_SNORM:case r.SRGB8_ALPHA8:case r.RGB9_E5:case r.RGB10_A2UI:case r.RGB10_A2:case c.DEPTH_COMPONENT32F:case a.DEPTH24_STENCIL8:return 4;case a.DEPTH32F_STENCIL8:return 5;case r.RGB16F:case r.RGB16I:case r.RGB16UI:return 6;case r.RG32F:case r.RG32I:case r.RG32UI:case r.RGBA16F:case r.RGBA16I:case r.RGBA16UI:return 8;case r.RGB32F:case r.RGB32I:case r.RGB32UI:return 12;case r.RGBA32F:case r.RGBA32I:case r.RGBA32UI:return 16;case t.COMPRESSED_RGB_S3TC_DXT1_EXT:case t.COMPRESSED_RGBA_S3TC_DXT1_EXT:return.5;case t.COMPRESSED_RGBA_S3TC_DXT3_EXT:case t.COMPRESSED_RGBA_S3TC_DXT5_EXT:return 1;case t.COMPRESSED_R11_EAC:case t.COMPRESSED_SIGNED_R11_EAC:case t.COMPRESSED_RGB8_ETC2:case t.COMPRESSED_SRGB8_ETC2:case t.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:case t.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:return.5;case t.COMPRESSED_RG11_EAC:case t.COMPRESSED_SIGNED_RG11_EAC:case t.COMPRESSED_RGBA8_ETC2_EAC:case t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:return 1}return 0}export{i as bindVertexBufferLayout,_ as getBytesPerElementFormat,n as getStride,o as vertexCount};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../core/Error.js";import has from"../../core/has.js";import r from"../../core/Logger.js";const o=()=>r.getLogger("esri.views.webgl.checkWebGLError");function t(e){switch(e){case 1280:return"Invalid Enum. An unacceptable value has been specified for an enumerated argument.";case 1281:return"Invalid Value. A numeric argument is out of range.";case 1282:return"Invalid Operation. The specified command is not allowed for the current state.";case 1286:return"Invalid Framebuffer operation. The currently bound framebuffer is not framebuffer complete when trying to render to or to read from it.";case 1285:return"Out of memory. Not enough memory is left to execute the command.";case 37442:return"WebGL context has been lost";default:return"Unknown error"}}const n=!!has("enable-feature:webgl-debug");function a(){return n}function c(){return n}function u(r,n=a()){if(n){const n=r.getError();if(n){const r=t(n),a=(new Error).stack;o().error(new e("webgl-error","WebGL error occurred",{message:r,stack:a}))}}}export{u as checkWebGLError,t as getErrorMessage,n as hasFeatureFlagWebGLDebug,a as webglDebugEnabled,c as webglValidateShadersEnabled};
5
+ import e from"../../core/Error.js";import has from"../../core/has.js";import r from"../../core/Logger.js";const n=()=>r.getLogger("esri.views.webgl.checkWebGLError");function t(e){switch(e.getError()){case e.NO_ERROR:return null;case e.INVALID_ENUM:return"Invalid Enum. An unacceptable value has been specified for an enumerated argument.";case e.INVALID_VALUE:return"Invalid Value. A numeric argument is out of range.";case e.INVALID_OPERATION:return"Invalid Operation. The specified command is not allowed for the current state.";case e.INVALID_FRAMEBUFFER_OPERATION:return"Invalid Framebuffer operation. The currently bound framebuffer is not framebuffer complete when trying to render to or to read from it.";case e.OUT_OF_MEMORY:return"Out of memory. Not enough memory is left to execute the command.";case e.CONTEXT_LOST_WEBGL:return"WebGL context has been lost";default:return"Unknown error"}}const o=!!has("enable-feature:webgl-debug");function a(){return o}function c(){return o}function u(r,o=a()){if(o){const o=t(r);if(o){const r=(new Error).stack;n().error(new e("webgl-error","WebGL error occurred",{message:o,stack:r}))}}}export{u as checkWebGLError,t as getErrorMessage,o as hasFeatureFlagWebGLDebug,a as webglDebugEnabled,c as webglValidateShadersEnabled};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{BufferObject as e}from"./BufferObject.js";import{SizedPixelFormat as r,DataType as t,PrimitiveType as o}from"./enums.js";import{FramebufferObject as n}from"./FramebufferObject.js";import{makePipelineState as i,destinationTimesOneMinusSourceAlpha as s}from"./renderState.js";import{TextureDescriptor as a}from"./TextureDescriptor.js";import{VertexArrayObject as p}from"./VertexArrayObject.js";import{VertexElementDescriptor as c}from"./VertexElementDescriptor.js";import{WebGLDriverTestModule as m}from"./WebGLDriverTestModule.js";class f extends m{constructor(e){if(super(),this._rctx=e,!e.gl)return;if(!(e.capabilities.colorBufferFloat?.textureFloat&&e.capabilities.colorBufferFloat?.floatBlend))return;const r="\n precision highp float;\n attribute vec2 a_pos;\n\n void main() {\n gl_Position = vec4(a_pos * 2.0 - 1.0, 0.0, 1.0);\n }\n ",t="\n precision highp float;\n\n void main() {\n gl_FragColor = vec4(0.5, 0.5, 0.5, 0.5);\n }\n ";this._program=e.programCache.acquire(r,t,new Map([["a_pos",0]]))}_test(m){const f=this._rctx,l=new a(1);l.wrapMode=33071,l.dataType=5126,l.internalFormat=r.RGBA32F,l.samplingMode=9728;const u=new n(f,l),b=e.createVertex(f,35044,new Uint16Array([0,0,1,0,0,1,1,1])),d=new p(f,new Map([["a_pos",0]]),new Map([["geometry",[new c("a_pos",2,t.UNSIGNED_SHORT,0,4)]]]),new Map([["geometry",b]]));f.gl.getError(),f.useProgram(m);const g=f.getBoundFramebufferObject(),{x:w,y:_,width:j,height:x}=f.getViewport();f.bindFramebuffer(u),f.setViewport(0,0,1,1),f.bindVAO(d),f.drawArrays(o.TRIANGLE_STRIP,0,4);const h=i({blending:s});f.setPipelineState(h),f.drawArrays(o.TRIANGLE_STRIP,0,4);const F=f.gl.getError();return f.setViewport(w,_,j,x),f.bindFramebuffer(g),d.dispose(),u.dispose(),1282!==F||(console.warn("Device claims support for WebGL extension EXT_float_blend but does not support it. Using fall back."),!1)}}export{f as FloatBufferBlend};
5
+ import{BufferObject as e}from"./BufferObject.js";import{SizedPixelFormat as r,DataType as t,PrimitiveType as o}from"./enums.js";import{FramebufferObject as n}from"./FramebufferObject.js";import{makePipelineState as i,destinationTimesOneMinusSourceAlpha as s}from"./renderState.js";import{TextureDescriptor as a}from"./TextureDescriptor.js";import{VertexArrayObject as p}from"./VertexArrayObject.js";import{VertexElementDescriptor as c}from"./VertexElementDescriptor.js";import{WebGLDriverTestModule as m}from"./WebGLDriverTestModule.js";class l extends m{constructor(e){if(super(),this._rctx=e,!e.gl)return;if(!(e.capabilities.colorBufferFloat?.textureFloat&&e.capabilities.colorBufferFloat?.floatBlend))return;const r="\n precision highp float;\n attribute vec2 a_pos;\n\n void main() {\n gl_Position = vec4(a_pos * 2.0 - 1.0, 0.0, 1.0);\n }\n ",t="\n precision highp float;\n\n void main() {\n gl_FragColor = vec4(0.5, 0.5, 0.5, 0.5);\n }\n ";this._program=e.programCache.acquire(r,t,new Map([["a_pos",0]]))}_test(m){const l=this._rctx,f=new a(1);f.wrapMode=33071,f.dataType=5126,f.internalFormat=r.RGBA32F,f.samplingMode=9728;const u=new n(l,f),g=e.createVertex(l,35044,new Uint16Array([0,0,1,0,0,1,1,1])),b=new p(l,new Map([["a_pos",0]]),new Map([["geometry",[new c("a_pos",2,t.UNSIGNED_SHORT,0,4)]]]),new Map([["geometry",g]]));l.gl.getError(),l.useProgram(m);const d=l.getBoundFramebufferObject(),{x:w,y:_,width:j,height:x}=l.getViewport();l.bindFramebuffer(u),l.setViewport(0,0,1,1),l.bindVAO(b),l.drawArrays(o.TRIANGLE_STRIP,0,4);const h=i({blending:s});l.setPipelineState(h),l.drawArrays(o.TRIANGLE_STRIP,0,4);const A=l.gl.getError();return l.setViewport(w,_,j,x),l.bindFramebuffer(d),b.dispose(),u.dispose(),A!==l.gl.INVALID_OPERATION||(console.warn("Device claims support for WebGL extension EXT_float_blend but does not support it. Using fall back."),!1)}}export{l as FloatBufferBlend};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.34/esri/copyright.txt for details.
4
4
  */
5
- import{__decorate as t}from"tslib";import{getAssetUrl as e}from"../../assets.js";import o from"../../Graphic.js";import"../../intl.js";import i from"../../core/Collection.js";import s from"../../core/Error.js";import r from"../../core/Evented.js";import n from"../../core/Logger.js";import{watch as a,initial as h,when as c}from"../../core/reactiveUtils.js";import{property as d}from"../../core/accessorSupport/decorators/property.js";import{cast as l}from"../../core/accessorSupport/decorators/cast.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as m}from"../../core/accessorSupport/decorators/subclass.js";import p from"../../geometry/Point.js";import{load as v}from"../../geometry/projectionUtils.js";import u from"../../symbols/PictureMarkerSymbol.js";import{pointSymbolTypes as f}from"../../symbols/support/typeUtils.js";import g from"./support/Conversion.js";import{isValidPoint as w,isSupportedNotation as _}from"./support/coordinateConversionUtils.js";import y from"./support/Format.js";import{generateDefaultFormats as C,setDefaultPatterns as b}from"./support/formatUtils.js";import L from"../support/GoTo.js";import{fetchMessageBundle as M}from"../../intl/messages.js";import{onLocaleChange as P,getLocale as j}from"../../intl/locale.js";const S={default:"default",crosshair:"crosshair"},F=new p([0,0,500]),G="xy",H=["mgrs","utm","usng","dd","dms","ddm"],E="esri__coordinateConversionWidgetState",x={conversions:"conversions",formats:"formats",view:"view",viewChange:"view-change"},T="esri/images/search/search-symbol-32.png";let W=class extends(L(r.EventedAccessor)){constructor(t){super(t),this._conversionPromise=null,this._locationGraphic=null,this._pointerCount=0,this.conversions=new i,this.formats=new i,this.formatterAvailable=!1,this.messages=null,this.filteredFormats=new i,this.locationSymbol=new u({url:e(T),width:24,height:24}),this.storageEnabled=!0,this.storageType="session",this.view=null,this._saveWidgetState=this._saveWidgetState.bind(this),this._handleFormatChange=this._handleFormatChange.bind(this),this._handleConversionChange=this._handleConversionChange.bind(this),this._handleViewChange=this._handleViewChange.bind(this),this._onClick=this._onClick.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerUp=this._onPointerUp.bind(this)}initialize(){const t=async()=>this.messages=await M("esri/widgets/CoordinateConversion/t9n/CoordinateConversion");this.formats.addMany(C()),t().then(()=>{if(!this.destroyed&&(b(this.messages,this.formats),this.storageEnabled&&this._loadWidgetState(),this.formats.forEach(t=>{t.viewModel=this,this.addHandles(a(()=>t.currentPattern,this._saveWidgetState),t.name??"unnamed-format")}),this.addHandles(this.conversions.on("change",this._handleConversionChange),x.conversions),this.addHandles(this.formats.on("change",this._handleFormatChange),x.formats),this.addHandles(P(()=>{t().then(()=>{b(this.messages,this.formats)})})),v().then(()=>{this.formatterAvailable=!0}).catch(t=>{n.getLogger(this).error(new s("coordinate-conversion:projection-load-failed","Failed to load the projection module.",{error:t})),this.formatterAvailable=!1,this._filterFormatsAndConversions()}).then(()=>this.addHandles(a(()=>this.view,this._handleViewChange,h),x.viewChange)),0===this.conversions.length)){const t=this.formats.find(t=>t.name===G)||this.formats.at(0);this.conversions.add(new g({format:t}))}})}destroy(){this.removeHandles(),this._cleanUpView(this.view),this.view=null}castConversions(t){return this._castToConversions(t)}set currentLocation(t){this._set("currentLocation",t),this._updateConversions()}get currentLocation(){return this._get("currentLocation")||null}set mode(t){switch(t){case"capture":this.currentLocation=null,this._startCaptureMode(),this._set("mode",t);break;case"live":this._startLiveMode(),this._set("mode",t)}}get mode(){return this._get("mode")||"live"}get state(){const{messages:t,view:e}=this,o=e?.ready;return t?o?"ready":e?"loading":"disabled":"disabled"}get storage(){const{storageType:t}=this;return"session"===t?sessionStorage:localStorage}get waitingForConversions(){return null!=this._conversionPromise}setLocation(t){if(this._locationGraphic&&this.view?.graphics.remove(this._locationGraphic),!t)return;const e=t.clone();e.hasZ&&(e.z=void 0),this._locationGraphic=new o({geometry:e,symbol:this.locationSymbol}),this.view?.graphics.add(this._locationGraphic)}async convert(t,e){if(!w(e))throw new s("coordinate-conversion:invalid-point","Invalid point cannot be converted.",{point:e});return Promise.resolve().then(()=>t.convert(e))}async goToLocation(t){const{view:e}=this;if(!e)throw new s("coordinate-conversion:go-to-failed","no view");const o="3d"===e.type?e.clippingArea:null,i=e.map?.basemap?.baseLayers;if(o||(i?.length??0)>0){const e=o??i?.at(0)?.fullExtent;if(null!=e&&!e.contains(t))throw new s("coordinate-conversion:go-to-failed","Point outside basemap extent.",{point:t})}return this.callGoTo({target:t})}pause(){this.currentLocation=null,this.removeHandles(x.view),this.view&&(this.view.cursor=S.default,this._locationGraphic&&this.view.graphics.remove(this._locationGraphic))}async previewConversion(t,e=this.currentLocation||F){return(await U(t,e)).displayCoordinate}resume(){"capture"===this.mode?this._startCaptureMode():this._startLiveMode()}reverseConvert(t,e){return e.reverseConvert(t)}async updateConversions(t,e){if("point"!==e?.type)throw this._clearConversions(this.conversions),new s("coordinate-conversion:invalid-input-point","Point is invalid, conversions cannot be updated.",{point:e});return this._convertMany(t,e)}_castToConversions(t){const e=new i;return t.forEach(t=>{let o=null;if(t instanceof g)o=t;else if("string"==typeof t){const e=this.formats.find(e=>e.name===t);e&&(o=new g({format:e}))}o&&e.add(o)}),e}_cleanUpView(t){t&&(this._locationGraphic&&t.graphics.remove(this._locationGraphic),this.removeHandles(x.view),t.cursor=S.default)}_clearConversions(t){t.forEach(t=>{t.position={location:null,coordinate:null}})}async _convertMany(t,e){return Promise.all(t.map(t=>U(t,e)))}_handleConversionChange(t){for(const e of t.added){const{format:t}=e;t&&(t.viewModel=this,this.currentLocation&&(this._set("waitingForConversions",!0),this.convert(t,this.currentLocation).then(t=>{e.position=t,this._set("waitingForConversions",!1)})))}this._saveWidgetState()}_handleFormatChange(t){t.added.forEach(t=>{this.addHandles(a(()=>t.currentPattern,this._saveWidgetState),t.name??"unnamed-format"),t.viewModel=this}),t.removed.forEach(t=>{t.viewModel=null;const e=this.conversions.filter(e=>e.format===t);this.conversions.removeMany(e),t.name&&this.removeHandles(t.name)})}_loadWidgetState(){try{const t=JSON.parse(this.storage.getItem(E));t&&this._setWidgetState(t)}catch(t){n.getLogger(this).error(new s("coordinate-conversion:invalid-session-storage-json","Could not read from storage.",{error:t}))}}_startCaptureMode(){this.removeHandles(x.view),this.view&&(this.view.cursor=S.crosshair,this.currentLocation&&this.setLocation(this.currentLocation),this.addHandles(this.view.on("click",this._onClick),x.view))}_startLiveMode(){this._pointerCount=0,this.removeHandles(x.view),this.view&&(this.view.cursor=S.default,this._locationGraphic&&this.view.graphics.remove(this._locationGraphic),this.addHandles([this.view.on("pointer-down",this._onPointerDown),this.view.on("pointer-up",this._onPointerUp),this.view.on("pointer-move",this._onPointerMove)],x.view))}_handleViewChange(t,e){e&&e!==t&&this._cleanUpView(e),t&&("capture"===this.mode?this._startCaptureMode():this._startLiveMode(),e&&this._filterFormatsAndConversions())}_onClick(t){if(0===t.button){const e=this.view?.toMap(t),o=e?.normalize();this.setLocation(o),this.currentLocation=o}}_onPointerDown(t){const{pointerType:e}=t;if(this._pointerCount++,("touch"===e||"pen"===e)&&1===this._pointerCount){const e=this.view?.toMap(t);this.currentLocation=e?.normalize()}}_onPointerMove(t){const{pointerType:e}=t;if("mouse"===e||1===this._pointerCount){const e=this.view?.toMap(t);this.currentLocation=e?.normalize()}}_onPointerUp(){this._pointerCount--}_setWidgetState(t){try{t.formats.forEach(e=>{const o=this.formats.find(t=>t.name===e.name);o&&t.locale===j()&&e.currentPattern&&(o.currentPattern=e.currentPattern),o&&e.index>=0&&this.conversions.add(new g({format:o}))})}catch(e){n.getLogger(this).warn(new s("coordinate-conversion:session-storage-read-error","Could not get widget state from stored JSON.",{error:e}))}}_saveWidgetState(){if(!this.storageEnabled)return;const t=this._toJSON();try{this.storage.setItem(E,JSON.stringify({formats:t,locale:j()}))}catch(e){n.getLogger(this).error(new s("coordinate-conversion:local-storage-write-error","Could not write to localStorage.",{error:e}))}}async _updateConversions(){try{await this.updateConversions(this.conversions.toArray(),this.currentLocation)}catch{}}_toJSON(){return this.formats.filter(t=>{const e=t.name;return"xy"===e||"basemap"===e||_(e)}).map(t=>({name:t.name,currentPattern:t.currentPattern,defaultPattern:t.defaultPattern,index:this.conversions.findIndex(e=>e.format===t)})).sort((t,e)=>t.index-e.index).toArray()}_filterFormatsAndConversions(){const{formatterAvailable:t,conversions:e,formats:o}=this;t||this.addHandles(c(()=>this.view?.spatialReference,t=>{const i=t.isWebMercator||t.isWGS84,s=o.filter(t=>{const{name:e}=t;return!!A(e)||"xy"===e&&!i}),r=this.filteredFormats.filter(t=>"xy"===t.name&&i&&!this.formats.includes(t)),n=e.filter(t=>s.includes(t.format));o.removeMany(s),e.removeMany(n),this.filteredFormats.addMany(s.filter(t=>!this.filteredFormats.includes(t))),o.addMany(r)},{once:!0,initial:!0}),x.view)}};async function U(t,e){try{t.position=await(t.format?.convert(e))}catch(o){t.position=null}return t}function A(t){return H.includes(t)}t([d({type:i.ofType(g)})],W.prototype,"conversions",void 0),t([l("conversions")],W.prototype,"castConversions",null),t([d({type:p})],W.prototype,"currentLocation",null),t([d({type:i.ofType(y)})],W.prototype,"formats",void 0),t([d()],W.prototype,"messages",void 0),t([d()],W.prototype,"mode",null),t([d()],W.prototype,"filteredFormats",void 0),t([d({readOnly:!0})],W.prototype,"state",null),t([d({types:f})],W.prototype,"locationSymbol",void 0),t([d({readOnly:!0,dependsOn:["storageType"]})],W.prototype,"storage",null),t([d()],W.prototype,"storageEnabled",void 0),t([d()],W.prototype,"storageType",void 0),t([d({readOnly:!0})],W.prototype,"waitingForConversions",null),t([d()],W.prototype,"view",void 0),W=t([m("esri.widgets.CoordinateConversion.CoordinateConversionViewModel")],W);const O=W;export{O as default};
5
+ import{__decorate as t}from"tslib";import{getAssetUrl as e}from"../../assets.js";import o from"../../Graphic.js";import"../../intl.js";import i from"../../core/Collection.js";import s from"../../core/Error.js";import r from"../../core/Evented.js";import n from"../../core/Logger.js";import{watch as a,initial as h,when as c}from"../../core/reactiveUtils.js";import{property as d}from"../../core/accessorSupport/decorators/property.js";import{cast as l}from"../../core/accessorSupport/decorators/cast.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as m}from"../../core/accessorSupport/decorators/subclass.js";import p from"../../geometry/Point.js";import{load as v}from"../../geometry/projectionUtils.js";import u from"../../symbols/PictureMarkerSymbol.js";import{pointSymbolTypes as f}from"../../symbols/support/typeUtils.js";import g from"./support/Conversion.js";import{isValidPoint as w,isSupportedNotation as _}from"./support/coordinateConversionUtils.js";import y from"./support/Format.js";import{generateDefaultFormats as C,setDefaultPatterns as b}from"./support/formatUtils.js";import L from"../support/GoTo.js";import{fetchMessageBundle as M}from"../../intl/messages.js";import{onLocaleChange as P,getLocale as j}from"../../intl/locale.js";const S=new p([0,0,500]),H="xy",F=["mgrs","utm","usng","dd","dms","ddm"],G="esri__coordinateConversionWidgetState",E={conversions:"conversions",formats:"formats",view:"view",viewChange:"view-change",cursor:"cursor"},x="esri/images/search/search-symbol-32.png";let T=class extends(L(r.EventedAccessor)){constructor(t){super(t),this._conversionPromise=null,this._locationGraphic=null,this._pointerCount=0,this.conversions=new i,this.formats=new i,this.formatterAvailable=!1,this.messages=null,this.filteredFormats=new i,this.locationSymbol=new u({url:e(x),width:24,height:24}),this.storageEnabled=!0,this.storageType="session",this.view=null,this._saveWidgetState=this._saveWidgetState.bind(this),this._handleFormatChange=this._handleFormatChange.bind(this),this._handleConversionChange=this._handleConversionChange.bind(this),this._handleViewChange=this._handleViewChange.bind(this),this._onClick=this._onClick.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerUp=this._onPointerUp.bind(this)}initialize(){const t=async()=>this.messages=await M("esri/widgets/CoordinateConversion/t9n/CoordinateConversion");this.formats.addMany(C()),t().then(()=>{if(!this.destroyed&&(b(this.messages,this.formats),this.storageEnabled&&this._loadWidgetState(),this.formats.forEach(t=>{t.viewModel=this,this.addHandles(a(()=>t.currentPattern,this._saveWidgetState),t.name??"unnamed-format")}),this.addHandles(this.conversions.on("change",this._handleConversionChange),E.conversions),this.addHandles(this.formats.on("change",this._handleFormatChange),E.formats),this.addHandles(P(()=>{t().then(()=>{b(this.messages,this.formats)})})),v().then(()=>{this.formatterAvailable=!0}).catch(t=>{n.getLogger(this).error(new s("coordinate-conversion:projection-load-failed","Failed to load the projection module.",{error:t})),this.formatterAvailable=!1,this._filterFormatsAndConversions()}).then(()=>this.addHandles(a(()=>this.view,this._handleViewChange,h),E.viewChange)),0===this.conversions.length)){const t=this.formats.find(t=>t.name===H)||this.formats.at(0);this.conversions.add(new g({format:t}))}})}destroy(){this.removeHandles(),this._cleanUpView(this.view),this.view=null}castConversions(t){return this._castToConversions(t)}set currentLocation(t){this._set("currentLocation",t),this._updateConversions()}get currentLocation(){return this._get("currentLocation")||null}set mode(t){switch(t){case"capture":this.currentLocation=null,this._startCaptureMode(),this._set("mode",t);break;case"live":this._startLiveMode(),this._set("mode",t)}}get mode(){return this._get("mode")||"live"}get state(){const{messages:t,view:e}=this,o=e?.ready;return t?o?"ready":e?"loading":"disabled":"disabled"}get storage(){const{storageType:t}=this;return"session"===t?sessionStorage:localStorage}get waitingForConversions(){return null!=this._conversionPromise}setLocation(t){if(this._locationGraphic&&this.view?.graphics.remove(this._locationGraphic),!t)return;const e=t.clone();e.hasZ&&(e.z=void 0),this._locationGraphic=new o({geometry:e,symbol:this.locationSymbol}),this.view?.graphics.add(this._locationGraphic)}async convert(t,e){if(!w(e))throw new s("coordinate-conversion:invalid-point","Invalid point cannot be converted.",{point:e});return Promise.resolve().then(()=>t.convert(e))}async goToLocation(t){const{view:e}=this;if(!e)throw new s("coordinate-conversion:go-to-failed","no view");const o="3d"===e.type?e.clippingArea:null,i=e.map?.basemap?.baseLayers;if(o||(i?.length??0)>0){const e=o??i?.at(0)?.fullExtent;if(null!=e&&!e.contains(t))throw new s("coordinate-conversion:go-to-failed","Point outside basemap extent.",{point:t})}return this.callGoTo({target:t})}pause(){this.currentLocation=null,this.removeHandles(E.view),this.view&&(this.removeHandles(E.cursor),this._locationGraphic&&this.view.graphics.remove(this._locationGraphic))}async previewConversion(t,e=this.currentLocation||S){return(await W(t,e)).displayCoordinate}resume(){"capture"===this.mode?this._startCaptureMode():this._startLiveMode()}reverseConvert(t,e){return e.reverseConvert(t)}async updateConversions(t,e){if("point"!==e?.type)throw this._clearConversions(this.conversions),new s("coordinate-conversion:invalid-input-point","Point is invalid, conversions cannot be updated.",{point:e});return this._convertMany(t,e)}_castToConversions(t){const e=new i;return t.forEach(t=>{let o=null;if(t instanceof g)o=t;else if("string"==typeof t){const e=this.formats.find(e=>e.name===t);e&&(o=new g({format:e}))}o&&e.add(o)}),e}_cleanUpView(t){t&&(this._locationGraphic&&t.graphics.remove(this._locationGraphic),this.removeHandles(E.view),this.removeHandles(E.cursor))}_clearConversions(t){t.forEach(t=>{t.position={location:null,coordinate:null}})}async _convertMany(t,e){return Promise.all(t.map(t=>W(t,e)))}_handleConversionChange(t){for(const e of t.added){const{format:t}=e;t&&(t.viewModel=this,this.currentLocation&&(this._set("waitingForConversions",!0),this.convert(t,this.currentLocation).then(t=>{e.position=t,this._set("waitingForConversions",!1)})))}this._saveWidgetState()}_handleFormatChange(t){t.added.forEach(t=>{this.addHandles(a(()=>t.currentPattern,this._saveWidgetState),t.name??"unnamed-format"),t.viewModel=this}),t.removed.forEach(t=>{t.viewModel=null;const e=this.conversions.filter(e=>e.format===t);this.conversions.removeMany(e),t.name&&this.removeHandles(t.name)})}_loadWidgetState(){try{const t=JSON.parse(this.storage.getItem(G));t&&this._setWidgetState(t)}catch(t){n.getLogger(this).error(new s("coordinate-conversion:invalid-session-storage-json","Could not read from storage.",{error:t}))}}_startCaptureMode(){this.removeHandles(E.view),this.view&&(this.currentLocation&&this.setLocation(this.currentLocation),this.removeHandles(E.cursor),this.addHandles(this.view.acquireCursor("crosshair","high"),E.cursor),this.addHandles(this.view.on("click",this._onClick),E.view))}_startLiveMode(){this._pointerCount=0,this.removeHandles(E.view),this.view&&(this.removeHandles(E.cursor),this._locationGraphic&&this.view.graphics.remove(this._locationGraphic),this.addHandles([this.view.on("pointer-down",this._onPointerDown),this.view.on("pointer-up",this._onPointerUp),this.view.on("pointer-move",this._onPointerMove)],E.view))}_handleViewChange(t,e){e&&e!==t&&this._cleanUpView(e),t&&("capture"===this.mode?this._startCaptureMode():this._startLiveMode(),e&&this._filterFormatsAndConversions())}_onClick(t){if(0===t.button){const e=this.view?.toMap(t),o=e?.normalize();this.setLocation(o),this.currentLocation=o}}_onPointerDown(t){const{pointerType:e}=t;if(this._pointerCount++,("touch"===e||"pen"===e)&&1===this._pointerCount){const e=this.view?.toMap(t);this.currentLocation=e?.normalize()}}_onPointerMove(t){const{pointerType:e}=t;if("mouse"===e||1===this._pointerCount){const e=this.view?.toMap(t);this.currentLocation=e?.normalize()}}_onPointerUp(){this._pointerCount--}_setWidgetState(t){try{t.formats.forEach(e=>{const o=this.formats.find(t=>t.name===e.name);o&&t.locale===j()&&e.currentPattern&&(o.currentPattern=e.currentPattern),o&&e.index>=0&&this.conversions.add(new g({format:o}))})}catch(e){n.getLogger(this).warn(new s("coordinate-conversion:session-storage-read-error","Could not get widget state from stored JSON.",{error:e}))}}_saveWidgetState(){if(!this.storageEnabled)return;const t=this._toJSON();try{this.storage.setItem(G,JSON.stringify({formats:t,locale:j()}))}catch(e){n.getLogger(this).error(new s("coordinate-conversion:local-storage-write-error","Could not write to localStorage.",{error:e}))}}async _updateConversions(){try{await this.updateConversions(this.conversions.toArray(),this.currentLocation)}catch{}}_toJSON(){return this.formats.filter(t=>{const e=t.name;return"xy"===e||"basemap"===e||_(e)}).map(t=>({name:t.name,currentPattern:t.currentPattern,defaultPattern:t.defaultPattern,index:this.conversions.findIndex(e=>e.format===t)})).sort((t,e)=>t.index-e.index).toArray()}_filterFormatsAndConversions(){const{formatterAvailable:t,conversions:e,formats:o}=this;t||this.addHandles(c(()=>this.view?.spatialReference,t=>{const i=t.isWebMercator||t.isWGS84,s=o.filter(t=>{const{name:e}=t;return!!U(e)||"xy"===e&&!i}),r=this.filteredFormats.filter(t=>"xy"===t.name&&i&&!this.formats.includes(t)),n=e.filter(t=>s.includes(t.format));o.removeMany(s),e.removeMany(n),this.filteredFormats.addMany(s.filter(t=>!this.filteredFormats.includes(t))),o.addMany(r)},{once:!0,initial:!0}),E.view)}};async function W(t,e){try{t.position=await(t.format?.convert(e))}catch(o){t.position=null}return t}function U(t){return F.includes(t)}t([d({type:i.ofType(g)})],T.prototype,"conversions",void 0),t([l("conversions")],T.prototype,"castConversions",null),t([d({type:p})],T.prototype,"currentLocation",null),t([d({type:i.ofType(y)})],T.prototype,"formats",void 0),t([d()],T.prototype,"messages",void 0),t([d()],T.prototype,"mode",null),t([d()],T.prototype,"filteredFormats",void 0),t([d({readOnly:!0})],T.prototype,"state",null),t([d({types:f})],T.prototype,"locationSymbol",void 0),t([d({readOnly:!0,dependsOn:["storageType"]})],T.prototype,"storage",null),t([d()],T.prototype,"storageEnabled",void 0),t([d()],T.prototype,"storageType",void 0),t([d({readOnly:!0})],T.prototype,"waitingForConversions",null),t([d()],T.prototype,"view",void 0),T=t([m("esri.widgets.CoordinateConversion.CoordinateConversionViewModel")],T);const A=T;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/4.34/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../Color.js";import t from"../../Graphic.js";import{isSome as r,equals as n,addMany as a}from"../../core/arrayUtils.js";import{createTask as o}from"../../core/asyncUtils.js";import"../../core/has.js";import i from"../../core/Error.js";import{handlesGroup as s,makeHandle as l,abortHandle as c}from"../../core/handleUtils.js";import{clone as u}from"../../core/lang.js";import p from"../../core/Logger.js";import{getOrCreateMapValue as d}from"../../core/MapUtils.js";import{debounce as f,isPromiseLike as y,throwIfAborted as m,whenOrAbort as h}from"../../core/promiseUtils.js";import{watch as g,on as b,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as v}from"../../core/screenUtils.js";import{diff as I}from"../../core/accessorSupport/diffUtils.js";import{isSharedTemplateOrMetadata as T,isSharedGroupTemplate as S,isSharedTemplate as j,isSharedPresetTemplate as F,isStandardFeatureTemplate as k,isSharedFeatureTemplate as A}from"../../editing/templateUtils.js";import{getSharedTemplateProvider as U}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import V from"../../layers/GraphicsLayer.js";import{featureHasFields as L,fixFields as M,getDisplayFieldName as O}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as x}from"../../layers/support/layerUtils.js";import{calculateTolerance as z}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as q}from"../../renderers/support/lengthUtils.js";import{isRenderer as P}from"../../renderers/support/typeUtils.js";import{getTransformationType as E}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import C from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import D from"../../symbols/SimpleMarkerSymbol.js";import{to3D as G}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as B}from"../../symbols/support/symbolUtils.js";import{getServices as N}from"../../undoredo/support/Services.js";import{GraphicState as Z}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as W}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as Q}from"../../views/support/drapedUtils.js";import{filterGraphicHits as $,hitTestSelectSimilarDistance as J}from"../../views/support/hitTestSelectUtils.js";import{dependencySort as H}from"./support/dependencySort.js";import{isDrawGraphicTool as K}from"../Sketch/support/sketchUtils.js";const X=()=>p.getLogger("esri.widgets.Editor.workflowUtils");function Y(e){return!!e&&"features"in e}function _(e){return null!=e&&"create-features"===e.type}function ee(e){return null!=e&&"update-features"===e.type}function te(e){return null!=e&&/update-/.test(e.type)&&"fullFeature"in e}function re(e){return null!=e&&"update"===e.type}function ne(e){const t=e&&"renderer"in e?e.renderer:null;if(!ue(t))return{rotation:null,size:null};const r=t.getVisualVariablesForType("rotation").filter(e=>(!e.axis||"heading"===e.axis)&&e.field&&!e.valueExpression),n=t.getVisualVariablesForType("size").filter(e=>e.field&&!e.useSymbolValue&&!e.valueExpression&&"real-world-size"===E(e));return{rotation:1===r.length?r[0]:null,size:1===n.length?n[0]:null}}function ae(e){const t=e.sourceLayer;if(!(t&&"renderer"in t&&ue(t.renderer)))return{rotation:null,size:null};const{rotation:r,size:n}=ne(t);let a=null,o=null;if(r){const e=t.fields?.filter(e=>e.name===r.field),n=1===e?.length?e[0]:null;a=oe(r,n)}if(n){const e=t.fields?.filter(e=>e.name===n.field),r=1===e?.length?e[0]:null;o=le(n,r)}return{rotation:a,size:o}}function oe(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,n=t?.type??"double",a={initial:0,current:0};return{field:e.field,fieldType:n,getDefaultValue:()=>Promise.resolve(0),getValue:e=>(a.current=a.initial-r*e,ce((a.current+360)%360,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,rotationType:e.rotationType??"geographic"}}function ie(e,t){switch(t){case"width":return e[0];case"depth":return e[1];case"height":return e[2];default:return e[2]||e[1]||e[0]}}async function se(e,t,r){if(null==t)return 0;const{symbol:n}=G(t);if(null==n||"web-style"===n.type||"cim"===n.type)return 0;const a=n.symbolLayers.at(0);if(!a)return 0;switch(a.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return Math.min(Ke.icon,(await e(a,Ke.icon))[0])||Ke.icon}case"text":return Ke.text;case"line":return Ke.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ie(await t(a,e.scale/Ke.viewScaleSizeFactor),r)}case"path":case"extrude":return e.scale/Ke.viewScaleSizeFactor;default:return 0}}function le(e,t){const r=e.axis,n=t?.type??"double",a={initial:0,current:0},o=q[e.valueUnit]??1;let i;return i="area"===e.valueRepresentation?e=>(e*o/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*o/2:e=>e*o,{field:e.field,fieldType:n,getDefaultValue:async(e,t)=>ce(i(await se(t,e,r)),n),getValue:(e,t)=>(a.initial||(a.initial=t.pixelSizeAt(t.center)),a.current=a.initial*e,ce(a.current,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,displayUnit:_e(e.valueUnit),axis:e.axis}}function ce(e,t){switch(t){case"small-integer":case"integer":case"long":return Math.round(e);case"double":case"single":return e;default:return 0}}function ue(e){if(!P(e))return!1;switch(e?.type){case"class-breaks":case"simple":case"unique-value":case"dot-density":case"dictionary":case"pie-chart":return!0;default:return!1}}async function pe(e,t,r){const n=await B(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=I(e.symbol,n)&&(e.symbol=n)}function de(e,t){if(!e||!t)throw new Error("no geometry type");if("multipatch"===e)return{tool:"mesh",createOptions:{mode:"hybrid"}};const r=new Map;r.set("circle",{mode:"freehand"}),r.set("rectangle",{mode:"freehand"});const n={mode:W,optionsPerTool:r};if(T(t)){const a=t.defaultTool,o=S(t)?t.definition?.inputGeometryType??e:e;switch(a){case"freehand":case"stream-line":return{tool:"polyline"===o?"freehandPolyline":"freehandPolygon",createOptions:n};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:n};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===o?"polygon":"polyline",createOptions:n};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:n};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:n};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:n};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:n};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:n};case"elevation-point-from-contour":case"elevation-point-from-dem":case"parcel-seed":case"point":case"point-and-rotation":case"point-at-end-of-line":return{tool:"point",createOptions:n}}}else{const a=t.drawingTool;if("circle"===a||"ellipse"===a)return r.get("circle").preserveAspectRatio="circle"===a,{tool:"circle",createOptions:n};if("rectangle"===a)return{tool:"rectangle",createOptions:n};if("freehand"===a)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:n}}return{tool:e,createOptions:n}}async function fe(e,t,r){const{creationInfo:n,fullTemplate:a}=t;if(!n)throw new i("featureworkflow","No creation info provided.");const o=n.layer,s=Me(a,n.attributeOverrides),{view:l}=e,c="2d"===l?.type;S(a)||F(a)||await Oe(e,o,s,r,c?l.scale:null);const{capabilities:u}=o;e.layer.elevationInfo=o.elevationInfo;const p=de(o.geometryType,a);e.defaultCreateOptions={graphicProperties:{attributes:s,sourceLayer:o},mode:p.createOptions.mode,optionsPerTool:p.createOptions.optionsPerTool,preserveAspectRatio:p.createOptions.preserveAspectRatio,hasZ:u.data.supportsZ,defaultZ:(c?u.editing.zDefault:null)??e.defaultCreateOptions.defaultZ},null==n.geometryToPlace?await e.create(p.tool):await e.place(n.geometryToPlace,{graphicProperties:{attributes:s,sourceLayer:o}})}async function ye(e){return s([await me(e),await he(e)])}async function me({creationAttributes:e,data:t,sketchViewModel:r,view:n,webStyleCache:a}){const{creationInfo:o}=t,{fullTemplate:i}=t;if(!o||"2d"!==n?.type||S(i)||F(i))return null;const s=f(t=>Oe(r,o.layer,e,a,t));return g(()=>n.scale,e=>s(e))}async function he({data:t,sketchViewModel:r,view:n}){const{templateExecutorInfo:a}=t;if(!a)return null;const o=r.activeComponent;if(!n||!K(o))return X().error(new i("featureworkflow","Failed to set up template feedback.")),null;const c=new V({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});n.map?.add(c);const{executor:u,serviceLayersById:p}=a,d=n.theme?.accentColor??new e([255,165,0,1]);return s([b(()=>o,["cursor-update","vertex-add"],()=>{c.removeAll();const e=o.graphic?.geometry;if(!e||!ge(e))return;const t=u(e,"digitizing");if(!y(t))for(const r of t.edits){const e=p.get(r.id);if(e&&r.addFeatures&&0!==r.addFeatures.length)for(const t of e)if(!t.isTable)for(const e of r.addFeatures){const t=be(e,d);t&&c.add(t)}}}),l(()=>{n.map.remove(c),c.destroy()})])}function ge(e){switch(e.type){case"point":case"multipoint":return!0;case"polyline":return e.paths[0].length>1;case"polygon":{const t=e.rings[0];return n(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function be(e,r){let n=null;switch(e.geometry?.type){case"point":case"multipoint":n=new D({angle:0,color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:1}),path:"undefined",size:8,style:"circle",xoffset:0,yoffset:0});break;case"polygon":n=new C({color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":n=new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:n,attributes:{...e.attributes}})}async function we(e,t){const r=await N(t).load(),n=x(e)?e.parent:e;return r.tablesAndLayersLookup.get(n)}async function ve(e,t){const r=await we(e,t);if(!r)return new Map;const n=new Map;for(const a of r.layersAndTables)d(n,a.layerId,()=>[]).push(a);return n}function Ie(e){const t=e.objectIdField,r=e.globalIdField??"";return{id:e.layerId,identifierFields:{objectIdField:t,globalIdField:r},addFeatures:[],deleteAttachments:[],addAttachments:[],deleteFeatures:[],updateFeatures:[]}}function Te(e){const{edits:t,serviceInfo:n,view:a,findOriginalFeature:o}=e,i=Se(n.layersAndTables),s=n.layersAndTables.toArray(),{allEditData:l,editDataByLayerIdMap:c,editDataByIdMap:u}=Fe(t,i,o),p=ke(l,je(s,c),c);if(a&&Ve(l,p,a),0===p.length)return t;const d=H(p,{continueOnCircularDependency:!0}).map(e=>u.get(e)).filter(r),f=new Map;for(const r of d)f.set(r.uniqueId,r);const y=[];for(const r of l)f.has(r.uniqueId)||y.push(r);const m=[];let h=null;for(const r of d){const{layer:e}=r;switch(null==h?h=Ie(e):h.id!==e.layerId&&(m.push(h),h=Ie(e)),r.operationType){case"add":case"modify":h.addFeatures.push(r.after);break;case"delete":h.deleteFeatures.push(r.before)}}null!==h&&m.push(h);for(const r of y){const e=r.layer.layerId,t=m.find(t=>t.id===e)??Ie(r.layer);switch(m.includes(t)||m.push(t),r.operationType){case"add":t.addFeatures.push(r.after);break;case"modify":t.updateFeatures.push(r.after);break;case"delete":t.deleteFeatures.push(r.before);break;case"deleteAttachment":t.deleteAttachments.push(r.attachmentId);break;case"addAttachment":t.addAttachments.push(r.attachment)}}for(const r of m)void 0!==r.deleteAttachments&&0===r.deleteAttachments.length&&delete r.deleteAttachments,void 0!==r.addAttachments&&0===r.addAttachments.length&&delete r.addAttachments;return m}function Se(e){const t=new Map;for(const r of e)t.set(r.layerId,r);return t}function je(e,t){const r=new Map;for(const n of e)for(const e of n.relationships??[])if(r.set(Ae(n,e),""),t.has(e.relatedTableId)){const a=t.get(e.relatedTableId);if(a.length>0)for(const t of a[0].layer.relationships??[])if(t.id===e.id){r.set(Ae(n,e),t.keyField);break}}return r}function Fe(e,t,r){const n=new Map,a=[],o=new Map;let s=1;for(const l of e){const e=[],c=t.get(l.id);if(!c)throw new i("featureworkflow",`Failed to prepare applyEdits payload. Layer with id ${l.id} not found.`);for(const t of l.addFeatures??[])e.push({uniqueId:"T"+s++,operationType:"add",layer:c,after:t});for(const t of l.deleteFeatures??[])e.push({uniqueId:"T"+s++,operationType:"delete",before:t,layer:c});for(const t of l.deleteAttachments??[])e.push({uniqueId:"T"+s++,operationType:"deleteAttachment",attachmentId:t,layer:c});for(const t of l.addAttachments??[])e.push({uniqueId:"T"+s++,operationType:"addAttachment",attachment:t,layer:c});for(const t of l.updateFeatures??[])e.push({uniqueId:"T"+s++,operationType:"modify",before:r(t),after:t,layer:c});n.set(c.layerId,e);for(const t of e)a.push(t),o.set(t.uniqueId,t)}return{allEditData:a,editDataByIdMap:o,editDataByLayerIdMap:n}}function ke(e,t,r){const n=[];for(const a of e){const e=a.layer.relationships??[],{uniqueId:o}=a;for(const i of e){const e=i.keyField;if("origin"===i.role){const s=r.get(i.relatedTableId);if(!s||0===s.length)continue;const l=Ae(a.layer,i),c=t.get(l);if(void 0===c||""===c)continue;switch(a.operationType){case"add":for(const t of s)t!==a&&("add"!==t.operationType&&"modify"!==t.operationType||t.after.attributes[c]===a.after.attributes[e]&&n.push([o,t.uniqueId]));break;case"modify":if(a.before.attributes[e]!==a.after.attributes[e])for(const t of s){const r=t.uniqueId;t!==a&&("delete"===t.operationType?t.before.attributes[c]===a.before.attributes[e]?n.push([r,o]):t.before.attributes[c]===a.after.attributes[e]&&n.push([o,r]):"add"===t.operationType?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):t.after.attributes[c]===a.before.attributes[e]&&n.push([r,o]):"modify"===t.operationType&&(t.before.attributes[c]!==t.after.attributes[c]?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):n.push([r,o]):n.push([o,r])))}break;case"delete":for(const t of s)t!==a&&("delete"!==t.operationType&&"modify"!==t.operationType||t.before.attributes[c]===a.before.attributes[e]&&n.push([t.uniqueId,o]))}}}}return n}function Ae(e,t){return`${e.layerId}:${t.id}`}function Ue(e,t){return!!(t?.map&&"utilityNetworks"in t.map&&t.map.utilityNetworks?.length&&t.map.utilityNetworks.some(t=>!(!t.loaded||!e.url?.startsWith(t.featureServiceUrl)||e.layerId!==t.networkSystemLayers.associationsTableId)))}function Ve(e,t,r){const n=[];for(const o of e)Ue(o.layer,r)&&n.push(o);if(0===n.length)return;let a=[];for(const o of n){const r=o.layer;switch(o.operationType){case"delete":a=[...Le(o.before.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.before.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([o.uniqueId,e.uniqueId]);break;case"add":a=[...Le(o.after.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.after.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([e.uniqueId,o.uniqueId])}}}function Le(e,t){const r=[],n=t.filter(({layer:e})=>""!==e.globalIdField&&null!=e.globalIdField);for(const a of n){const t=a.layer.globalIdField;("before"in a&&a.before?.attributes[t]===e||"after"in a&&a.after?.attributes[t]===e)&&r.push(a)}return r}function Me(e,t={}){return S(e)||F(e)?{}:k(e)?{...e.prototype.attributes,...t}:A(e)?{...e.definition?.defaultValues,...t}:{...t}}async function Oe(e,r,n,a,o){const i=new t({sourceLayer:r,attributes:n}),{rotation:s,size:l}=ae(i);let c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o}),u=!1;for(const t of[l,s]){if(null==t)continue;null==n[t.field]&&(n[t.field]=await t.getDefaultValue(c,e.view),u=!0)}switch(u&&(c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o})),c?.type){case"simple-fill":case"polygon-3d":e.polygonSymbol=c;break;case"simple-line":case"line-3d":e.polylineSymbol=c;break;case"simple-marker":case"picture-marker":case"point-3d":case"cim":e.pointSymbol=c;break;case"mesh-3d":e.meshSymbol=c}xe(e.tooltipOptions,l,s)}function xe(e,t,r){e.visualVariables=null!=t||null!=r?{size:null!=t?{unit:t.displayUnit,axis:t.axis,valueType:t.fieldType}:null,rotation:null!=r?{valueType:r.fieldType,rotationType:r.rotationType??"geographic"}:null}:null}function ze(e,t){return e?.find(e=>e.layer===t)}async function qe(e,t,r,n){switch(t.type){case"3d":return Pe(e,t,r,n);case"2d":return Ee(e,t,r,n)}}async function Pe(e,t,r,n){if(0===e.length)return[];const{updatable:o,graphicsByLayer:i}=await r.defer(async()=>{const{results:a}=await h(J(t,r),n),o=new Map,i=e=>{const t=e.layer,r=o.get(t);if(!r){const e=new Array;return o.set(t,e),e}return r};$(a).forEach(({graphic:e})=>i(e).push(e));const s=e.filter(({capabilities:e,layer:t})=>e.update.enabled&&o.has(t));return 0!==s.length&&r.stopPropagation(),{updatable:s,graphicsByLayer:o}});return h(Promise.allSettled(o.map(async({layer:e})=>{const t=i.get(e),r=Ce(e);if(t.every(e=>L(e,r)))return t;const o=[];for(const n of t){o.push(n.getObjectId());const e=Object.keys(n.attributes);a(r,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=o,s.outFields=M(e.fieldsIndex,r),e.queryFeatures(s,{signal:n}).then(({features:e})=>e)})),n)}async function Ee(e,t,r,n){if(0===e.length)return[];const{mapPoint:a}=r;if(null==a)return[];let o=null;const i=await r.defer(async()=>{const{results:a}=await h(t.hitTest(r),n);if(0===a.length)return[];const i=new Set;o=$(a),o.forEach(({graphic:e})=>e&&i.add(e.layer));const s=e.filter(e=>i.has(e.layer)&&e.supportsUpdateWorkflow);return s.length>0&&r.stopPropagation(),s});return h(Promise.allSettled(i.map(async({layer:e})=>{const i=e.createQuery();i.returnGeometry=!0,i.outFields=Ce(e);const s="renderer"in e?z({renderer:e.renderer,pointerType:r.pointerType}):0;i.geometry=Q(a,s,t),i.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(i,{signal:n});return o?.forEach(({graphic:t})=>{t.layer!==e||l.some(e=>e.getObjectId()===t.getObjectId())||l.push(t)}),l})),n)}function Ce(e){return M(e.fieldsIndex,[e.objectIdField,O({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Re(e,t,n,a){const o=t.createQuery();o.objectIds=e.map(e=>e.getObjectId()).filter(r),o.outFields=["*"],o.returnM=t.capabilities.data.supportsM,o.returnZ=t.capabilities.data.supportsZ,"scene"===t.type&&null!=t.infoFor3D||(o.outSpatialReference=n);const i=await t.queryFeatures(o,{signal:a});return m(a),i.features}function De(e){const t=new Map;for(const r of e){const e=r.sourceLayer,n=x(e)?e.parent:e;d(t,n,()=>[]).push(r)}return t}async function Ge(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a}=e;await Be(e);const o={multipleSelectionEnabled:!1};return"point"===n.geometryType&&(o.enableRotation=null!=a.rotation,o.enableScaling=null!=a.size),r.update(t,o)}async function Be(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a,webStyleCache:o}=e;let i=!1;const{rotation:s,size:l}=a;for(const c of[s,l]){if(null==c)continue;const e=t.getAttribute(c.field);if(null!=e)c.setInitialValue(e);else{const e=await c.getDefaultValue(t.symbol,r.view);c.setInitialValue(e),t.setAttribute(c.field,e),i=!0}}if(i){const e="2d"===r.view?.type?r.view.scale:null;await pe(t,o,e)}xe(r.tooltipOptions,l,s),r.layer.elevationInfo=n.elevationInfo}function Ne(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function Ze(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}function We(e,t,r,n){if(null==t.geometry||"point"!==t.geometry?.type)return!1;const a=t.attributes;let o=!1;const i=n.rotation,s=Ne(r.toolEventInfo);if(null!=i&&null!=s){const{field:r,getValue:n}=i;if("rotate-stop"===s.type)i.isUpdatingInteractively=!1,i.setInitialValue(t.getAttribute(r));else{i.isUpdatingInteractively=!0;const l=n(s.angle,e);l!==a[r]&&t.setAttribute(r,l),o=!0}}const l=n.size,c=Ze(r.toolEventInfo);if(null!=l&&null!=c){const{field:r,getValue:n}=l;if("scale-stop"===c.type)l.isUpdatingInteractively=!1,l.setInitialValue(t.getAttribute(r));else{l.isUpdatingInteractively=!0;const i=n(c.xScale,e);i!==a[r]&&t.setAttribute(r,i),o=!0}}return o}async function Qe({feature:e,featureClone:t,visualVariableAttributes:r,sketchViewModel:n,view:a,onUpdate:o,webStyleCache:i,addUpdatingPromise:u,addHandle:p}){await pe(t,i,"2d"===a.type?a.scale:null);let d=null;if("2d"===n?.view?.type){const e=f(e=>pe(t,i,e));d=g(()=>n?.view?.scale,t=>e(t))}const y=t.sourceLayer,m=rt(a,y);await Ge({graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i});let h=null;m.then(e=>h=e).catch(()=>{});const b=r.size,v=r.rotation,I=g(()=>e.attributes,async e=>{let r=!1;for(const n in e){const a=e[n];a!==t.getAttribute(n)&&(t.setAttribute(n,a),null==b||b.isUpdatingInteractively||b.field!==n||b.setInitialValue(a),null==v||v.isUpdatingInteractively||v.field!==n||v.setInitialValue(a),(null==h||h.requiredFields.includes(n))&&(r=!0))}r&&await pe(t,i,"2d"===a.type?a.scale:null)}),T=n.on("update",async e=>{const t=e.graphics[0],s={graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i};if("complete"===e.state){if(null===a.activeTool)return Ge(s);const e=new AbortController,t=c(e);return p(t),u(w(()=>null===a.activeTool,e.signal).then(async()=>{if(!e.signal.aborted)return e.abort(),Ge(s)}))}We(a,t,e,r)&&await pe(t,i,"2d"===a.type?a.scale:null),o(at(t),e)}),S=n.on(["undo","redo"],async e=>{o(at(e.graphics[0]),e)});return s([S,T,l(()=>n.cancel()),I,d])}async function $e(e,t,r){const n=e.view;e.layer.add(r);const a=t.sourceLayer,i=t.layer,c=t.getAttribute(i.objectIdField);let u=null;function p(e){u?.abort(),u=o(async t=>{const r=await rt(n,a);m(t),r.setVisibility?.(c,e)})}return await He(n,r),p(!1),s([Je(n,r,e=>p(!e)),l(async()=>{p(!0);try{if(!n.destroyed){const e=await rt(n,a).catch(()=>{});e&&!e.destroyed&&await w(()=>!e.updating)}}finally{e.layer.remove(r)}})])}function Je(e,t,r){if("3d"===e.type){const n=new Z({graphic:t});return s([e.trackGraphicState(n),g(()=>n.displaying,r)])}return g(()=>t.visible,r)}async function He(e,t){if("3d"===e.type){const r=new Z({graphic:t}),n=e.trackGraphicState(r);await w(()=>r.displaying||r.error),n.remove()}else await w(()=>t.visible)}const Ke={icon:v(24),text:v(12),line:v(1),viewScaleSizeFactor:100};function Xe(e,t,r){let n=!1;return e.filter(e=>!!n||(n=e===t,n)).map(e=>r[e]())}function Ye(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const n=r.layer,a=e.viewModel.getTemplatesForLayer(n);1===a.length&&"scene"!==n.type&&(r.template=a[0],t.shift())}return t}function _e(e){return"unknown"===e?null:e}function et(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const tt=e=>/-stop/.test(e)||/vertex-/.test(e),rt=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function nt(e){return"createInteractiveEditSession"in e}function at(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=u(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function ot(e){const t=e.cursor;return e.cursor="progress",l(()=>e.cursor=t)}async function it(e,t){const{template:r}=e;if(null==r)return null;if(j(r))return r.load();if(T(r)){const e=(await import("../../editing/sharedTemplates/SharedTemplate.js")).default,n=U(t,{makeSharedTemplateFromJSON:t=>e.fromJSON(t)}),a=await n.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===a.length)throw new i("editor:failed-to-load-template","Unable to load the provided template");return a[0].load()}return r}function st(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:n,sourceField:a}=t;e.setAttribute(r,n.getAttribute(a))}}function lt(e){const t=e.templateExecutorInfo?.completionResults;return t?.length?(t.forEach(e=>st(e.relationships)),t.flatMap(e=>e.edits)):null}function ct(e){if(null==e)return[];if(ee(e))return e.data.layers;const t=re(e)?e.activeWorkflow:e,r=t?.layer;return r?[r]:[]}function ut(){return new i("editing:multiple-layers-not-supported","UpdateFeaturesWorkflow does not support updating features from multiple layers.")}export{Ve as appendAllUtilityNetworkAssociationRelationships,Ye as avoidFeatureTemplateSelectionWithOnlyOneItem,nt as canCreateInteractiveEditSession,at as cloneGraphicExceptMesh,Se as createLayerIdMap,je as createRelationshipKeyMap,de as createToolFromGeometryType,Xe as createWorkflowSteps,qe as fetchCandidates,Re as fetchFullFeatures,ke as findAllDependencies,Le as findChangesByGlobalId,ze as findLayerInfo,Ae as generateHashForRelationship,Me as getCreationAttributes,it as getFullTemplateForCreationInfo,ct as getLayersFromWorkflow,oe as getRotationVariableAttribute,lt as getServiceEditsFromWorkflowData,we as getServiceInfoForLayer,ve as getServiceLayersById,le as getSizeVariableAttribute,ae as getVisualVariableAttributes,ne as getVisualVariablesForLayer,De as groupFeaturesByLayer,Y as isBatchAttributeFormViewModel,_ as isCreateFeaturesWorkflow,tt as isTerminalUpdateEventType,ee as isUpdateFeaturesWorkflow,te as isUpdateRecordWorkflow,re as isUpdateWorkflow,Ue as isUtilityNetworkAssociationsTable,ut as makeMultipleSourceLayersError,Te as orderEditsByRelationshipDependencies,et as prepareAttachmentsForCreateFeaturesWorkflow,st as setRelationshipFields,Qe as setUpGeometryUpdate,ye as setUpSketchCreateWatchers,Be as setVisualVariablesAndElevationInfoForUpdate,ot as showProgressCursor,Ke as sizeDefaults,_e as sizeVariableUnitToLengthUnit,fe as startCreatingNewFeature,Ge as startUpdatingFeatureGeometry,$e as swapForEditingSession,pe as updateGraphicSymbolWhenRequired,We as visualVariableInteractiveUpdate,rt as whenEditorLayerView,He as whenGraphicDisplayed};
5
+ import e from"../../Color.js";import t from"../../Graphic.js";import{isSome as r,equals as n,addMany as a}from"../../core/arrayUtils.js";import{createTask as o}from"../../core/asyncUtils.js";import"../../core/has.js";import i from"../../core/Error.js";import{handlesGroup as s,makeHandle as l,abortHandle as c}from"../../core/handleUtils.js";import{clone as u}from"../../core/lang.js";import p from"../../core/Logger.js";import{getOrCreateMapValue as d}from"../../core/MapUtils.js";import{debounce as f,isPromiseLike as y,throwIfAborted as m,whenOrAbort as h}from"../../core/promiseUtils.js";import{watch as g,on as b,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as v}from"../../core/screenUtils.js";import{diff as I}from"../../core/accessorSupport/diffUtils.js";import{isSharedTemplateOrMetadata as T,isSharedGroupTemplate as S,isSharedTemplate as j,isSharedPresetTemplate as F,isStandardFeatureTemplate as k,isSharedFeatureTemplate as A}from"../../editing/templateUtils.js";import{getSharedTemplateProvider as U}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import V from"../../layers/GraphicsLayer.js";import{featureHasFields as L,fixFields as M,getDisplayFieldName as O}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as x}from"../../layers/support/layerUtils.js";import{calculateTolerance as z}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as q}from"../../renderers/support/lengthUtils.js";import{isRenderer as P}from"../../renderers/support/typeUtils.js";import{getTransformationType as E}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import C from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import D from"../../symbols/SimpleMarkerSymbol.js";import{to3D as G}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as B}from"../../symbols/support/symbolUtils.js";import{getServices as N}from"../../undoredo/support/Services.js";import{GraphicState as Z}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as W}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as Q}from"../../views/support/drapedUtils.js";import{filterGraphicHits as $,hitTestSelectSimilarDistance as J}from"../../views/support/hitTestSelectUtils.js";import{dependencySort as H}from"./support/dependencySort.js";import{isDrawGraphicTool as K}from"../Sketch/support/sketchUtils.js";const X=()=>p.getLogger("esri.widgets.Editor.workflowUtils");function Y(e){return!!e&&"features"in e}function _(e){return null!=e&&"create-features"===e.type}function ee(e){return null!=e&&"update-features"===e.type}function te(e){return null!=e&&/update-/.test(e.type)&&"fullFeature"in e}function re(e){return null!=e&&"update"===e.type}function ne(e){const t=e&&"renderer"in e?e.renderer:null;if(!ue(t))return{rotation:null,size:null};const r=t.getVisualVariablesForType("rotation").filter(e=>(!e.axis||"heading"===e.axis)&&e.field&&!e.valueExpression),n=t.getVisualVariablesForType("size").filter(e=>e.field&&!e.useSymbolValue&&!e.valueExpression&&"real-world-size"===E(e));return{rotation:1===r.length?r[0]:null,size:1===n.length?n[0]:null}}function ae(e){const t=e.sourceLayer;if(!(t&&"renderer"in t&&ue(t.renderer)))return{rotation:null,size:null};const{rotation:r,size:n}=ne(t);let a=null,o=null;if(r){const e=t.fields?.filter(e=>e.name===r.field),n=1===e?.length?e[0]:null;a=oe(r,n)}if(n){const e=t.fields?.filter(e=>e.name===n.field),r=1===e?.length?e[0]:null;o=le(n,r)}return{rotation:a,size:o}}function oe(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,n=t?.type??"double",a={initial:0,current:0};return{field:e.field,fieldType:n,getDefaultValue:()=>Promise.resolve(0),getValue:e=>(a.current=a.initial-r*e,ce((a.current+360)%360,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,rotationType:e.rotationType??"geographic"}}function ie(e,t){switch(t){case"width":return e[0];case"depth":return e[1];case"height":return e[2];default:return e[2]||e[1]||e[0]}}async function se(e,t,r){if(null==t)return 0;const{symbol:n}=G(t);if(null==n||"web-style"===n.type||"cim"===n.type)return 0;const a=n.symbolLayers.at(0);if(!a)return 0;switch(a.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return Math.min(Ke.icon,(await e(a,Ke.icon))[0])||Ke.icon}case"text":return Ke.text;case"line":return Ke.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ie(await t(a,e.scale/Ke.viewScaleSizeFactor),r)}case"path":case"extrude":return e.scale/Ke.viewScaleSizeFactor;default:return 0}}function le(e,t){const r=e.axis,n=t?.type??"double",a={initial:0,current:0},o=q[e.valueUnit]??1;let i;return i="area"===e.valueRepresentation?e=>(e*o/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*o/2:e=>e*o,{field:e.field,fieldType:n,getDefaultValue:async(e,t)=>ce(i(await se(t,e,r)),n),getValue:(e,t)=>(a.initial||(a.initial=t.pixelSizeAt(t.center)),a.current=a.initial*e,ce(a.current,n)),setInitialValue:e=>{a.initial=e,a.current=0},isUpdatingInteractively:!1,displayUnit:_e(e.valueUnit),axis:e.axis}}function ce(e,t){switch(t){case"small-integer":case"integer":case"long":return Math.round(e);case"double":case"single":return e;default:return 0}}function ue(e){if(!P(e))return!1;switch(e?.type){case"class-breaks":case"simple":case"unique-value":case"dot-density":case"dictionary":case"pie-chart":return!0;default:return!1}}async function pe(e,t,r){const n=await B(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=I(e.symbol,n)&&(e.symbol=n)}function de(e,t){if(!e||!t)throw new Error("no geometry type");if("multipatch"===e)return{tool:"mesh",createOptions:{mode:"hybrid"}};const r=new Map;r.set("circle",{mode:"freehand"}),r.set("rectangle",{mode:"freehand"});const n={mode:W,optionsPerTool:r};if(T(t)){const a=t.defaultTool,o=S(t)?t.definition?.inputGeometryType??e:e;switch(a){case"freehand":case"stream-line":return{tool:"polyline"===o?"freehandPolyline":"freehandPolygon",createOptions:n};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:n};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===o?"polygon":"polyline",createOptions:n};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:n};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:n};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:n};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:n};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:n};case"elevation-point-from-contour":case"elevation-point-from-dem":case"parcel-seed":case"point":case"point-and-rotation":case"point-at-end-of-line":return{tool:"point",createOptions:n}}}else{const a=t.drawingTool;if("circle"===a||"ellipse"===a)return r.get("circle").preserveAspectRatio="circle"===a,{tool:"circle",createOptions:n};if("rectangle"===a)return{tool:"rectangle",createOptions:n};if("freehand"===a)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:n}}return{tool:e,createOptions:n}}async function fe(e,t,r){const{creationInfo:n,fullTemplate:a}=t;if(!n)throw new i("featureworkflow","No creation info provided.");const o=n.layer,s=Me(a,n.attributeOverrides),{view:l}=e,c="2d"===l?.type;S(a)||F(a)||await Oe(e,o,s,r,c?l.scale:null);const{capabilities:u}=o;e.layer.elevationInfo=o.elevationInfo;const p=de(o.geometryType,a);e.defaultCreateOptions={graphicProperties:{attributes:s,sourceLayer:o},mode:p.createOptions.mode,optionsPerTool:p.createOptions.optionsPerTool,preserveAspectRatio:p.createOptions.preserveAspectRatio,hasZ:u.data.supportsZ,defaultZ:(c?u.editing.zDefault:null)??e.defaultCreateOptions.defaultZ},null==n.geometryToPlace?await e.create(p.tool):await e.place(n.geometryToPlace,{graphicProperties:{attributes:s,sourceLayer:o}})}async function ye(e){return s([await me(e),await he(e)])}async function me({creationAttributes:e,data:t,sketchViewModel:r,view:n,webStyleCache:a}){const{creationInfo:o}=t,{fullTemplate:i}=t;if(!o||"2d"!==n?.type||S(i)||F(i))return null;const s=f(t=>Oe(r,o.layer,e,a,t));return g(()=>n.scale,e=>s(e))}async function he({data:t,sketchViewModel:r,view:n}){const{templateExecutorInfo:a}=t;if(!a)return null;const o=r.activeComponent;if(!n||!K(o))return X().error(new i("featureworkflow","Failed to set up template feedback.")),null;const c=new V({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});n.map?.add(c);const{executor:u,serviceLayersById:p}=a,d=n.theme?.accentColor??new e([255,165,0,1]);return s([b(()=>o,["cursor-update","vertex-add"],()=>{c.removeAll();const e=o.graphic?.geometry;if(!e||!ge(e))return;const t=u(e,"digitizing");if(!y(t))for(const r of t.edits){const e=p.get(r.id);if(e&&r.addFeatures&&0!==r.addFeatures.length)for(const t of e)if(!t.isTable)for(const e of r.addFeatures){const t=be(e,d);t&&c.add(t)}}}),l(()=>{n.map.remove(c),c.destroy()})])}function ge(e){switch(e.type){case"point":case"multipoint":return!0;case"polyline":return e.paths[0].length>1;case"polygon":{const t=e.rings[0];return n(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function be(e,r){let n=null;switch(e.geometry?.type){case"point":case"multipoint":n=new D({angle:0,color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:1}),path:"undefined",size:8,style:"circle",xoffset:0,yoffset:0});break;case"polygon":n=new C({color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":n=new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:n,attributes:{...e.attributes}})}async function we(e,t){const r=await N(t).load(),n=x(e)?e.parent:e;return r.tablesAndLayersLookup.get(n)}async function ve(e,t){const r=await we(e,t);if(!r)return new Map;const n=new Map;for(const a of r.layersAndTables)d(n,a.layerId,()=>[]).push(a);return n}function Ie(e){const t=e.objectIdField,r=e.globalIdField??"";return{id:e.layerId,identifierFields:{objectIdField:t,globalIdField:r},addFeatures:[],deleteAttachments:[],addAttachments:[],deleteFeatures:[],updateFeatures:[]}}function Te(e){const{edits:t,serviceInfo:n,view:a,findOriginalFeature:o}=e,i=Se(n.layersAndTables),s=n.layersAndTables.toArray(),{allEditData:l,editDataByLayerIdMap:c,editDataByIdMap:u}=Fe(t,i,o),p=ke(l,je(s,c),c);if(a&&Ve(l,p,a),0===p.length)return t;const d=H(p,{continueOnCircularDependency:!0}).map(e=>u.get(e)).filter(r),f=new Map;for(const r of d)f.set(r.uniqueId,r);const y=[];for(const r of l)f.has(r.uniqueId)||y.push(r);const m=[];let h=null;for(const r of d){const{layer:e}=r;switch(null==h?h=Ie(e):h.id!==e.layerId&&(m.push(h),h=Ie(e)),r.operationType){case"add":case"modify":h.addFeatures.push(r.after);break;case"delete":h.deleteFeatures.push(r.before)}}null!==h&&m.push(h);for(const r of y){const e=r.layer.layerId,t=m.find(t=>t.id===e)??Ie(r.layer);switch(m.includes(t)||m.push(t),r.operationType){case"add":t.addFeatures.push(r.after);break;case"modify":t.updateFeatures.push(r.after);break;case"delete":t.deleteFeatures.push(r.before);break;case"deleteAttachment":t.deleteAttachments.push(r.attachmentId);break;case"addAttachment":t.addAttachments.push(r.attachment)}}for(const r of m)void 0!==r.deleteAttachments&&0===r.deleteAttachments.length&&delete r.deleteAttachments,void 0!==r.addAttachments&&0===r.addAttachments.length&&delete r.addAttachments;return m}function Se(e){const t=new Map;for(const r of e)t.set(r.layerId,r);return t}function je(e,t){const r=new Map;for(const n of e)for(const e of n.relationships??[])if(r.set(Ae(n,e),""),t.has(e.relatedTableId)){const a=t.get(e.relatedTableId);if(a.length>0)for(const t of a[0].layer.relationships??[])if(t.id===e.id){r.set(Ae(n,e),t.keyField);break}}return r}function Fe(e,t,r){const n=new Map,a=[],o=new Map;let s=1;for(const l of e){const e=[],c=t.get(l.id);if(!c)throw new i("featureworkflow",`Failed to prepare applyEdits payload. Layer with id ${l.id} not found.`);for(const t of l.addFeatures??[])e.push({uniqueId:"T"+s++,operationType:"add",layer:c,after:t});for(const t of l.deleteFeatures??[])e.push({uniqueId:"T"+s++,operationType:"delete",before:t,layer:c});for(const t of l.deleteAttachments??[])e.push({uniqueId:"T"+s++,operationType:"deleteAttachment",attachmentId:t,layer:c});for(const t of l.addAttachments??[])e.push({uniqueId:"T"+s++,operationType:"addAttachment",attachment:t,layer:c});for(const t of l.updateFeatures??[])e.push({uniqueId:"T"+s++,operationType:"modify",before:r(t),after:t,layer:c});n.set(c.layerId,e);for(const t of e)a.push(t),o.set(t.uniqueId,t)}return{allEditData:a,editDataByIdMap:o,editDataByLayerIdMap:n}}function ke(e,t,r){const n=[];for(const a of e){const e=a.layer.relationships??[],{uniqueId:o}=a;for(const i of e){const e=i.keyField;if("origin"===i.role){const s=r.get(i.relatedTableId);if(!s||0===s.length)continue;const l=Ae(a.layer,i),c=t.get(l);if(void 0===c||""===c)continue;switch(a.operationType){case"add":for(const t of s)t!==a&&("add"!==t.operationType&&"modify"!==t.operationType||t.after.attributes[c]===a.after.attributes[e]&&n.push([o,t.uniqueId]));break;case"modify":if(a.before.attributes[e]!==a.after.attributes[e])for(const t of s){const r=t.uniqueId;t!==a&&("delete"===t.operationType?t.before.attributes[c]===a.before.attributes[e]?n.push([r,o]):t.before.attributes[c]===a.after.attributes[e]&&n.push([o,r]):"add"===t.operationType?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):t.after.attributes[c]===a.before.attributes[e]&&n.push([r,o]):"modify"===t.operationType&&(t.before.attributes[c]!==t.after.attributes[c]?t.after.attributes[c]===a.after.attributes[e]?n.push([o,r]):n.push([r,o]):n.push([o,r])))}break;case"delete":for(const t of s)t!==a&&("delete"!==t.operationType&&"modify"!==t.operationType||t.before.attributes[c]===a.before.attributes[e]&&n.push([t.uniqueId,o]))}}}}return n}function Ae(e,t){return`${e.layerId}:${t.id}`}function Ue(e,t){return!!(t?.map&&"utilityNetworks"in t.map&&t.map.utilityNetworks?.length&&t.map.utilityNetworks.some(t=>!(!t.loaded||!e.url?.startsWith(t.featureServiceUrl)||e.layerId!==t.networkSystemLayers.associationsTableId)))}function Ve(e,t,r){const n=[];for(const o of e)Ue(o.layer,r)&&n.push(o);if(0===n.length)return;let a=[];for(const o of n){const r=o.layer;switch(o.operationType){case"delete":a=[...Le(o.before.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.before.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([o.uniqueId,e.uniqueId]);break;case"add":a=[...Le(o.after.attributes[r.fieldsIndex.get("fromglobalid").name],e),...Le(o.after.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of a)t.push([e.uniqueId,o.uniqueId])}}}function Le(e,t){const r=[],n=t.filter(({layer:e})=>""!==e.globalIdField&&null!=e.globalIdField);for(const a of n){const t=a.layer.globalIdField;("before"in a&&a.before?.attributes[t]===e||"after"in a&&a.after?.attributes[t]===e)&&r.push(a)}return r}function Me(e,t={}){return S(e)||F(e)?{}:k(e)?{...e.prototype.attributes,...t}:A(e)?{...e.definition?.defaultValues,...t}:{...t}}async function Oe(e,r,n,a,o){const i=new t({sourceLayer:r,attributes:n}),{rotation:s,size:l}=ae(i);let c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o}),u=!1;for(const t of[l,s]){if(null==t)continue;null==n[t.field]&&(n[t.field]=await t.getDefaultValue(c,e.view),u=!0)}switch(u&&(c=await B(i,{useSourceLayer:!0,webStyleCache:a,scale:o})),c?.type){case"simple-fill":case"polygon-3d":e.polygonSymbol=c;break;case"simple-line":case"line-3d":e.polylineSymbol=c;break;case"simple-marker":case"picture-marker":case"point-3d":case"cim":e.pointSymbol=c;break;case"mesh-3d":e.meshSymbol=c}xe(e.tooltipOptions,l,s)}function xe(e,t,r){e.visualVariables=null!=t||null!=r?{size:null!=t?{unit:t.displayUnit,axis:t.axis,valueType:t.fieldType}:null,rotation:null!=r?{valueType:r.fieldType,rotationType:r.rotationType??"geographic"}:null}:null}function ze(e,t){return e?.find(e=>e.layer===t)}async function qe(e,t,r,n){switch(t.type){case"3d":return Pe(e,t,r,n);case"2d":return Ee(e,t,r,n)}}async function Pe(e,t,r,n){if(0===e.length)return[];const{updatable:o,graphicsByLayer:i}=await r.defer(async()=>{const{results:a}=await h(J(t,r),n),o=new Map,i=e=>{const t=e.layer,r=o.get(t);if(!r){const e=new Array;return o.set(t,e),e}return r};$(a).forEach(({graphic:e})=>i(e).push(e));const s=e.filter(({capabilities:e,layer:t})=>e.update.enabled&&o.has(t));return 0!==s.length&&r.stopPropagation(),{updatable:s,graphicsByLayer:o}});return h(Promise.allSettled(o.map(async({layer:e})=>{const t=i.get(e),r=Ce(e);if(t.every(e=>L(e,r)))return t;const o=[];for(const n of t){o.push(n.getObjectId());const e=Object.keys(n.attributes);a(r,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=o,s.outFields=M(e.fieldsIndex,r),e.queryFeatures(s,{signal:n}).then(({features:e})=>e)})),n)}async function Ee(e,t,r,n){if(0===e.length)return[];const{mapPoint:a}=r;if(null==a)return[];let o=null;const i=await r.defer(async()=>{const{results:a}=await h(t.hitTest(r),n);if(0===a.length)return[];const i=new Set;o=$(a),o.forEach(({graphic:e})=>e&&i.add(e.layer));const s=e.filter(e=>i.has(e.layer)&&e.supportsUpdateWorkflow);return s.length>0&&r.stopPropagation(),s});return h(Promise.allSettled(i.map(async({layer:e})=>{const i=e.createQuery();i.returnGeometry=!0,i.outFields=Ce(e);const s="renderer"in e?z({renderer:e.renderer,pointerType:r.pointerType}):0;i.geometry=Q(a,s,t),i.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(i,{signal:n});return o?.forEach(({graphic:t})=>{t.layer!==e||l.some(e=>e.getObjectId()===t.getObjectId())||l.push(t)}),l})),n)}function Ce(e){return M(e.fieldsIndex,[e.objectIdField,O({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Re(e,t,n,a){const o=t.createQuery();o.objectIds=e.map(e=>e.getObjectId()).filter(r),o.outFields=["*"],o.returnM=t.capabilities.data.supportsM,o.returnZ=t.capabilities.data.supportsZ,"scene"===t.type&&null!=t.infoFor3D||(o.outSpatialReference=n);const i=await t.queryFeatures(o,{signal:a});return m(a),i.features}function De(e){const t=new Map;for(const r of e){const e=r.sourceLayer,n=x(e)?e.parent:e;d(t,n,()=>[]).push(r)}return t}async function Ge(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a}=e;await Be(e);const o={multipleSelectionEnabled:!1};return"point"===n.geometryType&&(o.enableRotation=null!=a.rotation,o.enableScaling=null!=a.size),r.update(t,o)}async function Be(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:a,webStyleCache:o}=e;let i=!1;const{rotation:s,size:l}=a;for(const c of[s,l]){if(null==c)continue;const e=t.getAttribute(c.field);if(null!=e)c.setInitialValue(e);else{const e=await c.getDefaultValue(t.symbol,r.view);c.setInitialValue(e),t.setAttribute(c.field,e),i=!0}}if(i){const e="2d"===r.view?.type?r.view.scale:null;await pe(t,o,e)}xe(r.tooltipOptions,l,s),r.layer.elevationInfo=n.elevationInfo}function Ne(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function Ze(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}function We(e,t,r,n){if(null==t.geometry||"point"!==t.geometry?.type)return!1;const a=t.attributes;let o=!1;const i=n.rotation,s=Ne(r.toolEventInfo);if(null!=i&&null!=s){const{field:r,getValue:n}=i;if("rotate-stop"===s.type)i.isUpdatingInteractively=!1,i.setInitialValue(t.getAttribute(r));else{i.isUpdatingInteractively=!0;const l=n(s.angle,e);l!==a[r]&&t.setAttribute(r,l),o=!0}}const l=n.size,c=Ze(r.toolEventInfo);if(null!=l&&null!=c){const{field:r,getValue:n}=l;if("scale-stop"===c.type)l.isUpdatingInteractively=!1,l.setInitialValue(t.getAttribute(r));else{l.isUpdatingInteractively=!0;const i=n(c.xScale,e);i!==a[r]&&t.setAttribute(r,i),o=!0}}return o}async function Qe({feature:e,featureClone:t,visualVariableAttributes:r,sketchViewModel:n,view:a,onUpdate:o,webStyleCache:i,addUpdatingPromise:u,addHandle:p}){await pe(t,i,"2d"===a.type?a.scale:null);let d=null;if("2d"===n?.view?.type){const e=f(e=>pe(t,i,e));d=g(()=>n?.view?.scale,t=>e(t))}const y=t.sourceLayer,m=rt(a,y);await Ge({graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i});let h=null;m.then(e=>h=e).catch(()=>{});const b=r.size,v=r.rotation,I=g(()=>e.attributes,async e=>{let r=!1;for(const n in e){const a=e[n];a!==t.getAttribute(n)&&(t.setAttribute(n,a),null==b||b.isUpdatingInteractively||b.field!==n||b.setInitialValue(a),null==v||v.isUpdatingInteractively||v.field!==n||v.setInitialValue(a),(null==h||h.requiredFields.includes(n))&&(r=!0))}r&&await pe(t,i,"2d"===a.type?a.scale:null)}),T=n.on("update",async e=>{const t=e.graphics[0],s={graphic:t,sketchViewModel:n,sourceLayer:y,visualVariables:r,webStyleCache:i};if("complete"===e.state){if(null===a.activeTool)return Ge(s);const e=new AbortController,t=c(e);return p(t),u(w(()=>null===a.activeTool,e.signal).then(async()=>{if(!e.signal.aborted)return e.abort(),Ge(s)}))}We(a,t,e,r)&&await pe(t,i,"2d"===a.type?a.scale:null),o(at(t),e)}),S=n.on(["undo","redo"],async e=>{o(at(e.graphics[0]),e)});return s([S,T,l(()=>n.cancel()),I,d])}async function $e(e,t,r){const n=e.view;e.layer.add(r);const a=t.sourceLayer,i=t.layer,c=t.getAttribute(i.objectIdField);let u=null;function p(e){u?.abort(),u=o(async t=>{const r=await rt(n,a);m(t),r.setVisibility?.(c,e)})}return await He(n,r),p(!1),s([Je(n,r,e=>p(!e)),l(async()=>{p(!0);try{if(!n.destroyed){const e=await rt(n,a).catch(()=>{});e&&!e.destroyed&&await w(()=>!e.updating)}}finally{e.layer.remove(r)}})])}function Je(e,t,r){if("3d"===e.type){const n=new Z({graphic:t});return s([e.trackGraphicState(n),g(()=>n.displaying,r)])}return g(()=>t.visible,r)}async function He(e,t){if("3d"===e.type){const r=new Z({graphic:t}),n=e.trackGraphicState(r);await w(()=>r.displaying||r.error),n.remove()}else await w(()=>t.visible)}const Ke={icon:v(24),text:v(12),line:v(1),viewScaleSizeFactor:100};function Xe(e,t,r){let n=!1;return e.filter(e=>!!n||(n=e===t,n)).map(e=>r[e]())}function Ye(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const n=r.layer,a=e.viewModel.getTemplatesForLayer(n);1===a.length&&"scene"!==n.type&&(r.template=a[0],t.shift())}return t}function _e(e){return"unknown"===e?null:e}function et(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const tt=e=>/-stop/.test(e)||/vertex-/.test(e),rt=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function nt(e){return"createInteractiveEditSession"in e}function at(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=u(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function ot(e){return e.acquireCursor("progress")}async function it(e,t){const{template:r}=e;if(null==r)return null;if(j(r))return r.load();if(T(r)){const e=(await import("../../editing/sharedTemplates/SharedTemplate.js")).default,n=U(t,{makeSharedTemplateFromJSON:t=>e.fromJSON(t)}),a=await n.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===a.length)throw new i("editor:failed-to-load-template","Unable to load the provided template");return a[0].load()}return r}function st(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:n,sourceField:a}=t;e.setAttribute(r,n.getAttribute(a))}}function lt(e){const t=e.templateExecutorInfo?.completionResults;return t?.length?(t.forEach(e=>st(e.relationships)),t.flatMap(e=>e.edits)):null}function ct(e){if(null==e)return[];if(ee(e))return e.data.layers;const t=re(e)?e.activeWorkflow:e,r=t?.layer;return r?[r]:[]}function ut(){return new i("editing:multiple-layers-not-supported","UpdateFeaturesWorkflow does not support updating features from multiple layers.")}export{Ve as appendAllUtilityNetworkAssociationRelationships,Ye as avoidFeatureTemplateSelectionWithOnlyOneItem,nt as canCreateInteractiveEditSession,at as cloneGraphicExceptMesh,Se as createLayerIdMap,je as createRelationshipKeyMap,de as createToolFromGeometryType,Xe as createWorkflowSteps,qe as fetchCandidates,Re as fetchFullFeatures,ke as findAllDependencies,Le as findChangesByGlobalId,ze as findLayerInfo,Ae as generateHashForRelationship,Me as getCreationAttributes,it as getFullTemplateForCreationInfo,ct as getLayersFromWorkflow,oe as getRotationVariableAttribute,lt as getServiceEditsFromWorkflowData,we as getServiceInfoForLayer,ve as getServiceLayersById,le as getSizeVariableAttribute,ae as getVisualVariableAttributes,ne as getVisualVariablesForLayer,De as groupFeaturesByLayer,Y as isBatchAttributeFormViewModel,_ as isCreateFeaturesWorkflow,tt as isTerminalUpdateEventType,ee as isUpdateFeaturesWorkflow,te as isUpdateRecordWorkflow,re as isUpdateWorkflow,Ue as isUtilityNetworkAssociationsTable,ut as makeMultipleSourceLayersError,Te as orderEditsByRelationshipDependencies,et as prepareAttachmentsForCreateFeaturesWorkflow,st as setRelationshipFields,Qe as setUpGeometryUpdate,ye as setUpSketchCreateWatchers,Be as setVisualVariablesAndElevationInfoForUpdate,ot as showProgressCursor,Ke as sizeDefaults,_e as sizeVariableUnitToLengthUnit,fe as startCreatingNewFeature,Ge as startUpdatingFeatureGeometry,$e as swapForEditingSession,pe as updateGraphicSymbolWhenRequired,We as visualVariableInteractiveUpdate,rt as whenEditorLayerView,He as whenGraphicDisplayed};