@arcgis/core 4.29.0-next.20231221 → 4.29.0-next.20231222

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 (79) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/01dbff2fdff9d5c95892.js +1 -0
  3. package/assets/esri/core/workers/chunks/046b3920f4aca1061d06.js +1 -0
  4. package/assets/esri/core/workers/chunks/15af5fd13722ef57c8f7.js +1 -0
  5. package/assets/esri/core/workers/chunks/3a4598c384c4c31ab35b.js +1 -0
  6. package/assets/esri/core/workers/chunks/5c269c59f61a185ed5c7.js +1 -0
  7. package/assets/esri/core/workers/chunks/7435463436cda9eb4246.js +1 -0
  8. package/assets/esri/core/workers/chunks/c1c4f3909b724c13033d.js +1 -0
  9. package/assets/esri/core/workers/chunks/ccfdd3d278756f01f630.js +1 -0
  10. package/assets/esri/core/workers/chunks/d4cf3af5f5c30925539c.js +1 -0
  11. package/assets/esri/core/workers/chunks/ee0b43679cc0cc531d7c.js +1 -0
  12. package/assets/esri/core/workers/chunks/f9f3d6b4347e63f440e0.js +1 -0
  13. package/assets/esri/core/workers/chunks/fbfdb4779198f4c35c65.js +1 -0
  14. package/assets/esri/core/workers/chunks/ffad926201d92c4d6b4e.js +1 -0
  15. package/chunks/HUDMaterial.glsl.js +1 -1
  16. package/core/MemCache.js +1 -1
  17. package/core/MemCachePool.js +1 -1
  18. package/core/deprecate.js +1 -1
  19. package/layers/mixins/operationalLayerModuleMap.js +1 -1
  20. package/layers/mixins/operationalLayers.js +1 -1
  21. package/layers/support/editableLayers.js +1 -1
  22. package/layers/support/layersCreator.js +1 -1
  23. package/package.json +1 -1
  24. package/support/revision.js +1 -1
  25. package/views/2d/layers/FeatureLayerView2D.js +1 -1
  26. package/views/2d/layers/StreamLayerView2D.js +1 -1
  27. package/views/2d/layers/features/FeaturePipelineWorker.js +1 -1
  28. package/views/2d/layers/features/FeatureSourceEventLog.js +5 -0
  29. package/views/2d/layers/features/PipelineConnectionHandlers.js +1 -1
  30. package/views/2d/layers/features/layerAdapters/FeatureLayerAdapter.js +1 -1
  31. package/views/2d/layers/features/layerAdapters/InMemoryLayerAdapter.js +1 -1
  32. package/views/2d/layers/features/layerAdapters/KnowledgeGraphSublayerAdapter.js +1 -1
  33. package/views/2d/layers/features/layerAdapters/OGCFeatureLayerAdapter.js +1 -1
  34. package/views/2d/layers/features/layerAdapters/OrientedImageryLayerAdapter.js +1 -1
  35. package/views/2d/layers/features/layerAdapters/StreamLayerAdapter.js +1 -1
  36. package/views/2d/layers/features/layerAdapters/SubtypeGroupLayerAdapter.js +1 -1
  37. package/views/2d/layers/features/layerAdapters/featureServiceUtils.js +5 -0
  38. package/views/2d/layers/features/layerAdapters/geometryUtils.js +5 -0
  39. package/views/2d/layers/features/sources/FeatureSource.js +1 -1
  40. package/views/2d/layers/features/sources/strategies/AFetchLoadStrategy.js +1 -1
  41. package/views/2d/layers/features/sources/strategies/ATileLoadStrategy.js +1 -1
  42. package/views/2d/layers/features/sources/strategies/DrillDownTileLoadStrategy.js +1 -1
  43. package/views/2d/layers/features/sources/strategies/PagedTileLoadStrategy.js +1 -1
  44. package/views/2d/layers/features/sources/strategies/SnapshotLoadStrategy.js +1 -1
  45. package/views/2d/layers/features/sources/strategies/StreamLoadStrategy.js +1 -1
  46. package/views/2d/layers/features/sources/strategies/chunks/DrillDownTileSourceChunk.js +1 -1
  47. package/views/2d/layers/features/sources/strategies/chunks/FeatureSnapshotSourceChunk.js +1 -1
  48. package/views/2d/layers/features/sources/strategies/chunks/PagedTileSourceChunk.js +1 -1
  49. package/views/2d/layers/features/sources/strategies/chunks/SourceChunkStore.js +1 -1
  50. package/views/2d/layers/features/support/FeatureSetReaderJSON.js +1 -1
  51. package/views/3d/effects/RenderNode.js +1 -1
  52. package/views/3d/layers/I3SMeshView3D.js +1 -1
  53. package/views/3d/layers/IntegratedMesh3DTilesLayerView3D.js +1 -1
  54. package/views/3d/state/ViewStateManager.js +1 -1
  55. package/views/3d/terrain/TerrainAttributesCache.js +1 -1
  56. package/views/3d/webgl-engine/effects/RenderNodes.js +5 -0
  57. package/views/3d/webgl-engine/lib/OffscreenRendering.js +1 -1
  58. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  59. package/views/layers/FeatureLayerView.js +1 -1
  60. package/views/webgl/RenderingContext.js +1 -1
  61. package/webdoc/support/webdocSaveUtils.js +1 -1
  62. package/widgets/BasemapLayerList.js +1 -1
  63. package/widgets/Editor/EditorViewModel.js +1 -1
  64. package/widgets/LayerList.js +1 -1
  65. package/widgets/TableList.js +1 -1
  66. package/assets/esri/core/workers/chunks/251ceefdea4b345698a4.js +0 -1
  67. package/assets/esri/core/workers/chunks/2e6f1c788813b4162adf.js +0 -1
  68. package/assets/esri/core/workers/chunks/49ca15b23dd363bc3546.js +0 -1
  69. package/assets/esri/core/workers/chunks/521a38edbeff0073bfdd.js +0 -1
  70. package/assets/esri/core/workers/chunks/573ad8aa1c2cfad61eb8.js +0 -1
  71. package/assets/esri/core/workers/chunks/831283ac6653d7af90b6.js +0 -1
  72. package/assets/esri/core/workers/chunks/90444e25dd487d0bc438.js +0 -1
  73. package/assets/esri/core/workers/chunks/90b34ce04d5a83ea4344.js +0 -1
  74. package/assets/esri/core/workers/chunks/9c80cfae983c8ccfe616.js +0 -1
  75. package/assets/esri/core/workers/chunks/a1cf80c67ee8dbe9c897.js +0 -1
  76. package/assets/esri/core/workers/chunks/c76094c26e80656a2f8d.js +0 -1
  77. package/assets/esri/core/workers/chunks/df394ec25adfc9798f74.js +0 -1
  78. package/assets/esri/core/workers/chunks/e4ab40d895fccc81fe44.js +0 -1
  79. package/views/3d/webgl-engine/effects/RenderNodeCollection.js +0 -5
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Camera.js";import i from"../../../Viewpoint.js";import r from"../../../core/Accessor.js";import a from"../../../core/Logger.js";import{destroyMaybe as s}from"../../../core/maybe.js";import{on as n,watch as o,sync as h,when as l}from"../../../core/reactiveUtils.js";import{addFrameTask as p}from"../../../core/scheduling.js";import{createScreenPoint as c}from"../../../core/screenUtils.js";import{property as m}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/RandomLCG.js";import{subclass as d}from"../../../core/accessorSupport/decorators/subclass.js";import{a as v}from"../../../chunks/vec32.js";import{fromArray as u}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as w}from"../../../chunks/vec42.js";import{create as g}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import _ from"../../../geometry/Extent.js";import y from"../../../geometry/Point.js";import{isLoadedOrLoadFor as C,requiresLoad as f}from"../../../geometry/projection.js";import{ViewingMode as x}from"../../ViewingMode.js";import{applyAll as R}from"../camera/constraintUtils.js";import{cameraOnContentAlongViewDirection as P,surfaceElevationBelowRenderLocation as S}from"../camera/intersectionUtils.js";import{ConstraintsManager as O}from"./ConstraintsManager.js";import{Frustum as T}from"./Frustum.js";import{GoToOperation as b}from"./GoToOperation.js";import{SurfaceCollisionCorrectionController as j}from"./controllers/SurfaceCollisionCorrectionController.js";import{internalToExternal as I,externalToInternal as M,toExtent as z,distanceToScale as E,scaleToZoom as A,fromExtentSync as H,OrientationMode as N,getObserverForPointAtDistanceSync as L,scaleToDistance as V,zoomToScale as B}from"../support/cameraUtils.js";import{PropertiesPool as D}from"../support/PropertiesPool.js";import{fromCamera as G,toCameraSync as F}from"../support/viewpointUtils.js";import{Camera as U,PaddingSide as k}from"../webgl-engine/lib/Camera.js";import{RenderFeature as q}from"../webgl-engine/lib/RenderFeature.js";import{RenderState as W}from"../../support/RenderState.js";import{ensureAttachmentMaxSize as J}from"../../webgl/FramebufferObject.js";let K=class extends r{constructor(e){super(e),this.ready=!1,this._windowDevicePixelRatio=1,this._devicePixelRatioOverride=null,this._idleTimeout=ae,this.test={viewStateManager:this,contentCameraResetState:new Map,setDevicePixelRatio:e=>this._devicePixelRatioOverride=e,renderState:null,get maximumPixelRatio(){return this.viewStateManager.view.qualitySettings.maximumPixelRatio},get updatingIgnoreRenderState(){return null!=this.renderState},get idleTimeoutEnabled(){return this.viewStateManager._idleTimeout>0},set idleTimeoutEnabled(e){this.viewStateManager._idleTimeout=e?ae:0}},this._propertiesPool=new D({frustum:T},this),this._cameraSetByUser=!1,this._gotoOperation=null,this._cameraChangeTime=0,this._tmpCanvasSize=new Q}initialize(){this._cameraChangeTime=performance.now(),this.addHandles([n((()=>this.view.state.events),"before-camera-change",(e=>e&&this._updateElevation(e))),o((()=>this.view.state?.camera),((e,t)=>this._cameraChangedHandler(e,t)),h)]),l((()=>this.view.state?.camera),(e=>this._updateElevation(e)),{once:!0,sync:!0}),this.addHandles([p({prepare:()=>this._prepareFrame()}),o((()=>this.view.state.cameraController),(()=>{this._cameraSetByUser=!0,this.removeHandles(ie)})),n((()=>this.view.state.events),"camera-projection-changed",(()=>this.notifyChange("scale")))])}destroy(){this.exit(),this._propertiesPool=s(this._propertiesPool)}get camera(){const e=this._get("camera");if(!this.ready)return e;const t=I(this.view,this.view.state.camera,$);return t&&e&&t.equals(e)?e:t.clone()}set camera(e){this._updatePropertyBeforeReady("camera",e)||(this.view.elevationProvider?.enableCache(!0),this.setStateCamera(M(this.view,e),{applyConstraints:!1})||a.getLogger(this).error("#camera=","Invalid camera",e),this.view.elevationProvider?.enableCache(!1))}get contentCamera(){const e=this._get("contentCamera");if(!this.ready)return e;const t=I(this.view,this.view.state.contentCamera,$);return t&&e&&t.equals(e)?e:t.clone()}set contentCamera(e){if(this._updatePropertyBeforeReady("contentCamera",e))return;const t=M(this.view,e);null!=t?(this._updateElevation(t),this.view.state.contentCamera=t):this.view.state.contentCamera=null}installContentCameraReset(e){if(this.removeHandles(re),this.test.contentCameraResetState.clear(),!this.view.state.fixedContentCamera)return!1;const t=this.zoom,i=this.view.state.camera.distance**2,r=u(this.view.state.camera.center),a=e.sticky?this.contentCamera.clone():null;return this.addHandles([o((()=>this.contentCamera),(()=>{e.sticky||(this.removeHandles(re),this.test.contentCameraResetState.clear())})),o((()=>this.zoom),(e=>{void 0!==e&&void 0!==t&&(this.test.contentCameraResetState.set("view.zoom",Math.abs(e-t)/2),Math.abs(e-t)>2?this.contentCamera=null:this.view.state.fixedContentCamera||(this.contentCamera=a))})),o((()=>this.view.state.camera),(e=>{const t=v(r,e.center);this.test.contentCameraResetState.set("camera.center",t/i),t>i?this.contentCamera=null:this.view.state.fixedContentCamera||(this.contentCamera=a)}))],re),!0}get center(){return this.ready?this.view.pointsOfInterest.centerOnContent.location:this._get("center")}set center(e){this._updatePropertyBeforeReady("center",e)||(e?this.isCompatible(e)?this.setStateCamera(this._centerToCamera(e),{applyConstraints:!0})?this.view.pointsOfInterest.centerOnContent.runTask():a.getLogger(this).error("#center=","Invalid center",e):a.getLogger(this).error("#center=","Center has an incompatible spatial reference (center: "+(e.spatialReference?e.spatialReference.wkid:"none")+", view: "+this.view.spatialReference?.wkid+")",e):a.getLogger(this).error("#center=","Center may not be null or undefined"))}get extent(){if(!this.ready)return this._get("extent");const e=this.view,t=z(e,e.state.camera,e.pointsOfInterest.centerOnContent.renderLocation);return null!=t?t:this._get("extent")}set extent(e){this._updatePropertyBeforeReady("extent",e)||(e?this.isCompatible(e)?this.setStateCamera(this._extentToCamera(e),{applyConstraints:!0})||a.getLogger(this).error("#extent=","Invalid extent",e):a.getLogger(this).error("#extent=","Extent has an incompatible spatial reference (extent: "+(e.spatialReference?e.spatialReference.wkid:"none")+", view: "+this.view.spatialReference?.wkid+")",e):a.getLogger(this).error("#extent=","Extent may not be null or undefined"))}get frustum(){const e=this._propertiesPool.get("frustum");return e.renderCoordsHelper=this.view.renderCoordsHelper,e.update(this.view.state.camera),e}get constraintsManager(){return this._constraintsManager}get _initialViewpoint(){const e=this.view.map;return e&&"initialViewProperties"in e?e.initialViewProperties?.viewpoint:void 0}get hasInitialView(){return!!this._initialViewpoint}get scale(){if(this.ready){const e=this.view.pointsOfInterest.centerOnContent;return E(this.view,e.distance,e.location.latitude)}return this._get("scale")}set scale(e){this._updatePropertyBeforeReady("scale",e)||this.setStateCamera(this._scaleToCamera(e),{applyConstraints:!0})||a.getLogger(this).error("#scale=","Invalid scale",e)}get padding(){if(!this.ready)return this._get("padding");const e=this.view.state.camera,t=e.padding,i=e.pixelRatio,r=this._get("padding"),a=Math.round(t[k.TOP]/i),s=Math.round(t[k.RIGHT]/i),n=Math.round(t[k.BOTTOM]/i),o=Math.round(t[k.LEFT]/i);return null!=r&&r.top===a&&r.right===s&&r.bottom===n&&r.left===o?r:{top:a,right:s,bottom:n,left:o}}set padding(e){this._updatePropertyBeforeReady("padding",e)||(this._paddingToArray(e,this.view.state.camera.pixelRatio,te),this.view.state.updateCamera((e=>e.padding=te)))}_paddingToArray(e,t,i){e?w(i,e.top||0,e.right||0,e.bottom||0,e.left||0):w(i,0,0,0,0);for(let r=0;r<4;r++)i[r]=Math.round(i[r]*t)}get screenCenter(){const e=this.padding;return c((this.view.width-(e.left+e.right))/2+e.left,(this.view.height-(e.top+e.bottom))/2+e.top)}get viewpoint(){return this.ready?G(this.view,this.camera):this._get("viewpoint")}set viewpoint(e){if(!this._updatePropertyBeforeReady("viewpoint",e))if(e)if(this.isCompatible(e))this.setStateCamera(this._viewpointToCamera(e),{applyConstraints:!e.camera})||a.getLogger(this).error("#viewpoint=","Invalid viewpoint",e);else{const t=null!=e.camera?e.camera.position:e.targetGeometry,i=null!=t&&t.spatialReference;a.getLogger(this).error("#viewpoint=","Viewpoint has an incompatible spatial reference (viewpoint: "+(i?i.wkid:"none")+", view: "+this.view.spatialReference?.wkid+")",e)}else a.getLogger(this).error("#viewpoint=","Viewpoint may not be null or undefined")}get zoom(){return this.ready?A(this.view,this.scale):this._get("zoom")}set zoom(e){this._updatePropertyBeforeReady("zoom",e)||void 0===e||this.setStateCamera(this._zoomToCamera(e),{applyConstraints:!0})||a.getLogger(this).error("#zoom=","Invalid zoom",e)}_computeCanvasSize(){if(this._devicePixelRatioOverride)return this.view.state.contentPixelRatio=this._devicePixelRatioOverride,this._tmpCanvasSize.width=Math.round(this.view.surface.clientWidth*this._devicePixelRatioOverride),this._tmpCanvasSize.height=Math.round(this.view.surface.clientHeight*this._devicePixelRatioOverride),this._tmpCanvasSize.pixelRatio=this._devicePixelRatioOverride,this._tmpCanvasSize;const e=Math.min(this._windowDevicePixelRatio,this.view.qualitySettings.maximumPixelRatio),t=(this._usePhysicalPixelRendering?this._windowDevicePixelRatio:e)*this.view.resolutionScale;this._tmpCanvasSize.width=Math.round(this.view.surface.clientWidth*t),this._tmpCanvasSize.height=Math.round(this.view.surface.clientHeight*t);const i=this.view._stage.renderView.renderingContext.parameters.maxTextureSize;return J(this._tmpCanvasSize,i),this._tmpCanvasSize.pixelRatio=this._tmpCanvasSize.width>0?this._tmpCanvasSize.width/this.view.surface.clientWidth*.5+this._tmpCanvasSize.height/this.view.surface.clientHeight*.5:t,this.view.state&&(this.view.state.contentPixelRatio=Math.min(this._windowDevicePixelRatio,this.view.qualitySettings.maximumPixelRatio)),this._tmpCanvasSize}get _rasterPixelRatio(){return null!=this._devicePixelRatioOverride?this._devicePixelRatioOverride:this._usePhysicalPixelRenderingAny?this._windowDevicePixelRatio:Math.min(this._windowDevicePixelRatio,this.view.qualitySettings.maximumPixelRatio)}get _usePhysicalPixelRendering(){return this.view?._stage?.renderer.isFeatureEnabled(q.PhysicalPixelRendering)??!1}get _usePhysicalPixelRenderingAny(){const e=this.view?._stage?.renderer;return e&&(e.isFeatureEnabled(q.PhysicalPixelRendering,W.IDLE)||e.isFeatureEnabled(q.PhysicalPixelRendering,W.INTERACTING)||e.isFeatureEnabled(q.PhysicalPixelRendering,W.ANIMATING))}preinit(e){return!(this._isOverridden("center")&&!C(this.center.spatialReference,e))&&(!(this._isOverridden("camera")&&!C(this.camera.position.spatialReference,e))&&(!(this._isOverridden("extent")&&!C(this.extent.spatialReference,e))&&!!(!this._isOverridden("viewpoint")||C(this.viewpoint.targetGeometry?.spatialReference,e)&&C(this.viewpoint.camera?.position?.spatialReference,e))))}init(){this._constraintsManager=new O({view:this.view}),this._prepareFrame();const e=this._getInitialProperties();this._cameraSetByUser=!1,this._set("ready",!0);for(const t of e)this.set(t.name,t.value);if(!this._cameraSetByUser){const e=this._initialViewpoint||this.view.initialExtent;e&&this.isCompatible(e)?this._setInitialView(e):this.view.state.viewingMode===x.Local&&this.addHandles(l((()=>this.view.basemapTerrain.ready),(()=>{this.removeHandles(ie),this._setInitialView(this.view.dataExtent)}),{once:!0,initial:!0}),ie)}}exit(){this._cancelGoToOperation(),this.ready&&(this._override("padding",this.padding),this._set("ready",!1),this._clearOverride("hasInitialView"),this._cameraSetByUser=!1,this.removeHandles(ie),this._constraintsManager=s(this._constraintsManager))}async goTo(e,t){const i={animate:!0,...t};return null!=this._gotoOperation&&this._gotoOperation.abort(i.animate),this._gotoOperation=new b(e,i,this.view),this.view.resourceController.scheduler.stopFrame(),this._gotoOperation.promise}debugSetCameraOnContent(){this.setStateCamera(P(this.view),{applyConstraints:!1})}step(e){const t=this.view.state,i=t?.cameraController;i&&(t.updateCamera((t=>i.stepController(e,t))),i.steppingFinished&&i.finishController())}_cancelGoToOperation(){null!=this._gotoOperation&&(this._gotoOperation.abort(),this._gotoOperation=null)}_getInitialProperties(){const e=new Set,t=[];for(const{propertyName:i,overrides:r}of Y){const a=e.has(i),s=this._isOverridden(i);!a&&s&&t.push({name:i,value:this._get(i)}),this._clearOverride(i),(a||s)&&r.forEach((t=>e.add(t)))}return t}_setInitialView(e){if(null==e||this._cameraSetByUser)return;if(e instanceof t)return void this.setStateCamera(M(this.view,e),{applyConstraints:!1});if(e instanceof i){if(e.targetGeometry instanceof _){const t=H(this.view,e.targetGeometry,0,.5,N.LOCKED);return void(null!=t&&this.setStateCamera(M(this.view,t),{applyConstraints:!0}))}const t={applyConstraints:!e.camera},i=this._viewpointToCamera(e);return void this.setStateCamera(i,t)}const r=H(this.view,e,0,.5,N.LOCKED);null!=r&&this.setStateCamera(M(this.view,r),{applyConstraints:!0})}_updatePropertyBeforeReady(e,t){return!this.ready&&(this._override(e,t),t&&X.has(e)&&this._override("hasInitialView",!0),!0)}isCompatible(e){return null!=e&&(e instanceof i?e.camera?this.isCompatible(e.camera):this.isCompatible(e.targetGeometry):e instanceof t?this.isCompatible(e.position):e.spatialReference&&!f(e.spatialReference,this.view.spatialReference))}_getPreservingHeadingTilt(e=Z){return this._cameraSetByUser?(e.heading=this.camera.heading,e.tilt=this.camera.tilt):(e.heading=0,e.tilt=.5),e}_centerPointAtDistanceToCamera(e,t,i=ee){const{heading:r,tilt:a}=this._getPreservingHeadingTilt(),s=L(this.view,r,a,e,t,N.ADJUST);return null==s?null:(i.copyFrom(this.view.state.camera),i.eye=s.eye,i.center=s.center,i.up=s.up,i)}_centerToCamera(e){const t=this.view.pointsOfInterest.centerOnContent;t.runTask();const i=t.distance;return this._centerPointAtDistanceToCamera(e,i)}_extentToCamera(e){const{heading:t,tilt:i}=this._getPreservingHeadingTilt(),r=H(this.view,e,t,i,N.ADJUST,$);return r?M(this.view,r):null}_scaleToCamera(e){if(null==e)return null;const t=this.view.pointsOfInterest.centerOnContent;t.runTask();const i=t.renderLocation,r=t.location.latitude,a=V(this.view,e,r);return this._centerPointAtDistanceToCamera(i,a)}_zoomToCamera(e){return this._scaleToCamera(B(this.view,e))}_viewpointToCamera(e){return M(this.view,F(this.view,e))}setStateCamera(e,t){return!(null==e||!this.view.state.stopActiveCameraController())&&(this._cameraSetByUser=!0,t.doNotCancelGoToOperation||this._cancelGoToOperation(),this.view.state.updateCamera((i=>{t.positionAndOrientationOnly?(i.eye=e.eye,i.center=e.center,i.up=e.up):i.copyFrom(e),t.applyConstraints&&R(this.view,i)})),t.applyConstraints||(this.view.state.cameraController=new j({view:this.view,desiredCamera:e})),!0)}_prepareFrame(){const{surface:e,canvas:t}=this.view;if(!e||!t)return;this._windowDevicePixelRatio=window.devicePixelRatio;const i=this._computeCanvasSize();if(0!==i.width&&0!==i.height&&(t.width===i.width&&t.height===i.height||(t.width=i.width,t.height=i.height),this.view.state)){const e=this.view.state.camera;e.fullWidth===i.width&&e.fullHeight===i.height&&e.pixelRatio===i.pixelRatio||(ee.copyFrom(e),ee.pixelRatio!==i.pixelRatio&&(this._paddingToArray(this.padding,i.pixelRatio,te),ee.padding=te),ee.fullWidth=i.width,ee.fullHeight=i.height,ee.pixelRatio=i.pixelRatio,this.view.state.camera=ee),this._updateViewState()}}_updateElevation(e){const t=this.view.basemapTerrain?.spatialReference,i=this.view.renderCoordsHelper?.getAltitude(e.eye)??0,r=t?S(this.view,e.eye):0;e.relativeElevation=i-r}_updateViewState(){null!=this.test.renderState?this.view.state.mode=this.test.renderState:this.view.animation?this.view.state.mode=W.ANIMATING:this.view.interacting?this.view.state.mode=W.INTERACTING:(this.view.state.mode===W.ANIMATING&&(this._cameraChangeTime=0),performance.now()-this._cameraChangeTime<this._idleTimeout?this.view.state.mode=W.INTERACTING:this.view.state.mode=W.IDLE),this.view.state.rasterPixelRatio=this._rasterPixelRatio}_cameraChangedHandler(e,t){e&&t&&e.almostEquals(t)||(this._cameraChangeTime=performance.now(),this._updateViewState())}};e([m({type:t,dependsOn:["view.state.camera","ready"]})],K.prototype,"camera",null),e([m({type:t,dependsOn:["view.state.contentCamera","ready"]})],K.prototype,"contentCamera",null),e([m({type:y})],K.prototype,"center",null),e([m({type:_})],K.prototype,"extent",null),e([m({readOnly:!0})],K.prototype,"frustum",null),e([m()],K.prototype,"_constraintsManager",void 0),e([m({readOnly:!0})],K.prototype,"constraintsManager",null),e([m()],K.prototype,"_initialViewpoint",null),e([m({readOnly:!0})],K.prototype,"hasInitialView",null),e([m({readOnly:!0,type:Boolean})],K.prototype,"ready",void 0),e([m({type:Number})],K.prototype,"scale",null),e([m()],K.prototype,"padding",null),e([m({readOnly:!0})],K.prototype,"screenCenter",null),e([m({constructOnly:!0})],K.prototype,"view",void 0),e([m({type:i})],K.prototype,"viewpoint",null),e([m({type:Number})],K.prototype,"zoom",null),e([m({readOnly:!0})],K.prototype,"_rasterPixelRatio",null),e([m({readOnly:!0})],K.prototype,"_usePhysicalPixelRendering",null),e([m({readOnly:!0})],K.prototype,"_usePhysicalPixelRenderingAny",null),e([m()],K.prototype,"_windowDevicePixelRatio",void 0),e([m()],K.prototype,"_devicePixelRatioOverride",void 0),K=e([d("esri.views.3d.state.ViewStateManager")],K);class Q{constructor(){this.width=0,this.height=0,this.pixelRatio=1}}const X=new Set(["camera","viewpoint","extent","scale","center","zoom"]),Y=[{propertyName:"camera",overrides:["viewpoint"]},{propertyName:"viewpoint",overrides:["extent"]},{propertyName:"extent",overrides:["center","scale"]},{propertyName:"center",overrides:[]},{propertyName:"scale",overrides:["zoom"]},{propertyName:"zoom",overrides:[]},{propertyName:"padding",overrides:[]}],Z={heading:0,tilt:0},$=new t,ee=new U,te=g(),ie="pending-initial-view",re="content-camera-reset",ae=300,se=100;export{K as ViewStateManager,se as interactingTimeout};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Camera.js";import i from"../../../Viewpoint.js";import r from"../../../core/Accessor.js";import a from"../../../core/Logger.js";import{destroyMaybe as s}from"../../../core/maybe.js";import{on as n,watch as o,sync as h,when as l}from"../../../core/reactiveUtils.js";import{addFrameTask as p}from"../../../core/scheduling.js";import{createScreenPoint as c}from"../../../core/screenUtils.js";import{property as m}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/RandomLCG.js";import{subclass as d}from"../../../core/accessorSupport/decorators/subclass.js";import{a as v}from"../../../chunks/vec32.js";import{fromArray as u}from"../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as w}from"../../../chunks/vec42.js";import{create as g}from"../../../core/libs/gl-matrix-2/factories/vec4f64.js";import _ from"../../../geometry/Extent.js";import y from"../../../geometry/Point.js";import{isLoadedOrLoadFor as C,requiresLoad as f}from"../../../geometry/projection.js";import{ViewingMode as x}from"../../ViewingMode.js";import{applyAll as R}from"../camera/constraintUtils.js";import{cameraOnContentAlongViewDirection as P,surfaceElevationBelowRenderLocation as S}from"../camera/intersectionUtils.js";import{ConstraintsManager as O}from"./ConstraintsManager.js";import{Frustum as T}from"./Frustum.js";import{GoToOperation as b}from"./GoToOperation.js";import{SurfaceCollisionCorrectionController as j}from"./controllers/SurfaceCollisionCorrectionController.js";import{internalToExternal as I,externalToInternal as M,toExtent as z,distanceToScale as E,scaleToZoom as A,fromExtentSync as H,OrientationMode as N,getObserverForPointAtDistanceSync as L,scaleToDistance as V,zoomToScale as B}from"../support/cameraUtils.js";import{PropertiesPool as D}from"../support/PropertiesPool.js";import{fromCamera as G,toCameraSync as F}from"../support/viewpointUtils.js";import{Camera as U,PaddingSide as k}from"../webgl-engine/lib/Camera.js";import{RenderFeature as q}from"../webgl-engine/lib/RenderFeature.js";import{RenderState as W}from"../../support/RenderState.js";import{ensureAttachmentMaxSize as J}from"../../webgl/FramebufferObject.js";let K=class extends r{constructor(e){super(e),this.ready=!1,this._windowDevicePixelRatio=1,this._devicePixelRatioOverride=null,this._idleTimeout=ae,this.test={viewStateManager:this,contentCameraResetState:new Map,setDevicePixelRatio:e=>this._devicePixelRatioOverride=e,renderState:null,get maximumPixelRatio(){return this.viewStateManager.view.qualitySettings.maximumPixelRatio},get updatingIgnoreRenderState(){return null!=this.renderState},get idleTimeoutEnabled(){return this.viewStateManager._idleTimeout>0},set idleTimeoutEnabled(e){this.viewStateManager._idleTimeout=e?ae:0}},this._propertiesPool=new D({frustum:T},this),this._cameraSetByUser=!1,this._gotoOperation=null,this._cameraChangeTime=0,this._tmpCanvasSize=new Q}initialize(){this._cameraChangeTime=performance.now(),this.addHandles([n((()=>this.view.state.events),"before-camera-change",(e=>e&&this._updateElevation(e))),o((()=>this.view.state?.camera),((e,t)=>this._cameraChangedHandler(e,t)),h)]),l((()=>this.view.state?.camera),(e=>this._updateElevation(e)),{once:!0,sync:!0}),this.addHandles([p({prepare:()=>this._prepareFrame()}),o((()=>this.view.state.cameraController),(()=>{this._cameraSetByUser=!0,this.removeHandles(ie)})),n((()=>this.view.state.events),"camera-projection-changed",(()=>this.notifyChange("scale")))])}destroy(){this.exit(),this._propertiesPool=s(this._propertiesPool)}get camera(){const e=this._get("camera");if(!this.ready)return e;const t=I(this.view,this.view.state.camera,$);return t&&e&&t.equals(e)?e:t.clone()}set camera(e){this._updatePropertyBeforeReady("camera",e)||(this.view.elevationProvider?.enableCache(!0),this.setStateCamera(M(this.view,e),{applyConstraints:!1})||a.getLogger(this).error("#camera=","Invalid camera",e),this.view.elevationProvider?.enableCache(!1))}get contentCamera(){const e=this._get("contentCamera");if(!this.ready)return e;const t=I(this.view,this.view.state.contentCamera,$);return t&&e&&t.equals(e)?e:t.clone()}set contentCamera(e){if(this._updatePropertyBeforeReady("contentCamera",e))return;const t=M(this.view,e);null!=t?(this._updateElevation(t),this.view.state.contentCamera=t):this.view.state.contentCamera=null}installContentCameraReset(e){if(this.removeHandles(re),this.test.contentCameraResetState.clear(),!this.view.state.fixedContentCamera)return!1;const t=this.zoom,i=this.view.state.camera.distance**2,r=u(this.view.state.camera.center),a=e.sticky?this.contentCamera.clone():null;return this.addHandles([o((()=>this.contentCamera),(()=>{e.sticky||(this.removeHandles(re),this.test.contentCameraResetState.clear())})),o((()=>this.zoom),(e=>{void 0!==e&&void 0!==t&&(this.test.contentCameraResetState.set("view.zoom",Math.abs(e-t)/2),Math.abs(e-t)>2?this.contentCamera=null:this.view.state.fixedContentCamera||(this.contentCamera=a))})),o((()=>this.view.state.camera),(e=>{const t=v(r,e.center);this.test.contentCameraResetState.set("camera.center",t/i),t>i?this.contentCamera=null:this.view.state.fixedContentCamera||(this.contentCamera=a)}))],re),!0}get center(){return this.ready?this.view.pointsOfInterest.centerOnContent.location:this._get("center")}set center(e){this._updatePropertyBeforeReady("center",e)||(e?this.isCompatible(e)?this.setStateCamera(this._centerToCamera(e),{applyConstraints:!0})?this.view.pointsOfInterest.centerOnContent.runTask():a.getLogger(this).error("#center=","Invalid center",e):a.getLogger(this).error("#center=","Center has an incompatible spatial reference (center: "+(e.spatialReference?e.spatialReference.wkid:"none")+", view: "+this.view.spatialReference?.wkid+")",e):a.getLogger(this).error("#center=","Center may not be null or undefined"))}get extent(){if(!this.ready)return this._get("extent");const e=this.view,t=z(e,e.state.camera,e.pointsOfInterest.centerOnContent.renderLocation);return null!=t?t:this._get("extent")}set extent(e){this._updatePropertyBeforeReady("extent",e)||(e?this.isCompatible(e)?this.setStateCamera(this._extentToCamera(e),{applyConstraints:!0})||a.getLogger(this).error("#extent=","Invalid extent",e):a.getLogger(this).error("#extent=","Extent has an incompatible spatial reference (extent: "+(e.spatialReference?e.spatialReference.wkid:"none")+", view: "+this.view.spatialReference?.wkid+")",e):a.getLogger(this).error("#extent=","Extent may not be null or undefined"))}get frustum(){const e=this._propertiesPool.get("frustum");return e.renderCoordsHelper=this.view.renderCoordsHelper,e.update(this.view.state.camera),e}get constraintsManager(){return this._constraintsManager}get _initialViewpoint(){const e=this.view.map;return e&&"initialViewProperties"in e?e.initialViewProperties?.viewpoint:void 0}get hasInitialView(){return!!this._initialViewpoint}get scale(){if(this.ready){const e=this.view.pointsOfInterest.centerOnContent;return E(this.view,e.distance,e.location.latitude)}return this._get("scale")}set scale(e){this._updatePropertyBeforeReady("scale",e)||this.setStateCamera(this._scaleToCamera(e),{applyConstraints:!0})||a.getLogger(this).error("#scale=","Invalid scale",e)}get padding(){if(!this.ready)return this._get("padding");const e=this.view.state.camera,t=e.padding,i=e.pixelRatio,r=this._get("padding"),a=Math.round(t[k.TOP]/i),s=Math.round(t[k.RIGHT]/i),n=Math.round(t[k.BOTTOM]/i),o=Math.round(t[k.LEFT]/i);return null!=r&&r.top===a&&r.right===s&&r.bottom===n&&r.left===o?r:{top:a,right:s,bottom:n,left:o}}set padding(e){this._updatePropertyBeforeReady("padding",e)||(this._paddingToArray(e,this.view.state.camera.pixelRatio,te),this.view.state.updateCamera((e=>e.padding=te)))}_paddingToArray(e,t,i){e?w(i,e.top||0,e.right||0,e.bottom||0,e.left||0):w(i,0,0,0,0);for(let r=0;r<4;r++)i[r]=Math.round(i[r]*t)}get screenCenter(){const e=this.padding;return c((this.view.width-(e.left+e.right))/2+e.left,(this.view.height-(e.top+e.bottom))/2+e.top)}get viewpoint(){return this.ready?G(this.view,this.camera):this._get("viewpoint")}set viewpoint(e){if(!this._updatePropertyBeforeReady("viewpoint",e))if(e)if(this.isCompatible(e))this.setStateCamera(this._viewpointToCamera(e),{applyConstraints:!e.camera})||a.getLogger(this).error("#viewpoint=","Invalid viewpoint",e);else{const t=null!=e.camera?e.camera.position:e.targetGeometry,i=null!=t&&t.spatialReference;a.getLogger(this).error("#viewpoint=","Viewpoint has an incompatible spatial reference (viewpoint: "+(i?i.wkid:"none")+", view: "+this.view.spatialReference?.wkid+")",e)}else a.getLogger(this).error("#viewpoint=","Viewpoint may not be null or undefined")}get zoom(){return this.ready?A(this.view,this.scale):this._get("zoom")}set zoom(e){this._updatePropertyBeforeReady("zoom",e)||void 0===e||this.setStateCamera(this._zoomToCamera(e),{applyConstraints:!0})||a.getLogger(this).error("#zoom=","Invalid zoom",e)}_computeCanvasSize(){if(this._devicePixelRatioOverride)return this.view.state.contentPixelRatio=this._devicePixelRatioOverride,this._tmpCanvasSize.width=Math.round(this.view.surface.clientWidth*this._devicePixelRatioOverride),this._tmpCanvasSize.height=Math.round(this.view.surface.clientHeight*this._devicePixelRatioOverride),this._tmpCanvasSize.pixelRatio=this._devicePixelRatioOverride,this._tmpCanvasSize;const e=Math.min(this._windowDevicePixelRatio,this.view.qualitySettings.maximumPixelRatio),t=(this._usePhysicalPixelRendering?this._windowDevicePixelRatio:e)*this.view.resolutionScale;this._tmpCanvasSize.width=Math.round(this.view.surface.clientWidth*t),this._tmpCanvasSize.height=Math.round(this.view.surface.clientHeight*t);const i=this.view._stage.renderView.renderingContext?.parameters.maxTextureSize;return i&&J(this._tmpCanvasSize,i),this._tmpCanvasSize.pixelRatio=this._tmpCanvasSize.width>0?this._tmpCanvasSize.width/this.view.surface.clientWidth*.5+this._tmpCanvasSize.height/this.view.surface.clientHeight*.5:t,this.view.state&&(this.view.state.contentPixelRatio=Math.min(this._windowDevicePixelRatio,this.view.qualitySettings.maximumPixelRatio)),this._tmpCanvasSize}get _rasterPixelRatio(){return null!=this._devicePixelRatioOverride?this._devicePixelRatioOverride:this._usePhysicalPixelRenderingAny?this._windowDevicePixelRatio:Math.min(this._windowDevicePixelRatio,this.view.qualitySettings.maximumPixelRatio)}get _usePhysicalPixelRendering(){return this.view?._stage?.renderer.isFeatureEnabled(q.PhysicalPixelRendering)??!1}get _usePhysicalPixelRenderingAny(){const e=this.view?._stage?.renderer;return e&&(e.isFeatureEnabled(q.PhysicalPixelRendering,W.IDLE)||e.isFeatureEnabled(q.PhysicalPixelRendering,W.INTERACTING)||e.isFeatureEnabled(q.PhysicalPixelRendering,W.ANIMATING))}preinit(e){return!(this._isOverridden("center")&&!C(this.center.spatialReference,e))&&(!(this._isOverridden("camera")&&!C(this.camera.position.spatialReference,e))&&(!(this._isOverridden("extent")&&!C(this.extent.spatialReference,e))&&!!(!this._isOverridden("viewpoint")||C(this.viewpoint.targetGeometry?.spatialReference,e)&&C(this.viewpoint.camera?.position?.spatialReference,e))))}init(){this._constraintsManager=new O({view:this.view}),this._prepareFrame();const e=this._getInitialProperties();this._cameraSetByUser=!1,this._set("ready",!0);for(const t of e)this.set(t.name,t.value);if(!this._cameraSetByUser){const e=this._initialViewpoint||this.view.initialExtent;e&&this.isCompatible(e)?this._setInitialView(e):this.view.state.viewingMode===x.Local&&this.addHandles(l((()=>this.view.basemapTerrain.ready),(()=>{this.removeHandles(ie),this._setInitialView(this.view.dataExtent)}),{once:!0,initial:!0}),ie)}}exit(){this._cancelGoToOperation(),this.ready&&(this._override("padding",this.padding),this._set("ready",!1),this._clearOverride("hasInitialView"),this._cameraSetByUser=!1,this.removeHandles(ie),this._constraintsManager=s(this._constraintsManager))}async goTo(e,t){const i={animate:!0,...t};return null!=this._gotoOperation&&this._gotoOperation.abort(i.animate),this._gotoOperation=new b(e,i,this.view),this.view.resourceController.scheduler.stopFrame(),this._gotoOperation.promise}debugSetCameraOnContent(){this.setStateCamera(P(this.view),{applyConstraints:!1})}step(e){const t=this.view.state,i=t?.cameraController;i&&(t.updateCamera((t=>i.stepController(e,t))),i.steppingFinished&&i.finishController())}_cancelGoToOperation(){null!=this._gotoOperation&&(this._gotoOperation.abort(),this._gotoOperation=null)}_getInitialProperties(){const e=new Set,t=[];for(const{propertyName:i,overrides:r}of Y){const a=e.has(i),s=this._isOverridden(i);!a&&s&&t.push({name:i,value:this._get(i)}),this._clearOverride(i),(a||s)&&r.forEach((t=>e.add(t)))}return t}_setInitialView(e){if(null==e||this._cameraSetByUser)return;if(e instanceof t)return void this.setStateCamera(M(this.view,e),{applyConstraints:!1});if(e instanceof i){if(e.targetGeometry instanceof _){const t=H(this.view,e.targetGeometry,0,.5,N.LOCKED);return void(null!=t&&this.setStateCamera(M(this.view,t),{applyConstraints:!0}))}const t={applyConstraints:!e.camera},i=this._viewpointToCamera(e);return void this.setStateCamera(i,t)}const r=H(this.view,e,0,.5,N.LOCKED);null!=r&&this.setStateCamera(M(this.view,r),{applyConstraints:!0})}_updatePropertyBeforeReady(e,t){return!this.ready&&(this._override(e,t),t&&X.has(e)&&this._override("hasInitialView",!0),!0)}isCompatible(e){return null!=e&&(e instanceof i?e.camera?this.isCompatible(e.camera):this.isCompatible(e.targetGeometry):e instanceof t?this.isCompatible(e.position):e.spatialReference&&!f(e.spatialReference,this.view.spatialReference))}_getPreservingHeadingTilt(e=Z){return this._cameraSetByUser?(e.heading=this.camera.heading,e.tilt=this.camera.tilt):(e.heading=0,e.tilt=.5),e}_centerPointAtDistanceToCamera(e,t,i=ee){const{heading:r,tilt:a}=this._getPreservingHeadingTilt(),s=L(this.view,r,a,e,t,N.ADJUST);return null==s?null:(i.copyFrom(this.view.state.camera),i.eye=s.eye,i.center=s.center,i.up=s.up,i)}_centerToCamera(e){const t=this.view.pointsOfInterest.centerOnContent;t.runTask();const i=t.distance;return this._centerPointAtDistanceToCamera(e,i)}_extentToCamera(e){const{heading:t,tilt:i}=this._getPreservingHeadingTilt(),r=H(this.view,e,t,i,N.ADJUST,$);return r?M(this.view,r):null}_scaleToCamera(e){if(null==e)return null;const t=this.view.pointsOfInterest.centerOnContent;t.runTask();const i=t.renderLocation,r=t.location.latitude,a=V(this.view,e,r);return this._centerPointAtDistanceToCamera(i,a)}_zoomToCamera(e){return this._scaleToCamera(B(this.view,e))}_viewpointToCamera(e){return M(this.view,F(this.view,e))}setStateCamera(e,t){return!(null==e||!this.view.state.stopActiveCameraController())&&(this._cameraSetByUser=!0,t.doNotCancelGoToOperation||this._cancelGoToOperation(),this.view.state.updateCamera((i=>{t.positionAndOrientationOnly?(i.eye=e.eye,i.center=e.center,i.up=e.up):i.copyFrom(e),t.applyConstraints&&R(this.view,i)})),t.applyConstraints||(this.view.state.cameraController=new j({view:this.view,desiredCamera:e})),!0)}_prepareFrame(){const{surface:e,canvas:t}=this.view;if(!e||!t)return;this._windowDevicePixelRatio=window.devicePixelRatio;const i=this._computeCanvasSize();if(0!==i.width&&0!==i.height&&(t.width===i.width&&t.height===i.height||(t.width=i.width,t.height=i.height),this.view.state)){const e=this.view.state.camera;e.fullWidth===i.width&&e.fullHeight===i.height&&e.pixelRatio===i.pixelRatio||(ee.copyFrom(e),ee.pixelRatio!==i.pixelRatio&&(this._paddingToArray(this.padding,i.pixelRatio,te),ee.padding=te),ee.fullWidth=i.width,ee.fullHeight=i.height,ee.pixelRatio=i.pixelRatio,this.view.state.camera=ee),this._updateViewState()}}_updateElevation(e){const t=this.view.basemapTerrain?.spatialReference,i=this.view.renderCoordsHelper?.getAltitude(e.eye)??0,r=t?S(this.view,e.eye):0;e.relativeElevation=i-r}_updateViewState(){null!=this.test.renderState?this.view.state.mode=this.test.renderState:this.view.animation?this.view.state.mode=W.ANIMATING:this.view.interacting?this.view.state.mode=W.INTERACTING:(this.view.state.mode===W.ANIMATING&&(this._cameraChangeTime=0),performance.now()-this._cameraChangeTime<this._idleTimeout?this.view.state.mode=W.INTERACTING:this.view.state.mode=W.IDLE),this.view.state.rasterPixelRatio=this._rasterPixelRatio}_cameraChangedHandler(e,t){e&&t&&e.almostEquals(t)||(this._cameraChangeTime=performance.now(),this._updateViewState())}};e([m({type:t,dependsOn:["view.state.camera","ready"]})],K.prototype,"camera",null),e([m({type:t,dependsOn:["view.state.contentCamera","ready"]})],K.prototype,"contentCamera",null),e([m({type:y})],K.prototype,"center",null),e([m({type:_})],K.prototype,"extent",null),e([m({readOnly:!0})],K.prototype,"frustum",null),e([m()],K.prototype,"_constraintsManager",void 0),e([m({readOnly:!0})],K.prototype,"constraintsManager",null),e([m()],K.prototype,"_initialViewpoint",null),e([m({readOnly:!0})],K.prototype,"hasInitialView",null),e([m({readOnly:!0,type:Boolean})],K.prototype,"ready",void 0),e([m({type:Number})],K.prototype,"scale",null),e([m()],K.prototype,"padding",null),e([m({readOnly:!0})],K.prototype,"screenCenter",null),e([m({constructOnly:!0})],K.prototype,"view",void 0),e([m({type:i})],K.prototype,"viewpoint",null),e([m({type:Number})],K.prototype,"zoom",null),e([m({readOnly:!0})],K.prototype,"_rasterPixelRatio",null),e([m({readOnly:!0})],K.prototype,"_usePhysicalPixelRendering",null),e([m({readOnly:!0})],K.prototype,"_usePhysicalPixelRenderingAny",null),e([m()],K.prototype,"_windowDevicePixelRatio",void 0),e([m()],K.prototype,"_devicePixelRatioOverride",void 0),K=e([d("esri.views.3d.state.ViewStateManager")],K);class Q{constructor(){this.width=0,this.height=0,this.pixelRatio=1}}const X=new Set(["camera","viewpoint","extent","scale","center","zoom"]),Y=[{propertyName:"camera",overrides:["viewpoint"]},{propertyName:"viewpoint",overrides:["extent"]},{propertyName:"extent",overrides:["center","scale"]},{propertyName:"center",overrides:[]},{propertyName:"scale",overrides:["zoom"]},{propertyName:"zoom",overrides:[]},{propertyName:"padding",overrides:[]}],Z={heading:0,tilt:0},$=new t,ee=new U,te=g(),ie="pending-initial-view",re="content-camera-reset",ae=300,se=100;export{K as ViewStateManager,se as interactingTimeout};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{MemCachePool as e}from"../../../core/MemCachePool.js";import{terrainAttributesLayout as t}from"./TerrainAttributes.js";class r{constructor(t){this._storage=new e(((e,r)=>t.newCache(e,r)),"TileGeometry")}acquire(e){const r=4,s=Math.ceil(e/r)*r,a=this._storage.pop(o(s));if(a)return a;const c=t.createBuffer(s);return c.release=()=>this._release(c),c}_release(e){const t=e.count;this._storage.put(o(t),e)}clear(){this._storage.clear()}destroy(){this._storage.destroy()}}function o(e){return e.toString()}export{r as TerrainAttributesCache};
5
+ import{MemCachePool as e}from"../../../core/MemCachePool.js";import{terrainAttributesLayout as r}from"./TerrainAttributes.js";class t{constructor(r){this._storage=new e(((e,t)=>r.newCache(e,t)),"TileGeometry")}acquire(e){const t=4,s=Math.ceil(e/t)*t,a=this._storage,c=o(s),i=a.pop(c);if(i)return i;const n=r.createBuffer(s);return n.release=()=>a.put(c,n),n}clear(){this._storage.clear()}destroy(){this._storage.destroy()}}function o(e){return e.toString()}export{t as TerrainAttributesCache};
@@ -0,0 +1,5 @@
1
+ /*
2
+ All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
+ See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
+ */
5
+ import e from"../../../../core/PooledArray.js";class r{constructor(){this._nodes=new e}add(e){this._nodes.push(e)}remove(e){this._nodes.remove(e)?.destroy()}produces(e){return this._nodes.some((r=>r.produces.includes(e)))}consumes(e){return this._nodes.some((r=>r.consumes.required.includes(e)))}render(e,r){if(!e.composite)return;let s,o=e.composite;return this._nodes.filter((e=>e.produces.includes(r))).forEach((n=>{const t=new Array;for(const r of n.consumes.required)switch(r){case"composite-color":t.push(o);break;case"linear-depth":if(!e.linearDepth)return;t.push(e.linearDepth);break;case"normals":if(!e.normals)return;t.push(e.normals);break;case"highlight":if(!e.highlight)return;t.push(e.highlight)}o=n.render(t,r),s?.release(),s=o})),s}}export{r as RenderNodes};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import"../../../../core/has.js";import{releaseMaybe as t}from"../../../../core/maybe.js";import{c as e}from"../../../../chunks/vec42.js";import{create as r}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{ColorFormat as i,DepthFormat as o}from"../core/FBOCache.js";import{RendererTarget as h}from"./rendererUtils.js";import{TransparencyPassType as s}from"./TransparencyPassType.js";import{ClearBufferBit as c}from"../../../webgl/enums.js";import{ensureAttachmentMaxSize as a}from"../../../webgl/FramebufferObject.js";class l{constructor(t,e){this._fbos=t,this.compositingHelper=e,this._width=4,this._height=4,this._clearColor=r()}dispose(){this._color=t(this._color),this.releaseBuffers()}get framebuffer(){return this.color.detachDepth(),this.color.attachDepth(this.depth),this.color.fbo}get colorTexture(){return this.color.colorTexture}get depthTexture(){return this.depth.attachment}initializeFrame(t,r,i){this._fbos.interactive=i===h.Default;const o=this._fbos.rctx;this._width=t.fullWidth,this._height=t.fullHeight,a(this,o.parameters.maxTextureSize);const s=this._color;return this._color=null,this.releaseBuffers(),e(this._clearColor,r),s}releaseBuffers(){this._color?.detachDepth(),this._depth=t(this._depth)}renderHUDVisibility(t,e,r){return t?.fbo.width===this._width&&t?.fbo.height===this._height||(t?.release(),t=this._fbos.acquire(this._width,this._height,"hud visibility",i.RGBA4)),t.attachDepth(r||this.depth),this._fbos.rctx.bindFramebuffer(t.fbo),this.renderToFBO(e,f),t.detachDepth(),t}compositeToHUDVisibility(t,e){this._fbos.rctx.bindFramebuffer(t.hudVisibility?.fbo),this.compositingHelper.compositeHUD(t,e)}renderOITPass(t,e,r){let h,c;const{_width:a,_height:l}=this;switch(e){case s.Color:h=this._fbos.acquire(a,l,r?"oit hud color":"oit color",i.RGBA16F),c=[0,0,0,0];break;case s.Alpha:h=this._fbos.acquire(a,l,r?"oit hud alpha":"oit alpha",i.R16F),c=[1,1,1,1];break;case s.FrontFace:h=this._fbos.acquire(a,l,r?"oit hud front":"oit front"),c=[0,0,0,0]}return r?(h.acquireDepth(o.DEPTH16_BUFFER),this._fbos.rctx.bindFramebuffer(h.fbo),this.renderToFBO(t,c,!0,!0),h.releaseDepth()):(h.attachDepth(this.depth),this._fbos.rctx.bindFramebuffer(h.fbo),this.renderToFBO(t,c),h.detachDepth()),h}compositeToFramebuffer(t,e,r,i){this.bindFbo(),this.compositingHelper.composite(t,e,r,i)}compositeTransparentOntoOpaque(t,e,r,i,o){o?(this._fbos.rctx.bindFramebuffer(o.fbo),this._fbos.rctx.setClearColor(0,0,0,1e-13),this._fbos.rctx.clearSafe(c.COLOR_BUFFER_BIT)):this.bindFbo(),this.compositingHelper.compositeOIT(t,e.colorTexture,r.colorTexture,i.colorTexture)}renderDepthDetached(t){this._bindTarget(this.color),t(),this._bindTarget(this.color,this.depth)}renderToCachedFBO(e,r,h,s,c=i.RGBA,a=o.DEPTH16_BUFFER,l=this._width,f=this._height,_=null){return e?.fbo.width===l&&e?.fbo.height===f||(e=t(e)),e=e??this._fbos.acquire(l,f,r,c),null!=a&&e.acquireDepth(a),_?.forEach((t=>{e.acquireColor(t.format,t.attachment)})),this._fbos.rctx.bindFramebuffer(e.fbo),this.renderToFBO(h,s,!0,!0),e}renderToFBO(t,e,r=!1,i=!1){const o=this._fbos.rctx;let h=0;if(e){const t=1e-13,r=Math.max(t,e[3]);o.setClearColor(e[0],e[1],e[2],r),h|=c.COLOR_BUFFER_BIT}r&&(h|=c.DEPTH_BUFFER_BIT),!1===i?i=0:(!0===i&&(i=255),h|=c.STENCIL_BUFFER_BIT),h&&o.clearSafe(h,i),t(),o.gl.flush()}renderToTargets(t,e,r,i,o=!1,h=!1){this._bindTarget(e,r),this.renderToFBO(t,i,o,h),e.detachDepth()}bindFbo(){const t=null==this._color;if(this._bindTarget(this.color,this.depth),t){const t=this._fbos.rctx;t.setClearStencil(0),t.setClearColor(this._clearColor[0],this._clearColor[1],this._clearColor[2],this._clearColor[3]),t.clearSafe(c.COLOR_BUFFER_BIT|c.DEPTH_BUFFER_BIT|c.STENCIL_BUFFER_BIT)}}_bindTarget(t,e){t.detachDepth(),t.attachDepth(e),this._fbos.rctx.bindFramebuffer(t.fbo)}get width(){return this._width}get height(){return this._height}get color(){return this._color||(this._color=this._fbos.acquire(this._width,this._height,"composite-color")),this._color}get depth(){return this._depth||(this._depth=this._fbos.acquireDepth(o.DEPTH_STENCIL_TEXTURE,this._width,this._height,"depth")),this._depth}}const f=[0,1,0,1];export{l as OffscreenRendering};
5
+ import"../../../../core/has.js";import{releaseMaybe as t}from"../../../../core/maybe.js";import{c as e}from"../../../../chunks/vec42.js";import{create as r}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{ColorFormat as i,DepthFormat as h}from"../core/FBOCache.js";import{RendererTarget as o}from"./rendererUtils.js";import{TransparencyPassType as s}from"./TransparencyPassType.js";import{ClearBufferBit as c}from"../../../webgl/enums.js";import{ensureAttachmentMaxSize as a}from"../../../webgl/FramebufferObject.js";class l{constructor(t,e){this._fbos=t,this.compositingHelper=e,this._width=4,this._height=4,this._clearColor=r()}dispose(){this._color=t(this._color),this.releaseBuffers()}get framebuffer(){return this.color.detachDepth(),this.color.attachDepth(this.depth),this.color.fbo}get colorTexture(){return this.color.colorTexture}get depthTexture(){return this.depth.attachment}initializeFrame(t,r,i){this._fbos.interactive=i===o.Default;const h=this._fbos.rctx;this._width=t.fullWidth,this._height=t.fullHeight,a(this,h.parameters.maxTextureSize);const s=this._color;return this._color=null,this.releaseBuffers(),e(this._clearColor,r),s}releaseBuffers(){this._color?.detachDepth(),this._depth=t(this._depth)}renderHUDVisibility(t,e,r){return t?.fbo.width===this._width&&t?.fbo.height===this._height||(t?.release(),t=this._fbos.acquire(this._width,this._height,"hud visibility",i.RGBA4)),t.attachDepth(r||this.depth),this._fbos.rctx.bindFramebuffer(t.fbo),this._fbos.rctx.clearFramebuffer(f),e(),t.detachDepth(),t}compositeToHUDVisibility(t,e){this._fbos.rctx.bindFramebuffer(t.hudVisibility?.fbo),this.compositingHelper.compositeHUD(t,e)}renderOITPass(t,e,r){let o,c;const{_width:a,_height:l}=this;switch(e){case s.Color:o=this._fbos.acquire(a,l,r?"oit hud color":"oit color",i.RGBA16F),c=[0,0,0,0];break;case s.Alpha:o=this._fbos.acquire(a,l,r?"oit hud alpha":"oit alpha",i.R16F),c=[1,1,1,1];break;case s.FrontFace:o=this._fbos.acquire(a,l,r?"oit hud front":"oit front"),c=[0,0,0,0]}return r?o.acquireDepth(h.DEPTH16_BUFFER):o.attachDepth(this.depth),this._fbos.rctx.bindFramebuffer(o.fbo),this._fbos.rctx.clearFramebuffer(c,r,r),t(),r?o.releaseDepth():o.detachDepth(),o}compositeToFramebuffer(t,e,r,i){this.bindFbo(),this.compositingHelper.composite(t,e,r,i)}compositeTransparentOntoOpaque(t,e,r,i,h){h?(this._fbos.rctx.bindFramebuffer(h.fbo),this._fbos.rctx.setClearColor(0,0,0,1e-13),this._fbos.rctx.clearSafe(c.COLOR_BUFFER_BIT)):this.bindFbo(),this.compositingHelper.compositeOIT(t,e.colorTexture,r.colorTexture,i.colorTexture)}renderDepthDetached(t){this._bindTarget(this.color),t(),this._bindTarget(this.color,this.depth)}renderToCachedFBO(e,r,o,s,c=i.RGBA,a=h.DEPTH16_BUFFER,l=this._width,f=this._height,_=null){return e?.fbo.width===l&&e?.fbo.height===f||(e=t(e)),e=e??this._fbos.acquire(l,f,r,c),null!=a&&e.acquireDepth(a),_?.forEach((t=>{e.acquireColor(t.format,t.attachment)})),this._fbos.rctx.bindFramebuffer(e.fbo),this._fbos.rctx.clearFramebuffer(s,!0,!0),o(),e}renderToTargets(t,e,r,i,h=!1,o=!1){this._bindTarget(e,r),this._fbos.rctx.clearFramebuffer(i,h,o),t(),e.detachDepth()}bindFbo(){const t=null==this._color;if(this._bindTarget(this.color,this.depth),t){const t=this._fbos.rctx;t.setClearStencil(0),t.setClearColor(this._clearColor[0],this._clearColor[1],this._clearColor[2],this._clearColor[3]),t.clearSafe(c.COLOR_BUFFER_BIT|c.DEPTH_BUFFER_BIT|c.STENCIL_BUFFER_BIT)}}_bindTarget(t,e){t.detachDepth(),t.attachDepth(e),this._fbos.rctx.bindFramebuffer(t.fbo)}get width(){return this._width}get height(){return this._height}get color(){return this._color||(this._color=this._fbos.acquire(this._width,this._height,"composite-color")),this._color}get depth(){return this._depth||(this._depth=this._fbos.acquireDepth(h.DEPTH_STENCIL_TEXTURE,this._width,this._height,"depth")),this._depth}}const f=[0,1,0,1];export{l as OffscreenRendering};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../../chunks/tslib.es6.js";import r from"../../../../core/Accessor.js";import{update as t}from"../../../../core/arrayUtils.js";import{unitRGBAFromColor as s}from"../../../../core/colorUtils.js";import has from"../../../../core/has.js";import{removeMaybe as i,destroyMaybe as a,releaseMaybe as n}from"../../../../core/maybe.js";import h from"../../../../core/PooledArray.js";import{watch as o,syncAndInitial as d,initial as l,sync as _}from"../../../../core/reactiveUtils.js";import{property as p}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import{subclass as u}from"../../../../core/accessorSupport/decorators/subclass.js";import{equals as c,invert as m,multiply as f}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{IDENTITY as g,create as T}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{s as E}from"../../../../chunks/vec42.js";import{fromValues as A,ZEROS as b}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{a as R}from"../../../../chunks/boundedPlane.js";import{debugFlags as P}from"../../support/debugFlags.js";import{TransparencyMode as S}from"../../terrain/TerrainRenderer.js";import{DepthFormat as D,FBOCache as O,ColorFormat as y}from"../core/FBOCache.js";import{RenderPassManager as C}from"../core/renderPasses/RenderPassManager.js";import{ShaderOutput as I}from"../core/shaderLibrary/ShaderOutput.js";import{HUDRenderStyle as w}from"../core/shaderLibrary/hud/HUDRenderStyle.js";import{RenderNodeCollection as N}from"../effects/RenderNodeCollection.js";import{isPrepareRenderPlugin as L}from"../effects/RenderPlugin.js";import{RenderPluginInput as H}from"../effects/RenderPluginInput.js";import{RenderPluginManager as M}from"../effects/RenderPluginManager.js";import{Blit as F}from"../effects/blit/Blit.js";import{Highlight as x}from"../effects/highlight/Highlight.js";import{ShadowHighlight as v}from"../effects/highlight/ShadowHighlight.js";import{SMAA as U}from"../effects/smaa/SMAA.js";import{SSAO as G}from"../effects/ssao/SSAO.js";import{AnimationTimeStep as q}from"./AnimationTimeStep.js";import{Decorations as B,RenderRequestType as j,StencilBits as V}from"./basicInterfaces.js";import{BoundingInfo as Q}from"./BoundingInfo.js";import{zero as W,union as k}from"./depthRange.js";import{depthRangeFromScene as X}from"./depthRangeUtils.js";import{RenderOccludedFlag as Y}from"./Material.js";import{OffscreenRendering as z}from"./OffscreenRendering.js";import{RenderContext as J,defaultRenderOccludedMask as K}from"./RenderContext.js";import{splitRenderGeometryChangeSetByMaterial as Z,RendererTarget as $}from"./rendererUtils.js";import{setupFeatureDefaults as ee,RenderFeature as re}from"./RenderFeature.js";import{RenderSlot as te}from"./RenderSlot.js";import{ShadowAccumulator as se}from"./ShadowAccumulator.js";import{ShadowMap as ie,SnapshotSlot as ae}from"./ShadowMap.js";import ne from"./SliceHelper.js";import{TransparencyPassType as he}from"./TransparencyPassType.js";import{EdgeView as oe}from"./edgeRendering/EdgeView.js";import{Transparency as de}from"./edgeRendering/interfaces.js";import{MergedRenderer as le}from"../materials/renderers/MergedRenderer.js";import{AlphaMode as _e}from"../shaders/CompositingTechniqueConfiguration.js";import{RendererPerformanceInfo as pe,PerformanceCategory as ue}from"../statistics/RendererPerformanceInfo.js";import{RenderState as ce}from"../../../support/RenderState.js";import{PixelFormat as me,PixelType as fe,ClearBufferBit as ge}from"../../../webgl/enums.js";let Te=class extends r{get _bindParameters(){return this._renderContext.bindParameters}updateRenderFeatures(e=null,r=!has("disable-feature:high-quality-idle")){this._renderStateFeatures=ee(r,e),this.notifyChange("_renderStateFeatures"),this._plugins.renderFeatureChanged(),this._requestRender()}isFeatureEnabled(e,r=this._state){return this._renderStateFeatures.get(r,e)??!1}setFeatureEnabled(e,r,t){this._renderStateFeatures.set(r,e,t),this.notifyChange("_renderStateFeatures"),this._requestRender()}get _highQualityTransparency(){return this._highQualityTransparencyEnabled||this.isFeatureEnabled(re.HighQualityTransparency)}get hasReflections(){return(this._pluginsHas.water||this._hasOverlayWater)&&(this._ssrEnabled||this.isFeatureEnabled(re.WaterReflection))}get hasDecorations(){return this._plugins.hasDecorations}get hasHighlights(){return this._plugins.produces(te.OPAQUE_MATERIAL,I.Highlight)||this._plugins.produces(te.DRAPED_MATERIAL,I.Highlight)}get _magnifierEnabled(){return this._bindParameters.decorations===B.ON&&this._magnifierHelper.enabled}get fullResolutionAtmosphere(){return this._stage.view.qualitySettings.highResolutionAtmosphere||this.isFeatureEnabled(re.HighResolutionAtmosphere)}constructor(e,r,t,i,a,n,h,_){super({}),this._stage=e,this._techniqueRepository=i,this._rctx=a,this._compositingHelper=n,this._magnifierHelper=h,this._requestRender=_,this._needsTransparentPass=!1,this._pluginsHas={hudElements:!1,water:!1},this._hasOverlayWater=!1,this.renderOverlay=e=>{},this._isRendering=!1,this._backgroundColor=A(0,0,0,1),this._sliceHelper=new ne,this._renderNodes=new N,this._state=ce.IDLE,this._highQualityTransparencyEnabled=!0,this._terrainTransparency=S.Opaque,this._ssrEnabled=!1,this._hasAnimations=!1,this._animationTimestep=new q,this._renderHiddenTransparentEdges=()=>{},this._pluginInput=new H,this._releaseGeometryLinearDepth=e=>e?.release(),this._geometryLinearDepthFormat=D.DEPTH16_BUFFER,this.fboCache=new O(a),this._renderStateFeatures=ee(!has("disable-feature:high-quality-idle"),e.view.qualityProfile),this._offscreen=new z(this.fboCache,this._compositingHelper),this.performanceInfo=new pe(this._rctx),this._shadowMap=new ie(this.fboCache,e.viewingMode),this._highlight=new x({view:e.view}),this._shadowHighlight=new v({view:e.view,viewingMode:e.viewingMode}),this._shadowAccumulator=new se(this.fboCache,i,e,(e=>{const r=this.shadowsEnabled;this._shadowMap.enabled=!0,this._prepare(e.camera,e.contentCamera),this._plugins.prepareRender(),this._shadowMap.enabled=r}),((e,r,t)=>{const s=this._stage.view.qualitySettings.maximumPixelRatio;e.shadowMap.start(e.camera,r,t,!0,s),this._renderShadowCascades(I.Shadow,e.shadowMap),e.shadowMap.finish(),e.camera.setGLViewport(this._rctx),this._prepare(e.camera,e.contentCamera)}),_),this._ssao=new G({view:this._stage.view}),this._renderContext=new J(this._rctx,this._offscreen,this._shadowMap,this._sliceHelper),this._plugins=new M({renderContext:this._renderContext,techniqueRepository:i,textureRepository:t,materialRepository:r,requestRender:_,controller:e,fbos:this.fboCache,isFeatureEnabled:e=>this.isFeatureEnabled(e)}),this.renderPassManager=new C,this._plugins.add(this.renderPassManager),this._smaa=new U({view:this._stage.view}),this._plugins.add(this._smaa),this._blit=new F({opacity:1,alphaMode:_e.None}),this._plugins.add(this._blit),this._plugins.add(this._ssao),this._plugins.add(this._highlight),this._plugins.add(this._shadowHighlight),this.addHandles([o((()=>this._stage.view.state.camera),(()=>_()),d),o((()=>P.EDGES_SHOW_HIDDEN_TRANSPARENT_EDGES),(e=>{this._renderHiddenTransparentEdges=e?()=>this._renderEdges(de.TRANSPARENT):()=>{},_()}),l),o((()=>this._stage.view.environment.background?.color),(e=>{const r=e?s(e):b;E(this._backgroundColor,r[0]*r[3],r[1]*r[3],r[2]*r[3],r[3]),_()}),d)])}normalizeCtorArgs(){return{}}destroy(){this._gpuTimerHandle=i(this._gpuTimerHandle),this._offscreen.dispose(),this._shadowMap.dispose(),this._highlight.dispose(),this._shadowAccumulator.dispose(),this._edgeView=a(this._edgeView),this.renderPassManager.dispose(),this._releaseFBOs(),this._disposeOffscreenBuffers(),this.fboCache.destroy(),this._plugins.destroy(),Q.prune()}_releaseFBOs(){this._bindParameters.ssr.lastFrameColor=n(this._bindParameters.ssr.lastFrameColor),this._bindParameters.multipassTerrain.linearDepth=n(this._bindParameters.multipassTerrain.linearDepth),this._bindParameters.multipassGeometry.linearDepth=n(this._bindParameters.multipassGeometry.linearDepth)}_disposeOffscreenBuffers(){this._offscreen.dispose(),this._disposeBindBuffers()}_disposeBindBuffers(){this._shadowMap.disposeOffscreenBuffers(),this._bindParameters.linearDepth=n(this._bindParameters.linearDepth),this._bindParameters.hudVisibility=n(this._bindParameters.hudVisibility)}get updating(){return this._smaa.updating||null!=this._edgeView&&this._edgeView.updating||this._shadowAccumulator.running||this._plugins.updating||!this.isCameraFinal}ensureEdgeView(){if(null==this._edgeView){const e=this._stage.view.resourceController;this._edgeView=new oe({rctx:this._rctx,renderSR:this._stage.view.renderSpatialReference,viewingMode:this._stage.viewingMode,techniqueRepository:this._techniqueRepository,setNeedsRender:()=>this._requestRender(),schedule:Oe(e)}),this.addHandles(o((()=>this._edgeView?.updating),(()=>this._requestRender()),_)),this._requestRender()}return this._edgeView}get edgeView(){return this._edgeView}get isCameraFinal(){return c(this._bindParameters.ssr.reprojectionMatrix,g)}set _reprojectionMatrix(e){t(this._bindParameters.ssr.reprojectionMatrix,e)&&this.notifyChange("isCameraFinal")}get shadowsEnabled(){return!!this._shadowMap?.enabled}setParameters(e){const{_shadowMap:r,_bindParameters:t}=this;if(void 0!==e.qualitySettings?.reflections&&this._ssrEnabled!==e.qualitySettings.reflections&&(this._ssrEnabled=e.qualitySettings.reflections,this._requestRender()),void 0!==e.shadowMap&&this._shadowMap.enabled!==e.shadowMap&&(this._shadowMap.enabled=e.shadowMap,this._requestRender()),void 0!==e.shadowMapMaxCascades&&r.maxCascades!==e.shadowMapMaxCascades&&(r.maxCascades=e.shadowMapMaxCascades,this._requestRender()),null!=e.environment){null!=e.environment.weather&&(this._bindParameters.weather=e.environment.weather,this._bindParameters.weatherVisible=!!e.weatherVisible);const r="virtual"!==e.environment.lighting.type;t.enableFillLights!==r&&(t.enableFillLights=r,this._requestRender())}void 0!==e.highQualityTransparency&&this._highQualityTransparencyEnabled!==e.highQualityTransparency&&(this._highQualityTransparencyEnabled=e.highQualityTransparency,this._requestRender()),void 0!==e.hasOverlayWater&&this._hasOverlayWater!==e.hasOverlayWater&&(this._hasOverlayWater=e.hasOverlayWater,this._requestRender()),void 0!==e.slicePlane&&this._sliceHelper.plane!==e.slicePlane&&(this._sliceHelper.plane=e.slicePlane,this._requestRender()),void 0!==e.terrainTransparency&&this._terrainTransparency!==e.terrainTransparency&&(this._terrainTransparency=e.terrainTransparency,this._requestRender()),void 0!==e.shadowCastOptions&&this._shadowAccumulator.setOptions(e.shadowCastOptions)}get hasSlicePlane(){return!!this._sliceHelper.plane}get plugins(){return this._plugins}get _hasOITSupport(){return this._rctx.driverTest.floatBufferBlend.result}get _oitEnabled(){return this._highQualityTransparency&&this._hasOITSupport}modify(e,r){this._isRendering&&console.warn("Renderer.modify called while rendering");const{adds:t,removes:s,updates:i}=e;if(0===t.length&&0===s.length&&0===i.length)return;const a=Z(e);let n=!1;a.forEach(((t,s)=>{if(r.done)return;let i=this._plugins.getMaterialRenderer(s);if(null==i&&t.adds.length>0){const e=new le({material:s});e.initializeRenderContext(this._plugins._context),i=e,this._plugins.add(i)}i&&(i.modify(t),0===i.numGeometries&&(n=!0)),t.removes.forEach((r=>e.removes.removeUnordered(r))),t.adds.forEach((r=>e.adds.removeUnordered(r))),t.updates.forEach((r=>e.updates.removeUnordered(r))),r.madeProgress()})),n&&this._plugins.removeEmptyMaterialRenderers(),this._updateHasFlags(),this._requestRender()}_updateHasFlags(){const has=this._pluginsHas;has.hudElements=this._plugins.produces(te.LINE_CALLOUTS_HUD_DEPTH)||this._plugins.produces(te.HUD_MATERIAL)||this._plugins.produces(te.LABEL_MATERIAL),has.water=this._plugins.produces(te.DRAPED_WATER,I.Normal),this._bindParameters.hasOccludees=this._plugins.hasOccludees}updateAnimation(e){const r=this._hasAnimations;return this._hasAnimations=this._plugins.updateAnimation(e)||this._hasAnimations,this._hasAnimations!==r&&(this._gpuTimerHandle=r?i(this._gpuTimerHandle):this.performanceInfo.enableGPUPerformanceInfo()),this._hasAnimations}get animationTimestep(){return this._animationTimestep.value}get animationTimeDilation(){return this._animationTimestep.timeDilation}resetAnimation(){this._animationTimestep.clear()}tick(){this.fboCache.clean()}render(e,r,t=$.Default,s=B.ON){this._isRendering=!0,this.performanceInfo.startFrame(),this.fboCache.frameStart(),this._disposeBindBuffers();const i=this._offscreen,{camera:a,contentCamera:h,mode:o,alignPixelEnabled:d}=e;this._state=o,this._bindParameters.overlay=this.renderOverlay(r),this.performanceInfo.advance(ue.OVERLAY),this._renderContext.time=r,this._bindParameters.transparencyPassType=he.NONE,this._bindParameters.alignPixelEnabled=d,this._bindParameters.decorations=s,this._bindParameters.mainColor=this._bindParameters.mainDepth=null;const l=R(this._sliceHelper.plane);s===B.OFF&&(this._sliceHelper.plane=null),a.setGLViewport(this._rctx);const _=i.initializeFrame(a,this._backgroundColor,t);this.hasReflections?this._bindParameters.ssr.lastFrameColor=_:_?.release(),this._prepare(a,h),this._plugins.prepareRender(),this.performanceInfo.advance(ue.PREPARE);const p=this._computeDepthRange(a);this._renderShadowMap(a,this._bindParameters.lighting.mainLight.direction,p),this.performanceInfo.advance(ue.SHADOW_MAP),this._ensureBindParameters(a,h);const u=this._plugins.produces(te.OPAQUE_TERRAIN)&&(this._terrainTransparency===S.Semitransparent||this._terrainTransparency===S.TransparentWithDraped),c=this._highQualityTransparency&&u;this._prepareShaders(c,this._needsTransparentPass),this._renderLinearDepthForSSAO(),this.performanceInfo.advance(ue.LINEAR_DEPTH_SSAO);let m=this._renderNormals();this.performanceInfo.advance(ue.NORMALS);let f=m?.detachDepth();this._renderSSAO(m),m&&!this._renderNodes.consumes("normals")&&(m.release(),m=null),this.performanceInfo.advance(ue.SSAO),this._renderLinearDepth(f),f=n(f),this.performanceInfo.advance(ue.LINEAR_DEPTH),this._renderShadowAccumulation(p,a,h),this.performanceInfo.advance(ue.ACCUMULATED_SHADOWS),this._ensureBindParametersSSR(r),this._renderContext.output=I.Color,i.bindFbo(),this._bindParameters.mainColor=i.colorTexture,this._bindParameters.mainDepth=i.depthTexture,this._renderOpaqueGeometry(),this._plugins.render(te.ENVIRONMENT_OPAQUE),this.performanceInfo.advance(ue.OPAQUE),this.fboCache.debugCallback&&this.fboCache.debugCallback("opaque color",this._offscreen.color.fbo),this._renderTerrainLinearDepth(c),this._setMultipassTerrain(c),this._renderEdges(de.OPAQUE),this.performanceInfo.advance(ue.OPAQUE_EDGES),i.bindFbo(),this._plugins.render(te.VOXEL),this.performanceInfo.advance(ue.VOXEL),this._renderHiddenTransparentEdges(),this._needsTransparentPass&&(this._oitEnabled?this._renderOITPass(Ee.Geometry):this._renderTransparentMaterial()),this.performanceInfo.advance(ue.TRANSPARENT);const g=this._renderGeometryLinearDepth(c);this._renderHUDVisibility(g),c||this._plugins.render(te.LINE_CALLOUTS),this.performanceInfo.advance(ue.HUD_VISIBILITY);const T=t===$.ObjectAndLayerID?this._renderObjectAndLayerIdColor():null;this.performanceInfo.advance(ue.OBJECT_AND_LAYER_ID_COLOR),this._renderEdges(de.TRANSPARENT,g),this._releaseGeometryLinearDepth(g),this.performanceInfo.advance(ue.TRANSPARENT_EDGES);const E=u?this._renderTransparentTerrain():null;E&&this._bindParameters.hudVisibility&&(c?this._renderLineCallouts(w.Occluded):i.compositeToHUDVisibility(this._bindParameters,E.colorTexture),this._renderHUD(w.Occluded,i.color),this.performanceInfo.advance(ue.HUD_OCCLUDED)),this.performanceInfo.advance(ue.TRANSPARENT_TERRAIN),this._setTerrainCulling(!1),E&&(i.compositeToFramebuffer(this._bindParameters,E.colorTexture,_e.PremultipliedAlpha,1),E.release(),c&&(this._renderEdges(de.OPAQUE),this.performanceInfo.advance(ue.OPAQUE_EDGES),this._needsTransparentPass&&(this._oitEnabled?this._renderOITPass(Ee.Geometry):this._renderTransparentMaterial()),this.performanceInfo.advance(ue.TRANSPARENT),this._renderEdges(de.TRANSPARENT),this.performanceInfo.advance(ue.TRANSPARENT_EDGES))),this._bindParameters.ssao=n(this._bindParameters.ssao),c&&this._renderLineCallouts(w.NotOccluded),this._setMultipassEnabled(!1),this._shadowAccumulator.render(this._bindParameters),i.bindFbo(),this._plugins.render(te.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.render(te.ENVIRONMENT_TRANSPARENT),this.performanceInfo.advance(ue.ENVIRONMENT),this._renderLaserlines(),this.performanceInfo.advance(ue.LASER_LINES),this._renderOccluded(),this.performanceInfo.advance(ue.OCCLUDED);const A=this._renderHighlightPrepass(),b=this._magnifierEnabled&&t===$.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"magnifier"):null,P=t!==$.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"screenshot"):null,D=this._renderComposite(b??P,this._offscreen.color,m,A)??P;return m?.release(),this.performanceInfo.advance(ue.ANTIALIASING),this._renderHUD(w.NotOccluded,D),this.performanceInfo.advance(ue.HUD),this._renderHighlights(D,A,this._bindParameters),A?.release(),this.performanceInfo.advance(ue.HIGHLIGHTS),this._magnifierEnabled&&this._magnifierHelper.render(this._rctx,this._bindParameters),D!==P&&(this._rctx.bindFramebuffer(P?.fbo),this._compositingHelper.composite(this._bindParameters,b?.colorTexture,_e.None)),t===$.Default&&b?.release(),this.onPostRender&&this.onPostRender(),this._releaseFBOs(),this._offscreen.releaseBuffers(),this._renderContext.lastFrameCamera.copyFrom(this._bindParameters.camera),this._sliceHelper.plane=l,this._isRendering=!1,this.fboCache.frameEnd(),this.performanceInfo.finishFrame(),t!==$.Default&&(this._releaseFBOs(),this._disposeOffscreenBuffers()),{screen:P,oid:T}}_prepareShaders(e,r){this._renderContext.output=I.Color,this._prepareOpaqueGeometry(),this._setMultipassTerrain(e),this._plugins.prepare(te.TRANSPARENT_TERRAIN),this._setMultipassTerrain(!1),e||this._plugins.prepare(te.LINE_CALLOUTS),r&&this._prepareTransparencySlots(),this._plugins.prepare(te.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.prepare(te.ENVIRONMENT_TRANSPARENT),this._plugins.prepare(te.LASERLINES),this._rctx.gl.flush()}_renderObjectAndLayerIdColor(){if(!has("enable-feature:objectAndLayerId-rendering"))return;const e=this._renderContext.output,r=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oid");return r.acquireDepth(D.DEPTH_STENCIL_TEXTURE),this._rctx.bindFramebuffer(r.fbo),this._offscreen.renderToFBO((()=>this._renderAllGeometry(I.ObjectAndLayerIdColor)),[0,0,0,0],!0,!0),this._rctx.bindFramebuffer(r.fbo),this._offscreen.renderToFBO((()=>{this._bindParameters.hudRenderStyle=w.NotOccluded,this._plugins.render(te.HUD_MATERIAL)}),void 0,!0,!0),this._renderContext.output=e,r}finish(e){this._hasAnimations||this._animationTimestep.clear();const r=this.performanceInfo.gpuSamplingEnabled,t=e===j.BACKGROUND;if(t||r){const e=t?this.performanceInfo.elapsedTime:0,s=r?this.performanceInfo.totalGPUTimeSampler.last:this._rctx.gl.getError(),i=Math.max(e,s);this._animationTimestep.frame(i,t)}}readDepthPixels(e,r,t){const s=this._bindParameters.linearDepth?.fbo;if(s?.colorTexture)return void s.readPixels(r[0],r[1],r[2],r[3],me.RGBA,fe.UNSIGNED_BYTE,t);const i=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"depth").acquireDepth(D.DEPTH16_BUFFER);this._rctx.bindFramebuffer(i.fbo),this._ensureBindParameters(e,e),this._bindParameters.camera.setGLViewport(this._rctx),this._rctx.setClearColor(0,0,0,0);const a=ge.COLOR_BUFFER_BIT|ge.DEPTH_BUFFER_BIT|ge.STENCIL_BUFFER_BIT;this._rctx.clearSafe(a),this._renderAllGeometry(I.Depth),i.fbo.readPixels(r[0],r[1],r[2],r[3],me.RGBA,fe.UNSIGNED_BYTE,t),i.release()}readHUDVisibility(e,r,t,s,i){this._bindParameters.hudVisibility?.fbo.readPixels(e,r,t,s,me.RGBA,fe.UNSIGNED_BYTE,i)}readAccumulatedShadow(e){return this._shadowAccumulator.readAccumulatedShadow(e[0],e[1])}_setMultipassTerrain(e){this._setMultipassEnabled(e),this._setTerrainCulling(e)}_setMultipassEnabled(e){this._bindParameters.multipassEnabled=e}_setTerrainCulling(e){this._bindParameters.multipassTerrain.cullAboveGround=e}_renderEdges(e,r){const t=this._edgeView;if(t?.shouldRender()){const{width:s,height:i,depth:a}=this._offscreen,n=this.fboCache.acquire(s,i,"edges"),h=()=>t.render(this._bindParameters,e);this._offscreen.renderToTargets(h,n,r??a,be),this._offscreen.compositeToFramebuffer(this._bindParameters,n.colorTexture,_e.Alpha,1),n.release()}}_renderShadowMap(e,r,t){const s=this._shadowMap;s.enabled&&(s.start(e,r,t,this.isFeatureEnabled(re.HighResolutionShadows),this._stage.view.qualitySettings.maximumPixelRatio),this._shadowHighlight.updateParameters(e,r),this._needsShadowHighlight?(this._renderShadowCascades(I.ShadowHighlight,this._shadowMap),s.moveSnapshot(ae.Highlight),this._renderShadowCascades(I.ShadowExcludeHighlight,this._shadowMap),s.copySnapshot(ae.ExcludeHighlight),this._renderShadowCascades(I.ShadowHighlight,this._shadowMap)):this._renderShadowCascades(I.Shadow),s.finish(),e.setGLViewport(this._rctx))}_renderShadowCascades(e,r=this._shadowMap){for(const t of r.cascades)t.camera.setGLViewport(this._rctx),this._prepare(t.camera,t.camera),this._renderAllGeometry(e)}get _needsLinearDepth(){return this._plugins.consumes(I.Depth)||this._renderNodes.consumes("linear-depth")||this.hasReflections||this._needsShadowHighlight||this._needsShadowCast}_renderLinearDepthForSSAO(){this._plugins.produces(te.SSAO)&&(this._bindParameters.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.linearDepth,"linear-depth",(()=>this._renderGeometryForSSAO(I.Depth)),[0,0,0,0],y.RGBA,D.DEPTH_STENCIL_TEXTURE),this._bindParameters.linearDepth.releaseDepth())}_renderLinearDepth(e){if(this._needsLinearDepth){if(this._plugins.produces(te.SSAO)&&e&&this._bindParameters.linearDepth)return this._bindParameters.linearDepth.attachDepth(e),this._rctx.bindFramebuffer(this._bindParameters.linearDepth.fbo),this._offscreen.renderToFBO((()=>this._renderGeometryExcludedFromSSAO(I.Depth))),void this._bindParameters.linearDepth.detachDepth();this._bindParameters.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.linearDepth,"linear-depth",(()=>this._renderAllGeometry(I.Depth)),[0,0,0,0],y.RGBA,D.DEPTH_STENCIL_TEXTURE),this._bindParameters.linearDepth.releaseDepth()}else this._bindParameters.linearDepth=n(this._bindParameters.linearDepth)}_renderTerrainLinearDepth(e){if(e){const e=this._renderContext.output;this._renderContext.output=I.Depth,this._bindParameters.multipassTerrain.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassTerrain.linearDepth,"terrain depth",(()=>this._renderTransparentTerrain()),[-1e10,-1e10,-1e10,1]),this._bindParameters.multipassTerrain.linearDepth.releaseDepth(),this._renderContext.output=e}else this._bindParameters.multipassTerrain.linearDepth=n(this._bindParameters.multipassTerrain.linearDepth)}_renderGeometryLinearDepth(e){if(!e)return void(this._bindParameters.multipassGeometry.linearDepth=n(this._bindParameters.multipassGeometry.linearDepth));const r=this._renderContext.output;return this._bindParameters.multipassGeometry.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassGeometry.linearDepth,"geometry depth",(()=>this._renderOpaqueGeometryAndTransparentMaterial(I.Depth)),[1,1,1,1],y.RGBA,this._geometryLinearDepthFormat),this._renderContext.output=r,this._bindParameters.multipassGeometry.linearDepth.detachDepth()}get _needsDepthRange(){return this._shadowMap.enabled||this._needsShadowCast}_computeDepthRange(e){if(!this._needsDepthRange)return W;const r=X(e,this._plugins.plugins,this._stage.layers);return k(r,this._plugins.queryDepthRange(e)),r.near=Math.max(e.near,r.near),r.far=Math.min(e.far,r.far),r}_renderNormals(){if(!this._renderNodes.consumes("normals")&&!this._plugins.produces(te.SSAO))return;return this._offscreen.renderToCachedFBO(null,"normals",(()=>this._renderGeometryForSSAO(I.Normal)),[0,0,0,0],y.RGBA,D.DEPTH_STENCIL_TEXTURE)}_renderSSAO(e){this._plugins.produces(te.SSAO)&&(this._pluginInput.normals=e,this._bindParameters.ssao=this._plugins.render(te.SSAO,this._pluginInput))}_renderAllGeometry(e){this._renderContext.output=e,this._plugins.prepare(te.TRANSPARENT_TERRAIN),this._renderOpaqueGeometryAndTransparentMaterial(e),this._renderTransparentTerrain()}_renderOpaqueGeometryAndTransparentMaterial(e){this._renderContext.output=e,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._plugins.prepare(te.TRANSPARENT_NO_SSAO_DEPTH),this._renderOpaqueGeometry(),this._renderTransparentMaterial()}_renderGeometryForSSAO(e){this._renderContext.output=e,this._plugins.render(te.INTEGRATED_MESH),this._plugins.render(te.OPAQUE_TERRAIN),this._plugins.render(te.OPAQUE_MATERIAL),this._plugins.render(te.TRANSPARENT_MATERIAL),this._renderTransparentTerrain()}_renderGeometryExcludedFromSSAO(e){this._renderContext.output=e,this._plugins.render(te.OPAQUE_NO_SSAO_DEPTH),this._plugins.render(te.TRANSPARENT_NO_SSAO_DEPTH)}_prepareOpaqueGeometry(){this._plugins.prepare(te.INTEGRATED_MESH),this._plugins.prepare(te.OPAQUE_TERRAIN),this._plugins.prepare(te.OPAQUE_MATERIAL),this._plugins.prepare(te.OPAQUE_NO_SSAO_DEPTH),this._plugins.prepare(te.ENVIRONMENT_OPAQUE)}_renderOpaqueGeometry(){this._plugins.render(te.INTEGRATED_MESH),this._plugins.render(te.OPAQUE_TERRAIN),this._plugins.render(te.OPAQUE_MATERIAL),this._plugins.render(te.OPAQUE_NO_SSAO_DEPTH)}_renderTransparentMaterial(){this._plugins.render(te.TRANSPARENT_MATERIAL),this._plugins.render(te.TRANSPARENT_NO_SSAO_DEPTH)}_renderTransparentTerrain(){if(!this._plugins.produces(te.TRANSPARENT_TERRAIN))return;const e=()=>this._plugins.render(te.TRANSPARENT_TERRAIN,null);if(this._renderContext.output!==I.Color)return void e();const{width:r,height:t,depth:s}=this._offscreen,i=this.fboCache.acquire(r,t,"transparent terrain");return this._offscreen.renderToTargets(e,i,s,[0,0,0,0]),i}_renderHUDVisibility(e){this._plugins.produces(te.OCCLUSION_PIXELS)?(this._bindParameters.hudVisibility=this._offscreen.renderHUDVisibility(this._bindParameters.hudVisibility,(()=>this._plugins.render(te.OCCLUSION_PIXELS)),e),this._offscreen.bindFbo()):this._bindParameters.hudVisibility=n(this._bindParameters.hudVisibility)}_renderLineCallouts(e){if(this._bindParameters.hudRenderStyle=e,e===w.Occluded){const e=()=>{this._plugins.render(te.LINE_CALLOUTS)},{width:r,height:t,color:s}=this._offscreen,i=this.fboCache.acquireDepth(D.DEPTH16_BUFFER,r,t,"line callouts");this._offscreen.renderToTargets(e,s,i,void 0,!0,!0),i.release()}else this._plugins.render(te.LINE_CALLOUTS)}_renderLaserlines(){if(this._plugins.render(te.LASERLINES),this._plugins.produces(te.LASERLINES_CONTRAST_CONTROL)){const e=this._offscreen,{width:r,height:t,depth:s}=e,i=this.fboCache.acquire(r,t,"laser lines"),a=()=>this._plugins.render(te.LASERLINES_CONTRAST_CONTROL);e.renderToTargets(a,i,s,be),e.compositeToFramebuffer(this._bindParameters,i.colorTexture,_e.PremultipliedAlpha,1),i.release()}}_renderHUD(e,r){if(this._pluginsHas.hudElements)if(this._oitEnabled){const t=this._renderOITPass(Ee.HUD,e);this._rctx.bindFramebuffer(r?.fbo),this._compositingHelper.composite(this._bindParameters,t.colorTexture,_e.PremultipliedAlpha),t.release()}else if(e===w.Occluded){const r=()=>this._renderHUDElements(e),{width:t,height:s,color:i}=this._offscreen,a=this.fboCache.acquireDepth(D.DEPTH16_BUFFER,t,s,"hud");this._offscreen.renderToTargets(r,i,a,void 0,!0,!0),a.release()}else this._rctx.bindFramebuffer(null),r?.acquireDepth(D.DEPTH16_BUFFER),this._rctx.bindFramebuffer(r?.fbo),this._renderHUDElements(e),r?.releaseDepth()}_renderHUDElements(e){this._bindParameters.hudRenderStyle=e,this._plugins.prepare(te.LINE_CALLOUTS_HUD_DEPTH),this._plugins.prepare(te.HUD_MATERIAL),this._plugins.prepare(te.LABEL_MATERIAL),this._plugins.render(te.LINE_CALLOUTS_HUD_DEPTH),this._plugins.render(te.HUD_MATERIAL),this._plugins.render(te.LABEL_MATERIAL)}get _needsShadowHighlight(){return this._shadowMap.enabled&&this._plugins.produces(te.SHADOW_HIGHLIGHT)&&this._plugins.produces(te.OPAQUE_MATERIAL,I.ShadowHighlight)}_renderHighlightPrepass(){if(!this.hasHighlights&&!this._renderNodes.consumes("highlight"))return;const e=()=>{this._renderAllGeometry(I.Highlight),this._rctx.clearSafe(ge.DEPTH_BUFFER_BIT),this._renderHUDElements(w.Both)},r=this._offscreen.renderToCachedFBO(null,"highlight",e,[0,0,0,0],y.RGBA4,D.DEPTH_STENCIL_TEXTURE);return r.releaseDepth(),r}_renderHighlights(e,r,t){this.hasHighlights&&t.decorations!==B.OFF&&(this._needsShadowHighlight&&(this._pluginInput.highlight=r,this._plugins.render(te.SHADOW_HIGHLIGHT,this._pluginInput,e)),this._plugins.produces(te.HIGHLIGHT)&&(this._pluginInput.composite=null,this._pluginInput.normals=null,this._pluginInput.highlight=r,this._plugins.render(te.HIGHLIGHT,this._pluginInput,e)))}get _needsShadowCast(){return this._shadowAccumulator.isAccumulating}_renderShadowAccumulation(e,r,t){this._needsShadowCast&&this._bindParameters.linearDepth?.colorTexture&&this._shadowAccumulator.renderAccumulation(this._bindParameters.linearDepth,e,r,t)}_prepareTransparencySlots(){this._renderContext.output=I.Alpha,this._bindParameters.transparencyPassType=he.Alpha,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._renderContext.output=I.Color,this._bindParameters.transparencyPassType=he.Color,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=he.FrontFace,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=he.NONE}_renderOITPass(e,r=w.Both){const t=e===Ee.HUD,s=t?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oit hud composite"):null,i=t?()=>this._renderHUDElements(r):()=>this._renderTransparentMaterial(),a=this._renderContext.output;this._renderContext.output=I.Alpha,this._bindParameters.transparencyPassType=he.Alpha;const n=this._offscreen.renderOITPass(i,he.Alpha,t);this._renderContext.output=I.Color,this._bindParameters.transparencyPassType=he.Color;const h=this._offscreen.renderOITPass(i,he.Color,t);this._bindParameters.transparencyPassType=he.FrontFace;const o=this._offscreen.renderOITPass(i,he.FrontFace,t);return this._offscreen.compositeTransparentOntoOpaque(this._bindParameters,h,n,o,s),s?.releaseDepth(),o.release(),h.release(),n.release(),this._bindParameters.transparencyPassType=he.NONE,this._renderContext.output=a,s}_renderOccluded(){let e=0;Re.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;r.queryRenderOccludedState(Y.OccludeAndTransparentStencil)&&(e|=Y.OccludeAndTransparentStencil,Re.push(r))}));const r=this._offscreen,t=(t,s,i,a,n)=>{if(0==(e&s))return;const{width:h,height:o,depth:d}=r,l=this.fboCache.acquire(h,o,"tmp color");r.renderToTargets(i,l,d,[0,0,0,0],a,n),r.compositeToFramebuffer(this._bindParameters,l.colorTexture,_e.PremultipliedAlpha,t),l.release()},s=(e,r)=>{this._bindParameters.slot=e,r.forAll((e=>{if(L(e)){const r=e.prepareTechnique(this._renderContext);r&&e.renderNode(this._renderContext,r)}}))};0!==Re.length&&(s(te.OCCLUDER_MATERIAL,Re),t(.5,Y.OccludeAndTransparentStencil,(()=>s(te.TRANSPARENT_OCCLUDER_MATERIAL,Re)),!1,!1)),Re.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;const t=r.queryRenderOccludedState(Y.OccludeAndTransparent),s=r.queryRenderOccludedState(Y.Transparent),i=r.queryRenderOccludedState(Y.Opaque);(t||s||i)&&(e|=t?Y.OccludeAndTransparent:s?Y.Transparent:Y.Opaque,Re.push(r))}));const i=this._plugins.renderOccludedFlags;if(e|=i,!e)return;const a=e=>{this._renderContext.renderOccludedMask=e,i>Y.Occlude&&this._plugins.render(te.OCCLUDED_TERRAIN),s(te.OPAQUE_MATERIAL,Re),s(te.TRANSPARENT_MATERIAL,Re),s(te.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL,Re),this._renderContext.renderOccludedMask=K};this._renderContext.output=I.Color,t(.5,Y.OccludeAndTransparent,(()=>a(Y.OccludeAndTransparent)),!0,V.OutlineVisualElementMask),t(.5,Y.Transparent,(()=>a(Y.Transparent)),!0,V.OutlineVisualElementMask),t(1,Y.Opaque,(()=>a(Y.Opaque)),!0,V.OutlineVisualElementMask),Re.clear()}_renderComposite(e,r,t,s){this._pluginInput.composite=r;let i=null;const a=this._renderNodes.produces("composite-color");a&&(this._pluginInput.linearDepth=this._bindParameters.linearDepth,this._pluginInput.normals=t,this._pluginInput.highlight=s,i=this._renderNodes.render(this._pluginInput,"composite-color"),this._pluginInput.composite=i);const n=this._plugins.produces(te.ANTIALIASING),h=this._plugins.render(n?te.ANTIALIASING:te.BLIT,this._pluginInput,e);return a&&i?.release(),h}_prepare(e,r){this._needsTransparentPass=this._plugins.produces(te.TRANSPARENT_MATERIAL,I.Color),this._bindParameters.camera=e,this._bindParameters.contentCamera=r}_ensureBindParameters(e,r){this._bindParameters.camera=e,this._bindParameters.contentCamera=r}_ensureBindParametersSSR(e){if(this._bindParameters.ssr.lastFrameColor){null==this._ssrEnableTime&&(this._ssrEnableTime=e),this._renderContext.lastFrameCamera.equals(this._bindParameters.camera)?this._reprojectionMatrix=g:(m(Se,this._bindParameters.camera.viewMatrix),m(Pe,this._bindParameters.camera.projectionMatrix),f(De,Se,Pe),f(De,this._renderContext.lastFrameCamera.viewMatrix,De),f(De,this._renderContext.lastFrameCamera.projectionMatrix,De),this._reprojectionMatrix=De);const r=this._stage.view.qualitySettings.fadeDuration;this._bindParameters.ssr.fadeFactor=r>0?Math.min(r,e-this._ssrEnableTime)/r:1,this._bindParameters.ssr.fadeFactor<1&&this._requestRender()}else this._reprojectionMatrix=g,this._ssrEnableTime=null}addRenderNode(e){this._renderNodes.add(e),this._requestRender()}removeRenderNode(e){this._renderNodes.remove(e),this._requestRender()}get usedMemory(){return{fbos:this.fboCache.usedMemory,plugins:this._plugins.usedMemory,edges:this.edgeView?.usedMemory??0}}get test(){const e=this;return{offscreen:this._offscreen,shadowMap:this._shadowMap,highlight:this._highlight,lighting:this._bindParameters.lighting,renderPlugins:this._plugins,shadowAccumulator:this._shadowAccumulator,weatherIsFading:this._bindParameters.cloudsFade.isFading,resetRenderStateFeatures:()=>{e._renderStateFeatures=ee(),this._plugins.renderFeatureChanged(),this._requestRender()},releaseGeometryLinearDepth(r){e._releaseGeometryLinearDepth=r??(e=>e?.release()),e._geometryLinearDepthFormat=r?D.DEPTH_STENCIL_TEXTURE:D.DEPTH16_BUFFER},getFramebufferTexture:r=>{switch(r){case Ae.Color:return e._offscreen.colorTexture;case Ae.LinearDepth:return e._bindParameters.linearDepth?.colorTexture;case Ae.ShadowMap:return e._shadowMap.depthTexture;case Ae.HudVisibility:return e._bindParameters.hudVisibility?.colorTexture}}}}};var Ee,Ae;e([p()],Te.prototype,"_plugins",void 0),e([p()],Te.prototype,"_shadowAccumulator",void 0),e([p()],Te.prototype,"_state",void 0),e([p()],Te.prototype,"_renderStateFeatures",void 0),e([p({readOnly:!0})],Te.prototype,"fullResolutionAtmosphere",null),e([p()],Te.prototype,"_smaa",void 0),e([p()],Te.prototype,"_blit",void 0),e([p({autoDestroy:!0})],Te.prototype,"_edgeView",void 0),e([p()],Te.prototype,"updating",null),e([p()],Te.prototype,"isCameraFinal",null),Te=e([u("esri.views.3d.webgl-engine.lib.Renderer")],Te),function(e){e[e.Geometry=0]="Geometry",e[e.HUD=1]="HUD"}(Ee||(Ee={})),function(e){e[e.Color=0]="Color",e[e.LinearDepth=1]="LinearDepth",e[e.ShadowMap=2]="ShadowMap",e[e.HudVisibility=3]="HudVisibility"}(Ae||(Ae={}));const be=[0,0,0,0],Re=new h,Pe=T(),Se=T(),De=T();function Oe(e){return r=>e.immediate.schedule(r)}export{Ae as FramebufferId,Te as Renderer};
5
+ import{_ as e}from"../../../../chunks/tslib.es6.js";import r from"../../../../core/Accessor.js";import{update as t}from"../../../../core/arrayUtils.js";import{unitRGBAFromColor as s}from"../../../../core/colorUtils.js";import has from"../../../../core/has.js";import{removeMaybe as i,destroyMaybe as a,releaseMaybe as n}from"../../../../core/maybe.js";import h from"../../../../core/PooledArray.js";import{watch as o,syncAndInitial as d,initial as l,sync as _}from"../../../../core/reactiveUtils.js";import{property as p}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/Logger.js";import{subclass as u}from"../../../../core/accessorSupport/decorators/subclass.js";import{equals as c,invert as m,multiply as f}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{IDENTITY as g,create as T}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{s as E}from"../../../../chunks/vec42.js";import{fromValues as A,ZEROS as b}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{a as R}from"../../../../chunks/boundedPlane.js";import{debugFlags as P}from"../../support/debugFlags.js";import{TransparencyMode as S}from"../../terrain/TerrainRenderer.js";import{DepthFormat as D,FBOCache as y,ColorFormat as O}from"../core/FBOCache.js";import{RenderPassManager as C}from"../core/renderPasses/RenderPassManager.js";import{ShaderOutput as I}from"../core/shaderLibrary/ShaderOutput.js";import{HUDRenderStyle as w}from"../core/shaderLibrary/hud/HUDRenderStyle.js";import{RenderNodes as N}from"../effects/RenderNodes.js";import{isPrepareRenderPlugin as L}from"../effects/RenderPlugin.js";import{RenderPluginInput as H}from"../effects/RenderPluginInput.js";import{RenderPluginManager as M}from"../effects/RenderPluginManager.js";import{Blit as F}from"../effects/blit/Blit.js";import{Highlight as x}from"../effects/highlight/Highlight.js";import{ShadowHighlight as v}from"../effects/highlight/ShadowHighlight.js";import{SMAA as U}from"../effects/smaa/SMAA.js";import{SSAO as G}from"../effects/ssao/SSAO.js";import{AnimationTimeStep as q}from"./AnimationTimeStep.js";import{Decorations as B,RenderRequestType as j,StencilBits as V}from"./basicInterfaces.js";import{BoundingInfo as Q}from"./BoundingInfo.js";import{zero as W,union as k}from"./depthRange.js";import{depthRangeFromScene as X}from"./depthRangeUtils.js";import{RenderOccludedFlag as Y}from"./Material.js";import{OffscreenRendering as z}from"./OffscreenRendering.js";import{RenderContext as J,defaultRenderOccludedMask as K}from"./RenderContext.js";import{splitRenderGeometryChangeSetByMaterial as Z,RendererTarget as $}from"./rendererUtils.js";import{setupFeatureDefaults as ee,RenderFeature as re}from"./RenderFeature.js";import{RenderSlot as te}from"./RenderSlot.js";import{ShadowAccumulator as se}from"./ShadowAccumulator.js";import{ShadowMap as ie,SnapshotSlot as ae}from"./ShadowMap.js";import ne from"./SliceHelper.js";import{TransparencyPassType as he}from"./TransparencyPassType.js";import{EdgeView as oe}from"./edgeRendering/EdgeView.js";import{Transparency as de}from"./edgeRendering/interfaces.js";import{MergedRenderer as le}from"../materials/renderers/MergedRenderer.js";import{AlphaMode as _e}from"../shaders/CompositingTechniqueConfiguration.js";import{RendererPerformanceInfo as pe,PerformanceCategory as ue}from"../statistics/RendererPerformanceInfo.js";import{RenderState as ce}from"../../../support/RenderState.js";import{PixelFormat as me,PixelType as fe,ClearBufferBit as ge}from"../../../webgl/enums.js";let Te=class extends r{get _bindParameters(){return this._renderContext.bindParameters}updateRenderFeatures(e=null,r=!has("disable-feature:high-quality-idle")){this._renderStateFeatures=ee(r,e),this.notifyChange("_renderStateFeatures"),this._plugins.renderFeatureChanged(),this._requestRender()}isFeatureEnabled(e,r=this._state){return this._renderStateFeatures.get(r,e)??!1}setFeatureEnabled(e,r,t){this._renderStateFeatures.set(r,e,t),this.notifyChange("_renderStateFeatures"),this._requestRender()}get _highQualityTransparency(){return this._highQualityTransparencyEnabled||this.isFeatureEnabled(re.HighQualityTransparency)}get hasReflections(){return(this._pluginsHas.water||this._hasOverlayWater)&&(this._ssrEnabled||this.isFeatureEnabled(re.WaterReflection))}get hasDecorations(){return this._plugins.hasDecorations}get hasHighlights(){return this._plugins.produces(te.OPAQUE_MATERIAL,I.Highlight)||this._plugins.produces(te.DRAPED_MATERIAL,I.Highlight)}get _magnifierEnabled(){return this._bindParameters.decorations===B.ON&&this._magnifierHelper.enabled}get fullResolutionAtmosphere(){return this._stage.view.qualitySettings.highResolutionAtmosphere||this.isFeatureEnabled(re.HighResolutionAtmosphere)}constructor(e,r,t,i,a,n,h,_){super({}),this._stage=e,this._techniqueRepository=i,this._rctx=a,this._compositingHelper=n,this._magnifierHelper=h,this._requestRender=_,this._needsTransparentPass=!1,this._pluginsHas={hudElements:!1,water:!1},this._hasOverlayWater=!1,this.renderOverlay=e=>{},this._isRendering=!1,this._backgroundColor=A(0,0,0,1),this._sliceHelper=new ne,this._nodes=new N,this._state=ce.IDLE,this._highQualityTransparencyEnabled=!0,this._terrainTransparency=S.Opaque,this._ssrEnabled=!1,this._hasAnimations=!1,this._animationTimestep=new q,this._renderHiddenTransparentEdges=()=>{},this._pluginInput=new H,this._releaseGeometryLinearDepth=e=>e?.release(),this._geometryLinearDepthFormat=D.DEPTH16_BUFFER,this.fboCache=new y(a),this._renderStateFeatures=ee(!has("disable-feature:high-quality-idle"),e.view.qualityProfile),this._offscreen=new z(this.fboCache,this._compositingHelper),this.performanceInfo=new pe(this._rctx),this._shadowMap=new ie(this.fboCache,e.viewingMode),this._highlight=new x({view:e.view}),this._shadowHighlight=new v({view:e.view,viewingMode:e.viewingMode}),this._shadowAccumulator=new se(this.fboCache,i,e,(e=>{const r=this.shadowsEnabled;this._shadowMap.enabled=!0,this._prepare(e.camera,e.contentCamera),this._plugins.prepareRender(),this._shadowMap.enabled=r}),((e,r,t)=>{const s=this._stage.view.qualitySettings.maximumPixelRatio;e.shadowMap.start(e.camera,r,t,!0,s),this._renderShadowCascades(I.Shadow,e.shadowMap),e.shadowMap.finish(),e.camera.setGLViewport(this._rctx),this._prepare(e.camera,e.contentCamera)}),_),this._ssao=new G({view:this._stage.view}),this._renderContext=new J(this._rctx,this._offscreen,this._shadowMap,this._sliceHelper),this._plugins=new M({renderContext:this._renderContext,techniqueRepository:i,textureRepository:t,materialRepository:r,requestRender:_,controller:e,fbos:this.fboCache,isFeatureEnabled:e=>this.isFeatureEnabled(e)}),this.renderPassManager=new C,this._plugins.add(this.renderPassManager),this._smaa=new U({view:this._stage.view}),this._plugins.add(this._smaa),this._blit=new F({opacity:1,alphaMode:_e.None}),this._plugins.add(this._blit),this._plugins.add(this._ssao),this._plugins.add(this._highlight),this._plugins.add(this._shadowHighlight),this.addHandles([o((()=>this._stage.view.state.camera),(()=>_()),d),o((()=>P.EDGES_SHOW_HIDDEN_TRANSPARENT_EDGES),(e=>{this._renderHiddenTransparentEdges=e?()=>this._renderEdges(de.TRANSPARENT):()=>{},_()}),l),o((()=>this._stage.view.environment.background?.color),(e=>{const r=e?s(e):b;E(this._backgroundColor,r[0]*r[3],r[1]*r[3],r[2]*r[3],r[3]),_()}),d)])}normalizeCtorArgs(){return{}}destroy(){this._gpuTimerHandle=i(this._gpuTimerHandle),this._offscreen.dispose(),this._shadowMap.dispose(),this._highlight.dispose(),this._shadowAccumulator.dispose(),this._edgeView=a(this._edgeView),this.renderPassManager.dispose(),this._releaseFBOs(),this._disposeOffscreenBuffers(),this.fboCache.destroy(),this._plugins.destroy(),Q.prune()}_releaseFBOs(){this._bindParameters.ssr.lastFrameColor=n(this._bindParameters.ssr.lastFrameColor),this._bindParameters.multipassTerrain.linearDepth=n(this._bindParameters.multipassTerrain.linearDepth),this._bindParameters.multipassGeometry.linearDepth=n(this._bindParameters.multipassGeometry.linearDepth)}_disposeOffscreenBuffers(){this._offscreen.dispose(),this._disposeBindBuffers()}_disposeBindBuffers(){this._shadowMap.disposeOffscreenBuffers(),this._bindParameters.linearDepth=n(this._bindParameters.linearDepth),this._bindParameters.hudVisibility=n(this._bindParameters.hudVisibility)}get updating(){return this._smaa.updating||null!=this._edgeView&&this._edgeView.updating||this._shadowAccumulator.running||this._plugins.updating||!this.isCameraFinal}ensureEdgeView(){if(null==this._edgeView){const e=this._stage.view.resourceController;this._edgeView=new oe({rctx:this._rctx,renderSR:this._stage.view.renderSpatialReference,viewingMode:this._stage.viewingMode,techniqueRepository:this._techniqueRepository,setNeedsRender:()=>this._requestRender(),schedule:ye(e)}),this.addHandles(o((()=>this._edgeView?.updating),(()=>this._requestRender()),_)),this._requestRender()}return this._edgeView}get edgeView(){return this._edgeView}get isCameraFinal(){return c(this._bindParameters.ssr.reprojectionMatrix,g)}set _reprojectionMatrix(e){t(this._bindParameters.ssr.reprojectionMatrix,e)&&this.notifyChange("isCameraFinal")}get shadowsEnabled(){return!!this._shadowMap?.enabled}setParameters(e){const{_shadowMap:r,_bindParameters:t}=this;if(void 0!==e.qualitySettings?.reflections&&this._ssrEnabled!==e.qualitySettings.reflections&&(this._ssrEnabled=e.qualitySettings.reflections,this._requestRender()),void 0!==e.shadowMap&&this._shadowMap.enabled!==e.shadowMap&&(this._shadowMap.enabled=e.shadowMap,this._requestRender()),void 0!==e.shadowMapMaxCascades&&r.maxCascades!==e.shadowMapMaxCascades&&(r.maxCascades=e.shadowMapMaxCascades,this._requestRender()),null!=e.environment){null!=e.environment.weather&&(this._bindParameters.weather=e.environment.weather,this._bindParameters.weatherVisible=!!e.weatherVisible);const r="virtual"!==e.environment.lighting.type;t.enableFillLights!==r&&(t.enableFillLights=r,this._requestRender())}void 0!==e.highQualityTransparency&&this._highQualityTransparencyEnabled!==e.highQualityTransparency&&(this._highQualityTransparencyEnabled=e.highQualityTransparency,this._requestRender()),void 0!==e.hasOverlayWater&&this._hasOverlayWater!==e.hasOverlayWater&&(this._hasOverlayWater=e.hasOverlayWater,this._requestRender()),void 0!==e.slicePlane&&this._sliceHelper.plane!==e.slicePlane&&(this._sliceHelper.plane=e.slicePlane,this._requestRender()),void 0!==e.terrainTransparency&&this._terrainTransparency!==e.terrainTransparency&&(this._terrainTransparency=e.terrainTransparency,this._requestRender()),void 0!==e.shadowCastOptions&&this._shadowAccumulator.setOptions(e.shadowCastOptions)}get hasSlicePlane(){return!!this._sliceHelper.plane}get plugins(){return this._plugins}get _hasOITSupport(){return this._rctx.driverTest.floatBufferBlend.result}get _oitEnabled(){return this._highQualityTransparency&&this._hasOITSupport}modify(e,r){this._isRendering&&console.warn("Renderer.modify called while rendering");const{adds:t,removes:s,updates:i}=e;if(0===t.length&&0===s.length&&0===i.length)return;const a=Z(e);let n=!1;a.forEach(((t,s)=>{if(r.done)return;let i=this._plugins.getMaterialRenderer(s);if(null==i&&t.adds.length>0){const e=new le({material:s});e.initializeRenderContext(this._plugins._context),i=e,this._plugins.add(i)}i&&(i.modify(t),0===i.numGeometries&&(n=!0)),t.removes.forEach((r=>e.removes.removeUnordered(r))),t.adds.forEach((r=>e.adds.removeUnordered(r))),t.updates.forEach((r=>e.updates.removeUnordered(r))),r.madeProgress()})),n&&this._plugins.removeEmptyMaterialRenderers(),this._updateHasFlags(),this._requestRender()}_updateHasFlags(){const has=this._pluginsHas;has.hudElements=this._plugins.produces(te.LINE_CALLOUTS_HUD_DEPTH)||this._plugins.produces(te.HUD_MATERIAL)||this._plugins.produces(te.LABEL_MATERIAL),has.water=this._plugins.produces(te.DRAPED_WATER,I.Normal),this._bindParameters.hasOccludees=this._plugins.hasOccludees}updateAnimation(e){const r=this._hasAnimations;return this._hasAnimations=this._plugins.updateAnimation(e)||this._hasAnimations,this._hasAnimations!==r&&(this._gpuTimerHandle=r?i(this._gpuTimerHandle):this.performanceInfo.enableGPUPerformanceInfo()),this._hasAnimations}get animationTimestep(){return this._animationTimestep.value}get animationTimeDilation(){return this._animationTimestep.timeDilation}resetAnimation(){this._animationTimestep.clear()}tick(){this.fboCache.clean()}render(e,r,t=$.Default,s=B.ON){this._isRendering=!0,this.performanceInfo.startFrame(),this.fboCache.frameStart(),this._disposeBindBuffers();const i=this._offscreen,{camera:a,contentCamera:h,mode:o,alignPixelEnabled:d}=e;this._state=o,this._bindParameters.overlay=this.renderOverlay(r),this.performanceInfo.advance(ue.OVERLAY),this._renderContext.time=r,this._bindParameters.transparencyPassType=he.NONE,this._bindParameters.alignPixelEnabled=d,this._bindParameters.decorations=s,this._bindParameters.mainColor=this._bindParameters.mainDepth=null;const l=R(this._sliceHelper.plane);s===B.OFF&&(this._sliceHelper.plane=null),a.setGLViewport(this._rctx);const _=i.initializeFrame(a,this._backgroundColor,t);this.hasReflections?this._bindParameters.ssr.lastFrameColor=_:_?.release(),this._prepare(a,h),this._plugins.prepareRender(),this.performanceInfo.advance(ue.PREPARE);const p=this._computeDepthRange(a);this._renderShadowMap(a,this._bindParameters.lighting.mainLight.direction,p),this.performanceInfo.advance(ue.SHADOW_MAP),this._ensureBindParameters(a,h);const u=this._plugins.produces(te.OPAQUE_TERRAIN)&&(this._terrainTransparency===S.Semitransparent||this._terrainTransparency===S.TransparentWithDraped),c=this._highQualityTransparency&&u;this._prepareShaders(c,this._needsTransparentPass),this._renderLinearDepthForSSAO(),this.performanceInfo.advance(ue.LINEAR_DEPTH_SSAO);let m=this._renderNormals();this.performanceInfo.advance(ue.NORMALS);let f=m?.detachDepth();this._renderSSAO(m),m&&!this._nodes.consumes("normals")&&(m.release(),m=null),this.performanceInfo.advance(ue.SSAO),this._renderLinearDepth(f),f=n(f),this.performanceInfo.advance(ue.LINEAR_DEPTH),this._renderShadowAccumulation(p,a,h),this.performanceInfo.advance(ue.ACCUMULATED_SHADOWS),this._ensureBindParametersSSR(r),this._renderContext.output=I.Color,i.bindFbo(),this._bindParameters.mainColor=i.colorTexture,this._bindParameters.mainDepth=i.depthTexture,this._renderOpaqueGeometry(),this._plugins.render(te.ENVIRONMENT_OPAQUE),this.performanceInfo.advance(ue.OPAQUE),this.fboCache.debugCallback&&this.fboCache.debugCallback("opaque color",this._offscreen.color.fbo),this._renderTerrainLinearDepth(c),this._setMultipassTerrain(c),this._renderEdges(de.OPAQUE),this.performanceInfo.advance(ue.OPAQUE_EDGES),i.bindFbo(),this._plugins.render(te.VOXEL),this.performanceInfo.advance(ue.VOXEL),this._renderHiddenTransparentEdges(),this._needsTransparentPass&&(this._oitEnabled?this._renderOITPass(Ee.Geometry):this._renderTransparentMaterial()),this.performanceInfo.advance(ue.TRANSPARENT);const g=this._renderGeometryLinearDepth(c);this._renderHUDVisibility(g),c||this._plugins.render(te.LINE_CALLOUTS),this.performanceInfo.advance(ue.HUD_VISIBILITY);const T=t===$.ObjectAndLayerID?this._renderObjectAndLayerIdColor():null;this.performanceInfo.advance(ue.OBJECT_AND_LAYER_ID_COLOR),this._renderEdges(de.TRANSPARENT,g),this._releaseGeometryLinearDepth(g),this.performanceInfo.advance(ue.TRANSPARENT_EDGES);const E=u?this._renderTransparentTerrain():null;E&&this._bindParameters.hudVisibility&&(c?this._renderLineCallouts(w.Occluded):i.compositeToHUDVisibility(this._bindParameters,E.colorTexture),this._renderHUD(w.Occluded,i.color),this.performanceInfo.advance(ue.HUD_OCCLUDED)),this.performanceInfo.advance(ue.TRANSPARENT_TERRAIN),this._setTerrainCulling(!1),E&&(i.compositeToFramebuffer(this._bindParameters,E.colorTexture,_e.PremultipliedAlpha,1),E.release(),c&&(this._renderEdges(de.OPAQUE),this.performanceInfo.advance(ue.OPAQUE_EDGES),this._needsTransparentPass&&(this._oitEnabled?this._renderOITPass(Ee.Geometry):this._renderTransparentMaterial()),this.performanceInfo.advance(ue.TRANSPARENT),this._renderEdges(de.TRANSPARENT),this.performanceInfo.advance(ue.TRANSPARENT_EDGES))),this._bindParameters.ssao=n(this._bindParameters.ssao),c&&this._renderLineCallouts(w.NotOccluded),this._setMultipassEnabled(!1),this._shadowAccumulator.render(this._bindParameters),i.bindFbo(),this._plugins.render(te.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.render(te.ENVIRONMENT_TRANSPARENT),this.performanceInfo.advance(ue.ENVIRONMENT),this._renderLaserlines(),this.performanceInfo.advance(ue.LASER_LINES),this._renderOccluded(),this.performanceInfo.advance(ue.OCCLUDED);const A=this._renderHighlightPrepass(),b=this._magnifierEnabled&&t===$.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"magnifier"):null,P=t!==$.Default?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"screenshot"):null,D=this._renderComposite(b??P,this._offscreen.color,m,A)??P;return m?.release(),this.performanceInfo.advance(ue.ANTIALIASING),this._renderHUD(w.NotOccluded,D),this.performanceInfo.advance(ue.HUD),this._renderHighlights(D,A,this._bindParameters),A?.release(),this.performanceInfo.advance(ue.HIGHLIGHTS),this._magnifierEnabled&&this._magnifierHelper.render(this._rctx,this._bindParameters),D!==P&&(this._rctx.bindFramebuffer(P?.fbo),this._compositingHelper.composite(this._bindParameters,b?.colorTexture,_e.None)),t===$.Default&&b?.release(),this.onPostRender&&this.onPostRender(),this._releaseFBOs(),this._offscreen.releaseBuffers(),this._renderContext.lastFrameCamera.copyFrom(this._bindParameters.camera),this._sliceHelper.plane=l,this._isRendering=!1,this.fboCache.frameEnd(),this.performanceInfo.finishFrame(),t!==$.Default&&(this._releaseFBOs(),this._disposeOffscreenBuffers()),{screen:P,oid:T}}_prepareShaders(e,r){this._renderContext.output=I.Color,this._prepareOpaqueGeometry(),this._setMultipassTerrain(e),this._plugins.prepare(te.TRANSPARENT_TERRAIN),this._setMultipassTerrain(!1),e||this._plugins.prepare(te.LINE_CALLOUTS),r&&this._prepareTransparencySlots(),this._plugins.prepare(te.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL),this._plugins.prepare(te.ENVIRONMENT_TRANSPARENT),this._plugins.prepare(te.LASERLINES),this._rctx.gl.flush()}_renderObjectAndLayerIdColor(){if(!has("enable-feature:objectAndLayerId-rendering"))return;const e=this._renderContext.output,r=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oid");return r.acquireDepth(D.DEPTH_STENCIL_TEXTURE),this._rctx.bindFramebuffer(r.fbo),this.fboCache.rctx.clearFramebuffer([0,0,0,0],!0,!0),this._renderAllGeometry(I.ObjectAndLayerIdColor),this._rctx.bindFramebuffer(r.fbo),this.fboCache.rctx.clearFramebuffer(void 0,!0,!0),this._bindParameters.hudRenderStyle=w.NotOccluded,this._plugins.render(te.HUD_MATERIAL),this._renderContext.output=e,r}finish(e){this._hasAnimations||this._animationTimestep.clear();const r=this.performanceInfo.gpuSamplingEnabled,t=e===j.BACKGROUND;if(t||r){const e=t?this.performanceInfo.elapsedTime:0,s=r?this.performanceInfo.totalGPUTimeSampler.last:this._rctx.gl.getError(),i=Math.max(e,s);this._animationTimestep.frame(i,t)}}readDepthPixels(e,r,t){const s=this._bindParameters.linearDepth?.fbo;if(s?.colorTexture)return void s.readPixels(r[0],r[1],r[2],r[3],me.RGBA,fe.UNSIGNED_BYTE,t);const i=this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"depth").acquireDepth(D.DEPTH16_BUFFER);this._rctx.bindFramebuffer(i.fbo),this._ensureBindParameters(e,e),this._bindParameters.camera.setGLViewport(this._rctx),this._rctx.setClearColor(0,0,0,0);const a=ge.COLOR_BUFFER_BIT|ge.DEPTH_BUFFER_BIT|ge.STENCIL_BUFFER_BIT;this._rctx.clearSafe(a),this._renderAllGeometry(I.Depth),i.fbo.readPixels(r[0],r[1],r[2],r[3],me.RGBA,fe.UNSIGNED_BYTE,t),i.release()}readHUDVisibility(e,r,t,s,i){this._bindParameters.hudVisibility?.fbo.readPixels(e,r,t,s,me.RGBA,fe.UNSIGNED_BYTE,i)}readAccumulatedShadow(e){return this._shadowAccumulator.readAccumulatedShadow(e[0],e[1])}_setMultipassTerrain(e){this._setMultipassEnabled(e),this._setTerrainCulling(e)}_setMultipassEnabled(e){this._bindParameters.multipassEnabled=e}_setTerrainCulling(e){this._bindParameters.multipassTerrain.cullAboveGround=e}_renderEdges(e,r){const t=this._edgeView;if(t?.shouldRender()){const{width:s,height:i,depth:a}=this._offscreen,n=this.fboCache.acquire(s,i,"edges"),h=()=>t.render(this._bindParameters,e);this._offscreen.renderToTargets(h,n,r??a,be),this._offscreen.compositeToFramebuffer(this._bindParameters,n.colorTexture,_e.Alpha,1),n.release()}}_renderShadowMap(e,r,t){const s=this._shadowMap;s.enabled&&(s.start(e,r,t,this.isFeatureEnabled(re.HighResolutionShadows),this._stage.view.qualitySettings.maximumPixelRatio),this._shadowHighlight.updateParameters(e,r),this._needsShadowHighlight?(this._renderShadowCascades(I.ShadowHighlight,this._shadowMap),s.moveSnapshot(ae.Highlight),this._renderShadowCascades(I.ShadowExcludeHighlight,this._shadowMap),s.copySnapshot(ae.ExcludeHighlight),this._renderShadowCascades(I.ShadowHighlight,this._shadowMap)):this._renderShadowCascades(I.Shadow),s.finish(),e.setGLViewport(this._rctx))}_renderShadowCascades(e,r=this._shadowMap){for(const t of r.cascades)t.camera.setGLViewport(this._rctx),this._prepare(t.camera,t.camera),this._renderAllGeometry(e)}get _needsLinearDepth(){return this._plugins.consumes(I.Depth)||this._nodes.consumes("linear-depth")||this.hasReflections||this._needsShadowHighlight||this._needsShadowCast}_renderLinearDepthForSSAO(){this._plugins.produces(te.SSAO)&&(this._bindParameters.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.linearDepth,"linear-depth",(()=>this._renderGeometryForSSAO(I.Depth)),[0,0,0,0],O.RGBA,D.DEPTH_STENCIL_TEXTURE),this._bindParameters.linearDepth.releaseDepth())}_renderLinearDepth(e){if(this._needsLinearDepth){if(this._plugins.produces(te.SSAO)&&e&&this._bindParameters.linearDepth)return this._bindParameters.linearDepth.attachDepth(e),this._rctx.bindFramebuffer(this._bindParameters.linearDepth.fbo),this._renderGeometryExcludedFromSSAO(I.Depth),void this._bindParameters.linearDepth.detachDepth();this._bindParameters.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.linearDepth,"linear-depth",(()=>this._renderAllGeometry(I.Depth)),[0,0,0,0],O.RGBA,D.DEPTH_STENCIL_TEXTURE),this._bindParameters.linearDepth.releaseDepth()}else this._bindParameters.linearDepth=n(this._bindParameters.linearDepth)}_renderTerrainLinearDepth(e){if(e){const e=this._renderContext.output;this._renderContext.output=I.Depth,this._bindParameters.multipassTerrain.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassTerrain.linearDepth,"terrain depth",(()=>this._renderTransparentTerrain()),[-1e10,-1e10,-1e10,1]),this._bindParameters.multipassTerrain.linearDepth.releaseDepth(),this._renderContext.output=e}else this._bindParameters.multipassTerrain.linearDepth=n(this._bindParameters.multipassTerrain.linearDepth)}_renderGeometryLinearDepth(e){if(!e)return void(this._bindParameters.multipassGeometry.linearDepth=n(this._bindParameters.multipassGeometry.linearDepth));const r=this._renderContext.output;return this._bindParameters.multipassGeometry.linearDepth=this._offscreen.renderToCachedFBO(this._bindParameters.multipassGeometry.linearDepth,"geometry depth",(()=>this._renderOpaqueGeometryAndTransparentMaterial(I.Depth)),[1,1,1,1],O.RGBA,this._geometryLinearDepthFormat),this._renderContext.output=r,this._bindParameters.multipassGeometry.linearDepth.detachDepth()}get _needsDepthRange(){return this._shadowMap.enabled||this._needsShadowCast}_computeDepthRange(e){if(!this._needsDepthRange)return W;const r=X(e,this._plugins.plugins,this._stage.layers);return k(r,this._plugins.queryDepthRange(e)),r.near=Math.max(e.near,r.near),r.far=Math.min(e.far,r.far),r}_renderNormals(){if(!this._nodes.consumes("normals")&&!this._plugins.produces(te.SSAO))return;return this._offscreen.renderToCachedFBO(null,"normals",(()=>this._renderGeometryForSSAO(I.Normal)),[0,0,0,0],O.RGBA,D.DEPTH_STENCIL_TEXTURE)}_renderSSAO(e){this._plugins.produces(te.SSAO)&&(this._pluginInput.normals=e,this._bindParameters.ssao=this._plugins.render(te.SSAO,this._pluginInput))}_renderAllGeometry(e){this._renderContext.output=e,this._plugins.prepare(te.TRANSPARENT_TERRAIN),this._renderOpaqueGeometryAndTransparentMaterial(e),this._renderTransparentTerrain()}_renderOpaqueGeometryAndTransparentMaterial(e){this._renderContext.output=e,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._plugins.prepare(te.TRANSPARENT_NO_SSAO_DEPTH),this._renderOpaqueGeometry(),this._renderTransparentMaterial()}_renderGeometryForSSAO(e){this._renderContext.output=e,this._plugins.render(te.INTEGRATED_MESH),this._plugins.render(te.OPAQUE_TERRAIN),this._plugins.render(te.OPAQUE_MATERIAL),this._plugins.render(te.TRANSPARENT_MATERIAL),this._renderTransparentTerrain()}_renderGeometryExcludedFromSSAO(e){this._renderContext.output=e,this._plugins.render(te.OPAQUE_NO_SSAO_DEPTH),this._plugins.render(te.TRANSPARENT_NO_SSAO_DEPTH)}_prepareOpaqueGeometry(){this._plugins.prepare(te.INTEGRATED_MESH),this._plugins.prepare(te.OPAQUE_TERRAIN),this._plugins.prepare(te.OPAQUE_MATERIAL),this._plugins.prepare(te.OPAQUE_NO_SSAO_DEPTH),this._plugins.prepare(te.ENVIRONMENT_OPAQUE)}_renderOpaqueGeometry(){this._plugins.render(te.INTEGRATED_MESH),this._plugins.render(te.OPAQUE_TERRAIN),this._plugins.render(te.OPAQUE_MATERIAL),this._plugins.render(te.OPAQUE_NO_SSAO_DEPTH)}_renderTransparentMaterial(){this._plugins.render(te.TRANSPARENT_MATERIAL),this._plugins.render(te.TRANSPARENT_NO_SSAO_DEPTH)}_renderTransparentTerrain(){if(!this._plugins.produces(te.TRANSPARENT_TERRAIN))return;const e=()=>this._plugins.render(te.TRANSPARENT_TERRAIN,null);if(this._renderContext.output!==I.Color)return void e();const{width:r,height:t,depth:s}=this._offscreen,i=this.fboCache.acquire(r,t,"transparent terrain");return this._offscreen.renderToTargets(e,i,s,[0,0,0,0]),i}_renderHUDVisibility(e){this._plugins.produces(te.OCCLUSION_PIXELS)?(this._bindParameters.hudVisibility=this._offscreen.renderHUDVisibility(this._bindParameters.hudVisibility,(()=>this._plugins.render(te.OCCLUSION_PIXELS)),e),this._offscreen.bindFbo()):this._bindParameters.hudVisibility=n(this._bindParameters.hudVisibility)}_renderLineCallouts(e){if(this._bindParameters.hudRenderStyle=e,e===w.Occluded){const e=()=>{this._plugins.render(te.LINE_CALLOUTS)},{width:r,height:t,color:s}=this._offscreen,i=this.fboCache.acquireDepth(D.DEPTH16_BUFFER,r,t,"line callouts");this._offscreen.renderToTargets(e,s,i,void 0,!0,!0),i.release()}else this._plugins.render(te.LINE_CALLOUTS)}_renderLaserlines(){if(this._plugins.render(te.LASERLINES),this._plugins.produces(te.LASERLINES_CONTRAST_CONTROL)){const e=this._offscreen,{width:r,height:t,depth:s}=e,i=this.fboCache.acquire(r,t,"laser lines"),a=()=>this._plugins.render(te.LASERLINES_CONTRAST_CONTROL);e.renderToTargets(a,i,s,be),e.compositeToFramebuffer(this._bindParameters,i.colorTexture,_e.PremultipliedAlpha,1),i.release()}}_renderHUD(e,r){if(this._pluginsHas.hudElements)if(this._oitEnabled){const t=this._renderOITPass(Ee.HUD,e);this._rctx.bindFramebuffer(r?.fbo),this._compositingHelper.composite(this._bindParameters,t.colorTexture,_e.PremultipliedAlpha),t.release()}else if(e===w.Occluded){const r=()=>this._renderHUDElements(e),{width:t,height:s,color:i}=this._offscreen,a=this.fboCache.acquireDepth(D.DEPTH16_BUFFER,t,s,"hud");this._offscreen.renderToTargets(r,i,a,void 0,!0,!0),a.release()}else this._rctx.bindFramebuffer(null),r?.acquireDepth(D.DEPTH16_BUFFER),this._rctx.bindFramebuffer(r?.fbo),this._renderHUDElements(e),r?.releaseDepth()}_renderHUDElements(e){this._bindParameters.hudRenderStyle=e,this._plugins.prepare(te.LINE_CALLOUTS_HUD_DEPTH),this._plugins.prepare(te.HUD_MATERIAL),this._plugins.prepare(te.LABEL_MATERIAL),this._plugins.render(te.LINE_CALLOUTS_HUD_DEPTH),this._plugins.render(te.HUD_MATERIAL),this._plugins.render(te.LABEL_MATERIAL)}get _needsShadowHighlight(){return this._shadowMap.enabled&&this._plugins.produces(te.SHADOW_HIGHLIGHT)&&this._plugins.produces(te.OPAQUE_MATERIAL,I.ShadowHighlight)}_renderHighlightPrepass(){if(!this.hasHighlights&&!this._nodes.consumes("highlight"))return;const e=()=>{this._renderAllGeometry(I.Highlight),this._rctx.clearSafe(ge.DEPTH_BUFFER_BIT),this._renderHUDElements(w.Both)},r=this._offscreen.renderToCachedFBO(null,"highlight",e,[0,0,0,0],O.RGBA4,D.DEPTH_STENCIL_TEXTURE);return r.releaseDepth(),r}_renderHighlights(e,r,t){this.hasHighlights&&t.decorations!==B.OFF&&(this._needsShadowHighlight&&(this._pluginInput.highlight=r,this._plugins.render(te.SHADOW_HIGHLIGHT,this._pluginInput,e)),this._plugins.produces(te.HIGHLIGHT)&&(this._pluginInput.composite=null,this._pluginInput.normals=null,this._pluginInput.highlight=r,this._plugins.render(te.HIGHLIGHT,this._pluginInput,e)))}get _needsShadowCast(){return this._shadowAccumulator.isAccumulating}_renderShadowAccumulation(e,r,t){this._needsShadowCast&&this._bindParameters.linearDepth?.colorTexture&&this._shadowAccumulator.renderAccumulation(this._bindParameters.linearDepth,e,r,t)}_prepareTransparencySlots(){this._renderContext.output=I.Alpha,this._bindParameters.transparencyPassType=he.Alpha,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._renderContext.output=I.Color,this._bindParameters.transparencyPassType=he.Color,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=he.FrontFace,this._plugins.prepare(te.TRANSPARENT_MATERIAL),this._bindParameters.transparencyPassType=he.NONE}_renderOITPass(e,r=w.Both){const t=e===Ee.HUD,s=t?this.fboCache.acquire(this._offscreen.width,this._offscreen.height,"oit hud composite"):null,i=t?()=>this._renderHUDElements(r):()=>this._renderTransparentMaterial(),a=this._renderContext.output;this._renderContext.output=I.Alpha,this._bindParameters.transparencyPassType=he.Alpha;const n=this._offscreen.renderOITPass(i,he.Alpha,t);this._renderContext.output=I.Color,this._bindParameters.transparencyPassType=he.Color;const h=this._offscreen.renderOITPass(i,he.Color,t);this._bindParameters.transparencyPassType=he.FrontFace;const o=this._offscreen.renderOITPass(i,he.FrontFace,t);return this._offscreen.compositeTransparentOntoOpaque(this._bindParameters,h,n,o,s),s?.releaseDepth(),o.release(),h.release(),n.release(),this._bindParameters.transparencyPassType=he.NONE,this._renderContext.output=a,s}_renderOccluded(){let e=0;Re.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;r.queryRenderOccludedState(Y.OccludeAndTransparentStencil)&&(e|=Y.OccludeAndTransparentStencil,Re.push(r))}));const r=this._offscreen,t=(t,s,i,a,n)=>{if(0==(e&s))return;const{width:h,height:o,depth:d}=r,l=this.fboCache.acquire(h,o,"tmp color");r.renderToTargets(i,l,d,[0,0,0,0],a,n),r.compositeToFramebuffer(this._bindParameters,l.colorTexture,_e.PremultipliedAlpha,t),l.release()},s=(e,r)=>{this._bindParameters.slot=e,r.forAll((e=>{if(L(e)){const r=e.prepareTechnique(this._renderContext);r&&e.renderNode(this._renderContext,r)}}))};0!==Re.length&&(s(te.OCCLUDER_MATERIAL,Re),t(.5,Y.OccludeAndTransparentStencil,(()=>s(te.TRANSPARENT_OCCLUDER_MATERIAL,Re)),!1,!1)),Re.clear(),this._plugins.plugins.forAll((r=>{if(!r.materialReference)return;const t=r.queryRenderOccludedState(Y.OccludeAndTransparent),s=r.queryRenderOccludedState(Y.Transparent),i=r.queryRenderOccludedState(Y.Opaque);(t||s||i)&&(e|=t?Y.OccludeAndTransparent:s?Y.Transparent:Y.Opaque,Re.push(r))}));const i=this._plugins.renderOccludedFlags;if(e|=i,!e)return;const a=e=>{this._renderContext.renderOccludedMask=e,i>Y.Occlude&&this._plugins.render(te.OCCLUDED_TERRAIN),s(te.OPAQUE_MATERIAL,Re),s(te.TRANSPARENT_MATERIAL,Re),s(te.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL,Re),this._renderContext.renderOccludedMask=K};this._renderContext.output=I.Color,t(.5,Y.OccludeAndTransparent,(()=>a(Y.OccludeAndTransparent)),!0,V.OutlineVisualElementMask),t(.5,Y.Transparent,(()=>a(Y.Transparent)),!0,V.OutlineVisualElementMask),t(1,Y.Opaque,(()=>a(Y.Opaque)),!0,V.OutlineVisualElementMask),Re.clear()}_renderComposite(e,r,t,s){this._pluginInput.composite=r;let i=null;const a=this._nodes.produces("composite-color");a&&(this._pluginInput.linearDepth=this._bindParameters.linearDepth,this._pluginInput.normals=t,this._pluginInput.highlight=s,i=this._nodes.render(this._pluginInput,"composite-color"),this._pluginInput.composite=i);const n=this._plugins.produces(te.ANTIALIASING),h=this._plugins.render(n?te.ANTIALIASING:te.BLIT,this._pluginInput,e);return a&&i?.release(),h}_prepare(e,r){this._needsTransparentPass=this._plugins.produces(te.TRANSPARENT_MATERIAL,I.Color),this._bindParameters.camera=e,this._bindParameters.contentCamera=r}_ensureBindParameters(e,r){this._bindParameters.camera=e,this._bindParameters.contentCamera=r}_ensureBindParametersSSR(e){if(this._bindParameters.ssr.lastFrameColor){null==this._ssrEnableTime&&(this._ssrEnableTime=e),this._renderContext.lastFrameCamera.equals(this._bindParameters.camera)?this._reprojectionMatrix=g:(m(Se,this._bindParameters.camera.viewMatrix),m(Pe,this._bindParameters.camera.projectionMatrix),f(De,Se,Pe),f(De,this._renderContext.lastFrameCamera.viewMatrix,De),f(De,this._renderContext.lastFrameCamera.projectionMatrix,De),this._reprojectionMatrix=De);const r=this._stage.view.qualitySettings.fadeDuration;this._bindParameters.ssr.fadeFactor=r>0?Math.min(r,e-this._ssrEnableTime)/r:1,this._bindParameters.ssr.fadeFactor<1&&this._requestRender()}else this._reprojectionMatrix=g,this._ssrEnableTime=null}addRenderNode(e){this._nodes.add(e),this._requestRender()}removeRenderNode(e){this._nodes.remove(e),this._requestRender()}get usedMemory(){return{fbos:this.fboCache.usedMemory,plugins:this._plugins.usedMemory,edges:this.edgeView?.usedMemory??0}}get test(){const e=this;return{offscreen:this._offscreen,shadowMap:this._shadowMap,highlight:this._highlight,lighting:this._bindParameters.lighting,renderPlugins:this._plugins,shadowAccumulator:this._shadowAccumulator,weatherIsFading:this._bindParameters.cloudsFade.isFading,resetRenderStateFeatures:()=>{e._renderStateFeatures=ee(),this._plugins.renderFeatureChanged(),this._requestRender()},releaseGeometryLinearDepth(r){e._releaseGeometryLinearDepth=r??(e=>e?.release()),e._geometryLinearDepthFormat=r?D.DEPTH_STENCIL_TEXTURE:D.DEPTH16_BUFFER},getFramebufferTexture:r=>{switch(r){case Ae.Color:return e._offscreen.colorTexture;case Ae.LinearDepth:return e._bindParameters.linearDepth?.colorTexture;case Ae.ShadowMap:return e._shadowMap.depthTexture;case Ae.HudVisibility:return e._bindParameters.hudVisibility?.colorTexture}}}}};var Ee,Ae;e([p()],Te.prototype,"_plugins",void 0),e([p()],Te.prototype,"_shadowAccumulator",void 0),e([p()],Te.prototype,"_state",void 0),e([p()],Te.prototype,"_renderStateFeatures",void 0),e([p({readOnly:!0})],Te.prototype,"fullResolutionAtmosphere",null),e([p()],Te.prototype,"_smaa",void 0),e([p()],Te.prototype,"_blit",void 0),e([p({autoDestroy:!0})],Te.prototype,"_edgeView",void 0),e([p()],Te.prototype,"updating",null),e([p()],Te.prototype,"isCameraFinal",null),Te=e([u("esri.views.3d.webgl-engine.lib.Renderer")],Te),function(e){e[e.Geometry=0]="Geometry",e[e.HUD=1]="HUD"}(Ee||(Ee={})),function(e){e[e.Color=0]="Color",e[e.LinearDepth=1]="LinearDepth",e[e.ShadowMap=2]="ShadowMap",e[e.HudVisibility=3]="HudVisibility"}(Ae||(Ae={}));const be=[0,0,0,0],Re=new h,Pe=T(),Se=T(),De=T();function ye(e){return r=>e.immediate.schedule(r)}export{Ae as FramebufferId,Te as Renderer};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.29/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../core/Error.js";import r from"../../core/Logger.js";import{watch as i,syncAndInitial as s,on as o}from"../../core/reactiveUtils.js";import{property as l}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as n}from"../../core/accessorSupport/decorators/subclass.js";import{combinedViewLayerTimeExtentProperty as a}from"../../layers/support/commonProperties.js";import u from"../../layers/support/FeatureEffect.js";import p from"../../layers/support/FeatureFilter.js";import{fixFields as d,unpackFieldNames as f,collectLabelingFields as m,collectElevationFields as c,collectFilterFields as h,collectFeatureReductionFields as y,collectOrderByInfos as F,collectFields as g,collectField as w,featureHasFields as E}from"../../layers/support/fieldUtils.js";import{getFloorFilterClause as b}from"../../layers/support/floorFilterUtils.js";import x from"../../rest/support/Query.js";import{loadArcade as v}from"../../support/arcadeOnDemand.js";import{getFetchPopupTemplate as I,getRequiredFields as R}from"./support/popupUtils.js";const _=_=>{let q=class extends _{constructor(...e){super(...e),this._updatingRequiredFieldsPromise=null,this.dataUpdating=!1,this.filter=null,this.hasAllFeatures=!1,this.hasAllFeaturesInView=!1,this.hasFullGeometries=!1,this.timeExtent=null,this.layer=null,this.requiredFields=[],this.view=null}initialize(){this.addHandles([i((()=>{const e=this.layer;return[e?.elevationInfo?.featureExpressionInfo,e&&"displayField"in e?e.displayField:null,e&&"timeInfo"in e&&e.timeInfo,e&&"renderer"in e&&e.renderer,e&&"labelingInfo"in e&&e.labelingInfo,e&&"floorInfo"in e&&e.floorInfo,this.filter,this.featureEffect,this.timeExtent]}),(()=>this._handleRequiredFieldsChange()),s),o((()=>this.view?.floors),"change",(()=>this._handleRequiredFieldsChange())),o((()=>{const e=this.layer;return e&&"sublayers"in e?e.sublayers:null}),"change",(()=>this._handleRequiredFieldsChange()))])}get availableFields(){if(!this.layer)return[];const{layer:e,layer:{fieldsIndex:t},requiredFields:r}=this;return"outFields"in e&&e.outFields?d(t,[...f(t,e.outFields),...r]):d(t,r)}get featureEffect(){return this.layer&&"featureEffect"in this.layer?this.layer.featureEffect:null}set featureEffect(e){this._override("featureEffect",e)}get maximumNumberOfFeatures(){return 0}set maximumNumberOfFeatures(e){r.getLogger(this).error("#maximumNumberOfFeatures=","Setting maximum number of features is not supported")}get maximumNumberOfFeaturesExceeded(){return!1}highlight(e){throw new Error("missing implementation")}createQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference},t=null!=this.filter?this.filter.createQuery(e):new x(e);if("feature"===this.layer.type){const e=b(this);null!=e&&(t.where=t.where?`(${t.where}) AND (${e})`:e)}return null!=this.timeExtent&&(t.timeExtent=null!=t.timeExtent?t.timeExtent.intersection(this.timeExtent):this.timeExtent.clone()),t}createAggregateQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference};return new x(e)}queryFeatures(e,t){throw new Error("missing implementation")}queryObjectIds(e,t){throw new Error("missing implementation")}queryFeatureCount(e,t){throw new Error("missing implementation")}queryExtent(e,t){throw new Error("missing implementation")}async fetchPopupFeaturesFromGraphics(e,t){return this._validateFetchPopupFeatures(e,t),this._fetchPopupFeatures(e,t)}_loadArcadeModules(e){return e.expressionInfos?.length||Array.isArray(e.content)&&e.content.some((e=>"expression"===e.type))?v():Promise.resolve()}_handleRequiredFieldsChange(){const e=this._updateRequiredFields();this._set("_updatingRequiredFieldsPromise",e),e.then((()=>{this._updatingRequiredFieldsPromise===e&&this._set("_updatingRequiredFieldsPromise",null)}))}async _updateRequiredFields(){if(!this.layer||!this.view)return;const e="3d"===this.view.type,{layer:t,layer:{fieldsIndex:i,objectIdField:s}}=this,o="renderer"in t&&t.renderer,l="orderBy"in t&&t.orderBy,n="featureReduction"in t?t.featureReduction:null,a=new Set,u=await Promise.allSettled([o?o.collectRequiredFields(a,i):null,m(a,t),e?c(a,t):null,null!=this.filter?h(a,t,this.filter):null,e||null==this.featureEffect?null:h(a,t,this.featureEffect.filter),!e&&n?y(a,t,n):null,!e&&l?F(a,t,l):null]);if("timeInfo"in t&&t.timeInfo&&this.timeExtent&&g(a,t.fieldsIndex,[t.timeInfo.startField,t.timeInfo.endField]),"feature"===t.type&&(t.floorInfo&&g(a,t.fieldsIndex,[t.floorInfo.floorField]),e&&null!=t.infoFor3D&&(null==t.globalIdField&&r.getLogger(this).error("globalIdField missing on 3DObjectFeatureLayer"),g(a,t.fieldsIndex,[t.globalIdField]))),"subtype-group"===t.type){w(a,i,t.subtypeField);const e=t.sublayers.map((e=>Promise.all([e.renderer?.collectRequiredFields(a,i),m(a,e)])));await Promise.allSettled(e)}for(const d of u)"rejected"===d.status&&r.getLogger(this).error(d.reason);w(a,i,s),e&&"displayField"in t&&t.displayField&&w(a,i,t.displayField);const p=Array.from(a).sort();this._set("requiredFields",p)}_validateFetchPopupFeatures(e,r){if(null!=r)for(const i of e){const e=i.layer;if("popupEnabled"in e&&!e.popupEnabled)throw new t("featurelayerview:fetchPopupFeatures","Popups are disabled",{layer:e});if(i.isAggregate){const r="featureReduction"in e?e.featureReduction:null;if(!(r&&"popupTemplate"in r&&r.popupEnabled&&r.popupTemplate))throw new t("featurelayerview:fetchPopupFeatures","Popups are disabled",{layer:e})}else if("popupTemplate"in e){if(!I(e,r))throw new t("featurelayerview:fetchPopupFeatures","Layer does not define a popup template",{layer:e})}}}_popupFeatureHasRequiredFields(e,t){return E(t,e)}async _fetchPopupFeatures(e,t){const r=new Array(e.length),i=new Map,s=await this._createPopupQuery(e.map((e=>e.layer)),t);for(let o=0;o<e.length;o++){const l=e[o];if(l.isAggregate){r[o]=l;continue}const n=l.layer;if(!("popupEnabled"in n))continue;const a=f(this.layer.fieldsIndex,s.outFields),u=I(n,t);if(null==u)continue;const p=await this._loadArcadeModules(u);p&&p.arcadeUtils.hasGeometryOperations(u)||!this._popupFeatureHasRequiredFields(l,a)?i.set(l.getObjectId(),{graphic:l,index:o}):r[o]=l}if("stream"===this.layer.type||0===i.size)return r.filter(Boolean);s.objectIds=Array.from(i.keys());try{const e=await this.layer.queryFeatures(s);for(const t of e.features){const{graphic:{geometry:e},index:s}=i.get(t.getObjectId());t.geometry||=e,r[s]=t}}catch{}return r.filter(Boolean)}async _createPopupQuery(e,t){const r=this.layer.createQuery(),i=new Set;let s=!1;const o=e??[this.layer];for(const l of o){if(!("popupEnabled"in l))continue;const e=I(l,t);if(null==e)continue;const r=await this._loadArcadeModules(e),o=r&&r.arcadeUtils.hasGeometryOperations(e);s=!("point"!==this.layer.geometryType&&!o);const n=await R(this.layer,e);for(const t of n)i.add(t)}if(r.returnGeometry=s,r.returnZ=s,r.returnM=s,r.outFields=Array.from(i),r.outSpatialReference=this.view.spatialReference,"feature"===this.layer.type){const e=b(this);null!=e&&(r.where=r.where?`(${r.where}) AND (${e})`:e)}return r}canResume(){return!!super.canResume()&&(null==this.timeExtent||!this.timeExtent.isEmpty)}getTest(){return{createPopupQuery:e=>this._createPopupQuery(void 0,e)}}get test(){return this.getTest()}};return e([l()],q.prototype,"_updatingRequiredFieldsPromise",void 0),e([l({readOnly:!0})],q.prototype,"availableFields",null),e([l({readOnly:!0})],q.prototype,"dataUpdating",void 0),e([l({type:u})],q.prototype,"featureEffect",null),e([l({type:p})],q.prototype,"filter",void 0),e([l({readOnly:!0})],q.prototype,"hasAllFeatures",void 0),e([l({readOnly:!0})],q.prototype,"hasAllFeaturesInView",void 0),e([l({readOnly:!0})],q.prototype,"hasFullGeometries",void 0),e([l(a)],q.prototype,"timeExtent",void 0),e([l()],q.prototype,"layer",void 0),e([l({type:Number})],q.prototype,"maximumNumberOfFeatures",null),e([l({readOnly:!0,type:Boolean})],q.prototype,"maximumNumberOfFeaturesExceeded",null),e([l({readOnly:!0})],q.prototype,"requiredFields",void 0),e([l()],q.prototype,"suspended",void 0),e([l()],q.prototype,"view",void 0),q=e([n("esri.views.layers.FeatureLayerView")],q),q};export{_ as default};
5
+ import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../core/Error.js";import r from"../../core/Logger.js";import{watch as i,syncAndInitial as s,on as o}from"../../core/reactiveUtils.js";import{property as n}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as l}from"../../core/accessorSupport/decorators/subclass.js";import{combinedViewLayerTimeExtentProperty as a}from"../../layers/support/commonProperties.js";import u from"../../layers/support/FeatureEffect.js";import p from"../../layers/support/FeatureFilter.js";import{fixFields as d,unpackFieldNames as f,collectLabelingFields as m,collectElevationFields as c,collectFilterFields as h,collectFeatureReductionFields as y,collectOrderByInfos as F,collectFields as g,collectField as w,featureHasFields as E}from"../../layers/support/fieldUtils.js";import{getFloorFilterClause as b}from"../../layers/support/floorFilterUtils.js";import x from"../../rest/support/Query.js";import{loadArcade as v}from"../../support/arcadeOnDemand.js";import{getFetchPopupTemplate as I,getRequiredFields as R}from"./support/popupUtils.js";const _=_=>{let q=class extends _{constructor(...e){super(...e),this._updatingRequiredFieldsPromise=null,this.dataUpdating=!1,this.filter=null,this.timeExtent=null,this.layer=null,this.requiredFields=[],this.view=null}initialize(){this.addHandles([i((()=>{const e=this.layer;return[e?.elevationInfo?.featureExpressionInfo,e&&"displayField"in e?e.displayField:null,e&&"timeInfo"in e&&e.timeInfo,e&&"renderer"in e&&e.renderer,e&&"labelingInfo"in e&&e.labelingInfo,e&&"floorInfo"in e&&e.floorInfo,this.filter,this.featureEffect,this.timeExtent]}),(()=>this._handleRequiredFieldsChange()),s),o((()=>this.view?.floors),"change",(()=>this._handleRequiredFieldsChange())),o((()=>{const e=this.layer;return e&&"sublayers"in e?e.sublayers:null}),"change",(()=>this._handleRequiredFieldsChange()))])}get availableFields(){if(!this.layer)return[];const{layer:e,layer:{fieldsIndex:t},requiredFields:r}=this;return"outFields"in e&&e.outFields?d(t,[...f(t,e.outFields),...r]):d(t,r)}get featureEffect(){return this.layer&&"featureEffect"in this.layer?this.layer.featureEffect:null}set featureEffect(e){this._override("featureEffect",e)}get maximumNumberOfFeatures(){return 0}set maximumNumberOfFeatures(e){r.getLogger(this).error("#maximumNumberOfFeatures=","Setting maximum number of features is not supported")}get maximumNumberOfFeaturesExceeded(){return!1}highlight(e){throw new Error("missing implementation")}createQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference},t=null!=this.filter?this.filter.createQuery(e):new x(e);if("feature"===this.layer.type){const e=b(this);null!=e&&(t.where=t.where?`(${t.where}) AND (${e})`:e)}return null!=this.timeExtent&&(t.timeExtent=null!=t.timeExtent?t.timeExtent.intersection(this.timeExtent):this.timeExtent.clone()),t}createAggregateQuery(){const e={outFields:["*"],returnGeometry:!0,outSpatialReference:this.view.spatialReference};return new x(e)}queryFeatures(e,t){throw new Error("missing implementation")}queryObjectIds(e,t){throw new Error("missing implementation")}queryFeatureCount(e,t){throw new Error("missing implementation")}queryExtent(e,t){throw new Error("missing implementation")}async fetchPopupFeaturesFromGraphics(e,t){return this._validateFetchPopupFeatures(e,t),this._fetchPopupFeatures(e,t)}_loadArcadeModules(e){return e.expressionInfos?.length||Array.isArray(e.content)&&e.content.some((e=>"expression"===e.type))?v():Promise.resolve()}_handleRequiredFieldsChange(){const e=this._updateRequiredFields();this._set("_updatingRequiredFieldsPromise",e),e.then((()=>{this._updatingRequiredFieldsPromise===e&&this._set("_updatingRequiredFieldsPromise",null)}))}async _updateRequiredFields(){if(!this.layer||!this.view)return;const e="3d"===this.view.type,{layer:t,layer:{fieldsIndex:i,objectIdField:s}}=this,o="renderer"in t&&t.renderer,n="orderBy"in t&&t.orderBy,l="featureReduction"in t?t.featureReduction:null,a=new Set,u=await Promise.allSettled([o?o.collectRequiredFields(a,i):null,m(a,t),e?c(a,t):null,null!=this.filter?h(a,t,this.filter):null,e||null==this.featureEffect?null:h(a,t,this.featureEffect.filter),!e&&l?y(a,t,l):null,!e&&n?F(a,t,n):null]);if("timeInfo"in t&&t.timeInfo&&this.timeExtent&&g(a,t.fieldsIndex,[t.timeInfo.startField,t.timeInfo.endField]),"feature"===t.type&&(t.floorInfo&&g(a,t.fieldsIndex,[t.floorInfo.floorField]),e&&null!=t.infoFor3D&&(null==t.globalIdField&&r.getLogger(this).error("globalIdField missing on 3DObjectFeatureLayer"),g(a,t.fieldsIndex,[t.globalIdField]))),"subtype-group"===t.type){w(a,i,t.subtypeField);const e=t.sublayers.map((e=>Promise.all([e.renderer?.collectRequiredFields(a,i),m(a,e)])));await Promise.allSettled(e)}for(const d of u)"rejected"===d.status&&r.getLogger(this).error(d.reason);w(a,i,s),e&&"displayField"in t&&t.displayField&&w(a,i,t.displayField);const p=Array.from(a).sort();this._set("requiredFields",p)}_validateFetchPopupFeatures(e,r){if(null!=r)for(const i of e){const e=i.layer;if("popupEnabled"in e&&!e.popupEnabled)throw new t("featurelayerview:fetchPopupFeatures","Popups are disabled",{layer:e});if(i.isAggregate){const r="featureReduction"in e?e.featureReduction:null;if(!(r&&"popupTemplate"in r&&r.popupEnabled&&r.popupTemplate))throw new t("featurelayerview:fetchPopupFeatures","Popups are disabled",{layer:e})}else if("popupTemplate"in e){if(!I(e,r))throw new t("featurelayerview:fetchPopupFeatures","Layer does not define a popup template",{layer:e})}}}_popupFeatureHasRequiredFields(e,t){return E(t,e)}async _fetchPopupFeatures(e,t){const r=new Array(e.length),i=new Map,s=await this._createPopupQuery(e.map((e=>e.layer)),t);for(let o=0;o<e.length;o++){const n=e[o];if(n.isAggregate){r[o]=n;continue}const l=n.layer;if(!("popupEnabled"in l))continue;const a=f(this.layer.fieldsIndex,s.outFields),u=I(l,t);if(null==u)continue;const p=await this._loadArcadeModules(u);p&&p.arcadeUtils.hasGeometryOperations(u)||!this._popupFeatureHasRequiredFields(n,a)?i.set(n.getObjectId(),{graphic:n,index:o}):r[o]=n}if("stream"===this.layer.type||0===i.size)return r.filter(Boolean);s.objectIds=Array.from(i.keys());try{const e=await this.layer.queryFeatures(s);for(const t of e.features){const{graphic:{geometry:e},index:s}=i.get(t.getObjectId());t.geometry||=e,r[s]=t}}catch{}return r.filter(Boolean)}async _createPopupQuery(e,t){const r=this.layer.createQuery(),i=new Set;let s=!1;const o=e??[this.layer];for(const n of o){if(!("popupEnabled"in n))continue;const e=I(n,t);if(null==e)continue;const r=await this._loadArcadeModules(e),o=r&&r.arcadeUtils.hasGeometryOperations(e);s=!("point"!==this.layer.geometryType&&!o);const l=await R(this.layer,e);for(const t of l)i.add(t)}if(r.returnGeometry=s,r.returnZ=s,r.returnM=s,r.outFields=Array.from(i),r.outSpatialReference=this.view.spatialReference,"feature"===this.layer.type){const e=b(this);null!=e&&(r.where=r.where?`(${r.where}) AND (${e})`:e)}return r}canResume(){return!!super.canResume()&&(null==this.timeExtent||!this.timeExtent.isEmpty)}getTest(){return{createPopupQuery:e=>this._createPopupQuery(void 0,e)}}get test(){return this.getTest()}};return e([n()],q.prototype,"_updatingRequiredFieldsPromise",void 0),e([n({readOnly:!0})],q.prototype,"availableFields",null),e([n({readOnly:!0})],q.prototype,"dataUpdating",void 0),e([n({type:u})],q.prototype,"featureEffect",null),e([n({type:p})],q.prototype,"filter",void 0),e([n(a)],q.prototype,"timeExtent",void 0),e([n()],q.prototype,"layer",void 0),e([n({type:Number})],q.prototype,"maximumNumberOfFeatures",null),e([n({readOnly:!0,type:Boolean})],q.prototype,"maximumNumberOfFeaturesExceeded",null),e([n({readOnly:!0})],q.prototype,"requiredFields",void 0),e([n()],q.prototype,"suspended",void 0),e([n()],q.prototype,"view",void 0),q=e([l("esri.views.layers.FeatureLayerView")],q),q};export{_ 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.29/esri/copyright.txt for details.
4
4
  */
5
- 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{ContextType as n}from"./contextUtils.js";import{SpecialDrawBuffers as l,ColorAttachment as h,BufferType as f,Face as o,baseTextureUnit as u,ClearBufferBit as c,FramebufferTarget as _,TextureSamplingMode as d,SyncCondition as b,ResourceType as F,ClientWaitSyncStatus as g,BlendFactor as p,BlendOperation as B,CullMode as E,CompareFunction as m,StencilOperation as R,TextureType as T,PrimitiveType as A}from"./enums.js";import{InstanceCounter as O}from"./InstanceCounter.js";import{Parameters as C}from"./Parameters.js";import{ProgramCache as x}from"./ProgramCache.js";import{StateTracker as U}from"./renderState.js";import{Texture as k}from"./Texture.js";import{getErrorString as S}from"./Util.js";import{WebGLDriverTest as y}from"./WebGLDriverTest.js";import{Capabilities as w}from"./capabilities/Capabilities.js";import N from"./capabilities/isWebGL2Context.js";let P=class{constructor(t,e){this.gl=t,this.instanceCounter=new O,this.programCache=new x(this),this._transformFeedbackRequestInfo=null,this._state=new r,this._numOfDrawCalls=0,this._numOfTriangles=0,this.type=N(t)?n.WEBGL2:n.WEBGL1,this._loadExtensions(),this.configure(e)}get gl2(){return this.type===n.WEBGL1?null:this.gl}configure(e){this._capabilities=new w(this.gl,e),this._parameters=new C(this.gl,this._capabilities,e),k.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 U({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=>{const{drawBuffers:e}=this._capabilities;if(t)e?.drawBuffers(t.buffers);else{const{drawFramebuffer:t}=this._state;null===t||0===t.colorAttachments.length?e?.drawBuffers([l.BACK]):e?.drawBuffers([h.COLOR_ATTACHMENT0])}}}),this.enforceState(),t(this._driverTest),this._driverTest=new y(this)}dispose(){t(this._driverTest),this.programCache.dispose(),this.bindVAO(null),this.unbindBuffer(f.ARRAY_BUFFER),this.unbindBuffer(f.ELEMENT_ARRAY_BUFFER),this.type===n.WEBGL2&&(this.unbindBuffer(f.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(f.PIXEL_PACK_BUFFER),this.unbindBuffer(f.PIXEL_UNPACK_BUFFER),this.unbindBuffer(f.COPY_READ_BUFFER),this.unbindBuffer(f.COPY_WRITE_BUFFER)),this._state.textureUnitMap.length=0,i()&&console.log(this.instanceCounter.resourceInformation)}get driverTest(){return this._driverTest}get contextAttributes(){return this.gl.getContextAttributes()}get parameters(){return this._parameters}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(){const t=this.capabilities.vao;t&&(t.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=o.FRONT_AND_BACK,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){this._state.stencilOperation.face===o.FRONT_AND_BACK&&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=o.FRONT_AND_BACK,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(u+t),this._state.activeTexture=t),s}clear(t){t&&this.gl.clear(t)}clearSafe(t,e=255){t&&(t&c.COLOR_BUFFER_BIT&&this.setColorMask(!0,!0,!0,!0),t&c.DEPTH_BUFFER_BIT&&this.setDepthWriteEnabled(!0),t&c.STENCIL_BUFFER_BIT&&this.setStencilWriteMask(e),this.gl.clear(t))}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+=M(t,s);const e=this._state.textureUnitMap;for(let t=0;t<e.length;t++){const s=e[t];if(null!=s&&s===this._state.drawFramebuffer?.colorTexture)throw new Error(`Detected readWrite. Texture already bound at index ${t}`)}}this.gl.drawArrays(t,e,s),a(this.gl)}drawArraysInstanced(t,e,s,i){this.gl2?.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+=M(t,e)),this.gl.drawElements(t,e,s,a),i()){const i=S(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})}}}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(_.FRAMEBUFFER,null),this._state.readFramebuffer=null,void(this._state.drawFramebuffer=null);t.initializeAndBind(_.FRAMEBUFFER),this._state.readFramebuffer=t,this._state.drawFramebuffer=t}}bindFramebufferSeparate(t,e,s=!1){const i=e===_.READ_FRAMEBUFFER,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._state.drawFramebuffer=t??null)}blitFramebuffer(t,e,s=0,i=0,a=t.width,r=t.height,n=0,l=0,h=e.width,f=e.height,o=c.COLOR_BUFFER_BIT,u=d.NEAREST){this.bindFramebufferSeparate(t,_.READ_FRAMEBUFFER),this.bindFramebufferSeparate(e,_.DRAW_FRAMEBUFFER);this.gl.blitFramebuffer(s,i,a,r,n,l,h,f,o,u)}bindBuffer(t,e){if(t)switch(e??=t.bufferType,e){case f.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,t,e,this._state.vertexBuffer);break;case f.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,t,e,this._state.indexBuffer);break;case f.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,t,e,this._state.uniformBuffer);break;case f.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,t,e,this._state.pixelPackBuffer);break;case f.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,t,e,this._state.pixelUnpackBuffer);break;case f.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,t,e,this._state.copyReadBuffer);break;case f.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(this.gl,t,e,this._state.copyWriteBuffer);break;case f.TRANSFORM_FEEDBACK_BUFFER:this._state.transformFeedbackBuffer=v(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=t===f.UNIFORM_BUFFER?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);if(null==i)return;if(i.buffer===s&&0===i.offset&&0===i.size)return;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);if(null==r)return;if(r.buffer===s&&r.offset===i&&r.size===a)return;if(i%this._parameters.uniformBufferOffsetAlignment!=0)return void console.error("Uniform buffer binding offset is not a multiple of the context offset alignment");this.gl.bindBufferRange(t,e,s.glName,i,a),r.buffer=s,r.offset=i,r.size=a}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(f.UNIFORM_BUFFER,t,e.buffer,s,a):this.bindBufferBase(f.UNIFORM_BUFFER,t,e.buffer)):this.bindBufferBase(f.UNIFORM_BUFFER,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(f.UNIFORM_BUFFER,e,null)}}unbindBuffer(t){switch(t){case f.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,null,t,this._state.vertexBuffer);break;case f.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,null,t,this._state.indexBuffer);break;case f.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,null,t,this._state.uniformBuffer);break;case f.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,null,t,this._state.pixelPackBuffer);break;case f.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,null,t,this._state.pixelUnpackBuffer);break;case f.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,null,t,this._state.copyReadBuffer);break;case f.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(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 e=this.gl;e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,t.glName)}beginTransformFeedback(t,e){if(this._transformFeedbackRequestInfo)throw new Error("Already in a transform feedback request");const s=this.gl;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 t=this.gl;t.endTransformFeedback(),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null),this._transformFeedbackRequestInfo=null}async clientWaitAsync(t=s(10)){const i=this.gl,a=i.fenceSync(b.SYNC_GPU_COMMANDS_COMPLETE,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(r===g.TIMEOUT_EXPIRED);if(this.instanceCounter.decrement(F.Sync,a),i.deleteSync(a),r===g.WAIT_FAILED)throw new Error("Client wait failed")}getBoundFramebufferObject(t=_.FRAMEBUFFER){return t===_.READ_FRAMEBUFFER?this._state.readFramebuffer:this._state.drawFramebuffer}getBoundVAO(){return this._state.vertexArrayObject}resetState(){this.useProgram(null),this.bindVAO(null),this.bindFramebuffer(null,!0),this.unbindBuffer(f.ARRAY_BUFFER),this.unbindBuffer(f.ELEMENT_ARRAY_BUFFER),this.type===n.WEBGL2&&(this.unbindBuffer(f.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(f.PIXEL_PACK_BUFFER),this.unbindBuffer(f.PIXEL_UNPACK_BUFFER),this.unbindBuffer(f.COPY_READ_BUFFER),this.unbindBuffer(f.COPY_WRITE_BUFFER));for(let t=0;t<this.parameters.maxTextureImageUnits;++t)this.bindTexture(null,t);this.setBlendingEnabled(!1),this.setBlendFunction(p.ONE,p.ZERO),this.setBlendEquation(B.ADD),this.setBlendColor(0,0,0,0),this.setFaceCullingEnabled(!1),this.setCullFace(o.BACK),this.setFrontFace(E.CCW),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(m.LESS),this.setDepthRange(0,1),this.setStencilTestEnabled(!1),this.setStencilFunction(m.ALWAYS,0,0),this.setStencilOp(R.KEEP,R.KEEP,R.KEEP),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.setViewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}enforceState(){const t=this.capabilities.vao;t&&t.bindVertexArray(null);const{gl:e,gl2:s}=this;for(let a=0;a<this.parameters.maxVertexAttributes;a++)e.disableVertexAttribArray(a);if(this._state.vertexBuffer?e.bindBuffer(this._state.vertexBuffer.bufferType,this._state.vertexBuffer.glName):e.bindBuffer(f.ARRAY_BUFFER,null),this._state.indexBuffer?e.bindBuffer(this._state.indexBuffer.bufferType,this._state.indexBuffer.glName):e.bindBuffer(f.ELEMENT_ARRAY_BUFFER,null),null!=s){this._state.uniformBuffer?s.bindBuffer(this._state.uniformBuffer.bufferType,this._state.uniformBuffer.glName):s.bindBuffer(f.UNIFORM_BUFFER,null);for(let t=0;t<this._parameters.maxUniformBufferBindings;t++){const e=this._state.uniformBufferBindingPoints[t];if(null!=e){const{buffer:i,offset:a,size:r}=e;null!==i?0===a&&0===r?s.bindBufferBase(f.UNIFORM_BUFFER,t,i.glName):s.bindBufferRange(f.UNIFORM_BUFFER,t,i.glName,a,r):s.bindBufferBase(f.UNIFORM_BUFFER,t,null)}}this._state.pixelPackBuffer?s.bindBuffer(this._state.pixelPackBuffer.bufferType,this._state.pixelPackBuffer.glName):s.bindBuffer(f.PIXEL_PACK_BUFFER,null),this._state.pixelUnpackBuffer?s.bindBuffer(this._state.pixelUnpackBuffer.bufferType,this._state.pixelUnpackBuffer.glName):s.bindBuffer(f.PIXEL_UNPACK_BUFFER,null),this._state.copyReadBuffer?s.bindBuffer(this._state.copyReadBuffer.bufferType,this._state.copyReadBuffer.glName):s.bindBuffer(f.COPY_READ_BUFFER,null),this._state.copyWriteBuffer?s.bindBuffer(this._state.copyWriteBuffer.bufferType,this._state.copyWriteBuffer.glName):s.bindBuffer(f.COPY_WRITE_BUFFER,null),s.bindFramebuffer(_.READ_FRAMEBUFFER,null),s.readBuffer(s.BACK),this._state.readFramebuffer&&(s.bindFramebuffer(_.READ_FRAMEBUFFER,this._state.readFramebuffer.glName),s.readBuffer(h.COLOR_ATTACHMENT0)),s.bindFramebuffer(_.DRAW_FRAMEBUFFER,this._state.drawFramebuffer?.glName??null)}else this._state.readFramebuffer=this._state.drawFramebuffer,e.bindFramebuffer(_.FRAMEBUFFER,this._state.drawFramebuffer?.glName??null);if(t&&this._state.vertexArrayObject){const t=this._state.vertexArrayObject;this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null),this.bindVAO(t)}e.useProgram(this._state.program?.glName??null),e.blendColor(this._state.blendColor.r,this._state.blendColor.g,this._state.blendColor.b,this._state.blendColor.a),e.bindRenderbuffer(e.RENDERBUFFER,this._state.renderbuffer?this._state.renderbuffer.glName:null),!0===this._state.blend?e.enable(this.gl.BLEND):e.disable(this.gl.BLEND),e.blendEquationSeparate(this._state.blendEquation.mode,this._state.blendEquation.modeAlpha),e.blendFuncSeparate(this._state.blendFunction.srcRGB,this._state.blendFunction.dstRGB,this._state.blendFunction.srcAlpha,this._state.blendFunction.dstAlpha),e.clearColor(this._state.clearColor.r,this._state.clearColor.g,this._state.clearColor.b,this._state.clearColor.a),e.clearDepth(this._state.clearDepth),e.clearStencil(this._state.clearStencil),e.colorMask(this._state.colorMask.r,this._state.colorMask.g,this._state.colorMask.b,this._state.colorMask.a),e.cullFace(this._state.cullFace),e.depthFunc(this._state.depthFunction),e.depthRange(this._state.depthRange.zNear,this._state.depthRange.zFar),!0===this._state.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),e.depthMask(this._state.depthWrite),e.frontFace(this._state.frontFace),e.lineWidth(1),!0===this._state.faceCulling?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),e.polygonOffset(this._state.polygonOffset[0],this._state.polygonOffset[1]),!0===this._state.polygonOffsetFill?e.enable(e.POLYGON_OFFSET_FILL):e.disable(e.POLYGON_OFFSET_FILL),e.scissor(this._state.scissorRect.x,this._state.scissorRect.y,this._state.scissorRect.width,this._state.scissorRect.height),!0===this._state.scissorTest?e.enable(e.SCISSOR_TEST):e.disable(e.SCISSOR_TEST),e.stencilFunc(this._state.stencilFunction.func,this._state.stencilFunction.ref,this._state.stencilFunction.mask),e.stencilOpSeparate(this._state.stencilOperation.face,this._state.stencilOperation.fail,this._state.stencilOperation.zFail,this._state.stencilOperation.zPass),!0===this._state.stencilTest?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),e.stencilMask(this._state.stencilWriteMask);for(let a=0;a<this.parameters.maxTextureImageUnits;a++){e.activeTexture(u+a),e.bindTexture(T.TEXTURE_2D,null),e.bindTexture(T.TEXTURE_CUBE_MAP,null),this.type===n.WEBGL2&&(e.bindTexture(T.TEXTURE_3D,null),e.bindTexture(T.TEXTURE_2D_ARRAY,null));const t=this._state.textureUnitMap[a];null!=t&&e.bindTexture(t.descriptor.target,t.glName)}e.activeTexture(u+this._state.activeTexture);const i=this._state.viewport;e.viewport(i.x,i.y,i.width,i.height),this.resetInfo()}_loadExtensions(){this.type===n.WEBGL1&&this.gl.getExtension("OES_element_index_uint"),this.gl.getExtension("KHR_parallel_shader_compile")}};function v(t,e,s,i){return e?i!==e&&t.bindBuffer(s,e.glName):t.bindBuffer(s,null),e}function M(t,e){switch(t){case A.POINTS:return 2*e;case A.TRIANGLES:return e/3;case A.TRIANGLE_STRIP:case A.TRIANGLE_FAN:return e-2;default:return 0}}export{P as RenderingContext};
5
+ 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{ContextType as n}from"./contextUtils.js";import{SpecialDrawBuffers as l,ColorAttachment as h,BufferType as f,Face as o,baseTextureUnit as u,ClearBufferBit as c,FramebufferTarget as _,TextureSamplingMode as d,SyncCondition as b,ResourceType as F,ClientWaitSyncStatus as g,BlendFactor as B,BlendOperation as p,CullMode as E,CompareFunction as m,StencilOperation as R,TextureType as T,PrimitiveType as A}from"./enums.js";import{InstanceCounter as C}from"./InstanceCounter.js";import{Parameters as O}from"./Parameters.js";import{ProgramCache as x}from"./ProgramCache.js";import{StateTracker as U}from"./renderState.js";import{Texture as k}from"./Texture.js";import{getErrorString as S}from"./Util.js";import{WebGLDriverTest as y}from"./WebGLDriverTest.js";import{Capabilities as w}from"./capabilities/Capabilities.js";import N from"./capabilities/isWebGL2Context.js";let P=class{constructor(t,e){this.gl=t,this.instanceCounter=new C,this.programCache=new x(this),this._transformFeedbackRequestInfo=null,this._state=new r,this._numOfDrawCalls=0,this._numOfTriangles=0,this.type=N(t)?n.WEBGL2:n.WEBGL1,this._loadExtensions(),this.configure(e)}get gl2(){return this.type===n.WEBGL1?null:this.gl}configure(e){this._capabilities=new w(this.gl,e),this._parameters=new O(this.gl,this._capabilities,e),k.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 U({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=>{const{drawBuffers:e}=this._capabilities;if(t)e?.drawBuffers(t.buffers);else{const{drawFramebuffer:t}=this._state;null===t||0===t.colorAttachments.length?e?.drawBuffers([l.BACK]):e?.drawBuffers([h.COLOR_ATTACHMENT0])}}}),this.enforceState(),t(this._driverTest),this._driverTest=new y(this)}dispose(){t(this._driverTest),this.programCache.dispose(),this.bindVAO(null),this.unbindBuffer(f.ARRAY_BUFFER),this.unbindBuffer(f.ELEMENT_ARRAY_BUFFER),this.type===n.WEBGL2&&(this.unbindBuffer(f.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(f.PIXEL_PACK_BUFFER),this.unbindBuffer(f.PIXEL_UNPACK_BUFFER),this.unbindBuffer(f.COPY_READ_BUFFER),this.unbindBuffer(f.COPY_WRITE_BUFFER)),this._state.textureUnitMap.length=0,i()&&console.log(this.instanceCounter.resourceInformation)}get driverTest(){return this._driverTest}get contextAttributes(){return this.gl.getContextAttributes()}get parameters(){return this._parameters}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(){const t=this.capabilities.vao;t&&(t.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=o.FRONT_AND_BACK,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){this._state.stencilOperation.face===o.FRONT_AND_BACK&&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=o.FRONT_AND_BACK,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(u+t),this._state.activeTexture=t),s}clear(t){t&&this.gl.clear(t)}clearSafe(t,e=255){t&&(t&c.COLOR_BUFFER_BIT&&this.setColorMask(!0,!0,!0,!0),t&c.DEPTH_BUFFER_BIT&&this.setDepthWriteEnabled(!0),t&c.STENCIL_BUFFER_BIT&&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|=c.COLOR_BUFFER_BIT}e&&(i|=c.DEPTH_BUFFER_BIT),!1===s?s=0:(!0===s&&(s=255),i|=c.STENCIL_BUFFER_BIT),i&&this.clearSafe(i,s)}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+=M(t,s);const e=this._state.textureUnitMap;for(let t=0;t<e.length;t++){const s=e[t];if(null!=s&&s===this._state.drawFramebuffer?.colorTexture)throw new Error(`Detected readWrite. Texture already bound at index ${t}`)}}this.gl.drawArrays(t,e,s),a(this.gl)}drawArraysInstanced(t,e,s,i){this.gl2?.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+=M(t,e)),this.gl.drawElements(t,e,s,a),i()){const i=S(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})}}}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(_.FRAMEBUFFER,null),this._state.readFramebuffer=null,void(this._state.drawFramebuffer=null);t.initializeAndBind(_.FRAMEBUFFER),this._state.readFramebuffer=t,this._state.drawFramebuffer=t}}bindFramebufferSeparate(t,e,s=!1){const i=e===_.READ_FRAMEBUFFER,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._state.drawFramebuffer=t??null)}blitFramebuffer(t,e,s=0,i=0,a=t.width,r=t.height,n=0,l=0,h=e.width,f=e.height,o=c.COLOR_BUFFER_BIT,u=d.NEAREST){this.bindFramebufferSeparate(t,_.READ_FRAMEBUFFER),this.bindFramebufferSeparate(e,_.DRAW_FRAMEBUFFER);this.gl.blitFramebuffer(s,i,a,r,n,l,h,f,o,u)}bindBuffer(t,e){if(t)switch(e??=t.bufferType,e){case f.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,t,e,this._state.vertexBuffer);break;case f.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,t,e,this._state.indexBuffer);break;case f.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,t,e,this._state.uniformBuffer);break;case f.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,t,e,this._state.pixelPackBuffer);break;case f.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,t,e,this._state.pixelUnpackBuffer);break;case f.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,t,e,this._state.copyReadBuffer);break;case f.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(this.gl,t,e,this._state.copyWriteBuffer);break;case f.TRANSFORM_FEEDBACK_BUFFER:this._state.transformFeedbackBuffer=v(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=t===f.UNIFORM_BUFFER?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);if(null==i)return;if(i.buffer===s&&0===i.offset&&0===i.size)return;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);if(null==r)return;if(r.buffer===s&&r.offset===i&&r.size===a)return;if(i%this._parameters.uniformBufferOffsetAlignment!=0)return void console.error("Uniform buffer binding offset is not a multiple of the context offset alignment");this.gl.bindBufferRange(t,e,s.glName,i,a),r.buffer=s,r.offset=i,r.size=a}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(f.UNIFORM_BUFFER,t,e.buffer,s,a):this.bindBufferBase(f.UNIFORM_BUFFER,t,e.buffer)):this.bindBufferBase(f.UNIFORM_BUFFER,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(f.UNIFORM_BUFFER,e,null)}}unbindBuffer(t){switch(t){case f.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,null,t,this._state.vertexBuffer);break;case f.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,null,t,this._state.indexBuffer);break;case f.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,null,t,this._state.uniformBuffer);break;case f.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,null,t,this._state.pixelPackBuffer);break;case f.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,null,t,this._state.pixelUnpackBuffer);break;case f.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,null,t,this._state.copyReadBuffer);break;case f.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(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 e=this.gl;e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,t.glName)}beginTransformFeedback(t,e){if(this._transformFeedbackRequestInfo)throw new Error("Already in a transform feedback request");const s=this.gl;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 t=this.gl;t.endTransformFeedback(),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null),this._transformFeedbackRequestInfo=null}async clientWaitAsync(t=s(10)){const i=this.gl,a=i.fenceSync(b.SYNC_GPU_COMMANDS_COMPLETE,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(r===g.TIMEOUT_EXPIRED);if(this.instanceCounter.decrement(F.Sync,a),i.deleteSync(a),r===g.WAIT_FAILED)throw new Error("Client wait failed")}getBoundFramebufferObject(t=_.FRAMEBUFFER){return t===_.READ_FRAMEBUFFER?this._state.readFramebuffer:this._state.drawFramebuffer}getBoundVAO(){return this._state.vertexArrayObject}resetState(){this.useProgram(null),this.bindVAO(null),this.bindFramebuffer(null,!0),this.unbindBuffer(f.ARRAY_BUFFER),this.unbindBuffer(f.ELEMENT_ARRAY_BUFFER),this.type===n.WEBGL2&&(this.unbindBuffer(f.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(f.PIXEL_PACK_BUFFER),this.unbindBuffer(f.PIXEL_UNPACK_BUFFER),this.unbindBuffer(f.COPY_READ_BUFFER),this.unbindBuffer(f.COPY_WRITE_BUFFER));for(let t=0;t<this.parameters.maxTextureImageUnits;++t)this.bindTexture(null,t);this.setBlendingEnabled(!1),this.setBlendFunction(B.ONE,B.ZERO),this.setBlendEquation(p.ADD),this.setBlendColor(0,0,0,0),this.setFaceCullingEnabled(!1),this.setCullFace(o.BACK),this.setFrontFace(E.CCW),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(m.LESS),this.setDepthRange(0,1),this.setStencilTestEnabled(!1),this.setStencilFunction(m.ALWAYS,0,0),this.setStencilOp(R.KEEP,R.KEEP,R.KEEP),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.setViewport(0,0,this.gl.canvas.width,this.gl.canvas.height)}enforceState(){const t=this.capabilities.vao;t&&t.bindVertexArray(null);const{gl:e,gl2:s}=this;for(let a=0;a<this.parameters.maxVertexAttributes;a++)e.disableVertexAttribArray(a);if(this._state.vertexBuffer?e.bindBuffer(this._state.vertexBuffer.bufferType,this._state.vertexBuffer.glName):e.bindBuffer(f.ARRAY_BUFFER,null),this._state.indexBuffer?e.bindBuffer(this._state.indexBuffer.bufferType,this._state.indexBuffer.glName):e.bindBuffer(f.ELEMENT_ARRAY_BUFFER,null),null!=s){this._state.uniformBuffer?s.bindBuffer(this._state.uniformBuffer.bufferType,this._state.uniformBuffer.glName):s.bindBuffer(f.UNIFORM_BUFFER,null);for(let t=0;t<this._parameters.maxUniformBufferBindings;t++){const e=this._state.uniformBufferBindingPoints[t];if(null!=e){const{buffer:i,offset:a,size:r}=e;null!==i?0===a&&0===r?s.bindBufferBase(f.UNIFORM_BUFFER,t,i.glName):s.bindBufferRange(f.UNIFORM_BUFFER,t,i.glName,a,r):s.bindBufferBase(f.UNIFORM_BUFFER,t,null)}}this._state.pixelPackBuffer?s.bindBuffer(this._state.pixelPackBuffer.bufferType,this._state.pixelPackBuffer.glName):s.bindBuffer(f.PIXEL_PACK_BUFFER,null),this._state.pixelUnpackBuffer?s.bindBuffer(this._state.pixelUnpackBuffer.bufferType,this._state.pixelUnpackBuffer.glName):s.bindBuffer(f.PIXEL_UNPACK_BUFFER,null),this._state.copyReadBuffer?s.bindBuffer(this._state.copyReadBuffer.bufferType,this._state.copyReadBuffer.glName):s.bindBuffer(f.COPY_READ_BUFFER,null),this._state.copyWriteBuffer?s.bindBuffer(this._state.copyWriteBuffer.bufferType,this._state.copyWriteBuffer.glName):s.bindBuffer(f.COPY_WRITE_BUFFER,null),s.bindFramebuffer(_.READ_FRAMEBUFFER,null),s.readBuffer(s.BACK),this._state.readFramebuffer&&(s.bindFramebuffer(_.READ_FRAMEBUFFER,this._state.readFramebuffer.glName),s.readBuffer(h.COLOR_ATTACHMENT0)),s.bindFramebuffer(_.DRAW_FRAMEBUFFER,this._state.drawFramebuffer?.glName??null)}else this._state.readFramebuffer=this._state.drawFramebuffer,e.bindFramebuffer(_.FRAMEBUFFER,this._state.drawFramebuffer?.glName??null);if(t&&this._state.vertexArrayObject){const t=this._state.vertexArrayObject;this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null),this.bindVAO(t)}e.useProgram(this._state.program?.glName??null),e.blendColor(this._state.blendColor.r,this._state.blendColor.g,this._state.blendColor.b,this._state.blendColor.a),e.bindRenderbuffer(e.RENDERBUFFER,this._state.renderbuffer?this._state.renderbuffer.glName:null),!0===this._state.blend?e.enable(this.gl.BLEND):e.disable(this.gl.BLEND),e.blendEquationSeparate(this._state.blendEquation.mode,this._state.blendEquation.modeAlpha),e.blendFuncSeparate(this._state.blendFunction.srcRGB,this._state.blendFunction.dstRGB,this._state.blendFunction.srcAlpha,this._state.blendFunction.dstAlpha),e.clearColor(this._state.clearColor.r,this._state.clearColor.g,this._state.clearColor.b,this._state.clearColor.a),e.clearDepth(this._state.clearDepth),e.clearStencil(this._state.clearStencil),e.colorMask(this._state.colorMask.r,this._state.colorMask.g,this._state.colorMask.b,this._state.colorMask.a),e.cullFace(this._state.cullFace),e.depthFunc(this._state.depthFunction),e.depthRange(this._state.depthRange.zNear,this._state.depthRange.zFar),!0===this._state.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),e.depthMask(this._state.depthWrite),e.frontFace(this._state.frontFace),e.lineWidth(1),!0===this._state.faceCulling?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),e.polygonOffset(this._state.polygonOffset[0],this._state.polygonOffset[1]),!0===this._state.polygonOffsetFill?e.enable(e.POLYGON_OFFSET_FILL):e.disable(e.POLYGON_OFFSET_FILL),e.scissor(this._state.scissorRect.x,this._state.scissorRect.y,this._state.scissorRect.width,this._state.scissorRect.height),!0===this._state.scissorTest?e.enable(e.SCISSOR_TEST):e.disable(e.SCISSOR_TEST),e.stencilFunc(this._state.stencilFunction.func,this._state.stencilFunction.ref,this._state.stencilFunction.mask),e.stencilOpSeparate(this._state.stencilOperation.face,this._state.stencilOperation.fail,this._state.stencilOperation.zFail,this._state.stencilOperation.zPass),!0===this._state.stencilTest?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),e.stencilMask(this._state.stencilWriteMask);for(let a=0;a<this.parameters.maxTextureImageUnits;a++){e.activeTexture(u+a),e.bindTexture(T.TEXTURE_2D,null),e.bindTexture(T.TEXTURE_CUBE_MAP,null),this.type===n.WEBGL2&&(e.bindTexture(T.TEXTURE_3D,null),e.bindTexture(T.TEXTURE_2D_ARRAY,null));const t=this._state.textureUnitMap[a];null!=t&&e.bindTexture(t.descriptor.target,t.glName)}e.activeTexture(u+this._state.activeTexture);const i=this._state.viewport;e.viewport(i.x,i.y,i.width,i.height),this.resetInfo()}_loadExtensions(){this.type===n.WEBGL1&&this.gl.getExtension("OES_element_index_uint"),this.gl.getExtension("KHR_parallel_shader_compile")}};function v(t,e,s,i){return e?i!==e&&t.bindBuffer(s,e.glName):t.bindBuffer(s,null),e}function M(t,e){switch(t){case A.POINTS:return 2*e;case A.TRIANGLES:return e/3;case A.TRIANGLE_STRIP:case A.TRIANGLE_FAN:return e-2;default:return 0}}export{P 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.29/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../core/Error.js";import{MultiOriginJSONSupport as t}from"../../core/MultiOriginJSONSupport.js";import{whenOnce as r}from"../../core/reactiveUtils.js";import{hasSameCanonicalPortal as a,urlToObject as o}from"../../core/urlUtils.js";import{updateOrigins as i}from"../../core/accessorSupport/originUtils.js";import n from"../../geometry/SpatialReference.js";import{equals as s}from"../../geometry/support/spatialReferenceUtils.js";import{webMercatorToGeographic as l}from"../../geometry/support/webMercatorUtils.js";import{isServerOrServicesAGOLUrl as p}from"../../layers/support/arcgisLayerUrl.js";import{isLayerWithFeatureLayerSource as c,isFeatureCollectionLayer as m}from"../../layers/support/layerUtils.js";import u from"../../portal/Portal.js";import f from"../../portal/PortalItem.js";import{createForItemWrite as d}from"../../portal/support/jsonContext.js";import{TypeKeyword as w,removeTypeKeyword as y,addTypeKeyword as h,hasTypeKeyword as g}from"../../portal/support/portalItemUtils.js";import{project as _}from"../../rest/geometryService/project.js";import b from"../../rest/support/ProjectParameters.js";import{hasDeveloperBasemapLayer as R,findSpatialReference as v,isDeveloperBasemapLayer as j}from"../../support/basemapUtils.js";import{saveResources as P}from"./resourceUtils.js";import{validateSaveAPIKey as W}from"./saveAPIKeyUtils.js";import{beforeSave as I,evaluateWriteErrors as S}from"./saveUtils.js";const A=["NatGeo_World_Map","Ocean_Basemap","USA_Topo_Maps","World_Imagery","World_Street_Map","World_Terrain_Base","World_Topo_Map","World_Hillshade","Canvas/World_Light_Gray_Base","Canvas/World_Light_Gray_Reference","Canvas/World_Dark_Gray_Base","Canvas/World_Dark_Gray_Reference","Ocean/World_Ocean_Base","Ocean/World_Ocean_Reference","Reference/World_Boundaries_and_Places","Reference/World_Reference_Overlay","Reference/World_Transportation"].map((e=>e.toLowerCase()));async function O(e,t,a){a??={},T(e,t),await r((()=>!t.updatingFromView)),await t.load(),await E(t),await I(t),await C(e,t);const o=t.portalItem,i=d(o,"web-map",!0),n=t.write({},i);return await Promise.all(i.resources.pendingOperations),S(i,{errorName:`${e.name}:save`},a),await V(t,o),await ue(e,t,o,n,i),await Promise.all([t.updateItemThumbnail(),P(t.resourceReferences,i,null)]),o}async function U(e,t,a,o){o??={};const i=D(e,a);await r((()=>!t.updatingFromView)),await t.load(),await E(t),await I(t),await C(e,t);const n=d(i,"web-map",!0),s=t.write({},n);await Promise.all(n.resources.pendingOperations),S(n,{errorName:`${e.name}:save`},o),await Q(t,i);const l=t.getThumbnailState();return await fe(e,t,i,s,n,o)&&(t.resourceReferences.portalItem=i),t.restoreThumbnailFromState(l),await Promise.all([t.updateItemThumbnail(),P(t.resourceReferences,n,null)]),i}function T(t,r){if(!r.portalItem)throw new e(`${t.name}:portal-item-not-set`,"Portal item to save to has not been set on the WebMap");W(r.portalItem),M(t,r.portalItem)}function M(t,r){if(r.type!==t.itemType)throw new e(`${t.name}:portal-item-wrong-type`,`Portal item needs to have type "${t.itemType}"`)}async function C(t,a){if(!a.basemap?.baseLayers.length)throw new e(`${t.name}:save`,"Map does not have a valid basemap with a base layer.");let o=null;if(await r((()=>{const e=v(a.initialViewProperties,a.basemap);return o=e.spatialReference,!e.updating})),!s(o,a.initialViewProperties.spatialReference))throw new e(`${t.name}:save`,"The spatial reference of the basemap is not compatible with the one from the map.",{expected:a.initialViewProperties.spatialReference,actual:o})}function D(e,t){let r=f.from(t);return r.id&&(r=r.clone(),r.id=null),r.type||(r.type=e.itemType),r.portal||(r.portal=u.getDefault()),W(r),M(e,r),r}function E(e){const t=[];return e.basemap&&t.push(e.basemap.load()),e.ground&&t.push(e.ground.load()),Promise.allSettled(t).then((()=>{}))}async function V(e,t){t.extent=await se(e.portalItem,e.initialViewProperties.viewpoint.targetGeometry),await X(e,t)}const G=w.JSAPI,L="CollectorDisabled",k="Collector",$="Data Editing",B="OfflineDisabled",N="Offline",x="Workforce Project",K="Workforce Worker",F="Workforce Dispatcher",H="Offline Map Areas",J="FieldMapsDisabled",q=w.DEVELOPER_BASEMAP,z="UtilityNetwork";async function Q(e,t){y(t,L),y(t,J),y(t,w.METADATA),y(t,B),y(t,H),y(t,F),y(t,x),y(t,K),await V(e,t)}async function X(e,t){h(t,G),await Y(e),re(e,t),ae(e,t),oe(e,t),ie(e,t),ne(e,t),t.typeKeywords&&(t.typeKeywords=t.typeKeywords.filter(((e,t,r)=>r.indexOf(e)===t)))}function Y(e){const t=Z(e).map((e=>e.load())).toArray();return Promise.allSettled(t).then((()=>{}))}function Z(e){return e.allLayers.concat(e.allTables)}function ee(e){return Z(e).some((e=>e.loaded&&c(e)&&e.capabilities.operations.supportsEditing&&e.editingEnabled&&("subtype-group"!==e.type||e.sublayers.some((e=>e.editingEnabled)))))}function te(e){return Z(e).filter((e=>"group"!==e.type)).every((t=>t.loaded&&ce(e,t)))}function re(e,t){g(t,L)||g(t,x)||g(t,K)||g(t,F)||!ee(e)?y(t,k):h(t,k)}function ae(e,t){ee(e)?h(t,$):y(t,$)}function oe(e,t){!g(t,B)&&te(e)?h(t,N):y(t,N)}function ie(e,t){R(e.basemap)?h(t,q):y(t,q)}function ne(e,t){e.utilityNetworks?.length?h(t,z):y(t,z)}async function se(e,t){const r=t.clone().normalize();let a;if(r.length>1)for(const o of r)a?o.width>a.width&&(a=o):a=o;else a=r[0];return le(e,a)}async function le(e,t){const r=t.spatialReference;if(r.isWGS84)return t.clone();if(r.isWebMercator)return l(t);const{getGeometryServiceURL:a}=await import("../../portal/support/geometryServiceUtils.js"),o=await a(e),i=new b;i.geometries=[t],i.outSpatialReference=n.WGS84;return(await _(o,i))[0]}function pe(e){return m(e)||"map-notes"===e.type||"route"===e.type}function ce(e,t){return c(t)&&t.capabilities.operations.supportsSync||pe(t)&&!t.portalItem||("tile"===t.type||"vector-tile"===t.type)&&(t.capabilities.operations.supportsExportTiles||me(t)||j(t))&&t.spatialReference.equals(e.initialViewProperties.spatialReference)}function me(e){return"tile"===e.type&&(p(e.url)&&A.some((t=>e.url?.toLowerCase().includes("/"+t+"/"))))}async function ue(e,t,r,a,o){await r.update({data:a}),ye(e,t,r,a,o)}async function fe(t,r,a,o,i,n){const s=r.portalItem,l={item:s,authenticated:!(!s?.id||!s.portal.user)},p=a.portal;await p.signIn();const{copyAllowed:c,itemReloaded:m}=await de(l,p);if(l.authenticated||=m,!c)throw new e(`${t.name}:save-as-copy-not-allowed`,"Owner of this map does not allow others to save a copy");const u=await we(a,l,o,n);return r.portalItem=a,ye(t,r,a,o,i),u}async function de(e,t){const{item:r,authenticated:a}=e;return r?.id&&r.typeKeywords?.includes("useOnly")?r.portal.portalHostname!==t.portalHostname?{copyAllowed:!1,itemReloaded:!1}:(a||await r.reload(),{copyAllowed:"admin"===r.itemControl||"update"===r.itemControl,itemReloaded:!0}):{copyAllowed:!0,itemReloaded:!1}}async function we(e,t,r,o){const i=e.portal,{item:n}=t,{folder:s,copyAllResources:l}=o;let p=!1;if(l&&n?.id&&a(n.portal.url,i.url)&&parseInt(n.portal.currentVersion,10)>=2023){const{total:e}=await n.fetchResources();p=!!e}if(p){const t=await n.copy({copyResources:"all",folder:s});e.id=t.id,e.portal=t.portal;const a=e.toJSON();await e.load(),e.read(a),await e.update({data:r})}else await(i.user?.addItem({item:e,folder:s,data:r}));return p}function ye(e,r,a,n,s){t.prototype.read.call(r,{version:n.version,authoringApp:n.authoringApp,authoringAppVersion:n.authoringAppVersion},{origin:e.origin,ignoreDefaults:!0,url:a.itemUrl?o(a.itemUrl):void 0}),i(s),r.resourceInfo=n}export{O as save,U as saveAs};
5
+ import e from"../../core/Error.js";import{MultiOriginJSONSupport as t}from"../../core/MultiOriginJSONSupport.js";import{whenOnce as r}from"../../core/reactiveUtils.js";import{hasSameCanonicalPortal as a,urlToObject as o}from"../../core/urlUtils.js";import{updateOrigins as i}from"../../core/accessorSupport/originUtils.js";import n from"../../geometry/SpatialReference.js";import{equals as s}from"../../geometry/support/spatialReferenceUtils.js";import{webMercatorToGeographic as l}from"../../geometry/support/webMercatorUtils.js";import{isServerOrServicesAGOLUrl as p}from"../../layers/support/arcgisLayerUrl.js";import{isLayerWithFeatureLayerSource as c,isFeatureCollectionLayer as m}from"../../layers/support/layerUtils.js";import u from"../../portal/Portal.js";import f from"../../portal/PortalItem.js";import{createForItemWrite as d}from"../../portal/support/jsonContext.js";import{TypeKeyword as w,removeTypeKeyword as y,addTypeKeyword as g,hasTypeKeyword as h}from"../../portal/support/portalItemUtils.js";import{project as _}from"../../rest/geometryService/project.js";import b from"../../rest/support/ProjectParameters.js";import{hasDeveloperBasemapLayer as v,findSpatialReference as R,isDeveloperBasemapLayer as j}from"../../support/basemapUtils.js";import{saveResources as P}from"./resourceUtils.js";import{validateSaveAPIKey as W}from"./saveAPIKeyUtils.js";import{beforeSave as I,evaluateWriteErrors as S}from"./saveUtils.js";const A=["NatGeo_World_Map","Ocean_Basemap","USA_Topo_Maps","World_Imagery","World_Street_Map","World_Terrain_Base","World_Topo_Map","World_Hillshade","Canvas/World_Light_Gray_Base","Canvas/World_Light_Gray_Reference","Canvas/World_Dark_Gray_Base","Canvas/World_Dark_Gray_Reference","Ocean/World_Ocean_Base","Ocean/World_Ocean_Reference","Reference/World_Boundaries_and_Places","Reference/World_Reference_Overlay","Reference/World_Transportation"].map((e=>e.toLowerCase()));async function O(e,t,a){a??={},T(e,t),await r((()=>!t.updatingFromView)),await t.load(),await L(t),await I(t),await D(e,t);const o=t.portalItem,i=d(o,"web-map",!0),n=t.write({},i);return await Promise.all(i.resources.pendingOperations),S(i,{errorName:`${e.name}:save`},a),await V(t,o),await fe(e,t,o,n,i),await Promise.all([t.updateItemThumbnail(),P(t.resourceReferences,i,null)]),o}async function U(e,t,a,o){o??={};const i=E(e,a);await r((()=>!t.updatingFromView)),await t.load(),C(e,t),await L(t),await I(t),await D(e,t);const n=d(i,"web-map",!0),s=t.write({},n);await Promise.all(n.resources.pendingOperations),S(n,{errorName:`${e.name}:save`},o),await X(t,i);const l=t.getThumbnailState();return await de(e,t,i,s,n,o)&&(t.resourceReferences.portalItem=i),t.restoreThumbnailFromState(l),await Promise.all([t.updateItemThumbnail(),P(t.resourceReferences,n,null)]),i}function T(t,r){if(!r.portalItem)throw new e(`${t.name}:portal-item-not-set`,"Portal item to save to has not been set on the WebMap");W(r.portalItem),M(t,r.portalItem)}function M(t,r){if(r.type!==t.itemType)throw new e(`${t.name}:portal-item-wrong-type`,`Portal item needs to have type "${t.itemType}"`)}function C(t,r){const a=r.allLayers.filter((e=>"unsupported"===e.type&&"KnowledgeGraphLayer"===e.resourceInfo?.layerType));if(a.length)throw new e(`${t.name}:save-as-invalid-configuration`,`Failed to save a copy of ${t.name} to prevent persisting invalid configuration. See 'details.layers'`,{layers:a.toArray()})}async function D(t,a){if(!a.basemap?.baseLayers.length)throw new e(`${t.name}:save`,"Map does not have a valid basemap with a base layer.");let o=null;if(await r((()=>{const e=R(a.initialViewProperties,a.basemap);return o=e.spatialReference,!e.updating})),!s(o,a.initialViewProperties.spatialReference))throw new e(`${t.name}:save`,"The spatial reference of the basemap is not compatible with the one from the map.",{expected:a.initialViewProperties.spatialReference,actual:o})}function E(e,t){let r=f.from(t);return r.id&&(r=r.clone(),r.id=null),r.type||(r.type=e.itemType),r.portal||(r.portal=u.getDefault()),W(r),M(e,r),r}function L(e){const t=[];return e.basemap&&t.push(e.basemap.load()),e.ground&&t.push(e.ground.load()),Promise.allSettled(t).then((()=>{}))}async function V(e,t){t.extent=await le(e.portalItem,e.initialViewProperties.viewpoint.targetGeometry),await Y(e,t)}const G=w.JSAPI,$="CollectorDisabled",k="Collector",B="Data Editing",N="OfflineDisabled",x="Offline",K="Workforce Project",F="Workforce Worker",H="Workforce Dispatcher",J="Offline Map Areas",q="FieldMapsDisabled",z=w.DEVELOPER_BASEMAP,Q="UtilityNetwork";async function X(e,t){y(t,$),y(t,q),y(t,w.METADATA),y(t,N),y(t,J),y(t,H),y(t,K),y(t,F),await V(e,t)}async function Y(e,t){g(t,G),await Z(e),ae(e,t),oe(e,t),ie(e,t),ne(e,t),se(e,t),t.typeKeywords&&(t.typeKeywords=t.typeKeywords.filter(((e,t,r)=>r.indexOf(e)===t)))}function Z(e){const t=ee(e).map((e=>e.load())).toArray();return Promise.allSettled(t).then((()=>{}))}function ee(e){return e.allLayers.concat(e.allTables)}function te(e){return ee(e).some((e=>e.loaded&&c(e)&&e.capabilities.operations.supportsEditing&&e.editingEnabled&&("subtype-group"!==e.type||e.sublayers.some((e=>e.editingEnabled)))))}function re(e){return ee(e).filter((e=>"group"!==e.type)).every((t=>t.loaded&&me(e,t)))}function ae(e,t){h(t,$)||h(t,K)||h(t,F)||h(t,H)||!te(e)?y(t,k):g(t,k)}function oe(e,t){te(e)?g(t,B):y(t,B)}function ie(e,t){!h(t,N)&&re(e)?g(t,x):y(t,x)}function ne(e,t){v(e.basemap)?g(t,z):y(t,z)}function se(e,t){e.utilityNetworks?.length?g(t,Q):y(t,Q)}async function le(e,t){const r=t.clone().normalize();let a;if(r.length>1)for(const o of r)a?o.width>a.width&&(a=o):a=o;else a=r[0];return pe(e,a)}async function pe(e,t){const r=t.spatialReference;if(r.isWGS84)return t.clone();if(r.isWebMercator)return l(t);const{getGeometryServiceURL:a}=await import("../../portal/support/geometryServiceUtils.js"),o=await a(e),i=new b;i.geometries=[t],i.outSpatialReference=n.WGS84;return(await _(o,i))[0]}function ce(e){return m(e)||"map-notes"===e.type||"route"===e.type}function me(e,t){return c(t)&&t.capabilities.operations.supportsSync||ce(t)&&!t.portalItem||("tile"===t.type||"vector-tile"===t.type)&&(t.capabilities.operations.supportsExportTiles||ue(t)||j(t))&&t.spatialReference.equals(e.initialViewProperties.spatialReference)}function ue(e){return"tile"===e.type&&(p(e.url)&&A.some((t=>e.url?.toLowerCase().includes("/"+t+"/"))))}async function fe(e,t,r,a,o){await r.update({data:a}),ge(e,t,r,a,o)}async function de(t,r,a,o,i,n){const s=r.portalItem,l={item:s,authenticated:!(!s?.id||!s.portal.user)},p=a.portal;await p.signIn();const{copyAllowed:c,itemReloaded:m}=await we(l,p);if(l.authenticated||=m,!c)throw new e(`${t.name}:save-as-copy-not-allowed`,"Owner of this map does not allow others to save a copy");const u=await ye(a,l,o,n);return r.portalItem=a,ge(t,r,a,o,i),u}async function we(e,t){const{item:r,authenticated:a}=e;return r?.id&&r.typeKeywords?.includes("useOnly")?r.portal.portalHostname!==t.portalHostname?{copyAllowed:!1,itemReloaded:!1}:(a||await r.reload(),{copyAllowed:"admin"===r.itemControl||"update"===r.itemControl,itemReloaded:!0}):{copyAllowed:!0,itemReloaded:!1}}async function ye(e,t,r,o){const i=e.portal,{item:n}=t,{folder:s,copyAllResources:l}=o;let p=!1;if(l&&n?.id&&a(n.portal.url,i.url)&&parseInt(n.portal.currentVersion,10)>=2023){const{total:e}=await n.fetchResources();p=!!e}if(p){const t=await n.copy({copyResources:"all",folder:s});e.id=t.id,e.portal=t.portal;const a=e.toJSON();await e.load(),e.read(a),await e.update({data:r})}else await(i.user?.addItem({item:e,folder:s,data:r}));return p}function ge(e,r,a,n,s){t.prototype.read.call(r,{version:n.version,authoringApp:n.authoringApp,authoringAppVersion:n.authoringAppVersion},{origin:e.origin,ignoreDefaults:!0,url:a.itemUrl?o(a.itemUrl):void 0}),i(s),r.resourceInfo=n}export{O as save,U as saveAs};