/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import{has}from"../../../../applications/Components/baUtils.js";import{reallocGrowthFactor as t}from"../../../../core/arrayUtils.js";import{initialSplatAtlasTextureHeight as e,GaussianSplatAtlasPages as s,splatAtlasTextureWidth as r,elementsPerSplatPage as a}from"./GaussianSplatAtlasPages.js";import{PixelType as i,SizedPixelFormat as l}from"../../../webgl/enums.js";import{DisposableFramebufferObject as o}from"../../../webgl/FramebufferObject.js";import h from"../../../webgl/Texture.js";import{TextureDescriptor as u}from"../../../webgl/TextureDescriptor.js";class c{constructor(t,r,a,i){this._splatAtlasTextureHeight=e,this.texture=null,this._rctx=t,this._fboCache=a,this._onCachedTextureEvicted=i,this.pageAllocator=new s,this._cache=r.newCache("gaussian texture cache",t=>{t.dispose(),this._onCachedTextureEvicted()})}get usedMemory(){return this.texture?.usedMemory??0}ensureTextureAtlas(){if(this.texture?.hasWebGLTextureObject)return;this.texture=null;const t=this._cache.pop("splatTextureAtlas");if(t)return void(this.texture=t);const e=new u;e.height=this._splatAtlasTextureHeight,e.width=r,e.pixelFormat=36249,e.dataType=i.UNSIGNED_INT,e.internalFormat=l.RGBA32UI,e.samplingMode=9728,e.wrapMode=33071,e.isImmutable=!0,this.texture=new h(this._rctx,e),this._updatePageAllocator()}grow(){if(!this.texture)return this.ensureTextureAtlas(),!1;const e=Math.floor(this._splatAtlasTextureHeight*t);if(e>Math.min(has("esri-mobile")?1048:4096,this._rctx.parameters.maxTextureSize))return!1;const s=new o(this._rctx,this.texture),a=this._fboCache.acquire(r,e,"gaussian splat atlas resize",12);return this._rctx.blitFramebuffer(s,a.fbo,16384,9728,0,0,r,this._splatAtlasTextureHeight,0,0,r,this._splatAtlasTextureHeight),this.texture=a.fbo?.detachColorTexture(),s.dispose(),a.dispose(),this._splatAtlasTextureHeight=e,this._updatePageAllocator(),!0}requestPage(){let t=this.pageAllocator.findFirstFreePage();return null===t&&this.grow()&&(t=this.pageAllocator.findFirstFreePage()),null!==t&&this.pageAllocator.allocate(t),t}freePage(t){this.pageAllocator.free(t)}update(t,e,s){this.ensureTextureAtlas(),this.texture.updateData(0,t,e,a,1,s)}_updatePageAllocator(){const t=r*this._splatAtlasTextureHeight/a;this.pageAllocator.pageCount!==t&&this.pageAllocator.resize(t)}clear(){this.texture&&(this._cache.put("splatTextureAtlas",this.texture),this.texture=null)}destroy(){this._onCachedTextureEvicted=()=>{},this._cache.destroy(),this.texture?.dispose(),this.texture=null}}export{c as GaussianSplatTextureAtlas};
