@babylonjs/viewer
Version:
The Babylon Viewer aims to simplify a specific but common Babylon.js use case: loading, viewing, and interacting with a 3D model.
3 lines • 213 kB
JavaScript
import{aO as e,C as t,cJ as r,A as s,y as n,cK as i,cL as a,cM as o,cN as u,cO as c,aS as h,cC as l,a7 as d,cP as p,cQ as _,cR as g,w as m,aY as f,cS as b,cj as x,ck as T,cT as y,cU as E,b1 as S,cV as R,cW as C,cX as A,cY as v,cZ as I,c_ as w,c$ as B,d0 as P,d1 as F,d2 as D,d3 as L}from"./index-OM-TXt9s.esm.min.js";import{a as M}from"./sphericalPolynomial.pure-DSMa8uz9.esm.min.js";class G{static ComputeNumMipmapLevels(t,r){return e(Math.max(t,r))+1}static GetTextureTypeFromFormat(e){switch(e){case"r8unorm":case"r8uint":case"rg8unorm":case"rg8uint":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8uint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb10a2uint":case"rgb10a2unorm":case"rgb9e5ufloat":case"rg11b10ufloat":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc5-rg-unorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc4-r-unorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-rg11unorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":case"stencil8":return t.TEXTURETYPE_UNSIGNED_BYTE;case"r8snorm":case"r8sint":case"rg8snorm":case"rg8sint":case"rgba8snorm":case"rgba8sint":case"bc6h-rgb-float":case"bc5-rg-snorm":case"bc4-r-snorm":case"eac-r11snorm":case"eac-rg11snorm":return t.TEXTURETYPE_BYTE;case"r16uint":case"r16unorm":case"rg16unorm":case"rgba16unorm":case"rg16uint":case"rgba16uint":case"depth16unorm":return t.TEXTURETYPE_UNSIGNED_SHORT;case"r16sint":case"r16snorm":case"rg16snorm":case"rgba16snorm":case"rg16sint":case"rgba16sint":return t.TEXTURETYPE_SHORT;case"r16float":case"rg16float":case"rgba16float":return t.TEXTURETYPE_HALF_FLOAT;case"r32uint":case"rg32uint":case"rgba32uint":case"r32sint":case"rg32sint":case"rgba32sint":return t.TEXTURETYPE_UNSIGNED_INTEGER;case"r32float":case"rg32float":case"rgba32float":case"depth32float":case"depth32float-stencil8":case"depth24plus":case"depth24plus-stencil8":return t.TEXTURETYPE_FLOAT}return t.TEXTURETYPE_UNSIGNED_BYTE}static GetBlockInformationFromFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return{width:1,height:1,length:1};case"r16uint":case"r16sint":case"r16unorm":case"r16snorm":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return{width:1,height:1,length:2};case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rg16unorm":case"rg16snorm":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2uint":case"rgb10a2unorm":case"rg11b10ufloat":case"depth32float":return{width:1,height:1,length:4};case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba16unorm":case"rgba16snorm":return{width:1,height:1,length:8};case"rgba32uint":case"rgba32sint":case"rgba32float":return{width:1,height:1,length:16};case"stencil8":throw"No fixed size for Stencil8 format!";case"depth24plus":throw"No fixed size for Depth24Plus format!";case"depth24plus-stencil8":throw"No fixed size for Depth24PlusStencil8 format!";case"depth32float-stencil8":return{width:1,height:1,length:5};case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"bc5-rg-unorm":case"bc5-rg-snorm":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":return{width:4,height:4,length:16};case"bc4-r-unorm":case"bc4-r-snorm":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":return{width:4,height:4,length:8};case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":return{width:5,height:4,length:16};case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":return{width:5,height:5,length:16};case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":return{width:6,height:5,length:16};case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":return{width:6,height:6,length:16};case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":return{width:8,height:5,length:16};case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":return{width:8,height:6,length:16};case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":return{width:8,height:8,length:16};case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":return{width:10,height:5,length:16};case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":return{width:10,height:6,length:16};case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":return{width:10,height:8,length:16};case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":return{width:10,height:10,length:16};case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":return{width:12,height:10,length:16};case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case"bc7-rgba-unorm-srgb":case"bc7-rgba-unorm":case"bc6h-rgb-float":case"bc6h-rgb-ufloat":case"bc5-rg-snorm":case"bc5-rg-unorm":case"bc4-r-snorm":case"bc4-r-unorm":case"bc3-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc1-rgba-unorm-srgb":case"bc1-rgba-unorm":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"eac-r11unorm":case"eac-r11snorm":case"eac-rg11unorm":case"eac-rg11snorm":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return!0}return!1}static GetWebGPUTextureFormat(e,r,s=!1){switch(r){case t.TEXTUREFORMAT_DEPTH16:return"depth16unorm";case t.TEXTUREFORMAT_DEPTH24:return"depth24plus";case t.TEXTUREFORMAT_DEPTH24_STENCIL8:return"depth24plus-stencil8";case t.TEXTUREFORMAT_DEPTH32_FLOAT:return"depth32float";case t.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8:return"depth32float-stencil8";case t.TEXTUREFORMAT_STENCIL8:return"stencil8";case t.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:return s?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT:return"bc6h-rgb-ufloat";case t.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT:return"bc6h-rgb-float";case t.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:return s?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3:return s?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:case t.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:return s?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:return s?"astc-4x4-unorm-srgb":"astc-4x4-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4:return s?"astc-5x4-unorm-srgb":"astc-5x4-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5:return s?"astc-5x5-unorm-srgb":"astc-5x5-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5:return s?"astc-6x5-unorm-srgb":"astc-6x5-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6:return s?"astc-6x6-unorm-srgb":"astc-6x6-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5:return s?"astc-8x5-unorm-srgb":"astc-8x5-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6:return s?"astc-8x6-unorm-srgb":"astc-8x6-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8:return s?"astc-8x8-unorm-srgb":"astc-8x8-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5:return s?"astc-10x5-unorm-srgb":"astc-10x5-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6:return s?"astc-10x6-unorm-srgb":"astc-10x6-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8:return s?"astc-10x8-unorm-srgb":"astc-10x8-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10:return s?"astc-10x10-unorm-srgb":"astc-10x10-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10:return s?"astc-12x10-unorm-srgb":"astc-12x10-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12:return s?"astc-12x12-unorm-srgb":"astc-12x12-unorm";case t.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:case t.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:return s?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";case t.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:return s?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm"}switch(e){case t.TEXTURETYPE_BYTE:switch(r){case t.TEXTUREFORMAT_RED:return"r8snorm";case t.TEXTUREFORMAT_RG:return"rg8snorm";case t.TEXTUREFORMAT_RGB:throw"RGB format not supported in WebGPU";case t.TEXTUREFORMAT_RED_INTEGER:return"r8sint";case t.TEXTUREFORMAT_RG_INTEGER:return"rg8sint";case t.TEXTUREFORMAT_RGB_INTEGER:throw"RGB_INTEGER format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA_INTEGER:return"rgba8sint";default:return"rgba8snorm"}case t.TEXTURETYPE_UNSIGNED_BYTE:switch(r){case t.TEXTUREFORMAT_RED:return"r8unorm";case t.TEXTUREFORMAT_RG:return"rg8unorm";case t.TEXTUREFORMAT_RGB:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA:return s?"rgba8unorm-srgb":"rgba8unorm";case t.TEXTUREFORMAT_BGRA:return s?"bgra8unorm-srgb":"bgra8unorm";case t.TEXTUREFORMAT_RED_INTEGER:return"r8uint";case t.TEXTUREFORMAT_RG_INTEGER:return"rg8uint";case t.TEXTUREFORMAT_RGB_INTEGER:throw"RGB_INTEGER format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA_INTEGER:return"rgba8uint";case t.TEXTUREFORMAT_ALPHA:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case t.TEXTUREFORMAT_LUMINANCE:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case t.TEXTUREFORMAT_LUMINANCE_ALPHA:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return"rgba8unorm"}case t.TEXTURETYPE_SHORT:switch(r){case t.TEXTUREFORMAT_RED_INTEGER:return"r16sint";case t.TEXTUREFORMAT_RG_INTEGER:return"rg16sint";case t.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA_INTEGER:default:return"rgba16sint"}case t.TEXTURETYPE_UNSIGNED_SHORT:switch(r){case t.TEXTUREFORMAT_RED_INTEGER:return"r16uint";case t.TEXTUREFORMAT_RG_INTEGER:return"rg16uint";case t.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA_INTEGER:default:return"rgba16uint"}case t.TEXTURETYPE_INT:switch(r){case t.TEXTUREFORMAT_RED_INTEGER:return"r32sint";case t.TEXTUREFORMAT_RG_INTEGER:return"rg32sint";case t.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA_INTEGER:default:return"rgba32sint"}case t.TEXTURETYPE_UNSIGNED_INTEGER:switch(r){case t.TEXTUREFORMAT_RED_INTEGER:return"r32uint";case t.TEXTUREFORMAT_RG_INTEGER:return"rg32uint";case t.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA_INTEGER:default:return"rgba32uint"}case t.TEXTURETYPE_FLOAT:switch(r){case t.TEXTUREFORMAT_RED:return"r32float";case t.TEXTUREFORMAT_RG:return"rg32float";case t.TEXTUREFORMAT_RGB:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA:default:return"rgba32float"}case t.TEXTURETYPE_HALF_FLOAT:switch(r){case t.TEXTUREFORMAT_RED:return"r16float";case t.TEXTUREFORMAT_RG:return"rg16float";case t.TEXTUREFORMAT_RGB:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case t.TEXTUREFORMAT_RGBA:default:return"rgba16float"}case t.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case t.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:switch(r){case t.TEXTUREFORMAT_RGBA:return"rg11b10ufloat";case t.TEXTUREFORMAT_RGBA_INTEGER:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return"rg11b10ufloat"}case t.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:switch(r){case t.TEXTUREFORMAT_RGBA:return"rgb9e5ufloat";case t.TEXTUREFORMAT_RGBA_INTEGER:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return"rgb9e5ufloat"}case t.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case t.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case t.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(r){case t.TEXTUREFORMAT_RGBA:return"rgb10a2unorm";case t.TEXTUREFORMAT_RGBA_INTEGER:return"rgb10a2uint";default:return"rgb10a2unorm"}}return s?"rgba8unorm-srgb":"rgba8unorm"}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":case"bc4-r-unorm":case"bc4-r-snorm":case"r16uint":case"r16sint":case"depth16unorm":case"r16float":case"r16unorm":case"r16snorm":case"r32uint":case"r32sint":case"r32float":case"depth32float":case"stencil8":case"depth24plus":case"eac-r11unorm":case"eac-r11snorm":return 1;case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth32float-stencil8":case"bc5-rg-unorm":case"bc5-rg-snorm":case"rg16uint":case"rg16sint":case"rg16float":case"rg16unorm":case"rg16snorm":case"rg32uint":case"rg32sint":case"rg32float":case"depth24plus-stencil8":case"eac-rg11unorm":case"eac-rg11snorm":return 2;case"rgb9e5ufloat":case"rg11b10ufloat":case"bc6h-rgb-ufloat":case"bc6h-rgb-float":case"etc2-rgb8unorm":case"etc2-rgb8unorm-srgb":return 3;case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgba16unorm":case"rgba16snorm":case"rgb10a2uint":case"rgb10a2unorm":case"bc7-rgba-unorm":case"bc7-rgba-unorm-srgb":case"bc3-rgba-unorm":case"bc3-rgba-unorm-srgb":case"bc2-rgba-unorm":case"bc2-rgba-unorm-srgb":case"bc1-rgba-unorm":case"bc1-rgba-unorm-srgb":case"rgba16uint":case"rgba16sint":case"rgba16float":case"rgba32uint":case"rgba32sint":case"rgba32float":case"etc2-rgb8a1unorm":case"etc2-rgb8a1unorm-srgb":case"etc2-rgba8unorm":case"etc2-rgba8unorm-srgb":case"astc-4x4-unorm":case"astc-4x4-unorm-srgb":case"astc-5x4-unorm":case"astc-5x4-unorm-srgb":case"astc-5x5-unorm":case"astc-5x5-unorm-srgb":case"astc-6x5-unorm":case"astc-6x5-unorm-srgb":case"astc-6x6-unorm":case"astc-6x6-unorm-srgb":case"astc-8x5-unorm":case"astc-8x5-unorm-srgb":case"astc-8x6-unorm":case"astc-8x6-unorm-srgb":case"astc-8x8-unorm":case"astc-8x8-unorm-srgb":case"astc-10x5-unorm":case"astc-10x5-unorm-srgb":case"astc-10x6-unorm":case"astc-10x6-unorm-srgb":case"astc-10x8-unorm":case"astc-10x8-unorm-srgb":case"astc-10x10-unorm":case"astc-10x10-unorm-srgb":case"astc-12x10-unorm":case"astc-12x10-unorm-srgb":case"astc-12x12-unorm":case"astc-12x12-unorm-srgb":return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case"stencil8":case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static HasDepthAspect(e){switch(e){case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case"depth32float-stencil8":case"depth24plus-stencil8":return!0}return!1}static GetDepthFormatOnly(e){switch(e){case"depth16unorm":return"depth16unorm";case"depth24plus":case"depth24plus-stencil8":return"depth24plus";case"depth32float":case"depth32float-stencil8":return"depth32float"}return e}static GetSample(e){return e>1?4:1}}class U{constructor(){this._gpuTimeInFrameId=-1,this.counter=new r}_addDuration(e,t){e<this._gpuTimeInFrameId||(this._gpuTimeInFrameId!==e?(this.counter._fetchResult(),this.counter.fetchNewFrame(),this.counter.addCount(t,!1),this._gpuTimeInFrameId=e):this.counter.addCount(t,!1))}}class O extends s{constructor(){super(...arguments),this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._currentRenderPass=null,this._snapshotRenderingMode=t.SNAPSHOTRENDERING_STANDARD,this._timestampIndex=0,this._showGPUDebugMarkersLog=!1,this._debugMarkersEncoderGroups=[],this._debugMarkersPassGroups=[],this._debugMarkersPendingEncoderPops=0}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new U:void 0,this._timestampQuery.enable=e)}_currentPassIsMainPass(){return null===this._currentRenderTarget}_endCurrentRenderPass(){if(!this._currentRenderPass)return 0;this._debugPopBeforeEndOfEncoder();const e=this._currentPassIsMainPass()?2:1;return this._snapshotRendering.endRenderPass(this._currentRenderPass)||this.compatibilityMode||(this._bundleList.run(this._currentRenderPass),this._bundleList.reset()),this._currentRenderPass.end(),this._timestampQuery.endPass(this._timestampIndex,this._currentRenderTarget&&this._currentRenderTarget.gpuTimeInFrame?this._currentRenderTarget.gpuTimeInFrame:this.gpuTimeInFrameForMainPass),this._timestampIndex+=2,this._debugPendingPop(this._currentRenderPass),this._currentRenderPass=null,e}_generateMipmaps(e,t){t=t??this._renderEncoder;const r=e._hardwareTexture;if(!r)return;t===this._renderEncoder&&this._endCurrentRenderPass();const s=G.ComputeNumMipmapLevels(e.width,e.height);e.isCube?this._textureHelper.generateCubeMipmaps(r,s,t):3===e._source||11===e._source?this._textureHelper.generateMipmaps(r,e.mipLevelCount,0,t):this._textureHelper.generateMipmaps(r,s,0,t)}_debugPopBeforeEndOfEncoder(){if(!this._enableGPUDebugMarkers)return;const e=this._currentRenderPass?this._debugMarkersPassGroups:this._debugMarkersEncoderGroups,t=this._currentRenderPass??this._renderEncoder;for(let r=e.length-1;r>=0;--r)this._showGPUDebugMarkersLog&&n.Log(`[${this.frameId}] [E${this._debugMarkersEncoderGroups.length}|P${this._debugMarkersPassGroups.length}] [automatic] Popping debug group '${e[r]}' on '${t.label}'.`),t.popDebugGroup()}_debugPushAfterStartOfEncoder(){if(!this._enableGPUDebugMarkers)return;const e=this._currentRenderPass?this._debugMarkersPassGroups:this._debugMarkersEncoderGroups,t=this._currentRenderPass??this._renderEncoder;for(const r of e)this._showGPUDebugMarkersLog&&n.Log(`[${this.frameId}] [E${this._debugMarkersEncoderGroups.length}|P${this._debugMarkersPassGroups.length}] [automatic] Pushing debug group '${r}' on '${t.label}'.`),t.pushDebugGroup(r)}_debugPendingPop(e){if(this._enableGPUDebugMarkers){for(;this._debugMarkersPendingEncoderPops-- >0;){const t=this._debugMarkersEncoderGroups.pop();this._showGPUDebugMarkersLog&&n.Log(`[${this.frameId}] [E${this._debugMarkersEncoderGroups.length}|P${this._debugMarkersPassGroups.length}] [automatic] Popping debug group '${t}' on render encoder '${this._renderEncoder.label}' after the end of render pass '${e.label}'.`),this._renderEncoder.popDebugGroup()}this._debugMarkersPendingEncoderPops=0}}}var N,$,W,V,k,X,H,q,Y,z,Q,K,j,J,Z,ee,te,re,se,ne,ie,ae,oe,ue,ce,he,le,de,pe,_e,ge,me,fe,be,xe,Te,ye,Ee,Se,Re,Ce;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(N||(N={})),function(e){e.CoreFeaturesAndLimits="core-features-and-limits",e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionBCSliced3D="texture-compression-bc-sliced-3d",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TextureCompressionASTCSliced3D="texture-compression-astc-sliced-3d",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable",e.Float32Blendable="float32-blendable",e.ClipDistances="clip-distances",e.DualSourceBlending="dual-source-blending",e.Subgroups="subgroups",e.TextureFormatsTier1="texture-formats-tier1",e.TextureFormatsTier2="texture-formats-tier2",e.PrimitiveIndex="primitive-index",e.TextureComponentSwizzle="texture-component-swizzle"}($||($={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(W||(W={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(V||(V={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(k||(k={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(X||(X={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment",e[e.TransientAttachment=32]="TransientAttachment"}(H||(H={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(q||(q={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(Y||(Y={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R16Unorm="r16unorm",e.R16Snorm="r16snorm",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RG16Unorm="rg16unorm",e.RG16Snorm="rg16snorm",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA16Unorm="rgba16unorm",e.RGBA16Snorm="rgba16snorm",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(z||(z={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(Q||(Q={})),function(e){e.Nearest="nearest",e.Linear="linear"}(K||(K={})),function(e){e.Nearest="nearest",e.Linear="linear"}(j||(j={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(J||(J={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(Z||(Z={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(ee||(ee={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(te||(te={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(re||(re={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(se||(se={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(ne||(ne={})),function(e){e.Validation="validation",e.Internal="internal"}(ie||(ie={})),function(e){e.Auto="auto"}(ae||(ae={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(oe||(oe={})),function(e){e.CCW="ccw",e.CW="cw"}(ue||(ue={})),function(e){e.None="none",e.Front="front",e.Back="back"}(ce||(ce={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(he||(he={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant",e.Src1="src1",e.OneMinusSrc1="one-minus-src1",e.Src1Alpha="src1-alpha",e.OneMinusSrc1Alpha="one-minus-src1-alpha"}(le||(le={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(de||(de={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(pe||(pe={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(_e||(_e={})),function(e){e.Uint8="uint8",e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8="sint8",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8="unorm8",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8="snorm8",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16="uint16",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16="sint16",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16="unorm16",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16="snorm16",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16="float16",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2",e.UNORM8x4BGRA="unorm8x4-bgra"}(ge||(ge={})),function(e){e.Vertex="vertex",e.Instance="instance"}(me||(me={})),function(e){e.Beginning="beginning",e.End="end"}(fe||(fe={})),function(e){e.Beginning="beginning",e.End="end"}(be||(be={})),function(e){e.Load="load",e.Clear="clear"}(xe||(xe={})),function(e){e.Store="store",e.Discard="discard"}(Te||(Te={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(ye||(ye={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Ee||(Ee={})),function(e){e.Standard="standard",e.Extended="extended"}(Se||(Se={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Re||(Re={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Ce||(Ce={}));class Ae{constructor(){this.shaderLanguage=0}_addUniformToLeftOverUBO(e,t,r){let s;[e,t,s]=this._getArraySize(e,t,r);for(let t=0;t<this._webgpuProcessingContext.leftOverUniforms.length;t++)if(this._webgpuProcessingContext.leftOverUniforms[t].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:s})}_buildLeftOverUBO(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";const e=Ae.LeftOvertUBOName;let t=this._webgpuProcessingContext.availableBuffers[e];return t||(t={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[e]=t,this._addBufferBindingDescription(e,t,"uniform",!0),this._addBufferBindingDescription(e,t,"uniform",!1)),this._generateLeftOverUBOCode(e,t)}_collectBindingNames(){for(let e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(void 0!==t)for(let r=0;r<t.length;r++){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[e][r],s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].name,n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].nameInArrayOfTexture;t&&(t.texture||t.externalTexture||t.storageTexture?this._webgpuProcessingContext.textureNames.push(n):t.sampler?this._webgpuProcessingContext.samplerNames.push(s):t.buffer&&this._webgpuProcessingContext.bufferNames.push(s))}else this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[]}}_preCreateBindGroupEntries(){const e=this._webgpuProcessingContext.bindGroupEntries;for(let t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){const r=this._webgpuProcessingContext.bindGroupLayoutEntries[t],s=[];for(let e=0;e<r.length;e++){const r=this._webgpuProcessingContext.bindGroupLayoutEntries[t][e];r.sampler||r.texture||r.storageTexture||r.externalTexture?s.push({binding:r.binding,resource:void 0}):r.buffer&&s.push({binding:r.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=s}}_addTextureBindingDescription(e,t,r,s,n,i,a="write-only"){let{groupIndex:o,bindingIndex:u}=t.textures[r];if(this._webgpuProcessingContext.bindGroupLayoutEntries[o]||(this._webgpuProcessingContext.bindGroupLayoutEntries[o]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][u]){let i;i=null===s?this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:u,visibility:0,externalTexture:{}}):n?this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:u,visibility:0,storageTexture:{access:a,format:n,viewDimension:s}}):this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:u,visibility:0,texture:{sampleType:t.sampleType,viewDimension:s,multisampled:!1}});const c=t.isTextureArray?e+r:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][u]={name:e,index:i-1,nameInArrayOfTexture:c}}u=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][u].index,this._webgpuProcessingContext.bindGroupLayoutEntries[o][u].visibility|=i?1:2}_addSamplerBindingDescription(e,t,r){let{groupIndex:s,bindingIndex:n}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n]){const r=this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:n,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n]={name:e,index:r-1}}n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n].index,this._webgpuProcessingContext.bindGroupLayoutEntries[s][n].visibility|=r?1:2}_addBufferBindingDescription(e,t,r,s){let{groupIndex:n,bindingIndex:i}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[n]||(this._webgpuProcessingContext.bindGroupLayoutEntries[n]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][i]){const t=this._webgpuProcessingContext.bindGroupLayoutEntries[n].push({binding:i,visibility:0,buffer:{type:r}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][i]={name:e,index:t-1}}i=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][i].index,this._webgpuProcessingContext.bindGroupLayoutEntries[n][i].visibility|=s?1:2}}Ae.LeftOvertUBOName="LeftOver",Ae.InternalsUBOName="Internals",Ae.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,uvec2:2,vec3:3,ivec3:3,uvec3:3,vec4:4,ivec4:4,uvec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16,mat2x2f:4,mat3x3f:12,mat4x4f:16,vec2i:2,vec3i:3,vec4i:4,vec2u:2,vec3u:3,vec4u:4,vec2f:2,vec3f:3,vec4f:4,vec2h:1,vec3h:2,vec4h:2},Ae._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},Ae._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},Ae._GpuTextureViewDimensionByWebGPUTextureType={textureCube:"cube",textureCubeArray:"cube-array",texture2D:"2d",texture2DArray:"2d-array",texture3D:"3d"},Ae._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},Ae._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1};class ve{get isAsync(){return!1}get isReady(){return!!this.stages}constructor(e,t){this.bindGroupLayouts={},this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t,this.vertexBufferKindToType={}}_handlesSpectorRebuildCallback(){}_fillEffectInformation(e,t,r,s,n,i,a,o){const u=this.engine;u._doNotHandleContextLost&&(e._fragmentSourceCode="",e._vertexSourceCode="");const c=this.shaderProcessingContext.availableTextures;let h;for(h=0;h<n.length;h++){const e=n[h],t=c[n[h]];null==t||null==t?(n.splice(h,1),h--):i[e]=h}for(const e of u.getAttributes(this,a))o.push(e);this.buildUniformLayout();const l=[],d=[];for(h=0;h<a.length;h++){const e=o[h];e>=0&&(l.push(a[h]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=l,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer?.dispose(),this.uniformBuffer=new i(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),r=Ae.UniformSizes[t];this.uniformBuffer.addUniform(e.name,r,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,r)}setInt3(e,t,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,r,s)}setInt4(e,t,r,s,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,r,s,n)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,r)}setUInt3(e,t,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,r,s)}setUInt4(e,t,r,s,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,r,s,n)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,r)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,r,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,r,s,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,r,s,n)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,r){this.setFloat4(e,t.r,t.g,t.b,r)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const Ie={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class we{static get KnownUBOs(){return we._SimplifiedKnownBindings?we._SimplifiedKnownUBOs:we._KnownUBOs}constructor(e,t=!1){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],t||this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=we.KnownUBOs,t=[];for(const r in e){const s=e[r].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const r=this._attributeNextLocation;return this._attributeNextLocation+=(Ie[e]??1)*(t||1),r}getVaryingNextLocation(e,t=0){const r=this._varyingNextLocation;return this._varyingNextLocation+=(Ie[e]??1)*(t||1),r}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}function Be(e,t,r,s){let n=s,i=0,a="";for(;n<r.length;){const s=r.charAt(n);if(a)s===a?'"'===a||"'"===a?"\\"!==r.charAt(n-1)&&(a=""):a="":"*/"===a&&"*"===s&&n+1<r.length&&("/"===r.charAt(n+1)&&(a=""),""===a&&n++);else switch(s){case e:i++;break;case t:i--;break;case'"':case"'":case"`":a=s;break;case"/":if(n+1<r.length){const e=r.charAt(n+1);"/"===e?a="\n":"*"===e&&(a="*/")}}if(n++,0===i)break}return 0===i?n-1:-1}function Pe(e,t){for(;t<e.length;){const r=e[t];if(" "!==r&&"\n"!==r&&"\r"!==r&&"\t"!==r&&"\n"!==r&&" "!==r)break;t++}return t}function Fe(e){const t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function De(e){let t=0,r="",s=!1;const n=[];for(;t<e.length;){const i=e.charAt(t);if(r)i===r?'"'===r||"'"===r?("\\"!==e.charAt(t-1)&&(r=""),n.push(i)):(r="",s=!1):"*/"===r&&"*"===i&&t+1<e.length?("/"===e.charAt(t+1)&&(r=""),""===r&&(s=!1,t++)):s||n.push(i);else{switch(i){case'"':case"'":case"`":r=i;break;case"/":if(t+1<e.length){const n=e.charAt(t+1);"/"===n?(r="\n",s=!0):"*"===n&&(r="*/",s=!0)}}s||n.push(i)}t++}return n.join("")}function Le(e,t,r,s){for(;t>=0&&e.charAt(t)!==r&&e.charAt(t)!==s;)t--;return t}function Me(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t,r,s){let n=e.indexOf(t);if(n<0)return e;if(r){for(;n++<e.length&&"{"!=e.charAt(n););if(n<e.length){const t=e.substring(0,n+1),s=e.substring(n+1);e=t+r+s}}if(s){const t=e.lastIndexOf("}");e=e.substring(0,t),e+=s+"\n}"}return e}we._SimplifiedKnownBindings=!0,we._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},we._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class Ue extends Ae{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=0,this.parseGLES3=!0}_getArraySize(e,t,r){let s=0;const n=e.indexOf("["),i=e.indexOf("]");if(n>0&&i>0){const t=e.substring(n+1,i);s=+t,isNaN(s)&&(s=+r[t.trim()]),e=e.substring(0,n)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const r=`// Internals UBO\nuniform ${Ae.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:r+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:r+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,r){this._preProcessors=r;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const i=s[1]??"",a=s[2],o=s[3];let u;t?(u=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[u]="",void 0===u&&n.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(u=this._webgpuProcessingContext.getVaryingNextLocation(a,this._getArraySize(o,a,r)[2]),this._webgpuProcessingContext.availableVaryings[o]=u,this._missingVaryings[u]=`layout(location = ${u}) ${i} in ${a} ${o};`),e=e.replace(s[0],void 0===u?"":`layout(location = ${u}) ${i} ${t?"in":"out"} ${a} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const r=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==r){const s=r[1],n=r[2],i=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(n,s,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=i,this._webgpuProcessingContext.orderedAttributes[i]=n;const a=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[n];if(void 0!==a){const t=a<0?-1===a?"int":"ivec"+-a:1===a?"uint":"uvec"+a,o=`_int_${n}_`;e=e.replace(r[0],`layout(location = ${i}) in ${t} ${o}; ${s} ${n} = ${s}(${o});`)}else e=e.replace(r[0],`layout(location = ${i}) in ${s} ${n};`)}return e}uniformProcessor(e,r,s){this._preProcessors=s;const n=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==n){let i=n[1],a=n[2];if(0===i.indexOf("sampler")||1===i.indexOf("sampler")){let n;[a,i,n]=this._getArraySize(a,i,s);let o=this._webgpuProcessingContext.availableTextures[a];if(!o){o={autoBindSampler:!0,isTextureArray:n>0,isStorageTexture:!1,textures:[],sampleType:"float"};for(let e=0;e<(n||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const u=Ae._SamplerTypeByWebGLSamplerType[i]??"sampler",c=!!Ae._IsComparisonSamplerByWebGPUSamplerType[u],h=c?"comparison":"filtering",l=a+t.AUTOSAMPLERSUFFIX;let d=this._webgpuProcessingContext.availableSamplers[l];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const p="u"===i.charAt(0)?"u":"i"===i.charAt(0)?"i":"";p&&(i=i.substring(1));const _=c?"depth":"u"===p?"uint":"i"===p?"sint":"float";o.sampleType=_;const g=n>0,m=d.binding.groupIndex,f=d.binding.bindingIndex,b=Ae._SamplerFunctionByWebGLSamplerType[i],x=Ae._TextureTypeByWebGLSamplerType[i],T=Ae._GpuTextureViewDimensionByWebGPUTextureType[x];if(g){const t=[];t.push(`layout(set = ${m}, binding = ${f}) uniform ${p}${u} ${l};`),e="\n";for(let r=0;r<n;++r){const s=o.textures[r].groupIndex,n=o.textures[r].bindingIndex;t.push(`layout(set = ${s}, binding = ${n}) uniform ${x} ${a}Texture${r};`),e+=`${r>0?"\n":""}#define ${a}${r} ${p}${b}(${a}Texture${r}, ${l})`}e=t.join("\n")+e,this._textureArrayProcessing.push(a)}else n=1,e=`layout(set = ${m}, binding = ${f}) uniform ${u} ${l};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${p}${x} ${a}Texture;\n #define ${a} ${p}${b}(${a}Texture, ${l})`;this._webgpuProcessingContext.availableTextures[a]=o,this._webgpuProcessingContext.availableSamplers[l]=d,this._addSamplerBindingDescription(l,d,!r);for(let e=0;e<n;++e)this._addTextureBindingDescription(a,o,e,T,null,!r)}else this._addUniformToLeftOverUBO(a,i,s),e=""}return e}uniformBufferProcessor(e,t){const r=/uniform\s+(\w+)/gm.exec(e);if(null!==r){const s=r[1];let n=this._webgpuProcessingContext.availableBuffers[s];if(!n){const e=we.KnownUBOs[s];let t;t=e&&-1!==e.binding.groupIndex?e.binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),n={binding:t},this._webgpuProcessingContext.availableBuffers[s]=n}this._addBufferBindingDescription(s,n,"uniform",!t),e=e.replace("uniform",`layout(set = ${n.binding.groupIndex}, binding = ${n.binding.bindingIndex}) uniform`)}return e}postProcessor(e,t,r,s,n,i){const a=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),r){const t=e.indexOf("gl_FragCoord")>=0,r="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",n=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(a||n?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=Ge(e,"void main",r))}else{"VERTEXOUTPUT_INVARIANT"in i&&(e="invariant gl_Position;\n"+e),e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex");if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!r){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const r=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=r.exec(e);for(;null!==s;){const n=s[1];let i=+n;this._preProcessors&&isNaN(i)&&(i=+this._preProcessors[n.trim()]),e=e.replace(s[0],t+i),s=r.exec(e)}return e}_generateLeftOverUBOCode(e,t){let r=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?r+=` ${e.type} ${e.name}[${e.length}];\n`:r+=` ${e.type} ${e.name};\n`;return r+="};\n\n",r}finalizeShaders(e,t){for(let r=0;r<this._textureArrayProcessing.length;++r){const s=this._textureArrayProcessing[r];e=this._applyTextureArrayProcessing(e,s),t=this._applyTextureArrayProcessing(t,s)}for(let e=0;e<this._missingVaryings.length;++e){const r=this._missingVaryings[e];r&&r.length>0&&(t=r+"\n"+t)}const r=this._buildLeftOverUBO();return e=r+e,t=r+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}const Oe="fragmentOutputs.fragDepth",Ne={texture_1d:"1d",texture_2d:"2d",texture_2d_array:"2d-array",texture_3d:"3d",texture_cube:"cube",texture_cube_array:"cube-array",texture_multisampled_2d:"2d",texture_depth_2d:"2d",texture_depth_2d_array:"2d-array",texture_depth_cube:"cube",texture_depth_cube_array:"cube-array",texture_depth_multisampled_2d:"2d",texture_storage_1d:"1d",texture_storage_2d:"2d",texture_storage_2d_array:"2d-array",texture_storage_3d:"3d",texture_external:null};class $e extends Ae{constructor(){super(...arguments),this.shaderLanguage=1,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0,this.pureMode=!1}_getArraySize(e,t,r){let s=0;const n=t.lastIndexOf(">");if(t.indexOf("array")>=0&&n>0){let e=n;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const i=t.substring(e+1,n);for(s=+i,isNaN(s)&&(s=+r[i.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=this.pureMode?"":`struct ${Ae.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar<uniform> internals : ${Ae.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+De(e)}varyingCheck(e){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,r){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const i=s[1]??"perspective",a=s[2]??"center",o=s[4],u=s[3],c="flat"===i?`@interpolate(${i})`:`@interpolate(${i}, ${a})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[u],void 0===h&&n.Warn(`Invalid fragment shader: The varying named "${u}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(u,o,r)[2]),this._webgpuProcessingContext.availableVaryings[u]=h,this._varyingsWGSL.push(` @location(${h}) ${c} ${u} : ${o},`),this._varyingNamesWGSL.push(u)),e=""}return e}attributeProcessor(e,t){const r=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){const s=r[2],n=r[1],i=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(n,s,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=i,this._webgpuProcessingContext.orderedAttributes[i]=n;const a=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[n];if(void 0!==a){const e=a<0?-1===a?"i32":"vec"+-a+"<i32>":1===a?"u32":"vec"+a+"<u32>",t=`_int_${n}_`;this._attributesInputWGSL.push(`@location(${i}) ${t} : ${e},`),this._attributesWGSL.push(`${n} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${i}) ${n} : ${s},`),this._attributesWGSL.push(`${n} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${n} = vertexInputs_.${n};`);e=""}return e}uniformProcessor(e,t,r){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],n=s[1];this._addUniformToLeftOverUBO(n,t,r),e=""}return e}textureProcessor(e,t,r){const s=this.textureRegexp.exec(e);if(null!==s){const n=s[1],i=s[2],a=!!s[3],o=s[4],u=o.indexOf("storage")>0,c=s[6];let h=null,l="write-only";if(u){const e=c.indexOf(",");h=c.substring(0,e).trim();switch(c.substring(e+1).trim()){case"read":l="read-only";break;case"read_write":l="read-write";break;default:l="write-only"}}let d=a?this._getArraySize(n,i,r)[2]:0,p=this._webgpuProcessingContext.availableTextures[n];if(p)d=p.textures.length;else{p={isTextureArray:d>0,isStorageTexture:u,storageTextureAccess:u?l:void 0,textures:[],sampleType:"float"},d=d||1;for(let e=0;e<d;++e)p.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[n]=p;const _=o.indexOf("depth")>0,g=Ne[o],m=_?"depth":"u32"===c?"uint":"i32"===c?"sint":"float";if(p.sampleType=m,void 0===g)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let r=0;r<d;++r){const{groupIndex:s,bindingIndex:i}=p.textures[r];0===r&&(e=`@group(${s}) @binding(${i}) ${e}`),this._addTextureBindingDescription(n,p,r,g,h,!t,l)}}return e}_convertDefinesToConst(e){let t="";for(const r in e){const s=e[r];r.startsWith("__")||(isNaN(parseInt(s))&&isNaN(parseFloat(s))?r&&""===s&&(t+=`const ${r} = true;\n`):t+=`const ${r} = ${s};\n`)}return t}postProcessor(e,t,r,s,n,i,a){const o=[];for(const e in a){"true"!==a[e]&&o.push(e)}o.sort((e,t)=>e.length-t.length>0?-1:e.length===t.length?0:1);for(const t of o){const r=e.indexOf("#define "+t);let s=e.indexOf("\n",r);-1===s&&(s=e.length);const n=e.substring(r+8+t.length+1,s);e=e.replace(new RegExp(t,"g"),n)}return e=this._convertDefinesToConst(i)+e,"VERTEXOUTPUT_INVARIANT"in i&&(e="#define VERTEXOUTPUT_INVARIANT\n"+e),e}finalizeShaders(e,r){const s=[],n=r.indexOf("fragmentInputs.position")>=0&&!this.pureMode?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),r=this._processSamplers(r,!1),e=this._processCustomBuffers(e,!0),r=this._processCustomBuffers(r,!1);const i=this._buildLeftOverUBO();r=i+r,e=(e=i+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let a="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(a+=this._attributesInputWGSL.join("\n")),a+="\n};\nvar<private> vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(a+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",a+=this._attributesWGSL.join("\n"),a+="\n};\nvar<private> vertexInputs : VertexInputs_;\n");let o="struct FragmentInputs {\n @builtin(position)"+(e.indexOf("#define VERTEXOUTPUT_INVARIANT")>=0?" @invariant":"")+" position : vec4<f32>,\n";this._varyingsWGSL.length>0&&(o+=this._varyingsWGSL.join("\n")),o+="\n};\nvar<private> vertexOutputs : FragmentInputs;\n",e=a+o+e;let u=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(u+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",u+=this._attributesConversionCodeWGSL.join("\n"),u+="\n");const c=this.pureMode?" return vertexOutputs;":" vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;";let h=-1!==e.indexOf(t.DISABLEUA);e=(h?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+Ge(e,"fn main",u,c),r=r.replace(/#define /g,"//#define "),r=this._processStridedUniformArrays(r),this.pureMode||(r=r.replace(/dpdy/g,"(-internals.yFactor_)*dpdy"));let l="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar<private> fragmentInputs : FragmentInputs;\n";let d="struct FragmentOutputs {\n";const p=r.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," "),_=p.search(/\bfn\s+main\s*\(/),g=e=>/^\s*(vec4<u32>|vec4u\s*\()/.test(e)?"vec4<u32>":/^\s*(vec4<i32>|vec4i\s*\()/.test(e)?"vec4<i32>":null,m=e=>{const t=p.match(new RegExp(`fragmentOutputs\\.fragData${e}\\s*=\\s*([^;]+);`));if(!t)return"vec4<f32>";const r=t[1].trim(),s=g(r);if(s)return s;const n=r.match(/^([A-Za-z_]\w*)$/);if(n&&_>=0){const e=p.slice(_,t.index??p.length),r=e.match(new RegExp(`(?:var|let)\\s+${n[1]}\\s*:\\s*(vec4<u32>|vec4<i32>)`));if(r)return r[1];const s=e.match(new RegExp(`(?:var|let)\\s+${n[1]}\\s*=\\s*([^;]+);`));if(s){const e=g(s[1].trim());if(e)return e}}return"vec4<f32>"},f="fragmentOutputs\\.fragData";let b=p.match(new RegExp(f+"0","g")),x=0;if(b){d+=` @location(${x}) fragData0 : ${m(0)},\n`,x++;for(let e=1;e<8;e++)b=p.match(new RegExp(f+e,"g")),b&&(d+=` @location(${x}) fragData${x} : ${m(e)},\n`,x++);-1!==r.indexOf("MRT_AND_COLOR")&&(d+=` @location(${x}) color : vec4<f32>,\n`,x++)}if(b=r.match(/oitDepthSampler/),b&&(d+=` @location(${x++}) depth : vec2<f32>,\n`,d+=` @location(${x++}) frontColor : vec4<f32>,\n`,d+=` @location(${x++}) backColor : vec4<f32>,\n`),0===x){-1!==r.indexOf("DUAL_SOURCE_BLENDING")?(s.push("dual_source_blending"),d+=" @location(0) @blend_src(0) color : vec4<f32>,\n",d+=" @location(0) @blend_src(1) color2 : vec4<f32>,\n"):d+=" @location(0) color : vec4<f32>,\n"}let T=!1,y=0;for(;!(T||(y=r.indexOf(Oe,y),y<0));){const e=y;for(T=!0;y>1&&"\n"!==r.charAt(y);){if("/"===r.charAt(y)&&"/"===r.charAt(y-1)){T=!1;break}y--}y=e+25}T&&(d+=" @builtin(frag_depth) fragDepth: f32,\n"),d+="};\nvar<private> fragmentOutputs : FragmentOutputs;\n";const E=" fragmentInputs = input;\n "+n;return h=-1!==(r=l+d+r).indexOf(t.DISABLEUA),s.length>0&&(r="enable "+s.join(";\nenable ")+";\n"+r),r=(h?"diagnostic(off, derivative_uniformity);\n":"")+"diagnostic(off, chromium.unreachable_code);\n"+Ge(r,"fn main",E," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:r}}_generateLeftOverUBOCode(e,t){let r="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const n=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Ae.UniformSizes[n];if(t.length>0)if(i<=2){const i=`${e}_${this._stridedUniformArrays.length}_strided_arr`;r+=`struct ${i} {\n @size(16)\n el: ${n},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${i}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${r}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var<uniform> uniforms : ${e};\n`,s}_processSamplers(e,r){const s=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const n=s.exec(e);if(null===n)break;const i=n[1],a=n[2],o=i.length-t.AUTOSAMPLERSUFFIX.length,u=i.lastIndexOf(t.AUTOSAMPLERSUFFIX)===o?i.substring(0,o):null,c="sampler_comparison"===a?"comparison":"filtering";if(u){const e=this._webgpuProcessingContext.availableTextures[u];e&&(e.autoBindSampler=!0)}let h=this._webgpuProcessingContext.availableSamplers[i];h||(h={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c},this._webgpuProcessingContext.availableSamplers[i]=h),this._addSamplerBindingDescription(i,h,r);const l=e.substring(0,n.index),d=`@group(${h.binding.groupIndex}) @binding(${h.binding.bindingIndex}) `,p=e.substring(n.index);e=l+d+p,s.lastIndex+=d.length}return e}_processCustomBuffers(e,t){const r=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=r.exec(e);if(null===s)break;const n=s[1],i=s[3];let a=s[4];const o=s[5];let u=this._webgpuProcessingContext.availableBuffers[a];if(!u){const e="uniform"===n?we.KnownUBOs[o]:null;let t;e?(a=o,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[a]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),u={binding:t},this._webgpuProcessingContext.availableBuffers[a]=u}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],"read_write"===i?"storage":"storage"===n?"read-only-storage":"uniform",t);const c=u.binding.groupIndex,h=u.binding.bindingIndex,l=e.substring(0,s.index),d=`@group(${c}) @binding(${h}) `,p=e.substring(s.index);e=l+d+p,r.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*?)\\]`,"g"),`${t}[$1].el`);return e}}class We{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e,t=0){return this._webgpuMSAATexture[t]||this._createMSAATexture(e,t),this._webgpuMSAATexture[t]}releaseMSAATextures(){for(const e of this._webgpuMSAATexture)e&&this._engine._textureHelper.releaseTexture(e);this._webgpuMSAATexture.length=0}constructor(e,t=null){this._engine=e,this._originalFormatIsRGB=!1,this.format="rgba8unorm",this.originalFormat="rgba8unorm",this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=t,this._webgpuMSAATexture=[],this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(t,r,s,n,i,a,o,u){let c="2d",h=1;n?(c=s?"cube-array":"cube",h=6*(u||1)):i?(c="3d",h=1):s&&(c="2d-array",h=u);const l=G.GetDepthFormatOnly(this.format),d=G.HasDepthAndStencilAspects(this.format)?"depth-only":"all";this.createView({label:`TextureView${i?"3D":n?"Cube":"2D"}${s?"_Array"+h:""}_${a}x${o}_${r?"wmips":"womips"}_${this.format}_${c}`,format:l,dimension:c,mipLevelCount:r?e(Math.max(a,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:d})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture.length=0,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATextures(),this._copyInvertYTempTexture?.destroy(),this.reset()}_createMSAATexture(e,t){if(!this._webgpuTexture)throw new Error("Cannot create GPU MSAA texture because underlying GPU texture is not created yet.");this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),this._webgpuMSAATexture[t]=this._engine._textureHelper.createMSAATexture(this._webgpuTexture,this.originalFormat,e)}}const Ve="\n const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array<vec2<f32>, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n var img: texture_2d<f32>;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n #ifdef INVERTY\n vertexOutputs.vTextureSize = vec2f(textureDimensions(img, 0));\n #endif\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",ke=Ve;var Xe,He;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst",e[e.ResolveDepth=4]="ResolveDepth"}(Xe||(Xe={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(He||(He={}));const qe=[{vertex:"\n const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n const tex = array<vec2<f32>, 4>( vec2f(0.0f, 0.0f), vec2f(1.0f, 0.0f), vec2f(0.0f, 1.0f), vec2f(1.0f, 1.0f));\n\n varying vTex: vec2f;\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.vTex = tex[input.vertexIndex];\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n var imgSampler: sampler;\n var img: texture_2d<f32>;\n\n varying vTex: vec2f;\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = textureSample(img, imgSampler, input.vTex);\n }\n "},{vertex:Ve,fragment:"\n var img: texture_2d<f32>;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(input.vTextureSize.y - input.position.y)), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n "},{vertex:"\n const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n uniform color: vec4f;\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n fragmentOutputs.color = uniforms.color;\n }\n "},{vertex:ke,fragment:"\n var img: texture_2d<f32>;\n uniform ofstX: f32;\n uniform ofstY: f32;\n uniform width: f32;\n uniform height: f32;\n\n #ifdef INVERTY\n varying vTextureSize: vec2f;\n #endif\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n if (input.position.x < uniforms.ofstX || input.position.x >= uniforms.ofstX + uniforms.width) {\n discard;\n }\n if (input.position.y < uniforms.ofstY || input.position.y >= uniforms.ofstY + uniforms.height) {\n discard;\n }\n #ifdef INVERTY\n var color: vec4f = textureLoad(img, vec2i(i32(input.position.x), i32(uniforms.ofstY + uniforms.height - (input.position.y - uniforms.ofstY))), 0);\n #else\n var color: vec4f = textureLoad(img, vec2i(input.position.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color = vec4f(color.rgb * color.a, color.a);\n #endif\n fragmentOutputs.color = color;\n }\n "},{vertex:"\n const pos = array<vec2<f32>, 4>( vec2f(-1.0f, 1.0f), vec2f(1.0f, 1.0f), vec2f(-1.0f, -1.0f), vec2f(1.0f, -1.0f));\n\n @vertex\n fn main(input : VertexInputs) -> FragmentInputs {\n vertexOutputs.position = vec4f(pos[input.vertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n var msaaDepthTexture: texture_depth_multisampled_2d;\n\n @fragment\n fn main(input: FragmentInputs) -> FragmentOutputs {\n #ifdef USE_MIN\n let numSamples = textureNumSamples(msaaDepthTexture);\n var depth = 1.0;\n\n for (var i = 0u; i < numSamples; i = i + 1u) {\n depth = min(depth, textureLoad(msaaDepthTexture, vec2u(input.position.xy), i));\n }\n\n fragmentOutputs.color = vec4f(depth);\n #else\n fragmentOutputs.color = vec4f(textureLoad(msaaDepthTexture, vec2u(input.position.xy), 0)); // do like WebGL, take the first sample\n #endif\n }\n "}],Ye={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38,r16unorm:39,rg16unorm:40,rgba16unorm:41,r16snorm:42,rg16snorm:43,rgba16snorm:44};class ze{constructor(e,t,r,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._bufferManager=r,-1!==s.indexOf("rg11b10ufloat-renderable")){const e=Object.keys(Ye);Ye.rg11b10ufloat=Ye[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:"linear"}),this._videoSampler=t.createSampler({minFilter:"linear"}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,V.Uniform|V.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline("rgba8unorm"),this._getVideoPipeline("rgba8unorm")}_getPipeline(e,t=Xe.MipMap,r){const s=t===Xe.MipMap?1:t===Xe.InvertYPremultiplyAlpha?((r.invertY?1:0)<<1)+((r.premultiplyAlpha?1:0)<<2):t===Xe.Clear?8:t===Xe.InvertYPremultiplyAlphaWithOfst?((r.invertY?1:0)<<4)+((r.premultiplyAlpha?1:0)<<5):t===Xe.ResolveDepth?64:0;this._pipelines[e]||(this._pipelines[e]=[]);let n=this._pipelines[e][s];if(!n){let i="";t!==Xe.InvertYPremultiplyAlpha&&t!==Xe.InvertYPremultiplyAlphaWithOfst||(r.invertY&&(i+="#define INVERTY\n"),r.premultiplyAlpha&&(i+="#define PREMULTIPLYALPHA\n"));let c=this._compiledShaders[s];if(!c){let e=qe[t].vertex,r=qe[t].fragment;const n={defines:i.split("\n"),indexParameters:null,isFragment:!1,shouldUseHighPrecisionShader:!0,processor:this._engine._getShaderProcessor(1),supportsUniformBuffers:!0,shadersRepository:"",includesShadersStore:{},version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._engine._getShaderProcessingContext(1,!0),isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};a(n),n.processor.pureMode=!0,o(e,n,t=>{e=t},this._engine),n.isFragment=!0,o(r,n,e=>{r=e},this._engine);const h=u(e,r,n);n.processor.pureMode=!1;const l=this._device.createShaderModule({label:`BabylonWebGPUDevice${this._engine.uniqueId}_InternalVertexShader_${s}`,code:h.vertexCode}),d=this._device.createShaderModule({label:`BabylonWebGPUDevice${this._engine.uniqueId}_InternalFragmentShader_${s}`,code:h.fragmentCode});c=this._compiledShaders[s]=[l,d]}const h=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_InternalPipeline_${e}_${s}`,layout:"auto",vertex:{module:c[0],entryPoint:"main"},fragment:{module:c[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});n=this._pipelines[e][s]=[h,h.getBindGroupLayout(0)]}return n}_getVideoPipeline(e,t=He.DontInvertY){const r=t===He.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][r];if(!s){let t=this._videoCompiledShaders[r];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4<f32>,\n @location(0) fragUV : vec2<f32>\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array<vec2<f32>, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array<vec2<f32>, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n ",label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_VertexShader`}),s=this._device.createShaderModule({code:0===r?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2<f32>\n ) -> @location(0) vec4<f32> {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2<f32>\n ) -> @location(0) vec4<f32> {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y));\n }\n ",label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_FragmentShader_${0===r?"DontInvertY":"InvertY"}`});t=this._videoCompiledShaders[r]=[e,s]}const n=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_InternalVideoPipeline_${e}_${0===r?"DontInvertY":"InvertY"}`,layout:"auto",vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:"triangle-strip",stripIndexFormat:"uint16"}});s=this._videoPipelines[e][r]=[n,n.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,r,s=!1,n){const i=void 0===n,[a,o]=this._getVideoPipeline(r,s?He.InvertY:He.DontInvertY);i&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup(`copy video to texture (invertY=${s})`);const u=t._hardwareTexture,c={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${r}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:u.underlyingResource.createView({format:r,dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"}),loadOp:"load",storeOp:"store"}]},h=n.beginRenderPass(c),l={layout:o,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(l);h.setPipeline(a),h.setBindGroup(0,d),h.draw(4,1,0,0),h.end(),n.popDebugGroup(),i&&(this._device.queue.submit([n.finish()]),n=null)}invertYPreMultiplyAlpha(e,t,r,s,n=!1,i=!1,a=0,o=0,u=1,c=0,h=0,l=0,d=0,p,_){const g=0!==l,m=void 0===p,[f,b]=this._getPipeline(s,g?Xe.InvertYPremultiplyAlphaWithOfst:Xe.InvertYPremultiplyAlpha,{invertY:n,premultiplyAlpha:i});let x;if(a=Math.max(a,0),m&&(p=this._device.createCommandEncoder({})),G.IsHardwareTexture(e)?(x=e.underlyingResource,n&&!i&&1===u&&0===a||(e=void 0)):(x=e,e=void 0),!x)return;p.pushDebugGroup(`internal process texture "${x.label}" (invertY=${n} premultiplyAlpha=${i})`),g&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,h,l,d]),0,16);const T=e,y=T?._copyInvertYTempTexture??this.createTexture({width:t,height:r,layers:1},!1,!1,!1,!1,!1,s,1,p,21,void 0,"TempTextureForCopyWithInvertY"),E=T?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${n?"InvertY":"DontInvertY"}_${i?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:y.createView({format:s,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},S=p.beginRenderPass(E);let R=g?T?._copyInvertYBindGroupWithOfst:T?._copyInvertYBindGroup;if(!R){const e={layout:b,entries:[{binding:0,resource:x.createView({format:s,dimension:"2d",baseMipLevel:o,mipLevelCount:1,arrayLayerCount:u,baseArrayLayer:a})}]};g&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),R=this._device.createBindGroup(e)}S.setPipeline(f),S.setBindGroup(0,R),S.draw(4,1,0,0),S.end(),p.copyTextureToTexture({texture:y},{texture:x,mipLevel:o,origin:{x:0,y:0,z:a}},{width:l||t,height:d||r,depthOrArrayLayers:1}),T?(T._copyInvertYTempTexture=y,T._copyInvertYRenderPassDescr=E,g?T._copyInvertYBindGroupWithOfst=R:T._copyInvertYBindGroup=R):this._deferredReleaseTextures.push([y,null]),p.popDebugGroup(),m&&(this._device.queue.submit([p.finish()]),p=null)}createTexture(e,t=!1,r=!1,s=!1,n=!1,i=!1,a="rgba8unorm",o=1,u,c=-1,h=0,l,d){o=G.GetSample(o);const p=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:p},g=Ye[a]?16:0,m=G.IsCompressedFormat(a),f=G.ComputeNumMipmapLevels(e.width,e.height),b=t?Math.min(d??f,f):1,x=c>=0?c:7;h|=t&&!m?1|g:0,m||i||(h|=2|g);const T=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${i?"3D":"2D"}_${l?l+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${o}`,size:_,dimension:i?"3d":"2d",format:a,usage:x|h,sampleCount:o,mipLevelCount:b});return G.IsImageBitmap(e)&&(this.updateTexture(e,T,e.width,e.height,p,a,0,0,s,n,0,0),t&&r&&this.generateMipmaps(T,b,0,u)),T}createCubeTexture(e,t=!1,r=!1,s=!1,n=!1,i="rgba8unorm",a=1,o,u=-1,c=0,h){a=G.GetSample(a);const l=G.IsImageBitmapArray(e)?e[0].width:e.width,d=G.IsImageBitmapArray(e)?e[0].height:e.height,p=G.IsImageBitmapArray(e)?1:e.layers,_=Ye[i]?16:0,g=G.IsCompressedFormat(i),m=t?G.ComputeNumMipmapLevels(l,d):1,f=u>=0?u:7;c|=t&&!g?1|_:0,g||(c|=2|_);const b=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${h?h+"_":""}${l}x${d}x${p}_${t?"wmips":"womips"}_${i}_samples${a}`,size:{width:l,height:d,depthOrArrayLayers:6*p},dimension:"2d",format:i,usage:f|c,sampleCount:a,mipLevelCount:m});return G.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,b,l,d,i,s,n,0,0),t&&r&&this.generateCubeMipmaps(b,m,o)),b}generateCubeMipmaps(e,t,r){const s=void 0===r,n=G.IsHardwareTexture(e)?e.underlyingResource:e;s&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup(`create cube mipmaps for "${n.label}" (${t} levels)`);for(let s=0;s<n.depthOrArrayLayers;++s)this.generateMipmaps(e,t,s,r);r.popDebugGroup(),s&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,r=0,s){const n=void 0===s;let i;if(r=Math.max(r,0),n&&(s=this._device.createCommandEncoder({})),G.IsHardwareTexture(e)?(i=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(i=e,e=void 0),!i)return;s.pushDebugGroup(`create mipmaps for "${i.label}" (face #${r} - ${t} levels)`);const a=i.format,[o,u]=this._getPipeline(a),c="3d"===i.dimension,h=e;for(let e=1;e<t;++e){const t=h?._mipmapGenRenderPassDescr[r]?.[e-1]??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_generateMipmaps_${a}_faceIndex${r}_level${e}`,colorAttachments:[{view:i.createView({format:a,dimension:c?"3d":"2d",baseMipLevel:e,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r}),loadOp:"load",storeOp:"store"}]};h&&(h._mipmapGenRenderPassDescr[r]=h._mipmapGenRenderPassDescr[r]||[],h._mipmapGenRenderPassDescr[r][e-1]=t);const n=s.beginRenderPass(t),l=h?._mipmapGenBindGroup[r]?.[e-1]??this._device.createBindGroup({layout:u,entries:[{binding:0,resource:i.createView({format:a,dimension:c?"3d":"2d",baseMipLevel:e-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r})},{binding:1,resource:this._mipmapSampler}]});h&&(h._mipmapGenBindGroup[r]=h._mipmapGenBindGroup[r]||[],h._mipmapGenBindGroup[r][e-1]=l),n.setPipeline(o),n.setBindGroup(0,l),n.draw(4,1,0,0),n.end()}s.popDebugGroup(),n&&(this._device.queue.submit([s.finish()]),s=null)}createGPUTextureForInternalTexture(e,r,s,n,i){e._hardwareTexture||(e._hardwareTexture=new We(this._engine)),void 0===r&&(r=e.width),void 0===s&&(s=e.height),void 0===n&&(n=e.depth),e.width=e.baseWidth=r,e.height=e.baseHeight=s,e.depth=e.baseDepth=n;const a=e._hardwareTexture,o=0!==((i??0)&t.TEXTURE_CREATIONFLAG_STORAGE),u=e.label?e.label+"_InternalUniqueId"+e.uniqueId:"InternalUniqueId"+e.uniqueId;if(a.format=a.originalFormat=G.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),e.samples>1)switch(a.format){case"depth16unorm":a.format="r16unorm";break;case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":a.format="r32float"}a.textureUsages=5===e._source||6===e.source?21:12===e._source?20:-1,a.textureAdditionalUsages=o?8:0;const c=e.generateMipMaps,h=n||1;let l;if(l=null!==e._maxLodLevel?e._maxLodLevel:c?G.ComputeNumMipmapLevels(r,s):1,e.isCube){const t=this.createCubeTexture({width:r,height:s,layers:h},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,a.format,1,this._commandEncoderForCreation,a.textureUsages,a.textureAdditionalUsages,u);a.set(t);const n=G.GetDepthFormatOnly(a.format),i=G.HasDepthAndStencilAspects(a.format)?"depth-only":"all",d=e.is2DArray?"cube-array":"cube";a.createView({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureViewCube${e.is2DArray?"_Array"+h:""}_${r}x${s}_${c?"wmips":"womips"}_${n}_${d}_${i}_${u}`,format:n,dimension:d,mipLevelCount:l,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6*h,aspect:i},o)}else{const t=this.createTexture({width:r,height:s,layers:h},c,e.generateMipMaps,e.invertY,!1,e.is3D,a.format,1,this._commandEncoderForCreation,a.textureUsages,a.textureAdditionalUsages,u);a.set(t);const n=e.is3D?1:h,i=G.GetDepthFormatOnly(a.format),d=G.HasDepthAndStencilAspects(a.format)?"depth-only":"all",p=e.is2DArray?"2d-array":e.is3D?"3d":"2d";a.createView({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureView${e.is3D?"3D":"2D"}${e.is2DArray?"_Array"+n:""}_${r}x${s}${e.is3D?"x"+h:""}_${c?"wmips":"womips"}_${i}_${p}_${d}_${u}`,format:i,dimension:p,mipLevelCount:l,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:n,aspect:d},o)}return a}createMSAATexture(e,t,r){return this.createTexture({width:e.width,height:e.height,layers:1},!1,!1,!1,!1,!1,t,r,this._commandEncoderForCreation,20,0,e.label?e.label+" (MSAA)":"MSAA")}resolveMSAADepthTexture(e,t,r){const s=t.format,n=void 0===r,[i,a]=this._getPipeline(s,Xe.ResolveDepth);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup(`resolve MSAA Depth texture "${e.label}" to "${t.label}"`);const o={label:`BabylonWebGPUDevice${this._engine.uniqueId}_resolveMSAADepthTexture${e.label?"_"+e.label:""}`,colorAttachments:[{view:t.createView({format:s,dimension:"2d",baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:"load",storeOp:"store"}]},u=r.beginRenderPass(o),c={layout:a,entries:[{binding:0,resource:e.createView({format:G.GetDepthFormatOnly(e.format),dimension:"2d",mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:"depth-only"})}]},h=this._device.createBindGroup(c);u.setPipeline(i),u.setBindGroup(0,h),u.draw(4,1,0,0),u.end(),r.popDebugGroup(),n&&(this._device.queue.submit([r.finish()]),r=null)}updateCubeTextures(e,t,r,s,n,i=!1,a=!1,o=0,u=0){const c=[0,3,1,4,2,5];for(let h=0;h<c.length;++h){const l=e[c[h]];this.updateTexture(l,t,r,s,1,n,h,0,i,a,o,u)}}updateTexture(e,t,r,s,n,i,a=0,o=0,u=!1,c=!1,h=0,l=0,d){const p=G.IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,_=G.GetBlockInformationFromFormat(i),g=G.IsInternalTexture(t)?t._hardwareTexture:t,m={texture:p,origin:{x:h,y:l,z:Math.max(a,0)},mipLevel:o,premultipliedAlpha:c},f={width:Math.ceil(r/_.width)*_.width,height:Math.ceil(s/_.height)*_.height,depthOrArrayLayers:n||1};if(void 0!==e.byteLength){const b=Math.ceil(r/_.width)*_.length;if(256*Math.ceil(b/256)===b){const t=this._device.createCommandEncoder({}),r=this._bufferManager.createRawBuffer(e.byteLength,V.MapWrite|V.CopySrc,!0,"TempBufferForUpdateTexture"+(p?"_"+p.label:"")),s=r.getMappedRange();new Uint8Array(s).set(e),r.unmap(),t.copyBufferToTexture({buffer:r,offset:0,bytesPerRow:b,rowsPerImage:f.height/_.height},m,f),this._device.queue.submit([t.finish()]),this._bufferManager.releaseBuffer(r)}else this._device.queue.writeTexture(m,e,{offset:0,bytesPerRow:b,rowsPerImage:f.height/_.height},f);if(u||c){if(!G.IsInternalTexture(t))throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!";{const e=0===h&&0===l&&r===t.width&&s===t.height;this.invertYPreMultiplyAlpha(g,t.width,t.height,i,u,c,a,o,n||1,h,l,e?0:r,e?0:s,void 0,d)}}}else this._device.queue.copyExternalImageToTexture({source:e,flipY:u},m,f)}updateMipLevelCountForInternalTexture(e,t){const r=G.ComputeNumMipmapLevels(e.width,e.height);void 0!==t?e.mipLevelCount=Math.min(Math.max(1,t),r):e.generateMipMaps?e.mipLevelCount=r:e.mipLevelCount=1}readPixels(e,t,r,s,n,i,a=0,o=0,u=null,c=!1){const h=G.GetBlockInformationFromFormat(i),l=Math.ceil(s/h.width)*h.length,d=256*Math.ceil(l/256),p=d*n,_=this._bufferManager.createRawBuffer(p,V.MapRead|V.CopyDst,void 0,"TempBufferForReadPixels"+(e.label?"_"+e.label:"")),g=this._device.createCommandEncoder({});return g.copyTextureToBuffer({texture:e,mipLevel:o,origin:{x:t,y:r,z:Math.max(a,0)}},{buffer:_,offset:0,bytesPerRow:d},{width:s,height:n,depthOrArrayLayers:1}),this._device.queue.submit([g.finish()]),this._bufferManager.readDataFromBuffer(_,p,s,n,l,d,G.GetTextureTypeFromFormat(i),0,u,!0,c)}releaseTexture(e){if(G.IsInternalTexture(e)){const t=e._hardwareTexture,r=e._irradianceTexture;this._deferredReleaseTextures.push([t,r])}else this._deferredReleaseTextures.push([e,null])}destroyDeferredTextures(){for(let e=0;e<this._deferredReleaseTextures.length;++e){const[t,r]=this._deferredReleaseTextures[e];t&&(G.IsHardwareTexture(t)?t.release():t.destroy()),r?.dispose()}this._deferredReleaseTextures.length=0}}class Qe extends c{set buffer(e){this._buffer=e}constructor(e,t=0){super(),this.engineId=-1,this.capacity=t,e&&(this._buffer=e)}get underlyingResource(){return this._buffer}}class Ke{static _IsGPUBuffer(e){return void 0===e.underlyingResource}static _FlagsToString(e,t=""){let r=t;for(let t=0;t<=9;++t)e&1<<t&&(r&&(r+="_"),r+=V[1<<t]);return r}constructor(e,t){this._deferredReleaseBuffers=[],this._engine=e,this._device=t}createRawBuffer(e,t,r=!1,s){const n=void 0!==e.byteLength?e.byteLength+3&-4:e+3&-4,i={label:"BabylonWebGPUDevice"+this._engine.uniqueId+"_"+Ke._FlagsToString(t,s??"Buffer")+"_size"+n,mappedAtCreation:r,size:n,usage:t};return this._device.createBuffer(i)}createBuffer(e,t,r){const s=void 0!==e.byteLength,n=new Qe,i="DataBufferUniqueId="+n.uniqueId;return n.buffer=this.createRawBuffer(e,t,void 0,r?i+"-"+r:i),n.references=1,n.capacity=void 0!==e.byteLength?e.byteLength+3&-4:e+3&-4,n.engineId=this._engine.uniqueId,s&&this.setSubData(n,0,e),n}setRawData(e,t,r,s,n){s+=r.byteOffset,this._device.queue.writeBuffer(e,t,r.buffer,s,n)}setSubData(e,t,r,s=0,n=0){const i=e.underlyingResource;n=n||r.byteLength-s;const a=3&t;s-=a,t-=a;const o=n;n=n+a+3&-4;if(r.buffer.byteLength-r.byteOffset<n){const e=new Uint8Array(n);e.set(new Uint8Array(r.buffer,r.byteOffset+s,o)),r=e,s=0}this.setRawData(i,t,r,s,n)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,r){r?e=Math.min(e,r.length):r=new Float32Array(e);const s=new Uint16Array(t);for(;e--;)r[e]=h(s[e]);return r}readDataFromBuffer(e,r,s,n,i,a,o=t.TEXTURETYPE_UNSIGNED_BYTE,u=0,c=null,h=!0,d=!1){const p=o===t.TEXTURETYPE_FLOAT?2:o===t.TEXTURETYPE_HALF_FLOAT?1:0,_=this._engine.uniqueId;return new Promise((t,s)=>{e.mapAsync(1,u,r).then(()=>{const s=e.getMappedRange(u,r);let _=c;if(d)_=null===_?l(o,r,!0,s):l(o,_.buffer,void 0,s);else if(null===_)switch(p){case 0:_=new Uint8Array(r),_.set(new Uint8Array(s));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(r/2,s);break;case 2:_=new Float32Array(r/4),_.set(new Float32Array(s))}else switch(p){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(s,0,Math.min(_.byteLength,r)));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(r/2,s,c);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(s,0,_.byteLength/4))}if(i!==a){1!==p||d||(i*=2,a*=2);const e=new Uint8Array(_.buffer);let t,r=i;for(let s=1;s<n;++s){t=s*a;for(let s=0;s<i;++s)e[r++]=e[t++]}_=0===p||d?new Uint8Array(e.buffer,0,r):new Float32Array(e.buffer,0,r/4)}e.unmap(),h&&this.releaseBuffer(e),t(_)},e=>{this._engine.isDisposed||this._engine.uniqueId!==_?t(new Uint8Array):s(e)})})}releaseBuffer(e){return Ke._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0}}const je=[0,0,3,7,0,2,6,2,4,1,5,3,1],Je=[0,64,32,96,16,80,48,112,8],Ze=[0,128,128,0,0,0,0,128,0,0,0,0,128];class et{constructor(e){this._samplers={},this._device=e,this.disabled=!1}static GetSamplerHashCode(e){const t=e._cachedAnisotropicFilteringLevel?e._cachedAnisotropicFilteringLevel:1;return je[e.samplingMode]+Je[(e._comparisonFunction||514)-512+1]+Ze[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,r){let s,n,i,a,o;const u=e.useMipMaps;switch(e.samplingMode){case t.TEXTURE_LINEAR_LINEAR_MIPNEAREST:s="linear",n="linear",i="nearest",u||(a=o=0);break;case t.TEXTURE_TRILINEAR_SAMPLINGMODE:s="linear",n="linear",u?i="linear":(i="nearest",a=o=0);break;case t.TEXTURE_NEAREST_NEAREST_MIPLINEAR:s="nearest",n="nearest",u?i="linear":(i="nearest",a=o=0);break;case t.TEXTURE_NEAREST_NEAREST_MIPNEAREST:s="nearest",n="nearest",i="nearest",u||(a=o=0);break;case t.TEXTURE_NEAREST_LINEAR_MIPNEAREST:s="nearest",n="linear",i="nearest",u||(a=o=0);break;case t.TEXTURE_NEAREST_LINEAR_MIPLINEAR:s="nearest",n="linear",u?i="linear":(i="nearest",a=o=0);break;case t.TEXTURE_NEAREST_LINEAR:s="nearest",n="linear",i="nearest",a=o=0;break;case t.TEXTURE_NEAREST_SAMPLINGMODE:s="nearest",n="nearest",i="nearest",a=o=0;break;case t.TEXTURE_LINEAR_NEAREST_MIPNEAREST:s="linear",n="nearest",i="nearest",u||(a=o=0);break;case t.TEXTURE_LINEAR_NEAREST_MIPLINEAR:s="linear",n="nearest",u?i="linear":(i="nearest",a=o=0);break;case t.TEXTURE_BILINEAR_SAMPLINGMODE:s="linear",n="linear",r>1?i="linear":(i="nearest",a=o=0);break;case t.TEXTURE_LINEAR_NEAREST:s="linear",n="nearest",i="nearest",a=o=0;break;default:s="nearest",n="nearest",i="nearest",a=o=0}return r>1&&(0!==a||0!==o)?{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",anisotropyEnabled:!0}:{magFilter:s,minFilter:n,mipmapFilter:i,lodMinClamp:a,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case t.TEXTURE_WRAP_ADDRESSMODE:return"repeat";case t.TEXTURE_CLAMP_ADDRESSMODE:return"clamp-to-edge";case t.TEXTURE_MIRROR_ADDRESSMODE:return"mirror-repeat"}return"repeat"}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,r){let s=(e.useMipMaps||e.samplingMode===t.TEXTURE_LINEAR_LINEAR)&&e._cachedAnisotropicFilteringLevel?e._cachedAnisotropicFilteringLevel:1;e.samplingMode!==t.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&e.samplingMode!==t.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&e.samplingMode!==t.TEXTURE_LINEAR_LINEAR&&(s=1);const n=this._GetSamplerFilterDescriptor(e,s);return{label:r,...n,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?et.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:n.anisotropyEnabled?s:1}}static GetCompareFunction(e){switch(e){case t.ALWAYS:return"always";case t.EQUAL:return"equal";case t.GREATER:return"greater";case t.GEQUAL:return"greater-equal";case t.LESS:return"less";case t.LEQUAL:return"less-equal";case t.NEVER:return"never";case t.NOTEQUAL:return"not-equal";default:return"less"}}getSampler(e,t=!1,r=0,s){if(this.disabled)return this._device.createSampler(et._GetSamplerDescriptor(e,s));t?r=0:0===r&&(r=et.GetSamplerHashCode(e));let n=t?void 0:this._samplers[r];return n||(n=this._device.createSampler(et._GetSamplerDescriptor(e,s)),t||(this._samplers[r]=n)),n}}const tt={[d.PositionKind]:!0,[d.NormalKind]:!0,[d.TangentKind]:!0,[d.UVKind]:!0,[d.UV2Kind]:!0,[d.UV3Kind]:!0,[d.UV4Kind]:!0,[d.UV5Kind]:!0,[d.UV6Kind]:!0,[d.ColorKind]:!0,[d.ColorInstanceKind]:!0,[d.MatricesIndicesKind]:!0,[d.MatricesWeightsKind]:!0,[d.MatricesIndicesExtraKind]:!0,[d.MatricesWeightsExtraKind]:!0};function rt(e){switch(e){case d.BYTE:case d.SHORT:case d.INT:case d.FLOAT:case d.HALF_FLOAT:return!0;case d.UNSIGNED_BYTE:case d.UNSIGNED_SHORT:case d.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}var st;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments=5]="MRTAttachments",e[e.RasterizationState=6]="RasterizationState",e[e.ColorStates1=7]="ColorStates1",e[e.ColorStates2=8]="ColorStates2",e[e.ColorStates3=9]="ColorStates3",e[e.ColorStates4=10]="ColorStates4",e[e.ShaderStage=11]="ShaderStage",e[e.TextureStage=12]="TextureStage",e[e.VertexState=13]="VertexState",e[e.NumStates=14]="NumStates"}(st||(st={}));const nt={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:14,32772:15,35065:16,35066:17,34185:18,35067:19},it={32774:0,32775:1,32776:2,32778:3,32779:4},at={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},ot=[0,0,0,0];class ut{constructor(e,t){this._depthBiasClamp=0,this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(st.VertexState+2*(e.limits.maxVertexAttributes||16)),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=["bgra8unorm"],this.setColorFormat("bgra8unorm"),this.setMRT([]),this.setAlphaBlendEnabled([!1],1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat("depth24plus-stencil8"),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments>0?this._mrtFormats:this._webgpuColorFormat}_lookupRenderPipeline(e,t,r,s){return this._setShaderStage(t.uniqueId),this._setRasterizationState(e,r),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline?(this._stateDirtyLowestIndex=this._statesLength,ut.NumCacheHitWithoutHash++,this._parameter.pipeline):(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline?(ut.NumCacheHitWithHash++,this._parameter.pipeline):null)}getRenderPipeline(e,t,r,s=0){if(r=G.GetSample(r),this.disabled){const n=ut._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,n,r),ut.NumCacheMiss++,ut._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}const n=this._lookupRenderPipeline(e,t,r,s);if(n)return n;const i=ut._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,i,r),this._setRenderPipeline(this._parameter),ut.NumCacheMiss++,ut._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){ut.NumPipelineCreationLastFrame=ut._NumPipelineCreationCurrentFrame,ut._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,t.ALWAYS)}setDepthCullingState(e,r,s,n,i,a,o,u){this._depthWriteEnabled=o,this._depthTestEnabled=a,this._depthCompare=(u??t.ALWAYS)-512,this._cullFace=s,this._cullEnabled=e,this._frontFace=r,this.setDepthBiasSlopeScale(n),this.setDepthBias(i)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[st.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[st.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Ye[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let r=0;r<e.length;++r)0!==e[r]&&(t+=1<<r);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.MRTAttachments))}setMRT(e,t){if((t=t??e.length)>8)throw new Error("Can't handle more than 8 attachments for a MRT in cache render pipeline!");this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let r=0,s=0;for(let n=0;n<t;++n){const t=e[n],i=t?._hardwareTexture;this._mrtFormats[n]=i?.format??this._webgpuColorFormat[0],r+=Ye[this._mrtFormats[n]??""]*2**s,s+=6}this._mrtFormats.length=t,this._mrtAttachments!==r&&(this._mrtAttachments=r,this._states[st.MRTAttachments]=r,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.MRTAttachments))}setAlphaBlendEnabled(e,t){this._alphaBlendEnabled=e,this._numAlphaBlendTargetsEnabled=t}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:Ye[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??t.ALWAYS)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??t.ALWAYS)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:at[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:at[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:at[e]}setStencilBackCompare(e){this._stencilBackCompare=(e??t.ALWAYS)-512}setStencilBackDepthFailOp(e){this._stencilBackDepthFailOp=null===e?1:at[e]}setStencilBackPassOp(e){this._stencilBackPassOp=null===e?2:at[e]}setStencilBackFailOp(e){this._stencilBackFailOp=null===e?1:at[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[st.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[st.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,t.ALWAYS,t.KEEP,t.REPLACE,t.KEEP,255,255)}setStencilState(e,r,s,n,i,a,o,u=null,c=null,h=null,l=null){this._stencilEnabled=e,this._stencilFrontCompare=(r??t.ALWAYS)-512,this._stencilFrontDepthFailOp=null===s?1:at[s],this._stencilFrontPassOp=null===n?2:at[n],this._stencilFrontFailOp=null===i?1:at[i],this._stencilBackCompare=(u??t.ALWAYS)-512,this._stencilBackDepthFailOp=null===c?1:at[c],this._stencilBackPassOp=null===h?2:at[h],this._stencilBackFailOp=null===l?1:at[l],this.setStencilReadMask(a),this.setStencilWriteMask(o)}setBuffers(e,t,r){this._vertexBuffers=e,this._overrideVertexBuffers=r,this.indexBuffer=t}static _GetTopology(e){switch(e){case t.MATERIAL_TriangleFillMode:return"triangle-list";case t.MATERIAL_PointFillMode:return"point-list";case t.MATERIAL_WireFrameFillMode:return"line-list";case t.MATERIAL_PointListDrawMode:return"point-list";case t.MATERIAL_LineListDrawMode:return"line-list";case t.MATERIAL_LineLoopDrawMode:throw"LineLoop is an unsupported fillmode in WebGPU";case t.MATERIAL_LineStripDrawMode:return"line-strip";case t.MATERIAL_TriangleStripDrawMode:return"triangle-strip";case t.MATERIAL_TriangleFanDrawMode:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return"triangle-list"}}static _GetAphaBlendOperation(e){switch(e){case t.GL_ALPHA_EQUATION_ADD:return"add";case t.GL_ALPHA_EQUATION_SUBTRACT:return"subtract";case t.GL_ALPHA_EQUATION_REVERSE_SUBTRACT:return"reverse-subtract";case t.GL_ALPHA_EQUATION_MIN:return"min";case t.GL_ALPHA_EQUATION_MAX:return"max";default:return"add"}}static _GetAphaBlendFactor(e){switch(e){case 0:return"zero";case 1:return"one";case t.GL_ALPHA_FUNCTION_SRC:return"src";case t.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR:return"one-minus-src";case t.GL_ALPHA_FUNCTION_SRC_ALPHA:return"src-alpha";case t.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA:return"one-minus-src-alpha";case t.GL_ALPHA_FUNCTION_DST_ALPHA:return"dst-alpha";case t.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA:return"one-minus-dst-alpha";case t.GL_ALPHA_FUNCTION_DST_COLOR:return"dst";case t.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR:return"one-minus-dst";case t.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED:return"src-alpha-saturated";case t.GL_ALPHA_FUNCTION_CONSTANT_COLOR:case t.GL_ALPHA_FUNCTION_CONSTANT_ALPHA:return"constant";case t.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR:case t.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA:return"one-minus-constant";case t.GL_ALPHA_FUNCTION_SRC1_COLOR:return"src1";case t.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR:return"one-minus-src1";case t.GL_ALPHA_FUNCTION_SRC1_ALPHA:return"src1-alpha";case t.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA:return"one-minus-src1-alpha";default:return"one"}}static _GetCompareFunction(e){switch(e){case 0:return"never";case 1:return"less";case 2:return"equal";case 3:return"less-equal";case 4:return"greater";case 5:return"not-equal";case 6:return"greater-equal";case 7:return"always"}return"never"}static _GetStencilOpFunction(e){switch(e){case 0:return"zero";case 1:return"keep";case 2:return"replace";case 3:return"increment-clamp";case 4:return"decrement-clamp";case 5:return"invert";case 6:return"increment-wrap";case 7:return"decrement-wrap"}return"keep"}static _GetVertexInputDescriptorFormat(e){const t=e.type,r=e.normalized,s=e.getSize();switch(t){case d.BYTE:switch(s){case 1:case 2:return r?"snorm8x2":"sint8x2";case 3:case 4:return r?"snorm8x4":"sint8x4"}break;case d.UNSIGNED_BYTE:switch(s){case 1:case 2:return r?"unorm8x2":"uint8x2";case 3:case 4:return r?"unorm8x4":"uint8x4"}break;case d.SHORT:switch(s){case 1:case 2:return r?"snorm16x2":"sint16x2";case 3:case 4:return r?"snorm16x4":"sint16x4"}break;case d.UNSIGNED_SHORT:switch(s){case 1:case 2:return r?"unorm16x2":"uint16x2";case 3:case 4:return r?"unorm16x4":"uint16x4"}break;case d.HALF_FLOAT:switch(s){case 1:case 2:return"float16x2";case 3:case 4:return"float16x4"}break;case d.INT:switch(s){case 1:return"sint32";case 2:return"sint32x2";case 3:return"sint32x3";case 4:return"sint32x4"}break;case d.UNSIGNED_INT:switch(s){case 1:return"uint32";case 2:return"uint32x2";case 3:return"uint32x3";case 4:return"uint32x4"}break;case d.FLOAT:switch(s){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4"}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${r}, size=${s}`)}_getAphaBlendState(e){return this._alphaBlendEnabled[e]?{srcFactor:ut._GetAphaBlendFactor(this._alphaBlendFuncParams[4*e+2]),dstFactor:ut._GetAphaBlendFactor(this._alphaBlendFuncParams[4*e+3]),operation:ut._GetAphaBlendOperation(this._alphaBlendEqParams[2*e+1])}:null}_getColorBlendState(e){return this._alphaBlendEnabled?{srcFactor:ut._GetAphaBlendFactor(this._alphaBlendFuncParams[4*e+0]),dstFactor:ut._GetAphaBlendFactor(this._alphaBlendFuncParams[4*e+1]),operation:ut._GetAphaBlendOperation(this._alphaBlendEqParams[2*e+0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[st.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.ShaderStage))}_setRasterizationState(e,t){const r=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled&&t>1?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==r&&(this._rasterizationState=r,this._states[st.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.RasterizationState))}_setColorStates(){ot[0]=(this._writeMask?1:0)*2**53,ot[1]=(this._depthWriteEnabled?1:0)*2**53,ot[2]=(7&this._colorFormat)*2**50,ot[3]=(56&this._colorFormat)*2**47;let e=0,t=!1;for(let r=0;r<8;r++){if(this._alphaBlendEnabled[r]){const t=4*r+0,s=4*r+1,n=4*r+2,i=4*r+3,a=2*r+0,o=2*r+1,u=null===this._alphaBlendEqParams[a]?0:it[this._alphaBlendEqParams[a]],c=null===this._alphaBlendEqParams[o]?0:it[this._alphaBlendEqParams[o]];ot[e]+=((null===this._alphaBlendFuncParams[t]?1:nt[this._alphaBlendFuncParams[t]])|0)+((null===this._alphaBlendFuncParams[s]?1:nt[this._alphaBlendFuncParams[s]])<<5)+((null===this._alphaBlendFuncParams[n]?1:nt[this._alphaBlendFuncParams[n]])<<10)+((null===this._alphaBlendFuncParams[i]?1:nt[this._alphaBlendFuncParams[i]])<<15)+(u+5*c)*(1<<20)}1&r&&(t=t||this._states[st.ColorStates1+e]!==ot[e],this._states[st.ColorStates1+e]=ot[e],e++)}t&&(this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.ColorStates1))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9)+(this._stencilBackCompare<<12)+(this._stencilBackDepthFailOp<<15)+(this._stencilBackPassOp<<18)+(this._stencilBackFailOp<<21):2421327,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+1024*e;this._depthStencilState!==t&&(this._depthStencilState=t,this._states[st.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let r=st.VertexState;const s=e._pipelineContext,i=s.shaderProcessingContext.attributeNamesFromEffect,a=s.shaderProcessingContext.attributeLocationsFromEffect;let o,u=0;for(let e=0;e<i.length;e++){const t=a[e];let s=(this._overrideVertexBuffers&&this._overrideVertexBuffers[i[e]])??this._vertexBuffers[i[e]];s||(s=this._emptyVertexBuffer,ut.LogErrorIfNoVertexBuffer&&n.Error(`No vertex buffer is provided for the "${i[e]}" attribute. A default empty vertex buffer will be used, but this may generate errors in some browsers.`));const c=s.effectiveBuffer?.underlyingResource;if(void 0===s._validOffsetRange){const e=s.effectiveByteOffset,t=s.getSize(!0),r=s.effectiveByteStride;s._validOffsetRange=e+t<=this._kMaxVertexBufferStride&&0===r||0!==r&&e+t<=r}const h=ut._CanMergeVertexBuffer(o,c,s);h||(this.vertexBuffers[u++]=s,o=s._validOffsetRange?c:null);const l=s.hashCode+(t<<7)+(h?67108864:0),d=s._validOffsetRange?s.effectiveByteOffset:0;if(this._isDirty=this._isDirty||this._states[r]!==l,this._states[r++]=l,0!==d){const e=-d;this._isDirty=this._isDirty||this._states[r]!==e,this._states[r++]=e}}this.vertexBuffers.length=u,this._statesLength=r,this._isDirty=this._isDirty||r!==t,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.VertexState))}_setTextureState(e){this._textureState!==e&&(this._textureState=e,this._states[st.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,st.TextureStage))}_createPipelineLayout(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);const t=[],r=e.shaderProcessingContext.bindGroupLayoutEntries;for(let e=0;e<r.length;e++){const s=r[e];t[e]=this._device.createBindGroupLayout({entries:s})}return e.bindGroupLayouts[0]=t,this._device.createPipelineLayout({bindGroupLayouts:t})}_createPipelineLayoutWithTextureStage(e){const r=e.shaderProcessingContext,s=r.bindGroupLayoutEntries;let n=1;for(let e=0;e<s.length;e++){const i=s[e];for(let a=0;a<i.length;a++){const i=s[e][a];if(i.texture){const a=r.bindGroupLayoutEntryInfo[e][i.binding].name,o=r.availableTextures[a],u=o.autoBindSampler?r.availableSamplers[a+t.AUTOSAMPLERSUFFIX]:null;let c=o.sampleType,h=u?.type??"filtering";if(this._textureState&n&&"depth"!==c&&(o.autoBindSampler&&(h="non-filtering"),c="unfilterable-float"),i.texture.sampleType=c,u){const e=r.bindGroupLayoutEntryInfo[u.binding.groupIndex][u.binding.bindingIndex].index;s[u.binding.groupIndex][e].sampler.type=h}n<<=1}}}const i=[];for(let e=0;e<s.length;++e)i[e]=this._device.createBindGroupLayout({entries:s[e]});return e.bindGroupLayouts[this._textureState]=i,this._device.createPipelineLayout({bindGroupLayouts:i})}_getVertexInputDescriptor(e){const t=[],r=e._pipelineContext,s=r.shaderProcessingContext.attributeNamesFromEffect,n=r.shaderProcessingContext.attributeLocationsFromEffect;let i,a;for(let e=0;e<s.length;e++){const r=n[e];let o=(this._overrideVertexBuffers&&this._overrideVertexBuffers[s[e]])??this._vertexBuffers[s[e]];o||(o=this._emptyVertexBuffer);let u=o.effectiveBuffer?.underlyingResource,c=o.effectiveByteOffset;const h=!o._validOffsetRange;if(!ut._CanMergeVertexBuffer(i,u,o)){const e={arrayStride:o.effectiveByteStride,stepMode:o.getIsInstanced()?"instance":"vertex",attributes:[]};t.push(e),a=e.attributes,h&&(c=0,u=null)}a.push({shaderLocation:r,offset:c,format:ut._GetVertexInputDescriptorFormat(o)}),i=u}return t}static _CanMergeVertexBuffer(e,t,r){return!!e&&e===t&&r._validOffsetRange}_buildRenderPipelineDescriptor(e,t,r){const s=e._pipelineContext,n=this._getVertexInputDescriptor(e),i=this._createPipelineLayout(s),a=[];if(this._vertexBuffers&&function(e,t){const r=t.getEngine(),s=t._pipelineContext;if(!s?.vertexBufferKindToType)return;let n=null;for(const i in e){const a=e[i];if(!a||!tt[i])continue;const o=a.normalized||a.type===d.HALF_FLOAT?d.FLOAT:a.type,u=s.vertexBufferKindToType[i];(o!==d.FLOAT&&void 0===u||void 0!==u&&u!==o)&&(n||(n=r._getShaderProcessingContext(t.shaderLanguage,!1)),s.vertexBufferKindToType[i]=o,o!==d.FLOAT&&(n.vertexBufferKindToNumberOfComponents[i]=p(i),rt(o)&&(n.vertexBufferKindToNumberOfComponents[i]*=-1)))}if(n){const e=r._caps.parallelShaderCompile;r._caps.parallelShaderCompile=void 0,t._processShaderCodeAsync(null,r._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,n),r._caps.parallelShaderCompile=e}}(this._vertexBuffers,e),this._mrtAttachments>0)for(let e=0;e<this._mrtFormats.length;++e){const t=this._mrtFormats[e];if(t){const r={format:t,writeMask:this._mrtEnabledMask&1<<e?this._writeMask:0},s=this._getAphaBlendState(e<this._numAlphaBlendTargetsEnabled?e:0),n=this._getColorBlendState(e<this._numAlphaBlendTargetsEnabled?e:0);s&&n&&(r.blend={alpha:s,color:n}),a.push(r)}else a.push(null)}else if(this._webgpuColorFormat[0]){const e={format:this._webgpuColorFormat[0],writeMask:this._writeMask},t=this._getAphaBlendState(0),r=this._getColorBlendState(0);t&&r&&(e.blend={alpha:t,color:r}),a.push(e)}else a.push(null);const o={compare:ut._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:ut._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:ut._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:ut._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)},u={compare:ut._GetCompareFunction(this._stencilEnabled?this._stencilBackCompare:7),depthFailOp:ut._GetStencilOpFunction(this._stencilEnabled?this._stencilBackDepthFailOp:1),failOp:ut._GetStencilOpFunction(this._stencilEnabled?this._stencilBackFailOp:1),passOp:ut._GetStencilOpFunction(this._stencilEnabled?this._stencilBackPassOp:1)},c="triangle-list"===t||"triangle-strip"===t;let h;"line-strip"!==t&&"triangle-strip"!==t||(h=!this.indexBuffer||this.indexBuffer.is32Bits?"uint32":"uint16");const l=!!this._webgpuDepthStencilFormat&&G.HasStencilAspect(this._webgpuDepthStencilFormat),_={topology:t,frontFace:1===this._frontFace?"ccw":"cw",cullMode:this._cullEnabled?2===this._cullFace?"front":"back":"none"};return h&&(_.stripIndexFormat=h),{label:`RenderPipeline_${a[0]?.format??"nooutput"}_${this._webgpuDepthStencilFormat??"nodepth"}_samples${r}_textureState${this._textureState}`,layout:i,vertex:{module:s.stages.vertexStage.module,entryPoint:s.stages.vertexStage.entryPoint,buffers:n},primitive:_,fragment:s.stages.fragmentStage?{module:s.stages.fragmentStage.module,entryPoint:s.stages.fragmentStage.entryPoint,targets:a}:void 0,multisample:{count:r},depthStencil:void 0===this._webgpuDepthStencilFormat?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?ut._GetCompareFunction(this._depthCompare):"always",format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&l?o:void 0,stencilBack:this._stencilEnabled&&l?u:void 0,stencilReadMask:this._stencilEnabled&&l?this._stencilReadMask:4294967295,stencilWriteMask:this._stencilEnabled&&l?this._stencilWriteMask:4294967295,depthBias:this._depthBias,depthBiasClamp:c?this._depthBiasClamp:0,depthBiasSlopeScale:c?this._depthBiasSlopeScale:0}}}_createRenderPipeline(e,t,r){return this._device.createRenderPipeline(this._buildRenderPipelineDescriptor(e,t,r))}preWarmPipeline(e,t,r,s=0){r=G.GetSample(r);if(this._lookupRenderPipeline(e,t,r,s))return null;const n=ut._GetTopology(e),i={token:this._parameter.token,pipeline:null};return this._device.createRenderPipelineAsync(this._buildRenderPipelineDescriptor(t,n,r)).then(e=>(i.pipeline=e,this._setRenderPipeline(i),ut.NumCacheMiss++,e))}}ut.LogErrorIfNoVertexBuffer=!1,ut.NumCacheHitWithoutHash=0,ut.NumCacheHitWithHash=0,ut.NumCacheMiss=0,ut.NumPipelineCreationLastFrame=0,ut._NumPipelineCreationCurrentFrame=0;class ct{constructor(){this.values={}}count(){let e=0,t=this.pipeline?1:0;for(const r in this.values){const s=this.values[r],[n,i]=s.count();e+=n,t+=i,e++}return[e,t]}}class ht extends ut{static GetNodeCounts(){const e=ht._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}}static _GetPipelines(e,t,r,s){if(e.pipeline){const e=r.slice();e.length=s,t.push(e)}for(const n in e.values){const i=e.values[n];r[s]=parseInt(n),ht._GetPipelines(i,t,r,s+1)}}static GetPipelines(){const e=[];return ht._GetPipelines(ht._Cache,e,[],0),e}static ResetCache(){ht._Cache=new ct}reset(){this._nodeStack=[],this._nodeStack[0]=ht._Cache,super.reset()}_getRenderPipeline(e){let t=this._nodeStack[this._stateDirtyLowestIndex];for(let e=this._stateDirtyLowestIndex;e<this._statesLength;++e){let r=t.values[this._states[e]];r||(r=new ct,t.values[this._states[e]]=r),t=r,this._nodeStack[e+1]=t}e.token=t,e.pipeline=t.pipeline}_setRenderPipeline(e){e.token.pipeline=e.pipeline}}ht._Cache=new ct;class lt extends _{constructor(e){super(!1),this._cache=e,this.reset()}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))}get backFunc(){return this._backFunc}set backFunc(e){this._backFunc!==e&&(this._backFunc=e,this._cache.setStencilBackCompare(e))}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail!==e&&(this._backOpStencilFail=e,this._cache.setStencilBackFailOp(e))}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail!==e&&(this._backOpDepthFail=e,this._cache.setStencilBackDepthFailOp(e))}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass!==e&&(this._backOpStencilDepthPass=e,this._cache.setStencilBackPassOp(e))}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))}reset(){super.reset(),this._cache.resetStencilState()}apply(){const e=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=e?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.mask=e?this.stencilMaterial.mask:this.stencilGlobal.mask,this.funcRef=e?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=e?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.func=e?this.stencilMaterial.func:this.stencilGlobal.func,this.opStencilFail=e?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=e?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=e?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.backFunc=e?this.stencilMaterial.backFunc:this.stencilGlobal.backFunc,this.backOpStencilFail=e?this.stencilMaterial.backOpStencilFail:this.stencilGlobal.backOpStencilFail,this.backOpDepthFail=e?this.stencilMaterial.backOpDepthFail:this.stencilGlobal.backOpDepthFail,this.backOpStencilDepthPass=e?this.stencilMaterial.backOpStencilDepthPass:this.stencilGlobal.backOpStencilDepthPass)}}class dt extends g{constructor(e){super(!1),this._cache=e,this.reset()}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(e??1))}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(e??2))}reset(){super.reset(),this._cache.resetDepthCullingState()}apply(){}}class pt{static IsExternalTexture(e){return void 0!==e.underlyingResource}getClassName(){return"ExternalTexture"}get underlyingResource(){return this._video}constructor(e){this.useMipMaps=!1,this.type=t.TEXTURETYPE_UNDEFINED,this.format=t.TEXTUREFORMAT_UNDEFINED,this._video=e,this.uniqueId=m._Counter++}isReady(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA}dispose(){}}class _t{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.useVertexPulling=!1,this.uniqueId=_t._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let r=this.samplers[e],s=-1;r?s=r.hashCode:this.samplers[e]=r={sampler:t,hashCode:0},r.sampler=t,r.hashCode=t?et.GetSamplerHashCode(t):0;const n=s!==r.hashCode;n&&this.updateId++,this.isDirty||=n}setTexture(e,r){let s=this.textures[e],n=-1;s?n=s.texture?.uniqueId??-1:this.textures[e]=s={texture:r,isFloatOrDepthTexture:!1,isExternalTexture:!1},s.isExternalTexture&&this._numExternalTextures--,s.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,r?(s.isFloatOrDepthTexture=r.type===t.TEXTURETYPE_FLOAT||r.format>=t.TEXTUREFORMAT_DEPTH24_STENCIL8&&r.format<=t.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8,s.isExternalTexture=pt.IsExternalTexture(r),s.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,s.isExternalTexture&&this._numExternalTextures++):(s.isFloatOrDepthTexture=!1,s.isExternalTexture=!1),s.texture=r;const i=n!==(r?.uniqueId??-1);i&&this.updateId++,this.isDirty||=i}}_t._Counter=0;class gt{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get enableIndirectDraw(){return this._enableIndirectDraw}set enableIndirectDraw(e){this._enableIndirectDrawInCompatMode=!0,this._enableIndirectDraw!==e&&(this._enableIndirectDraw=e,e||this._useInstancing||!this.indirectDrawBuffer?e&&!this.indirectDrawBuffer&&(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,V.CopyDst|V.Indirect|V.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0))}get useInstancing(){return this._useInstancing}set useInstancing(e){if(this._useInstancing===e)return;this._useInstancing=e,this._currentInstanceCount=-1;const t=this._enableIndirectDrawInCompatMode;this.enableIndirectDraw=e,this._enableIndirectDrawInCompatMode=t}constructor(e,t){this._dummyIndexBuffer=t,this._enableIndirectDrawInCompatMode=!1,this._bufferManager=e,this.uniqueId=gt._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this._enableIndirectDraw=!1,this._vertexPullingEnabled=!1,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0,this._vertexPullingEnabled=!1}setBuffer(e,t){this._isDirty||=t?.uniqueId!==this.buffers[e]?.uniqueId,this.buffers[e]=t}setIndirectData(e,t,r,s=!1){(s||t!==this._currentInstanceCount)&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=r,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}setVertexPulling(e,t,r,s,n){if(this._vertexPullingEnabled===e)return;this._vertexPullingEnabled=e,this._isDirty=!0;const i=t.shaderProcessingContext.bufferNames;if(n)for(const t in n){const r=n[t];if(!r||-1===i.indexOf(t))continue;const s=r.effectiveBuffer;this.setBuffer(t,e?s:null)}for(const t in r){if(n&&t in n)continue;const s=r[t];if(!s||-1===i.indexOf(t))continue;const a=s.effectiveBuffer;this.setBuffer(t,e?a:null)}-1!==i.indexOf("indices")&&this.setBuffer("indices",e?s??this._dummyIndexBuffer:null)}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0,this._enableIndirectDraw=!1}}gt._Counter=0;const mt=2**35;class ft{constructor(){this.values={}}}class bt{static get Statistics(){return{totalCreated:bt.NumBindGroupsCreatedTotal,lastFrameCreated:bt.NumBindGroupsCreatedLastFrame,lookupLastFrame:bt.NumBindGroupsLookupLastFrame,noLookupLastFrame:bt.NumBindGroupsNoLookupLastFrame}}static ResetCache(){bt._Cache=new ft,bt.NumBindGroupsCreatedTotal=0,bt.NumBindGroupsCreatedLastFrame=0,bt.NumBindGroupsLookupLastFrame=0,bt.NumBindGroupsNoLookupLastFrame=0,bt._NumBindGroupsCreatedCurrentFrame=0,bt._NumBindGroupsLookupCurrentFrame=0,bt._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,r){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=r}endFrame(){bt.NumBindGroupsCreatedLastFrame=bt._NumBindGroupsCreatedCurrentFrame,bt.NumBindGroupsLookupLastFrame=bt._NumBindGroupsLookupCurrentFrame,bt.NumBindGroupsNoLookupLastFrame=bt._NumBindGroupsNoLookupCurrentFrame,bt._NumBindGroupsCreatedCurrentFrame=0,bt._NumBindGroupsLookupCurrentFrame=0,bt._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,r){let s,i=bt._Cache;const a=this.disabled||r.forceBindGroupCreation;if(!a){if(!t.isDirty(r.updateId)&&!r.isDirty)return bt._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const r of e.shaderProcessingContext.bufferNames){const e=(t.buffers[r]?.uniqueId??0)+1048576;let s=i.values[e];s||(s=new ft,i.values[e]=s),i=s}for(const t of e.shaderProcessingContext.samplerNames){const e=r.samplers[t]?.hashCode??0;let s=i.values[e];s||(s=new ft,i.values[e]=s),i=s}for(const t of e.shaderProcessingContext.textureNames){const e=(r.textures[t]?.texture?.uniqueId??0)+mt;let s=i.values[e];s||(s=new ft,i.values[e]=s),i=s}s=i.bindGroups}if(t.resetIsDirty(r.updateId),r.isDirty=!1,s)return t.bindGroups=s,bt._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,a||(i.bindGroups=s),bt.NumBindGroupsCreatedTotal++,bt._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[r.textureState];for(let i=0;i<e.shaderProcessingContext.bindGroupLayoutEntries.length;i++){const a=e.shaderProcessingContext.bindGroupLayoutEntries[i],u=e.shaderProcessingContext.bindGroupEntries[i];for(let s=0;s<a.length;s++){const a=e.shaderProcessingContext.bindGroupLayoutEntries[i][s],o=e.shaderProcessingContext.bindGroupLayoutEntryInfo[i][a.binding],c=o.nameInArrayOfTexture??o.name;if(a.sampler){const e=r.samplers[c];if(e){const t=e.sampler;if(!t){this._engine.dbgSanityChecks&&n.Error(`Trying to bind a null sampler! entry=${JSON.stringify(a)}, name=${c}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${r.uniqueId}`,50);continue}u[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else n.Error(`Sampler "${c}" not found in the material context. Make sure you bound it. entry=${JSON.stringify(a)}, materialContext=${JSON.stringify(r,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(a.texture||a.storageTexture){const e=r.textures[c];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){n.Error(`Trying to bind a null texture! name="${c}", entry=${JSON.stringify(a)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${r.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||a.texture&&!t.view||a.storageTexture&&!t.viewForWriting)){n.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(a)}, name=${c}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${r.uniqueId}`,50);continue}u[s].resource=a.storageTexture?t.viewForWriting:t.view}else n.Error(`Texture "${c}" not found in the material context. Make sure you bound it (something like effect.setTexture("${c}", texture)). entry=${JSON.stringify(a)}, materialContext=${JSON.stringify(r,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(a.externalTexture){const e=r.textures[c];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){n.Error(`Trying to bind a null external texture! entry=${JSON.stringify(a)}, name=${c}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${r.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){n.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(a)}, name=${c}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${r.uniqueId}`,50);continue}u[s].resource=this._device.importExternalTexture({source:t})}else n.Error(`External texture "${c}" not found in the material context. Make sure you bound it. entry=${JSON.stringify(a)}, materialContext=${JSON.stringify(r,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(a.buffer){const e=t.buffers[c];if(e){const t=e.underlyingResource;u[s].resource.buffer=t,u[s].resource.size=e.capacity}else n.Error(`Can't find buffer "${c}" in the draw context. Make sure you bound it. entry=${JSON.stringify(a)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const c=o[i];s[i]=this._device.createBindGroup({layout:c,entries:u})}return s}}bt.NumBindGroupsCreatedTotal=0,bt.NumBindGroupsCreatedLastFrame=0,bt.NumBindGroupsLookupLastFrame=0,bt.NumBindGroupsNoLookupLastFrame=0,bt._Cache=new ft,bt._NumBindGroupsCreatedCurrentFrame=0,bt._NumBindGroupsLookupCurrentFrame=0,bt._NumBindGroupsNoLookupCurrentFrame=0;class xt{constructor(){this._cache=new WeakMap}getView(e,t){let r=this._cache.get(e);r||(r=new Map,this._cache.set(e,r));const s=xt._GetKey(t);let n=r.get(s);return n||(n=e.createView(t),r.set(s,n)),n}static _GetKey(e){return`${e.format}_${e.dimension}_${e.baseMipLevel}_${e.mipLevelCount}_${e.baseArrayLayer}_${e.arrayLayerCount}_${e.aspect}_${e.usage}_${e.swizzle}`}}class Tt{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,r){this._cacheRenderPipeline.setMRT(t,r),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,r){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new ht(this._device,r),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,1,async()=>{await Promise.all([import("./clearQuad.vertex-CdU-16Tw.esm.min.js"),import("./clearQuad.fragment-CiEkcQah.esm.min.js")])})}clear(e,r,s,n,i=1){let a,o,u=null;const c=!!this._engine._currentRenderTarget;if(e)a=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t<this._cacheRenderPipeline.colorFormats.length;++t)this._keyTemp[e++]=Ye[this._cacheRenderPipeline.colorFormats[t]??""];const t=Ye[this._depthTextureFormat??0];if(this._keyTemp[e]=(r?r.r+256*r.g+256*r.b*256+256*r.a*256*256:0)+(s?2**32:0)+(n?2**33:0)+(this._engine.useReverseDepthBuffer?2**34:0)+(c?2**35:0)+(i>1?2**36:0)+t*2**37,o=this._keyTemp.join("_"),u=this._bundleCache[o],u)return u;a=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:G.GetSample(i)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!s),this._cacheRenderPipeline.setStencilEnabled(!!n&&!!this._depthTextureFormat&&G.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(n?255:0),this._cacheRenderPipeline.setStencilCompare(n?t.ALWAYS:t.NEVER),this._cacheRenderPipeline.setStencilPassOp(n?t.REPLACE:t.KEEP),this._cacheRenderPipeline.setWriteMask(r?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(t.MATERIAL_TriangleStripDrawMode,this._effect,i),l=this._effect._pipelineContext;r&&this._effect.setDirectColor4("color",r),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),l.uniformBuffer.update();const d=c?this._engine._ubInvertY:this._engine._ubDontInvertY,p=l.uniformBuffer.getBuffer(),_=p.uniqueId+"-"+d.uniqueId;let g=this._bindGroups[_];if(!g){const e=l.bindGroupLayouts[0];g=this._bindGroups[_]=[],g.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${_}`,layout:e[0],entries:[]})),we._SimplifiedKnownBindings||g.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${_}`,layout:e[1],entries:[]})),g.push(this._device.createBindGroup({label:`clearQuadBindGroup${we._SimplifiedKnownBindings?1:2}-${_}`,layout:e[we._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:d.underlyingResource,size:d.capacity}},{binding:1,resource:{buffer:p.underlyingResource,size:p.capacity}}]}))}a.setPipeline(h);for(let e=0;e<g.length;++e)a.setBindGroup(e,g[e]);return a.draw(4,1,0,0),e||(u=a.finish(),this._bundleCache[o]=u),u}}class yt{constructor(e,t,r,s){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(r),this.h=Math.floor(s)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new yt(this.x,this.y,this.w,this.h)}}class Et{constructor(e,t,r,s){this.x=e,this.y=t,this.w=r,this.h=s}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new Et(this.x,this.y,this.w,this.h)}}class St{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new St(this.ref)}}class Rt{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new Rt(this.color)}}class Ct{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new Ct(this.query)}}class At{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new At}}class vt{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){const e=new vt;return e.bundles=this.bundles,e}}class It{constructor(e){this.numDrawCalls=0,this._device=e,this._list=new Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){const e=new vt;this._list[this._listLength++]=e,this._currentBundleList=e.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,r){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:G.GetSample(r)})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t<this._listLength;++t)this._list[t].run(e)}reset(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0}clone(){this.close();const e=new It(this._device);e._list=new Array(this._listLength),e._listLength=this._listLength,e.numDrawCalls=this.numDrawCalls;for(let t=0;t<this._listLength;++t)e._list[t]=this._list[t].clone();return e}}class wt{get querySet(){return this._querySet}constructor(e,t,r,s,n,i=!0,a){this._dstBuffers=[],this._engine=e,this._device=s,this._bufferManager=n,this._count=t,this._canUseMultipleBuffers=i,this._querySet=s.createQuerySet({label:a??"QuerySet",type:r,count:t}),this._queryBuffer=n.createRawBuffer(8*t,V.QueryResolve|V.CopySrc,void 0,"QueryBuffer"),i||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,V.MapRead|V.CopyDst,void 0,"QueryBufferNoMultipleBuffers"))}_getBuffer(e,t){if(!this._canUseMultipleBuffers&&0===this._dstBuffers.length)return null;const r=this._device.createCommandEncoder();let s;return 0===this._dstBuffers.length?s=this._bufferManager.createRawBuffer(8*this._count,V.MapRead|V.CopyDst,void 0,"QueryBufferAdditionalBuffer"):(s=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),r.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),r.copyBufferToBuffer(this._queryBuffer,0,s,0,8*t),this._device.queue.submit([r.finish()]),s}async readValues(e=0,t=1){const r=this._getBuffer(e,t);if(null===r)return null;const s=this._engine.uniqueId;try{await r.mapAsync(1);const e=new BigUint64Array(r.getMappedRange()).slice();return r.unmap(),this._dstBuffers[this._dstBuffers.length]=r,e}catch(e){if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const r=this._engine.uniqueId;try{await t.mapAsync(1);const e=new BigUint64Array(t.getMappedRange()),r=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}catch(e){if(this._engine.isDisposed||this._engine.uniqueId!==r)return 0;throw e}}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const r=this._engine.uniqueId;try{await t.mapAsync(1);const e=new BigUint64Array(t.getMappedRange()),r=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}catch(e){if(this._engine.isDisposed||this._engine.uniqueId!==r)return 0;throw e}}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])}}class Bt{get gpuFrameTimeCounter(){return this._gpuFrameTimeCounter}constructor(e,t,s){this._enabled=!1,this._gpuFrameTimeCounter=new r,this._measureDurationState=0,this._engine=e,this._device=t,this._bufferManager=s}get enable(){return this._enabled}set enable(e){if(this._enabled!==e)if(this._enabled=e,this._measureDurationState=0,e)try{this._measureDuration=new Pt(this._engine,this._device,this._bufferManager,2e3,"QuerySet_TimestampQuery")}catch(e){return this._enabled=!1,void n.Error("Could not create a WebGPUDurationMeasure!\nError: "+e.message+"\nMake sure timestamp query is supported and enabled in your browser.")}else this._measureDuration.dispose()}startFrame(e){this._enabled&&0===this._measureDurationState&&(this._measureDuration.start(e),this._measureDurationState=1)}endFrame(e){1===this._measureDurationState&&(this._measureDurationState=2,this._measureDuration.stop(e).then(e=>{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const r=this._engine.frameId;this._measureDuration.stopPass(e).then(e=>{t._addDuration(r,null!==e&&e>0?e:0)})}dispose(){this._measureDuration?.dispose()}}class Pt{constructor(e,t,r,s=2,n){this._count=s,this._querySet=new wt(e,s,"timestamp",t,r,!0,n)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?await this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return await this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Ft{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,r,s=50,n=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=r,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=n,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e<this._lastBuffer.length}getQueryResult(e){return Number(this._lastBuffer?.[e]??-1)}_retrieveQueryBuffer(){this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer!==this._engine.frameId&&(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then(e=>{this._lastBuffer=e}))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new wt(this._engine,this._currentTotalIndices,"occlusion",this._device,this._bufferManager,!1,"QuerySet_OcclusionQuery_count_"+this._currentTotalIndices),this._frameQuerySetIsDirty=this._engine.frameId}_delayQuerySetDispose(){const e=this._querySet;e&&setTimeout(()=>e.dispose,1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Dt{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&n.Log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&n.Log("End of inlining process.")}_collectFunctions(){let e=0;for(;e<this._sourceCode.length;){const t=this._sourceCode.indexOf(this.inlineToken,e);if(t<0)break;const r=this._sourceCode.indexOf("(",t+this.inlineToken.length);if(r<0){this.debug&&n.Warn(`Could not find the opening parenthesis after the token. startIndex=${e}`),e=t+this.inlineToken.length;continue}const s=Dt._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t+this.inlineToken.length,r));if(!s){this.debug&&n.Warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(t+this.inlineToken.length,r)}`),e=t+this.inlineToken.length;continue}const[i,a]=[s[3],s[4]],o=Be("(",")",this._sourceCode,r);if(o<0){this.debug&&n.Warn(`Could not extract the parameters the function '${a}' (type=${i}). funcParamsStartIndex=${r}`),e=t+this.inlineToken.length;continue}const u=this._sourceCode.substring(r+1,o),c=Pe(this._sourceCode,o+1);if(c===this._sourceCode.length){this.debug&&n.Warn(`Could not extract the body of the function '${a}' (type=${i}). funcParamsEndIndex=${o}`),e=t+this.inlineToken.length;continue}const h=Be("{","}",this._sourceCode,c);if(h<0){this.debug&&n.Warn(`Could not extract the body of the function '${a}' (type=${i}). funcBodyStartIndex=${c}`),e=t+this.inlineToken.length;continue}const l=this._sourceCode.substring(c,h+1),d=De(u).split(","),p=[];for(let e=0;e<d.length;++e){const t=d[e].trim(),r=t.lastIndexOf(" ");r>=0&&p.push(t.substring(r+1))}"void"!==i&&p.push("return"),this._functionDescr.push({name:a,type:i,parameters:p,body:l,callIndex:0}),e=h+1;const _=t>0?this._sourceCode.substring(0,t):"",g=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";this._sourceCode=_+g,e-=h+1-t}this.debug&&n.Log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=${this._functionDescr}`)}_processInlining(e=20){for(;e-- >=0&&this._replaceFunctionCallsByCode(););return this.debug&&n.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:r,type:s,parameters:i,body:a}=t;let o=0;for(;o<this._sourceCode.length;){const u=this._sourceCode.indexOf(r,o);if(u<0)break;if(0===u||Fe(this._sourceCode.charAt(u-1))){o=u+r.length;continue}const c=Pe(this._sourceCode,u+r.length);if(c===this._sourceCode.length||"("!==this._sourceCode.charAt(c)){o=u+r.length;continue}const h=Be("(",")",this._sourceCode,c);if(h<0){this.debug&&n.Warn(`Could not extract the parameters of the function call. Function '${r}' (type=${s}). callParamsStartIndex=${c}`),o=u+r.length;continue}const l=this._sourceCode.substring(c+1,h),d=e=>{const t=[];let r=0,s=0;for(;r<e.length;){if("("===e.charAt(r)){const t=Be("(",")",e,r);if(t<0)return null;r=t}else","===e.charAt(r)&&(t.push(e.substring(s,r)),s=r+1);r++}return s<r&&t.push(e.substring(s,r)),t},p=d(De(l));if(null===p){this.debug&&n.Warn(`Invalid function call: can't extract the parameters of the function call. Function '${r}' (type=${s}). callParamsStartIndex=${c}, callParams=`+l),o=u+r.length;continue}const _=[];for(let e=0;e<p.length;++e){const t=p[e].trim();_.push(t)}const g="void"!==s?r+"_"+t.callIndex++:null;if(g&&_.push(g+" ="),_.length!==i.length){this.debug&&n.Warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${r}' (type=${s}). function parameters=${i}, call parameters=${_}`),o=u+r.length;continue}o=h+1;const m=this._replaceNames(a,i,_);let f=u>0?this._sourceCode.substring(0,u):"";const b=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";if(g){const e=Le(this._sourceCode,u-1,"\n","{");f=this._sourceCode.substring(0,e+1);const t=this._sourceCode.substring(e+1,u);this._sourceCode=f+s+" "+g+";\n"+m+"\n"+t+g+b,this.debug&&n.Log(`Replace function call by code. Function '${r}' (type=${s}). injectDeclarationIndex=${e}, call parameters=${_}`)}else this._sourceCode=f+m+b,o+=m.length-(h+1-u),this.debug&&n.Log(`Replace function call by code. Function '${r}' (type=${s}). functionCallIndex=${u}, call parameters=${_}`);e=!0}}return e}_replaceNames(e,t,r){for(let s=0;s<t.length;++s){const n=new RegExp(Me(t[s]),"g"),i=t[s].length,a=r[s];e=e.replace(n,(r,...n)=>{const o=n[0];return Fe(e.charAt(o-1))||Fe(e.charAt(o+i))?t[s]:a})}return e}}Dt._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class Lt{async initTwgsl(e){if(!Lt._Twgsl)if(e=e||{},(e={...Lt._TwgslDefaultOptions,...e}).twgsl)Lt._Twgsl=e.twgsl;else{if(e.jsPath&&e.wasmPath&&await f.LoadBabylonScriptAsync(e.jsPath),!self.twgsl)throw new Error("twgsl is not available.");Lt._Twgsl=await self.twgsl(f.GetBabylonScriptURL(e.wasmPath))}}convertSpirV2WGSL(e,t=!1){const r=Lt._Twgsl.convertSpirV2WGSL(e,Lt.DisableUniformityAnalysis||t);return Lt.ShowWGSLShaderCode&&(n.Log(r),n.Log("***********************************************")),Lt.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+r:r}}Lt._TwgslDefaultOptions={jsPath:`${f._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${f._DefaultCdnUrl}/twgsl/twgsl.wasm`},Lt.ShowWGSLShaderCode=!1,Lt.DisableUniformityAnalysis=!1,Lt._Twgsl=null;class Mt{constructor(e,t,r){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this.showDebugLogs=!1,this._engine=e,this._mode=t,this._bundleList=r}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._log("enabled",`activate=${e}, mode=${this._mode}`),this._allBundleLists.length=0,this._record&&(this._mode=this._modeSaved),this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=t.SNAPSHOTRENDERING_STANDARD)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let r=null;return this._record?(r=this._bundleList.clone(),this._allBundleLists.push(r),this._bundleList.reset(),this._log("endRenderPass","bundleList recorded at position #"+(this._allBundleLists.length-1))):this._playBundleListIndex>=this._allBundleLists.length?this._log("endRenderPass",`empty or out-of-sync bundleList (_allBundleLists.length=${this._allBundleLists.length}, playBundleListIndex=${this._playBundleListIndex})`):(this._log("endRenderPass",`run bundleList #${this._playBundleListIndex}`),r=this._allBundleLists[this._playBundleListIndex++]),r&&(r.run(e),this._mode===t.SNAPSHOTRENDERING_FAST&&this._engine._reportDrawCall(r.numDrawCalls)),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved,this._log("endFrame","bundles recorded, switching to play mode")),this._playBundleListIndex=0}reset(){this._log("reset","called"),this.enabled=!1,this.enabled=!0}_log(e,t){this.showDebugLogs&&n.Log(`[Frame: ${this._engine.frameId}] WebGPUSnapshotRendering:${e} - ${t}`)}}class Gt extends pt{constructor(e){super(e)}}const Ut={label:"TextureView_SwapChain_ResolveTarget",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},Ot={label:"TextureView_SwapChain",dimension:"2d",format:void 0,mipLevelCount:1,arrayLayerCount:1},Nt=new S;class $t extends O{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return b(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return n.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const r=new $t(e,t);return new Promise(e=>{r.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(r))})}constructor(e,t={}){x(),T(),super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._glslangAndTintAreFullyLoaded=!1,this._adapterInfo={vendor:"",architecture:"",device:"",description:"",subgroupMinSize:0,subgroupMaxSize:0,isFallbackAdapter:!1},this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._currentVertexBuffers={},this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this._internalFrameCounter=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._workingGlslangAndTintPromise=null,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new y,this._name="WebGPU",this._drawCalls=new r,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,this._enableGPUDebugMarkers=t.enableGPUDebugMarkers,n.Log(`Babylon.js v${s.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new Ue,this._shaderProcessorWGSL=new $e):n.Error("WebGPU is not supported by your browser.")}prepareGlslangAndTintAsync(){return this._workingGlslangAndTintPromise||(this._workingGlslangAndTintPromise=new Promise(e=>{this._initGlslangAsync(this._glslangOptions??this._options?.glslangOptions).then(t=>{this._glslang=t,this._tintWASM=new Lt,this._tintWASM.initTwgsl(this._twgslOptions??this._options?.twgslOptions).then(()=>{this._glslangAndTintAreFullyLoaded=!0,e()})})})),this._workingGlslangAndTintPromise}initAsync(e,r){return this.uniqueId=$t._InstanceId++,this._glslangOptions=e,this._twgslOptions=r,navigator.gpu.requestAdapter(this._options).then(async e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach(e=>{this._adapterSupportedExtensions.push(e)}),this._adapterSupportedLimits=this._adapter.limits,this._adapterInfo=this._adapter.info;const t=this._options.deviceDescriptor??{},r=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(r){const e=r,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,await this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null or undefined)."}).then(e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach(e=>{this._deviceEnabledExtensions.push(e)}),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",e=>{++t<this.numMaxUncapturedErrors?n.Warn(`[Frame ${this._frameId}] WebGPU uncaptured error (${t+1}): ${e.error} - ${e.error.message}`):t++===this.numMaxUncapturedErrors&&n.Warn(`[Frame ${this._frameId}] WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`)}),this._doNotHandleContextLost||this._device.lost?.then(e=>{this._isDisposed||(this._contextWasLost=!0,n.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,r=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,n=this.disableCacheBindGroups,i=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=r,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=n,this.enableGPUTimingMeasurements=i,this._currentRenderPass=null}))})}).then(()=>{this._initializeLimits(),this._bufferManager=new Ke(this,this._device),this._textureHelper=new ze(this,this._device,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new et(this._device),this._cacheBindGroups=new bt(this._device,this._cacheSampler,this),this._cacheTextureViews=new xt,this._timestampQuery=new Bt(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Ft(this,this._device,this._bufferManager):void 0,this._bundleList=new It(this._device),this._snapshotRendering=new Mt(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),V.Uniform|V.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),V.Uniform|V.CopyDst,"UBDontInvertY");const e=this._internalFrameCounter++;this._uploadEncoderDescriptor.label=`[${this.frameId}|${e}] - UploadEncoder`,this._renderEncoderDescriptor.label=`[${this.frameId}|${e}] - RenderEncoder`,this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._emptyVertexBuffer=new d(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._dummyIndexBuffer=this._bufferManager.createBuffer(new Uint16Array([0,0,0,0]),V.Storage|V.CopyDst,"DummyIndices"),this._cacheRenderPipeline=new ht(this._device,this._emptyVertexBuffer),this._depthCullingState=new dt(this._cacheRenderPipeline),this._stencilStateComposer=new lt(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=t.LEQUAL,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new Tt(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(e=>{throw n.Error("A fatal error occurred during WebGPU creation/initialization."),e})}_initGlslangAsync(e){if(e=e||{},(e={...$t._GlslangDefaultOptions,...e}).glslang)return e.glslang;if(self.glslang)return self.glslang(e.wasmPath);if(e.jsPath&&e.wasmPath)return f.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(f.GetBabylonScriptURL(e.wasmPath)));throw new Error("glslang is not available")}_initializeLimits(){const e=this._deviceEnabledExtensions.indexOf("texture-formats-tier1")>=0;this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxDrawBuffers:8,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxUniformBuffersPerShaderStage:this._deviceLimits.maxUniformBuffersPerShaderStage,shaderFloatPrecision:23,standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf("texture-compression-astc")>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf("texture-compression-etc2")>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf("texture-compression-bc")>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,blendFloat:this._deviceEnabledExtensions.indexOf("float32-blendable")>=0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf("rg11b10ufloat-renderable")>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf("float32-filterable")>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf("timestamp-query")||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1,textureNorm16:e,blendParametersPerTarget:!0,dualSourceBlending:this._deviceEnabledExtensions.includes("dual-source-blending"),supportReadWriteStorageTextures:"undefined"!=typeof navigator&&!0===navigator.gpu?.wgslLanguageFeatures?.has("readonly_and_readwrite_storage_textures")},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportIBLShadows:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0},this._alphaState=new E(this._caps.blendParametersPerTarget)}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new We(this)],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._options.swapChainFormat,usage:16};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:"2d",format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new S(0,0,0,1),loadOp:"clear",storeOp:"store"}]}else t=[{view:void 0,clearValue:new S(0,0,0,1),loadOp:"clear",storeOp:"store"}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?"depth24plus-stencil8":"depth32float",this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const r={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:"2d",format:this._mainRenderPassWrapper.depthTextureFormat,usage:16};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(r);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:"2d",format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:"clear",depthStoreOp:"store",stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?"clear":void 0,stencilStoreOp:this.isStencilEnable?"store":void 0},n=this._internalFrameCounter++;this._mainRenderPassWrapper.renderPassDescriptor={label:`[${this.frameId}|${n}] - MainRenderPass`,colorAttachments:t,depthStencilAttachment:s},this.beginFrame(),this._startMainRenderPass(!0,null,!0,!1),this._endCurrentRenderPass(),this._frameId--,this.endFrame()}_sharedInit(e){super._sharedInit(e),R(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:17,alphaMode:this.premultipliedAlpha?"premultiplied":"opaque"})}resizeImageBitmap(e,t,r){return C(this,e,t,r)}async _createImageBitmapFromSource(e,t){return await A(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&v(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&I()}enterPointerlock(){this._renderingCanvas&&w(this._renderingCanvas)}exitPointerlock(){B()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){ht.ResetCache(),bt.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const r=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&r.push(e);this._uniformBuffers=r,super._restoreEngineAfterContextLost(e)}setSize(e,t,r=!1){return!!super.setSize(e,t,r)&&(this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0)}_getShaderProcessor(e){return 1===e?this._shaderProcessorWGSL:this._shaderProcessor}_getShaderProcessingContext(e,t){return new we(e,t)}_getCurrentRenderPass(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass}_getCurrentRenderPassWrapper(){return this._currentRenderTarget?this._rttRenderPassWrapper:this._mainRenderPassWrapper}applyStates(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState._alphaBlend,this._alphaState._numTargetEnabled)}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=t.LEQUAL,this._alphaState.reset(),this._resetAlphaMode(),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState._alphaBlend,this._alphaState._numTargetEnabled),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}setColorWrite(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)}getColorWrite(){return this._colorWriteLocal}_mustUpdateViewport(){const e=this._viewportCached.x,t=this._viewportCached.y,r=this._viewportCached.z,s=this._viewportCached.w,n=this._viewportsCurrent.x!==e||this._viewportsCurrent.y!==t||this._viewportsCurrent.w!==r||this._viewportsCurrent.h!==s;return n&&(this._viewportsCurrent.x=this._viewportCached.x,this._viewportsCurrent.y=this._viewportCached.y,this._viewportsCurrent.w=this._viewportCached.z,this._viewportsCurrent.h=this._viewportCached.w),n}_applyViewport(e){const t=Math.floor(this._viewportCached.x),r=Math.floor(this._viewportCached.z),s=Math.floor(this._viewportCached.w);let n=Math.floor(this._viewportCached.y);this._currentRenderTarget||(n=this.getRenderHeight(!0)-n-s),e?e.addItem(new yt(t,n,r,s)):this._getCurrentRenderPass().setViewport(t,n,r,s,0,1)}_viewport(e,t,r,s){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=r,this._viewportCached.w=s}_mustUpdateScissor(){const e=this._scissorCached.x,t=this._scissorCached.y,r=this._scissorCached.z,s=this._scissorCached.w,n=this._scissorsCurrent.x!==e||this._scissorsCurrent.y!==t||this._scissorsCurrent.w!==r||this._scissorsCurrent.h!==s;return n&&(this._scissorsCurrent.x=this._scissorCached.x,this._scissorsCurrent.y=this._scissorCached.y,this._scissorsCurrent.w=this._scissorCached.z,this._scissorsCurrent.h=this._scissorCached.w),n}_applyScissor(e){const t=this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y;e?e.addItem(new Et(this._scissorCached.x,t,this._scissorCached.z,this._scissorCached.w)):this._getCurrentRenderPass().setScissorRect(this._scissorCached.x,t,this._scissorCached.z,this._scissorCached.w)}_scissorIsActive(){return 0!==this._scissorCached.x||0!==this._scissorCached.y||0!==this._scissorCached.z||0!==this._scissorCached.w}enableScissor(e,t,r,s){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=r,this._scissorCached.w=s}disableScissor(){this._scissorCached.x=this._scissorCached.y=this._scissorCached.z=this._scissorCached.w=0,this._scissorsCurrent.x=this._scissorsCurrent.y=this._scissorsCurrent.w=this._scissorsCurrent.h=0}_mustUpdateStencilRef(){const e=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent;return e&&(this._stencilRefsCurrent=this._stencilStateComposer.funcRef),e}_applyStencilRef(e){e?e.addItem(new St(this._stencilStateComposer.funcRef??0)):this._getCurrentRenderPass().setStencilReference(this._stencilStateComposer.funcRef??0)}_mustUpdateBlendColor(){const e=this._alphaState._blendConstants,t=e[0]!==this._blendColorsCurrent[0]||e[1]!==this._blendColorsCurrent[1]||e[2]!==this._blendColorsCurrent[2]||e[3]!==this._blendColorsCurrent[3];return t&&(this._blendColorsCurrent[0]=e[0],this._blendColorsCurrent[1]=e[1],this._blendColorsCurrent[2]=e[2],this._blendColorsCurrent[3]=e[3]),t}_applyBlendColor(e){e?e.addItem(new Rt(this._alphaState._blendConstants.slice())):this._getCurrentRenderPass().setBlendConstant(this._alphaState._blendConstants)}_resetRenderPassStates(){this._viewportsCurrent.x=this._viewportsCurrent.y=this._viewportsCurrent.w=this._viewportsCurrent.h=0,this._scissorsCurrent.x=this._scissorsCurrent.y=this._scissorsCurrent.w=this._scissorsCurrent.h=0,this._stencilRefsCurrent=-1,this._blendColorsCurrent[0]=this._blendColorsCurrent[1]=this._blendColorsCurrent[2]=this._blendColorsCurrent[3]=null}clear(e,t,r,s=!1,n=0){e&&void 0===e.a&&(e.a=1),s&&(this._clearStencilValue=n);const i=this._scissorIsActive();this._currentRenderTarget?i?(this._currentRenderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,r,s),this._applyScissor(this.compatibilityMode?null:this._bundleList),this._clearFullQuad(t?e:null,r,s)):(this._currentRenderPass&&this._endCurrentRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,r,s)):(this._currentRenderPass&&i||this._startMainRenderPass(!i,t?e:null,r,s),i&&(this._applyScissor(this.compatibilityMode?null:this._bundleList),this._clearFullQuad(t?e:null,r,s)))}_clearFullQuad(e,t,r){const s=this.compatibilityMode?this._getCurrentRenderPass():null;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(this._cacheRenderPipeline.mrtAttachments??[],this._cacheRenderPipeline.mrtTextureArray??[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?s.setStencilReference(this._clearStencilValue):this._bundleList.addItem(new St(this._clearStencilValue));const n=this._clearQuad.clear(s,e,t,r,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(null):(this._bundleList.addBundle(n),this._applyStencilRef(this._bundleList),this._reportDrawCall())}createVertexBuffer(e,t,r){let s;s=e instanceof Array?new Float32Array(e):ArrayBuffer.isView(e)?e:new Uint8Array(e);return this._bufferManager.createBuffer(s,V.Vertex|V.CopyDst|V.Storage,r)}createDynamicVertexBuffer(e,t){return this.createVertexBuffer(e,void 0,t)}createIndexBuffer(e,t,r){let s,n=!0;if(e instanceof Uint32Array||e instanceof Int32Array)s=e;else if(e instanceof Uint16Array)s=e,n=!1;else{for(let t=0;t<e.length;t++)if(e[t]>65535){s=new Uint32Array(e);break}s||(s=new Uint16Array(e),n=!1)}const i=this._bufferManager.createBuffer(s,V.Index|V.CopyDst|V.Storage,r);return i.is32Bits=n,i}updateDynamicIndexBuffer(e,t,r=0){const s=e;let n;n=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(s,r,n)}updateDynamicVertexBuffer(e,t,r,s){const n=e;let i;void 0===r&&(r=0),void 0===s?(i=t instanceof Array?new Float32Array(t):ArrayBuffer.isView(t)?t:new Uint8Array(t),s=i.byteLength):i=t instanceof Array?new Float32Array(t):ArrayBuffer.isView(t)?t:new Uint8Array(t),this._bufferManager.setSubData(n,r,i,0,s)}_createBuffer(e,r,s){let n;n=e instanceof Array?new Float32Array(e):ArrayBuffer.isView(e)?e:new Uint8Array(e);let i=0;return r&t.BUFFER_CREATIONFLAG_READ&&(i|=V.CopySrc),r&t.BUFFER_CREATIONFLAG_WRITE&&(i|=V.CopyDst),r&t.BUFFER_CREATIONFLAG_UNIFORM&&(i|=V.Uniform),r&t.BUFFER_CREATIONFLAG_VERTEX&&(i|=V.Vertex),r&t.BUFFER_CREATIONFLAG_INDEX&&(i|=V.Index),r&t.BUFFER_CREATIONFLAG_STORAGE&&(i|=V.Storage),r&t.BUFFER_CREATIONFLAG_INDIRECT&&(i|=V.Indirect),this._bufferManager.createBuffer(n,i,s)}bindBuffersDirectly(){throw"Not implemented on WebGPU"}updateAndBindInstancesBuffer(){throw"Not implemented on WebGPU"}unbindInstanceAttributes(){}bindBuffers(e,t,r,s){this._currentVertexBuffers=e,this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=s??null,this._cacheRenderPipeline.setBuffers(this._currentVertexBuffers,this._currentIndexBuffer,this._currentOverrideVertexBuffers)}_releaseBuffer(e){return this._bufferManager.releaseBuffer(e)}createUniformBuffer(e,t){let r;r=e instanceof Array?new Float32Array(e):e;return this._bufferManager.createBuffer(r,V.Uniform|V.CopyDst,t)}createDynamicUniformBuffer(e,t){return this.createUniformBuffer(e,t)}updateUniformBuffer(e,t,r,s){void 0===r&&(r=0);const n=e;let i;void 0===s?(i=t instanceof Float32Array?t:new Float32Array(t),s=i.byteLength):i=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(n,r,i,0,s)}bindUniformBufferBase(e,t,r){this._currentDrawContext.setBuffer(r,e)}bindUniformBlock(){}createEffect(e,t,r,s,n,i,a,o,u,c=0,h){const l="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,d="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,p=this._getGlobalDefines(),_=void 0!==t.attributes;let g=n??t.defines??"";p&&(g+="\n"+p);const m=l+"+"+d+"@"+g;if(this._compiledEffects[m]){const e=this._compiledEffects[m];return a&&e.isReady()&&a(e),e._refCount++,e}const f=new P(e,t,_?this:r,s,this,n,i,a,o,u,m,t.shaderLanguage??c,t.extraInitializationsAsync??h);return this._compiledEffects[m]=f,f}_compileRawShaderToSpirV(e,t){return this._glslang.compileGLSL(e,t)}_compileShaderToSpirV(e,t,r,s){return this._compileRawShaderToSpirV(s+(r?r+"\n":"")+e,t)}_getWGSLShader(e,t,r){return(r=r?"//"+r.split("\n").join("\n//")+"\n":"")+e}_createPipelineStageDescriptor(e,t,r,s,n){return this._tintWASM&&0===r&&(e=this._tintWASM.convertSpirV2WGSL(e,s),t=this._tintWASM.convertSpirV2WGSL(t,n)),{vertexStage:{module:this._device.createShaderModule({label:"vertex",code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({label:"fragment",code:t}),entryPoint:"main"}}}_compileRawPipelineStageDescriptor(e,r,s){const n=e.indexOf(t.DISABLEUA)>=0,i=r.indexOf(t.DISABLEUA)>=0,a=0===s?this._compileRawShaderToSpirV(e,"vertex"):e,o=0===s?this._compileRawShaderToSpirV(r,"fragment"):r;return this._createPipelineStageDescriptor(a,o,s,n,i)}_compilePipelineStageDescriptor(e,r,s,n){this.onBeforeShaderCompilationObservable.notifyObservers(this);const i=e.indexOf(t.DISABLEUA)>=0,a=r.indexOf(t.DISABLEUA)>=0,o="#version 450\n",u=0===n?this._compileShaderToSpirV(e,"vertex",s,o):this._getWGSLShader(e,"vertex",s),c=0===n?this._compileShaderToSpirV(r,"fragment",s,o):this._getWGSLShader(r,"fragment",s),h=this._createPipelineStageDescriptor(u,c,n,i,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Dt(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new ve(e,this)}createMaterialContext(){return new _t}createDrawContext(){return new gt(this._bufferManager,this._dummyIndexBuffer)}async _preparePipelineContextAsync(e,t,r,s,i,a,o,u,c,h,l){const d=e,p=d.shaderProcessingContext.shaderLanguage;0!==p||this._glslangAndTintAreFullyLoaded||await this.prepareGlslangAndTintAsync(),this.dbgShowShaderCode&&(n.Log(["defines",u]),n.Log(t),n.Log(r),n.Log("***********************************************")),d.sources={fragment:r,vertex:t,rawVertex:i,rawFragment:a},d.stages=s?this._compileRawPipelineStageDescriptor(t,r,p):this._compilePipelineStageDescriptor(t,r,u,p),l()}getAttributes(e,t){const r=new Array(t.length),s=e;for(let e=0;e<t.length;e++){const n=t[e],i=s.shaderProcessingContext.availableAttributes[n];void 0!==i&&(r[e]=i)}return r}enableEffect(e){if(e){if(F(e)){if(!e.effect||e.effect===this._currentEffect&&e.materialContext===this._currentMaterialContext&&e.drawContext===this._currentDrawContext&&!this._forceEnableEffect){if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw n.Log(["drawWrapper=",e]),"Invalid call to enableEffect: the effect property is empty!";return}if(this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw n.Log(["drawWrapper=",e]),"Invalid call to enableEffect: the materialContext property is empty!"}else this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&n.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${e.uniqueId}, effect.name=${e.name}, effect.name.vertex=${"string"==typeof e.name?"":e.name.vertex}, effect.name.fragment=${"string"==typeof e.name?"":e.name.fragment}`,10);this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!1,this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect)}}_releaseEffect(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={},this.onReleaseEffectsObservable.notifyObservers(this)}_deletePipelineContext(e){e&&D(e)}get needPOTTextures(){return!1}_createHardwareTexture(){return new We(this)}_releaseTexture(e){const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)}_getRGBABufferInternalSizedFormat(){return t.TEXTUREFORMAT_RGBA}updateTextureComparisonFunction(e,t){e._comparisonFunction=t}_createInternalTexture(e,r,s=!0,i=0){const a={};void 0!==r&&"object"==typeof r?(a.generateMipMaps=r.generateMipMaps,a.createMipMaps=r.createMipMaps,a.type=void 0===r.type?t.TEXTURETYPE_UNSIGNED_BYTE:r.type,a.samplingMode=void 0===r.samplingMode?t.TEXTURE_TRILINEAR_SAMPLINGMODE:r.samplingMode,a.format=void 0===r.format?t.TEXTUREFORMAT_RGBA:r.format,a.samples=r.samples??1,a.creationFlags=r.creationFlags??0,a.useSRGBBuffer=r.useSRGBBuffer??!1,a.label=r.label,a.isCube=!!r.isCube):(a.generateMipMaps=r,a.type=t.TEXTURETYPE_UNSIGNED_BYTE,a.samplingMode=t.TEXTURE_TRILINEAR_SAMPLINGMODE,a.format=t.TEXTUREFORMAT_RGBA,a.samples=1,a.creationFlags=0,a.useSRGBBuffer=!1,a.isCube=!1),(a.type!==t.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(a.type!==t.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(a.samplingMode=t.TEXTURE_NEAREST_SAMPLINGMODE),a.type!==t.TEXTURETYPE_FLOAT||this._caps.textureFloat||(a.type=t.TEXTURETYPE_UNSIGNED_BYTE,n.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const o=new m(this,i),u=e.width??e,c=e.height??e,h=e.depth??0,l=e.layers??0;if(o.baseWidth=u,o.baseHeight=c,o.width=u,o.height=c,o.depth=h||l,o.isReady=!0,o.samples=a.samples,o.generateMipMaps=!!a.generateMipMaps,o.samplingMode=a.samplingMode,o.type=a.type,o.format=a.format,o.is2DArray=l>0,o.is3D=h>0,o.isCube=a.isCube,o._cachedWrapU=t.TEXTURE_CLAMP_ADDRESSMODE,o._cachedWrapV=t.TEXTURE_CLAMP_ADDRESSMODE,o._useSRGBBuffer=a.useSRGBBuffer,o.label=a.label,this._internalTexturesCache.push(o),!s){const e=!a.generateMipMaps&&a.createMipMaps;e&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,u,c,o.depth||1,a.creationFlags),e&&(o.generateMipMaps=!1)}return o}createTexture(e,r,s,n,i=t.TEXTURE_TRILINEAR_SAMPLINGMODE,a=null,o=null,u=null,c=null,h=null,l=null,d,p,_,g){return this._createTextureBase(e,r,s,n,i,a,o,(e,r,s,n,i,a,o,u)=>{const c=n;if(e.baseWidth=c.width,e.baseHeight=c.height,e.width=c.width,e.height=c.height,e.format=-1!==e.format?e.format:h??t.TEXTUREFORMAT_RGBA,e.type=-1!==e.type?e.type:t.TEXTURETYPE_UNSIGNED_BYTE,e._creationFlags=_??0,u(e.width,e.height,c,r,e,()=>{}),e._hardwareTexture?.underlyingResource)a||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,c.width,c.height,void 0,_);G.IsImageBitmap(c)&&(this._textureHelper.updateTexture(c,e,c.width,c.height,e.depth,t.format,0,0,i,!1,0,0),a||o||this._generateMipmaps(e,this._uploadEncoder))}s&&s.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,u,c,h,l,d,p,g)}wrapWebGPUTexture(e){const t=new We(this,e);t.format=e.format,t.originalFormat=e.format;const r=new m(this,15,!0);return r._hardwareTexture=t,r.baseWidth=e.width,r.baseHeight=e.height,r.width=e.width,r.height=e.height,r.isReady=!0,r}updateWrappedWebGPUTexture(e,t){if(15!==e.source)throw new Error("updateWrappedWebGPUTexture: target InternalTexture was not produced by wrapWebGPUTexture.");if(t.width!==e.baseWidth||t.height!==e.baseHeight)throw new Error(`updateWrappedWebGPUTexture: new GPUTexture dimensions (${t.width}x${t.height}) must match the wrapped texture's dimensions (${e.baseWidth}x${e.baseHeight}).`);const r=e._hardwareTexture;r.set(t),r.setUsage(15,e.generateMipMaps,e.is2DArray,e.isCube,e.is3D,t.width,t.height,e.depth),e.isReady=!0,e._setUniqueId(m._Counter++)}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}updateWrappedWebGLTexture(){throw new Error("updateWrappedWebGLTexture is not supported, use updateWrappedWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,r=!1){r&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,r=null,s=null){null!==t&&(e._cachedWrapU=t),null!==r&&(e._cachedWrapV=r),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,r,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===r&&e.depth===s)return;const n=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,r,s,n)}_setInternalTexture(e,r,s){if(s=s??e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[s];if(this._currentMaterialContext.setTexture(e,r),n&&n.autoBindSampler){const e=s+t.AUTOSAMPLERSUFFIX;this._currentMaterialContext.setSampler(e,r)}}}createPrefilteredCubeTexture(e,t,r,s,n=null,i=null,a,o=null,u=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e)return void(n&&n(null));const t=e.texture;u?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=t._sphericalPolynomial??new M,t._source=9,n&&n(t)},i,a,o,u,r,s)}setTexture(e,t,r,s){this._setTexture(e,r,!1,!1,s,s)}setTextureArray(e,t,r,s){for(let e=0;e<r.length;e++)this._setTexture(-1,r[e],!0,!1,s+e.toString(),s)}_setTexture(e,r,s=!1,n=!1,i="",a){if(a=a??i,this._currentEffect){if(!r)return this._currentMaterialContext.setTexture(i,null),!1;if(r.video)r.update();else if(r.delayLoadState===t.DELAYLOADSTATE_NOTLOADED)return r.delayLoad(),!1;let e;if(e=n?r.depthStencilTexture:r.isReady()?r.getInternalTexture():r.isCube?this.emptyCubeTexture:r.is3D?this.emptyTexture3D:r.is2DArray?this.emptyTexture2DArray:this.emptyTexture,e&&!e.isMultiview){if(e.isCube&&e._cachedCoordinatesMode!==r.coordinatesMode){e._cachedCoordinatesMode=r.coordinatesMode;const s=r.coordinatesMode!==t.TEXTURE_CUBIC_MODE&&r.coordinatesMode!==t.TEXTURE_SKYBOX_MODE?t.TEXTURE_WRAP_ADDRESSMODE:t.TEXTURE_CLAMP_ADDRESSMODE;r.wrapU=s,r.wrapV=s}e._cachedWrapU=r.wrapU,e._cachedWrapV=r.wrapV,e.is3D&&(e._cachedWrapR=r.wrapR),this._setAnisotropicLevel(0,e,r.anisotropicFilteringLevel)}this._setInternalTexture(i,e,a)}return!0}_setAnisotropicLevel(e,t,r){t._cachedAnisotropicFilteringLevel!==r&&(t._cachedAnisotropicFilteringLevel=Math.min(r,this._caps.maxAnisotropy))}_bindTexture(e,t,r){void 0!==e&&this._setInternalTexture(r,t)}generateMipmaps(e){this._generateMipmaps(e)}updateTextureData(e,t,r,s,n,i,a=0,o=0,u=!1){let c=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(c=this._textureHelper.createGPUTextureForInternalTexture(e));const h=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(h,e,n,i,e.depth,c.format,a,o,e.invertY,!1,r,s),u&&this._generateMipmaps(e)}_uploadCompressedDataToTextureDirectly(e,t,r,s,n,i=0,a=0){let o=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(e.format=t,o=this._textureHelper.createGPUTextureForInternalTexture(e,r,s));const u=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);this._textureHelper.updateTexture(u,e,r,s,e.depth,o.format,i,a,!1,!1,0,0)}_uploadDataToTextureDirectly(e,t,r=0,s=0,n,i=!1){const a=Math.round(Math.log(e.width)*Math.LOG2E),o=Math.round(Math.log(e.height)*Math.LOG2E),u=i?e.width:Math.pow(2,Math.max(a-s,0)),c=i?e.height:Math.pow(2,Math.max(o-s,0));let h=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(h=this._textureHelper.createGPUTextureForInternalTexture(e,u,c));const l=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(l,e,u,c,e.depth,h.format,r,s,e.invertY,!1,0,0)}_uploadArrayBufferViewToTexture(e,t,r=0,s=0){this._uploadDataToTextureDirectly(e,t,r,s)}_uploadImageToTexture(e,t,r=0,s=0){let n=e._hardwareTexture;if(e._hardwareTexture?.underlyingResource||(n=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";const i=t,a=Math.ceil(e.width/(1<<s)),o=Math.ceil(e.height/(1<<s));this._textureHelper.updateTexture(i,e,a,o,e.depth,n.format,r,s,e.invertY,!1,0,0)}readPixels(e,t,r,s,n=!0,i=!0,a=null){const o=this._getCurrentRenderPassWrapper().colorAttachmentGPUTextures[0];if(!o)return Promise.resolve(new Uint8Array(0));const u=o.underlyingResource,c=o.format;return u?(i&&this.flushFramebuffer(),this._textureHelper.readPixels(u,e,t,r,s,c,void 0,void 0,a)):Promise.resolve(new Uint8Array(0))}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}beginFrame(){this._measureFps(),super.beginFrame()}endFrame(){this._endCurrentRenderPass(),this._snapshotRendering.endFrame(),this._timestampQuery.endFrame(this._renderEncoder),this._timestampIndex=0,this._internalFrameCounter=0,this.flushFramebuffer(!0),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),super.endFrame()}extractDriverInfo(){return""}flushFramebuffer(e=!1){this._endCurrentRenderPass(),this._debugPopBeforeEndOfEncoder(),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers);const t=this._internalFrameCounter++;this._uploadEncoderDescriptor.label=`[${e?this.frameId+1:this.frameId}|${t}] - UploadEncoder`,this._renderEncoderDescriptor.label=`[${e?this.frameId+1:this.frameId}|${t}] - RenderEncoder`,this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),e?(this._debugMarkersEncoderGroups.length=0,this._debugMarkersPassGroups.length=0):this._debugPushAfterStartOfEncoder(),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset()}_currentFrameBufferIsDefaultFrameBuffer(){return this._currentPassIsMainPass()}_startRenderTargetRenderPass(e,r,s,n,i){this._endCurrentRenderPass();const a=e,o=e.samples,u=o>1,c=a._depthStencilTexture,h=c?._hardwareTexture,l=h?.underlyingResource;let d,p;if(u){const e=h?.getMSAATexture(o);d=e?this._cacheTextureViews.getView(e,this._rttRenderPassWrapper.depthAttachmentViewDescriptor):void 0,p=e?.format}!d&&l&&(d=this._cacheTextureViews.getView(l,this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),!p&&h&&(p=h.format);const _=!!p&&G.HasStencilAspect(p),g=!!p&&G.HasDepthAspect(p),m=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();const f=Nt;s&&(f.r=255*s.r,f.g=255*s.g,f.b=255*s.b,f.a=255*s.a);const b=r&&s,x=r&&n,T=r&&i;if(a._attachments&&a.isMulti){this._mrtAttachments&&0!==this._mrtAttachments.length||(this._mrtAttachments=a._defaultAttachments);for(let e=0;e<this._mrtAttachments.length;++e){const r=this._mrtAttachments[e],n=a.textures[e],i=n?._hardwareTexture,c=i?.underlyingResource;if(i&&c){const h=n.is3D?a.layerIndices?.[e]??0:void 0,l=a.getBaseArrayLayer(e),d=u?i.getMSAATexture(o,n.is3D?h:l):void 0,p={...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,dimension:n.is3D?"3d":"2d",format:i.format,baseArrayLayer:l},_={...this._rttRenderPassWrapper.colorAttachmentViewDescriptor,dimension:n.is3D?"3d":"2d",format:i.format,baseArrayLayer:0},g=n.type===t.TEXTURETYPE_UNSIGNED_INTEGER||n.type===t.TEXTURETYPE_UNSIGNED_SHORT,x=this._cacheTextureViews.getView(c,p),T=d?this._cacheTextureViews.getView(d,_):void 0;m.push({view:T||x,resolveTarget:d&&!a.disableAutomaticMSAAResolve&&a.resolveMSAAColors?x:void 0,depthSlice:h,clearValue:0!==r&&b?g?f:s:void 0,loadOp:0!==r&&b?"clear":"load",storeOp:"store"})}}this._cacheRenderPipeline.setMRT(a.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else{const e=a.texture;if(e){const r=e._hardwareTexture,n=r.underlyingResource,i=this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer;let c;a.is3D&&(c=this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer,this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer=0);const h=u?r.getMSAATexture(o,i):void 0,l=this._cacheTextureViews.getView(n,this._rttRenderPassWrapper.colorAttachmentViewDescriptor),d=h?this._cacheTextureViews.getView(h,this._rttRenderPassWrapper.colorAttachmentViewDescriptor):void 0,p=e.type===t.TEXTURETYPE_UNSIGNED_INTEGER||e.type===t.TEXTURETYPE_UNSIGNED_SHORT;m.push({view:d||l,resolveTarget:h&&!a.disableAutomaticMSAAResolve&&a.resolveMSAAColors?l:void 0,depthSlice:c,clearValue:b?p?f:s:void 0,loadOp:b?"clear":"load",storeOp:"store"})}else m.push(null)}const y=this._internalFrameCounter++;this._rttRenderPassWrapper.renderPassDescriptor={label:`[${this.frameId}|${y}] - `+(e.label??"RTT")+" - RenderPass",colorAttachments:m,depthStencilAttachment:c&&l?{view:d,depthClearValue:x?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:a.depthReadOnly||!g?void 0:x?"clear":"load",depthStoreOp:a.depthReadOnly||!g?void 0:"store",depthReadOnly:a.depthReadOnly,stencilClearValue:a._depthStencilTextureWithStencil&&T?this._clearStencilValue:void 0,stencilLoadOp:a.stencilReadOnly||!_?void 0:a._depthStencilTextureWithStencil&&T?"clear":"load",stencilStoreOp:a.stencilReadOnly||!_?void 0:"store",stencilReadOnly:a.stencilReadOnly}:void 0,occlusionQuerySet:this._occlusionQuery?.hasQueries?this._occlusionQuery.querySet:void 0},this._timestampQuery.startPass(this._rttRenderPassWrapper.renderPassDescriptor,this._timestampIndex),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this._debugPushAfterStartOfEncoder(),this._resetRenderPassStates(),h&&G.HasStencilAspect(h.format)||(this._stencilStateComposer.enabled=!1)}_startMainRenderPass(e,t,r,s){this._endCurrentRenderPass(),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();const n=e&&t,i=e&&r,a=e&&s,o=this._internalFrameCounter++;this._mainRenderPassWrapper.renderPassDescriptor.label=`[${this.frameId}|${o}] - MainRenderPass`,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=n?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=n?"clear":"load",this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=i?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=i?"clear":"load",this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=a?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?a?"clear":"load":void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=this._occlusionQuery?.hasQueries?this._occlusionQuery.querySet:void 0;const u=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(u),this._options.antialias?(Ut.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=u.createView(Ut)):(Ot.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=u.createView(Ot)),this._timestampQuery.startPass(this._mainRenderPassWrapper.renderPassDescriptor,this._timestampIndex),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._debugPushAfterStartOfEncoder(),this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper),this._resetRenderPassStates(),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)}bindFramebuffer(e,t=0,r,s,n,i=0,a=0){const o=e.texture?._hardwareTexture;this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass(),this._currentRenderTarget=e;const u=this._currentRenderTarget._depthStencilTexture;this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=o,this._rttRenderPassWrapper.depthTextureFormat=u?G.GetWebGPUTextureFormat(-1,u.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={label:e.label?e.label+" - Color Attachment View":"RTT - Color Attachment View",format:this._colorFormat,dimension:e.is3D?"3d":"2d",mipLevelCount:1,baseArrayLayer:e.isCube?6*a+t:a,baseMipLevel:i,arrayLayerCount:1,aspect:"all"},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={label:e.label?e.label+" - Depth Attachment View":"RTT - Depth Attachment View",format:this._depthTextureFormat,dimension:u&&u.is3D?"3d":"2d",mipLevelCount:1,baseArrayLayer:u?u.isCube?6*a+t:a:0,baseMipLevel:0,arrayLayerCount:1,aspect:"all"},(this._snapshotRendering.play||this._snapshotRendering.record)&&this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),this._cachedViewport&&!n?this.setViewport(this._cachedViewport,r,s):(r||(r=e.width,i&&(r/=Math.pow(2,i))),s||(s=e.height,i&&(s/=Math.pow(2,i))),this._viewport(0,0,r,s)),this.wipeCaches()}unBindFramebuffer(e,t=!1,r){const s=this._currentRenderTarget;this._currentRenderTarget=null,r&&r(),this._currentRenderTarget=s,this._endCurrentRenderPass(),this._resolveAndGenerateMipMapsFramebuffer(e,t),this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}_resolveAndGenerateMipMapsFramebuffer(e,t=!1){e.disableAutomaticMSAAResolve||this.resolveFramebuffer(e,!1),t||(e.isMulti?this.generateMipMapsMultiFramebuffer(e):this.generateMipMapsFramebuffer(e))}generateMipMapsFramebuffer(e){e.isMulti||!e.texture?.generateMipMaps||e.isCube||this._generateMipmaps(e.texture)}resolveFramebuffer(e,t=!0){if(!(e.samples<=1)){if(e.resolveMSAAColors&&t){const t=e.disableAutomaticMSAAResolve;e.disableAutomaticMSAAResolve=!1,this.bindFramebuffer(e),this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),this.unBindFramebuffer(e),e.disableAutomaticMSAAResolve=t}if(e.resolveMSAADepth&&e._depthStencilTexture){const t=e._depthStencilTexture._hardwareTexture;this._textureHelper.resolveMSAADepthTexture(t.getMSAATexture(e.samples),t.underlyingResource,this._renderEncoder)}}}restoreDefaultFramebuffer(e){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._currentRenderPass||e?this._endCurrentRenderPass():this._startMainRenderPass(!1),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_setColorFormat(e){const t=e.colorAttachmentGPUTextures[0]?.format??null;this._cacheRenderPipeline.setColorFormat(t),this._colorFormat!==t&&(this._colorFormat=t)}_setDepthTextureFormat(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)}setDitheringState(){}setRasterizerState(){}_executeWhenRenderingStateIsCompiled(e,t){t()}bindSamplers(){}_getUnpackAlignement(){return 1}_bindTextureDirectly(){return!1}setStateCullFaceType(e,t=!1){const r=this.cullBackFaces??e??1?1:2;(this._depthCullingState.cullFace!==r||t)&&(this._depthCullingState.cullFace=r)}setState(e,t=0,r,s=!1,n,i,a=0){(this._depthCullingState.cull!==e||r)&&(this._depthCullingState.cull=e),this.setStateCullFaceType(n,r),this.setZOffset(t),this.setZOffsetUnits(a);const o=!!this._currentRenderTarget&&!this._currentRenderTarget._disableEngineYFlip,u=s?o?1:2:o?2:1;(this._depthCullingState.frontFace!==u||r)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=i}_applyRenderPassChanges(e){const t=!!this._stencilStateComposer.enabled&&this._mustUpdateStencilRef(),r=!!this._alphaState.alphaBlend&&this._mustUpdateBlendColor();this._mustUpdateViewport()&&this._applyViewport(e),this._mustUpdateScissor()&&this._applyScissor(e),t&&this._applyStencilRef(e),r&&this._applyBlendColor(e)}_draw(e,r,s,n,i){const a=this._getCurrentRenderPass(),o=this._bundleList;this.applyStates();const u=this._currentEffect._pipelineContext,c=!!this._currentRenderTarget&&!this._currentRenderTarget._disableEngineYFlip;if(this.bindUniformBufferBase(c?this._ubInvertY:this._ubDontInvertY,0,Ae.InternalsUBOName),this._currentDrawContext.setVertexPulling(this._currentMaterialContext.useVertexPulling,u,this._currentVertexBuffers,this._cacheRenderPipeline.indexBuffer,this._currentOverrideVertexBuffers),u.uniformBuffer&&(u.uniformBuffer.update(),this.bindUniformBufferBase(u.uniformBuffer.getBuffer(),0,Ae.LeftOvertUBOName)),this._snapshotRendering.play)return void this._reportDrawCall();!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);let h=a;if(!this.compatibilityMode&&this._currentDrawContext.fastBundle||this._snapshotRendering.record){if(this._applyRenderPassChanges(o),!this._snapshotRendering.record)return this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(n,i||1,s),o.addBundle(this._currentDrawContext.fastBundle),void this._reportDrawCall();h=o.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),o.numDrawCalls++}let l=0;if(this._currentMaterialContext.hasFloatOrDepthTextures){let e=1;for(let r=0;r<u.shaderProcessingContext.textureNames.length;++r){const s=u.shaderProcessingContext.textureNames[r],n=this._currentMaterialContext.textures[s]?.texture,i=n&&n.format>=t.TEXTUREFORMAT_DEPTH24_STENCIL8&&n.format<=t.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8;(n?.type===t.TEXTURETYPE_FLOAT&&!this._caps.textureFloatLinearFiltering||i)&&(l|=e),e<<=1}}this._currentMaterialContext.textureState=l;const d=this._cacheRenderPipeline.getRenderPipeline(r,this._currentEffect,this.currentSampleCount,l),p=this._cacheBindGroups.getBindGroups(u,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(this.compatibilityMode?null:o),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,h=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:G.GetSample(this.currentSampleCount)}))),h.setPipeline(d),this._currentIndexBuffer&&h.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?"uint32":"uint16",0);const _=this._cacheRenderPipeline.vertexBuffers;for(let e=0;e<_.length;e++){const t=_[e],r=t.effectiveBuffer;r&&h.setVertexBuffer(e,r.underlyingResource,t._validOffsetRange?0:t.byteOffset)}for(let e=0;e<p.length;e++)h.setBindGroup(e,p[e]);const g=!this.compatibilityMode&&!this._snapshotRendering.record;(g||this._currentDrawContext._enableIndirectDrawInCompatMode)&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(n,i||1,s),0===e?h.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):h.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):0===e?h.drawIndexed(n,i||1,s,0,0):h.draw(n,i||1,s,0),g&&(this._currentDrawContext.fastBundle=h.finish(),o.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}drawElementsType(e,t,r,s=1){this._draw(0,e,t,r,s)}drawArraysType(e,t,r,s=1){this._currentIndexBuffer=null,this._draw(1,e,t,r,s)}createRenderPipelineAsync(e){if("vertex"in e)return[this._device.createRenderPipelineAsync(e)];const r=Array.isArray(e)?e:[e],s=[],n=this._cacheRenderPipeline;for(const e of r){n.setColorFormat(e.colorFormat??this._colorFormat),n.setDepthStencilFormat(e.depthStencilFormat??this._depthTextureFormat);const r=e.mesh.geometry;if(!r)throw new Error("WebGPUEngine.createRenderPipelineAsync: mesh has no geometry to derive vertex/index buffers from.");n.setBuffers(r.getVertexBuffers(),r.getIndexBuffer(),null);const i=e.alphaMode??t.ALPHA_DISABLE;if(i===t.ALPHA_DISABLE)n.setAlphaBlendEnabled([!1],0);else{const e=this._alphaMode[0];this.setAlphaMode(i),n.setAlphaBlendEnabled(this._alphaState._alphaBlend,this._alphaState._numTargetEnabled),n.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this.setAlphaMode(e)}n.setDepthWriteEnabled(e.depthWrite??!0),n.setDepthTestEnabled(e.depthTest??!0),n.setDepthCompare(e.depthCompare??t.LEQUAL),n.setCullEnabled(e.cullEnabled??!0),n.setCullFace(e.cullFace??1),n.setFrontFace(e.frontFace??2),n.setWriteMask(e.writeMask??15),n.setStencilEnabled(e.stencilEnabled??!1);const a=e.fillMode??t.MATERIAL_TriangleFillMode,o=e.sampleCount??this.currentSampleCount,u=n.preWarmPipeline(a,e.effect,o,0);u&&s.push(u)}return n.setColorFormat(this._colorFormat),n.setDepthStencilFormat(this._depthTextureFormat),n.setBuffers(this._currentVertexBuffers??null,this._currentIndexBuffer,this._currentOverrideVertexBuffers??null),n.setDepthCullingState(this._depthCullingState.cull??!1,this._depthCullingState.frontFace??2,this._depthCullingState.cullFace??1,this._depthCullingState.zOffset,this._depthCullingState.zOffsetUnits,this._depthCullingState.depthTest??!0,this._depthCullingState.depthMask??!0,this._depthCullingState.depthFunc),n.setAlphaBlendEnabled(this._alphaState._alphaBlend,this._alphaState._numTargetEnabled),n.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),n.setStencilEnabled(this._stencilStateComposer.enabled??!1),n.setWriteMask(this._colorWrite?15:0),s}dispose(){this._isDisposed=!0,this.hideLoadingUI?.(),this._timestampQuery.dispose(),this._mainTexture?.destroy(),this._depthTexture?.destroy(),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._device.destroy(),L(this,this._renderingCanvas),super.dispose()}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._renderingCanvas?.width??0}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._renderingCanvas?.height??0}getError(){return 0}createExternalTexture(e){return new Gt(e)}setExternalTexture(e,t){t?this._setInternalTexture(e,t):this._currentMaterialContext.setTexture(e,null)}setTextureSampler(e,t){this._currentMaterialContext?.setSampler(e,t)}createStorageBuffer(e,r,s){return this._createBuffer(e,r|t.BUFFER_CREATIONFLAG_STORAGE,s)}clearStorageBuffer(e,t,r){this._endCurrentRenderPass(),this._renderEncoder.clearBuffer(e.underlyingResource,t,r)}updateStorageBuffer(e,t,r,s){const n=e;let i;void 0===r&&(r=0),void 0===s?(i=t instanceof Array?new Float32Array(t):ArrayBuffer.isView(t)?t:new Uint8Array(t),s=i.byteLength):i=t instanceof Array?new Float32Array(t):ArrayBuffer.isView(t)?t:new Uint8Array(t),this._bufferManager.setSubData(n,r,i,0,s)}async _readFromGPUBuffer(e,t,r,s){return await new Promise((n,i)=>{const a=()=>{e.mapAsync(1,0,t).then(()=>{const s=e.getMappedRange(0,t);let i=r;if(void 0===i)i=new Uint8Array(t),i.set(new Uint8Array(s));else{const e=i.constructor;i=new e(i.buffer),i.set(new e(s))}e.unmap(),this._bufferManager.releaseBuffer(e),n(i)},e=>{this.isDisposed?n(new Uint8Array):i(e)})};s?(this.flushFramebuffer(),a()):this.onEndFrameObservable.addOnce(()=>{a()})})}readFromStorageBuffer(e,t,r,s,n){r=r||e.capacity;const i=this._bufferManager.createRawBuffer(r,V.MapRead|V.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,t??0,i,0,r),this._readFromGPUBuffer(i,r,s,n)}readFromMultipleStorageBuffers(e,t,r,s,n){r=r||e[0].capacity;const i=this._bufferManager.createRawBuffer(r*e.length,V.MapRead|V.CopyDst,void 0,"TempReadFromMultipleStorageBuffers");for(let s=0;s<e.length;s++)this._renderEncoder.copyBufferToBuffer(e[s].underlyingResource,t??0,i,s*r,r);return this._readFromGPUBuffer(i,r*e.length,s,n)}setStorageBuffer(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)}}$t._GlslangDefaultOptions={jsPath:`${f._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${f._DefaultCdnUrl}/glslang/glslang.wasm`},$t._InstanceId=0;export{O as T,$t as W,ut as a,G as b,U as c,Ct as d,At as e};
//# sourceMappingURL=webgpuEngine.pure-Cq3S0inF.esm.min.js.map