@therealjsmastery/jsm-hq 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -2
  3. package/TRADEMARKS.md +17 -0
  4. package/bin/jsm-hq.mjs +50 -0
  5. package/dist/assets/CanvasPool-O1IaWL-9.js +1 -0
  6. package/dist/assets/CanvasRenderer-Dd4pZNIN.js +1 -0
  7. package/dist/assets/RenderTargetSystem-BccyHTeF.js +184 -0
  8. package/dist/assets/WebGLRenderer-1zkR__s9.js +156 -0
  9. package/dist/assets/WebGPURenderer-CSiZQVKf.js +75 -0
  10. package/dist/assets/browserAll-K-v47ayM.js +14 -0
  11. package/dist/assets/canvasUtils-C3DGUQjp.js +1 -0
  12. package/dist/assets/getTexelRangeRects-D8_SvULv.js +195 -0
  13. package/dist/assets/index-BHNtDgvI.css +1 -0
  14. package/dist/assets/index-DPTN0V6X.js +311 -0
  15. package/dist/assets/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
  16. package/dist/assets/pixelify-sans-cyrillic-600-normal-B3EuUOZG.woff +0 -0
  17. package/dist/assets/pixelify-sans-cyrillic-700-normal-BrZTw8tu.woff +0 -0
  18. package/dist/assets/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
  19. package/dist/assets/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
  20. package/dist/assets/pixelify-sans-latin-600-normal-BNlgYbDL.woff +0 -0
  21. package/dist/assets/pixelify-sans-latin-600-normal-Dd_Dy7u5.woff2 +0 -0
  22. package/dist/assets/pixelify-sans-latin-700-normal-BctWAS0u.woff +0 -0
  23. package/dist/assets/pixelify-sans-latin-700-normal-D3Xxx3QE.woff2 +0 -0
  24. package/dist/assets/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
  25. package/dist/assets/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
  26. package/dist/assets/pixelify-sans-latin-ext-600-normal-CDaIumwU.woff +0 -0
  27. package/dist/assets/pixelify-sans-latin-ext-600-normal-Dha6RiOG.woff2 +0 -0
  28. package/dist/assets/pixelify-sans-latin-ext-700-normal-BadXkHzZ.woff +0 -0
  29. package/dist/assets/pixelify-sans-latin-ext-700-normal-ClyJstAh.woff2 +0 -0
  30. package/dist/assets/vt323-latin-400-normal-Dqn9ZSPj.woff +0 -0
  31. package/dist/assets/vt323-latin-400-normal-wDgJuOC9.woff2 +0 -0
  32. package/dist/assets/vt323-latin-ext-400-normal-DqOq58ri.woff +0 -0
  33. package/dist/assets/vt323-latin-ext-400-normal-iUdYUaX4.woff2 +0 -0
  34. package/dist/assets/vt323-vietnamese-400-normal-D0VnvwZ9.woff2 +0 -0
  35. package/dist/assets/vt323-vietnamese-400-normal-D_5Q7Vcv.woff +0 -0
  36. package/dist/assets/webworkerAll-wf0zq30l.js +83 -0
  37. package/dist/index.html +14 -0
  38. package/dist-server/main.mjs +2342 -0
  39. package/package.json +79 -4
  40. package/scripts/fix-node-pty.mjs +17 -0
@@ -0,0 +1,156 @@
1
+ import{D as g,a as P,o as d,K as O,j as N,w as p,f as Q,b as Ue,S as L,T as R,ak as Fe,V as ee,al as Me,h as y,X as T,x as C,W as x,E as Pe,k as Oe,Y as w,am as Le,an as k,y as S,M as te,ao as re,ap as we,aq as ne,ar as He,as as Xe,A as Ve,R as ke}from"./index-DPTN0V6X.js";import{e as We,G as je,c as Ke,b as Ye,U as $e,B as se,d as I,g as ze,f as ie,h as qe}from"./getTexelRangeRects-D8_SvULv.js";import{R as Ze,S as Je,d as Qe}from"./RenderTargetSystem-BccyHTeF.js";import"./CanvasPool-O1IaWL-9.js";function et(){const{userAgent:r}=g.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(r)}class ae{constructor(){this._tempState=P.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,n){const s=e.renderer,i=this._didUploadHash[n.uid];s.shader.bind(n,i),i||(this._didUploadHash[n.uid]=!0),s.shader.updateUniformGroup(s.globalUniforms.uniformGroup),s.geometry.bind(t,n.glProgram)}execute(e,t){const n=e.renderer;this._tempState.blendMode=t.blendMode,n.state.set(this._tempState);const s=t.textures.textures;for(let i=0;i<t.textures.count;i++)n.texture.bind(s[i],i);n.texture.unbindIntegerTextures(t.textures.count),n.geometry.draw(t.topology,t.size,t.start)}}ae.extension={type:[d.WebGLPipesAdaptor],name:"batch"};var D=(r=>(r[r.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",r[r.ARRAY_BUFFER=34962]="ARRAY_BUFFER",r[r.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",r))(D||{});class tt{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}class oe{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new O({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"glBuffer"})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){const{_gl:t}=this,n=this.getGlBuffer(e);t.bindBuffer(n.type,n.buffer)}bindBufferBase(e,t){const{_gl:n}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,n.bindBufferBase(n.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let n=0,s=this._nextBindBaseIndex;for(;n<2;){s>=this._maxBindings&&(s=this._minBaseLocation,n++);const i=this._boundBufferBases[s];if(i&&i._lastBindCallId===this._bindCallId){s++;continue}break}return t=s,this._nextBindBaseIndex=s+1,n>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){const t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,n,s){const{_gl:i}=this;n||(n=0),t||(t=0),this._boundBufferBases[t]=null,i.bindBufferRange(i.UNIFORM_BUFFER,t||0,e.buffer,n*256,s||256)}updateBuffer(e){const{_gl:t}=this,n=this.getGlBuffer(e);if(e._updateID===n.updateID)return n;n.updateID=e._updateID,t.bindBuffer(n.type,n.buffer);const s=e.data,i=e.descriptor.usage&N.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return s?n.byteLength>=s.byteLength?t.bufferSubData(n.type,e._updateOffset,s,e._updateOffset/s.BYTES_PER_ELEMENT,(e._updateSize||s.byteLength)/s.BYTES_PER_ELEMENT):(n.byteLength=s.byteLength,t.bufferData(n.type,s,i)):(n.byteLength=e.descriptor.size,t.bufferData(n.type,n.byteLength,i)),n}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){const n=e._gpuData[this._renderer.uid];n&&(t||this._gl.deleteBuffer(n.buffer))}createGLBuffer(e){const{_gl:t}=this;let n=D.ARRAY_BUFFER;e.descriptor.usage&N.INDEX?n=D.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&N.UNIFORM&&(n=D.UNIFORM_BUFFER);const s=new tt(t.createBuffer(),n);return e._gpuData[this._renderer.uid]=s,this._managedBuffers.add(e),s}resetState(){this._boundBufferBases=Object.create(null)}}oe.extension={type:[d.WebGLSystem],name:"buffer"};const H=class ce{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(e){e={...ce.defaultOptions,...e};let t=this.multiView=e.multiView;if(e.context&&t&&(p("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),t=!1),t?this.canvas=g.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,e.context)this.initFromContext(e.context);else{const n=this._renderer.background.alpha<1,s=e.premultipliedAlpha??!0,i=e.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(e.preferWebGLVersion,{alpha:n,premultipliedAlpha:s,antialias:i,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:e.powerPreference??"default"})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&p("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof g.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);const t=this._renderer.view.canvas;t.addEventListener("webglcontextlost",this.handleContextLost,!1),t.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(e,t){let n;const s=this.canvas;if(e===2&&(n=s.getContext("webgl2",t)),!n&&(n=s.getContext("webgl",t),!n))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=n,this.initFromContext(this.gl)}getExtensions(){const{gl:e}=this,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc"),bptc:e.getExtension("EXT_texture_compression_bptc"),rgtc:e.getExtension("EXT_texture_compression_rgtc"),loseContext:e.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:e.getExtension("ANGLE_instanced_arrays"),srgb:e.getExtension("EXT_sRGB")};else{this.extensions={...t,colorBufferFloat:e.getExtension("EXT_color_buffer_float")};const n=e.getExtension("WEBGL_provoking_vertex");n&&n.provokingVertexWEBGL(n.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{var t;this.gl.isContextLost()&&((t=this.extensions.loseContext)==null||t.restoreContext())},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var t;const e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),(t=this.extensions.loseContext)==null||t.loseContext()}forceContextLoss(){var e;(e=this.extensions.loseContext)==null||e.loseContext(),this._contextLossForced=!0}validateContext(e){const t=e.getContextAttributes();t&&!t.stencil&&p("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const n=this.supports,s=this.webGLVersion===2,i=this.extensions;n.uint32Indices=s||!!i.uint32ElementIndex,n.uniformBufferObject=s,n.vertexArrayObject=s||!!i.vertexArrayObject,n.srgbTextures=s||!!i.srgb,n.nonPowOf2wrapping=s,n.nonPowOf2mipmaps=s,n.msaa=s,n.uint32Indices||p("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};H.extension={type:[d.WebGLSystem],name:"context"};H.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let rt=H;var F=(r=>(r[r.RGBA=6408]="RGBA",r[r.RGB=6407]="RGB",r[r.RG=33319]="RG",r[r.RED=6403]="RED",r[r.RGBA_INTEGER=36249]="RGBA_INTEGER",r[r.RGB_INTEGER=36248]="RGB_INTEGER",r[r.RG_INTEGER=33320]="RG_INTEGER",r[r.RED_INTEGER=36244]="RED_INTEGER",r[r.ALPHA=6406]="ALPHA",r[r.LUMINANCE=6409]="LUMINANCE",r[r.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",r[r.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",r[r.DEPTH_STENCIL=34041]="DEPTH_STENCIL",r))(F||{}),v=(r=>(r[r.TEXTURE_2D=3553]="TEXTURE_2D",r[r.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",r[r.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",r[r.TEXTURE_3D=32879]="TEXTURE_3D",r[r.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",r[r.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",r[r.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",r[r.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",r[r.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",r[r.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",r))(v||{}),f=(r=>(r[r.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",r[r.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",r[r.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",r[r.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",r[r.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",r[r.UNSIGNED_INT=5125]="UNSIGNED_INT",r[r.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",r[r.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",r[r.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",r[r.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",r[r.BYTE=5120]="BYTE",r[r.SHORT=5122]="SHORT",r[r.INT=5124]="INT",r[r.FLOAT=5126]="FLOAT",r[r.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",r[r.HALF_FLOAT=36193]="HALF_FLOAT",r))(f||{});const W={uint8x2:f.UNSIGNED_BYTE,uint8x4:f.UNSIGNED_BYTE,sint8x2:f.BYTE,sint8x4:f.BYTE,unorm8x2:f.UNSIGNED_BYTE,unorm8x4:f.UNSIGNED_BYTE,snorm8x2:f.BYTE,snorm8x4:f.BYTE,uint16x2:f.UNSIGNED_SHORT,uint16x4:f.UNSIGNED_SHORT,sint16x2:f.SHORT,sint16x4:f.SHORT,unorm16x2:f.UNSIGNED_SHORT,unorm16x4:f.UNSIGNED_SHORT,snorm16x2:f.SHORT,snorm16x4:f.SHORT,float16x2:f.HALF_FLOAT,float16x4:f.HALF_FLOAT,float32:f.FLOAT,float32x2:f.FLOAT,float32x3:f.FLOAT,float32x4:f.FLOAT,uint32:f.UNSIGNED_INT,uint32x2:f.UNSIGNED_INT,uint32x3:f.UNSIGNED_INT,uint32x4:f.UNSIGNED_INT,sint32:f.INT,sint32x2:f.INT,sint32x3:f.INT,sint32x4:f.INT};function nt(r){return W[r]??W.float32}const st={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class it{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}}class ue{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new O({renderer:e,type:"resource",onUnload:this.onGeometryUnload.bind(this),name:"glGeometry"})}contextChange(){const e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");this.destroyAll(!0);const t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=s=>t.bindVertexArrayOES(s),e.deleteVertexArray=s=>t.deleteVertexArrayOES(s));const n=this._renderer.context.extensions.vertexAttribDivisorANGLE;n&&(e.drawArraysInstanced=(s,i,a,o)=>{n.drawArraysInstancedANGLE(s,i,a,o)},e.drawElementsInstanced=(s,i,a,o,c)=>{n.drawElementsInstancedANGLE(s,i,a,o,c)},e.vertexAttribDivisor=(s,i)=>n.vertexAttribDivisorANGLE(s,i)),this._activeGeometry=null,this._activeVao=null}bind(e,t){const n=this.gl;this._activeGeometry=e;const s=this.getVao(e,t);this._activeVao!==s&&(this._activeVao=s,n.bindVertexArray(s)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const e=this._activeGeometry,t=this._renderer.buffer;for(let n=0;n<e.buffers.length;n++){const s=e.buffers[n];t.updateBuffer(s)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){const n=e.attributes,s=t._attributeData;for(const i in s)if(!n[i])throw new Error(`shader and geometry incompatible, geometry missing the "${i}" attribute`)}getSignature(e,t){const n=e.attributes,s=t._attributeData,i=["g",e.uid];for(const a in n)s[a]&&i.push(a,s[a].location);return i.join("-")}getVao(e,t){var n;return((n=e._gpuData[this._renderer.uid])==null?void 0:n.vaoCache[t._key])||this.initGeometryVao(e,t)}initGeometryVao(e,t,n=!0){const s=this._renderer.gl,i=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);const a=this.getSignature(e,t);let o=e._gpuData[this._renderer.uid];o||(o=new it,e._gpuData[this._renderer.uid]=o,this._managedGeometries.add(e));const c=o.vaoCache;let u=c[a];if(u)return c[t._key]=u,u;We(e,t._attributeData);const _=e.buffers;u=s.createVertexArray(),s.bindVertexArray(u);for(let h=0;h<_.length;h++){const l=_[h];i.bind(l)}return this.activateVao(e,t),c[t._key]=u,c[a]=u,s.bindVertexArray(null),u}onGeometryUnload(e,t=!1){const n=e._gpuData[this._renderer.uid];if(!n)return;const s=n.vaoCache;if(!t)for(const i in s)this._activeVao===s[i]&&this.resetState(),this.gl.deleteVertexArray(s[i])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){var o;const n=this._renderer.gl,s=this._renderer.buffer,i=e.attributes;e.indexBuffer&&s.bind(e.indexBuffer);let a=null;for(const c in i){const u=i[c],_=u.buffer,h=s.getGlBuffer(_),l=t._attributeData[c];if(l){a!==h&&(s.bind(_),a=h);const m=l.location;n.enableVertexAttribArray(m);const E=Q(u.format),b=nt(u.format);if(((o=l.format)==null?void 0:o.substring(1,4))==="int"?n.vertexAttribIPointer(m,E.size,b,u.stride,u.offset):n.vertexAttribPointer(m,E.size,b,E.normalised,u.stride,u.offset),u.instance)if(this.hasInstance){const Ge=u.divisor??1;n.vertexAttribDivisor(m,Ge)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(e,t,n,s){const{gl:i}=this._renderer,a=this._activeGeometry,o=st[e||a.topology];if(s??(s=a.instanceCount),a.indexBuffer){const c=a.indexBuffer.data.BYTES_PER_ELEMENT,u=c===2?i.UNSIGNED_SHORT:i.UNSIGNED_INT,_=t||a.indexCount||a.indexBuffer.data.length,h=(n||0)*c;s!==1?i.drawElementsInstanced(o,_,u,h,s):i.drawElements(o,_,u,h)}else s!==1?i.drawArraysInstanced(o,n||0,t||a.vertexCount,s):i.drawArrays(o,n||0,t||a.vertexCount);return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}}ue.extension={type:[d.WebGLSystem],name:"geometry"};const at=new Fe({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),X=class _e{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(e={}){const{useBackBuffer:t,antialias:n}={..._e.defaultOptions,...e};this.useBackBuffer=t,this._antialias=n,this._renderer.context.supports.msaa||(p("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=P.for2d();const s=new Ue({vertex:`
2
+ attribute vec2 aPosition;
3
+ out vec2 vUv;
4
+
5
+ void main() {
6
+ gl_Position = vec4(aPosition, 0.0, 1.0);
7
+
8
+ vUv = (aPosition + 1.0) / 2.0;
9
+
10
+ // flip dem UVs
11
+ vUv.y = 1.0 - vUv.y;
12
+ }`,fragment:`
13
+ in vec2 vUv;
14
+ out vec4 finalColor;
15
+
16
+ uniform sampler2D uTexture;
17
+
18
+ void main() {
19
+ finalColor = texture(uTexture, vUv);
20
+ }`,name:"big-triangle"});this._bigTriangleShader=new L({glProgram:s,resources:{uTexture:R.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const n=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=n.colorTexture,e.target=this._getBackBufferTexture(n.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind({target:this._targetTexture,clear:!1}),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:at,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new R({source:new ee({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};X.extension={type:[d.WebGLSystem],name:"backBuffer",priority:1};X.defaultOptions={useBackBuffer:!1};let ot=X;class he{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}he.extension={type:[d.WebGLSystem],name:"colorMask"};class fe{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:n,shader:s,state:i,skipSync:a,topology:o,size:c,start:u,instanceCount:_}=e;t.shader.bind(s,a),t.geometry.bind(n,t.shader._activeProgram),i&&t.state.set(i),t.geometry.draw(o,c,u,_??n.instanceCount)}destroy(){this._renderer=null}}fe.extension={type:[d.WebGLSystem],name:"encoder"};class le{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=Me(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}le.extension={type:[d.WebGLSystem],name:"limits"};class ct{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[],this.stencilMode=y.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}class de{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:y.NONE},this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this._activeGpuRenderTarget=null,this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;const t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=y.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const n=this._activeGpuRenderTarget??(this._activeGpuRenderTarget=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget)),s=this._gl,i=je[e],a=this._stencilCache;if(n.stencilMode=e,n.stencilReference=t,e===y.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,s.disable(s.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,s.enable(s.STENCIL_TEST)),(e!==a.stencilMode||a.stencilReference!==t)&&(a.stencilMode=e,a.stencilReference=t,s.stencilFunc(this._comparisonFuncMapping[i.stencilBack.compare],t,255),s.stencilOp(s.KEEP,s.KEEP,this._stencilOpsMapping[i.stencilBack.passOp]))}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._gl=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}}de.extension={type:[d.WebGLSystem],name:"stencil"};const me={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,u32:4,"vec2<u32>":8,"vec3<u32>":12,"vec4<u32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function ut(r){const e=r.map(i=>({data:i,offset:0,size:0})),t=16;let n=0,s=0;for(let i=0;i<e.length;i++){const a=e[i];if(n=me[a.data.type],!n)throw new Error(`Unknown type ${a.data.type}`);a.data.size>1&&(n=Math.max(n,t)*a.data.size);const o=n===12?16:n;a.size=n;const c=s%t;c>0&&t-c<o?s+=(t-c)%16:s+=(n-c%n)%n,a.offset=s,s+=n}return s=Math.ceil(s/16)*16,{uboElements:e,size:s}}function _t(r,e){const t=Math.max(me[r.data.type]/16,1),n=r.data.value.length/r.data.size,s=(4-n%4)%4,i=r.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
21
+ v = uv.${r.data.name};
22
+ offset += ${e};
23
+
24
+ arrayOffset = offset;
25
+
26
+ t = 0;
27
+
28
+ for(var i=0; i < ${r.data.size*t}; i++)
29
+ {
30
+ for(var j = 0; j < ${n}; j++)
31
+ {
32
+ ${i}[arrayOffset++] = v[t++];
33
+ }
34
+ ${s!==0?`arrayOffset += ${s};`:""}
35
+ }
36
+ `}function ht(r){return Ke(r,Ye,_t)}class Ee extends $e{constructor(){super({createUboElements:ut,generateUboSync:ht})}}Ee.extension={type:[d.WebGLSystem],name:"ubo"};class ft{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new T,this._boundFramebuffer=void 0}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new T,this._boundFramebuffer=void 0;const e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(n,s)=>e.COLOR_ATTACHMENT0+s)}copyToTexture(e,t,n,s,i){const a=this._renderTargetSystem,o=this._renderer,c=a.getGpuRenderTarget(e),u=o.gl;return this.finishRenderPass(e),u.bindFramebuffer(u.FRAMEBUFFER,c.resolveTargetFramebuffer),this._boundFramebuffer=c.resolveTargetFramebuffer,o.texture.bind(t,0),u.copyTexSubImage2D(u.TEXTURE_2D,0,i.x,i.y,n.x,n.y,s.width,s.height),t}copyDepthTexture(e,t,n,s,i){const a=this._renderTargetSystem,o=this._renderer.gl;this.finishRenderPass(e);const c=a.getRenderTarget(t),u=a.getGpuRenderTarget(e),_=a.getGpuRenderTarget(c);o.bindFramebuffer(o.READ_FRAMEBUFFER,u.framebuffer),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,_.framebuffer),this._boundFramebuffer=void 0,o.blitFramebuffer(n.x,n.y,n.x+s.width,n.y+s.height,i.x,i.y,i.x+s.width,i.y+s.height,o.DEPTH_BUFFER_BIT,o.NEAREST)}startRenderPass(e,t=!0,n,s,i=0,a=0){const c=this._renderTargetSystem.getGpuRenderTarget(e);if(a!==0&&this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to array layers requires WebGL2.");if(i>0){if(c.msaa)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");if(this._renderer.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Rendering to mip levels requires WebGL2.")}e.colorAttachments.forEach(l=>{this._renderer.texture.unbind(l.texture)});const u=this._renderer.gl;this.bindFramebuffer(c.framebuffer),!e.isRoot&&e.colorAttachments.length>0&&(c._attachedMipLevel!==i||c._attachedLayer!==a)&&(e.colorAttachments.forEach((l,m)=>{const E=l.texture,b=this._renderer.texture.getGlSource(E);if(b.target===u.TEXTURE_2D){if(a!==0)throw new Error("[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+m,u.TEXTURE_2D,b.texture,i)}else if(b.target===u.TEXTURE_2D_ARRAY||b.target===u.TEXTURE_3D)u.framebufferTextureLayer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+m,b.texture,i,a);else if(b.target===u.TEXTURE_CUBE_MAP){if(a<0||a>5)throw new Error("[RenderTargetSystem] Cube map layer must be between 0 and 5.");u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0+m,u.TEXTURE_CUBE_MAP_POSITIVE_X+a,b.texture,i)}else throw new Error("[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.")}),c._attachedMipLevel=i,c._attachedLayer=a),c.framebuffer&&(e.depthStencilAttachment?this._attachDepthStencilTexture(e,i,a):!c.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(c)),e.colorAttachments.length>1&&this._setDrawBuffers(e,u);let _=s.y;e.isRoot&&(_=e.pixelHeight-s.height-s.y);const h=this._viewPortCache;(h.x!==s.x||h.y!==_||h.width!==s.width||h.height!==s.height)&&(h.x=s.x,h.y=_,h.width=s.width,h.height=s.height,u.viewport(s.x,_,s.width,s.height)),this.clear(e,t,n)}finishRenderPass(e){const n=this._renderTargetSystem.getGpuRenderTarget(e);if(!n.msaa||e.colorAttachments.length===0)return;const s=this._renderer.gl;s.bindFramebuffer(s.FRAMEBUFFER,n.resolveTargetFramebuffer),s.bindFramebuffer(s.READ_FRAMEBUFFER,n.framebuffer),s.blitFramebuffer(0,0,n.width,n.height,0,0,n.width,n.height,s.COLOR_BUFFER_BIT,s.NEAREST),s.bindFramebuffer(s.FRAMEBUFFER,n.framebuffer),this._boundFramebuffer=n.framebuffer}initGpuRenderTarget(e){const n=this._renderer.gl,s=new ct;s._attachedMipLevel=0,s._attachedLayer=0;const i=e.colorTexture;return i instanceof C?(this._renderer.context.ensureCanvasSize(i.resource),s.framebuffer=null,s):(s.width=e.pixelWidth,s.height=e.pixelHeight,e.colorAttachments.length===0?this._initDepth(e,s):this._initColor(e,s),e.depthStencilAttachment&&this._attachDepthStencilTexture(e,0,0),n.bindFramebuffer(n.FRAMEBUFFER,null),this._boundFramebuffer=null,s)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(n=>{t.deleteRenderbuffer(n)}),e.msaaRenderBuffer.length=0}clear(e,t,n,s,i=0,a=0){if(!t)return;if(a!==0)throw new Error("[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.");const o=this._renderTargetSystem;if(typeof t=="boolean"&&(t=t?x.ALL:x.NONE),e.colorAttachments.length===0&&(t&=~x.COLOR,!t))return;const c=this._renderer.gl,u=!!(t&x.DEPTH)&&!this._renderer.state.depthMaskEnabled;if(t&x.COLOR){n??(n=o.defaultClearColor);const _=this._clearColorCache,h=n;(_[0]!==h[0]||_[1]!==h[1]||_[2]!==h[2]||_[3]!==h[3])&&(_[0]=h[0],_[1]=h[1],_[2]=h[2],_[3]=h[3],c.clearColor(h[0],h[1],h[2],h[3]))}u&&c.depthMask(!0),c.clear(t),u&&c.depthMask(!1)}resizeGpuRenderTarget(e){if(e.isRoot)return;const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.pixelWidth,t.height=e.pixelHeight,e.colorAttachments.length>0&&this._resizeColor(e,t),t.depthStencilRenderBuffer&&this._resizeStencil(t),this._boundFramebuffer=void 0}_initColor(e,t){const n=this._renderer,s=n.gl,i=s.createFramebuffer();if(t.resolveTargetFramebuffer=i,s.bindFramebuffer(s.FRAMEBUFFER,i),e.colorAttachments.forEach((o,c)=>{const u=o.texture;u.antialias&&(n.context.supports.msaa?t.msaa=!0:p("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),n.texture.bindSource(u,0);const _=n.texture.getGlSource(u),h=_.texture;if(_.target===s.TEXTURE_2D)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+c,s.TEXTURE_2D,h,0);else if(_.target===s.TEXTURE_2D_ARRAY||_.target===s.TEXTURE_3D)s.framebufferTextureLayer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+c,h,0,0);else if(_.target===s.TEXTURE_CUBE_MAP)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+c,s.TEXTURE_CUBE_MAP_POSITIVE_X,h,0);else throw new Error("[RenderTargetSystem] Unsupported texture target for framebuffer attachment.")}),t.msaa){const o=s.createFramebuffer();t.framebuffer=o,s.bindFramebuffer(s.FRAMEBUFFER,o),e.colorAttachments.forEach((c,u)=>{const _=s.createRenderbuffer();t.msaaRenderBuffer[u]=_})}else t.framebuffer=i;this._resizeColor(e,t)}_initDepth(e,t){const n=this._renderer;if(n.context.webGLVersion<2)throw new Error("[RenderTargetSystem] Depth-only render targets require WebGL2.");const s=n.gl,i=s.createFramebuffer();t.resolveTargetFramebuffer=i,t.framebuffer=i,s.bindFramebuffer(s.FRAMEBUFFER,i),s.drawBuffers([s.NONE]),s.readBuffer(s.NONE)}_resizeColor(e,t){const n=e.colorAttachments[0].texture;if(t._attachedMipLevel=0,t._attachedLayer=0,e.colorAttachments.forEach((s,i)=>{i!==0&&s.texture.resize(n.width,n.height,n._resolution)}),t.msaa){const s=this._renderer,i=s.gl,a=t.framebuffer;i.bindFramebuffer(i.FRAMEBUFFER,a),e.colorAttachments.forEach((o,c)=>{const u=o.texture;s.texture.bindSource(u,0);const h=s.texture.getGlSource(u).internalFormat,l=t.msaaRenderBuffer[c];i.bindRenderbuffer(i.RENDERBUFFER,l),i.renderbufferStorageMultisample(i.RENDERBUFFER,4,h,u.pixelWidth,u.pixelHeight),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+c,i.RENDERBUFFER,l)})}}_attachDepthStencilTexture(e,t,n){const s=this._renderer,i=s.gl,a=e.depthStencilAttachment.texture,o=s.texture.getGlSource(a),c=o.texture,u=a.format;let _;u==="depth24plus-stencil8"||u==="depth32float-stencil8"?_=i.DEPTH_STENCIL_ATTACHMENT:u==="stencil8"?_=i.STENCIL_ATTACHMENT:_=i.DEPTH_ATTACHMENT,o.target===i.TEXTURE_2D?i.framebufferTexture2D(i.FRAMEBUFFER,_,i.TEXTURE_2D,c,t):o.target===i.TEXTURE_2D_ARRAY||o.target===i.TEXTURE_3D?i.framebufferTextureLayer(i.FRAMEBUFFER,_,c,t,n):o.target===i.TEXTURE_CUBE_MAP&&i.framebufferTexture2D(i.FRAMEBUFFER,_,i.TEXTURE_CUBE_MAP_POSITIVE_X+n,c,t)}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,n=t.createRenderbuffer();e.depthStencilRenderBuffer=n,t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,n),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){if(e.colorAttachments.length===0)return;const t=e.colorAttachments[0].texture.resource;this._renderer.context.multiView&&C.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(!this._renderer.context.multiView||e.colorAttachments.length===0)return;const t=e.colorAttachments[0].texture;if(C.test(t.resource)){const n=this._renderer.context.canvas,s=t;s.context2D.drawImage(n,0,s.pixelHeight-n.height)}}_setDrawBuffers(e,t){const n=e.colorAttachments.length,s=this._drawBuffersCache[n];if(this._renderer.context.webGLVersion===1){const i=this._renderer.context.extensions.drawBuffers;i?i.drawBuffersWEBGL(s):p("[RenderTexture] This WebGL1 context does not support rendering to multiple targets")}else t.drawBuffers(s)}resetState(){this._boundFramebuffer=void 0,this._viewPortCache=new T,this._clearColorCache=[0,0,0,0]}bindFramebuffer(e){this._boundFramebuffer!==e&&(this._boundFramebuffer=e,this._renderer.gl.bindFramebuffer(this._renderer.gl.FRAMEBUFFER,e))}}class be extends Ze{constructor(e){super(e),this.adaptor=new ft,this.adaptor.init(e,this)}resetState(){this.adaptor.resetState()}}be.extension={type:[d.WebGLSystem],name:"renderTarget"};class lt extends Pe{constructor(e,t){super(),this._resourceType="textureView",this._resourceId=Oe("resource"),this.source=e,this.viewDescriptor=t,this._onChange=this._onChange.bind(this),this._onDestroy=this._onDestroy.bind(this),this.source.on("change",this._onChange),this.source.on("destroy",this._onDestroy)}_onChange(){this.emit("change",this)}_onDestroy(){this.destroy()}get destroyed(){return this.source.destroyed}destroy(){this.source&&(this.source.off("change",this._onChange),this.source.off("destroy",this._onDestroy)),this.emit("destroy",this),this.removeAllListeners()}}function dt(r,e){const t=[],n=[`
37
+ var g = s.groups;
38
+ var sS = r.shader;
39
+ var p = s.glProgram;
40
+ var ugS = r.uniformGroup;
41
+ var resources;
42
+ `];let s=!1,i=0;const a=e._getProgramData(r.glProgram);for(const c in r.groups){const u=r.groups[c];t.push(`
43
+ resources = g[${c}].resources;
44
+ `);for(const _ in u.resources){const h=u.resources[_];if(h instanceof w)if(h.ubo){const l=r._uniformBindMap[c][Number(_)];t.push(`
45
+ sS.bindUniformBlock(
46
+ resources[${_}],
47
+ '${l}',
48
+ ${r.glProgram._uniformBlockData[l].index}
49
+ );
50
+ `)}else t.push(`
51
+ ugS.updateUniformGroup(resources[${_}], p, sD);
52
+ `);else if(h instanceof se){const l=r._uniformBindMap[c][Number(_)];t.push(`
53
+ sS.bindUniformBlock(
54
+ resources[${_}],
55
+ '${l}',
56
+ ${r.glProgram._uniformBlockData[l].index}
57
+ );
58
+ `)}else if(h instanceof ee||h instanceof lt){const l=r._uniformBindMap[c][_],m=a.uniformData[l];m&&(s||(s=!0,n.push(`
59
+ var tS = r.texture;
60
+ `)),e._gl.uniform1i(m.location,i),t.push(`
61
+ tS.bind(resources[${_}], ${i});
62
+ `),i++)}}}const o=[...n,...t].join(`
63
+ `);return new Function("r","s","sD",o)}class mt{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function j(r,e,t){const n=r.createShader(e);return r.shaderSource(n,t),r.compileShader(n),n}function G(r){const e=new Array(r);for(let t=0;t<e.length;t++)e[t]=!1;return e}function pe(r,e){switch(r){case"float":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"int":case"uint":case"sampler2D":case"sampler2DArray":case"sampler3D":return 0;case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return G(2*e);case"bvec3":return G(3*e);case"bvec4":return G(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}let A=null;const K={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_2D_SHADOW:"sampler2DShadow",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_CUBE_SHADOW:"samplerCubeShadow",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray",SAMPLER_2D_ARRAY_SHADOW:"sampler2DArrayShadow",SAMPLER_3D:"sampler3D",INT_SAMPLER_3D:"sampler3D",UNSIGNED_INT_SAMPLER_3D:"sampler3D"},Et={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function Re(r,e){if(!A){const t=Object.keys(K);A={};for(let n=0;n<t.length;++n){const s=t[n];A[r[s]]=K[s]}}return A[e]}function bt(r,e){const t=Re(r,e);return Et[t]||"float32"}function pt(r,e,t=!1){const n={},s=e.getProgramParameter(r,e.ACTIVE_ATTRIBUTES);for(let a=0;a<s;a++){const o=e.getActiveAttrib(r,a);if(o.name.startsWith("gl_"))continue;const c=bt(e,o.type);n[o.name]={location:0,format:c,stride:Q(c).stride,offset:0,instance:!1,start:0}}const i=Object.keys(n);if(t){i.sort((a,o)=>a>o?1:-1);for(let a=0;a<i.length;a++)n[i[a]].location=a,e.bindAttribLocation(r,a,i[a]);e.linkProgram(r)}else for(let a=0;a<i.length;a++)n[i[a]].location=e.getAttribLocation(r,i[a]);return n}function Rt(r,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},n=e.getProgramParameter(r,e.ACTIVE_UNIFORM_BLOCKS);for(let s=0;s<n;s++){const i=e.getActiveUniformBlockName(r,s),a=e.getUniformBlockIndex(r,i),o=e.getActiveUniformBlockParameter(r,s,e.UNIFORM_BLOCK_DATA_SIZE);t[i]={name:i,index:a,size:o}}return t}function Tt(r,e){const t={},n=e.getProgramParameter(r,e.ACTIVE_UNIFORMS);for(let s=0;s<n;s++){const i=e.getActiveUniform(r,s),a=i.name.replace(/\[.*?\]$/,""),o=!!i.name.match(/\[.*?\]$/),c=Re(e,i.type);t[a]={name:a,index:s,type:c,size:i.size,isArray:o,value:pe(c,i.size)}}return t}function Y(r,e){const t=r.getShaderSource(e);if(t===null){console.error("PixiJS Error: Could not retrieve shader source (WebGL context may be lost).");return}const n=t.split(`
64
+ `).map((_,h)=>`${h}: ${_}`),s=r.getShaderInfoLog(e)??"",i=s.split(`
65
+ `),a={},o=i.map(_=>parseFloat(_.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(_=>_&&!a[_]?(a[_]=!0,!0):!1),c=[""];o.forEach(_=>{n[_-1]=`%c${n[_-1]}%c`,c.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const u=n.join(`
66
+ `);c[0]=u,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...c),console.groupEnd()}function gt(r,e,t,n){r.getProgramParameter(e,r.LINK_STATUS)||(r.getShaderParameter(t,r.COMPILE_STATUS)||Y(r,t),r.getShaderParameter(n,r.COMPILE_STATUS)||Y(r,n),console.error("PixiJS Error: Could not initialize shader."),r.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",r.getProgramInfoLog(e)))}function St(r,e){const t=j(r,r.VERTEX_SHADER,e.vertex),n=j(r,r.FRAGMENT_SHADER,e.fragment),s=r.createProgram();r.attachShader(s,t),r.attachShader(s,n);const i=e.transformFeedbackVaryings;i&&(typeof r.transformFeedbackVaryings!="function"?p("TransformFeedback is not supported but TransformFeedbackVaryings are given."):r.transformFeedbackVaryings(s,i.names,i.bufferMode==="separate"?r.SEPARATE_ATTRIBS:r.INTERLEAVED_ATTRIBS)),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||gt(r,s,t,n),e._attributeData=pt(s,r,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=Tt(s,r),e._uniformBlockData=Rt(s,r),r.deleteShader(t),r.deleteShader(n);const a={};for(const c in e._uniformData){const u=e._uniformData[c];a[c]={location:r.getUniformLocation(s,c),value:pe(u.type,u.size)}}return new mt(s,a)}const B={textureCount:0,blockIndex:0};class Te{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;B.textureCount=0,B.blockIndex=0;let n=this._shaderSyncFunctions[e.glProgram._key];n||(n=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),n(this._renderer,e,B)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,B)}bindUniformBlock(e,t,n=0){const s=this._renderer.buffer,i=this._getProgramData(this._activeProgram),a=e._bufferResource;a||this._renderer.ubo.updateUniformGroup(e);const o=e.buffer,c=s.updateBuffer(o),u=s.freeLocationForBufferBase(c);if(a){const{offset:h,size:l}=e;h===0&&l===o.data.byteLength?s.bindBufferBase(c,u):s.bindBufferRange(c,u,h)}else s.getLastBindBaseLocation(c)!==u&&s.bindBufferBase(c,u);const _=this._activeProgram._uniformBlockData[t].index;i.uniformBlockBindings[n]!==u&&(i.uniformBlockBindings[n]=u,this._renderer.gl.uniformBlockBinding(i.program,_,u))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const t=e._key;return this._programDataHash[t]=St(this._gl,e),this._programDataHash[t]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return dt(e,t)}resetState(){this._activeProgram=null}}Te.extension={type:[d.WebGLSystem],name:"shader"};const xt={f32:`if (cv !== v) {
67
+ cu.value = v;
68
+ gl.uniform1f(location, v);
69
+ }`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
70
+ cv[0] = v[0];
71
+ cv[1] = v[1];
72
+ gl.uniform2f(location, v[0], v[1]);
73
+ }`,"vec3<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
74
+ cv[0] = v[0];
75
+ cv[1] = v[1];
76
+ cv[2] = v[2];
77
+ gl.uniform3f(location, v[0], v[1], v[2]);
78
+ }`,"vec4<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
79
+ cv[0] = v[0];
80
+ cv[1] = v[1];
81
+ cv[2] = v[2];
82
+ cv[3] = v[3];
83
+ gl.uniform4f(location, v[0], v[1], v[2], v[3]);
84
+ }`,i32:`if (cv !== v) {
85
+ cu.value = v;
86
+ gl.uniform1i(location, v);
87
+ }`,"vec2<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
88
+ cv[0] = v[0];
89
+ cv[1] = v[1];
90
+ gl.uniform2i(location, v[0], v[1]);
91
+ }`,"vec3<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
92
+ cv[0] = v[0];
93
+ cv[1] = v[1];
94
+ cv[2] = v[2];
95
+ gl.uniform3i(location, v[0], v[1], v[2]);
96
+ }`,"vec4<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
97
+ cv[0] = v[0];
98
+ cv[1] = v[1];
99
+ cv[2] = v[2];
100
+ cv[3] = v[3];
101
+ gl.uniform4i(location, v[0], v[1], v[2], v[3]);
102
+ }`,u32:`if (cv !== v) {
103
+ cu.value = v;
104
+ gl.uniform1ui(location, v);
105
+ }`,"vec2<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
106
+ cv[0] = v[0];
107
+ cv[1] = v[1];
108
+ gl.uniform2ui(location, v[0], v[1]);
109
+ }`,"vec3<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
110
+ cv[0] = v[0];
111
+ cv[1] = v[1];
112
+ cv[2] = v[2];
113
+ gl.uniform3ui(location, v[0], v[1], v[2]);
114
+ }`,"vec4<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
115
+ cv[0] = v[0];
116
+ cv[1] = v[1];
117
+ cv[2] = v[2];
118
+ cv[3] = v[3];
119
+ gl.uniform4ui(location, v[0], v[1], v[2], v[3]);
120
+ }`,bool:`if (cv !== v) {
121
+ cu.value = v;
122
+ gl.uniform1i(location, v);
123
+ }`,"vec2<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
124
+ cv[0] = v[0];
125
+ cv[1] = v[1];
126
+ gl.uniform2i(location, v[0], v[1]);
127
+ }`,"vec3<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
128
+ cv[0] = v[0];
129
+ cv[1] = v[1];
130
+ cv[2] = v[2];
131
+ gl.uniform3i(location, v[0], v[1], v[2]);
132
+ }`,"vec4<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
133
+ cv[0] = v[0];
134
+ cv[1] = v[1];
135
+ cv[2] = v[2];
136
+ cv[3] = v[3];
137
+ gl.uniform4i(location, v[0], v[1], v[2], v[3]);
138
+ }`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},vt={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function At(r,e){const t=[`
139
+ var v = null;
140
+ var cv = null;
141
+ var cu = null;
142
+ var t = 0;
143
+ var gl = renderer.gl;
144
+ var name = null;
145
+ `];for(const n in r.uniforms){if(!e[n]){r.uniforms[n]instanceof w?r.uniforms[n].ubo?t.push(`
146
+ renderer.shader.bindUniformBlock(uv.${n}, "${n}");
147
+ `):t.push(`
148
+ renderer.shader.updateUniformGroup(uv.${n});
149
+ `):r.uniforms[n]instanceof se&&t.push(`
150
+ renderer.shader.bindBufferResource(uv.${n}, "${n}");
151
+ `);continue}const s=r.uniformStructures[n];let i=!1;for(let a=0;a<I.length;a++){const o=I[a];if(s.type===o.type&&o.test(s)){t.push(`name = "${n}";`,I[a].uniform),i=!0;break}}if(!i){const o=(s.size===1?xt:vt)[s.type].replace("location",`ud["${n}"].location`);t.push(`
152
+ cu = ud["${n}"];
153
+ cv = cu.value;
154
+ v = uv["${n}"];
155
+ ${o};`)}}return new Function("ud","uv","renderer","syncData",t.join(`
156
+ `))}class ge{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,n){const s=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==s.uniformDirtyGroups[e.uid])&&(s.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(s.uniformData,e.uniforms,this._renderer,n))}_getUniformSyncFunction(e,t){var n;return((n=this._uniformGroupSyncHash[e._signature])==null?void 0:n[t._key])||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const n=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),s=this._getSignature(e,t._uniformData,"u");return this._cache[s]||(this._cache[s]=this._generateUniformsSync(e,t._uniformData)),n[t._key]=this._cache[s],n[t._key]}_generateUniformsSync(e,t){return At(e,t)}_getSignature(e,t,n){const s=e.uniforms,i=[`${n}-`];for(const a in s)i.push(a),t[a]&&i.push(t[a].type);return i.join("-")}destroy(){this._renderer=null,this._cache=null}}ge.extension={type:[d.WebGLSystem],name:"uniformGroup"};function Bt(r){const e={};if(e.normal=[r.ONE,r.ONE_MINUS_SRC_ALPHA],e.add=[r.ONE,r.ONE],e.multiply=[r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.screen=[r.ONE,r.ONE_MINUS_SRC_COLOR,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[r.SRC_ALPHA,r.ONE,r.ONE,r.ONE],e["screen-npm"]=[r.SRC_ALPHA,r.ONE_MINUS_SRC_COLOR,r.ONE,r.ONE_MINUS_SRC_ALPHA],e.erase=[r.ZERO,r.ONE_MINUS_SRC_ALPHA],!(r instanceof g.get().getWebGLRenderingContext()))e.min=[r.ONE,r.ONE,r.ONE,r.ONE,r.MIN,r.MIN],e.max=[r.ONE,r.ONE,r.ONE,r.ONE,r.MAX,r.MAX];else{const n=r.getExtension("EXT_blend_minmax");n&&(e.min=[r.ONE,r.ONE,r.ONE,r.ONE,n.MIN_EXT,n.MIN_EXT],e.max=[r.ONE,r.ONE,r.ONE,r.ONE,n.MAX_EXT,n.MAX_EXT])}return e}const{BLEND:yt,OFFSET:Dt,CULLING:Nt,DEPTH_TEST:Ct,WINDING:It,DEPTH_MASK:$}=Le,Se=class M{constructor(e){this._invertFrontFace=!1,this._renderer=e,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[yt]=this.setBlend,this.map[Dt]=this.setOffset,this.map[Nt]=this.setCullFace,this.map[Ct]=this.setDepthTest,this.map[It]=this.setFrontFace,this.map[$]=this.setDepthMask,this.checks=[],this.defaultState=P.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=Bt(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,n=0;for(;t;)t&1&&this.map[n].call(this,!!(e.data&1<<n)),t>>=1,n++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(M._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(M._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}get depthMaskEnabled(){return!!(this.stateId&1<<$)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],n=this.gl;t.length===2?n.blendFunc(t[0],t[1]):n.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,n.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,n.blendEquationSeparate(n.FUNC_ADD,n.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const n=this.checks.indexOf(e);t&&n===-1?this.checks.push(e):!t&&n!==-1&&this.checks.splice(n,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0,this._renderer=null}};Se.extension={type:[d.WebGLSystem],name:"state"};let Gt=Se;class Ut{constructor(e){this.target=v.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=f.UNSIGNED_BYTE,this.internalFormat=F.RGBA,this.format=F.RGBA,this.samplerType=0}destroy(){}}const z=[new T,new T,new T],Ft={id:"buffer",upload(r,e,t,n,s,i=!1){const a=s||e.target,o=r.resource;if(a===v.TEXTURE_3D||a===v.TEXTURE_2D_ARRAY){i||e.width!==r.width||e.height!==r.height?t.texImage3D(a,0,e.internalFormat,r.width,r.height,r.depthOrArrayLayers,0,e.format,e.type,o):t.texSubImage3D(a,0,0,0,0,r.width,r.height,r.depthOrArrayLayers,e.format,e.type,o),e.width=r.width,e.height=r.height;return}const c=r.width*r.height,u=i||e.width!==r.width||e.height!==r.height,_=r._updateStart>0||r._updateEnd<c;if(u)t.texImage2D(a,0,e.internalFormat,r.width,r.height,0,e.format,e.type,o);else if(_){const h=o.length/c,l=ze(r._updateStart,r._updateEnd,r.width,r.height,z);for(let m=0;m<l;m++){const E=z[m],b=(E.y*r.width+E.x)*h;t.texSubImage2D(a,0,E.x,E.y,E.width,E.height,e.format,e.type,o.subarray(b,b+E.width*E.height*h))}}else t.texSubImage2D(a,0,0,0,r.width,r.height,e.format,e.type,o);e.width=r.width,e.height=r.height}},Mt={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},Pt={id:"compressed",upload(r,e,t,n,s,i){const a=s??e.target;t.pixelStorei(t.UNPACK_ALIGNMENT,4);let o=r.pixelWidth,c=r.pixelHeight;const u=!!Mt[r.format];for(let _=0;_<r.resource.length;_++){const h=r.resource[_];u?t.compressedTexImage2D(a,_,e.internalFormat,o,c,0,h):t.texImage2D(a,_,e.internalFormat,o,c,0,e.format,e.type,h),o=Math.max(o>>1,1),c=Math.max(c>>1,1)}}},q=["right","left","top","bottom","front","back"];function Ot(r){return{id:"cube",upload(e,t,n,s){const i=e.faces;for(let a=0;a<q.length;a++){const o=q[a],c=i[o];if(!c.resource)continue;(r[c.uploadMethodId]||r.image).upload(c,t,n,s,v.TEXTURE_CUBE_MAP_POSITIVE_X+a,(t._layerInitMask&1<<a)===0),t._layerInitMask|=1<<a}t.width=e.pixelWidth,t.height=e.pixelHeight}}}const xe={id:"image",upload(r,e,t,n,s,i=!1){const a=s||e.target,o=r.pixelWidth,c=r.pixelHeight,u=r.resourceWidth,_=r.resourceHeight,h=n===2,l=i||e.width!==o||e.height!==c,m=u>=o&&_>=c,E=r.resource;(h?Lt:wt)(t,a,e,o,c,u,_,E,l,m),e.width=o,e.height=c}};function Lt(r,e,t,n,s,i,a,o,c,u){if(!u){c&&r.texImage2D(e,0,t.internalFormat,n,s,0,t.format,t.type,null),r.texSubImage2D(e,0,0,0,i,a,t.format,t.type,o);return}if(!c){r.texSubImage2D(e,0,0,0,t.format,t.type,o);return}r.texImage2D(e,0,t.internalFormat,n,s,0,t.format,t.type,o)}function wt(r,e,t,n,s,i,a,o,c,u){if(!u){c&&r.texImage2D(e,0,t.internalFormat,n,s,0,t.format,t.type,null),r.texSubImage2D(e,0,0,0,t.format,t.type,o);return}if(!c){r.texSubImage2D(e,0,0,0,t.format,t.type,o);return}r.texImage2D(e,0,t.internalFormat,t.format,t.type,o)}const Ht=et(),Xt={id:"video",upload(r,e,t,n,s,i=Ht){if(!r.isValid){const a=s??e.target;t.texImage2D(a,0,e.internalFormat,1,1,0,e.format,e.type,null);return}xe.upload(r,e,t,n,s,i)}},Z={linear:9729,nearest:9728},Vt={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},U={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},kt={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function J(r,e,t,n,s,i,a,o){const c=i;if(!o||r.addressModeU!=="repeat"||r.addressModeV!=="repeat"||r.addressModeW!=="repeat"){const u=U[a?"clamp-to-edge":r.addressModeU],_=U[a?"clamp-to-edge":r.addressModeV],h=U[a?"clamp-to-edge":r.addressModeW];e[s](c,e.TEXTURE_WRAP_S,u),e[s](c,e.TEXTURE_WRAP_T,_),e.TEXTURE_WRAP_R&&e[s](c,e.TEXTURE_WRAP_R,h)}if((!o||r.magFilter!=="linear")&&e[s](c,e.TEXTURE_MAG_FILTER,Z[r.magFilter]),t){if(!o||r.mipmapFilter!=="linear"){const u=Vt[r.minFilter][r.mipmapFilter];e[s](c,e.TEXTURE_MIN_FILTER,u)}}else e[s](c,e.TEXTURE_MIN_FILTER,Z[r.minFilter]);if(n&&r.maxAnisotropy>1){const u=Math.min(r.maxAnisotropy,e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[s](c,n.TEXTURE_MAX_ANISOTROPY_EXT,u)}r.compare?(e[s](c,e.TEXTURE_COMPARE_FUNC,kt[r.compare]),e[s](c,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE)):o||e[s](c,e.TEXTURE_COMPARE_MODE,e.NONE)}function Wt(r){return{r8unorm:r.RED,r8snorm:r.RED,r8uint:r.RED_INTEGER,r8sint:r.RED_INTEGER,r16uint:r.RED_INTEGER,r16sint:r.RED_INTEGER,r16float:r.RED,rg8unorm:r.RG,rg8snorm:r.RG,rg8uint:r.RG_INTEGER,rg8sint:r.RG_INTEGER,r32uint:r.RED_INTEGER,r32sint:r.RED_INTEGER,r32float:r.RED,rg16uint:r.RG_INTEGER,rg16sint:r.RG_INTEGER,rg16float:r.RG,rgba8unorm:r.RGBA,"rgba8unorm-srgb":r.RGBA,rgba8snorm:r.RGBA,rgba8uint:r.RGBA_INTEGER,rgba8sint:r.RGBA_INTEGER,bgra8unorm:r.RGBA,"bgra8unorm-srgb":r.RGBA,rgb9e5ufloat:r.RGB,rgb10a2unorm:r.RGBA,rg11b10ufloat:r.RGB,rg32uint:r.RG_INTEGER,rg32sint:r.RG_INTEGER,rg32float:r.RG,rgba16uint:r.RGBA_INTEGER,rgba16sint:r.RGBA_INTEGER,rgba16float:r.RGBA,rgba32uint:r.RGBA_INTEGER,rgba32sint:r.RGBA_INTEGER,rgba32float:r.RGBA,stencil8:r.STENCIL_INDEX8,depth16unorm:r.DEPTH_COMPONENT,depth24plus:r.DEPTH_COMPONENT,"depth24plus-stencil8":r.DEPTH_STENCIL,depth32float:r.DEPTH_COMPONENT,"depth32float-stencil8":r.DEPTH_STENCIL}}function jt(r,e){let t={},n=r.RGBA;return r instanceof g.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":r.SRGB8_ALPHA8,"bgra8unorm-srgb":r.SRGB8_ALPHA8},n=r.RGBA8),{r8unorm:r.R8,r8snorm:r.R8_SNORM,r8uint:r.R8UI,r8sint:r.R8I,r16uint:r.R16UI,r16sint:r.R16I,r16float:r.R16F,rg8unorm:r.RG8,rg8snorm:r.RG8_SNORM,rg8uint:r.RG8UI,rg8sint:r.RG8I,r32uint:r.R32UI,r32sint:r.R32I,r32float:r.R32F,rg16uint:r.RG16UI,rg16sint:r.RG16I,rg16float:r.RG16F,rgba8unorm:r.RGBA,...t,rgba8snorm:r.RGBA8_SNORM,rgba8uint:r.RGBA8UI,rgba8sint:r.RGBA8I,bgra8unorm:n,rgb9e5ufloat:r.RGB9_E5,rgb10a2unorm:r.RGB10_A2,rg11b10ufloat:r.R11F_G11F_B10F,rg32uint:r.RG32UI,rg32sint:r.RG32I,rg32float:r.RG32F,rgba16uint:r.RGBA16UI,rgba16sint:r.RGBA16I,rgba16float:r.RGBA16F,rgba32uint:r.RGBA32UI,rgba32sint:r.RGBA32I,rgba32float:r.RGBA32F,stencil8:r.STENCIL_INDEX8,depth16unorm:r.DEPTH_COMPONENT16,depth24plus:r.DEPTH_COMPONENT24,"depth24plus-stencil8":r.DEPTH24_STENCIL8,depth32float:r.DEPTH_COMPONENT32F,"depth32float-stencil8":r.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function Kt(r){return{r8unorm:r.UNSIGNED_BYTE,r8snorm:r.BYTE,r8uint:r.UNSIGNED_BYTE,r8sint:r.BYTE,r16uint:r.UNSIGNED_SHORT,r16sint:r.SHORT,r16float:r.HALF_FLOAT,rg8unorm:r.UNSIGNED_BYTE,rg8snorm:r.BYTE,rg8uint:r.UNSIGNED_BYTE,rg8sint:r.BYTE,r32uint:r.UNSIGNED_INT,r32sint:r.INT,r32float:r.FLOAT,rg16uint:r.UNSIGNED_SHORT,rg16sint:r.SHORT,rg16float:r.HALF_FLOAT,rgba8unorm:r.UNSIGNED_BYTE,"rgba8unorm-srgb":r.UNSIGNED_BYTE,rgba8snorm:r.BYTE,rgba8uint:r.UNSIGNED_BYTE,rgba8sint:r.BYTE,bgra8unorm:r.UNSIGNED_BYTE,"bgra8unorm-srgb":r.UNSIGNED_BYTE,rgb9e5ufloat:r.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:r.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:r.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:r.UNSIGNED_INT,rg32sint:r.INT,rg32float:r.FLOAT,rgba16uint:r.UNSIGNED_SHORT,rgba16sint:r.SHORT,rgba16float:r.HALF_FLOAT,rgba32uint:r.UNSIGNED_INT,rgba32sint:r.INT,rgba32float:r.FLOAT,stencil8:r.UNSIGNED_BYTE,depth16unorm:r.UNSIGNED_SHORT,depth24plus:r.UNSIGNED_INT,"depth24plus-stencil8":r.UNSIGNED_INT_24_8,depth32float:r.FLOAT,"depth32float-stencil8":r.FLOAT_32_UNSIGNED_INT_24_8_REV}}function Yt(r){return{"2d":r.TEXTURE_2D,cube:r.TEXTURE_CUBE_MAP,"1d":null,"3d":(r==null?void 0:r.TEXTURE_3D)||null,"2d-array":(r==null?void 0:r.TEXTURE_2D_ARRAY)||null,"cube-array":(r==null?void 0:r.TEXTURE_CUBE_MAP_ARRAY)||null}}const $t=4,V=class ve{constructor(e){this._glSamplers=Object.create(null),this._boundTextures=[],this._integerUnits=0,this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._managedTextures=new O({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"glTexture"});const t={image:xe,buffer:Ft,video:Xt,compressed:Pt,...ve.uploadExtensions};this._uploads={...t,cube:Ot(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=jt(e,this._renderer.context.extensions),this._mapFormatToType=Kt(e),this._mapFormatToFormat=Wt(e),this._mapViewDimensionToGlTarget=Yt(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(R.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const n=e.source;e?(this.bindSource(n,t),this._useSeparateSamplers&&this._bindSampler(n.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const n=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._setBoundTexture(t,e),this._activateLocation(t),e||(e=R.EMPTY.source);const s=this.getGlSource(e);n.bindTexture(s.target,s.texture)}}unbindIntegerTextures(e){if(e>=32)return;let t=this._integerUnits>>>e<<e;for(;t;){const n=31-Math.clz32(t);t&=~(1<<n),this.bind(R.EMPTY,n)}}_setBoundTexture(e,t){this._boundTextures[e]=t,!(e<0||e>31)&&(!t||t.viewDimension!=="2d"||(k(t.format)?this._integerUnits|=1<<e:this._integerUnits&=~(1<<e)))}_bindSampler(e,t=0){const n=this._gl;if(!e){this._boundSamplers[t]=null,n.bindSampler(t,null);return}const s=this._getGlSampler(e);this._boundSamplers[t]!==s&&(this._boundSamplers[t]=s,n.bindSampler(t,s))}unbind(e){const t=e.source,n=this._boundTextures,s=this._gl;for(let i=0;i<n.length;i++)if(n[i]===t){this._activateLocation(i);const a=this.getGlSource(t);s.bindTexture(a.target,null),this._setBoundTexture(i,null)}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,n=new Ut(t.createTexture());if(n.type=this._mapFormatToType[e.format],n.internalFormat=this._mapFormatToInternalFormat[e.format],n.format=this._mapFormatToFormat[e.format],n.target=this._mapViewDimensionToGlTarget[e.viewDimension],n.target===null)throw new Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const i=Math.max(e.width,e.height,e.depth);e.mipLevelCount=Math.floor(Math.log2(i))+1}return e._gpuData[this._renderer.uid]=n,this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),n}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const n=this._gl,s=this.getGlSource(e);n.bindTexture(s.target,s.texture),this._setBoundTexture(this._activeTextureLocation,e),J(e.style,n,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",s.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){const n=e._gpuData[this._renderer.uid];n&&(t||(this.unbind(e),this._gl.deleteTexture(n.texture)),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this))}onSourceUpdate(e){const t=this._gl,n=this.getGlSource(e);t.bindTexture(n.target,n.texture),this._setBoundTexture(this._activeTextureLocation,e);const s=e.alphaMode==="premultiply-alpha-on-upload"&&!k(e.format)&&n.target!==t.TEXTURE_3D&&n.target!==t.TEXTURE_2D_ARRAY;if(this._premultiplyAlpha!==s&&(this._premultiplyAlpha=s,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,s)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,n,t,this._renderer.context.webGLVersion);else if(n.target===t.TEXTURE_2D)this._initEmptyTexture2D(n,e);else if(n.target===t.TEXTURE_2D_ARRAY||n.target===t.TEXTURE_3D)this._initEmptyTexture3D(n,e);else if(n.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(n,e);else throw new Error("[GlTextureSystem] Unsupported texture target for empty allocation.");this._applyMipRange(n,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const n=this.getGlSource(e);this._gl.generateMipmap(n.target)}_initEmptyTexture2D(e,t){const n=this._gl;n.texImage2D(n.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let s=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)n.texImage2D(n.TEXTURE_2D,a,e.internalFormat,s,i,0,e.format,e.type,null),s=Math.max(s>>1,1),i=Math.max(i>>1,1)}_initEmptyTexture3D(e,t){const n=this._gl,s=e.target===n.TEXTURE_3D;let i=t.pixelWidth,a=t.pixelHeight,o=t.depthOrArrayLayers;for(let c=0;c<t.mipLevelCount;c++)n.texImage3D(e.target,c,e.internalFormat,i,a,o,0,e.format,e.type,null),i=Math.max(i>>1,1),a=Math.max(a>>1,1),s&&(o=Math.max(o>>1,1))}_initEmptyTextureCube(e,t){const n=this._gl,s=6;for(let o=0;o<s;o++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let i=Math.max(t.pixelWidth>>1,1),a=Math.max(t.pixelHeight>>1,1);for(let o=1;o<t.mipLevelCount;o++){for(let c=0;c<s;c++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+c,o,e.internalFormat,i,a,0,e.format,e.type,null);i=Math.max(i>>1,1),a=Math.max(a>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2||t.mipLevelCount<=1)return;const n=this._gl,s=Math.max((t.mipLevelCount|0)-1,0);n.texParameteri(e.target,n.TEXTURE_BASE_LEVEL,0),n.texParameteri(e.target,n.TEXTURE_MAX_LEVEL,s)}_initSampler(e){const t=this._gl,n=this._gl.createSampler();return this._glSamplers[e._resourceId]=n,J(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",n,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:n,height:s}=this.getPixels(e),i=g.get().createCanvas();i.width=n,i.height=s;const a=i.getContext("2d");if(a){const o=a.createImageData(n,s);o.data.set(t),a.putImageData(o,0,0)}return i}getPixels(e){const t=e.source.resolution,n=e.frame,s=Math.max(Math.round(n.width*t),1),i=Math.max(Math.round(n.height*t),1),a=new Uint8Array($t*s*i),o=this._renderer,c=o.renderTarget.getRenderTarget(e),u=o.renderTarget.getGpuRenderTarget(c),_=o.gl;return o.renderTarget.adaptor.bindFramebuffer(u.resolveTargetFramebuffer),_.readPixels(Math.round(n.x*t),Math.round(n.y*t),s,i,_.RGBA,_.UNSIGNED_BYTE,a),{pixels:new Uint8ClampedArray(a.buffer),width:s,height:i}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){const e=this._renderer.limits.maxTextures;this._activeTextureLocation=-1,this._boundTextures.fill(null),this._integerUnits=e>=32?-1:(1<<e)-1,this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}};V.extension={type:[d.WebGLSystem],name:"texture"};V.uploadExtensions=Object.create(null);let Ae=V;S.handleByMap(d.TextureUploaderWebGL,Ae.uploadExtensions);class Be{contextChange(e){const t=new w({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new te,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),n=e.limits.maxBatchableTextures,s=re({name:"graphics",bits:[we,He(n),ie,ne]});this.shader=new L({glProgram:s,resources:{localUniforms:t,batchSamplers:Xe(n)}})}execute(e,t){const n=t.context,s=n.customShader||this.shader,i=e.renderer,a=i.graphicsContext,{batcher:o,instructions:c}=a.getContextRenderData(n);s.groups[0]=i.globalUniforms.bindGroup,i.state.set(e.state),i.shader.bind(s),i.geometry.bind(o.geometry,s.glProgram);const u=c.instructions;for(let _=0;_<c.instructionSize;_++){const h=u[_];if(h.size){for(let l=0;l<h.textures.count;l++)i.texture.bind(h.textures.textures[l],l);i.texture.unbindIntegerTextures(h.textures.count),i.geometry.draw(h.topology,h.size,h.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}Be.extension={type:[d.WebGLPipesAdaptor],name:"graphics"};class ye{init(){const e=re({name:"mesh",bits:[ie,qe,ne]});this._shader=new L({glProgram:e,resources:{uTexture:R.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new te}}}})}execute(e,t){const n=e.renderer;let s=t._shader;if(s){if(!s.glProgram){p("Mesh shader has no glProgram",t.shader);return}}else{s=this._shader;const i=t.texture,a=i.source;s.resources.uTexture=a,s.resources.uSampler=a.style,s.resources.textureUniforms.uniforms.uTextureMatrix=i.textureMatrix.mapCoord}s.groups[100]=n.globalUniforms.bindGroup,s.groups[101]=e.localUniformsBindGroup,n.encoder.draw({geometry:t._geometry,shader:s,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}ye.extension={type:[d.WebGLPipesAdaptor],name:"mesh"};const zt=[...Je,Ee,ot,rt,le,oe,Ae,be,ue,ge,Te,fe,Gt,de,he],qt=[...Qe],Zt=[ae,ye,Be],De=[],Ne=[],Ce=[],Ie=[];S.handleByNamedList(d.WebGLSystem,De);S.handleByNamedList(d.WebGLPipes,Ne);S.handleByNamedList(d.WebGLPipesAdaptor,Ce);S.handleByNamedList(d.WebGLLoader,Ie);S.add(...zt,...qt,...Zt);class rr extends Ve{constructor(){const e={name:"webgl",type:ke.WEBGL,systems:De,renderPipes:Ne,renderPipeAdaptors:Ce,loaders:Ie};super(e)}}export{rr as WebGLRenderer};
@@ -0,0 +1,75 @@
1
+ import{J as te,a as re,o as g,K as se,L as Fe,w as B,D as E,j as A,B as De,N as ie,h as D,O as W,Q as ke,V as ne,W as S,x as L,X as F,Y as ae,y as T,M as oe,Z as ue,_ as Ie,$ as ce,a0 as ze,S as de,T as V,A as We,R as Ve}from"./index-DPTN0V6X.js";import{c as Ne,u as He,U as $e,B as Ke,G as je,e as N,g as qe,l as Ye,a as Xe,t as Ze}from"./getTexelRangeRects-D8_SvULv.js";import{R as Je,S as Qe,d as et}from"./RenderTargetSystem-BccyHTeF.js";import{C as H}from"./CanvasPool-O1IaWL-9.js";const M=re.for2d();class le{start(e,t,r){const s=e.renderer,i=s.encoder,n=r.gpuProgram;this._shader=r,this._geometry=t,i.setGeometry(t,n),M.blendMode="normal",s.pipeline.getPipeline(t,n,M,void 0,r._overrides);const a=s.globalUniforms.bindGroup;i.resetBindGroup(1),i.setBindGroup(0,a,n)}execute(e,t){const r=this._shader.gpuProgram,s=e.renderer,i=s.encoder;if(!t.bindGroup){const o=t.textures;t.bindGroup=te(o.textures,o.count,s.limits.maxBatchableTextures)}M.blendMode=t.blendMode;const n=s.bindGroup.getBindGroup(t.bindGroup,r,1),a=s.pipeline.getPipeline(this._geometry,r,M,t.topology,this._shader._overrides);t.bindGroup._touch(s.gc.now),i.setPipeline(a),i.renderPassEncoder.setBindGroup(1,n),i.renderPassEncoder.drawIndexed(t.size,1,t.start)}}le.extension={type:[g.WebGPUPipesAdaptor],name:"batch"};class tt{constructor(e,t){this.autoGarbageCollect=!0,this._gpuData=null,this.gpuBindGroup=e,this._gcLastUsed=t}unload(){this.gpuBindGroup=null}}class he{constructor(e){this._hash=Object.create(null),this._renderer=e,e.gc.addResourceHash(this,"_hash","resource"),e.gc.addCollection(this,"_hash","hash")}contextChange(e){this._gpu=e,this._hash=Object.create(null)}getBindGroup(e,t,r){const s=`${e._key}:${t._layoutKey<<4|r}`,i=this._hash[s];return i?(i._gcLastUsed=this._renderer.gc.now,i.gpuBindGroup):this._createBindGroup(s,e,t,r)}_createBindGroup(e,t,r,s){const i=this._gpu.device,n=r.layout[s],a=[],o=this._renderer;for(const h in n){const d=t.resources[h]??t.resources[n[h]];if(!d||d.destroyed)throw new Error(`[BindGroup] the resource bound as '${h}' was destroyed while a shader still uses it. Remove it from the shader before destroying it.`);let m;if(d._resourceType==="uniformGroup"){const p=d;o.ubo.updateUniformGroup(p);const f=p.buffer;m={buffer:o.buffer.getGPUBuffer(f),offset:0,size:f.descriptor.size}}else if(d._resourceType==="buffer"){const p=d;m={buffer:o.buffer.getGPUBuffer(p),offset:0,size:p.descriptor.size}}else if(d._resourceType==="bufferResource"){const p=d;m={buffer:o.buffer.getGPUBuffer(p.buffer),offset:p.offset,size:p.size??p.buffer.descriptor.size}}else if(d._resourceType==="textureSampler"){const p=d;m=o.texture.getGpuSampler(p)}else if(d._resourceType==="textureSource"){const p=d;m=o.texture.getTextureView(p)}else if(d._resourceType==="textureView"){const p=d;m=o.texture.getTextureView(p.source,p.viewDescriptor)}a.push({binding:n[h],resource:m})}const c=o.shader.getProgramData(r).bindGroups[s],l=i.createBindGroup({layout:c,entries:a});return this._hash[e]=new tt(l,o.gc.now),l}destroy(){this._hash=null,this._renderer=null}}he.extension={type:[g.WebGPUSystem],name:"bindGroup"};class rt{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}}class pe{constructor(e){this._renderer=e,this._managedBuffers=new se({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e,this.destroyAll()}getGPUBuffer(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuBuffer)||this.createGPUBuffer(e)}updateBuffer(e){const t=this.getGPUBuffer(e),r=e.data;return e._updateID&&r&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,e._updateOffset,r.buffer,r.byteOffset+e._updateOffset,(e._updateSize||r.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e.data&&(Fe(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new rt(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}}pe.extension={type:[g.WebGPUSystem],name:"buffer"};class st{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let r=t+e*4;if(r=Math.ceil(r/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,r>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=r,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let r=0;r<e.length;r++)this.data[t/4+r]=e[r];return t}destroy(){this.data=null}}class fe{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}fe.extension={type:[g.WebGPUSystem],name:"colorMask"};const it=new Set(["apple","arm","qualcomm","img-tec"]);class k{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._options=e,this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>this._setGpu(t)),this._initPromise)}_setGpu(e){var t,r;this.gpu=e,this.extensions={transientAttachment:typeof GPUTextureUsage.TRANSIENT_ATTACHMENT=="number",tileBased:it.has((r=(t=e.adapter)==null?void 0:t.info)==null?void 0:r.vendor)},this._options.gpu||e.device.lost.then(()=>this._restoreDevice()).catch(s=>B("WebGPU device was lost and could not be restored",s)),this._renderer.runners.contextChange.emit(this.gpu)}async _restoreDevice(){if(!this._renderer)return;const e=await this._createDeviceAndAdaptor(this._options);if(!this._renderer){e.device.destroy();return}this._setGpu(e)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await E.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter});if(!t)throw new Error("WebGPU not supported. No GPU adapter was returned by navigator.gpu.requestAdapter().");const r=["texture-compression-bc","texture-compression-astc","texture-compression-etc2","indirect-first-instance","bgra8unorm-storage","texture-formats-tier1"].filter(i=>t.features.has(i)),s=await t.requestDevice({requiredFeatures:r,requiredLimits:{maxSampledTexturesPerShaderStage:t.limits.maxSampledTexturesPerShaderStage,maxSamplersPerShaderStage:t.limits.maxSamplersPerShaderStage}});return{adapter:t,device:s}}destroy(){var e,t;(e=this._options)!=null&&e.gpu||(t=this.gpu)==null||t.device.destroy(),this.gpu=null,this.extensions=null,this._renderer=null}}k.extension={type:[g.WebGPUSystem],name:"device"};k.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class nt{constructor(e,t,r,s){this.gpuBundle=e,this.stateKey=t,this.device=r,this.label=s}}class me{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e;for(let t=0;t<16;t++)this._boundBindGroup[t]={bindGroup:null,program:null,key:null}}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){return this.endRenderPass(),this._clearCache(),this._passEncoder=this.commandEncoder.beginRenderPass(e.descriptor),this.renderPassEncoder=this._passEncoder,this._passEncoder}endRenderPass(){this._passEncoder&&this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null}beginBundle(e){if(this._passEncoder!==this.renderPassEncoder)throw new Error("Cannot begin a new render bundle while one is already being recorded.");this._clearCache();const t=this._renderer.pipeline,r=t.getBundleDescriptor();r.label=e,this._bundleStateKey=t.bundleStateKey,this._bundleLabel=e,this.renderPassEncoder=this._gpu.device.createRenderBundleEncoder(r)}endBundle(){const e=this.renderPassEncoder;if(!e||!("finish"in e))throw new Error("endBundle called without an active render bundle.");const t=e.finish({label:this._bundleLabel});return this.renderPassEncoder=this._passEncoder,this._clearCache(),new nt(t,this._bundleStateKey,this._gpu.device,this._bundleLabel)}isBundleValid(e){return(e==null?void 0:e.stateKey)===this._renderer.pipeline.bundleStateKey&&e.device===this._gpu.device}executeBundle(e){const t=[];if(Array.isArray(e))for(let r=0;r<e.length;r++)t[r]=this._getGpuBundle(e[r]);else t[0]=this._getGpuBundle(e);this._clearCache(),this._passEncoder.executeBundles(t)}_getGpuBundle(e){return this.isBundleValid(e)||B(`Render bundle ${(e==null?void 0:e.label)??"(unlabeled)"} was recorded against a different render target state or on a lost device. Re-record it — replaying it will either be rejected by WebGPU or draw with the wrong winding. Check encoder.isBundleValid(bundle) before executing.`),e.gpuBundle}setViewport(e){this._passEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setStencilReference(e){this._passEncoder.setStencilReference(e)}setPipelineFromGeometryProgramAndState(e,t,r,s,i){const n=this._renderer.pipeline.getPipeline(e,t,r,s,i);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){const t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=null}setBindGroup(e,t,r){const s=this._boundBindGroup[e];if(s.bindGroup===t&&s.program===r&&s.key===t._key)return;s.bindGroup=t,s.program=r,s.key=t._key,t._touch(this._renderer.gc.now);const i=this._renderer.bindGroup.getBindGroup(t,r,e);this.renderPassEncoder.setBindGroup(e,i)}setGeometry(e,t){const r=this._renderer.pipeline.getBufferNamesToBind(e,t);for(let s=0;s<r.length;s++)this._setVertexBuffer(s,e.attributes[r[s]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){const r=e.gpuProgram,s=r.layout;for(let i=0;i<s.length;i++){const n=e.groups[i];!s[i]||!n||(t||this._syncBindGroup(n),this.setBindGroup(i,n,r))}}_syncBindGroup(e){const t=e.resources,r=e._resourceKeys;for(let s=0;s<r.length;s++){const i=t[r[s]];i&&i.isUniformGroup&&this._renderer.ubo.updateUniformGroup(i)}}draw(e){const{geometry:t,shader:r,state:s,topology:i,size:n,start:a,baseVertex:o,instanceCount:c,skipSync:l,firstInstance:h}=e;this.setPipelineFromGeometryProgramAndState(t,r.gpuProgram,s,i,r._overrides),this.setGeometry(t,r.gpuProgram),this._setShaderBindGroups(r,l),t.indexBuffer?this.renderPassEncoder.drawIndexed(n||t.indexCount||t.indexBuffer.data.length,c??t.instanceCount,a||0,o||0,h||0):this.renderPassEncoder.draw(n||t.vertexCount,c??t.instanceCount,a||0,h||0)}drawIndirect(e){const{geometry:t,shader:r,state:s,topology:i,skipSync:n,indirectBuffer:a,indirectOffset:o}=e;this.setPipelineFromGeometryProgramAndState(t,r.gpuProgram,s,i,r._overrides),this.setGeometry(t,r.gpuProgram),this._setShaderBindGroups(r,n),t.indexBuffer?this.renderPassEncoder.drawIndexedIndirect(a,o):this.renderPassEncoder.drawIndirect(a,o)}finishRenderPass(){this._passEncoder&&(this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}_clearCache(){for(let e=0;e<16;e++){const t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=null,this._boundVertexBuffer[e]=null}this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null,this.renderPassEncoder=null,this._passEncoder=null}contextChange(e){this._gpu=e}}me.extension={type:[g.WebGPUSystem],name:"encoder",priority:1};class ge{constructor(e){this.supportsOverrideConstants=!1,this._renderer=e}contextChange(){const e=this._renderer.device.gpu.device;this.maxTextures=Math.min(e.limits.maxSampledTexturesPerShaderStage,e.limits.maxSamplersPerShaderStage),this.maxBatchableTextures=this.maxTextures,this._detectOverrideConstantsSupport(e)}_detectOverrideConstantsSupport(e){e.pushErrorScope("validation");const t=e.createShaderModule({code:`override TEST_VALUE: f32 = 0.0;
2
+ @compute @workgroup_size(1) fn main() {}`});e.createComputePipeline({layout:"auto",compute:{module:t,entryPoint:"main",constants:{TEST_VALUE:1}}}),e.popErrorScope().then(r=>{this.supportsOverrideConstants=!r})}destroy(){}}ge.extension={type:[g.WebGPUSystem],name:"limits"};class _e{constructor(e){this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}contextChange(){this._activeGpuRenderTarget=null}onRenderTargetChange(e){const t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeRenderTarget=e,this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const r=this._activeGpuRenderTarget??(this._activeGpuRenderTarget=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget));r.stencilMode=e,r.stencilReference=t;const s=this._renderer;s.pipeline.setStencilMode(e),s.encoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}}_e.extension={type:[g.WebGPUSystem],name:"stencil"};const U={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function at(u){const e=u.map(r=>({data:r,offset:0,size:0}));let t=0;for(let r=0;r<e.length;r++){const s=e[r];let i=U[s.data.type].size;const n=U[s.data.type].align;if(!U[s.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${s.data.type}`);s.data.size>1&&(i=Math.max(i,n)*s.data.size),t=Math.ceil(t/n)*n,s.size=i,s.offset=t,t+=i}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function ot(u,e){const{size:t,align:r}=U[u.data.type],s=(Math.max(t,r)-t)/4,i=u.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
3
+ v = uv.${u.data.name};
4
+ ${e!==0?`offset += ${e};`:""}
5
+
6
+ arrayOffset = offset;
7
+
8
+ t = 0;
9
+
10
+ for(var i=0; i < ${u.data.size}; i++)
11
+ {
12
+ for(var j = 0; j < ${t/4}; j++)
13
+ {
14
+ ${i}[arrayOffset++] = v[t++];
15
+ }
16
+ ${s!==0?`arrayOffset += ${s};`:""}
17
+ }
18
+ `}function ut(u){return Ne(u,He,ot)}class be extends $e{constructor(){super({createUboElements:at,generateUboSync:ut})}}be.extension={type:[g.WebGPUSystem],name:"ubo"};const v=128;class ye{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new st({minUniformOffsetAlignment:v});const t=256/v;for(let r=0;r<t;r++){let s=A.UNIFORM|A.COPY_DST;r===0&&(s|=A.COPY_SRC),this._buffers.push(new De({data:this._batchBuffer.data,usage:s}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const r=e.buffer.data,s=this._batchBuffer.addEmptyGroup(r.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,s/4),this._bindGroupHash[e.uid]=this._getBindGroup(s/v),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,r=this._batchBuffer.addGroup(t);return this._getBufferResource(r/v)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/v)}getArrayBufferResource(e){const r=this._batchBuffer.addGroup(e)/v;return this._getBufferResource(r)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Ke({buffer:t,offset:(e/2|0)*256,size:v})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new ie({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const r=this._renderer.gpu.device.createCommandEncoder();for(let s=1;s<this._buffers.length;s++){const i=this._buffers[s];r.copyBufferToBuffer(e.getGPUBuffer(t),v,e.getGPUBuffer(i),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([r.finish()])}destroy(){var e;for(let t=0;t<this._bindGroups.length;t++)(e=this._bindGroups[t])==null||e.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}}ye.extension={type:[g.WebGPUPipes],name:"uniformBatch"};const $={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4},ct=new ke({}),dt={"depth24plus-stencil8":{depth:!0,stencil:!0,index:1},depth24plus:{depth:!0,stencil:!1,index:2},depth32float:{depth:!0,stencil:!1,index:3},"depth32float-stencil8":{depth:!0,stencil:!0,index:4},depth16unorm:{depth:!0,stencil:!1,index:5},stencil8:{depth:!1,stencil:!0,index:6}},K={depth:!1,stencil:!1,index:0};function j(u,e){for(const[t,r]of Object.entries(e)){const s=new RegExp(`override\\s+${t}\\s*:\\s*(\\w+)\\s*(?:=[^;]*)?;`);u=u.replace(s,(i,n)=>{let a;return n==="u32"?a=`${Math.trunc(r)}u`:n==="i32"?a=`${Math.trunc(r)}`:a=Number.isInteger(r)?`${r}.0`:`${r}`,`const ${t}: ${n} = ${a};`})}return u}function q(u,e,t,r,s,i){return u*35184372088832+e*536870912+i*16384+(t<<8)+(r<<3)+s}const Y=Object.create(null);let lt=0;function X(u){let e=Y[u];return e===void 0&&(e=Y[u]=lt++),e}function ht(u,e,t,r,s,i,n,a){return a<<20|i<<16|s<<13|t<<9|u<<6|n<<5|r<<1|e}function pt(u,e,t,r,s,i,n){return n<<11|i<<10|s<<9|r<<8|t<<5|e<<1|u}class xe{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=new Map,this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._colorFormat="bgra8unorm",this._colorFormatId=X("bgra8unorm"),this._depthStencilFormat="depth24plus-stencil8",this._depthStencilFormatData=K,this._depthReadOnly=!1,this._stencilReadOnly=!1,this._invertFrontFace=!1,this._renderer=e}contextChange(e){this._gpu=e,this._moduleCache=Object.create(null),this._pipeStateCaches=Object.create(null),this.setStencilMode(D.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){var r,s,i,n;const t=(r=e.colorAttachments[0])==null?void 0:r.texture;this._multisampleCount=t!=null&&t.source.antialias?4:1,this._colorTargetCount=e.colorAttachments.length,this._colorFormat=(t==null?void 0:t.format)??"bgra8unorm",this._colorFormatId=X(this._colorFormat),this._depthStencilFormat=(s=e.depthStencilAttachment)==null?void 0:s.texture.format,this._depthStencilFormatData=dt[this._depthStencilFormat]||K,this._depthReadOnly=((i=e.depthStencilAttachment)==null?void 0:i.depthReadOnly)??!1,this._stencilReadOnly=((n=e.depthStencilAttachment)==null?void 0:n.stencilReadOnly)??this._depthReadOnly,this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=je[e],this._updatePipeHash())}get bundleStateKey(){const e=this._depthStencilFormatData;return pt(this._multisampleCount===1?0:1,this._colorTargetCount,e.index,e.depth&&this._depthReadOnly?1:0,e.stencil&&this._stencilReadOnly?1:0,this._invertFrontFace?1:0,this._colorFormatId)}getBundleDescriptor(){const e=[];for(let s=0;s<this._colorTargetCount;s++)e.push(this._colorFormat);const t={colorFormats:e,sampleCount:this._multisampleCount},r=this._depthStencilFormatData;return(r.depth||r.stencil)&&(t.depthStencilFormat=this._depthStencilFormat,r.depth&&this._depthReadOnly&&(t.depthReadOnly=!0),r.stencil&&this._stencilReadOnly&&(t.stencilReadOnly=!0)),t}setPipeline(e,t,r,s){const i=this.getPipeline(e,t,r);s.setPipeline(i)}getPipelineKey(e,t,r,s,i){return e._layoutKey||(N(e,t.attributeData),this._generateBufferKey(e)),q(e._layoutKey,t._layoutKey,r.data,r._blendModeId,$[s],i.id)}getPipeline(e,t,r,s,i){e._layoutKey||(N(e,t.attributeData),this._generateBufferKey(e)),s||(s=e.topology),i||(i=ct);const n=q(e._layoutKey,t._layoutKey,r.data,r._blendModeId,$[s],i.id);let a=this._pipeCache.get(n);return a||(a=this._createPipeline(e,t,r,s,i),this._pipeCache.set(n,a)),a}_createPipeline(e,t,r,s,i){const n=this._gpu.device,a=this._createVertexBufferLayouts(e,t),o=this._renderer.state.getColorTargets(r,this._colorTargetCount,this._colorFormat),c=this._stencilMode===D.RENDERING_MASK_ADD?0:this._colorMask;for(let y=0;y<o.length;y++)o[y].writeMask=c;const l=this._renderer.shader.getProgramData(t).pipeline,h=Object.keys(i.data).length>0;let d=t.vertex.source,m=t.fragment.source,p;h&&(this._renderer.limits.supportsOverrideConstants?p=i.data:(d=j(d,i.data),m=j(m,i.data)));const f={vertex:{module:this._getModule(d),entryPoint:t.vertex.entryPoint,constants:p,buffers:a},fragment:{module:this._getModule(m),entryPoint:t.fragment.entryPoint,targets:o,constants:p},primitive:{topology:s,cullMode:r.culling?"back":"none",frontFace:r.clockwiseFrontFace!==this._invertFrontFace?"cw":"ccw"},layout:l,multisample:{count:this._multisampleCount},label:t.name?`PIXI Pipeline (${t.name})`:"PIXI Pipeline"};if(this._depthStencilFormatData.depth||this._depthStencilFormatData.stencil){const y=this._depthStencilFormatData;f.depthStencil={...this._stencilState,format:this._depthStencilFormat,depthWriteEnabled:y.depth?r.depthMask&&!this._depthReadOnly:!1,depthCompare:y.depth&&r.depthTest?"less":"always"}}return n.createRenderPipeline(f)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let r=0;const s=Object.keys(e.attributes).sort();for(let n=0;n<s.length;n++){const a=e.attributes[s[n]];t[r++]=a.offset,t[r++]=a.format,t[r++]=a.stride,t[r++]=a.instance}const i=t.join("|");return e._layoutKey=W(i,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let r=0;const s=Object.keys(e.attributeData).sort();for(let n=0;n<s.length;n++){const a=e.attributeData[s[n]];t[r++]=a.location}const i=t.join("|");return e._attributeLocationsKey=W(i,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const r=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[r])return this._bindingNamesCache[r];const s=this._createVertexBufferLayouts(e,t),i=[],n=t.attributeData;for(let a=0;a<s.length;a++){const c=Object.values(s[a].attributes)[0].shaderLocation;for(const l in n)if(n[l].location===c){i[a]=l;break}}return this._bindingNamesCache[r]=i,i}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const r=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[r])return this._bufferLayoutsCache[r];const s=[];return e.buffers.forEach(i=>{const n={arrayStride:0,stepMode:"vertex",attributes:[]},a=n.attributes;for(const o in t.attributeData){const c=e.attributes[o];(c.divisor??1)!==1&&B(`Attribute ${o} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===i&&(n.arrayStride=c.stride,n.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[o].location,offset:c.offset,format:c.format}))}a.length&&s.push(n)}),this._bufferLayoutsCache[r]=s,s}_updatePipeHash(){var e;const t=ht(this._stencilMode,this._multisampleCount===1?0:1,this._colorMask,this._colorTargetCount,this._depthStencilFormatData.index,this._colorFormatId,this._depthReadOnly?1:0,this._invertFrontFace?1:0);this._pipeCache=(e=this._pipeStateCaches)[t]??(e[t]=new Map)}destroy(){this._bufferLayoutsCache=null,this._pipeCache=null,this._gpu=null,this._renderer=null,this._bindingNamesCache=null,this._pipeStateCaches=null,this._moduleCache=null}}xe.extension={type:[g.WebGPUSystem],name:"pipeline"};class ft{constructor(e){this._pipelines=Object.create(null),this._modules=Object.create(null),this._bindGroups=new WeakMap,this._renderer=e,this._device=e.gpu.device,this._layout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._layout]})}copy(e,t,r,s){var i;const n=this._renderer.renderTarget.getGpuRenderTarget(t),a=t.colorAttachments[r].texture;(i=n.msaaBackTextures)[r]??(i[r]=new ne({label:"msaa-back-texture",width:a.width,height:a.height,resolution:a._resolution,format:n.msaaTextures[r].format,autoGenerateMipmaps:!1,autoGarbageCollect:!0}));const o=this._renderer.texture.getGpuSource(n.msaaBackTextures[r]);e.copyTextureToTexture({texture:s},{texture:o},{width:Math.min(s.width,o.width),height:Math.min(s.height,o.height)})}draw(e,t,r){var l;var s;const i=this._renderer.renderTarget.getGpuRenderTarget(t),n=this._renderer.texture.getGpuSource(i.msaaBackTextures[r]);let a=((l=t.depthStencilAttachment)==null?void 0:l.texture.format)??"";for(const h of t.colorAttachments)a+=`|${h.texture.format}`;const o=(s=this._pipelines)[a]??(s[a]=[]);let c=this._bindGroups.get(n);c||(c=this._device.createBindGroup({layout:this._layout,entries:[{binding:0,resource:n.createView()}]}),this._bindGroups.set(n,c)),e.setPipeline(o[r]??(o[r]=this._createPipeline(t,r))),e.setBindGroup(0,c),e.draw(3)}_getModule(e){var t;return(t=this._modules)[e]??(t[e]=this._device.createShaderModule({label:"msaa-restore",code:`
19
+ @group(0) @binding(0) var resolved: texture_2d<f32>;
20
+
21
+ @vertex
22
+ fn vertexMain(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
23
+ let pos = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
24
+
25
+ return vec4<f32>(pos[i], 0.0, 1.0);
26
+ }
27
+
28
+ @fragment
29
+ fn fragmentMain(@builtin(position) position: vec4<f32>) -> @location(${e}) vec4<f32> {
30
+ return textureLoad(resolved, vec2<i32>(position.xy), 0);
31
+ }
32
+ `})),this._modules[e]}_createPipeline(e,t){var n;const r=(n=e.depthStencilAttachment)==null?void 0:n.texture.format;let s;r&&(s={format:r},r.includes("depth")&&(s.depthWriteEnabled=!1,s.depthCompare="always"));const i=this._getModule(t);return this._device.createRenderPipeline({label:"msaa-restore",layout:this._pipelineLayout,vertex:{module:i,entryPoint:"vertexMain"},fragment:{module:i,entryPoint:"fragmentMain",targets:e.colorAttachments.map((a,o)=>({format:a.texture.format,writeMask:o===t?GPUColorWrite.ALL:0}))},depthStencil:s,multisample:{count:4}})}}class mt{constructor(){this.contexts=[],this.canvasTextures=[],this.msaaTextures=[],this.transient=!1,this.msaaSamples=1,this.msaaBackTextures=[],this.stencilMode=D.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}const gt={bgra8unorm:!0,rgba8unorm:!0,rgba16float:!0};function _t(u){if(gt[u])return u;const e=navigator.gpu.getPreferredCanvasFormat();return B(`[WebGPU] CanvasSource format '${u}' is not a valid GPUCanvasContext format. Falling back to '${e}'. Allowed formats are: bgra8unorm, rgba8unorm, rgba16float.`),e}class bt{constructor(){this._activePass=null}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this),e.runners.destroy.add(this)}contextChange(){this._msaaRestore=null}destroy(){this._msaaRestore=null}copyToTexture(e,t,r,s,i){const n=this._renderer;this.finishRenderPass();const a=this._getGpuColorTexture(e),o=n.texture.getGpuSource(t.source);return n.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:r},{texture:o,origin:i},s),t}copyDepthTexture(e,t,r,s,i){const n=this._renderer;this.finishRenderPass();const a=e.depthStencilAttachment.texture,o=n.texture.getGpuSource(a),c=n.texture.getGpuSource(t.source),l=n.encoder.commandEncoder===null,h=l?n.gpu.device.createCommandEncoder():n.encoder.commandEncoder;h.copyTextureToTexture({texture:o,origin:r},{texture:c,origin:i},{width:s.width,height:s.height}),l&&n.gpu.device.queue.submit([h.finish()])}startRenderPass(e,t=!0,r,s,i=0,n=0){var b,y;const o=this._renderTargetSystem.getGpuRenderTarget(e);if(n!==0&&((b=o.msaaTextures)!=null&&b.length))throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(i>0&&((y=o.msaaTextures)!=null&&y.length))throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");let c=t;typeof c=="boolean"&&(c=c?S.ALL:S.NONE),(e.stencil||e.depth)&&!e.depthStencilAttachment&&e.ensureDepthStencilTexture();const l=!!e.depthStencilAttachment,h=this._activePass,d=h!==null&&h.renderTarget===e&&h.mipLevel===i&&h.layer===n&&h.depthStencil===l&&this._renderer.encoder.renderPassEncoder!==null&&c===S.NONE;if(this._renderer.pipeline.setRenderTarget(e),d){this._renderer.encoder.setViewport(s);return}const{descriptor:m,restore:p}=this._buildDescriptor(e,t,r,i,n);o.descriptor=m;const f=this._renderer.encoder;p?(f.endRenderPass(),this._beginRestoredPass(e,p,f.commandEncoder,()=>f.beginRenderPass(o))):f.beginRenderPass(o),f.setViewport(s),this._activePass={renderTarget:e,mipLevel:i,layer:n,depthStencil:l}}finishRenderPass(){this._renderer.encoder.endRenderPass(),this._activePass=null}_beginRestoredPass(e,t,r,s){const i=this._msaaRestore??(this._msaaRestore=new ft(this._renderer));for(const a of t)i.copy(r,e,a,this._getGpuColorTexture(e,a));const n=s();for(const a of t)i.draw(n,e,a);return n}_getGpuColorTexture(e,t=0){if(e.colorAttachments.length===0)throw new Error("[GpuRenderTargetAdaptor] cannot get gpu color texture from a depth-only render target");const r=e.colorAttachments[t].texture;return r instanceof L&&r._gpuContext?r._gpuContext.getCurrentTexture():this._renderer.texture.getGpuSource(r)}getDescriptor(e,t,r,s=0,i=0){return this._buildDescriptor(e,t,r,s,i).descriptor}_buildDescriptor(e,t,r,s=0,i=0){let n=null;typeof t=="boolean"&&(t=t?S.ALL:S.NONE);const a=this._renderTargetSystem,o=a.getGpuRenderTarget(e),c=e.colorAttachments.map((d,m)=>{const p=d.texture,f=p instanceof L?p._gpuContext:null;let b,y,C=!1;if(f){if(i!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");const G=f.getCurrentTexture();C=o.canvasTextures[m]!==G,o.canvasTextures[m]=G,b=G.createView(d.viewDescriptor)}else b=this._renderer.texture.getTextureRenderTargetView(d.texture,s,i,d.viewDescriptor);const _=o.msaaTextures[m];_&&(y=b,b=this._renderer.texture.getTextureView(_));let w=d.loadOp;t!==void 0&&(w=t&S.COLOR?"clear":"load"),r??(r=a.defaultClearColor);const z=!!(_!=null&&_.transient),O=z&&w!=="clear",Le=O&&!C;O&&(w="clear",Le&&(n??(n=[])).push(m));const R={view:b,resolveTarget:y,storeOp:z?"discard":d.storeOp??"store",loadOp:w};p.dimension==="3d"&&(R.depthSlice=i),O?R.clearValue=[0,0,0,0]:w==="clear"&&(r??(r=d.clearValue??a.defaultClearColor),R.clearValue=r);for(const G in d)G!=="texture"&&G!=="viewDescriptor"&&G!=="clearValue"&&G!=="loadOp"&&G!=="storeOp"&&(R[G]=d[G]);return R});let l;if(e.depthStencilAttachment){this._prepareDepthStencil(e,o);const d=e.depthStencilAttachment,m=d.texture.format.includes("stencil"),p=d.texture.format.includes("depth"),f=o.transient?"discard":"store",b=o.transient?"clear":"load";l={view:this._renderer.texture.getTextureRenderTargetView(d.texture,s,i,d.viewDescriptor)};const y=d.depthReadOnly??!1,C=d.stencilReadOnly??y;m&&!C?(l.stencilLoadOp=t&S.STENCIL?"clear":d.stencilLoadOp??b,l.stencilStoreOp=d.stencilStoreOp??f,l.stencilLoadOp==="clear"&&(l.stencilClearValue=d.stencilClearValue??0)):m&&C&&(l.stencilReadOnly=!0),p&&!y?(l.depthLoadOp=t&S.DEPTH?"clear":d.depthLoadOp??b,l.depthStoreOp=d.depthStoreOp??f,l.depthLoadOp==="clear"&&(l.depthClearValue=d.depthClearValue??1)):p&&y&&(l.depthReadOnly=!0);for(const _ in d)_!=="texture"&&_!=="viewDescriptor"&&_!=="stencilLoadOp"&&_!=="stencilStoreOp"&&_!=="stencilClearValue"&&_!=="stencilReadOnly"&&_!=="depthLoadOp"&&_!=="depthStoreOp"&&_!=="depthClearValue"&&_!=="depthReadOnly"&&(l[_]=d[_])}return{descriptor:{colorAttachments:c,depthStencilAttachment:l,label:e.label},restore:n}}clear(e,t=!0,r,s,i=0,n=0){if(!t)return;const{gpu:a,encoder:o}=this._renderer,c=a.device;if(o.commandEncoder===null){const h=c.createCommandEncoder(),{descriptor:d,restore:m}=this._buildDescriptor(e,t,r,i,n),p=()=>h.beginRenderPass(d),f=m?this._beginRestoredPass(e,m,h,p):p();f.setViewport(s.x,s.y,s.width,s.height,0,1),f.end();const b=h.finish();c.queue.submit([b])}else this.startRenderPass(e,t,r,s,i,n)}initGpuRenderTarget(e){var r;e.isRoot=!0;const t=new mt;return t.transient=!!((r=e.colorTexture)!=null&&r.antialias)&&!!e.colorTexture.transient,e.colorAttachments.forEach((s,i)=>{const n=s.texture;if(n instanceof L){const a=n._gpuContext??(n._gpuContext=n.resource.getContext("webgpu")),o=n.transparent?"premultiplied":"opaque",c=_t(n.format);try{a.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:c,alphaMode:o,...c==="rgba16float"?{toneMapping:{mode:"extended"}}:{}})}catch(l){console.error(l)}t.contexts[i]=a}if(t.msaa=n.source.antialias,n.antialias){const a=new ne({width:0,height:0,sampleCount:4,autoGenerateMipmaps:!1,transient:this._renderer.device.extensions.tileBased||t.transient,arrayLayerCount:n.arrayLayerCount,format:n.format});t.msaaTextures[i]=a}}),t.msaa&&(t.msaaSamples=4),t}_prepareDepthStencil(e,t){var s;const r=(s=e.depthStencilAttachment)==null?void 0:s.texture;!r||!t.msaa||(r.sampleCount=4,r.transient=t.transient)}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaBackTextures.forEach(t=>{t==null||t.destroy()}),e.msaaTextures.length=0,e.msaaBackTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){this._prepareDepthStencil(e,this._renderTargetSystem.getGpuRenderTarget(e))}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorAttachments.forEach((r,s)=>{var n,a;const i=r.texture;(n=t.msaaTextures[s])==null||n.resize(i.width,i.height,i._resolution),(a=t.msaaBackTextures[s])==null||a.resize(i.width,i.height,i._resolution)})}}class Ge extends Je{constructor(e){super(e),this.adaptor=new bt,this.adaptor.init(e,this)}}Ge.extension={type:[g.WebGPUSystem],name:"renderTarget"};class Se{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e,this._gpuProgramData=Object.create(null)}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,r=e.gpuLayout.map(i=>t.createBindGroupLayout({entries:i})),s={bindGroupLayouts:r};return this._gpuProgramData[e._layoutKey]={bindGroups:r,pipeline:t.createPipelineLayout(s)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Se.extension={type:[g.WebGPUSystem],name:"shader"};const x={};x.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};x.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}};x.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}};x.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};x.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};x.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}};x["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}};x["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}};x["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}};x.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}};x.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}};x.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class ve{constructor(){this.defaultState=new re,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t,r){const s=e.blend?x[e.blendMode]||x.normal:void 0,i=[];for(let n=0;n<t;n++)i[n]={format:r,writeMask:0,blend:s};return i}destroy(){this.gpu=null}}ve.extension={type:[g.WebGPUSystem],name:"state"};const Z=[new F,new F,new F],yt={type:"image",upload(u,e,t,r=0){const s=u.resource,i=u.pixelWidth|0,n=u.pixelHeight|0,a=u.depthOrArrayLayers,o=s.byteLength/(i*n*a);if(a>1){t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:r}},s,{offset:0,rowsPerImage:n,bytesPerRow:i*o},{width:i,height:n,depthOrArrayLayers:a});return}const c=qe(u._updateStart,u._updateEnd,i,n,Z);for(let l=0;l<c;l++){const h=Z[l];t.device.queue.writeTexture({texture:e,origin:{x:h.x,y:h.y,z:r}},s,{offset:(h.y*i+h.x)*o,rowsPerImage:h.height,bytesPerRow:i*o},{width:h.width,height:h.height,depthOrArrayLayers:1})}}},Pe={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},xt={blockBytes:4,blockWidth:1,blockHeight:1},Gt={type:"compressed",upload(u,e,t,r=0){let s=u.pixelWidth,i=u.pixelHeight;const n=Pe[u.format]||xt;for(let a=0;a<u.resource.length;a++){const o=u.resource[a],c=Math.ceil(s/n.blockWidth)*n.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:a,origin:{x:0,y:0,z:r}},o,{offset:0,bytesPerRow:c},{width:Math.ceil(s/n.blockWidth)*n.blockWidth,height:Math.ceil(i/n.blockHeight)*n.blockHeight,depthOrArrayLayers:1}),s=Math.max(s>>1,1),i=Math.max(i>>1,1)}}},J=["right","left","top","bottom","front","back"];function St(u){return{type:"cube",upload(e,t,r){const s=e.faces;for(let i=0;i<J.length;i++){const n=J[i],a=s[n];(u[a.uploadMethodId]||u.image).upload(a,t,r,i)}}}}const Be={type:"image",upload(u,e,t,r=0){const s=u.resource;if(!s)return;if(globalThis.HTMLImageElement&&s instanceof HTMLImageElement){const o=E.get().createCanvas(s.width,s.height);o.getContext("2d").drawImage(s,0,0,s.width,s.height),u.resource=o,B("ImageSource: Image element passed, converting to canvas and replacing resource.")}const i=Math.min(e.width,u.resourceWidth||u.pixelWidth),n=Math.min(e.height,u.resourceHeight||u.pixelHeight),a=u.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:s},{texture:e,origin:{x:0,y:0,z:r},premultipliedAlpha:a},{width:i,height:n})}},vt={type:"video",upload(u,e,t,r){Be.upload(u,e,t,r)}},Q=["rgba8unorm","rgba16float"],P=4;function Te(u,e){if(!e)throw new Error("[Gpu3dMipmapGenerator] generating mipmaps for a 3D texture needs storage: true.");if(!Q.includes(u))throw new Error(`[Gpu3dMipmapGenerator] format '${u}' can't be downsampled. Use ${Q.join(", ")}.`)}class Pt{constructor(e){this._pipelines={},this._device=e,this._sampler=e.createSampler({magFilter:"linear",minFilter:"linear"})}_getMipmapPipeline(e){var t;return(t=this._pipelines)[e]??(t[e]=this._device.createComputePipeline({layout:"auto",compute:{module:this._device.createShaderModule({code:`
33
+ @group(0) @binding(0) var srcSampler : sampler;
34
+ @group(0) @binding(1) var src : texture_3d<f32>;
35
+ @group(0) @binding(2) var dst : texture_storage_3d<${e}, write>;
36
+
37
+ @compute @workgroup_size(${P}, ${P}, ${P})
38
+ fn main(@builtin(global_invocation_id) gid : vec3<u32>) {
39
+ let dstSize = textureDimensions(dst);
40
+
41
+ if (gid.x >= dstSize.x || gid.y >= dstSize.y || gid.z >= dstSize.z) {
42
+ return;
43
+ }
44
+
45
+ // centre of the 2x2x2 footprint in the previous mip. When a dimension is
46
+ // odd its last texel, row or slice is never sampled, as in the 2D generator
47
+ let uv = (vec3<f32>(gid) * 2.0 + 1.0) / vec3<f32>(textureDimensions(src));
48
+
49
+ textureStore(dst, gid, textureSampleLevel(src, srcSampler, uv, 0.0));
50
+ }
51
+ `}),entryPoint:"main"}})),this._pipelines[e]}generateMipmap(e){if(e.dimension!=="3d")throw new Error("[Gpu3dMipmapGenerator] generateMipmap expects a 3D texture.");if(e.mipLevelCount<2)return;Te(e.format,(e.usage&GPUTextureUsage.STORAGE_BINDING)!==0);const t=this._getMipmapPipeline(e.format),r=t.getBindGroupLayout(0),s=this._device.createCommandEncoder({label:"Gpu3dMipmapGenerator"}),i=s.beginComputePass();i.setPipeline(t);let n=e.width,a=e.height,o=e.depthOrArrayLayers,c=e.createView({dimension:"3d",baseMipLevel:0,mipLevelCount:1});for(let l=1;l<e.mipLevelCount;l++){n=Math.max(1,n>>1),a=Math.max(1,a>>1),o=Math.max(1,o>>1);const h=e.createView({dimension:"3d",baseMipLevel:l,mipLevelCount:1});i.setBindGroup(0,this._device.createBindGroup({layout:r,entries:[{binding:0,resource:this._sampler},{binding:1,resource:c},{binding:2,resource:h}]})),i.dispatchWorkgroups(Math.ceil(n/P),Math.ceil(a/P),Math.ceil(o/P)),c=h}i.end(),this._device.queue.submit([s.finish()])}}class Bt{constructor(e){this._pipelines={},this._device=e,this._sampler=e.createSampler({minFilter:"linear"})}_getMipmapPipeline(e){let t=this._pipelines[e];return t||(this._mipmapShaderModule||(this._mipmapShaderModule=this._device.createShaderModule({code:`
52
+ var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
53
+ vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
54
+
55
+ struct VertexOutput {
56
+ @builtin(position) position : vec4<f32>,
57
+ @location(0) texCoord : vec2<f32>,
58
+ };
59
+
60
+ @vertex
61
+ fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
62
+ var output : VertexOutput;
63
+ output.texCoord = pos[vertexIndex] * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);
64
+ output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
65
+ return output;
66
+ }
67
+
68
+ @group(0) @binding(0) var imgSampler : sampler;
69
+ @group(0) @binding(1) var img : texture_2d<f32>;
70
+
71
+ @fragment
72
+ fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
73
+ return textureSample(img, imgSampler, texCoord);
74
+ }
75
+ `})),t=this._device.createRenderPipeline({layout:"auto",vertex:{module:this._mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this._mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this._pipelines[e]=t),t}generateMipmap(e){if(e.dimension==="3d")throw new Error("[GpuMipmapGenerator] a 3D texture uses Gpu3dMipmapGenerator.");if(e.dimension==="1d")throw new Error("Generating mipmaps for 1d textures is currently unsupported!");const t=this._getMipmapPipeline(e.format);let r=e;const s=e.depthOrArrayLayers||1,i=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!i){const o={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:s},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};r=this._device.createTexture(o)}const n=this._device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let o=0;o<s;++o){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:o,arrayLayerCount:1}),l=i?1:0;for(let h=1;h<e.mipLevelCount;++h){const d=r.createView({baseMipLevel:l++,mipLevelCount:1,dimension:"2d",baseArrayLayer:o,arrayLayerCount:1}),m=n.beginRenderPass({colorAttachments:[{view:d,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),p=this._device.createBindGroup({layout:a,entries:[{binding:0,resource:this._sampler},{binding:1,resource:c}]});m.setPipeline(t),m.setBindGroup(0,p),m.draw(3,1,0,0),m.end(),c=d}}if(!i){const o={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:s};for(let c=1;c<e.mipLevelCount;++c)n.copyTextureToTexture({texture:r,mipLevel:c-1},{texture:e,mipLevel:c},o),o.width=Math.ceil(o.width/2),o.height=Math.ceil(o.height/2)}return this._device.queue.submit([n.finish()]),i||r.destroy(),e}}class Tt{constructor(e){this.textureView=null,this.textureViews=Object.create(null),this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.textureViews=null,this.gpuTexture=null}}const Ct=/^(rgba8|bgra8|bc[1237]-rgba-|etc2-rgb8|etc2-rgb8a1|etc2-rgba8|astc-\d+x\d+-)unorm$/;function wt(u){return Ct.test(u)?[`${u}-srgb`]:void 0}function ee(u){return`${u.format||""}.${u.dimension||""}.${u.aspect||""}.${u.baseMipLevel||0}.${u.mipLevelCount||""}.${u.baseArrayLayer||0}.${u.arrayLayerCount||""}`}const I=class Ce{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new se({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Be,buffer:yt,video:vt,compressed:Gt,...Ce.uploadExtensions};this._uploads={...t,cube:St(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e,this._managedTextures.removeAll(),this._gpuSamplers=Object.create(null),this._mipmapGenerator=null,this._mipmap3dGenerator=null}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){e.dimension==="3d"&&Te(e.format,e.storage);const l=Math.max(e.pixelWidth,e.pixelHeight,e.depth);e.mipLevelCount=Math.floor(Math.log2(l))+1}let t,r;e.sampleCount>1?(t=GPUTextureUsage.RENDER_ATTACHMENT,e.transient&&this._renderer.device.extensions.transientAttachment&&(t|=GPUTextureUsage.TRANSIENT_ATTACHMENT)):(t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC),e.storage&&(t|=GPUTextureUsage.STORAGE_BINDING),r=wt(e.format));const s=Pe[e.format]||{blockWidth:1,blockHeight:1},i=Math.ceil(e.pixelWidth/s.blockWidth)*s.blockWidth,n=Math.ceil(e.pixelHeight/s.blockHeight)*s.blockHeight,a={label:e.label,size:{width:i,height:n,depthOrArrayLayers:e.depthOrArrayLayers},format:e.format,viewFormats:r,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},o=this._gpu.device.createTexture(a);return e._gpuData[this._renderer.uid]=new Tt(o),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),o}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){const t=this.getGpuSource(e);if(e.dimension==="3d"){this._mipmap3dGenerator??(this._mipmap3dGenerator=new Pt(this._gpu.device)),this._mipmap3dGenerator.generateMipmap(t);return}this._mipmapGenerator??(this._mipmapGenerator=new Bt(this._gpu.device)),this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],r=t==null?void 0:t.gpuTexture;r?(r.width!==e.pixelWidth||r.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new ie({0:t,1:t.style,2:new ae({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e,t){var r;const s=e.source;s._gcLastUsed=this._renderer.gc.now;let i=s._gpuData[this._renderer.uid];i||(this.initSource(s),i=s._gpuData[this._renderer.uid]);const n=t?ee(t):0;return(r=i.textureViews)[n]||(r[n]=i.gpuTexture.createView({dimension:s.viewDimension,...t})),i.textureViews[n]}getTextureRenderTargetView(e,t=0,r=0,s){var i;const n=e.source;n._gcLastUsed=this._renderer.gc.now;let a=n._gpuData[this._renderer.uid];a||(this.initSource(n),a=n._gpuData[this._renderer.uid]);const o=n.dimension==="3d";o&&(r=0);let c=r*(n.mipLevelCount||1)+t+1;return s&&(c=`${c}.${ee(s)}`),(i=a.textureViews)[c]||(i[c]=a.gpuTexture.createView({dimension:o?"3d":"2d",baseMipLevel:t,mipLevelCount:1,baseArrayLayer:r,arrayLayerCount:1,...s})),a.textureViews[c]}generateCanvas(e){const t=this._renderer,r=t.gpu.device.createCommandEncoder(),s=E.get().createCanvas();s.width=e.source.pixelWidth,s.height=e.source.pixelHeight;const i=s.getContext("webgpu");return i.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:E.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),r.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:i.getCurrentTexture()},{width:s.width,height:s.height}),t.gpu.device.queue.submit([r.finish()]),s}getPixels(e){const t=this.generateCanvas(e),r=H.getOptimalCanvasAndContext(t.width,t.height),s=r.context;s.drawImage(t,0,0);const{width:i,height:n}=t,a=s.getImageData(0,0,i,n),o=new Uint8ClampedArray(a.data.buffer);return H.returnCanvasAndContext(r),{pixels:o,width:i,height:n}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),r=this._bindGroupHash[t];r==null||r.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._mipmap3dGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}};I.extension={type:[g.WebGPUSystem],name:"texture"};I.uploadExtensions=Object.create(null);let we=I;T.handleByMap(g.TextureUploaderWebGPU,we.uploadExtensions);class Re{constructor(){this._maxTextures=0}contextChange(e){const t=new ae({uTransformMatrix:{value:new oe,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const r=ue({name:"graphics",bits:[Ie,ze(this._maxTextures),Ye,ce]});this.shader=new de({gpuProgram:r,resources:{localUniforms:t}})}execute(e,t){const r=t.context,s=r.customShader||this.shader,i=e.renderer,n=i.graphicsContext,{batcher:a,instructions:o}=n.getContextRenderData(r),c=i.encoder;c.setGeometry(a.geometry,s.gpuProgram);const l=i.globalUniforms.bindGroup;c.setBindGroup(0,l,s.gpuProgram);const h=i.renderPipes.uniformBatch.getUniformBindGroup(s.resources.localUniforms,!0);c.setBindGroup(2,h,s.gpuProgram);const d=o.instructions;let m=null;for(let p=0;p<o.instructionSize;p++){const f=d[p];if(f.topology!==m&&(m=f.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,s.gpuProgram,e.state,f.topology,s._overrides)),s.groups[1]=f.bindGroup,!f.gpuBindGroup){const b=f.textures;f.bindGroup=te(b.textures,b.count,this._maxTextures),f.gpuBindGroup=i.bindGroup.getBindGroup(f.bindGroup,s.gpuProgram,1)}c.setBindGroup(1,f.bindGroup,s.gpuProgram),c.renderPassEncoder.drawIndexed(f.size,1,f.start)}}destroy(){this.shader.destroy(),this.shader=null}}Re.extension={type:[g.WebGPUPipesAdaptor],name:"graphics"};class Me{init(){const e=ue({name:"mesh",bits:[Xe,Ze,ce]});this._shader=new de({gpuProgram:e,resources:{uTexture:V.EMPTY._source,uSampler:V.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new oe}}}})}execute(e,t){const r=e.renderer;let s=t._shader;if(!s)s=this._shader,s.groups[2]=r.texture.getTextureBindGroup(t.texture);else if(!s.gpuProgram){B("Mesh shader has no gpuProgram",t.shader);return}const i=s.gpuProgram;if(i.autoAssignGlobalUniforms&&(s.groups[0]=r.globalUniforms.bindGroup),i.autoAssignLocalUniforms){const n=e.localUniforms;s.groups[1]=r.renderPipes.uniformBatch.getUniformBindGroup(n,!0)}r.encoder.draw({geometry:t._geometry,shader:s,state:t.state})}destroy(){this._shader.destroy(),this._shader=null}}Me.extension={type:[g.WebGPUPipesAdaptor],name:"mesh"};const Rt=[...Qe,be,me,k,ge,pe,we,Ge,Se,ve,xe,fe,_e,he],Mt=[...et,ye],Ut=[le,Me,Re],Ue=[],Ee=[],Oe=[],Ae=[];T.handleByNamedList(g.WebGPUSystem,Ue);T.handleByNamedList(g.WebGPUPipes,Ee);T.handleByNamedList(g.WebGPUPipesAdaptor,Oe);T.handleByNamedList(g.WebGPULoader,Ae);T.add(...Rt,...Mt,...Ut);class Dt extends We{constructor(){const e={name:"webgpu",type:Ve.WEBGPU,systems:Ue,renderPipes:Ee,renderPipeAdaptors:Oe,loaders:Ae};super(e)}}export{Dt as WebGPURenderer};