@arcgis/core 4.26.0-next.20230112 → 4.26.0-next.20230113
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.
- package/assets/esri/core/workers/RemoteClient.js +1 -1
- package/assets/esri/core/workers/chunks/{4abb5627d06d329d2c0d.js → 028f9a133104e78e60d2.js} +1 -1
- package/assets/esri/core/workers/chunks/033e6ae5da6afebd993c.js +1 -0
- package/assets/esri/core/workers/chunks/{c9cc3d601f4a08162b69.js → 05ab092987251d4a1242.js} +1 -1
- package/assets/esri/core/workers/chunks/{6e6c8364baaeca09b501.js → 27ba1889fe9f1812389a.js} +21 -21
- package/assets/esri/core/workers/chunks/{e11e581b626a56adf6c6.js → 3b6748f414437cc6cfde.js} +1 -1
- package/assets/esri/core/workers/chunks/64f137358100a1c818f0.js +1 -0
- package/assets/esri/themes/base/widgets/_Editor.scss +1 -11
- package/assets/esri/themes/base/widgets/_ItemList.scss +0 -13
- package/assets/esri/themes/dark/main.css +1 -1
- package/assets/esri/themes/light/main.css +1 -1
- package/assets/esri/themes/light/view.css +1 -1
- package/chunks/ComponentShader.glsl.js +1 -1
- package/chunks/Path.glsl.js +1 -1
- package/chunks/Terrain.glsl.js +1 -1
- package/interfaces.d.ts +1398 -1313
- package/layers/VoxelWasmPerSceneView.js +1 -1
- package/layers/mixins/ArcGISImageService.js +1 -1
- package/package.json +1 -1
- package/rest/imageService.js +1 -1
- package/rest/support/BaseImageMeasureResult.d.ts +4 -0
- package/rest/support/ImageAreaParameters.d.ts +4 -0
- package/rest/support/{ImageMeasureAreaAndPerimeterParameters.js → ImageAreaParameters.js} +1 -1
- package/rest/support/ImageAreaResult.d.ts +4 -0
- package/rest/support/{ImageMeasureAreaAndPerimeterResult.js → ImageAreaResult.js} +1 -1
- package/rest/support/ImageDistanceParameters.d.ts +4 -0
- package/rest/support/{ImageMeasureDistanceAndAngleParameters.js → ImageDistanceParameters.js} +1 -1
- package/rest/support/ImageDistanceResult.d.ts +4 -0
- package/rest/support/ImageDistanceResult.js +5 -0
- package/rest/support/ImageHeightParameters.d.ts +4 -0
- package/rest/support/{ImageMeasureHeightParameters.js → ImageHeightParameters.js} +1 -1
- package/rest/support/ImageHeightResult.d.ts +4 -0
- package/rest/support/{ImageMeasureHeightResult.js → ImageHeightResult.js} +1 -1
- package/rest/support/ImagePointParameters.d.ts +4 -0
- package/rest/support/{ImageMeasurePointParameters.js → ImagePointParameters.js} +1 -1
- package/rest/support/ImagePointResult.d.ts +4 -0
- package/rest/support/{ImageMeasurePointResult.js → ImagePointResult.js} +1 -1
- package/support/revision.js +1 -1
- package/views/2d/engine/webgl/Overlay.js +1 -1
- package/views/3d/environment/EnvironmentRenderer.js +1 -1
- package/views/3d/layers/VectorTileLayerView3D.js +1 -1
- package/views/3d/layers/graphics/Graphics3DCore.js +1 -1
- package/views/3d/layers/graphics/Graphics3DIconSymbolLayer.js +1 -1
- package/views/3d/layers/graphics/Graphics3DTextSymbolLayer.js +1 -1
- package/views/3d/layers/graphics/Labeler.js +1 -1
- package/views/3d/state/ViewState.js +1 -1
- package/views/3d/state/ViewStateManager.js +1 -1
- package/views/3d/terrain/Overlay.js +1 -1
- package/views/3d/terrain/OverlayManager.js +1 -1
- package/views/3d/terrain/TerrainRenderer.js +1 -1
- package/views/3d/terrain/TerrainSurface.js +1 -1
- package/views/3d/terrain/TileRenderer.js +1 -1
- package/views/3d/webgl-engine/core/renderPasses/RenderPassManager.js +1 -1
- package/views/3d/webgl-engine/core/shaderLibrary/ForwardLinearDepth.glsl.js +1 -1
- package/views/3d/webgl-engine/core/shaderLibrary/ShaderOutput.js +1 -1
- package/views/3d/webgl-engine/core/shaderLibrary/default/DefaultMaterialAuxiliaryPasses.glsl.js +1 -1
- package/views/3d/webgl-engine/core/shaderLibrary/output/OutputDepth.glsl.js +1 -1
- package/views/3d/webgl-engine/lib/AnimationTimeStep.js +5 -0
- package/views/3d/webgl-engine/lib/AnimationTimer.js +1 -1
- package/views/3d/webgl-engine/lib/GLMaterial.js +1 -1
- package/views/3d/webgl-engine/lib/Material.js +1 -1
- package/views/3d/webgl-engine/lib/RenderFeature.js +5 -0
- package/views/3d/webgl-engine/lib/Renderer.js +1 -1
- package/views/3d/webgl-engine/lib/Texture.js +1 -1
- package/views/3d/webgl-engine/lib/lodRendering/LodRenderer.js +1 -1
- package/views/3d/webgl-engine/materials/DefaultMaterial.js +1 -1
- package/views/3d/webgl-engine/materials/PathMaterial.js +1 -1
- package/views/3d/webgl-engine/materials/renderers/MergedRenderer.js +1 -1
- package/views/3d/webgl-engine/parts/RenderView.js +1 -1
- package/views/webgl/RenderingContext.js +1 -1
- package/views/webgl/Texture.js +1 -1
- package/widgets/Editor/EditorViewModel.js +1 -1
- package/widgets/Editor.js +1 -1
- package/widgets/FeatureTemplates/FeatureTemplatesViewModel.js +1 -1
- package/widgets/FeatureTemplates/ItemList.js +1 -1
- package/widgets/FeatureTemplates/TemplateItem.js +1 -1
- package/widgets/FeatureTemplates/TemplateItemGroup.js +1 -1
- package/widgets/FeatureTemplates.js +1 -1
- package/widgets/support/decorators/accessibleHandler.js +1 -1
- package/assets/esri/core/workers/chunks/080a4be417be4943f6a0.js +0 -1
- package/assets/esri/core/workers/chunks/bf20831b3efe169d4cb8.js +0 -1
- package/rest/support/ImageMeasureDistanceAndAngleResult.js +0 -5
- package/views/3d/support/animationUtils.js +0 -5
- package/views/3d/webgl-engine/lib/RenderStateFeature.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.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{neverReached as t}from"../../../../core/compilerUtils.js";import e from"../../../../core/Error.js";import r from"../../../../core/Evented.js";import{isPowerOfTwo as
|
|
5
|
+
import{neverReached as t}from"../../../../core/compilerUtils.js";import e from"../../../../core/Error.js";import r from"../../../../core/Evented.js";import{isPowerOfTwo as s,nextHighestPowerOfTwo as i}from"../../../../core/mathUtils.js";import{isNone as a,isSome as o,removeMaybe as n}from"../../../../core/maybe.js";import{throwIfAborted as h,onAbort as l,createAbortError as m}from"../../../../core/promiseUtils.js";import{isArrayBuffer as p,isUint8Array as d}from"../../../../core/typedArrayUtil.js";import{isBlobProtocol as _,isDataProtocol as c}from"../../../../core/urlUtils.js";import{requestImage as u}from"../../../../support/requestImageUtils.js";import{loadImageAsync as T}from"../../../../support/requestUtils.js";import{T as g}from"../../../../chunks/TextureOnly.glsl.js";import{PowerOfTwoResizeMode as f,TextureEncodingMimeType as w}from"./basicInterfaces.js";import{estimateMemoryKTX2 as E,estimateMemoryBasis as A,createTextureKTX2 as x,createTextureBasis as D}from"./BasisUtil.js";import{ContentObject as M}from"./ContentObject.js";import{ContentObjectType as y}from"./ContentObjectType.js";import{createDDSTexture as I}from"./DDSUtil.js";import{createQuadVAO as F}from"./glUtil3D.js";import{assert as O}from"./Util.js";import{ContextType as R}from"../../../webgl/context-util.js";import{TextureWrapMode as U,TextureType as P,PixelFormat as N,PixelType as b,TextureSamplingMode as C,TargetType as H,DepthStencilTargetType as V,PrimitiveType as v}from"../../../webgl/enums.js";import{FramebufferObject as S}from"../../../webgl/FramebufferObject.js";import{Texture as j}from"../../../webgl/Texture.js";import{vertexCount as L}from"../../../webgl/Util.js";class G extends M{constructor(t,e){super(),this._data=t,this.type=y.Texture,this._glTexture=null,this._powerOfTwoStretchInfo=null,this._loadingPromise=null,this._loadingController=null,this.events=new r,this._passParameters=new g,this.params=e||{},this.params.mipmap=!1!==this.params.mipmap,this.params.noUnpackFlip=this.params.noUnpackFlip||!1,this.params.preMultiplyAlpha=this.params.preMultiplyAlpha||!1,this.params.wrap=this.params.wrap||{s:U.REPEAT,t:U.REPEAT},this.params.powerOfTwoResizeMode=this.params.powerOfTwoResizeMode||f.STRETCH,this.estimatedTexMemRequired=G._estimateTexMemRequired(this._data,this.params),this._startPreload()}_startPreload(){const t=this._data;a(t)||(t instanceof HTMLVideoElement?this._startPreloadVideoElement(t):t instanceof HTMLImageElement&&this._startPreloadImageElement(t))}_startPreloadVideoElement(t){if(!(_(t.src)||"auto"===t.preload&&t.crossOrigin)){t.preload="auto",t.crossOrigin="anonymous";const e=!t.paused;if(t.src=t.src,e&&t.autoplay){const e=()=>{t.removeEventListener("canplay",e),t.play()};t.addEventListener("canplay",e)}}}_startPreloadImageElement(t){c(t.src)||_(t.src)||t.crossOrigin||(t.crossOrigin="anonymous",t.src=t.src)}static _getDataDimensions(t){return t instanceof HTMLVideoElement?{width:t.videoWidth,height:t.videoHeight}:t}static _estimateTexMemRequired(t,e){if(a(t))return 0;if(p(t)||d(t))return e.encoding===w.KTX2_ENCODING?E(t,!!e.mipmap):e.encoding===w.BASIS_ENCODING?A(t,!!e.mipmap):t.byteLength;const{width:r,height:s}=t instanceof Image||t instanceof ImageData||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement?G._getDataDimensions(t):e;return(e.mipmap?4/3:1)*r*s*(e.components||4)||0}dispose(){this._data=void 0}get width(){return this.params.width}get height(){return this.params.height}_createDescriptor(t){return{target:P.TEXTURE_2D,pixelFormat:N.RGBA,dataType:b.UNSIGNED_BYTE,wrapMode:this.params.wrap,flipped:!this.params.noUnpackFlip,samplingMode:this.params.mipmap?C.LINEAR_MIPMAP_LINEAR:C.LINEAR,hasMipmap:this.params.mipmap,preMultiplyAlpha:this.params.preMultiplyAlpha,maxAnisotropy:this.params.maxAnisotropy??(this.params.mipmap?t.parameters.maxMaxAnisotropy:1)}}get glTexture(){return this._glTexture}load(t,e){if(o(this._glTexture))return this._glTexture;if(o(this._loadingPromise))return this._loadingPromise;const r=this._data;return a(r)?(this._glTexture=new j(t,this._createDescriptor(t),null),this._glTexture):"string"==typeof r?this._loadFromURL(t,e,r):r instanceof Image?this._loadFromImageElement(t,e,r):r instanceof HTMLVideoElement?this._loadFromVideoElement(t,e,r):r instanceof ImageData||r instanceof HTMLCanvasElement?this._loadFromImage(t,r,e):(p(r)||d(r))&&this.params.encoding===w.DDS_ENCODING?(this._data=void 0,this._loadFromDDSData(t,r)):(p(r)||d(r))&&this.params.encoding===w.KTX2_ENCODING?(this._data=void 0,this._loadFromKTX2(t,r)):(p(r)||d(r))&&this.params.encoding===w.BASIS_ENCODING?(this._data=void 0,this._loadFromBasis(t,r)):d(r)?this._loadFromPixelData(t,r):p(r)?this._loadFromPixelData(t,new Uint8Array(r)):null}get requiresFrameUpdates(){return this._data instanceof HTMLVideoElement}frameUpdate(t,e,r){if(!(this._data instanceof HTMLVideoElement)||a(this._glTexture))return r;if(this._data.readyState<B.HAVE_CURRENT_DATA||r===this._data.currentTime)return r;if(o(this._powerOfTwoStretchInfo)){const{framebuffer:r,vao:s,sourceTexture:i}=this._powerOfTwoStretchInfo;i.setData(this._data),this._drawStretchedTexture(t,e,r,s,i,this._glTexture)}else{const{videoWidth:t,videoHeight:e}=this._data,{width:r,height:s}=this._glTexture.descriptor;t!==r||e!==s?this._glTexture.updateData(0,0,0,Math.min(t,r),Math.min(e,s),this._data):this._glTexture.setData(this._data)}return this._glTexture.descriptor.hasMipmap&&this._glTexture.generateMipmap(),this.params.updateCallback&&this.params.updateCallback(),this._data.currentTime}_loadFromDDSData(t,e){return this._glTexture=I(t,this._createDescriptor(t),e),this._glTexture}_loadFromKTX2(t,e){return this._loadAsync((()=>x(t,this._createDescriptor(t),e).then((t=>(this._glTexture=t,t)))))}_loadFromBasis(t,e){return this._loadAsync((()=>D(t,this._createDescriptor(t),e).then((t=>(this._glTexture=t,t)))))}_loadFromPixelData(t,e){O(this.params.width>0&&this.params.height>0);const r=this._createDescriptor(t);return r.pixelFormat=1===this.params.components?N.LUMINANCE:3===this.params.components?N.RGB:N.RGBA,r.width=this.params.width,r.height=this.params.height,this._glTexture=new j(t,r,e),this._glTexture}_loadFromURL(t,e,r){return this._loadAsync((async s=>{const i=await u(r,{signal:s});return h(s),this._loadFromImage(t,i,e)}))}_loadFromImageElement(t,e,r){return r.complete?this._loadFromImage(t,r,e):this._loadAsync((async s=>{const i=await T(r,r.src,!1,s);return h(s),this._loadFromImage(t,i,e)}))}_loadFromVideoElement(t,e,r){return r.readyState>=B.HAVE_CURRENT_DATA?this._loadFromImage(t,r,e):this._loadFromVideoElementAsync(t,e,r)}_loadFromVideoElementAsync(t,r,s){return this._loadAsync((i=>new Promise(((a,o)=>{const h=()=>{s.removeEventListener("loadeddata",p),s.removeEventListener("error",d),n(_)},p=()=>{s.readyState>=B.HAVE_CURRENT_DATA&&(h(),a(this._loadFromImage(t,s,r)))},d=t=>{h(),o(t||new e("Failed to load video"))};s.addEventListener("loadeddata",p),s.addEventListener("error",d);const _=l(i,(()=>d(m())))}))))}_loadFromImage(t,e,r){const i=G._getDataDimensions(e);this.params.width=i.width,this.params.height=i.height;const a=this._createDescriptor(t);return a.pixelFormat=3===this.params.components?N.RGB:N.RGBA,!this._requiresPowerOfTwo(t,a)||s(i.width)&&s(i.height)?(a.width=i.width,a.height=i.height,this._glTexture=new j(t,a,e),this._glTexture):(this._glTexture=this._makePowerOfTwoTexture(t,e,i,a,r),this._glTexture)}_loadAsync(t){const e=new AbortController;this._loadingController=e;const r=t(e.signal);this._loadingPromise=r;const s=()=>{this._loadingController===e&&(this._loadingController=null),this._loadingPromise===r&&(this._loadingPromise=null)};return r.then(s,s),r}_requiresPowerOfTwo(t,e){const r=U.CLAMP_TO_EDGE,s="number"==typeof e.wrapMode?e.wrapMode===r:e.wrapMode.s===r&&e.wrapMode.t===r;return t.type===R.WEBGL1&&(e.hasMipmap||!s)}_makePowerOfTwoTexture(e,r,s,a,o){const{width:n,height:h}=s,l=i(n),m=i(h);let p;switch(a.width=l,a.height=m,this.params.powerOfTwoResizeMode){case f.PAD:a.textureCoordinateScaleFactor=[n/l,h/m],p=new j(e,a),p.updateData(0,0,0,n,h,r);break;case f.STRETCH:case null:case void 0:p=this._stretchToPowerOfTwo(e,r,a,o());break;default:t(this.params.powerOfTwoResizeMode)}return a.hasMipmap&&p.generateMipmap(),p}_stretchToPowerOfTwo(t,e,r,s){const i=new j(t,r),a=new S(t,{colorTarget:H.TEXTURE,depthStencilTarget:V.NONE},i),o=new j(t,{target:P.TEXTURE_2D,pixelFormat:r.pixelFormat,dataType:b.UNSIGNED_BYTE,wrapMode:U.CLAMP_TO_EDGE,samplingMode:C.LINEAR,flipped:!!r.flipped,maxAnisotropy:8,preMultiplyAlpha:r.preMultiplyAlpha},e),n=F(t),h=t.getBoundFramebufferObject();return this._drawStretchedTexture(t,s,a,n,o,i),this.requiresFrameUpdates?this._powerOfTwoStretchInfo={vao:n,sourceTexture:o,framebuffer:a}:(n.dispose(!0),o.dispose(),a.detachColorTexture(),a.dispose()),t.bindFramebuffer(h),i}_drawStretchedTexture(t,e,r,s,i,a){this._passParameters.texture=i,t.bindFramebuffer(r);const o=t.getViewport();t.setViewport(0,0,a.descriptor.width,a.descriptor.height),t.bindTechnique(e,this._passParameters,null),t.bindVAO(s),t.drawArrays(v.TRIANGLE_STRIP,0,L(s,"geometry")),t.bindFramebuffer(null),t.setViewport(o.x,o.y,o.width,o.height),this._passParameters.texture=null}unload(){if(o(this._powerOfTwoStretchInfo)){const{framebuffer:t,vao:e,sourceTexture:r}=this._powerOfTwoStretchInfo;e.dispose(!0),r.dispose(),t.dispose(),this._glTexture=null,this._powerOfTwoStretchInfo=null}if(o(this._glTexture)&&(this._glTexture.dispose(),this._glTexture=null),o(this._loadingController)){const t=this._loadingController;this._loadingController=null,this._loadingPromise=null,t.abort()}this.events.emit("unloaded")}}var B;!function(t){t[t.HAVE_NOTHING=0]="HAVE_NOTHING",t[t.HAVE_METADATA=1]="HAVE_METADATA",t[t.HAVE_CURRENT_DATA=2]="HAVE_CURRENT_DATA",t[t.HAVE_FUTURE_DATA=3]="HAVE_FUTURE_DATA",t[t.HAVE_ENOUGH_DATA=4]="HAVE_ENOUGH_DATA"}(B||(B={}));export{G as Texture};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{_ as e}from"../../../../../chunks/tslib.es6.js";import t from"../../../../../core/Accessor.js";import{isSome as r,isNone as a,destroyMaybe as s}from"../../../../../core/maybe.js";import{isAborted as n,throwIfAborted as i}from"../../../../../core/promiseUtils.js";import{property as o}from"../../../../../core/accessorSupport/decorators/property.js";import"../../../../../core/accessorSupport/ensureType.js";import"../../../../../core/arrayUtils.js";import{subclass as c}from"../../../../../core/accessorSupport/decorators/subclass.js";import{c as l}from"../../../../../chunks/mat4f64.js";import{b as h,e as d,m as u}from"../../../../../chunks/vec3.js";import{c as m}from"../../../../../chunks/vec3f64.js";import{c as p,f as _}from"../../../../../chunks/vec4f64.js";import f from"../../../support/debugFlags.js";import{glLayout as g}from"../../../support/buffer/glUtil.js";import{newLayout as I}from"../../../support/buffer/InterleavedLayout.js";import{ShaderOutput as y}from"../../core/shaderLibrary/ShaderOutput.js";import{Camera as C}from"../Camera.js";import{Default3D as v}from"../DefaultVertexAttributeLocations.js";import{IntersectorType as E}from"../IntersectorInterfaces.js";import R from"../Octree.js";import{RenderSlot as D}from"../RenderSlot.js";import{assert as b}from"../Util.js";import{VertexAttribute as A}from"../VertexAttribute.js";import{InstanceData as T,StateFlags as L}from"./InstanceData.js";import{InstanceOctree as O}from"./InstanceOctree.js";import{LevelSelector as S}from"./LevelSelector.js";import{LodLevel as j}from"./LodLevel.js";import{RenderInstanceData as x}from"./RenderInstanceData.js";import{colorMixModes as U}from"../../materials/internal/MaterialUtil.js";import{encodeDoubleVec3 as N}from"../../materials/renderers/utils.js";import{DefaultMaterialDrawParameters as M}from"../../shaders/DefaultMaterialTechnique.js";import{TaskPriority as F,noBudget as V}from"../../../../support/Scheduler.js";import{bindVertexBufferLayout as w,unbindVertexBufferLayout as B}from"../../../../webgl/Util.js";const H=e=>{const t=e.baseBoundingSphere.radius,r=e.levels.map((e=>e.minScreenSpaceRadius));return new S(t,r)};let q=class extends t{constructor(e,t){super(e),this.type=E.LOD,this.isGround=!1,this._levels=[],this._defaultRenderInstanceData=[],this._highlightRenderInstanceData=[],this._instanceIndex=0,this._cycleStartIndex=0,this._slicePlane=!1,this._camera=new C,this._updateCyclesWithStaticCamera=-1,this._needFullCycle=!1,this.slots=[D.OPAQUE_MATERIAL,D.TRANSPARENT_MATERIAL],this.canRender=!0,this._instanceData=new T({shaderTransformation:e.shaderTransformation},e.optionalFields),this._frameTask=t.registerTask(F.LOD_RENDERER,this)}initialize(){this._instanceBufferLayout=k(this.optionalFields),this._glInstanceBufferLayout=g(this._instanceBufferLayout,1),this._instanceData.events.on("instances-changed",(()=>this._requestUpdateCycle())),this._instanceData.events.on("instance-transform-changed",(({index:e})=>{this._requestUpdateCycle(),this.metadata.notifyGraphicGeometryChanged(e)})),this._instanceData.events.on("instance-visibility-changed",(({index:e})=>{this._requestUpdateCycle(!0),this.metadata.notifyGraphicVisibilityChanged(e)})),this._instanceData.events.on("instance-highlight-changed",(()=>this._requestUpdateCycle(!0)))}destroy(){this._frameTask.remove()}get _enableLevelSelection(){return this.symbol.levels.length>1}get levels(){return this._levels}get baseBoundingBox(){return this._levels[this._levels.length-1].boundingBox}get baseBoundingSphere(){return this._levels[this._levels.length-1].boundingSphere}get baseMaterial(){return this._levels[this._levels.length-1].components[0].material}get slicePlaneEnabled(){return this._slicePlane}set slicePlaneEnabled(e){this._slicePlane=e}get layerUid(){return this.metadata.layerUid}get instanceData(){return this._instanceData}get memoryUsage(){const e={cpu:0,gpu:0};return this._defaultRenderInstanceData.forEach((t=>{const r=t.memoryUsage;e.cpu+=r.cpu,e.gpu+=r.gpu})),this._highlightRenderInstanceData.forEach((t=>{const r=t.memoryUsage;e.cpu+=r.cpu,e.gpu+=r.gpu})),e}get renderStats(){const e=this._instanceData.size,t=[];return this._levels.forEach(((e,r)=>{const a=this._defaultRenderInstanceData[r],s=this._highlightRenderInstanceData[r],n=a.size+s.size,i=e.triangleCount;t.push({renderedInstances:n,renderedTriangles:n*i,trianglesPerInstance:i})})),{totalInstances:e,renderedInstances:t.reduce(((e,t)=>e+t.renderedInstances),0),renderedTriangles:t.reduce(((e,t)=>e+t.renderedTriangles),0),levels:t}}async initializeRenderContext(e,t){this._context=e;const a=e.renderContext.rctx,s=await Promise.allSettled(this.symbol.levels.map((r=>(this._defaultRenderInstanceData.push(new x(a,this._instanceBufferLayout)),this._highlightRenderInstanceData.push(new x(a,this._instanceBufferLayout)),j.create(e,r,t))))),o=s.map((e=>"fulfilled"===e.status?e.value:null)).filter(r);if(n(t)||o.length!==s.length){o.forEach((e=>e.destroy())),i(t);for(const e of s)if("rejected"===e.status)throw e.reason}this._levels=o,this._levelSelector=H(this)}uninitializeRenderContext(){this._invalidateOctree(),this._levels.forEach((e=>e.destroy())),this._defaultRenderInstanceData.forEach((e=>e.destroy())),this._highlightRenderInstanceData.forEach((e=>e.destroy()))}get needsTransparentPass(){return this._levels.some((e=>e.components.some((e=>e.material.requiresSlot(D.TRANSPARENT_MATERIAL,y.Color)))))}get needsHighlight(){return this._highlightRenderInstanceData.some((e=>e.size>0))}prepareRender(e){if(!f.LOD_INSTANCE_RENDERER_DISABLE_UPDATES){if(this._enableLevelSelection){const t=e.bindParameters.contentCamera.equals(this._camera);this._camera.copyFrom(e.bindParameters.contentCamera),t||this._requestUpdateCycle()}this._needFullCycle&&(this.runTask(V),this._needFullCycle=!1)}}render(e){if(!this.baseMaterial.isVisible()||!this.baseMaterial.isVisibleForOutput(e.output))return;e.rctx.bindVAO();e.output!==y.Highlight&&e.output!==y.ShadowHighlight&&this._renderComponents(e,this._defaultRenderInstanceData);e.output!==y.ShadowExludeHighlight&&this._renderComponents(e,this._highlightRenderInstanceData)}intersect(e,t,r,s){if(!this.baseMaterial.isVisible()||a(this._octree))return;const n=m();h(n,s,r);const i=a=>{this._instanceData.getCombinedModelTransform(a,K),e.transform.set(K),u(Y,r,e.transform.inverse),u(J,s,e.transform.inverse);const n=this._instanceData.getState(a),i=this._instanceData.getLodLevel(a),o=this._levels.length;b(0!=(n&L.ACTIVE),"invalid instance state"),b(i>=0&&i<o,"invaid lod level"),this._levels[i].intersect(e,t,Y,J,a,this.metadata,o)};this.baseMaterial.parameters.verticalOffset?this._octree.forEach(i):this._octree.forEachAlongRay(r,n,i)}queryDepthRange(e){return this._queryDepthRangeOctree(e)}notifyShaderTransformationChanged(){this._invalidateOctree(),this._requestUpdateCycle()}get _octree(){if(a(this._octreeCached)){const e=this._instanceData,t=e.view?.state;if(!t)return null;this._octreeCached=new O(e,this.baseBoundingSphere);for(let r=0;r<e.capacity;++r)t.get(r)&L.ACTIVE&&this._octreeCached.addInstance(r)}return this._octreeCached}_invalidateOctree(){this._octreeCached=s(this._octreeCached)}_queryDepthRangeOctree(e){if(a(this._octree))return{near:1/0,far:-1/0};const t=e.viewForward,r=this._octree.findClosest(t,R.DepthOrder.FRONT_TO_BACK,e.frustum),s=this._octree.findClosest(t,R.DepthOrder.BACK_TO_FRONT,e.frustum);if(null==r||null==s)return{near:1/0,far:-1/0};const n=e.eye,i=this._instanceData.view;i.boundingSphere.getVec(r,W),h(W,W,n);const o=d(W,t)-W[3];i.boundingSphere.getVec(s,W),h(W,W,n);const c=d(W,t)+W[3];return{near:Math.max(e.near,o),far:Math.min(e.far,c)}}_requestUpdateCycle(e=!1){this._updateCyclesWithStaticCamera=-1,this._cycleStartIndex=this._instanceIndex,e&&(this._needFullCycle=!0,this._context.requestRender())}_startUpdateCycle(){this._updateCyclesWithStaticCamera++,this._defaultRenderInstanceData.forEach((e=>e.startUpdateCycle())),this._highlightRenderInstanceData.forEach((e=>e.startUpdateCycle()))}get running(){return this._instanceData.size>0&&this._updateCyclesWithStaticCamera<1}runTask(e){const{_enableLevelSelection:t,_camera:a,_levelSelector:s}=this;this._defaultRenderInstanceData.forEach((e=>e.beginUpdate())),this._highlightRenderInstanceData.forEach((e=>e.beginUpdate()));const n=this._instanceData,i=n.view;let o=n.size;const c=n.capacity;let l=this._instanceIndex;for(let h=0;h<o&&!e.done;++h){l===this._cycleStartIndex&&this._startUpdateCycle();const h=i.state.get(l);let d=0;if(!(h&L.ALLOCATED)){l=l+1===c?0:l+1,o++;continue}const u=i.lodLevel.get(l);if(h&L.DEFAULT_ACTIVE&&this._defaultRenderInstanceData[u].freeTail(),h&L.HIGHLIGHT_ACTIVE&&this._highlightRenderInstanceData[u].freeTail(),h&L.REMOVE)n.freeInstance(l);else if(h&L.VISIBLE){let e=0;t&&(i.modelOrigin.getVec(l,z),e=s.selectLevel(z,n.getCombinedMedianScaleFactor(l),a)),d=h&~(L.ACTIVE|L.TRANSFORM_CHANGED),e>=0&&(h&L.HIGHLIGHT?(P(this._highlightRenderInstanceData[e],i,l),d|=L.HIGHLIGHT_ACTIVE):(P(this._defaultRenderInstanceData[e],i,l),d|=L.DEFAULT_ACTIVE)),i.state.set(l,d),i.lodLevel.set(l,e)}else d=h&~(L.ACTIVE|L.TRANSFORM_CHANGED),i.state.set(l,d);if(r(this._octreeCached)){const e=!!(h&L.ACTIVE),t=!!(d&L.ACTIVE);!e&&t?this._octreeCached.addInstance(l):e&&!t?this._octreeCached.removeInstance(l):e&&t&&h&L.TRANSFORM_CHANGED&&(this._octreeCached.removeInstance(l),this._octreeCached.addInstance(l))}l=l+1===c?0:l+1,e.madeProgress()}this._instanceIndex=l,this._defaultRenderInstanceData.forEach((e=>e.endUpdate())),this._highlightRenderInstanceData.forEach((e=>e.endUpdate())),this._context.requestRender()}_renderComponents(e,t){this.levels.forEach(((r,a)=>{const s=r.components.map((r=>this._beginComponent(e,t[a],r)));r.components.forEach(((r,n)=>this._renderComponent(e,s[n],t[a],r,a)))}))}_beginComponent(e,t,a){const{bindParameters:s,rctx:n,output:i}=e;if(0===t.size||!a.material.requiresSlot(s.slot,e.output))return null;const o=a.glMaterials.load(n,s.slot,i);return r(o)?o.beginSlot(s):null}_renderComponent(e,t,r,s,n){if(a(t))return;const{bindParameters:i,rctx:o}=e,c=o.bindTechnique(t,s.material.parameters,i);o.bindVAO(s.vao),t.ensureAttributeLocations(s.vao),c.bindDraw(Z,i,s.material.parameters),f.LOD_INSTANCE_RENDERER_COLORIZE_BY_LEVEL&&e.output===y.Color&&(c.setUniform4fv("externalColor",Q[Math.min(n,Q.length-1)]),c.setUniform1i("colorMixMode",U.replace));const l=o.capabilities.instancing,h=r.capacity,d=r.headIndex,u=r.tailIndex,m=r.firstIndex,p=this._glInstanceBufferLayout,_=(e,a)=>{w(o,v,r.buffer,p,e),l.drawArraysInstanced(t.primitiveType,0,s.vertexCount,a-e),B(o,v,r.buffer,p)};s.material.parameters.transparent&&null!=m?d>u?(b(m>=u&&m<=d,"invalid firstIndex"),_(m,d),_(u,m)):d<u&&(m<=d?(b(m>=0&&m<=d,"invalid firstIndex"),_(m,d),_(u,h),_(0,m)):(b(m>=u&&m<=h,"invalid firstIndex"),_(m,h),_(0,d),_(u,m))):d>u?_(u,d):d<u&&(_(0,d),_(u,h)),o.bindVAO(null)}};function P(e,t,r){const a=e.allocateHead();G(t,r,e.view,a)}function G(e,t,r,a){N(e.modelOrigin,t,r.modelOriginHi,r.modelOriginLo,a),r.model.copyFrom(a,e.model,t),r.modelNormal.copyFrom(a,e.modelNormal,t),e.color&&r.color&&r.color.copyFrom(a,e.color,t),e.objectAndLayerIdColor&&r.objectAndLayerIdColor&&r.objectAndLayerIdColor.copyFrom(a,e.objectAndLayerIdColor,t),e.featureAttribute&&r.featureAttribute&&r.featureAttribute.copyFrom(a,e.featureAttribute,t)}function k(e){let t=I().vec3f(A.MODELORIGINHI).vec3f(A.MODELORIGINLO).mat3f(A.MODEL).mat3f(A.MODELNORMAL);return r(e)&&e.includes("color")&&(t=t.vec4f(A.INSTANCECOLOR)),r(e)&&e.includes("featureAttribute")&&(t=t.vec4f(A.INSTANCEFEATUREATTRIBUTE)),r(e)&&e.includes("objectAndLayerIdColor")&&(t=t.vec4u8(A.OBJECTANDLAYERIDCOLOR_INSTANCED)),t}e([o({constructOnly:!0})],q.prototype,"symbol",void 0),e([o({constructOnly:!0})],q.prototype,"optionalFields",void 0),e([o({constructOnly:!0})],q.prototype,"metadata",void 0),e([o({constructOnly:!0})],q.prototype,"shaderTransformation",void 0),e([o()],q.prototype,"_instanceData",void 0),e([o()],q.prototype,"_cycleStartIndex",void 0),e([o({readOnly:!0})],q.prototype,"_enableLevelSelection",null),e([o()],q.prototype,"_updateCyclesWithStaticCamera",void 0),e([o({readOnly:!0})],q.prototype,"running",null),q=e([c("esri.views.3d.webgl-engine.lib.lodRendering.LodRenderer")],q);const z=m(),W=p(),K=l(),Y=m(),J=m(),Q=[_(1,0,1,1),_(0,0,1,1),_(0,1,0,1),_(1,1,0,1),_(1,0,0,1)],Z=new M;export{q as LodRenderer};
|
|
5
|
+
import{_ as e}from"../../../../../chunks/tslib.es6.js";import t from"../../../../../core/Accessor.js";import{isSome as r,isNone as a,destroyMaybe as s}from"../../../../../core/maybe.js";import{isAborted as n,throwIfAborted as i}from"../../../../../core/promiseUtils.js";import{property as o}from"../../../../../core/accessorSupport/decorators/property.js";import"../../../../../core/accessorSupport/ensureType.js";import"../../../../../core/arrayUtils.js";import{subclass as c}from"../../../../../core/accessorSupport/decorators/subclass.js";import{c as l}from"../../../../../chunks/mat4f64.js";import{b as h,e as d,m as u}from"../../../../../chunks/vec3.js";import{c as m}from"../../../../../chunks/vec3f64.js";import{c as p,f as _}from"../../../../../chunks/vec4f64.js";import f from"../../../support/debugFlags.js";import{glLayout as g}from"../../../support/buffer/glUtil.js";import{newLayout as I}from"../../../support/buffer/InterleavedLayout.js";import{ShaderOutput as y}from"../../core/shaderLibrary/ShaderOutput.js";import{Camera as C}from"../Camera.js";import{Default3D as v}from"../DefaultVertexAttributeLocations.js";import{IntersectorType as E}from"../IntersectorInterfaces.js";import R from"../Octree.js";import{RenderSlot as D}from"../RenderSlot.js";import{assert as b}from"../Util.js";import{VertexAttribute as A}from"../VertexAttribute.js";import{InstanceData as T,StateFlags as L}from"./InstanceData.js";import{InstanceOctree as O}from"./InstanceOctree.js";import{LevelSelector as S}from"./LevelSelector.js";import{LodLevel as j}from"./LodLevel.js";import{RenderInstanceData as x}from"./RenderInstanceData.js";import{colorMixModes as U}from"../../materials/internal/MaterialUtil.js";import{encodeDoubleVec3 as N}from"../../materials/renderers/utils.js";import{DefaultMaterialDrawParameters as M}from"../../shaders/DefaultMaterialTechnique.js";import{TaskPriority as F,noBudget as V}from"../../../../support/Scheduler.js";import{bindVertexBufferLayout as w,unbindVertexBufferLayout as B}from"../../../../webgl/Util.js";const H=e=>{const t=e.baseBoundingSphere.radius,r=e.levels.map((e=>e.minScreenSpaceRadius));return new S(t,r)};let q=class extends t{constructor(e,t){super(e),this.type=E.LOD,this.isGround=!1,this._levels=[],this._defaultRenderInstanceData=[],this._highlightRenderInstanceData=[],this._instanceIndex=0,this._cycleStartIndex=0,this._slicePlane=!1,this._camera=new C,this._updateCyclesWithStaticCamera=-1,this._needFullCycle=!1,this.slots=[D.OPAQUE_MATERIAL,D.TRANSPARENT_MATERIAL],this.canRender=!0,this._instanceData=new T({shaderTransformation:e.shaderTransformation},e.optionalFields),this._frameTask=t.registerTask(F.LOD_RENDERER,this)}initialize(){this._instanceBufferLayout=k(this.optionalFields),this._glInstanceBufferLayout=g(this._instanceBufferLayout,1),this._instanceData.events.on("instances-changed",(()=>this._requestUpdateCycle())),this._instanceData.events.on("instance-transform-changed",(({index:e})=>{this._requestUpdateCycle(),this.metadata.notifyGraphicGeometryChanged(e)})),this._instanceData.events.on("instance-visibility-changed",(({index:e})=>{this._requestUpdateCycle(!0),this.metadata.notifyGraphicVisibilityChanged(e)})),this._instanceData.events.on("instance-highlight-changed",(()=>this._requestUpdateCycle(!0)))}destroy(){this._frameTask.remove()}get _enableLevelSelection(){return this.symbol.levels.length>1}get levels(){return this._levels}get baseBoundingBox(){return this._levels[this._levels.length-1].boundingBox}get baseBoundingSphere(){return this._levels[this._levels.length-1].boundingSphere}get baseMaterial(){return this._levels[this._levels.length-1].components[0].material}get slicePlaneEnabled(){return this._slicePlane}set slicePlaneEnabled(e){this._slicePlane=e}get layerUid(){return this.metadata.layerUid}get instanceData(){return this._instanceData}get memoryUsage(){const e={cpu:0,gpu:0};return this._defaultRenderInstanceData.forEach((t=>{const r=t.memoryUsage;e.cpu+=r.cpu,e.gpu+=r.gpu})),this._highlightRenderInstanceData.forEach((t=>{const r=t.memoryUsage;e.cpu+=r.cpu,e.gpu+=r.gpu})),e}get renderStats(){const e=this._instanceData.size,t=[];return this._levels.forEach(((e,r)=>{const a=this._defaultRenderInstanceData[r],s=this._highlightRenderInstanceData[r],n=a.size+s.size,i=e.triangleCount;t.push({renderedInstances:n,renderedTriangles:n*i,trianglesPerInstance:i})})),{totalInstances:e,renderedInstances:t.reduce(((e,t)=>e+t.renderedInstances),0),renderedTriangles:t.reduce(((e,t)=>e+t.renderedTriangles),0),levels:t}}async initializeRenderContext(e,t){this._context=e;const a=e.renderContext.rctx,s=await Promise.allSettled(this.symbol.levels.map((r=>(this._defaultRenderInstanceData.push(new x(a,this._instanceBufferLayout)),this._highlightRenderInstanceData.push(new x(a,this._instanceBufferLayout)),j.create(e,r,t))))),o=s.map((e=>"fulfilled"===e.status?e.value:null)).filter(r);if(n(t)||o.length!==s.length){o.forEach((e=>e.destroy())),i(t);for(const e of s)if("rejected"===e.status)throw e.reason}this._levels=o,this._levelSelector=H(this)}uninitializeRenderContext(){this._invalidateOctree(),this._levels.forEach((e=>e.destroy())),this._defaultRenderInstanceData.forEach((e=>e.destroy())),this._highlightRenderInstanceData.forEach((e=>e.destroy()))}get needsTransparentPass(){return this._levels.some((e=>e.components.some((e=>e.material.requiresSlot(D.TRANSPARENT_MATERIAL,y.Color)))))}get needsHighlight(){return this._highlightRenderInstanceData.some((e=>e.size>0))}prepareRender(e){if(!f.LOD_INSTANCE_RENDERER_DISABLE_UPDATES){if(this._enableLevelSelection){const t=e.bindParameters.contentCamera.equals(this._camera);this._camera.copyFrom(e.bindParameters.contentCamera),t||this._requestUpdateCycle()}this._needFullCycle&&(this.runTask(V),this._needFullCycle=!1)}}render(e){if(!this.baseMaterial.isVisible()||!this.baseMaterial.isVisibleForOutput(e.output))return;e.rctx.bindVAO();e.output!==y.Highlight&&e.output!==y.ShadowHighlight&&this._renderComponents(e,this._defaultRenderInstanceData);e.output!==y.ShadowExcludeHighlight&&this._renderComponents(e,this._highlightRenderInstanceData)}intersect(e,t,r,s){if(!this.baseMaterial.isVisible()||a(this._octree))return;const n=m();h(n,s,r);const i=a=>{this._instanceData.getCombinedModelTransform(a,K),e.transform.set(K),u(Y,r,e.transform.inverse),u(J,s,e.transform.inverse);const n=this._instanceData.getState(a),i=this._instanceData.getLodLevel(a),o=this._levels.length;b(0!=(n&L.ACTIVE),"invalid instance state"),b(i>=0&&i<o,"invaid lod level"),this._levels[i].intersect(e,t,Y,J,a,this.metadata,o)};this.baseMaterial.parameters.verticalOffset?this._octree.forEach(i):this._octree.forEachAlongRay(r,n,i)}queryDepthRange(e){return this._queryDepthRangeOctree(e)}notifyShaderTransformationChanged(){this._invalidateOctree(),this._requestUpdateCycle()}get _octree(){if(a(this._octreeCached)){const e=this._instanceData,t=e.view?.state;if(!t)return null;this._octreeCached=new O(e,this.baseBoundingSphere);for(let r=0;r<e.capacity;++r)t.get(r)&L.ACTIVE&&this._octreeCached.addInstance(r)}return this._octreeCached}_invalidateOctree(){this._octreeCached=s(this._octreeCached)}_queryDepthRangeOctree(e){if(a(this._octree))return{near:1/0,far:-1/0};const t=e.viewForward,r=this._octree.findClosest(t,R.DepthOrder.FRONT_TO_BACK,e.frustum),s=this._octree.findClosest(t,R.DepthOrder.BACK_TO_FRONT,e.frustum);if(null==r||null==s)return{near:1/0,far:-1/0};const n=e.eye,i=this._instanceData.view;i.boundingSphere.getVec(r,W),h(W,W,n);const o=d(W,t)-W[3];i.boundingSphere.getVec(s,W),h(W,W,n);const c=d(W,t)+W[3];return{near:Math.max(e.near,o),far:Math.min(e.far,c)}}_requestUpdateCycle(e=!1){this._updateCyclesWithStaticCamera=-1,this._cycleStartIndex=this._instanceIndex,e&&(this._needFullCycle=!0,this._context.requestRender())}_startUpdateCycle(){this._updateCyclesWithStaticCamera++,this._defaultRenderInstanceData.forEach((e=>e.startUpdateCycle())),this._highlightRenderInstanceData.forEach((e=>e.startUpdateCycle()))}get running(){return this._instanceData.size>0&&this._updateCyclesWithStaticCamera<1}runTask(e){const{_enableLevelSelection:t,_camera:a,_levelSelector:s}=this;this._defaultRenderInstanceData.forEach((e=>e.beginUpdate())),this._highlightRenderInstanceData.forEach((e=>e.beginUpdate()));const n=this._instanceData,i=n.view;let o=n.size;const c=n.capacity;let l=this._instanceIndex;for(let h=0;h<o&&!e.done;++h){l===this._cycleStartIndex&&this._startUpdateCycle();const h=i.state.get(l);let d=0;if(!(h&L.ALLOCATED)){l=l+1===c?0:l+1,o++;continue}const u=i.lodLevel.get(l);if(h&L.DEFAULT_ACTIVE&&this._defaultRenderInstanceData[u].freeTail(),h&L.HIGHLIGHT_ACTIVE&&this._highlightRenderInstanceData[u].freeTail(),h&L.REMOVE)n.freeInstance(l);else if(h&L.VISIBLE){let e=0;t&&(i.modelOrigin.getVec(l,z),e=s.selectLevel(z,n.getCombinedMedianScaleFactor(l),a)),d=h&~(L.ACTIVE|L.TRANSFORM_CHANGED),e>=0&&(h&L.HIGHLIGHT?(P(this._highlightRenderInstanceData[e],i,l),d|=L.HIGHLIGHT_ACTIVE):(P(this._defaultRenderInstanceData[e],i,l),d|=L.DEFAULT_ACTIVE)),i.state.set(l,d),i.lodLevel.set(l,e)}else d=h&~(L.ACTIVE|L.TRANSFORM_CHANGED),i.state.set(l,d);if(r(this._octreeCached)){const e=!!(h&L.ACTIVE),t=!!(d&L.ACTIVE);!e&&t?this._octreeCached.addInstance(l):e&&!t?this._octreeCached.removeInstance(l):e&&t&&h&L.TRANSFORM_CHANGED&&(this._octreeCached.removeInstance(l),this._octreeCached.addInstance(l))}l=l+1===c?0:l+1,e.madeProgress()}this._instanceIndex=l,this._defaultRenderInstanceData.forEach((e=>e.endUpdate())),this._highlightRenderInstanceData.forEach((e=>e.endUpdate())),this._context.requestRender()}_renderComponents(e,t){this.levels.forEach(((r,a)=>{const s=r.components.map((r=>this._beginComponent(e,t[a],r)));r.components.forEach(((r,n)=>this._renderComponent(e,s[n],t[a],r,a)))}))}_beginComponent(e,t,a){const{bindParameters:s,rctx:n,output:i}=e;if(0===t.size||!a.material.requiresSlot(s.slot,e.output))return null;const o=a.glMaterials.load(n,s.slot,i);return r(o)?o.beginSlot(s):null}_renderComponent(e,t,r,s,n){if(a(t))return;const{bindParameters:i,rctx:o}=e,c=o.bindTechnique(t,s.material.parameters,i);o.bindVAO(s.vao),t.ensureAttributeLocations(s.vao),c.bindDraw(Z,i,s.material.parameters),f.LOD_INSTANCE_RENDERER_COLORIZE_BY_LEVEL&&e.output===y.Color&&(c.setUniform4fv("externalColor",Q[Math.min(n,Q.length-1)]),c.setUniform1i("colorMixMode",U.replace));const l=o.capabilities.instancing,h=r.capacity,d=r.headIndex,u=r.tailIndex,m=r.firstIndex,p=this._glInstanceBufferLayout,_=(e,a)=>{w(o,v,r.buffer,p,e),l.drawArraysInstanced(t.primitiveType,0,s.vertexCount,a-e),B(o,v,r.buffer,p)};s.material.parameters.transparent&&null!=m?d>u?(b(m>=u&&m<=d,"invalid firstIndex"),_(m,d),_(u,m)):d<u&&(m<=d?(b(m>=0&&m<=d,"invalid firstIndex"),_(m,d),_(u,h),_(0,m)):(b(m>=u&&m<=h,"invalid firstIndex"),_(m,h),_(0,d),_(u,m))):d>u?_(u,d):d<u&&(_(0,d),_(u,h)),o.bindVAO(null)}};function P(e,t,r){const a=e.allocateHead();G(t,r,e.view,a)}function G(e,t,r,a){N(e.modelOrigin,t,r.modelOriginHi,r.modelOriginLo,a),r.model.copyFrom(a,e.model,t),r.modelNormal.copyFrom(a,e.modelNormal,t),e.color&&r.color&&r.color.copyFrom(a,e.color,t),e.objectAndLayerIdColor&&r.objectAndLayerIdColor&&r.objectAndLayerIdColor.copyFrom(a,e.objectAndLayerIdColor,t),e.featureAttribute&&r.featureAttribute&&r.featureAttribute.copyFrom(a,e.featureAttribute,t)}function k(e){let t=I().vec3f(A.MODELORIGINHI).vec3f(A.MODELORIGINLO).mat3f(A.MODEL).mat3f(A.MODELNORMAL);return r(e)&&e.includes("color")&&(t=t.vec4f(A.INSTANCECOLOR)),r(e)&&e.includes("featureAttribute")&&(t=t.vec4f(A.INSTANCEFEATUREATTRIBUTE)),r(e)&&e.includes("objectAndLayerIdColor")&&(t=t.vec4u8(A.OBJECTANDLAYERIDCOLOR_INSTANCED)),t}e([o({constructOnly:!0})],q.prototype,"symbol",void 0),e([o({constructOnly:!0})],q.prototype,"optionalFields",void 0),e([o({constructOnly:!0})],q.prototype,"metadata",void 0),e([o({constructOnly:!0})],q.prototype,"shaderTransformation",void 0),e([o()],q.prototype,"_instanceData",void 0),e([o()],q.prototype,"_cycleStartIndex",void 0),e([o({readOnly:!0})],q.prototype,"_enableLevelSelection",null),e([o()],q.prototype,"_updateCyclesWithStaticCamera",void 0),e([o({readOnly:!0})],q.prototype,"running",null),q=e([c("esri.views.3d.webgl-engine.lib.lodRendering.LodRenderer")],q);const z=m(),W=p(),K=l(),Y=m(),J=m(),Q=[_(1,0,1,1),_(0,0,1,1),_(0,1,0,1),_(1,1,0,1),_(1,0,0,1)],Z=new M;export{q as LodRenderer};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import has from"../../../../core/has.js";import{isSome as e}from"../../../../core/maybe.js";import{s as t,c as r,n as a,b as s,l as i,g as o,e as n,t as h}from"../../../../chunks/vec3.js";import{c,f as l}from"../../../../chunks/vec3f64.js";import{ViewingMode as u}from"../../../ViewingMode.js";import{newLayout as m}from"../../support/buffer/InterleavedLayout.js";import{ShaderOutput as p}from"../core/shaderLibrary/ShaderOutput.js";import{NormalsDoubleSidedMode as d}from"../core/shaderLibrary/shading/Normals.glsl.js";import{PBRMode as f}from"../core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{CullFaceOptions as g}from"../lib/basicInterfaces.js";import{GLTextureMaterial as T}from"../lib/GLTextureMaterial.js";import{Material as _}from"../lib/Material.js";import{OITPolygonOffsetLimit as x}from"../lib/OrderIndependentTransparency.js";import{RenderSlot as b}from"../lib/RenderSlot.js";import{VertexAttribute as S}from"../lib/VertexAttribute.js";import{getVerticalOffsetObject3D as v}from"../lib/verticalOffsetUtils.js";import{DefaultBufferWriter as O}from"./DefaultBufferWriter.js";import{verticalOffsetAtDistance as w,intersectTriangleGeometry as M}from"./internal/MaterialUtil.js";import{DefaultMaterialTechnique as A,DefaultMaterialPassParameters as y}from"../shaders/DefaultMaterialTechnique.js";import{DefaultMaterialTechniqueConfiguration as C}from"../shaders/DefaultMaterialTechniqueConfiguration.js";import{RealisticTreeTechnique as R}from"../shaders/RealisticTreeTechnique.js";class I extends _{constructor(e){super(e,j),this.supportsEdges=!0,this._configuration=new C,this._vertexBufferLayout=L(this.parameters)}isVisibleForOutput(e){return e!==p.Shadow&&e!==p.
|
|
5
|
+
import has from"../../../../core/has.js";import{isSome as e}from"../../../../core/maybe.js";import{s as t,c as r,n as a,b as s,l as i,g as o,e as n,t as h}from"../../../../chunks/vec3.js";import{c,f as l}from"../../../../chunks/vec3f64.js";import{ViewingMode as u}from"../../../ViewingMode.js";import{newLayout as m}from"../../support/buffer/InterleavedLayout.js";import{ShaderOutput as p}from"../core/shaderLibrary/ShaderOutput.js";import{NormalsDoubleSidedMode as d}from"../core/shaderLibrary/shading/Normals.glsl.js";import{PBRMode as f}from"../core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js";import{CullFaceOptions as g}from"../lib/basicInterfaces.js";import{GLTextureMaterial as T}from"../lib/GLTextureMaterial.js";import{Material as _}from"../lib/Material.js";import{OITPolygonOffsetLimit as x}from"../lib/OrderIndependentTransparency.js";import{RenderSlot as b}from"../lib/RenderSlot.js";import{VertexAttribute as S}from"../lib/VertexAttribute.js";import{getVerticalOffsetObject3D as v}from"../lib/verticalOffsetUtils.js";import{DefaultBufferWriter as O}from"./DefaultBufferWriter.js";import{verticalOffsetAtDistance as w,intersectTriangleGeometry as M}from"./internal/MaterialUtil.js";import{DefaultMaterialTechnique as A,DefaultMaterialPassParameters as y}from"../shaders/DefaultMaterialTechnique.js";import{DefaultMaterialTechniqueConfiguration as C}from"../shaders/DefaultMaterialTechniqueConfiguration.js";import{RealisticTreeTechnique as R}from"../shaders/RealisticTreeTechnique.js";class I extends _{constructor(e){super(e,j),this.supportsEdges=!0,this._configuration=new C,this._vertexBufferLayout=L(this.parameters)}isVisibleForOutput(e){return e!==p.Shadow&&e!==p.ShadowExcludeHighlight&&e!==p.ShadowHighlight||this.parameters.castShadows}isVisible(){const t=this.parameters;if(!super.isVisible()||0===t.layerOpacity)return!1;const{instanced:r,hasVertexColors:a,hasSymbolColors:s,vvColorEnabled:i}=t,o=e(r)&&r.includes("color"),n="replace"===t.colorMixMode,h=t.opacity>0,c=t.externalColor&&t.externalColor[3]>0;return a&&(o||i||s)?!!n||h:a?n?c:h:o||i||s?!!n||h:n?c:h}getConfiguration(t,r){return this._configuration.output=t,this._configuration.hasNormalTexture=!!this.parameters.normalTextureId,this._configuration.hasColorTexture=!!this.parameters.textureId,this._configuration.hasVertexTangents=this.parameters.hasVertexTangents,this._configuration.instanced=!!this.parameters.instanced,this._configuration.instancedDoublePrecision=this.parameters.instancedDoublePrecision,this._configuration.vvSize=this.parameters.vvSizeEnabled,this._configuration.hasVerticalOffset=e(this.parameters.verticalOffset),this._configuration.hasScreenSizePerspective=e(this.parameters.screenSizePerspective),this._configuration.hasSlicePlane=this.parameters.hasSlicePlane,this._configuration.hasSliceHighlight=this.parameters.hasSliceHighlight,this._configuration.alphaDiscardMode=this.parameters.textureAlphaMode,this._configuration.normalType=this.parameters.normalType,this._configuration.transparent=this.parameters.transparent,this._configuration.writeDepth=this.parameters.writeDepth,e(this.parameters.customDepthTest)&&(this._configuration.customDepthTest=this.parameters.customDepthTest),this._configuration.hasOccludees=this.parameters.hasOccludees,this._configuration.cullFace=this.parameters.hasSlicePlane?g.None:this.parameters.cullFace,this._configuration.hasMultipassTerrain=r.multipassTerrain.enabled,this._configuration.cullAboveGround=r.multipassTerrain.cullAboveGround,this._configuration.hasModelTransformation=e(this.parameters.modelTransformation),t!==p.Color&&t!==p.Alpha||(this._configuration.hasVertexColors=this.parameters.hasVertexColors,this._configuration.hasSymbolColors=this.parameters.hasSymbolColors,this.parameters.treeRendering?this._configuration.doubleSidedMode=d.WindingOrder:this._configuration.doubleSidedMode=this.parameters.doubleSided&&"normal"===this.parameters.doubleSidedType?d.View:this.parameters.doubleSided&&"winding-order"===this.parameters.doubleSidedType?d.WindingOrder:d.None,this._configuration.instancedColor=e(this.parameters.instanced)&&this.parameters.instanced.includes("color"),this._configuration.receiveShadows=this.parameters.receiveShadows&&this.parameters.shadowMappingEnabled,this._configuration.receiveAmbientOcclusion=!!r.ssaoHelper.enabled&&this.parameters.receiveSSAO,this._configuration.vvColor=this.parameters.vvColorEnabled,this._configuration.textureAlphaPremultiplied=!!this.parameters.textureAlphaPremultiplied,this._configuration.pbrMode=this.parameters.usePBR?this.parameters.isSchematic?f.Schematic:f.Normal:f.Disabled,this._configuration.hasMetallicRoughnessTexture=!!this.parameters.metallicRoughnessTextureId,this._configuration.hasEmissionTexture=!!this.parameters.emissiveTextureId,this._configuration.hasOcclusionTexture=!!this.parameters.occlusionTextureId,this._configuration.offsetBackfaces=!(!this.parameters.transparent||!this.parameters.offsetTransparentBackfaces),this._configuration.transparencyPassType=r.transparencyPassType,this._configuration.enableOffset=r.camera.relativeElevation<x,this._configuration.snowCover=this.hasSnowCover(r),this._configuration.hasColorTextureTransform=!!this.parameters.colorTextureTransformMatrix,this._configuration.hasNormalTextureTransform=!!this.parameters.normalTextureTransformMatrix,this._configuration.hasEmissionTextureTransform=!!this.parameters.emissiveTextureTransformMatrix,this._configuration.hasOcclusionTextureTransform=!!this.parameters.occlusionTextureTransformMatrix,this._configuration.hasMetallicRoughnessTextureTransform=!!this.parameters.metallicRoughnessTextureTransformMatrix),this._configuration}hasSnowCover(t){return e(t.weather)&&t.weatherVisible&&"snowy"===t.weather.type&&"enabled"===t.weather.snowCover}intersect(c,l,m,p,d,f){if(e(this.parameters.verticalOffset)){const e=m.camera;t(z,l[12],l[13],l[14]);let c=null;switch(m.viewingMode){case u.Global:c=a(B,z);break;case u.Local:c=r(B,N)}let f=0;const g=s(G,z,e.eye),T=i(g),_=o(g,g,1/T);let x=null;this.parameters.screenSizePerspective&&(x=n(c,_)),f+=w(e,T,this.parameters.verticalOffset,x??0,this.parameters.screenSizePerspective),o(c,c,f),h(H,c,m.transform.inverseRotation),p=s(D,p,H),d=s(V,d,H)}M(c,m,p,d,v(m.verticalOffset),f)}requiresSlot(e,t){if(t===p.Color||t===p.Alpha||t===p.Depth||t===p.Normal||t===p.Shadow||t===p.ShadowHighlight||t===p.ShadowExcludeHighlight||t===p.Highlight||t===p.ObjectAndLayerIdColor){return e===(this.parameters.transparent?this.parameters.writeDepth?b.TRANSPARENT_MATERIAL:b.TRANSPARENT_DEPTH_WRITE_DISABLED_MATERIAL:b.OPAQUE_MATERIAL)||e===b.DRAPED_MATERIAL||t===p.ObjectAndLayerIdColor}return!1}createGLMaterial(e){return new E(e)}createBufferWriter(){return new O(this._vertexBufferLayout)}}class E extends T{constructor(e){super({...e,...e.material.parameters})}_updateShadowState(e){e.shadowMap.enabled!==this._material.parameters.shadowMappingEnabled&&this._material.setParameters({shadowMappingEnabled:e.shadowMap.enabled})}_updateOccludeeState(e){e.hasOccludees!==this._material.parameters.hasOccludees&&this._material.setParameters({hasOccludees:e.hasOccludees})}beginSlot(e){this._output!==p.Color&&this._output!==p.Alpha||(this._updateShadowState(e),this._updateOccludeeState(e));const r=this._material.parameters;this.updateTexture(r.textureId);const a=e.camera.viewInverseTransposeMatrix;return t(r.origin,a[3],a[7],a[11]),this._material.setParameters(this.textureBindParameters),this.ensureTechnique(r.treeRendering?R:A,e)}}class P extends y{constructor(){super(...arguments),this.initTextureTransparent=!1,this.treeRendering=!1,this.hasVertexTangents=!1}}const j=new P;function L(e){const t=m().vec3f(S.POSITION).vec3f(S.NORMAL),r=e.textureId||e.normalTextureId||e.metallicRoughnessTextureId||e.emissiveTextureId||e.occlusionTextureId;return e.hasVertexTangents&&t.vec4f(S.TANGENT),r&&t.vec2f(S.UV0),e.hasVertexColors&&t.vec4u8(S.COLOR),e.hasSymbolColors&&t.vec4u8(S.SYMBOLCOLOR),has("enable-feature:objectAndLayerId-rendering")&&t.vec4u8(S.OBJECTANDLAYERIDCOLOR),t}const D=c(),V=c(),N=l(0,0,1),B=c(),H=c(),z=c(),G=c();export{E as DefaultGLMaterial,I as DefaultMaterial,P as DefaultMaterialParameters};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{clamp as e}from"../../../../core/mathUtils.js";import{isNone as t}from"../../../../core/maybe.js";import{fromValues as r}from"../../../../geometry/support/aaBoundingBox.js";import{newLayout as i}from"../../support/buffer/InterleavedLayout.js";import{ShaderOutput as a}from"../core/shaderLibrary/ShaderOutput.js";import{NormalsDoubleSidedMode as s}from"../core/shaderLibrary/shading/Normals.glsl.js";import o from"../lib/GLMaterial.js";import{Material as n}from"../lib/Material.js";import{isPathGeometry as h}from"../lib/PathGeometry.js";import{RenderSlot as c}from"../lib/RenderSlot.js";import{VertexAttribute as u}from"../lib/VertexAttribute.js";import{DefaultBufferWriter as l}from"./DefaultBufferWriter.js";import{vertexAttributeLocations as d,PathTechniqueConfiguration as p,PathTechnique as m,PathPassParameters as f}from"./PathTechnique.js";import{intersectAabbInvDir as b}from"./internal/MaterialUtil.js";class S extends n{constructor(e){super(e,new v),this.supportsEdges=!0,this._vertexAttributeLocations=d,this._configuration=new p,this._vertexBufferLayout=S.getVertexBufferLayout()}getConfiguration(e,t){return this._configuration.output=e,this._configuration.vvSize=this.parameters.vvSizeEnabled,this._configuration.vvColor=this.parameters.vvColorEnabled,this._configuration.vvOpacity=this.parameters.vvOpacityEnabled,this._configuration.hasSlicePlane=this.parameters.hasSlicePlane,this._configuration.transparent=this.parameters.transparent,this._configuration.hasOccludees=this.parameters.hasOccludees,e!==a.Color&&e!==a.Alpha||(this._configuration.doubleSidedMode=this.parameters.doubleSided&&"normal"===this.parameters.doubleSidedType?s.View:this.parameters.doubleSided&&"winding-order"===this.parameters.doubleSidedType?s.WindingOrder:s.None,this._configuration.receiveShadows=this.parameters.receiveShadows,this._configuration.receiveAmbientOcclusion=!!t.ssaoHelper.enabled&&this.parameters.receiveSSAO),this._configuration.transparencyPassType=t.transparencyPassType,this._configuration.hasMultipassTerrain=t.multipassTerrain.enabled,this._configuration.cullAboveGround=t.multipassTerrain.cullAboveGround,this._configuration}isVisibleForOutput(e){return e!==a.Shadow&&e!==a.
|
|
5
|
+
import{clamp as e}from"../../../../core/mathUtils.js";import{isNone as t}from"../../../../core/maybe.js";import{fromValues as r}from"../../../../geometry/support/aaBoundingBox.js";import{newLayout as i}from"../../support/buffer/InterleavedLayout.js";import{ShaderOutput as a}from"../core/shaderLibrary/ShaderOutput.js";import{NormalsDoubleSidedMode as s}from"../core/shaderLibrary/shading/Normals.glsl.js";import o from"../lib/GLMaterial.js";import{Material as n}from"../lib/Material.js";import{isPathGeometry as h}from"../lib/PathGeometry.js";import{RenderSlot as c}from"../lib/RenderSlot.js";import{VertexAttribute as u}from"../lib/VertexAttribute.js";import{DefaultBufferWriter as l}from"./DefaultBufferWriter.js";import{vertexAttributeLocations as d,PathTechniqueConfiguration as p,PathTechnique as m,PathPassParameters as f}from"./PathTechnique.js";import{intersectAabbInvDir as b}from"./internal/MaterialUtil.js";class S extends n{constructor(e){super(e,new v),this.supportsEdges=!0,this._vertexAttributeLocations=d,this._configuration=new p,this._vertexBufferLayout=S.getVertexBufferLayout()}getConfiguration(e,t){return this._configuration.output=e,this._configuration.vvSize=this.parameters.vvSizeEnabled,this._configuration.vvColor=this.parameters.vvColorEnabled,this._configuration.vvOpacity=this.parameters.vvOpacityEnabled,this._configuration.hasSlicePlane=this.parameters.hasSlicePlane,this._configuration.transparent=this.parameters.transparent,this._configuration.hasOccludees=this.parameters.hasOccludees,e!==a.Color&&e!==a.Alpha||(this._configuration.doubleSidedMode=this.parameters.doubleSided&&"normal"===this.parameters.doubleSidedType?s.View:this.parameters.doubleSided&&"winding-order"===this.parameters.doubleSidedType?s.WindingOrder:s.None,this._configuration.receiveShadows=this.parameters.receiveShadows,this._configuration.receiveAmbientOcclusion=!!t.ssaoHelper.enabled&&this.parameters.receiveSSAO),this._configuration.transparencyPassType=t.transparencyPassType,this._configuration.hasMultipassTerrain=t.multipassTerrain.enabled,this._configuration.cullAboveGround=t.multipassTerrain.cullAboveGround,this._configuration}isVisibleForOutput(e){return e!==a.Shadow&&e!==a.ShadowExcludeHighlight&&e!==a.ShadowHighlight||this.parameters.castShadows}isVisible(){return super.isVisible()&&this.parameters.opacity>0}intersect(i,a,s,o,n,c){const u=i;if(!h(u))return;const l=u.path,d=[this.parameters.size[0],this.parameters.size[1]];if(this.parameters.vvSizeEnabled){const t=this.parameters.vvSizeOffset,r=this.parameters.vvSizeFactor,i=this.parameters.vvSizeMinSize,a=this.parameters.vvSizeMaxSize,s=l.sizeAttributeValue;d[0]*=e(t[0]+s*r[0],i[0],a[0]),d[1]*=e(t[2]+s*r[2],i[2],a[2])}const p=Math.max(d[0],d[1]),m=i.boundingInfo;if(t(m))return void this._intersectTriangles(l,d,o,n,c);const f=r(m.bbMin[0]-p,m.bbMin[1]-p,m.bbMin[2]-p,m.bbMax[0]+p,m.bbMax[1]+p,m.bbMax[2]+p),S=[n[0]-o[0],n[1]-o[1],n[2]-o[2]],g=Math.sqrt(S[0]*S[0]+S[1]*S[1]+S[2]*S[2]),v=[g/S[0],g/S[1],g/S[2]];b(f,o,v,s.tolerance)&&this._intersectTriangles(l,d,o,n,c)}_intersectTriangles(e,t,r,i,a){e.baked.size&&e.baked.size[0]===t[0]&&e.baked.size[1]===t[1]||e.baked.bake(t),e.baked.intersect(r,i,a)}createBufferWriter(){return new l(this._vertexBufferLayout)}requiresSlot(e,t){switch(t){case a.Shadow:case a.ShadowHighlight:case a.ShadowExcludeHighlight:if(!this.parameters.castShadows)return!1;case a.Color:case a.Alpha:case a.Depth:case a.Normal:case a.Highlight:case a.ObjectAndLayerIdColor:return e===(this.parameters.transparent?c.TRANSPARENT_MATERIAL:c.OPAQUE_MATERIAL)||e===c.DRAPED_MATERIAL;default:return!1}}createGLMaterial(e){return new g(e)}static getVertexBufferLayout(){return i().vec3f(u.POSITION).vec4f(u.PROFILERIGHT).vec4f(u.PROFILEUP).vec4f(u.PROFILEVERTEXANDNORMAL).vec4f(u.FEATUREVALUE)}}class g extends o{_updateOccludeeState(e){e.hasOccludees!==this._material.parameters.hasOccludees&&this._material.setParameters({hasOccludees:e.hasOccludees})}_updateShadowState(e){(t(this.technique)||e.shadowMap.enabled!==this.technique.configuration.receiveShadows)&&this._material.setParameters({receiveShadows:e.shadowMap.enabled})}beginSlot(e){return this._output!==a.Color&&this._output!==a.Alpha||(this._updateShadowState(e),this._updateOccludeeState(e)),this.ensureTechnique(m,e)}}class v extends f{constructor(){super(...arguments),this.doubleSided=!1,this.doubleSidedType="normal",this.receiveSSAO=!0,this.receiveShadows=!1,this.castShadows=!0,this.hasSlicePlane=!1,this.transparent=!1,this.hasOccludees=!1}}export{S as PathMaterial,v as PathMaterialParameters};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{removeUnordered as e,filterInPlace as t}from"../../../../../core/arrayUtils.js";import{someMap as r}from"../../../../../core/MapUtils.js";import{isNone as s,isSome as i}from"../../../../../core/maybe.js";import{NestedMap as a}from"../../../../../core/NestedMap.js";import o from"../../../../../core/PooledArray.js";import{m as n,a as l,t as h}from"../../../../../chunks/mat4.js";import{c as u}from"../../../../../chunks/mat4f64.js";import{glLayout as f}from"../../../support/buffer/glUtil.js";import{ShaderOutput as c}from"../../core/shaderLibrary/ShaderOutput.js";import{GLMaterials as m}from"../../lib/GLMaterials.js";import{RenderOccludedFlag as d}from"../../lib/Material.js";import{DirtyState as g}from"../../lib/ModelDirtyTypes.js";import{assert as p,setMatrixTranslation3 as y}from"../../lib/Util.js";import{DrawParameters as _}from"../DrawParameters.js";import{WaterMaterial as v}from"../WaterMaterial.js";import{BufferRange as w,mergeAdjacentRanges as b}from"./BufferRange.js";import{Instance as O}from"./Instance.js";import{PerBufferData as B,hasVao as C}from"./PerBufferData.js";import{PerOriginData as E}from"./PerOriginData.js";import{VaoCache as A}from"./VaoCache.js";class D{constructor(e,t,r){this._rctx=e,this._materialRepository=t,this.material=r,this._dataByOrigin=new Map,this._hasHighlights=!1,this._hasOccludees=!1,this._glMaterials=new m(this.material,this._materialRepository),this._bufferWriter=r.createBufferWriter(),this._vaoCache=new A(e,r.vertexAttributeLocations,f(this._bufferWriter.vertexBufferLayout))}dispose(){this._glMaterials.destroy(),this._dataByOrigin.forEach((e=>e.dispose())),this._dataByOrigin.clear(),this._vaoCache.dispose()}get isEmpty(){return 0===this._dataByOrigin.size}get hasHighlights(){return this._hasHighlights}get hasOccludees(){return this._hasOccludees}get hasWater(){return!this.isEmpty&&this.material instanceof v}get rendersOccluded(){return!this.isEmpty&&this.material.renderOccluded!==d.Occlude}get numGeometries(){let e=0;return this._dataByOrigin.forEach((t=>e+=t.buffers.reduce(((e,t)=>e+t.instances.size),0))),e}forEachGeometry(e){this._dataByOrigin.forEach((t=>t.buffers.forEach((t=>t.instances.forEach((t=>e(t.geometry)))))))}modify(e){this._updateGeometries(e.updates),this._addAndRemoveGeometries(e.adds,e.removes),this._updateDrawCommands()}_updateGeometries(e){const t=this._bufferWriter,r=t.vertexBufferLayout.stride/4;for(const i of e){const e=i.renderGeometry,a=this._dataByOrigin.get(e.localOrigin.id)?.findBuffer(e.id);if(s(a))return;const o=a.instances.get(e.id);if(i.updateType&(g.GEOMETRY|g.TRANSFORMATION)){const s=V(t.elementCount(o.geometry.geometry)*r),i=t.vertexBufferLayout.createView(s.buffer);this._writeGeometry(e,i,0),a.vao.vertexBuffers.geometry.setSubData(s,o.from*r,0,o.numElements*r)}i.updateType&(g.HIGHLIGHT|g.OCCLUDEE|g.VISIBILITY)&&(a.drawCommandsDirty=!0)}}_computeDeltas(e,t){const r=new a;for(const i of e){const e=i.localOrigin;if(s(e))continue;let t=r.get(e.id,null);s(t)&&(t=new H(e.vec3),r.set(e.id,null,t)),t.changes.push(i)}for(const i of t){const e=i.localOrigin;if(s(e))continue;const t=this._dataByOrigin.get(e.id)?.findBuffer(i.id);if(s(t))continue;let a=r.get(e.id,t);s(a)&&(a=new H(e.vec3),r.set(e.id,t,a)),a.changes.push(i)}return r}_addAndRemoveGeometries(t,r){const{_bufferWriter:a,_dataByOrigin:o}=this,n=a.vertexBufferLayout.stride/4,l=this._computeDeltas(t,r);l.forEach(((t,r)=>{const h=t.get(null),u=i(h)?h.changes:[];l.delete(r,null);let f=o.get(r);if(t.forEach(((t,i)=>{if(l.delete(r,i),s(i))return void p(!1,"No VAO for removed geometries");if(i.instances.size===t.changes.length)return this._vaoCache.deleteVao(i.vao),e(f.buffers,i),void(0===f.buffers.length&&0===u.length&&o.delete(r));const h=i.numElements,c=i.vao.size/4,m=u.reduce(((e,t)=>e+a.elementCount(t.geometry)),0),d=t.changes.reduce(((e,t)=>e+a.elementCount(t.geometry)),0),g=Math.min((h+m-d)*n,W),y=g>c;g>L&&g<c/2?(t.changes.forEach((({id:e})=>i.deleteInstance(e))),i.instances.forEach((({geometry:e})=>u.push(e))),this._vaoCache.deleteVao(i.vao),e(f.buffers,i)):y?this._applyAndRebuild(i,u,t):this._applyRemoves(i,t)})),u.length>0)for(s(f)&&(f=new E(h.origin),o.set(r,f)),f.buffers.forEach((e=>this._applyAdds(e,u)));u.length>0;)f.buffers.push(this._applyAndRebuild(new B,u,null))}))}_updateDrawCommands(){this._hasHighlights=!1,this._hasOccludees=!1,this._dataByOrigin.forEach((e=>{e.buffers.forEach((e=>{e.drawCommandsDirty&&(e.hasHiddenInstances=!1,e.hasHighlights=!1,e.hasOccludees=!1,r(e.instances,(t=>(e.updateDrawState(t),e.hasHiddenInstances&&e.hasHighlights&&e.hasOccludees))),e.updateDrawCommands(this._bufferWriter.vertexBufferLayout.stride)),this._hasHighlights=this._hasHighlights||e.hasHighlights,this._hasOccludees=this._hasOccludees||e.hasOccludees}))}))}_applyAndRebuild(e,t,r){if(i(r))for(const i of r.changes)e.deleteInstance(i.id);const s=this._bufferWriter,a=s.vertexBufferLayout.stride,o=a/4,n=Math.floor(W/o);let l=e.numElements;for(;t.length>0;){const r=t.pop(),i=s.elementCount(r.geometry);if(l+i>n&&l>0){t.push(r);break}l+=i;const a=new O(r,0,0);p(null==e.instances.get(r.id)),e.addInstance(r.id,a)}const h=l*o,u=V(h),f=s.vertexBufferLayout.createView(u.buffer);let c=0;e.hasHiddenInstances=!1,e.hasHighlights=!1,e.hasOccludees=!1,e.instances.forEach(((t,r)=>{this._writeGeometry(t.geometry,f,c);const i=c;c+=s.elementCount(t.geometry.geometry),e.updateInstance(r,i,c),e.updateDrawState(t)})),this._vaoCache.deleteVao(e.vao),e.vao=this._vaoCache.newVao(z(h)),e.vao.vertexBuffers.geometry.setSubData(u,0,0,c*o),e.holes.clear();const m=e.holes.pushNew();return m.from=c,m.to=Math.floor(e.vao.size/a),e.updateDrawCommands(a),e}_applyRemoves(e,t){if(0===t.changes.length)return;for(const o of t.changes){const t=o.id,r=e.instances.get(t);if(!r)continue;e.deleteInstance(t);const s=I.back();if(s){if(s.to===r.from){s.to=r.to;continue}if(s.from===r.to){s.from=r.from;continue}}const i=I.pushNew();i.from=r.from,i.to=r.to}b(I);const r=this._bufferWriter.vertexBufferLayout.stride/4,s=I.reduce(((e,t)=>Math.max(e,t.numElements)),0)*r,i=V(s);i.fill(0,0,s);const a=e.vao.vertexBuffers.geometry;I.forAll((e=>a.setSubData(i,e.from*r,0,e.numElements*r))),e.holes.pushArray(I.data,I.length),I.forAll(((e,t)=>I.data[t]=null)),I.clear(),e.drawCommandsDirty=!0}_applyAdds(e,r){if(0===r.length)return;if(!C(e))return void this._applyAndRebuild(e,r,null);const i=this._bufferWriter,a=i.vertexBufferLayout.stride/4,o=e.numElements,n=r.reduce(((e,t)=>e+i.elementCount(t.geometry)),0),l=Math.min((o+n)*a,W),h=4*l;if(e.vao.size<z(W-L)&&h>e.vao.size)return void this._applyAndRebuild(e,r,null);b(e.holes);const u=new Array;for(const t of r){const r=i.elementCount(t.geometry),s=M(e.holes,r);u.push(s)}const f=e.vao.vertexBuffers.geometry;let c=0,m=0,d=0;const g=V(l),y=i.vertexBufferLayout.createView(g.buffer);r.forEach(((t,r)=>{const o=u[r];if(s(o))return;if(!(d===o)){const e=d-m;e>0&&f.setSubData(g,m*a,0,e*a),m=o,c=0}const n=i.elementCount(t.geometry);this._writeGeometry(t,y,c),c+=n,d=o+n;const l=new O(t,o,o+n);p(null==e.instances.get(t.id)),e.addInstance(t.id,l),e.drawCommandsDirty=!0}));const _=d-m;_>0&&f.setSubData(g,m*a,0,_*a),t(r,((e,t)=>s(u[t])))}_writeGeometry(e,t,r){const s=e.localOrigin.vec3;y(x,-s[0],-s[1],-s[2]);const a=i(e.transformation)?n(j,x,e.transformation):x;l(S,a),h(S,S),this._bufferWriter.write(a,S,e.geometry,t,r)}updateAnimation(e){return this.material.update(e)}requiresSlot(e,t){return this.material.requiresSlot(e,t)}render(e,t){if(!this.requiresSlot(t.slot,e))return!1;const r=e===c.Highlight||e===c.ShadowHighlight;if(r&&!this._hasHighlights)return!1;const a=e===c.
|
|
5
|
+
import{removeUnordered as e,filterInPlace as t}from"../../../../../core/arrayUtils.js";import{someMap as r}from"../../../../../core/MapUtils.js";import{isNone as s,isSome as i}from"../../../../../core/maybe.js";import{NestedMap as a}from"../../../../../core/NestedMap.js";import o from"../../../../../core/PooledArray.js";import{m as n,a as l,t as h}from"../../../../../chunks/mat4.js";import{c as u}from"../../../../../chunks/mat4f64.js";import{glLayout as f}from"../../../support/buffer/glUtil.js";import{ShaderOutput as c}from"../../core/shaderLibrary/ShaderOutput.js";import{GLMaterials as m}from"../../lib/GLMaterials.js";import{RenderOccludedFlag as d}from"../../lib/Material.js";import{DirtyState as g}from"../../lib/ModelDirtyTypes.js";import{assert as p,setMatrixTranslation3 as y}from"../../lib/Util.js";import{DrawParameters as _}from"../DrawParameters.js";import{WaterMaterial as v}from"../WaterMaterial.js";import{BufferRange as w,mergeAdjacentRanges as b}from"./BufferRange.js";import{Instance as O}from"./Instance.js";import{PerBufferData as B,hasVao as C}from"./PerBufferData.js";import{PerOriginData as E}from"./PerOriginData.js";import{VaoCache as A}from"./VaoCache.js";class D{constructor(e,t,r){this._rctx=e,this._materialRepository=t,this.material=r,this._dataByOrigin=new Map,this._hasHighlights=!1,this._hasOccludees=!1,this._glMaterials=new m(this.material,this._materialRepository),this._bufferWriter=r.createBufferWriter(),this._vaoCache=new A(e,r.vertexAttributeLocations,f(this._bufferWriter.vertexBufferLayout))}dispose(){this._glMaterials.destroy(),this._dataByOrigin.forEach((e=>e.dispose())),this._dataByOrigin.clear(),this._vaoCache.dispose()}get isEmpty(){return 0===this._dataByOrigin.size}get hasHighlights(){return this._hasHighlights}get hasOccludees(){return this._hasOccludees}get hasWater(){return!this.isEmpty&&this.material instanceof v}get rendersOccluded(){return!this.isEmpty&&this.material.renderOccluded!==d.Occlude}get numGeometries(){let e=0;return this._dataByOrigin.forEach((t=>e+=t.buffers.reduce(((e,t)=>e+t.instances.size),0))),e}forEachGeometry(e){this._dataByOrigin.forEach((t=>t.buffers.forEach((t=>t.instances.forEach((t=>e(t.geometry)))))))}modify(e){this._updateGeometries(e.updates),this._addAndRemoveGeometries(e.adds,e.removes),this._updateDrawCommands()}_updateGeometries(e){const t=this._bufferWriter,r=t.vertexBufferLayout.stride/4;for(const i of e){const e=i.renderGeometry,a=this._dataByOrigin.get(e.localOrigin.id)?.findBuffer(e.id);if(s(a))return;const o=a.instances.get(e.id);if(i.updateType&(g.GEOMETRY|g.TRANSFORMATION)){const s=V(t.elementCount(o.geometry.geometry)*r),i=t.vertexBufferLayout.createView(s.buffer);this._writeGeometry(e,i,0),a.vao.vertexBuffers.geometry.setSubData(s,o.from*r,0,o.numElements*r)}i.updateType&(g.HIGHLIGHT|g.OCCLUDEE|g.VISIBILITY)&&(a.drawCommandsDirty=!0)}}_computeDeltas(e,t){const r=new a;for(const i of e){const e=i.localOrigin;if(s(e))continue;let t=r.get(e.id,null);s(t)&&(t=new H(e.vec3),r.set(e.id,null,t)),t.changes.push(i)}for(const i of t){const e=i.localOrigin;if(s(e))continue;const t=this._dataByOrigin.get(e.id)?.findBuffer(i.id);if(s(t))continue;let a=r.get(e.id,t);s(a)&&(a=new H(e.vec3),r.set(e.id,t,a)),a.changes.push(i)}return r}_addAndRemoveGeometries(t,r){const{_bufferWriter:a,_dataByOrigin:o}=this,n=a.vertexBufferLayout.stride/4,l=this._computeDeltas(t,r);l.forEach(((t,r)=>{const h=t.get(null),u=i(h)?h.changes:[];l.delete(r,null);let f=o.get(r);if(t.forEach(((t,i)=>{if(l.delete(r,i),s(i))return void p(!1,"No VAO for removed geometries");if(i.instances.size===t.changes.length)return this._vaoCache.deleteVao(i.vao),e(f.buffers,i),void(0===f.buffers.length&&0===u.length&&o.delete(r));const h=i.numElements,c=i.vao.size/4,m=u.reduce(((e,t)=>e+a.elementCount(t.geometry)),0),d=t.changes.reduce(((e,t)=>e+a.elementCount(t.geometry)),0),g=Math.min((h+m-d)*n,W),y=g>c;g>L&&g<c/2?(t.changes.forEach((({id:e})=>i.deleteInstance(e))),i.instances.forEach((({geometry:e})=>u.push(e))),this._vaoCache.deleteVao(i.vao),e(f.buffers,i)):y?this._applyAndRebuild(i,u,t):this._applyRemoves(i,t)})),u.length>0)for(s(f)&&(f=new E(h.origin),o.set(r,f)),f.buffers.forEach((e=>this._applyAdds(e,u)));u.length>0;)f.buffers.push(this._applyAndRebuild(new B,u,null))}))}_updateDrawCommands(){this._hasHighlights=!1,this._hasOccludees=!1,this._dataByOrigin.forEach((e=>{e.buffers.forEach((e=>{e.drawCommandsDirty&&(e.hasHiddenInstances=!1,e.hasHighlights=!1,e.hasOccludees=!1,r(e.instances,(t=>(e.updateDrawState(t),e.hasHiddenInstances&&e.hasHighlights&&e.hasOccludees))),e.updateDrawCommands(this._bufferWriter.vertexBufferLayout.stride)),this._hasHighlights=this._hasHighlights||e.hasHighlights,this._hasOccludees=this._hasOccludees||e.hasOccludees}))}))}_applyAndRebuild(e,t,r){if(i(r))for(const i of r.changes)e.deleteInstance(i.id);const s=this._bufferWriter,a=s.vertexBufferLayout.stride,o=a/4,n=Math.floor(W/o);let l=e.numElements;for(;t.length>0;){const r=t.pop(),i=s.elementCount(r.geometry);if(l+i>n&&l>0){t.push(r);break}l+=i;const a=new O(r,0,0);p(null==e.instances.get(r.id)),e.addInstance(r.id,a)}const h=l*o,u=V(h),f=s.vertexBufferLayout.createView(u.buffer);let c=0;e.hasHiddenInstances=!1,e.hasHighlights=!1,e.hasOccludees=!1,e.instances.forEach(((t,r)=>{this._writeGeometry(t.geometry,f,c);const i=c;c+=s.elementCount(t.geometry.geometry),e.updateInstance(r,i,c),e.updateDrawState(t)})),this._vaoCache.deleteVao(e.vao),e.vao=this._vaoCache.newVao(z(h)),e.vao.vertexBuffers.geometry.setSubData(u,0,0,c*o),e.holes.clear();const m=e.holes.pushNew();return m.from=c,m.to=Math.floor(e.vao.size/a),e.updateDrawCommands(a),e}_applyRemoves(e,t){if(0===t.changes.length)return;for(const o of t.changes){const t=o.id,r=e.instances.get(t);if(!r)continue;e.deleteInstance(t);const s=I.back();if(s){if(s.to===r.from){s.to=r.to;continue}if(s.from===r.to){s.from=r.from;continue}}const i=I.pushNew();i.from=r.from,i.to=r.to}b(I);const r=this._bufferWriter.vertexBufferLayout.stride/4,s=I.reduce(((e,t)=>Math.max(e,t.numElements)),0)*r,i=V(s);i.fill(0,0,s);const a=e.vao.vertexBuffers.geometry;I.forAll((e=>a.setSubData(i,e.from*r,0,e.numElements*r))),e.holes.pushArray(I.data,I.length),I.forAll(((e,t)=>I.data[t]=null)),I.clear(),e.drawCommandsDirty=!0}_applyAdds(e,r){if(0===r.length)return;if(!C(e))return void this._applyAndRebuild(e,r,null);const i=this._bufferWriter,a=i.vertexBufferLayout.stride/4,o=e.numElements,n=r.reduce(((e,t)=>e+i.elementCount(t.geometry)),0),l=Math.min((o+n)*a,W),h=4*l;if(e.vao.size<z(W-L)&&h>e.vao.size)return void this._applyAndRebuild(e,r,null);b(e.holes);const u=new Array;for(const t of r){const r=i.elementCount(t.geometry),s=M(e.holes,r);u.push(s)}const f=e.vao.vertexBuffers.geometry;let c=0,m=0,d=0;const g=V(l),y=i.vertexBufferLayout.createView(g.buffer);r.forEach(((t,r)=>{const o=u[r];if(s(o))return;if(!(d===o)){const e=d-m;e>0&&f.setSubData(g,m*a,0,e*a),m=o,c=0}const n=i.elementCount(t.geometry);this._writeGeometry(t,y,c),c+=n,d=o+n;const l=new O(t,o,o+n);p(null==e.instances.get(t.id)),e.addInstance(t.id,l),e.drawCommandsDirty=!0}));const _=d-m;_>0&&f.setSubData(g,m*a,0,_*a),t(r,((e,t)=>s(u[t])))}_writeGeometry(e,t,r){const s=e.localOrigin.vec3;y(x,-s[0],-s[1],-s[2]);const a=i(e.transformation)?n(j,x,e.transformation):x;l(S,a),h(S,S),this._bufferWriter.write(a,S,e.geometry,t,r)}updateAnimation(e){return this.material.update(e)}requiresSlot(e,t){return this.material.requiresSlot(e,t)}render(e,t){if(!this.requiresSlot(t.slot,e))return!1;const r=e===c.Highlight||e===c.ShadowHighlight;if(r&&!this._hasHighlights)return!1;const a=e===c.ShadowExcludeHighlight,o=!(r||a),n=this._rctx;let l;const h=()=>{if(i(l))return l;const r=this._glMaterials.load(n,t.slot,e);return s(r)?null:(l=r.beginSlot(t),s(l)?null:(n.bindTechnique(l,this.material.parameters,t),l))};for(const i of this._dataByOrigin.values())for(const e of i.buffers){if(r&&!e.hasHighlights)continue;const l=(r?e.drawCommandsHighlight:a&&e.needsMultipleCommands()?e.drawCommandsShadowHighlightRest:e.drawCommandsDefault)||null,u=o&&e.drawCommandsOccludees||null;if(l?.length||u?.length){const r=h();if(s(r))return!1;r.program.bindDraw(new _(i.origin),t,this.material.parameters),r.ensureAttributeLocations(e.vao),n.bindVAO(e.vao),l?.length&&(r.bindPipelineState(n,t.slot,!1),l.forAll((e=>n.drawArrays(r.primitiveType,e.first,e.count)))),u?.length&&(r.bindPipelineState(n,t.slot,!0),u.forAll((e=>n.drawArrays(r.primitiveType,e.first,e.count))))}}return i(l)}get test(){return{material:this.material,glMaterials:this._glMaterials,dataByOrigin:this._dataByOrigin}}}class H{constructor(e){this.origin=e,this.changes=new Array}}function M(e,t){let r;if(!e.some((e=>!(e.numElements<t)&&(r=e,!0))))return null;const s=r.from;return r.from+=t,r.from>=r.to&&e.removeUnordered(r),s}const x=u(),j=u(),S=u(),I=new o({allocator:e=>e||new w,deallocator:null}),L=65536,R=4*L,G=16777216,W=G/4;let T=new Float32Array(L);function V(e){return T.length<e&&(T=new Float32Array(e)),T}function z(e){const t=4*e;return t<R?R:Math.max(Math.min(Math.ceil(1.5*t/R)*R,G),t)}export{D as MergedRenderer};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import r from"../../../../core/Evented.js";import has from"../../../../core/has.js";import i from"../../../../core/Logger.js";import{removeMaybe as s,destroyMaybe as o,isSome as n,isNone as a,unwrapOr as p}from"../../../../core/maybe.js";import{watch as d,initial as h}from"../../../../core/reactiveUtils.js";import{addFrameTask as c}from"../../../../core/scheduling.js";import{property as l}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/accessorSupport/ensureType.js";import"../../../../core/arrayUtils.js";import{subclass as m}from"../../../../core/accessorSupport/decorators/subclass.js";import{ComponentObjectCollection as u}from"../collections/Component/ComponentObjectCollection.js";import{ShaderTechniqueRepository as _}from"../core/shaderTechnique/ShaderTechniqueRepository.js";import{RenderRequestType as y,Decorations as f}from"../lib/basicInterfaces.js";import g from"../lib/CompositingHelper.js";import{textureToDepth as R}from"../lib/depthRangeUtils.js";import{GLMaterialRepository as x}from"../lib/GLMaterialRepository.js";import{MagnifierHelper as b}from"../lib/MagnifierHelper.js";import{ObjectAndLayerIdRenderHelper as v}from"../lib/ObjectAndLayerIdRenderHelper.js";import{Renderer as j}from"../lib/Renderer.js";import{RenderingContext as w}from"../lib/RenderingContext.js";import{TextureRepository as A}from"../lib/TextureRepository.js";import{StippleTextureRepository as C}from"../materials/StippleTextureRepository.js";import{WaterTextureRepository as T}from"../materials/internal/WaterTextureRepository.js";import{getContextCache as U}from"./contextCache.js";import{removeLoadedShaderModules as D}from"./requireUtils.js";import{ScreenshotManager as O,ScreenshotContext as q}from"./ScreenshotManager.js";import{contextCache as M}from"./testUtils.js";import{RenderState as S}from"../../../support/RenderState.js";import{createContextOrErrorHTML as L}from"../../../webgl/context-util.js";let H=class extends t{constructor(e){super({}),this.events=new r,this.waterTextureRepository=new T,this._magnifierHelper=new b,this.objectAndLayerIdRenderHelper=has("enable-feature:objectAndLayerId-rendering")?new v:null,this._needsUpdate=!0,this._needsRender=!0,this._idleSuspend=!0,this._needsWaterReflectionUpdate=!1,this._lastAnimationUpdate=0,this._container=e.container,this._viewingMode=e.viewingMode,this._initializeContext(e),d((()=>this.waterTextureRepository?.updating),(()=>this.requestRender()),h),this._magnifierHelper.events.on("request-render",(()=>this.requestRender())),this._stippleTextureRepository=new C(this._rctx),this._shaderTechniqueRepository=new _({rctx:this._rctx,viewingMode:e.viewingMode,stippleTextureRepository:this._stippleTextureRepository,waterTextureRepository:this.waterTextureRepository}),this._textureRepository=new A(e,this._shaderTechniqueRepository,this._rctx),this._textureRepository.events.on("changed",(e=>this.requestRender(e))),this._materialRepository=new x(this._textureRepository,this._shaderTechniqueRepository,(()=>this.requestRender()),(()=>this.requestRender())),this._compositingHelper=new g(this._rctx,this._shaderTechniqueRepository),this.renderer=new j(this._materialRepository,this._textureRepository,this._shaderTechniqueRepository,this._rctx,this._compositingHelper,this._magnifierHelper,(e=>this.requestRender(e)),e);const t={renderScene:(e,t,r,i,s)=>this.renderer.render(e,t,{camera:r,contentCamera:r,mode:S.IDLE},i,s),requestRenderScene:e=>this.requestRender(e),prepareOverlay:()=>e.options.screenshot.prepareOverlay(),renderOverlay:(t,r)=>e.options.screenshot.renderOverlay(t,r)};this._screenshotManager=new O(this._rctx,t,(e=>this.events.emit("force-camera-for-screenshot",e)),(()=>this.renderer.disposeOffscreenBuffers())),this._registerFrameTask(e)}normalizeCtorArgs(){return{}}destroy(){this._container.contains(this._canvas)&&this._container.removeChild(this._canvas),this._frameTask=s(this._frameTask),this._shaderTechniqueRepository=o(this._shaderTechniqueRepository)}get performanceInfo(){const e=this._rctx.gl;return{renderer:this.renderer.performanceInfo,textureMemory:void 0!==e.getUsedTextureMemory?e.getUsedTextureMemory():void 0,renderbufferMemory:void 0!==e.getUsedRenderbufferMemory?e.getUsedRenderbufferMemory():void 0,VBOMemory:void 0!==e.getUsedVBOMemory?e.getUsedVBOMemory():void 0}}requestRender(e=y.UPDATE){this._needsRender=!0,e===y.UPDATE&&(this._needsUpdate=!0)}get updating(){return this._needsUpdate||this._needsWaterReflectionUpdate||this.renderer.updating||this._textureRepository.updating||this.waterTextureRepository.updating||this._magnifierHelper.updating}get textureRepository(){return this._textureRepository}get compositingHelper(){return this._compositingHelper}set magnifier(e){this._magnifierHelper.magnifier=e}setIdleSuspend(e){this._idleSuspend!==e&&(this._idleSuspend=e,this.requestRender())}get renderingContext(){return this._rctx}get capabilities(){return this._rctx.capabilities}get canvas(){return this._canvas}takeScreenshot(e){return this._screenshotManager.takeScreenshot(e).then((e=>e[0]))}takeScreenshotWithOID(e){return e.objectAndLayerIdColor=!0,this._screenshotManager.takeScreenshot(e)}getAlpha(){return!!this._rctx.contextAttributes.alpha}getMinimalDepthForArea(e,t,r,i,s,o=s){const a=i.constrainWindowSize(t,r,s*i.pixelRatio,o*i.pixelRatio),p=this._ensureDepthBuffer(a);this.renderer.readDepthPixels(i,a,p);let d=Number.MAX_VALUE;for(let n=0;n<a[2]*a[3];n++){const e=R(4*n,p,i.nearFar);d>e&&e!==i.nearFar[0]&&e!==i.nearFar[1]&&(d=e)}if(n(e)){const s=e.pickDepth(t*i.pixelRatio,r*i.pixelRatio,i);n(s)&&d>s&&s!==i.nearFar[0]&&s!==i.nearFar[1]&&(d=s)}return d===Number.MAX_VALUE?void 0:d}_ensureDepthBuffer(e){const t=4*e[2]*e[3];return(a(this._tmpDepthBuffer)||this._tmpDepthBuffer.byteLength<t)&&(this._tmpDepthBuffer=new Uint8Array(t)),this._tmpDepthBuffer}async reloadShaders(){D(),await this._shaderTechniqueRepository.reloadAll(),this.requestRender()}_registerFrameTask(e){const t=e.state;let r=!1,i=y.BACKGROUND,s=!1;const o={preRender:({time:s})=>{r=this.updating,i=this._needsUpdate?y.UPDATE:y.BACKGROUND,e.commitSyncLayers();(s-this._lastAnimationUpdate>this.renderer.animationTimestep||n(t.forcedAnimationTime)||r||this._needsRender)&&(s=p(t.forcedAnimationTime,s),this.renderer.updateAnimation({camera:t.camera,time:s})&&this.requestRender(y.BACKGROUND),this._lastAnimationUpdate=s)},render:({time:e})=>{if((this._needsRender||!this._idleSuspend||!this.renderer.isCameraFinal||this._needsWaterReflectionUpdate)&&t.camera.fullWidth>0&&t.camera.fullHeight>0){const r=this._needsUpdate&&this._idleSuspend&&this.renderer.isCameraFinal;this._needsRender=!1,this._needsUpdate=!1,this._needsWaterReflectionUpdate=!1,this.renderer.render(null,null,t,f.ON,e),s=!0,r&&this.renderer.hasWaterReflection&&(this.requestRender(y.BACKGROUND),this._needsWaterReflectionUpdate=!0)}},update:({time:e})=>{const r=new q(t.camera,this.renderer.hasSlicePlane||this._magnifierHelper.enabled);this._textureRepository.update(),this._screenshotManager.update(r,e)},finish:()=>{s&&(this.renderer.finish(t.mode===S.IDLE?i:y.UPDATE),s=!1)}};this._frameTask=c(o)}_initializeContext(e){const t=e.options;this._canvas=t.canvas,this._canvas||(this._canvas=document.createElement("canvas")),this._canvas.setAttribute("style","width: 100%; height:100%; display:block;");const r={alpha:t.alpha||!1,premultipliedAlpha:!0,antialias:!1,depth:!0,stencil:null==t.stencil||t.stencil,powerPreference:"high-performance",preserveDrawingBuffer:t.preserveDrawingBuffer??!1},s=L("3d",this._canvas,r);if(a(s)){const e=has("esri-force-webgl");i.getLogger(this.declaredClass).error(e)}else this._rctx=this._newRenderingContext(s,e),this._loadShaderOnlyExtensions(),!t.alpha&&this._rctx.contextAttributes.alpha&&i.getLogger(this.declaredClass).error("WebGL context has alpha channel even though no alpha channel was requested"),!this._rctx.contextAttributes.alpha&&has("safari")>=11&&(this._container.style.backgroundColor="black"),this._container.appendChild(this._canvas)}_newRenderingContext(e,t){const r={disabledExtensions:t.options.deactivatedWebGLExtensions||{},debugWebGLExtensions:t.options.debugWebGLExtensions||{},maxAnisotropy:8},i=(e,r)=>t.resourceController.memoryController.newCache(e,r);if(M.enabled){let t=B.get(e);return t?(t.configure(r),t.newCache=i,t.ref(),t):(t=new w(e,r,i),B.set(e,t),t.ref(),t)}return new w(e,r,i)}_loadShaderOnlyExtensions(){this._rctx.capabilities.enable("standardDerivatives"),this._rctx.capabilities.enable("shaderTextureLOD"),this._rctx.capabilities.enable("textureFloat")}getObjectAndLayerIdColor(e){return n(this.objectAndLayerIdRenderHelper)?this.objectAndLayerIdRenderHelper.getObjectAndLayerIdColor(e):null}get componentObjectCollection(){return a(this._componentObjectCollection)&&(this._componentObjectCollection=new u(this.renderer.renderPassManager,this._viewingMode)),this._componentObjectCollection}set componentObjectCollection(e){this._componentObjectCollection=e}};e([l({type:Boolean,readOnly:!0})],H.prototype,"updating",null),e([l({autoDestroy:!0})],H.prototype,"_rctx",void 0),e([l({autoDestroy:!0})],H.prototype,"_container",void 0),e([l({autoDestroy:!0})],H.prototype,"_canvas",void 0),e([l({autoDestroy:!0})],H.prototype,"_stippleTextureRepository",void 0),e([l({autoDestroy:!0})],H.prototype,"waterTextureRepository",void 0),e([l({autoDestroy:!0})],H.prototype,"_magnifierHelper",void 0),e([l({readOnly:!0})],H.prototype,"objectAndLayerIdRenderHelper",void 0),e([l({autoDestroy:!0})],H.prototype,"_textureRepository",void 0),e([l({autoDestroy:!0})],H.prototype,"_compositingHelper",void 0),e([l({autoDestroy:!0,readOnly:!0})],H.prototype,"renderer",void 0),e([l({autoDestroy:!0})],H.prototype,"_screenshotManager",void 0),e([l()],H.prototype,"componentObjectCollection",null),e([l({autoDestroy:!0})],H.prototype,"_componentObjectCollection",void 0),e([l()],H.prototype,"_needsUpdate",void 0),e([l()],H.prototype,"_needsWaterReflectionUpdate",void 0),H=e([m("esri.views.3d.webgl-engine.parts.RenderView")],H);const B=U();export{H as RenderView};
|
|
5
|
+
import{_ as e}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import r from"../../../../core/Evented.js";import has from"../../../../core/has.js";import i from"../../../../core/Logger.js";import{removeMaybe as s,destroyMaybe as o,isSome as n,isNone as a}from"../../../../core/maybe.js";import{watch as p,initial as d}from"../../../../core/reactiveUtils.js";import{addFrameTask as h}from"../../../../core/scheduling.js";import{Milliseconds as c}from"../../../../core/time.js";import{property as l}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/accessorSupport/ensureType.js";import"../../../../core/arrayUtils.js";import{subclass as m}from"../../../../core/accessorSupport/decorators/subclass.js";import{ComponentObjectCollection as u}from"../collections/Component/ComponentObjectCollection.js";import{ShaderTechniqueRepository as _}from"../core/shaderTechnique/ShaderTechniqueRepository.js";import{RenderRequestType as f,Decorations as y}from"../lib/basicInterfaces.js";import g from"../lib/CompositingHelper.js";import{textureToDepth as R}from"../lib/depthRangeUtils.js";import{GLMaterialRepository as x}from"../lib/GLMaterialRepository.js";import{MagnifierHelper as b}from"../lib/MagnifierHelper.js";import{UpdateParameters as v}from"../lib/Material.js";import{ObjectAndLayerIdRenderHelper as j}from"../lib/ObjectAndLayerIdRenderHelper.js";import{Renderer as w}from"../lib/Renderer.js";import{RenderingContext as T}from"../lib/RenderingContext.js";import{TextureRepository as A}from"../lib/TextureRepository.js";import{StippleTextureRepository as C}from"../materials/StippleTextureRepository.js";import{WaterTextureRepository as U}from"../materials/internal/WaterTextureRepository.js";import{getContextCache as D}from"./contextCache.js";import{removeLoadedShaderModules as O}from"./requireUtils.js";import{ScreenshotManager as M,ScreenshotContext as q}from"./ScreenshotManager.js";import{contextCache as S}from"./testUtils.js";import{RenderState as L}from"../../../support/RenderState.js";import{createContextOrErrorHTML as H}from"../../../webgl/context-util.js";let B=class extends t{constructor(e){super({}),this.events=new r,this.waterTextureRepository=new U,this._magnifierHelper=new b,this.objectAndLayerIdRenderHelper=has("enable-feature:objectAndLayerId-rendering")?new j:null,this._needsUpdate=!0,this._needsRender=!0,this._idleSuspend=!0,this._needsWaterReflectionUpdate=!1,this._lastAnimationUpdate=0,this._container=e.container,this._viewingMode=e.viewingMode,this._initializeContext(e),p((()=>this.waterTextureRepository?.updating),(()=>this.requestRender()),d),this._magnifierHelper.events.on("request-render",(()=>this.requestRender())),this._stippleTextureRepository=new C(this._rctx),this._shaderTechniqueRepository=new _({rctx:this._rctx,viewingMode:e.viewingMode,stippleTextureRepository:this._stippleTextureRepository,waterTextureRepository:this.waterTextureRepository}),this._textureRepository=new A(e,this._shaderTechniqueRepository,this._rctx),this._textureRepository.events.on("changed",(e=>this.requestRender(e))),this._materialRepository=new x(this._textureRepository,this._shaderTechniqueRepository,(()=>this.requestRender()),(()=>this.requestRender())),this._compositingHelper=new g(this._rctx,this._shaderTechniqueRepository),this.renderer=new w(this._materialRepository,this._textureRepository,this._shaderTechniqueRepository,this._rctx,this._compositingHelper,this._magnifierHelper,(e=>this.requestRender(e)),e);const t={renderScene:(e,t,r,i,s)=>this.renderer.render(e,t,{camera:r,contentCamera:r,mode:L.IDLE},i,s),requestRenderScene:e=>this.requestRender(e),prepareOverlay:()=>e.options.screenshot.prepareOverlay(),renderOverlay:(t,r)=>e.options.screenshot.renderOverlay(t,r)};this._screenshotManager=new M(this._rctx,t,(e=>this.events.emit("force-camera-for-screenshot",e)),(()=>this.renderer.disposeOffscreenBuffers())),this._registerFrameTask(e)}normalizeCtorArgs(){return{}}destroy(){this._container.contains(this._canvas)&&this._container.removeChild(this._canvas),this._frameTask=s(this._frameTask),this._shaderTechniqueRepository=o(this._shaderTechniqueRepository)}get performanceInfo(){const e=this._rctx.gl;return{renderer:this.renderer.performanceInfo,textureMemory:void 0!==e.getUsedTextureMemory?e.getUsedTextureMemory():void 0,renderbufferMemory:void 0!==e.getUsedRenderbufferMemory?e.getUsedRenderbufferMemory():void 0,VBOMemory:void 0!==e.getUsedVBOMemory?e.getUsedVBOMemory():void 0}}requestRender(e=f.UPDATE){this._needsRender=!0,e===f.UPDATE&&(this._needsUpdate=!0)}get updating(){return this._needsUpdate||this._needsWaterReflectionUpdate||this.renderer.updating||this._textureRepository.updating||this.waterTextureRepository.updating||this._magnifierHelper.updating}get textureRepository(){return this._textureRepository}get compositingHelper(){return this._compositingHelper}set magnifier(e){this._magnifierHelper.magnifier=e}setIdleSuspend(e){this._idleSuspend!==e&&(this._idleSuspend=e,this.requestRender())}get renderingContext(){return this._rctx}get capabilities(){return this._rctx.capabilities}get canvas(){return this._canvas}takeScreenshot(e){return this._screenshotManager.takeScreenshot(e).then((e=>e[0]))}takeScreenshotWithOID(e){return e.objectAndLayerIdColor=!0,this._screenshotManager.takeScreenshot(e)}getAlpha(){return!!this._rctx.contextAttributes.alpha}getMinimalDepthForArea(e,t,r,i,s,o=s){const a=i.constrainWindowSize(t,r,s*i.pixelRatio,o*i.pixelRatio),p=this._ensureDepthBuffer(a);this.renderer.readDepthPixels(i,a,p);let d=Number.MAX_VALUE;for(let n=0;n<a[2]*a[3];n++){const e=R(4*n,p,i.nearFar);d>e&&e!==i.nearFar[0]&&e!==i.nearFar[1]&&(d=e)}if(n(e)){const s=e.pickDepth(t*i.pixelRatio,r*i.pixelRatio,i);n(s)&&d>s&&s!==i.nearFar[0]&&s!==i.nearFar[1]&&(d=s)}return d===Number.MAX_VALUE?void 0:d}_ensureDepthBuffer(e){const t=4*e[2]*e[3];return(a(this._tmpDepthBuffer)||this._tmpDepthBuffer.byteLength<t)&&(this._tmpDepthBuffer=new Uint8Array(t)),this._tmpDepthBuffer}async reloadShaders(){O(),await this._shaderTechniqueRepository.reloadAll(),this.requestRender()}_registerFrameTask(e){const t=e.state;let r=!1,i=f.BACKGROUND,s=!1;const o={preRender:({time:s})=>{r=this.updating,i=this._needsUpdate?f.UPDATE:f.BACKGROUND,e.commitSyncLayers();const o=c(s-this._lastAnimationUpdate);if(o>this.renderer.animationTimestep||n(t.forcedAnimationTime)||r||this._needsRender){const e=c(o/this.renderer.animationTimeDilation),r=new v(t.camera,e,t.forcedAnimationTime);this.renderer.updateAnimation(r)&&this.requestRender(f.BACKGROUND),this._lastAnimationUpdate=s}},render:({time:e})=>{if((this._needsRender||!this._idleSuspend||!this.renderer.isCameraFinal||this._needsWaterReflectionUpdate)&&t.camera.fullWidth>0&&t.camera.fullHeight>0){const r=this._needsUpdate&&this._idleSuspend&&this.renderer.isCameraFinal;this._needsRender=!1,this._needsUpdate=!1,this._needsWaterReflectionUpdate=!1,this.renderer.render(null,null,t,y.ON,e),s=!0,r&&this.renderer.hasWaterReflection&&(this.requestRender(f.BACKGROUND),this._needsWaterReflectionUpdate=!0)}},update:({time:e})=>{const r=new q(t.camera,this.renderer.hasSlicePlane||this._magnifierHelper.enabled);this._textureRepository.update(),this._screenshotManager.update(r,e)},finish:()=>{s&&(this.renderer.finish(t.mode===L.IDLE?i:f.UPDATE),s=!1)}};this._frameTask=h(o)}_initializeContext(e){const t=e.options;this._canvas=t.canvas,this._canvas||(this._canvas=document.createElement("canvas")),this._canvas.setAttribute("style","width: 100%; height:100%; display:block;");const r={alpha:t.alpha||!1,premultipliedAlpha:!0,antialias:!1,depth:!0,stencil:null==t.stencil||t.stencil,powerPreference:"high-performance",preserveDrawingBuffer:t.preserveDrawingBuffer??!1},s=H("3d",this._canvas,r);if(a(s)){const e=has("esri-force-webgl");i.getLogger(this.declaredClass).error(e)}else this._rctx=this._newRenderingContext(s,e),this._loadShaderOnlyExtensions(),!t.alpha&&this._rctx.contextAttributes.alpha&&i.getLogger(this.declaredClass).error("WebGL context has alpha channel even though no alpha channel was requested"),!this._rctx.contextAttributes.alpha&&has("safari")>=11&&(this._container.style.backgroundColor="black"),this._container.appendChild(this._canvas)}_newRenderingContext(e,t){const r={disabledExtensions:t.options.deactivatedWebGLExtensions||{},debugWebGLExtensions:t.options.debugWebGLExtensions||{},maxAnisotropy:8},i=(e,r)=>t.resourceController.memoryController.newCache(e,r);if(S.enabled){let t=E.get(e);return t?(t.configure(r),t.newCache=i,t.ref(),t):(t=new T(e,r,i),E.set(e,t),t.ref(),t)}return new T(e,r,i)}_loadShaderOnlyExtensions(){this._rctx.capabilities.enable("standardDerivatives"),this._rctx.capabilities.enable("shaderTextureLOD"),this._rctx.capabilities.enable("textureFloat")}getObjectAndLayerIdColor(e){return n(this.objectAndLayerIdRenderHelper)?this.objectAndLayerIdRenderHelper.getObjectAndLayerIdColor(e):null}get componentObjectCollection(){return a(this._componentObjectCollection)&&(this._componentObjectCollection=new u(this.renderer.renderPassManager,this._viewingMode)),this._componentObjectCollection}set componentObjectCollection(e){this._componentObjectCollection=e}};e([l({type:Boolean,readOnly:!0})],B.prototype,"updating",null),e([l({autoDestroy:!0})],B.prototype,"_rctx",void 0),e([l({autoDestroy:!0})],B.prototype,"_container",void 0),e([l({autoDestroy:!0})],B.prototype,"_canvas",void 0),e([l({autoDestroy:!0})],B.prototype,"_stippleTextureRepository",void 0),e([l({autoDestroy:!0})],B.prototype,"waterTextureRepository",void 0),e([l({autoDestroy:!0})],B.prototype,"_magnifierHelper",void 0),e([l({readOnly:!0})],B.prototype,"objectAndLayerIdRenderHelper",void 0),e([l({autoDestroy:!0})],B.prototype,"_textureRepository",void 0),e([l({autoDestroy:!0})],B.prototype,"_compositingHelper",void 0),e([l({autoDestroy:!0,readOnly:!0})],B.prototype,"renderer",void 0),e([l({autoDestroy:!0})],B.prototype,"_screenshotManager",void 0),e([l()],B.prototype,"componentObjectCollection",null),e([l({autoDestroy:!0})],B.prototype,"_componentObjectCollection",void 0),e([l()],B.prototype,"_needsUpdate",void 0),e([l()],B.prototype,"_needsWaterReflectionUpdate",void 0),B=e([m("esri.views.3d.webgl-engine.parts.RenderView")],B);const E=D();export{B as RenderView};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{disposeMaybe as t,applySome as e,isNone as s,isSome as i,unwrapOr as a}from"../../core/maybe.js";import{after as r}from"../../core/promiseUtils.js";import{Milliseconds as n}from"../../core/time.js";import{webglDebugEnabled as l}from"./checkWebGLError.js";import{ContextType as h}from"./context-util.js";import{ContextState as f}from"./ContextState.js";import{BufferType as o,Face as _,BASE_TEXTURE_UNIT as u,ClearBufferBit as c,FramebufferTarget as d,TextureSamplingMode as b,SyncCondition as F,ResourceType as g,ClientWaitSyncStatus as E,BlendFactor as B,BlendOperation as p,CullMode as m,CompareFunction as R,StencilOperation as T,ColorAttachment as A,TextureType as x,PrimitiveType as O}from"./enums.js";import{InstanceCounter as U}from"./InstanceCounter.js";import{ProgramCache as C}from"./ProgramCache.js";import{StateTracker as S}from"./renderState.js";import{Texture as P}from"./Texture.js";import{getErrorString as M}from"./Util.js";import{WebGLDriverTest as N}from"./WebGLDriverTest.js";import{Capabilities as k}from"./capabilities/Capabilities.js";import y from"./capabilities/isWebGL2Context.js";let I=class{constructor(t,e){this.gl=t,this.instanceCounter=new U,this.programCache=new C(this),this._state=new f,this._numOfDrawCalls=0,this._numOfTriangles=0,this.type=y(t)?h.WEBGL2:h.WEBGL1,this._loadExtensions(),this.configure(e)}configure(e){this._capabilities=new k(this.gl,e),this._parameters=this._loadParameters(e);const s=this.gl.getParameter(this.gl.VIEWPORT);this._state=new f,this._state.viewport={x:s[0],y:s[1],width:s[2],height:s[3]},this._stateTracker=new S({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)}}),this.enforceState(),t(this._driverTest),this._driverTest=new N(this)}dispose(){t(this._driverTest),this.programCache.dispose(),this.bindVAO(null),this.unbindBuffer(o.ARRAY_BUFFER),this.unbindBuffer(o.ELEMENT_ARRAY_BUFFER),y(this.gl)&&(this.unbindBuffer(o.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(o.PIXEL_PACK_BUFFER),this.unbindBuffer(o.PIXEL_UNPACK_BUFFER),this.unbindBuffer(o.COPY_READ_BUFFER),this.unbindBuffer(o.COPY_WRITE_BUFFER)),this._state.textureUnitMap.length=0,l()&&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=_.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===_.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=_.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(l()&&(this._numOfDrawCalls++,this._numOfTriangles+=D(t,s)),this.gl.drawArrays(t,e,s),l()){const t=M(this);t&&console.error("drawArrays:",t)}}drawElements(t,s,i,a){if(l()&&(this._numOfDrawCalls++,this._numOfTriangles+=D(t,s)),this.gl.drawElements(t,s,i,a),l()){const r=M(this);if(r){const n=this.getBoundVAO(),l=n?.indexBuffer,h=n?.vertexBuffers,f={indexBuffer:l,vertexBuffers:h},o={mode:t,count:s,type:i,offset:a},_=e(l,(t=>t.size))??0,u=a+s,c=_<u?`. Buffer is too small. Attempted to draw index ${u} of ${_}`:"";console.error(`drawElements: ${r}${c}`,{args:o,vao:f})}}}logInfo(){l()&&console.log(`DrawCalls: ${this._numOfDrawCalls}, Triangles: ${this._numOfTriangles}`)}resetInfo(){l()&&(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))}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,a=!1){(e>=this.parameters.maxTextureImageUnits||e<0)&&console.error("Input texture unit is out of range of available units!");const r=this._state.textureUnitMap[e];return s(t)||null==t.glName?(i(r)&&(this.setActiveTexture(e,a),this.gl.bindTexture(r.descriptor.target,null)),this._state.textureUnitMap[e]=null,r):a||r!==t?(this.setActiveTexture(e,a),this.gl.bindTexture(t.descriptor.target,t.glName),t.applyChanges(),this._state.textureUnitMap[e]=t,r):(t.isDirty&&(this.setActiveTexture(e,a),t.applyChanges()),r)}unbindTexture(t){if(!s(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(s(t))return this.gl.bindFramebuffer(d.FRAMEBUFFER,null),this._state.readFramebuffer=null,void(this._state.drawFramebuffer=null);t.initializeAndBind(d.FRAMEBUFFER),this._state.readFramebuffer=t,this._state.drawFramebuffer=t}}bindFramebufferSeparate(t,e,i=!1){const r=e===d.READ_FRAMEBUFFER,n=r?this._state.readFramebuffer:this._state.drawFramebuffer;(i||n!==t)&&(s(t)?this.gl.bindFramebuffer(e,null):t.initializeAndBind(e),r?this._state.readFramebuffer=a(t,null):this._state.drawFramebuffer=a(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,_=b.NEAREST){this.bindFramebufferSeparate(t,d.READ_FRAMEBUFFER),this.bindFramebufferSeparate(e,d.DRAW_FRAMEBUFFER);this.gl.blitFramebuffer(s,i,a,r,n,l,h,f,o,_)}bindBuffer(t,e){if(t)switch(e??(e=t.bufferType),e){case o.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,t,e,this._state.vertexBuffer);break;case o.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,t,e,this._state.indexBuffer);break;case o.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,t,e,this._state.uniformBuffer);break;case o.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,t,e,this._state.pixelPackBuffer);break;case o.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,t,e,this._state.pixelUnpackBuffer);break;case o.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,t,e,this._state.copyReadBuffer);break;case o.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(this.gl,t,e,this._state.copyWriteBuffer)}}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 i=this._state.uniformBufferBindingPoints;let a=i[e];return s(a)&&(a={buffer:null,offset:0,size:0},i[e]=a),a}bindBufferBase(t,e,i){const a=this._getBufferBinding(t,e);if(s(a))return;if(a.buffer===i&&0===a.offset&&0===a.size)return;this.gl.bindBufferBase(t,e,i?i.glName:null),a.buffer=i,a.offset=0,a.size=0}bindBufferRange(t,e,i,a,r){const n=this._getBufferBinding(t,e);if(s(n))return;if(n.buffer===i&&n.offset===a&&n.size===r)return;if(a%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,i.glName,a,r),n.buffer=i,n.offset=a,n.size=r}bindUBO(t,e,i,a){s(e)?this.bindBufferBase(o.UNIFORM_BUFFER,t,null):(l()&&(a??e.byteLength)>this._parameters.maxUniformBlockSize&&console.error("Attempting to bind more data than the maximum uniform block size"),e.initialize(),void 0!==i&&void 0!==a?this.bindBufferRange(o.UNIFORM_BUFFER,t,e.buffer,i,a):this.bindBufferBase(o.UNIFORM_BUFFER,t,e.buffer))}unbindUBO(t){for(let e=0,s=this._state.uniformBufferBindingPoints.length;e<s;e++){const s=this._state.uniformBufferBindingPoints[e];i(s)&&s.buffer===t.buffer&&this.bindBufferBase(o.UNIFORM_BUFFER,e,null)}}unbindBuffer(t){switch(t){case o.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,null,t,this._state.vertexBuffer);break;case o.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,null,t,this._state.indexBuffer);break;case o.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,null,t,this._state.uniformBuffer);break;case o.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,null,t,this._state.pixelPackBuffer);break;case o.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,null,t,this._state.pixelUnpackBuffer);break;case o.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,null,t,this._state.copyReadBuffer);break;case o.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(this.gl,null,t,this._state.copyWriteBuffer)}}bindVAO(t=null){s(t)?this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null):this._state.vertexArrayObject!==t&&(t.bind(),this._state.vertexArrayObject=t)}async clientWaitAsync(t=n(10)){const e=this.gl,s=e.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);if(!s)throw new Error("Client wait failed, could not create sync object");let i;this.instanceCounter.increment(g.Sync,s),e.flush();do{await r(t),i=e.clientWaitSync(s,0,0)}while(i===E.TIMEOUT_EXPIRED);if(this.instanceCounter.decrement(g.Sync,s),e.deleteSync(s),i===E.WAIT_FAILED)throw new Error("Client wait failed")}getBoundFramebufferObject(t=d.FRAMEBUFFER){return t===d.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(o.ARRAY_BUFFER),this.unbindBuffer(o.ELEMENT_ARRAY_BUFFER),y(this.gl)&&(this.unbindBuffer(o.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(o.PIXEL_PACK_BUFFER),this.unbindBuffer(o.PIXEL_UNPACK_BUFFER),this.unbindBuffer(o.COPY_READ_BUFFER),this.unbindBuffer(o.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(_.BACK),this.setFrontFace(m.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(R.LESS),this.setDepthRange(0,1),this.setStencilTestEnabled(!1),this.setStencilFunction(R.ALWAYS,0,0),this.setStencilOp(T.KEEP,T.KEEP,T.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.gl,e=this.capabilities.vao;e&&e.bindVertexArray(null);for(let i=0;i<this.parameters.maxVertexAttributes;i++)t.disableVertexAttribArray(i);if(this._state.vertexBuffer?t.bindBuffer(this._state.vertexBuffer.bufferType,this._state.vertexBuffer.glName):t.bindBuffer(o.ARRAY_BUFFER,null),this._state.indexBuffer?t.bindBuffer(this._state.indexBuffer.bufferType,this._state.indexBuffer.glName):t.bindBuffer(o.ELEMENT_ARRAY_BUFFER,null),y(t)){this._state.uniformBuffer?t.bindBuffer(this._state.uniformBuffer.bufferType,this._state.uniformBuffer.glName):t.bindBuffer(o.UNIFORM_BUFFER,null);for(let e=0;e<this._parameters.maxUniformBufferBindings;e++){const s=this._state.uniformBufferBindingPoints[e];if(i(s)){const{buffer:i,offset:a,size:r}=s;null!==i?0===a&&0===r?t.bindBufferBase(o.UNIFORM_BUFFER,e,i.glName):t.bindBufferRange(o.UNIFORM_BUFFER,e,i.glName,a,r):t.bindBufferBase(o.UNIFORM_BUFFER,e,null)}}this._state.pixelPackBuffer?t.bindBuffer(this._state.pixelPackBuffer.bufferType,this._state.pixelPackBuffer.glName):t.bindBuffer(o.PIXEL_PACK_BUFFER,null),this._state.pixelUnpackBuffer?t.bindBuffer(this._state.pixelUnpackBuffer.bufferType,this._state.pixelUnpackBuffer.glName):t.bindBuffer(o.PIXEL_UNPACK_BUFFER,null),this._state.copyReadBuffer?t.bindBuffer(this._state.copyReadBuffer.bufferType,this._state.copyReadBuffer.glName):t.bindBuffer(o.COPY_READ_BUFFER,null),this._state.copyWriteBuffer?t.bindBuffer(this._state.copyWriteBuffer.bufferType,this._state.copyWriteBuffer.glName):t.bindBuffer(o.COPY_WRITE_BUFFER,null),t.bindFramebuffer(d.READ_FRAMEBUFFER,null),t.readBuffer(t.BACK),this._state.readFramebuffer&&(t.bindFramebuffer(d.READ_FRAMEBUFFER,this._state.readFramebuffer.glName),t.readBuffer(A.COLOR_ATTACHMENT0)),t.bindFramebuffer(d.DRAW_FRAMEBUFFER,this._state.drawFramebuffer?.glName??null)}else this._state.readFramebuffer=this._state.drawFramebuffer,t.bindFramebuffer(d.FRAMEBUFFER,this._state.drawFramebuffer?.glName??null);if(e&&this._state.vertexArrayObject){const t=this._state.vertexArrayObject;this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null),this.bindVAO(t)}t.useProgram(this._state.program?.glName??null),t.blendColor(this._state.blendColor.r,this._state.blendColor.g,this._state.blendColor.b,this._state.blendColor.a),t.bindRenderbuffer(t.RENDERBUFFER,this._state.renderbuffer?this._state.renderbuffer.glName:null),!0===this._state.blend?t.enable(this.gl.BLEND):t.disable(this.gl.BLEND),t.blendEquationSeparate(this._state.blendEquation.mode,this._state.blendEquation.modeAlpha),t.blendFuncSeparate(this._state.blendFunction.srcRGB,this._state.blendFunction.dstRGB,this._state.blendFunction.srcAlpha,this._state.blendFunction.dstAlpha),t.clearColor(this._state.clearColor.r,this._state.clearColor.g,this._state.clearColor.b,this._state.clearColor.a),t.clearDepth(this._state.clearDepth),t.clearStencil(this._state.clearStencil),t.colorMask(this._state.colorMask.r,this._state.colorMask.g,this._state.colorMask.b,this._state.colorMask.a),t.cullFace(this._state.cullFace),t.depthFunc(this._state.depthFunction),t.depthRange(this._state.depthRange.zNear,this._state.depthRange.zFar),!0===this._state.depthTest?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),t.depthMask(this._state.depthWrite),t.frontFace(this._state.frontFace),t.lineWidth(1),!0===this._state.faceCulling?t.enable(t.CULL_FACE):t.disable(t.CULL_FACE),t.polygonOffset(this._state.polygonOffset[0],this._state.polygonOffset[1]),!0===this._state.polygonOffsetFill?t.enable(t.POLYGON_OFFSET_FILL):t.disable(t.POLYGON_OFFSET_FILL),t.scissor(this._state.scissorRect.x,this._state.scissorRect.y,this._state.scissorRect.width,this._state.scissorRect.height),!0===this._state.scissorTest?t.enable(t.SCISSOR_TEST):t.disable(t.SCISSOR_TEST),t.stencilFunc(this._state.stencilFunction.func,this._state.stencilFunction.ref,this._state.stencilFunction.mask),t.stencilOpSeparate(this._state.stencilOperation.face,this._state.stencilOperation.fail,this._state.stencilOperation.zFail,this._state.stencilOperation.zPass),!0===this._state.stencilTest?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),t.stencilMask(this._state.stencilWriteMask);for(let a=0;a<this.parameters.maxTextureImageUnits;a++){t.activeTexture(u+a),t.bindTexture(x.TEXTURE_2D,null),t.bindTexture(x.TEXTURE_CUBE_MAP,null),y(t)&&(t.bindTexture(x.TEXTURE_3D,null),t.bindTexture(x.TEXTURE_2D_ARRAY,null));const e=this._state.textureUnitMap[a];i(e)&&t.bindTexture(e.descriptor.target,e.glName)}t.activeTexture(u+this._state.activeTexture);const s=this._state.viewport;t.viewport(s.x,s.y,s.width,s.height),this.resetInfo()}_loadExtensions(){this.type===h.WEBGL1&&this.gl.getExtension("OES_element_index_uint"),this.gl.getExtension("KHR_parallel_shader_compile")}_loadParameters(t){const e=this.capabilities.textureFilterAnisotropic,s=t.maxAnisotropy??1/0,i=y(this.gl),a=this.gl,r={versionString:this.gl.getParameter(this.gl.VERSION),maxVertexTextureImageUnits:this.gl.getParameter(this.gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxVertexAttributes:this.gl.getParameter(this.gl.MAX_VERTEX_ATTRIBS),maxMaxAnisotropy:e?Math.min(this.gl.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY),s):1,maxTextureImageUnits:this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),maxTextureSize:this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE),maxUniformBufferBindings:i?a.getParameter(a.MAX_UNIFORM_BUFFER_BINDINGS):0,maxVertexUniformBlocks:i?a.getParameter(a.MAX_VERTEX_UNIFORM_BLOCKS):0,maxFragmentUniformBlocks:i?a.getParameter(a.MAX_FRAGMENT_UNIFORM_BLOCKS):0,maxUniformBlockSize:i?a.getParameter(a.MAX_UNIFORM_BLOCK_SIZE):0,uniformBufferOffsetAlignment:i?a.getParameter(a.UNIFORM_BUFFER_OFFSET_ALIGNMENT):1,maxArrayTextureLayers:i?a.getParameter(a.MAX_ARRAY_TEXTURE_LAYERS):1,maxSamples:i?a.getParameter(a.MAX_SAMPLES):1};return P.TEXTURE_UNIT_FOR_UPDATES=r.maxTextureImageUnits-1,r}};function v(t,e,s,i){return e?i!==e&&t.bindBuffer(s,e.glName):t.bindBuffer(s,null),e}function D(t,e){switch(t){case O.POINTS:return 2*e;case O.TRIANGLES:return e/3;case O.TRIANGLE_STRIP:case O.TRIANGLE_FAN:return e-2;default:return 0}}export{I as RenderingContext};
|
|
5
|
+
import{disposeMaybe as t,applySome as e,isNone as s,isSome as i,unwrapOr as a}from"../../core/maybe.js";import{after as r}from"../../core/promiseUtils.js";import{Milliseconds as n}from"../../core/time.js";import{webglDebugEnabled as l}from"./checkWebGLError.js";import{ContextType as h}from"./context-util.js";import{ContextState as f}from"./ContextState.js";import{BufferType as o,Face as _,BASE_TEXTURE_UNIT as u,ClearBufferBit as c,FramebufferTarget as d,TextureSamplingMode as b,SyncCondition as F,ResourceType as g,ClientWaitSyncStatus as E,BlendFactor as B,BlendOperation as p,CullMode as m,CompareFunction as R,StencilOperation as T,ColorAttachment as A,TextureType as x,PrimitiveType as O}from"./enums.js";import{InstanceCounter as U}from"./InstanceCounter.js";import{ProgramCache as C}from"./ProgramCache.js";import{StateTracker as S}from"./renderState.js";import{Texture as P}from"./Texture.js";import{getErrorString as M}from"./Util.js";import{WebGLDriverTest as y}from"./WebGLDriverTest.js";import{Capabilities as N}from"./capabilities/Capabilities.js";import k from"./capabilities/isWebGL2Context.js";let I=class{constructor(t,e){this.gl=t,this.instanceCounter=new U,this.programCache=new C(this),this._state=new f,this._numOfDrawCalls=0,this._numOfTriangles=0,this.type=k(t)?h.WEBGL2:h.WEBGL1,this._loadExtensions(),this.configure(e)}get gl2(){return this.type===h.WEBGL1?null:this.gl}configure(e){this._capabilities=new N(this.gl,e),this._parameters=this._loadParameters(e);const s=this.gl.getParameter(this.gl.VIEWPORT);this._state=new f,this._state.viewport={x:s[0],y:s[1],width:s[2],height:s[3]},this._stateTracker=new S({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)}}),this.enforceState(),t(this._driverTest),this._driverTest=new y(this)}dispose(){t(this._driverTest),this.programCache.dispose(),this.bindVAO(null),this.unbindBuffer(o.ARRAY_BUFFER),this.unbindBuffer(o.ELEMENT_ARRAY_BUFFER),this.type===h.WEBGL2&&(this.unbindBuffer(o.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(o.PIXEL_PACK_BUFFER),this.unbindBuffer(o.PIXEL_UNPACK_BUFFER),this.unbindBuffer(o.COPY_READ_BUFFER),this.unbindBuffer(o.COPY_WRITE_BUFFER)),this._state.textureUnitMap.length=0,l()&&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=_.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===_.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=_.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(l()&&(this._numOfDrawCalls++,this._numOfTriangles+=D(t,s)),this.gl.drawArrays(t,e,s),l()){const t=M(this);t&&console.error("drawArrays:",t)}}drawElements(t,s,i,a){if(l()&&(this._numOfDrawCalls++,this._numOfTriangles+=D(t,s)),this.gl.drawElements(t,s,i,a),l()){const r=M(this);if(r){const n=this.getBoundVAO(),l=n?.indexBuffer,h=n?.vertexBuffers,f={indexBuffer:l,vertexBuffers:h},o={mode:t,count:s,type:i,offset:a},_=e(l,(t=>t.size))??0,u=a+s,c=_<u?`. Buffer is too small. Attempted to draw index ${u} of ${_}`:"";console.error(`drawElements: ${r}${c}`,{args:o,vao:f})}}}logInfo(){l()&&console.log(`DrawCalls: ${this._numOfDrawCalls}, Triangles: ${this._numOfTriangles}`)}resetInfo(){l()&&(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))}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,a=!1){(e>=this.parameters.maxTextureImageUnits||e<0)&&console.error("Input texture unit is out of range of available units!");const r=this._state.textureUnitMap[e];return s(t)||null==t.glName?(i(r)&&(this.setActiveTexture(e,a),this.gl.bindTexture(r.descriptor.target,null)),this._state.textureUnitMap[e]=null,r):a||r!==t?(this.setActiveTexture(e,a),this.gl.bindTexture(t.descriptor.target,t.glName),t.applyChanges(),this._state.textureUnitMap[e]=t,r):(t.isDirty&&(this.setActiveTexture(e,a),t.applyChanges()),r)}unbindTexture(t){if(!s(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(s(t))return this.gl.bindFramebuffer(d.FRAMEBUFFER,null),this._state.readFramebuffer=null,void(this._state.drawFramebuffer=null);t.initializeAndBind(d.FRAMEBUFFER),this._state.readFramebuffer=t,this._state.drawFramebuffer=t}}bindFramebufferSeparate(t,e,i=!1){const r=e===d.READ_FRAMEBUFFER,n=r?this._state.readFramebuffer:this._state.drawFramebuffer;(i||n!==t)&&(s(t)?this.gl.bindFramebuffer(e,null):t.initializeAndBind(e),r?this._state.readFramebuffer=a(t,null):this._state.drawFramebuffer=a(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,_=b.NEAREST){this.bindFramebufferSeparate(t,d.READ_FRAMEBUFFER),this.bindFramebufferSeparate(e,d.DRAW_FRAMEBUFFER);this.gl.blitFramebuffer(s,i,a,r,n,l,h,f,o,_)}bindBuffer(t,e){if(t)switch(e??(e=t.bufferType),e){case o.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,t,e,this._state.vertexBuffer);break;case o.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,t,e,this._state.indexBuffer);break;case o.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,t,e,this._state.uniformBuffer);break;case o.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,t,e,this._state.pixelPackBuffer);break;case o.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,t,e,this._state.pixelUnpackBuffer);break;case o.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,t,e,this._state.copyReadBuffer);break;case o.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(this.gl,t,e,this._state.copyWriteBuffer)}}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 i=this._state.uniformBufferBindingPoints;let a=i[e];return s(a)&&(a={buffer:null,offset:0,size:0},i[e]=a),a}bindBufferBase(t,e,i){const a=this._getBufferBinding(t,e);if(s(a))return;if(a.buffer===i&&0===a.offset&&0===a.size)return;this.gl.bindBufferBase(t,e,i?i.glName:null),a.buffer=i,a.offset=0,a.size=0}bindBufferRange(t,e,i,a,r){const n=this._getBufferBinding(t,e);if(s(n))return;if(n.buffer===i&&n.offset===a&&n.size===r)return;if(a%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,i.glName,a,r),n.buffer=i,n.offset=a,n.size=r}bindUBO(t,e,i,a){s(e)?this.bindBufferBase(o.UNIFORM_BUFFER,t,null):(l()&&(a??e.byteLength)>this._parameters.maxUniformBlockSize&&console.error("Attempting to bind more data than the maximum uniform block size"),e.initialize(),void 0!==i&&void 0!==a?this.bindBufferRange(o.UNIFORM_BUFFER,t,e.buffer,i,a):this.bindBufferBase(o.UNIFORM_BUFFER,t,e.buffer))}unbindUBO(t){for(let e=0,s=this._state.uniformBufferBindingPoints.length;e<s;e++){const s=this._state.uniformBufferBindingPoints[e];i(s)&&s.buffer===t.buffer&&this.bindBufferBase(o.UNIFORM_BUFFER,e,null)}}unbindBuffer(t){switch(t){case o.ARRAY_BUFFER:this._state.vertexBuffer=v(this.gl,null,t,this._state.vertexBuffer);break;case o.ELEMENT_ARRAY_BUFFER:this._state.indexBuffer=v(this.gl,null,t,this._state.indexBuffer);break;case o.UNIFORM_BUFFER:this._state.uniformBuffer=v(this.gl,null,t,this._state.uniformBuffer);break;case o.PIXEL_PACK_BUFFER:this._state.pixelPackBuffer=v(this.gl,null,t,this._state.pixelPackBuffer);break;case o.PIXEL_UNPACK_BUFFER:this._state.pixelUnpackBuffer=v(this.gl,null,t,this._state.pixelUnpackBuffer);break;case o.COPY_READ_BUFFER:this._state.copyReadBuffer=v(this.gl,null,t,this._state.copyReadBuffer);break;case o.COPY_WRITE_BUFFER:this._state.copyWriteBuffer=v(this.gl,null,t,this._state.copyWriteBuffer)}}bindVAO(t=null){s(t)?this._state.vertexArrayObject&&(this._state.vertexArrayObject.unbind(),this._state.vertexArrayObject=null):this._state.vertexArrayObject!==t&&(t.bind(),this._state.vertexArrayObject=t)}async clientWaitAsync(t=n(10)){const e=this.gl,s=e.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);if(!s)throw new Error("Client wait failed, could not create sync object");let i;this.instanceCounter.increment(g.Sync,s),e.flush();do{await r(t),i=e.clientWaitSync(s,0,0)}while(i===E.TIMEOUT_EXPIRED);if(this.instanceCounter.decrement(g.Sync,s),e.deleteSync(s),i===E.WAIT_FAILED)throw new Error("Client wait failed")}getBoundFramebufferObject(t=d.FRAMEBUFFER){return t===d.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(o.ARRAY_BUFFER),this.unbindBuffer(o.ELEMENT_ARRAY_BUFFER),this.type===h.WEBGL2&&(this.unbindBuffer(o.UNIFORM_BUFFER),this._state.uniformBufferBindingPoints.length=0,this.unbindBuffer(o.PIXEL_PACK_BUFFER),this.unbindBuffer(o.PIXEL_UNPACK_BUFFER),this.unbindBuffer(o.COPY_READ_BUFFER),this.unbindBuffer(o.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(_.BACK),this.setFrontFace(m.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(R.LESS),this.setDepthRange(0,1),this.setStencilTestEnabled(!1),this.setStencilFunction(R.ALWAYS,0,0),this.setStencilOp(T.KEEP,T.KEEP,T.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 i=0;i<this.parameters.maxVertexAttributes;i++)e.disableVertexAttribArray(i);if(this._state.vertexBuffer?e.bindBuffer(this._state.vertexBuffer.bufferType,this._state.vertexBuffer.glName):e.bindBuffer(o.ARRAY_BUFFER,null),this._state.indexBuffer?e.bindBuffer(this._state.indexBuffer.bufferType,this._state.indexBuffer.glName):e.bindBuffer(o.ELEMENT_ARRAY_BUFFER,null),i(s)){this._state.uniformBuffer?s.bindBuffer(this._state.uniformBuffer.bufferType,this._state.uniformBuffer.glName):s.bindBuffer(o.UNIFORM_BUFFER,null);for(let t=0;t<this._parameters.maxUniformBufferBindings;t++){const e=this._state.uniformBufferBindingPoints[t];if(i(e)){const{buffer:i,offset:a,size:r}=e;null!==i?0===a&&0===r?s.bindBufferBase(o.UNIFORM_BUFFER,t,i.glName):s.bindBufferRange(o.UNIFORM_BUFFER,t,i.glName,a,r):s.bindBufferBase(o.UNIFORM_BUFFER,t,null)}}this._state.pixelPackBuffer?s.bindBuffer(this._state.pixelPackBuffer.bufferType,this._state.pixelPackBuffer.glName):s.bindBuffer(o.PIXEL_PACK_BUFFER,null),this._state.pixelUnpackBuffer?s.bindBuffer(this._state.pixelUnpackBuffer.bufferType,this._state.pixelUnpackBuffer.glName):s.bindBuffer(o.PIXEL_UNPACK_BUFFER,null),this._state.copyReadBuffer?s.bindBuffer(this._state.copyReadBuffer.bufferType,this._state.copyReadBuffer.glName):s.bindBuffer(o.COPY_READ_BUFFER,null),this._state.copyWriteBuffer?s.bindBuffer(this._state.copyWriteBuffer.bufferType,this._state.copyWriteBuffer.glName):s.bindBuffer(o.COPY_WRITE_BUFFER,null),s.bindFramebuffer(d.READ_FRAMEBUFFER,null),s.readBuffer(s.BACK),this._state.readFramebuffer&&(s.bindFramebuffer(d.READ_FRAMEBUFFER,this._state.readFramebuffer.glName),s.readBuffer(A.COLOR_ATTACHMENT0)),s.bindFramebuffer(d.DRAW_FRAMEBUFFER,this._state.drawFramebuffer?.glName??null)}else this._state.readFramebuffer=this._state.drawFramebuffer,e.bindFramebuffer(d.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 r=0;r<this.parameters.maxTextureImageUnits;r++){e.activeTexture(u+r),e.bindTexture(x.TEXTURE_2D,null),e.bindTexture(x.TEXTURE_CUBE_MAP,null),this.type===h.WEBGL2&&(e.bindTexture(x.TEXTURE_3D,null),e.bindTexture(x.TEXTURE_2D_ARRAY,null));const t=this._state.textureUnitMap[r];i(t)&&e.bindTexture(t.descriptor.target,t.glName)}e.activeTexture(u+this._state.activeTexture);const a=this._state.viewport;e.viewport(a.x,a.y,a.width,a.height),this.resetInfo()}_loadExtensions(){this.type===h.WEBGL1&&this.gl.getExtension("OES_element_index_uint"),this.gl.getExtension("KHR_parallel_shader_compile")}_loadParameters(t){const e=this.capabilities.textureFilterAnisotropic,s=t.maxAnisotropy??1/0,i=this.type===h.WEBGL2,a=this.gl,r={versionString:this.gl.getParameter(this.gl.VERSION),maxVertexTextureImageUnits:this.gl.getParameter(this.gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxVertexAttributes:this.gl.getParameter(this.gl.MAX_VERTEX_ATTRIBS),maxMaxAnisotropy:e?Math.min(this.gl.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY),s):1,maxTextureImageUnits:this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),maxTextureSize:this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE),maxUniformBufferBindings:i?a.getParameter(a.MAX_UNIFORM_BUFFER_BINDINGS):0,maxVertexUniformBlocks:i?a.getParameter(a.MAX_VERTEX_UNIFORM_BLOCKS):0,maxFragmentUniformBlocks:i?a.getParameter(a.MAX_FRAGMENT_UNIFORM_BLOCKS):0,maxUniformBlockSize:i?a.getParameter(a.MAX_UNIFORM_BLOCK_SIZE):0,uniformBufferOffsetAlignment:i?a.getParameter(a.UNIFORM_BUFFER_OFFSET_ALIGNMENT):1,maxArrayTextureLayers:i?a.getParameter(a.MAX_ARRAY_TEXTURE_LAYERS):1,maxSamples:i?a.getParameter(a.MAX_SAMPLES):1};return P.TEXTURE_UNIT_FOR_UPDATES=r.maxTextureImageUnits-1,r}};function v(t,e,s,i){return e?i!==e&&t.bindBuffer(s,e.glName):t.bindBuffer(s,null),e}function D(t,e){switch(t){case O.POINTS:return 2*e;case O.TRIANGLES:return e/3;case O.TRIANGLE_STRIP:case O.TRIANGLE_FAN:return e-2;default:return 0}}export{I as RenderingContext};
|
package/views/webgl/Texture.js
CHANGED
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import"../../core/has.js";import{isPowerOfTwo as t}from"../../core/mathUtils.js";import{isSome as e,unwrap as i}from"../../core/maybe.js";import{checkWebGLError as r}from"./checkWebGLError.js";import{ContextType as o}from"./context-util.js";import{TextureType as s,TextureSamplingMode as a,TextureWrapMode as n,ResourceType as l,PixelType as h,PixelFormat as p,SizedPixelFormat as _,CompressedTextureFormat as m}from"./enums.js";import d from"./capabilities/isWebGL2Context.js";const u={target:s.TEXTURE_2D,samplingMode:a.LINEAR,wrapMode:n.REPEAT,flipped:!1,hasMipmap:!1,isOpaque:!1,unpackAlignment:4,preMultiplyAlpha:!1,isImmutable:!1},c=4;let E=class{constructor(t,e,i=null){this._context=t,this.type="texture",this._glName=null,this._samplingModeDirty=!1,this._wrapModeDirty=!1,this._wasImmutablyAllocated=!1,t.instanceCounter.increment(l.Texture,this),this._descriptor={...u,...e};for(const r in u){void 0===this._descriptor[r]&&(this._descriptor[r]=u[r])}if(t.type!==o.WEBGL2&&(this._descriptor.isImmutable&&(this._descriptor.isImmutable=!1),A(this._descriptor.target)))throw new Error("3D and array textures are not supported in WebGL1");this._descriptor.target===s.TEXTURE_CUBE_MAP?this._setDataCubeMap(i):this.setData(i)}get glName(){return this._glName}get descriptor(){return this._descriptor}get isDirty(){return this._samplingModeDirty||this._wrapModeDirty}dispose(){this._context.gl&&this._glName&&(this._context.unbindTexture(this),this._context.gl.deleteTexture(this._glName),this._glName=null,this._context.instanceCounter.decrement(l.Texture,this))}release(){this.dispose()}resize(t,e){const i=this._descriptor;if(i.width!==t||i.height!==e){if(this._wasImmutablyAllocated)throw new Error("Immutable textures can't be resized!");i.width=t,i.height=e,this._descriptor.target===s.TEXTURE_CUBE_MAP?this._setDataCubeMap(null):this.setData(null)}}_setDataCubeMap(t=null){for(let e=s.TEXTURE_CUBE_MAP_POSITIVE_X;e<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z;e++)this._setData(t,e)}setData(t){this._setData(t)}_setData(t,i){if(!this._context||!this._context.gl)return;const o=this._context.gl;this._glName||(this._glName=o.createTexture()),void 0===t&&(t=null);const s=this._descriptor,a=i??s.target,n=A(a);null===t&&(s.width=s.width||c,s.height=s.height||c,n&&(s.depth=s.depth??1));const l=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES);this._context.setActiveTexture(E.TEXTURE_UNIT_FOR_UPDATES),E._validateTexture(this._context,s),this._configurePixelStorage(),r(o);const h=s.pixelFormat;let p=s.internalFormat??this._deriveInternalFormat(h,s.dataType);if(f(t)){let e=t.width,i=t.height;const l=1;t instanceof HTMLVideoElement&&(e=t.videoWidth,i=t.videoHeight),s.width&&s.height,n&&s.depth,s.isImmutable&&!this._wasImmutablyAllocated&&this._texStorage(a,p,s.hasMipmap,e,i,l),this._texImage(a,0,p,e,i,l,t),r(o),s.hasMipmap&&this.generateMipmap(),void 0===s.width&&(s.width=e),void 0===s.height&&(s.height=i),n&&void 0===s.depth&&(s.depth=l)}else{const{width:i,height:l,depth:h}=s;if(null==i||null==l)throw new Error("Width and height must be specified!");if(n&&null==h)throw new Error("Depth must be specified!");if(s.isImmutable&&!this._wasImmutablyAllocated&&this._texStorage(a,p,s.hasMipmap,i,l,h),o.DEPTH24_STENCIL8&&p===o.DEPTH_STENCIL&&(p=o.DEPTH24_STENCIL8),x(t)){const e=t.levels,r=w(a,i,l,h),n=Math.min(r-1,e.length-1);d(o)?o.texParameteri(s.target,o.TEXTURE_MAX_LEVEL,n):s.hasMipmap=s.hasMipmap&&r===e.length;const _=p;if(!g(_))throw new Error("Attempting to use compressed data with an umcompressed format!");this._forEachMipmapLevel(((t,i,r,o)=>{const s=e[Math.min(t,e.length-1)];this._compressedTexImage(a,t,_,i,r,o,s)}),n)}else e(t)?(this._texImage(a,0,p,i,l,h,t),r(o),s.hasMipmap&&this.generateMipmap()):this._forEachMipmapLevel(((t,e,i,s)=>{this._texImage(a,t,p,e,i,s,null),r(o)}))}E._applySamplingMode(o,this._descriptor),E._applyWrapMode(o,this._descriptor),E._applyAnisotropicFilteringParameters(this._context,this._descriptor),r(o),this._context.bindTexture(l,E.TEXTURE_UNIT_FOR_UPDATES)}updateData(t,e,i,r,o,s,a=0){s||console.error("An attempt to use uninitialized data!"),this._glName||console.error("An attempt to update uninitialized texture!");const n=this._context.gl,l=this._descriptor,{pixelFormat:h,dataType:p,target:_,isImmutable:m}=l,u=l.internalFormat??this._deriveInternalFormat(h,p);if(m&&!this._wasImmutablyAllocated)throw new Error("Cannot update immutable texture before allocation!");const c=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES,!0);if((e<0||i<0||r>l.width||o>l.height||e+r>l.width||i+o>l.height)&&console.error("An attempt to update out of bounds of the texture!"),this._configurePixelStorage(),a){if(!d(n))return void console.error("Webgl2 must be enabled to use dataRowOffset!");n.pixelStorei(n.UNPACK_SKIP_ROWS,a)}if(f(s)?d(n)?n.texSubImage2D(_,t,e,i,r,o,h,p,s):n.texSubImage2D(_,t,e,i,h,p,s):x(s)?n.compressedTexSubImage2D(_,t,e,i,r,o,u,s.levels[t]):n.texSubImage2D(_,t,e,i,r,o,h,p,s),a){if(!d(n))return void console.error("Webgl2 must be enabled to use dataRowOffset!");n.pixelStorei(n.UNPACK_SKIP_ROWS,0)}this._context.bindTexture(c,E.TEXTURE_UNIT_FOR_UPDATES)}updateData3D(t,e,i,r,o,s,a,n){n||console.error("An attempt to use uninitialized data!"),this._glName||console.error("An attempt to update uninitialized texture!");const l=this._context.gl;if(!d(l))throw new Error("3D textures are not supported in WebGL1");const h=this._descriptor,{pixelFormat:p,dataType:_,isImmutable:m,target:u}=h,c=h.internalFormat??this._deriveInternalFormat(p,_);if(m&&!this._wasImmutablyAllocated)throw new Error("Cannot update immutable texture before allocation!");A(u)||console.warn("Attempting to set 3D texture data on a non-3D texture");const T=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES);if(this._context.setActiveTexture(E.TEXTURE_UNIT_FOR_UPDATES),(e<0||i<0||r<0||o>h.width||s>h.height||a>h.depth||e+o>h.width||i+s>h.height||r+a>h.depth)&&console.error("An attempt to update out of bounds of the texture!"),this._configurePixelStorage(),x(n))n=n.levels[t],l.compressedTexSubImage3D(u,t,e,i,r,o,s,a,c,n);else{const h=n;l.texSubImage3D(u,t,e,i,r,o,s,a,p,_,h)}this._context.bindTexture(T,E.TEXTURE_UNIT_FOR_UPDATES)}generateMipmap(){const t=this._descriptor;if(!t.hasMipmap){if(this._wasImmutablyAllocated)throw new Error("Cannot add mipmaps to immutable texture after allocation");t.hasMipmap=!0,this._samplingModeDirty=!0,E._validateTexture(this._context,t)}t.samplingMode===a.LINEAR?(this._samplingModeDirty=!0,t.samplingMode=a.LINEAR_MIPMAP_NEAREST):t.samplingMode===a.NEAREST&&(this._samplingModeDirty=!0,t.samplingMode=a.NEAREST_MIPMAP_NEAREST);const e=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES);this._context.setActiveTexture(E.TEXTURE_UNIT_FOR_UPDATES);this._context.gl.generateMipmap(t.target),this._context.bindTexture(e,E.TEXTURE_UNIT_FOR_UPDATES)}setSamplingMode(t){t!==this._descriptor.samplingMode&&(this._descriptor.samplingMode=t,this._samplingModeDirty=!0)}setWrapMode(t){t!==this._descriptor.wrapMode&&(this._descriptor.wrapMode=t,E._validateTexture(this._context,this._descriptor),this._wrapModeDirty=!0)}applyChanges(){const t=this._context.gl,e=this._descriptor;this._samplingModeDirty&&(E._applySamplingMode(t,e),this._samplingModeDirty=!1),this._wrapModeDirty&&(E._applyWrapMode(t,e),this._wrapModeDirty=!1)}_deriveInternalFormat(t,e){if(this._context.type===o.WEBGL1)return t;switch(e){case h.FLOAT:switch(t){case p.RGBA:return _.RGBA32F;case p.RGB:return _.RGB32F;default:throw new Error("Unable to derive format")}case h.UNSIGNED_BYTE:switch(t){case p.RGBA:return _.RGBA8;case p.RGB:return _.RGB8}default:return t}}_configurePixelStorage(){const t=this._context.gl,{unpackAlignment:e,flipped:i,preMultiplyAlpha:r}=this._descriptor;t.pixelStorei(t.UNPACK_ALIGNMENT,e),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,i?1:0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r?1:0)}_texStorage(t,e,i,r,o,s){const a=this._context.gl;if(!d(a))throw new Error("Immutable textures are not supported in WebGL1");if(!T(e))throw new Error("Immutable textures must have a sized internal format");if(!this._descriptor.isImmutable)return;const n=i?w(t,r,o,s):1;if(A(t)){if(null==s)throw new Error("Missing depth dimension for 3D texture upload");a.texStorage3D(t,n,e,r,o,s)}else a.texStorage2D(t,n,e,r,o);this._wasImmutablyAllocated=!0}_texImage(t,r,s,a,n,l,h){const p=this._context.gl;let _=null;const m=this._context.type===o.WEBGL2,d=A(t),{isImmutable:u,pixelFormat:c,dataType:E}=this._descriptor;if(m&&(_=p),m||!f(h))if(u){if(e(h)){const e=h;if(d){if(null==l)throw new Error("Missing depth dimension for 3D texture upload");_.texSubImage3D(t,r,0,0,0,a,n,l,c,E,e)}else p.texSubImage2D(t,r,0,0,a,n,c,E,e)}}else{const e=i(h);if(d){if(null==l)throw new Error("Missing depth dimension for 3D texture upload");_.texImage3D(t,r,s,a,n,l,0,c,E,e)}else p.texImage2D(t,r,s,a,n,0,c,E,e)}else p.texImage2D(t,0,s,c,E,h)}_compressedTexImage(t,i,r,s,a,n,l){const h=this._context.gl;let p=null;const _=A(t),m=this._descriptor.isImmutable;if(_){if(this._context.type!==o.WEBGL2)throw new Error("3D textures are not supported in WebGL1");p=h}if(m){if(e(l))if(_){if(null==n)throw new Error("Missing depth dimension for 3D texture upload");p.compressedTexSubImage3D(t,i,0,0,0,s,a,n,r,l)}else h.compressedTexSubImage2D(t,i,0,0,s,a,r,l)}else if(_){if(null==n)throw new Error("Missing depth dimension for 3D texture upload");p.compressedTexImage3D(t,i,r,s,a,n,0,l)}else h.compressedTexImage2D(t,i,r,s,a,0,l)}_forEachMipmapLevel(t,e=1/0){let{width:i,height:r,depth:o,hasMipmap:a,target:n}=this._descriptor;const l=n===s.TEXTURE_3D;if(null==i||null==r||l&&null==o)throw new Error("Missing texture dimensions for mipmap calculation");for(let s=0;t(s,i,r,o),a&&(1!==i||1!==r||l&&1!==o)&&!(s>=e);++s)i=Math.max(1,i>>1),r=Math.max(1,r>>1),l&&(o=Math.max(1,o>>1))}static _validateTexture(e,i){(null!=i.width&&i.width<0||null!=i.height&&i.height<0||null!=i.depth&&i.depth<0)&&console.error("Negative dimension parameters are not allowed!");const r=d(e.gl),o=null!=i.width&&t(i.width)&&null!=i.height&&t(i.height);r||!i.isImmutable&&!A(i.target)||console.error("Immutable and 3D-like textures are not supported in WebGL1!"),r||o||("number"==typeof i.wrapMode?i.wrapMode!==n.CLAMP_TO_EDGE&&console.error("Non-power-of-two textures must have a wrap mode of CLAMP_TO_EDGE!"):i.wrapMode.s===n.CLAMP_TO_EDGE&&i.wrapMode.t===n.CLAMP_TO_EDGE||console.error("Non-power-of-two textures must have a wrap mode of CLAMP_TO_EDGE!"),i.hasMipmap&&console.error("Mipmapping requires power-of-two textures!"))}static _applySamplingMode(t,e){let i=e.samplingMode,r=e.samplingMode;i===a.LINEAR_MIPMAP_NEAREST||i===a.LINEAR_MIPMAP_LINEAR?(i=a.LINEAR,e.hasMipmap||(r=a.LINEAR)):i!==a.NEAREST_MIPMAP_NEAREST&&i!==a.NEAREST_MIPMAP_LINEAR||(i=a.NEAREST,e.hasMipmap||(r=a.NEAREST)),t.texParameteri(e.target,t.TEXTURE_MAG_FILTER,i),t.texParameteri(e.target,t.TEXTURE_MIN_FILTER,r)}static _applyWrapMode(t,e){"number"==typeof e.wrapMode?(t.texParameteri(e.target,t.TEXTURE_WRAP_S,e.wrapMode),t.texParameteri(e.target,t.TEXTURE_WRAP_T,e.wrapMode)):(t.texParameteri(e.target,t.TEXTURE_WRAP_S,e.wrapMode.s),t.texParameteri(e.target,t.TEXTURE_WRAP_T,e.wrapMode.t))}static _applyAnisotropicFilteringParameters(t,e){const i=t.capabilities.textureFilterAnisotropic;if(!i)return;t.gl.texParameterf(e.target,i.TEXTURE_MAX_ANISOTROPY,e.maxAnisotropy??1)}};function T(t){return t in _}function g(t){return t in m}function x(t){return e(t)&&"type"in t&&"compressed"===t.type}function M(t){return e(t)&&"byteLength"in t}function f(t){return e(t)&&!x(t)&&!M(t)}function A(t){return t===s.TEXTURE_3D||t===s.TEXTURE_2D_ARRAY}function w(t,e,i,r=1){let o=Math.max(e,i);return t===s.TEXTURE_3D&&(o=Math.max(o,r)),Math.round(Math.log(o)/Math.LN2)+1}E.TEXTURE_UNIT_FOR_UPDATES=0;export{E as Texture};
|
|
5
|
+
import"../../core/has.js";import{isPowerOfTwo as t}from"../../core/mathUtils.js";import{isSome as e,isNone as i,unwrap as r}from"../../core/maybe.js";import{checkWebGLError as o}from"./checkWebGLError.js";import{ContextType as s}from"./context-util.js";import{TextureType as a,TextureSamplingMode as n,TextureWrapMode as l,ResourceType as h,PixelType as p,PixelFormat as _,SizedPixelFormat as m,CompressedTextureFormat as d}from"./enums.js";const u={target:a.TEXTURE_2D,samplingMode:n.LINEAR,wrapMode:l.REPEAT,flipped:!1,hasMipmap:!1,isOpaque:!1,unpackAlignment:4,preMultiplyAlpha:!1,isImmutable:!1},c=4;let E=class{constructor(t,e,i=null){this._context=t,this.type="texture",this._glName=null,this._samplingModeDirty=!1,this._wrapModeDirty=!1,this._wasImmutablyAllocated=!1,t.instanceCounter.increment(h.Texture,this),this._descriptor={...u,...e};for(const r in u){void 0===this._descriptor[r]&&(this._descriptor[r]=u[r])}if(t.type!==s.WEBGL2&&(this._descriptor.isImmutable&&(this._descriptor.isImmutable=!1),A(this._descriptor.target)))throw new Error("3D and array textures are not supported in WebGL1");this._descriptor.target===a.TEXTURE_CUBE_MAP?this._setDataCubeMap(i):this.setData(i)}get glName(){return this._glName}get descriptor(){return this._descriptor}get isDirty(){return this._samplingModeDirty||this._wrapModeDirty}dispose(){this._context.gl&&this._glName&&(this._context.unbindTexture(this),this._context.gl.deleteTexture(this._glName),this._glName=null,this._context.instanceCounter.decrement(h.Texture,this))}release(){this.dispose()}resize(t,e){const i=this._descriptor;if(i.width!==t||i.height!==e){if(this._wasImmutablyAllocated)throw new Error("Immutable textures can't be resized!");i.width=t,i.height=e,this._descriptor.target===a.TEXTURE_CUBE_MAP?this._setDataCubeMap(null):this.setData(null)}}_setDataCubeMap(t=null){for(let e=a.TEXTURE_CUBE_MAP_POSITIVE_X;e<=a.TEXTURE_CUBE_MAP_NEGATIVE_Z;e++)this._setData(t,e)}setData(t){this._setData(t)}_setData(t,i){if(!this._context||!this._context.gl)return;const r=this._context.gl;this._glName||(this._glName=r.createTexture()),void 0===t&&(t=null);const s=this._descriptor,a=i??s.target,n=A(a);null===t&&(s.width=s.width||c,s.height=s.height||c,n&&(s.depth=s.depth??1));const l=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES);this._context.setActiveTexture(E.TEXTURE_UNIT_FOR_UPDATES),E._validateTexture(this._context,s),this._configurePixelStorage(),o(r);const h=s.pixelFormat;let p=s.internalFormat??this._deriveInternalFormat(h,s.dataType);if(f(t)){let e=t.width,i=t.height;const l=1;t instanceof HTMLVideoElement&&(e=t.videoWidth,i=t.videoHeight),s.width&&s.height,n&&s.depth,s.isImmutable&&!this._wasImmutablyAllocated&&this._texStorage(a,p,s.hasMipmap,e,i,l),this._texImage(a,0,p,e,i,l,t),o(r),s.hasMipmap&&this.generateMipmap(),void 0===s.width&&(s.width=e),void 0===s.height&&(s.height=i),n&&void 0===s.depth&&(s.depth=l)}else{const{width:i,height:l,depth:h}=s;if(null==i||null==l)throw new Error("Width and height must be specified!");if(n&&null==h)throw new Error("Depth must be specified!");if(s.isImmutable&&!this._wasImmutablyAllocated&&this._texStorage(a,p,s.hasMipmap,i,l,h),r.DEPTH24_STENCIL8&&p===r.DEPTH_STENCIL&&(p=r.DEPTH24_STENCIL8),x(t)){const o=t.levels,n=w(a,i,l,h),_=Math.min(n-1,o.length-1);e(this._context.gl2)?r.texParameteri(s.target,this._context.gl2.TEXTURE_MAX_LEVEL,_):s.hasMipmap=s.hasMipmap&&n===o.length;const m=p;if(!T(m))throw new Error("Attempting to use compressed data with an umcompressed format!");this._forEachMipmapLevel(((t,e,i,r)=>{const s=o[Math.min(t,o.length-1)];this._compressedTexImage(a,t,m,e,i,r,s)}),_)}else e(t)?(this._texImage(a,0,p,i,l,h,t),o(r),s.hasMipmap&&this.generateMipmap()):this._forEachMipmapLevel(((t,e,i,s)=>{this._texImage(a,t,p,e,i,s,null),o(r)}))}E._applySamplingMode(r,this._descriptor),E._applyWrapMode(r,this._descriptor),E._applyAnisotropicFilteringParameters(this._context,this._descriptor),o(r),this._context.bindTexture(l,E.TEXTURE_UNIT_FOR_UPDATES)}updateData(t,r,o,s,a,n,l=0){n||console.error("An attempt to use uninitialized data!"),this._glName||console.error("An attempt to update uninitialized texture!");const h=this._context.gl,p=this._descriptor,{pixelFormat:_,dataType:m,target:d,isImmutable:u}=p,c=p.internalFormat??this._deriveInternalFormat(_,m);if(u&&!this._wasImmutablyAllocated)throw new Error("Cannot update immutable texture before allocation!");const g=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES,!0);if((r<0||o<0||s>p.width||a>p.height||r+s>p.width||o+a>p.height)&&console.error("An attempt to update out of bounds of the texture!"),this._configurePixelStorage(),l){if(i(this._context.gl2))return void console.error("Webgl2 must be enabled to use dataRowOffset!");h.pixelStorei(this._context.gl2.UNPACK_SKIP_ROWS,l)}if(f(n)?e(this._context.gl2)?this._context.gl2.texSubImage2D(d,t,r,o,s,a,_,m,n):h.texSubImage2D(d,t,r,o,_,m,n):x(n)?h.compressedTexSubImage2D(d,t,r,o,s,a,c,n.levels[t]):h.texSubImage2D(d,t,r,o,s,a,_,m,n),l){if(i(this._context.gl2))return void console.error("Webgl2 must be enabled to use dataRowOffset!");h.pixelStorei(this._context.gl2.UNPACK_SKIP_ROWS,0)}this._context.bindTexture(g,E.TEXTURE_UNIT_FOR_UPDATES)}updateData3D(t,e,r,o,s,a,n,l){l||console.error("An attempt to use uninitialized data!"),this._glName||console.error("An attempt to update uninitialized texture!");const h=this._context.gl2;if(i(h))throw new Error("3D textures are not supported in WebGL1");const p=this._descriptor,{pixelFormat:_,dataType:m,isImmutable:d,target:u}=p,c=p.internalFormat??this._deriveInternalFormat(_,m);if(d&&!this._wasImmutablyAllocated)throw new Error("Cannot update immutable texture before allocation!");A(u)||console.warn("Attempting to set 3D texture data on a non-3D texture");const g=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES);if(this._context.setActiveTexture(E.TEXTURE_UNIT_FOR_UPDATES),(e<0||r<0||o<0||s>p.width||a>p.height||n>p.depth||e+s>p.width||r+a>p.height||o+n>p.depth)&&console.error("An attempt to update out of bounds of the texture!"),this._configurePixelStorage(),x(l))l=l.levels[t],h.compressedTexSubImage3D(u,t,e,r,o,s,a,n,c,l);else{const i=l;h.texSubImage3D(u,t,e,r,o,s,a,n,_,m,i)}this._context.bindTexture(g,E.TEXTURE_UNIT_FOR_UPDATES)}generateMipmap(){const t=this._descriptor;if(!t.hasMipmap){if(this._wasImmutablyAllocated)throw new Error("Cannot add mipmaps to immutable texture after allocation");t.hasMipmap=!0,this._samplingModeDirty=!0,E._validateTexture(this._context,t)}t.samplingMode===n.LINEAR?(this._samplingModeDirty=!0,t.samplingMode=n.LINEAR_MIPMAP_NEAREST):t.samplingMode===n.NEAREST&&(this._samplingModeDirty=!0,t.samplingMode=n.NEAREST_MIPMAP_NEAREST);const e=this._context.bindTexture(this,E.TEXTURE_UNIT_FOR_UPDATES);this._context.setActiveTexture(E.TEXTURE_UNIT_FOR_UPDATES);this._context.gl.generateMipmap(t.target),this._context.bindTexture(e,E.TEXTURE_UNIT_FOR_UPDATES)}setSamplingMode(t){t!==this._descriptor.samplingMode&&(this._descriptor.samplingMode=t,this._samplingModeDirty=!0)}setWrapMode(t){t!==this._descriptor.wrapMode&&(this._descriptor.wrapMode=t,E._validateTexture(this._context,this._descriptor),this._wrapModeDirty=!0)}applyChanges(){const t=this._context.gl,e=this._descriptor;this._samplingModeDirty&&(E._applySamplingMode(t,e),this._samplingModeDirty=!1),this._wrapModeDirty&&(E._applyWrapMode(t,e),this._wrapModeDirty=!1)}_deriveInternalFormat(t,e){if(this._context.type===s.WEBGL1)return t;switch(e){case p.FLOAT:switch(t){case _.RGBA:return m.RGBA32F;case _.RGB:return m.RGB32F;default:throw new Error("Unable to derive format")}case p.UNSIGNED_BYTE:switch(t){case _.RGBA:return m.RGBA8;case _.RGB:return m.RGB8}default:return t}}_configurePixelStorage(){const t=this._context.gl,{unpackAlignment:e,flipped:i,preMultiplyAlpha:r}=this._descriptor;t.pixelStorei(t.UNPACK_ALIGNMENT,e),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,i?1:0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r?1:0)}_texStorage(t,e,r,o,s,a){const n=this._context.gl2;if(i(n))throw new Error("Immutable textures are not supported in WebGL1");if(!g(e))throw new Error("Immutable textures must have a sized internal format");if(!this._descriptor.isImmutable)return;const l=r?w(t,o,s,a):1;if(A(t)){if(null==a)throw new Error("Missing depth dimension for 3D texture upload");n.texStorage3D(t,l,e,o,s,a)}else n.texStorage2D(t,l,e,o,s);this._wasImmutablyAllocated=!0}_texImage(t,i,o,a,n,l,h){const p=this._context.gl;let _=null;const m=this._context.type===s.WEBGL2,d=A(t),{isImmutable:u,pixelFormat:c,dataType:E}=this._descriptor;if(m&&(_=p),m||!f(h))if(u){if(e(h)){const e=h;if(d){if(null==l)throw new Error("Missing depth dimension for 3D texture upload");_.texSubImage3D(t,i,0,0,0,a,n,l,c,E,e)}else p.texSubImage2D(t,i,0,0,a,n,c,E,e)}}else{const e=r(h);if(d){if(null==l)throw new Error("Missing depth dimension for 3D texture upload");_.texImage3D(t,i,o,a,n,l,0,c,E,e)}else p.texImage2D(t,i,o,a,n,0,c,E,e)}else p.texImage2D(t,0,o,c,E,h)}_compressedTexImage(t,i,r,o,a,n,l){const h=this._context.gl;let p=null;const _=A(t),m=this._descriptor.isImmutable;if(_){if(this._context.type!==s.WEBGL2)throw new Error("3D textures are not supported in WebGL1");p=h}if(m){if(e(l))if(_){if(null==n)throw new Error("Missing depth dimension for 3D texture upload");p.compressedTexSubImage3D(t,i,0,0,0,o,a,n,r,l)}else h.compressedTexSubImage2D(t,i,0,0,o,a,r,l)}else if(_){if(null==n)throw new Error("Missing depth dimension for 3D texture upload");p.compressedTexImage3D(t,i,r,o,a,n,0,l)}else h.compressedTexImage2D(t,i,r,o,a,0,l)}_forEachMipmapLevel(t,e=1/0){let{width:i,height:r,depth:o,hasMipmap:s,target:n}=this._descriptor;const l=n===a.TEXTURE_3D;if(null==i||null==r||l&&null==o)throw new Error("Missing texture dimensions for mipmap calculation");for(let a=0;t(a,i,r,o),s&&(1!==i||1!==r||l&&1!==o)&&!(a>=e);++a)i=Math.max(1,i>>1),r=Math.max(1,r>>1),l&&(o=Math.max(1,o>>1))}static _validateTexture(e,i){(null!=i.width&&i.width<0||null!=i.height&&i.height<0||null!=i.depth&&i.depth<0)&&console.error("Negative dimension parameters are not allowed!");const r=e.type===s.WEBGL2,o=null!=i.width&&t(i.width)&&null!=i.height&&t(i.height);r||!i.isImmutable&&!A(i.target)||console.error("Immutable and 3D-like textures are not supported in WebGL1!"),r||o||("number"==typeof i.wrapMode?i.wrapMode!==l.CLAMP_TO_EDGE&&console.error("Non-power-of-two textures must have a wrap mode of CLAMP_TO_EDGE!"):i.wrapMode.s===l.CLAMP_TO_EDGE&&i.wrapMode.t===l.CLAMP_TO_EDGE||console.error("Non-power-of-two textures must have a wrap mode of CLAMP_TO_EDGE!"),i.hasMipmap&&console.error("Mipmapping requires power-of-two textures!"))}static _applySamplingMode(t,e){let i=e.samplingMode,r=e.samplingMode;i===n.LINEAR_MIPMAP_NEAREST||i===n.LINEAR_MIPMAP_LINEAR?(i=n.LINEAR,e.hasMipmap||(r=n.LINEAR)):i!==n.NEAREST_MIPMAP_NEAREST&&i!==n.NEAREST_MIPMAP_LINEAR||(i=n.NEAREST,e.hasMipmap||(r=n.NEAREST)),t.texParameteri(e.target,t.TEXTURE_MAG_FILTER,i),t.texParameteri(e.target,t.TEXTURE_MIN_FILTER,r)}static _applyWrapMode(t,e){"number"==typeof e.wrapMode?(t.texParameteri(e.target,t.TEXTURE_WRAP_S,e.wrapMode),t.texParameteri(e.target,t.TEXTURE_WRAP_T,e.wrapMode)):(t.texParameteri(e.target,t.TEXTURE_WRAP_S,e.wrapMode.s),t.texParameteri(e.target,t.TEXTURE_WRAP_T,e.wrapMode.t))}static _applyAnisotropicFilteringParameters(t,e){const i=t.capabilities.textureFilterAnisotropic;if(!i)return;t.gl.texParameterf(e.target,i.TEXTURE_MAX_ANISOTROPY,e.maxAnisotropy??1)}};function g(t){return t in m}function T(t){return t in d}function x(t){return e(t)&&"type"in t&&"compressed"===t.type}function M(t){return e(t)&&"byteLength"in t}function f(t){return e(t)&&!x(t)&&!M(t)}function A(t){return t===a.TEXTURE_3D||t===a.TEXTURE_2D_ARRAY}function w(t,e,i,r=1){let o=Math.max(e,i);return t===a.TEXTURE_3D&&(o=Math.max(o,r)),Math.round(Math.log(o)/Math.LN2)+1}E.TEXTURE_UNIT_FOR_UPDATES=0;export{E as Texture};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.26/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../core/Collection.js";import{deprecated as r}from"../../core/deprecate.js";import a from"../../core/Error.js";import o from"../../core/Evented.js";import{HandleOwnerMixin as i}from"../../core/HandleOwner.js";import s from"../../core/Logger.js";import{on as n,when as l,watch as d,whenOnce as c,initial as p}from"../../core/reactiveUtils.js";import{property as u}from"../../core/accessorSupport/decorators/property.js";import"../../core/accessorSupport/ensureType.js";import"../../core/arrayUtils.js";import{subclass as w}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../layers/GraphicsLayer.js";import f from"../Attachments/AttachmentsViewModel.js";import m from"./CreateFeaturesWorkflow.js";import y from"./CreateWorkflow.js";import{workflowDeprecation as k}from"./deprecationUtils.js";import W from"./UpdateWorkflow.js";import _ from"../FeatureForm/FeatureFormViewModel.js";import g from"../FeatureTemplates/FeatureTemplatesViewModel.js";import v from"../Sketch/SketchViewModel.js";import b from"../Spinner/SpinnerViewModel.js";const C="esri.widgets.Editor.EditorViewModel",F=s.getLogger(C),E=["create","create-features","update"];function O(e,t,r){F.error(new a(e,t,r))}function A(e,t){return e?e.find((e=>e.layer===t)):void 0}let U=class extends(i(o.EventedAccessor)){constructor(e){super(e),this._sketchGraphicsLayer=new h({listMode:"hide",internal:!0}),this.activeWorkflow=null,this._activityQueue=[],this.failures=[],this.attachmentsViewModel=new f({abilities:{editing:!0}}),this.featureFormViewModel=new _,this.featureTemplatesViewModel=new g,this.sketchViewModel=new v({layer:this._sketchGraphicsLayer}),this.spinnerViewModel=new b}initialize(){this.handles.add([n((()=>this.activeWorkflow),"cancel",(()=>this.emit("workflow-cancel"))),n((()=>this.activeWorkflow),"commit",(()=>this.emit("workflow-commit"))),l((()=>this.view?.map),(e=>{e.add(this._sketchGraphicsLayer)}),p),d((()=>this.editableItems.toArray()),(()=>{const{activeWorkflow:e}=this;if(this.refreshCreationTemplates(),!e)return;const{stepId:t}=e;"create"!==e.type?"update"===e.type&&("awaiting-feature-to-update"===t&&!this.canUpdate||"awaiting-update-feature-candidate"===t&&!e.data.candidates.some((e=>{const t=this.editableItems.find((t=>t.layer===e.layer));return t&&t.supports.includes("update")})))&&this._cancelWorkflow():"awaiting-feature-creation-info"!==t||this.canCreate||this._cancelWorkflow()}))])}destroy(){this._cancelWorkflow().then((()=>{this.view?.map&&this.view.map.remove(this._sketchGraphicsLayer),this.view=null}))}get allowedWorkflows(){return this._get("allowedWorkflows")}set allowedWorkflows(e){e&&0!==e.length||(e=[...E]),this._set("allowedWorkflows",e)}get canCreate(){return this.editableItems.some((e=>e.supports.includes("create")))}get canUpdate(){return this.editableItems.some((e=>e.supports.includes("update")||e.supports.includes("delete")||e.attachmentsOnUpdateEnabled))}get editableItems(){const e=this.view?.allLayerViews;if(!e)return new t;const r=this.view?.map?.editableLayers,a=new Set(r),o=r?.filter((e=>e.visible&&e.capabilities.operations.supportsAdd&&!e.capabilities.operations.supportsQuery)),i=e.filter((e=>a.has(e.layer))).map((({layer:e,suspended:t})=>this._getEditableItemFromLayer(e,t))).reverse();return o?.forEach((e=>i.push(this._getEditableItemFromLayer(e,!1)))),i}get labelOptions(){return this.sketchViewModel.labelOptions}set labelOptions(e){this.sketchViewModel.labelOptions=e}set layerInfos(e){e?.some((e=>{const t=!1!==e.allowAttachments;return t&&r(F,"Property: layerInfo.allowAttachments",{replacement:"layerInfo.attachmentsOnCreateEnabled or layerInfo.attachmentsOnUpdateEnabled",version:"4.26"}),t})),this._set("layerInfos",e)}get snappingOptions(){return this.sketchViewModel.snappingOptions}set snappingOptions(e){this.sketchViewModel.snappingOptions=e}get state(){if(!this.get("view.ready")||0===this.editableItems.length)return"disabled";const e=this.attachmentsViewModel.mode;if("add"===e)return"adding-attachment";if("edit"===e)return"editing-attachment";const{activeWorkflow:t}=this;return t?t.stepId:"ready"}get syncing(){return this._activityQueue.length>0}get tooltipOptions(){return this.sketchViewModel.tooltipOptions}set tooltipOptions(e){this.sketchViewModel.tooltipOptions=e}set view(e){this.sketchViewModel.view=e,this.spinnerViewModel.view=e,this._set("view",e)}async startCreateWorkflowAtFeatureTypeSelection(){if(k(F,"startCreateWorkflowAtFeatureTypeSelection","startCreateFeaturesWorkflowAtFeatureTypeSelection"),!this.canCreate)return void O("editing:unsupported-workflow","Create workflow is unsupported or disabled.");await this._cancelWorkflow();const e=this._createCreateWorkflow();await e.start(),this._set("activeWorkflow",e)}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateWorkflowAtFeatureCreation(e){if(k(F,"startCreateWorkflowAtFeatureCreation","startCreateFeaturesWorkflowAtFeatureCreation"),!this.canCreate)return void O("editing:unsupported-workflow","Create workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createCreateWorkflow("awaiting-feature-to-create");t.data.creationInfo=e,await t.start(),this._set("activeWorkflow",t)}async startCreateFeaturesWorkflowAtFeatureCreation(e){return this.startCreateFeaturesWorkflow(e,"creating-features")}async startCreateFeaturesWorkflow(e,t="awaiting-feature-creation-info"){if(!this.canCreate)throw new a("editing:unsupported-workflow","Creating features is unsupported or disabled.");await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow(e,t);await r.start(),this._set("activeWorkflow",r)}async startCreateWorkflowAtFeatureEdit(e){if(k(F,"startCreateWorkflowAtFeatureEdit"),!this.canCreate)return void O("editing:unsupported-workflow","Create workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createCreateWorkflow("editing-new-feature");t.data.edits.feature=e,await t.start(),this._set("activeWorkflow",t)}async startUpdateWorkflowAtFeatureSelection(){if(!this.canUpdate)return void O("editing:unsupported-workflow","Update workflow is unsupported or disabled.");await this._cancelWorkflow();const e=this._createUpdateWorkflow();await e.start(),this._set("activeWorkflow",e)}async startUpdateWorkflowAtMultipleFeatureSelection(e){if(!this.canUpdate)return void O("editing:unsupported-workflow","Update workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createUpdateWorkflow("awaiting-update-feature-candidate");t.data.candidates=e,await t.start(),this._set("activeWorkflow",t)}async startUpdateWorkflowAtFeatureEdit(e){if(!this.canUpdate)return void O("editing:unsupported-workflow","Update workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createUpdateWorkflow("editing-existing-feature");t.data.edits.feature=e,await t.start(),this._set("activeWorkflow",t)}async deleteFeatureFromWorkflow(){const{activeWorkflow:e}=this;e&&"update"===e.type?(await this._delete(e.data.edits.feature),await e.reset()):O("editing:unsupported-workflow","Deleting requires an active update workflow.")}async cancelWorkflow(e){return this._cancelWorkflow({warn:!0,...e})}refreshCreationTemplates(){const e=[];for(const{layer:t,supports:r}of this.editableItems)t.loaded&&r.includes("create")&&e.push(t);this.featureTemplatesViewModel.layers=e}async _cancelWorkflow(e){const t=this.activeWorkflow;if(!t)return void(e&&e.warn&&O("editing:no-active-workflow","There is no active workflow to cancel."));if(!e||!1!==e.force)return this.emit("workflow-cancel"),this._set("activeWorkflow",null),void await t.cancel(e);await t.cancel(e),this._set("activeWorkflow",null)}_createCreateFeaturesWorkflow(e,t){return m.create(this,e,t,((e,t,r)=>this._applyEdits(e,t,r)),((e,t)=>this._addAttachments(e,t)))}_createCreateWorkflow(e){return y.create(this,e,((e,t,r)=>this._applyEdits(e,t,r)))}_createUpdateWorkflow(e){return W.create(this,e,((e,t)=>this._applyEdits(e,t)))}async _delete(e){const t=e?.sourceLayer;t&&"applyEdits"in t&&await this._applyEdits(t,{deleteFeatures:[e]})}_addAttachments(e,t){const r=[];return t?.forEach((t=>r.push(this._addAttachment(e,t.feature,t.attachment)))),Promise.all(r)}async _addAttachment(e,t,r){let a=null;return await this._queueOperation((async()=>(a=await(e.addAttachment?.(t,r).catch((e=>{throw e?.error||e})))??null,a))),a}async _applyEdits(e,t,r){let a=null;return await this._queueOperation((async()=>{if(e.capabilities.operations.supportsQuery){const o=await this.view.whenLayerView(e);return a=await e.applyEdits(t,r),await c((()=>!o.updating)),a}return a=await e.applyEdits(t,r),a})),a}_queueOperation(e){this._activityQueue.push(e),this.notifyChange("syncing");const t=(e,t)=>{const r=t.indexOf(e);r>-1&&t.splice(r,1)};return e().then((e=>{if("error"in e&&e.error)throw e.error;if("addFeatureResults"in e){const{addFeatureResults:t,deleteFeatureResults:r,updateFeatureResults:a}=e,o=t.find((e=>!!e.error))||a.find((e=>!!e.error))||r.find((e=>!!e.error));if(o)throw o.error}return e})).catch((r=>{O("editing:operation-error","An error occurred.",{error:r});const a={error:r,retry:()=>(t(a,this.failures),this._queueOperation(e)),cancel:()=>{t(a,this.failures)}};this._set("failures",[...this.failures,a])})).then((()=>{t(e,this._activityQueue),this.notifyChange("syncing")}))}_getEditableItemFromLayer(e,t=!0){const{data:r,editing:{supportsGeometryUpdate:a},operations:o}=e.capabilities,i=A(this.layerInfos,e),s=this.allowedWorkflows,n=[];o.supportsAdd&&(s.includes("create")||s.includes("create-features"))&&(!i||!1!==i.enabled&&!1!==i.addEnabled)&&n.push("create");const l=o.supportsUpdate&&s.includes("update")&&(!i||!1!==i.enabled&&!1!==i.updateEnabled);l&&n.push("update"),o.supportsDelete&&s.includes("update")&&(!i||!1!==i.enabled&&!1!==i.deleteEnabled)&&n.push("delete");const d=l&&(!i||!1!==i.attributeUpdatesEnabled),c=l&&a&&(!i||!1!==i.geometryUpdatesEnabled),p=!!r.supportsAttachment&&(n.includes("create")||n.includes("update"))&&(!i||!1!==i.allowAttachments);return{layer:e,supports:t?[]:n,attributeUpdatesEnabled:d,geometryUpdatesEnabled:c,hasAttachments:p,attachmentsOnCreateEnabled:p&&(s.includes("create")||s.includes("create-features"))&&(!i||!1!==i.attachmentsOnCreateEnabled),attachmentsOnUpdateEnabled:p&&s.includes("update")&&(!i||!1!==i.attachmentsOnUpdateEnabled)}}};e([u({readOnly:!0})],U.prototype,"activeWorkflow",void 0),e([u({readOnly:!0})],U.prototype,"_activityQueue",void 0),e([u({value:[...E]})],U.prototype,"allowedWorkflows",null),e([u({readOnly:!0})],U.prototype,"canCreate",null),e([u({readOnly:!0})],U.prototype,"canUpdate",null),e([u({readOnly:!0})],U.prototype,"editableItems",null),e([u({readOnly:!0})],U.prototype,"failures",void 0),e([u()],U.prototype,"attachmentsViewModel",void 0),e([u()],U.prototype,"featureFormViewModel",void 0),e([u()],U.prototype,"featureTemplatesViewModel",void 0),e([u()],U.prototype,"labelOptions",null),e([u()],U.prototype,"layerInfos",null),e([u()],U.prototype,"sketchViewModel",void 0),e([u()],U.prototype,"snappingOptions",null),e([u()],U.prototype,"spinnerViewModel",void 0),e([u()],U.prototype,"state",null),e([u({readOnly:!0})],U.prototype,"syncing",null),e([u()],U.prototype,"tooltipOptions",null),e([u()],U.prototype,"view",null),U=e([w(C)],U);const M=U;export{M as default};
|
|
5
|
+
import{_ as e}from"../../chunks/tslib.es6.js";import t from"../../core/Collection.js";import{deprecated as r}from"../../core/deprecate.js";import a from"../../core/Error.js";import o from"../../core/Evented.js";import{HandleOwnerMixin as i}from"../../core/HandleOwner.js";import s from"../../core/Logger.js";import{on as n,when as l,watch as d,whenOnce as p,initial as c}from"../../core/reactiveUtils.js";import{property as u}from"../../core/accessorSupport/decorators/property.js";import"../../core/accessorSupport/ensureType.js";import"../../core/arrayUtils.js";import{subclass as w}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../layers/GraphicsLayer.js";import f from"../Attachments/AttachmentsViewModel.js";import m from"./CreateFeaturesWorkflow.js";import y from"./CreateWorkflow.js";import{workflowDeprecation as k}from"./deprecationUtils.js";import g from"./UpdateWorkflow.js";import W from"../FeatureForm/FeatureFormViewModel.js";import v from"../FeatureTemplates/FeatureTemplatesViewModel.js";import _ from"../Sketch/SketchViewModel.js";import b from"../Spinner/SpinnerViewModel.js";const C="esri.widgets.Editor.EditorViewModel",F=s.getLogger(C),O=["create","create-features","update"];function E(e,t,r){F.error(new a(e,t,r))}function A(e,t){return e?e.find((e=>e.layer===t)):void 0}let U=class extends(i(o.EventedAccessor)){constructor(e){super(e),this._sketchGraphicsLayer=new h({listMode:"hide",internal:!0}),this.activeWorkflow=null,this._activityQueue=[],this.failures=[],this.attachmentsViewModel=new f({abilities:{editing:!0}}),this.featureFormViewModel=new W,this.featureTemplatesViewModel=new v,this.sketchViewModel=new _({layer:this._sketchGraphicsLayer}),this.spinnerViewModel=new b,this.pageStack=[]}initialize(){this.handles.add([n((()=>this.activeWorkflow),"cancel",(()=>this.emit("workflow-cancel"))),n((()=>this.activeWorkflow),"commit",(()=>this.emit("workflow-commit"))),l((()=>this.view?.map),(e=>{e.add(this._sketchGraphicsLayer)}),c),d((()=>this.editableItems.toArray()),(()=>{const{activeWorkflow:e}=this;if(this.refreshCreationTemplates(),!e)return;const{stepId:t}=e;"create"!==e.type?"update"===e.type&&("awaiting-feature-to-update"===t&&!this.canUpdate||"awaiting-update-feature-candidate"===t&&!e.data.candidates.some((e=>{const t=this.editableItems.find((t=>t.layer===e.layer));return t&&t.supports.includes("update")})))&&this._cancelWorkflow():"awaiting-feature-creation-info"!==t||this.canCreate||this._cancelWorkflow()})),d((()=>this.page),((e,t)=>{const r=this.pageStack.slice(),a=r.indexOf(e);-1===a&&t?r.push(t):r.splice(a),this.pageStack=r}))])}destroy(){this._cancelWorkflow().then((()=>{this.view?.map&&this.view.map.remove(this._sketchGraphicsLayer),this.view=null}))}get allowedWorkflows(){return this._get("allowedWorkflows")}set allowedWorkflows(e){e&&0!==e.length||(e=[...O]),this._set("allowedWorkflows",e)}get canCreate(){return this.editableItems.some((e=>e.supports.includes("create")))}get canUpdate(){return this.editableItems.some((e=>e.supports.includes("update")||e.supports.includes("delete")||e.attachmentsOnUpdateEnabled))}get editableItems(){const e=this.view?.allLayerViews;if(!e)return new t;const r=this.view?.map?.editableLayers,a=new Set(r),o=r?.filter((e=>e.visible&&e.capabilities.operations.supportsAdd&&!e.capabilities.operations.supportsQuery)),i=e.filter((e=>a.has(e.layer))).map((({layer:e,suspended:t})=>this._getEditableItemFromLayer(e,t))).reverse();return o?.forEach((e=>i.push(this._getEditableItemFromLayer(e,!1)))),i}get labelOptions(){return this.sketchViewModel.labelOptions}set labelOptions(e){this.sketchViewModel.labelOptions=e}set layerInfos(e){e?.some((e=>{const t=!1!==e.allowAttachments;return t&&r(F,"Property: layerInfo.allowAttachments",{replacement:"layerInfo.attachmentsOnCreateEnabled or layerInfo.attachmentsOnUpdateEnabled",version:"4.26"}),t})),this._set("layerInfos",e)}get snappingOptions(){return this.sketchViewModel.snappingOptions}set snappingOptions(e){this.sketchViewModel.snappingOptions=e}get state(){if(!this.get("view.ready")||0===this.editableItems.length)return"disabled";const e=this.attachmentsViewModel.mode;if("add"===e)return"adding-attachment";if("edit"===e)return"editing-attachment";const{activeWorkflow:t}=this;return t?t.stepId:"ready"}get syncing(){return this._activityQueue.length>0}get tooltipOptions(){return this.sketchViewModel.tooltipOptions}set tooltipOptions(e){this.sketchViewModel.tooltipOptions=e}set view(e){this.sketchViewModel.view=e,this.spinnerViewModel.view=e,this._set("view",e)}get page(){const{activeWorkflow:e,state:t}=this;return"awaiting-feature-to-update"===t||"awaiting-feature-to-create"===t||e&&"create-features"===e.type&&e.pendingFeatures.length<1?"ready":t??"disabled"}async startCreateWorkflowAtFeatureTypeSelection(){if(k(F,"startCreateWorkflowAtFeatureTypeSelection","startCreateFeaturesWorkflowAtFeatureTypeSelection"),!this.canCreate)return void E("editing:unsupported-workflow","Create workflow is unsupported or disabled.");await this._cancelWorkflow();const e=this._createCreateWorkflow();await e.start(),this._set("activeWorkflow",e)}async startCreateFeaturesWorkflowAtFeatureTypeSelection(){return this.startCreateFeaturesWorkflow()}async startCreateWorkflowAtFeatureCreation(e){if(k(F,"startCreateWorkflowAtFeatureCreation","startCreateFeaturesWorkflowAtFeatureCreation"),!this.canCreate)return void E("editing:unsupported-workflow","Create workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createCreateWorkflow("awaiting-feature-to-create");t.data.creationInfo=e,await t.start(),this._set("activeWorkflow",t)}async startCreateFeaturesWorkflowAtFeatureCreation(e){return this.startCreateFeaturesWorkflow(e,"creating-features")}async startCreateFeaturesWorkflow(e,t="awaiting-feature-creation-info"){if(!this.canCreate)throw new a("editing:unsupported-workflow","Creating features is unsupported or disabled.");await this._cancelWorkflow();const r=this._createCreateFeaturesWorkflow(e,t);await r.start(),this._set("activeWorkflow",r)}async startCreateWorkflowAtFeatureEdit(e){if(k(F,"startCreateWorkflowAtFeatureEdit"),!this.canCreate)return void E("editing:unsupported-workflow","Create workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createCreateWorkflow("editing-new-feature");t.data.edits.feature=e,await t.start(),this._set("activeWorkflow",t)}async startUpdateWorkflowAtFeatureSelection(){if(!this.canUpdate)return void E("editing:unsupported-workflow","Update workflow is unsupported or disabled.");await this._cancelWorkflow();const e=this._createUpdateWorkflow();await e.start(),this._set("activeWorkflow",e)}async startUpdateWorkflowAtMultipleFeatureSelection(e){if(!this.canUpdate)return void E("editing:unsupported-workflow","Update workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createUpdateWorkflow("awaiting-update-feature-candidate");t.data.candidates=e,await t.start(),this._set("activeWorkflow",t)}async startUpdateWorkflowAtFeatureEdit(e){if(!this.canUpdate)return void E("editing:unsupported-workflow","Update workflow is unsupported or disabled.");await this._cancelWorkflow();const t=this._createUpdateWorkflow("editing-existing-feature");t.data.edits.feature=e,await t.start(),this._set("activeWorkflow",t)}async deleteFeatureFromWorkflow(){const{activeWorkflow:e}=this;e&&"update"===e.type?(await this._delete(e.data.edits.feature),await e.reset()):E("editing:unsupported-workflow","Deleting requires an active update workflow.")}async cancelWorkflow(e){return this._cancelWorkflow({warn:!0,...e})}refreshCreationTemplates(){const e=[];for(const{layer:t,supports:r}of this.editableItems)t.loaded&&r.includes("create")&&e.push(t);this.featureTemplatesViewModel.layers=e}async _cancelWorkflow(e){const t=this.activeWorkflow;if(!t)return void(e&&e.warn&&E("editing:no-active-workflow","There is no active workflow to cancel."));if(!e||!1!==e.force)return this.emit("workflow-cancel"),this._set("activeWorkflow",null),void await t.cancel(e);await t.cancel(e),this._set("activeWorkflow",null)}_createCreateFeaturesWorkflow(e,t){return m.create(this,e,t,((e,t,r)=>this._applyEdits(e,t,r)),((e,t)=>this._addAttachments(e,t)))}_createCreateWorkflow(e){return y.create(this,e,((e,t,r)=>this._applyEdits(e,t,r)))}_createUpdateWorkflow(e){return g.create(this,e,((e,t)=>this._applyEdits(e,t)))}async _delete(e){const t=e?.sourceLayer;t&&"applyEdits"in t&&await this._applyEdits(t,{deleteFeatures:[e]})}_addAttachments(e,t){const r=[];return t?.forEach((t=>r.push(this._addAttachment(e,t.feature,t.attachment)))),Promise.all(r)}async _addAttachment(e,t,r){let a=null;return await this._queueOperation((async()=>(a=await(e.addAttachment?.(t,r).catch((e=>{throw e?.error||e})))??null,a))),a}async _applyEdits(e,t,r){let a=null;return await this._queueOperation((async()=>{if(e.capabilities.operations.supportsQuery){const o=await this.view.whenLayerView(e);return a=await e.applyEdits(t,r),await p((()=>!o.updating)),a}return a=await e.applyEdits(t,r),a})),a}_queueOperation(e){this._activityQueue.push(e),this.notifyChange("syncing");const t=(e,t)=>{const r=t.indexOf(e);r>-1&&t.splice(r,1)};return e().then((e=>{if("error"in e&&e.error)throw e.error;if("addFeatureResults"in e){const{addFeatureResults:t,deleteFeatureResults:r,updateFeatureResults:a}=e,o=t.find((e=>!!e.error))||a.find((e=>!!e.error))||r.find((e=>!!e.error));if(o)throw o.error}return e})).catch((r=>{E("editing:operation-error","An error occurred.",{error:r});const a={error:r,retry:()=>(t(a,this.failures),this._queueOperation(e)),cancel:()=>{t(a,this.failures)}};this._set("failures",[...this.failures,a])})).then((()=>{t(e,this._activityQueue),this.notifyChange("syncing")}))}_getEditableItemFromLayer(e,t=!0){const{data:r,editing:{supportsGeometryUpdate:a},operations:o}=e.capabilities,i=A(this.layerInfos,e),s=this.allowedWorkflows,n=[];o.supportsAdd&&(s.includes("create")||s.includes("create-features"))&&(!i||!1!==i.enabled&&!1!==i.addEnabled)&&n.push("create");const l=o.supportsUpdate&&s.includes("update")&&(!i||!1!==i.enabled&&!1!==i.updateEnabled);l&&n.push("update"),o.supportsDelete&&s.includes("update")&&(!i||!1!==i.enabled&&!1!==i.deleteEnabled)&&n.push("delete");const d=l&&(!i||!1!==i.attributeUpdatesEnabled),p=l&&a&&(!i||!1!==i.geometryUpdatesEnabled),c=!!r.supportsAttachment&&(n.includes("create")||n.includes("update"))&&(!i||!1!==i.allowAttachments);return{layer:e,supports:t?[]:n,attributeUpdatesEnabled:d,geometryUpdatesEnabled:p,hasAttachments:c,attachmentsOnCreateEnabled:c&&(s.includes("create")||s.includes("create-features"))&&(!i||!1!==i.attachmentsOnCreateEnabled),attachmentsOnUpdateEnabled:c&&s.includes("update")&&(!i||!1!==i.attachmentsOnUpdateEnabled)}}};e([u({readOnly:!0})],U.prototype,"activeWorkflow",void 0),e([u({readOnly:!0})],U.prototype,"_activityQueue",void 0),e([u({value:[...O]})],U.prototype,"allowedWorkflows",null),e([u({readOnly:!0})],U.prototype,"canCreate",null),e([u({readOnly:!0})],U.prototype,"canUpdate",null),e([u({readOnly:!0})],U.prototype,"editableItems",null),e([u({readOnly:!0})],U.prototype,"failures",void 0),e([u()],U.prototype,"attachmentsViewModel",void 0),e([u()],U.prototype,"featureFormViewModel",void 0),e([u()],U.prototype,"featureTemplatesViewModel",void 0),e([u()],U.prototype,"labelOptions",null),e([u()],U.prototype,"layerInfos",null),e([u()],U.prototype,"sketchViewModel",void 0),e([u()],U.prototype,"snappingOptions",null),e([u()],U.prototype,"spinnerViewModel",void 0),e([u()],U.prototype,"state",null),e([u({readOnly:!0})],U.prototype,"syncing",null),e([u()],U.prototype,"tooltipOptions",null),e([u()],U.prototype,"view",null),e([u()],U.prototype,"pageStack",void 0),e([u()],U.prototype,"page",null),U=e([w(C)],U);const M=U;export{M as default};
|