/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{disposeMaybe as t}from"../../../../../core/maybe.js";import{Vec4Field as e,ScalarField as r}from"./TextureBackedBufferFields.js";import{getItemsRectangle as i}from"./TextureBackedBufferUtils.js";import{TextureBuffer as u}from"./TextureBuffer.js";class s{constructor(t,e){this._rctx=t,this._layout=e,this._nameToFieldMap=new Map,this._dirty=!0,this._textureData=e.createBuffer(0),this._setupFields(e)}get layout(){return this._layout}dispose(){this._textureBuffer=t(this._textureBuffer),this._textureData=void 0}get test(){return{data:this._textureData}}getScalarField(t){const e=this._nameToFieldMap.get(t);return 1===e?.elementCount?e:null}getVec4Field(t){const e=this._nameToFieldMap.get(t);return 4===e?.elementCount?e:null}resizeToFit(t){const e=t+1;e>this._textureData.count&&this._resize(e)}updateTexture(){if(this._dirty){if(this._dirty=!1,0!==this._textureData.count)return null==this._textureBuffer||this._textureBuffer.itemCount<this._textureData.count?(this._textureBuffer=t(this._textureBuffer),void(this._textureBuffer=new u(this._rctx,this.layout,this._textureData.buffer))):void this._textureBuffer.setSubData(this._textureData.buffer);this._textureBuffer=t(this._textureBuffer)}}get texture(){return this._textureBuffer?.texture}_resize(t){const{_layout:e}=this;if(0===t)return this._textureData=e.createBuffer(0),this._updateFields(),void(this._dirty=!0);const r=i(t).itemCount,u=e.createBuffer(r);u.texelElementBuffer.set(this._textureData.texelElementBuffer),this._textureData=u,this._updateFields(),this._dirty=!0}_setupFields(t){const i=this._textureData,u=()=>{this._dirty=!0},s=new Map;for(const[f,o]of t.fields){const t=i.getField(f,o.bufferViewConstructor);if(null==t)throw new Error(`Field ${f} does not exist in buffer`);s.set(f,4===t.elementCount?new e(t,o,u):new r(t,o,u))}this._nameToFieldMap=s}_updateFields(){const t=this._textureData;for(const[e,r]of this._nameToFieldMap){const i=t.getField(e,r.layoutField.bufferViewConstructor);if(null==i)throw new Error(`Field ${e} does not exist in buffer`);r.updateBufferView(i)}}}export{s as TextureBackedBuffer};
