@luma.gl/engine 10.0.0-beta.3 → 10.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dist.dev.js +3 -1
- package/dist/dist.min.js +1 -1
- package/dist/gltf/index.cjs.map +1 -1
- package/dist/gltf/parsers/parse-gltf-joints.cjs +8 -1
- package/dist/gltf/parsers/parse-gltf-joints.d.ts +1 -0
- package/dist/gltf/parsers/parse-gltf-joints.d.ts.map +1 -1
- package/dist/gltf/parsers/parse-gltf-joints.js +8 -1
- package/dist/gltf/parsers/parse-gltf-joints.js.map +1 -1
- package/dist/gltf/physics/index.cjs.map +1 -1
- package/dist/graph/models/index.cjs.map +1 -1
- package/dist/graph/physics/index.cjs.map +1 -1
- package/dist/graph/physics/scenegraph-joints.cjs +1 -0
- package/dist/graph/physics/scenegraph-joints.d.ts.map +1 -1
- package/dist/graph/physics/scenegraph-joints.js +1 -0
- package/dist/graph/physics/scenegraph-joints.js.map +1 -1
- package/dist/graph/physics/scenegraph-motion.cjs +25 -3
- package/dist/graph/physics/scenegraph-motion.d.ts +1 -1
- package/dist/graph/physics/scenegraph-motion.d.ts.map +1 -1
- package/dist/graph/physics/scenegraph-motion.js +27 -2
- package/dist/graph/physics/scenegraph-motion.js.map +1 -1
- package/dist/graph/physics/scenegraph-session.cjs +2 -2
- package/dist/graph/physics/scenegraph-session.d.ts +4 -2
- package/dist/graph/physics/scenegraph-session.d.ts.map +1 -1
- package/dist/graph/physics/scenegraph-session.js +2 -2
- package/dist/graph/physics/scenegraph-session.js.map +1 -1
- package/dist/graph/tables/index.cjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/lighting/index.cjs.map +1 -1
- package/dist/model/gpu-vector-model.cjs +2 -2
- package/dist/model/gpu-vector-model.d.ts.map +1 -1
- package/dist/model/gpu-vector-model.js +2 -1
- package/dist/model/gpu-vector-model.js.map +1 -1
- package/dist/scenegraph/controllers/joint-controller.d.ts +2 -0
- package/dist/scenegraph/controllers/joint-controller.d.ts.map +1 -1
- package/dist/scenegraph/controllers/joint-controller.js.map +1 -1
- package/package.json +8 -8
- package/src/gltf/parsers/parse-gltf-joints.ts +9 -2
- package/src/graph/physics/scenegraph-joints.ts +1 -0
- package/src/graph/physics/scenegraph-motion.ts +29 -2
- package/src/graph/physics/scenegraph-session.ts +5 -2
- package/src/model/gpu-vector-model.ts +8 -2
- package/src/scenegraph/controllers/joint-controller.ts +2 -0
package/dist/dist.dev.js
CHANGED
|
@@ -14948,7 +14948,9 @@ ${declarations.join("\n")}`).match(
|
|
|
14948
14948
|
const nextColorAttachmentFormats = renderBundleProps.colorAttachmentFormats ?? framebuffer?.colorAttachments?.map(
|
|
14949
14949
|
(colorAttachment) => asColorAttachmentFormat(colorAttachment?.texture?.format)
|
|
14950
14950
|
);
|
|
14951
|
-
const nextDepthStencilAttachmentFormat = renderBundleProps.depthStencilAttachmentFormat === false ? void 0 : renderBundleProps.depthStencilAttachmentFormat ?? asDepthStencilAttachmentFormat(
|
|
14951
|
+
const nextDepthStencilAttachmentFormat = renderBundleProps.depthStencilAttachmentFormat === false ? void 0 : renderBundleProps.depthStencilAttachmentFormat ?? asDepthStencilAttachmentFormat(
|
|
14952
|
+
framebuffer?.depthStencilAttachment?.props?.format ?? framebuffer?.depthStencilAttachment?.texture?.format
|
|
14953
|
+
);
|
|
14952
14954
|
if (!deepEqual(this._colorAttachmentFormats, nextColorAttachmentFormats, 1) || this._depthStencilAttachmentFormat !== nextDepthStencilAttachmentFormat) {
|
|
14953
14955
|
this._colorAttachmentFormats = nextColorAttachmentFormats;
|
|
14954
14956
|
this._depthStencilAttachmentFormat = nextDepthStencilAttachmentFormat;
|
package/dist/dist.min.js
CHANGED
|
@@ -127,7 +127,7 @@ ${n.join(`
|
|
|
127
127
|
`));return v+=W4(T,S,O),v+=t5(C),v+=M.source,v=Re(v,n,x,!1,"wgsl",{vertex:d,fragment:f}),v=m9(v,T,O),e5(v),{source:v,bindingAssignments:C}}function U4(r,e,t,n){r&&(t["vs:#decl"]=t["vs:#decl"]||[],t["vs:#decl"].push({injection:r,order:Number.MIN_SAFE_INTEGER})),e&&(n["vs:#main-start"]=n["vs:#main-start"]||[],n["vs:#main-start"].push({injection:e,order:Number.MIN_SAFE_INTEGER}))}function V4(r,e,t){r.declarations&&(e["vs:#decl"]=e["vs:#decl"]||[],e["vs:#decl"].push({injection:r.declarations,order:Number.MIN_SAFE_INTEGER})),r.vertexInitialization&&(t["vs:#main-start"]=t["vs:#main-start"]||[],t["vs:#main-start"].push({injection:r.vertexInitialization,order:Number.MIN_SAFE_INTEGER})),r.fragmentInitialization&&(t["fs:#main-start"]=t["fs:#main-start"]||[],t["fs:#main-start"].push({injection:r.fragmentInitialization,order:Number.MIN_SAFE_INTEGER}))}function j4(r){let e=[...r["vs:#decl"]||[],...r["fs:#decl"]||[]];return e.length?{"vs:#decl":e}:{}}function W4(r,e,t=Wr(r)){return["vertex","fragment"].map(n=>{let i=Object.fromEntries(Object.entries(r[n]).map(([s,o])=>{let a=s.slice(3),c=t.get(a)?.[n]||a;return[s,{...o,signature:c+o.signature.slice(a.length)}]}));return Cr(i,e,"wgsl")}).join("")}function q4(r){let e=new Map;for(let t of oe(r,Ko)){let n=Number(t.bindingToken),i=Number(t.groupToken);Wi(i,n,t.name),ke(e,i,n,`application binding "${t.name}"`)}return e}function H4(r){let e=oe(r,Fr),t=new Map;for(let s of e){if(s.bindingToken==="auto")continue;let o=Number(s.bindingToken),a=Number(s.groupToken);Wi(a,o,s.name),ke(t,a,o,`application binding "${s.name}"`)}let n={sawSupportedBindingDeclaration:e.length>0},i=Di(r,Fr,s=>K4(s,t,n));if(Bi(r)&&!n.sawSupportedBindingDeclaration)throw new Error('Unsupported @binding(auto) declaration form in application WGSL. Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.');return{source:i}}function X4(r,e,t){let n=[],s={sawSupportedBindingDeclaration:oe(r,Be).length>0,nextHintedBindingLocation:typeof e.firstBindingSlot=="number"?e.firstBindingSlot:null},o=Di(r,Be,a=>Y4(a,{module:e,context:t,bindingAssignments:n,relocationState:s}));if(Bi(r)&&!s.sawSupportedBindingDeclaration)throw new Error(`Unsupported @binding(auto) declaration form in module "${e.name}". Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.`);return{source:o,bindingAssignments:n}}function Y4(r,e){let{module:t,context:n,bindingAssignments:i,relocationState:s}=e,{match:o,bindingToken:a,groupToken:c,name:u}=r,l=Number(c);if(a==="auto"){let h=qr(l,t.name,u),p=n.bindingRegistry?.get(h),m=p!==void 0?p:Q4(l,n.usedBindingsByGroup,t.name,s.nextHintedBindingLocation??void 0,n.bindingRegistry);return ji(t.name,l,m,u),p!==void 0&&g9(n.reservedBindingKeysByGroup,l,m,h)?(i.push({moduleName:t.name,name:u,group:l,location:m}),o.replace(/@binding\(\s*auto\s*\)/,`@binding(${m})`)):(ke(n.usedBindingsByGroup,l,m,`module "${t.name}" binding "${u}"`),n.bindingRegistry?.set(h,m),i.push({moduleName:t.name,name:u,group:l,location:m}),s.nextHintedBindingLocation!==null&&p===void 0&&(s.nextHintedBindingLocation=m+1),o.replace(/@binding\(\s*auto\s*\)/,`@binding(${m})`))}let d=Number(a);ji(t.name,l,d,u);let f=qr(l,t.name,u);return g9(n.reservedBindingKeysByGroup,l,d,f)||ke(n.usedBindingsByGroup,l,d,`module "${t.name}" binding "${u}"`),i.push({moduleName:t.name,name:u,group:l,location:d}),o}function K4(r,e,t){let{match:n,bindingToken:i,groupToken:s,name:o}=r,a=Number(s);if(i==="auto"){let c=J4(a,e);return Wi(a,c,o),ke(e,a,c,`application binding "${o}"`),n.replace(/@binding\(\s*auto\s*\)/,`@binding(${c})`)}return t.sawSupportedBindingDeclaration=!0,n}function Z4(r,e,t){let n=new Map,i=[];function s(o,a,c,u){ke(t,o,a,u);let l=n.get(o)||new Map;l.set(a,c),n.set(o,l)}for(let{module:o,source:a}of r)for(let c of oe(a,Be)){let u=Number(c.groupToken);if(c.bindingToken==="auto"){i.push({module:o,name:c.name,group:u});continue}let l=Number(c.bindingToken);ji(o.name,u,l,c.name),s(u,l,qr(u,o.name,c.name),`module "${o.name}" binding "${c.name}"`)}for(let{module:o,name:a,group:c}of i){let u=qr(c,o.name,a),l=e?.get(u);l!==void 0&&s(c,l,u,`registered module binding "${u}"`)}return n}function g9(r,e,t,n){let i=r.get(e);if(!i)return!1;let s=i.get(t);if(!s)return!1;if(s!==n)throw new Error(`Registered module binding "${n}" collided with "${s}": group ${e}, binding ${t}.`);return i.delete(t),!0}function Wi(r,e,t){if(r===0&&e>=Mt)throw new Error(`Application binding "${t}" in group 0 uses reserved binding ${e}. Application-owned explicit group-0 bindings must stay below ${Mt}.`)}function ji(r,e,t,n){if(e===0&&t<Mt)throw new Error(`Module "${r}" binding "${n}" in group 0 uses reserved application binding ${t}. Module-owned explicit group-0 bindings must be ${Mt} or higher.`)}function ke(r,e,t,n){let i=r.get(e)||new Set;if(i.has(t))throw new Error(`Duplicate WGSL binding assignment for ${n}: group ${e}, binding ${t}.`);i.add(t),r.set(e,i)}function Q4(r,e,t,n,i){let s=e.get(r)||new Set,o=new Set,a=`${r}:`,c=`${a}${t}:`;for(let[l,d]of i||[])l.startsWith(c)&&o.add(d);let u=n??(r===0?Mt:s.size>0?Math.max(...s)+1:0);for(;s.has(u)||o.has(u);)u++;for(let[l,d]of i||[])d===u&&l.startsWith(a)&&i?.delete(l);return u}function J4(r,e){let t=e.get(r)||new Set,n=0;for(;t.has(n);)n++;return n}function e5(r){let e=Zo(r,Be);if(!e)return;let t=r5(r,e.index);throw t?new Error(`Unresolved @binding(auto) for module "${t}" binding "${e.name}" remained in assembled WGSL source.`):n5(r,e.index)?new Error(`Unresolved @binding(auto) for application binding "${e.name}" remained in assembled WGSL source.`):new Error(`Unresolved @binding(auto) remained in assembled WGSL source near "${i5(e.match)}".`)}function t5(r){if(r.length===0)return"";let e=`// ----- MODULE WGSL BINDING ASSIGNMENTS ---------------
|
|
128
128
|
`;for(let t of r)e+=`// ${t.moduleName}.${t.name} -> @group(${t.group}) @binding(${t.location})
|
|
129
129
|
`;return e+=`
|
|
130
|
-
`,e}function qr(r,e,t){return`${r}:${e}:${t}`}function r5(r,e){let t=/^\/\/ ----- MODULE ([^\n]+) ---------------$/gm,n,i;for(i=t.exec(r);i&&i.index<=e;)n=i[1],i=t.exec(r);return n}function n5(r,e){let t=r.indexOf(wt);return t>=0?e>t:!0}function i5(r){return r.replace(/\s+/g," ").trim()}var $0=class r extends Le{shaderLanguage="wgsl";_wgslBindingRegistry=new Map;assembleWGSLShader(e){let t=this._getModuleList(e.modules),n=[...this._injectionTargets,...e.injectionTargets||[]],i=this._transpileShader(e,t,e.source,e.shaderStage??(e.computeEntryPoint?"compute":void 0)),s={vertex:i.entryPoints?.vertex??e.vertexEntryPoint,fragment:i.entryPoints?.fragment??e.fragmentEntryPoint,compute:i.entryPoints?.compute??e.computeEntryPoint},o=r.getShaderPreprocessorDefines(e,t),a=e.platformInfo.shaderLanguage==="wgsl"&&i.code?Ne(i.code,{defines:o}):i.code,{source:c,getUniforms:u,bindingAssignments:l}=y9({...e,source:a,vertexEntryPoint:s.vertex,fragmentEntryPoint:s.fragment,defines:o,_bindingRegistry:this._wgslBindingRegistry,modules:i.modules,injectionTargets:n}),d=e.platformInfo.shaderLanguage==="wgsl"?Ne(c,{defines:o}):c;return{source:d,entryPoints:s,getUniforms:u,modules:t,bindingAssignments:l,bindingTable:p9(d,l),shaderLayout:s9(d,{vertexEntryPoint:s.vertex,scanVertexAttributes:e.scanVertexAttributes})}}static getShaderPreprocessorDefines(e,t){return{...r.getPlatformPreprocessorDefines(e.platformInfo),...t.reduce((n,i)=>(Object.assign(n,i.defines),n),{}),...e.defines}}static getPlatformPreprocessorDefines(e){let t=e.limits||{};return{LUMA_SUPPORTS_VERTEX_STORAGE_BUFFERS:e.type==="webgpu"&&(t.maxStorageBuffersInVertexStage||0)>0,LUMA_FP32_TAN_PRECISION_WORKAROUND:e.type==="webgpu"&&e.gpu.toLowerCase()!=="nvidia"&&e.gpu.toLowerCase()!=="amd",LUMA_FP64_INTEGER_ARITHMETIC:e.type==="webgpu"&&e.gpu.toLowerCase()==="apple"}}};var Et=B(k(),1),Hr=class{device;buffer;byteOffset=0;constructor(e){this.device=e}prepare(e){if(!this.buffer||this.buffer.byteLength<e){let t=Math.max(1024,(this.buffer?.byteLength??0)*2,e),n=this.device.createBuffer({id:"batch-uniforms",byteLength:t,usage:Et.Buffer.UNIFORM|Et.Buffer.COPY_DST});this.buffer?.destroy(),this.buffer=n}this.byteOffset=0}getAlignedByteLength(e){let t=this.device.limits.minUniformBufferOffsetAlignment||1;return Math.ceil(e/t)*t}write(e){(0,Et.assert)(this.buffer&&this.byteOffset+e.byteLength<=this.buffer.byteLength);let t={buffer:this.buffer,offset:this.byteOffset,size:e.byteLength};return this.buffer.write(e,t.offset),this.byteOffset+=this.getAlignedByteLength(e.byteLength),t}destroy(){this.buffer?.destroy(),this.buffer=void 0,this.byteOffset=0}};function x9(r,e){let t={},n="Values";if(r.attributes.length===0&&!r.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let i of r.attributes)if(i){let s=`${i.location} ${i.name}: ${i.type}`;t[`in ${s}`]={[n]:i.stepMode||"vertex"}}for(let i of r.varyings||[]){let s=`${i.location} ${i.name}`;t[`out ${s}`]={[n]:JSON.stringify(i)}}return t}var b9="__debugFramebufferState";function T9(r,e,t){if(r.device.type!=="webgl")return;let n=a5(r.device);if(!n.flushing){if(u5(r)){s5(r,t,n);return}e&&c5(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function s5(r,e,t){if(t.queuedFramebuffers.length===0)return;let n=r.device,{gl:i}=n,s=i.getParameter(36010),o=i.getParameter(36006),[a,c]=r.device.getDefaultCanvasContext().getDrawingBufferSize(),u=v9(e.top,8),l=v9(e.left,8);t.flushing=!0;try{for(let d of t.queuedFramebuffers){let[f,h,p,m,g]=o5({framebuffer:d,targetWidth:a,targetHeight:c,topPx:u,leftPx:l,minimap:e.minimap});i.bindFramebuffer(36008,d.handle),i.bindFramebuffer(36009,null),i.blitFramebuffer(0,0,d.width,d.height,f,h,p,m,16384,9728),u+=g+8}}finally{i.bindFramebuffer(36008,s),i.bindFramebuffer(36009,o),t.flushing=!1}}function o5(r){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:i,leftPx:s,minimap:o}=r,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,u=Math.min(a/e.width,c/e.height),l=Math.max(Math.floor(e.width*u),1),d=Math.max(Math.floor(e.height*u),1),f=s,h=Math.max(n-i-d,0),p=f+l,m=h+d;return[f,h,p,m,d]}function a5(r){return r.userData[b9]||={flushing:!1,queuedFramebuffers:[]},r.userData[b9]}function c5(r){return"colorAttachments"in r}function u5(r){let e=r.props.framebuffer;return!e||e.handle===null}function v9(r,e){if(!r)return e;let t=Number.parseInt(r,10);return Number.isFinite(t)?t:e}function Fe(r,e,t){if(r===e)return!0;if(!t||!r||!e)return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!Fe(r[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof r=="object"&&typeof e=="object"){let n=r,i=e,s=Object.keys(r),o=Object.keys(e);if(s.length!==o.length)return!1;for(let a of s)if(!e.hasOwnProperty(a)||!Fe(n[a],i[a],t-1))return!1;return!0}return!1}var S9=B(k(),1),Xr=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,S9.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let i of t){let s=n.findIndex(o=>o.name===i.name);s<0?n.push(i):n[s]=i}return n}};var U0=B(k(),1);function qi(r,e){let t=(0,U0.getShaderAttributeLocationMap)(r),n=e.slice();return n.sort((i,s)=>{let o=(0,U0.getMinimumAttributeLocation)((0,U0.getBufferLayoutAttributeNames)(i).map(c=>t[c])),a=(0,U0.getMinimumAttributeLocation)((0,U0.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}var Yr=B(b0(),1);function Ge(r,e){if(!r||!e.some(n=>n.bindingLayout?.length))return r;let t={...r,bindings:r.bindings.map(n=>({...n}))};"attributes"in(r||{})&&(t.attributes=r?.attributes||[]);for(let n of e)for(let i of n.bindingLayout||[])for(let s of l5(i.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=i.group),o&&i.visibility!==void 0&&(o.visibility=i.visibility)}return t}function w9(r,e,t=[]){return r?e?{...r,attributes:r.attributes.length?h5(r.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:f5(r.bindings,e.bindings)}:r:e}function ce(r){return!!(r.uniformTypes&&!d5(r.uniformTypes))}function I9(r){let e=[];for(let t of r){let n=(0,Yr.getShaderModuleUniformBlockName)(t),i=new Set([t.vs,t.fs].flatMap(o=>o?(0,Yr.getGLSLUniformBlocks)(o).filter(a=>a.isStd140).map(a=>a.blockName):[])),s=i.has(n)?n:i.size===1?i.values().next().value:void 0;ce(t)&&s&&e.push({name:s,uniformTypes:t.uniformTypes})}return e}function Kr(r,e){let t=[],n=new Set;for(let i of[...r||[],...e||[]])n.has(i.name)||(n.add(i.name),t.push(i));return t}function l5(r){let e=new Set([r,`${r}Uniforms`]);return r.endsWith("Uniforms")||e.add(`${r}Sampler`),[...e]}function d5(r){for(let e in r)return!1;return!0}function f5(r,e){let t=r.map(s=>({...s})),n=new Set(r.map(s=>s.name)),i=new Set(r.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!i.has(o)&&t.push({...s})}return t}function h5(r,e){let t=r.map(s=>({...s})),n=new Map(r.map(s=>[s.name,s])),i=new Map(r.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=i.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}function ue(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var Hi={};function J(r="id"){Hi[r]=Hi[r]||1;let e=Hi[r]++;return`${r}-${e}`}var A9=B(k(),1);function Xi(r,e,t){for(let[n,i]of Object.entries(e)){if(!i)continue;if(!i.format)throw new Error(`${r} GPUVector "${n}" requires a format`);let s=t.find(d=>d.name===n);if(!s)throw new Error(`${r} GPUVector "${n}" requires a Model buffer layout`);let o=s.attributes??[];if(o.length>1)throw new Error(`${r} GPUVector "${n}" does not support interleaved layouts`);let a=o[0],c=s.format??a?.format,u=_9(r,n,i.format),l=s.byteStride??u.byteLength;if(c!==i.format||l!==i.byteStride||i.rowByteLength!==u.byteLength)throw new Error(`${r} GPUVector "${n}" must match its Model buffer layout`)}}function V0(r,e){let t=Object.entries(e).filter(o=>o[1]!==void 0);if(t.length===0)return[];let[n,i]=t[0];for(let[o,a]of t){if(!a.format)throw new Error(`${r} GPUVector "${o}" requires a format`);if(_9(r,o,a.format),a.length!==i.length)throw new Error(`${r} GPUVector "${o}" rows must match "${n}" rows`);if(a.data.length!==i.data.length)throw new Error(`${r} GPUVector chunk counts must align`)}let s=0;return i.data.map((o,a)=>{let c={};for(let[l,d]of t){let f=d.data[a];if(!f||f.length!==o.length)throw new Error(`${r} GPUVector chunk ${a} row counts must align`);if(f.format!==d.format||f.byteStride!==d.byteStride||f.rowByteLength!==d.rowByteLength)throw new Error(`${r} GPUVector "${l}" chunk layout must be stable`);c[l]=f}let u={batchIndex:a,rowIndexOffset:s,rowCount:o.length,data:c};return s+=o.length,u})}function _9(r,e,t){if(t.includes("<"))throw new Error(`${r} GPUVector "${e}" requires a fixed-width scalar format`);return A9.vertexFormatDecoder.getVertexFormatInfo(t)}var Zr=B(k(),1);function C0(r){let e;for(let t of Object.values(r)){if(!t||"isConstant"in t)continue;let n=0;for(let i of t.data)n+=i.length;if((0,Zr.assert)(n===t.length),e){(0,Zr.assert)(t.length===e.length&&t.data.length===e.data.length);for(let i=0;i<t.data.length;i++)(0,Zr.assert)(t.data[i].length===e.data[i].length)}else e=t}}function E9(r,e,t,n,i,s){let o=e.inputs,a=t.inputs,c=e.sourceLayouts,u=t.sourceLayouts,l=e.layouts,d=t.layouts,f=t.stepMode,h=e.batchCount,p=t.batchCount,m=Array.from({length:h},(x,w)=>e.getBatch(w)),g=Array.from({length:p},(x,w)=>t.getBatch(w)),b=M9(m),v=M9(g),T=r.vertexCount,S=r.instanceCount,y=!0;try{let x=r.isInstanced&&t.vertexCount===void 0,w=x?h*p:Math.max(h,p);if(h===0||p===0)return!0;for(let I=0;I<w;I++){let A=x?Math.floor(I/p):Math.min(I,h-1),M=x?I%p:Math.min(I,p-1);e.setInputs(m[A],l,"vertex"),t.setInputs(g[M],d,f),n();let R=e.rowCount!==void 0?b[A]:t.vertexCount!==void 0?v[M]:0;s==="vertex"&&r.setVertexCount(Math.max(0,Math.min(e.rowCount??t.vertexCount??T,T-R))),s==="instance"&&t.instanceCount!==void 0&&r.setInstanceCount(Math.max(0,Math.min(t.instanceCount,S-v[M]))),!(!r.indexBuffer&&r.vertexCount===0||r.isInstanced&&r.instanceCount===0)&&(y=i()&&y)}}finally{e.setInputs(o,c,"vertex"),t.setInputs(a,u,f),n(),r.setVertexCount(T),r.setInstanceCount(S)}return y}function M9(r){let e=0;return r.map(t=>{let n=e;for(let i of Object.values(t))if(i&&"data"in i){e+=i.length;break}return n})}var o0=B(k(),1);var Pt=class{device;id;inputs={};sourceLayouts;stepMode="vertex";claimedNames=new Set;layouts=[];buffers={};byteOffsets={};constants={};rowCount;vertexCount;instanceCount;constantBuffers={};constructor(e,t){this.device=e,this.id=t}setInputs(e,t,n,i=!0){if(i)C0(e);else for(let u of Object.values(e))u&&!q(u)&&(0,o0.assert)(u.data.length===1);this.claimedNames.clear(),this.inputs=e,this.sourceLayouts=t,this.stepMode=n,this.rowCount=void 0,this.vertexCount=void 0,this.instanceCount=void 0;let s=t??Object.entries(e).flatMap(([u,l])=>l&&!q(l)&&l.bufferLayout?[{...l.bufferLayout,name:u}]:[]),o=Object.entries(e).flatMap(([u,l])=>{if(!l||s.some(h=>h.name===u||h.attributes?.some(p=>p.attribute===u)))return[];(0,o0.assert)(l.format);let d=l.format,f=q(l)?0:l.byteStride;return[{name:u,stepMode:n,byteStride:f,attributes:[{attribute:u,format:d,byteOffset:0}]}]}),a=[...s,...m5(e,o)];for(let[u,l]of Object.entries(e))if(l){if(!q(l)&&!Array.isArray(l.data))throw new TypeError(`Expected a GPU vector or constant for ${u}`);!q(l)&&i&&((a.find(h=>h.name===u||h.attributes?.some(p=>p.attribute===u))?.stepMode??n)==="instance"?((0,o0.assert)(this.instanceCount===void 0||this.instanceCount===l.length),this.instanceCount=l.length):((0,o0.assert)(this.vertexCount===void 0||this.vertexCount===l.length),this.vertexCount=l.length),this.rowCount=n==="instance"?this.instanceCount:this.vertexCount),this.claimedNames.add(u)}this.layouts=a.flatMap(u=>{let l=e[u.name],d=u.attributes??(u.format?[{attribute:u.name,format:u.format,byteOffset:0}]:[]),f=d.filter(p=>q(e[p.attribute])),h={...u,stepMode:u.stepMode??n};return this.device.type!=="webgpu"||l&&!q(l)&&l.bufferLayout||!f.length||f.length===d.length?[{...h,byteStride:f.length===d.length&&f.length?0:h.byteStride}]:[{...h,attributes:d.filter(p=>!q(e[p.attribute]))},{...h,name:`${u.name}-constants`,byteStride:0,attributes:f}]}),this.buffers={},this.byteOffsets={},this.constants={};let c=new Set;for(let u of this.layouts){this.claimedNames.add(u.name);let l=u.attributes??(u.format?[{attribute:u.name,format:u.format,byteOffset:0}]:[]);for(let h of l)this.claimedNames.add(h.attribute);let d=e[u.name];if(d&&!q(d)){let h=d.bufferLayout||!d.format?0:(l.find(p=>p.attribute===u.name)??l[0])?.byteOffset??0;this.bindVector(u.name,d,h)}let f=0;for(let h of l){let p=e[h.attribute]??(h.attribute===u.name?e[u.name]:void 0);p&&((0,o0.assert)(p.format===void 0||p.format===h.format),q(p)?(this.constants[h.attribute]=p5(p),f=Math.max(f,(h.byteOffset??0)+p.byteLength)):this.buffers[u.name]||this.bindVector(u.name,p,h.byteOffset??0))}if(this.device.type==="webgpu"&&f&&!this.buffers[u.name]){let h=new Uint8Array(Math.ceil(f/4)*4);for(let m of l){let g=e[m.attribute];q(g)&&h.set(new Uint8Array(g.value.buffer,g.value.byteOffset,g.byteLength),m.byteOffset??0)}let p=this.constantBuffers[u.name];(!p||p.byteLength<h.byteLength)&&(p?.destroy(),p=this.device.createBuffer({id:`${this.id}-${u.name}-constant`,byteLength:h.byteLength,usage:o0.Buffer.VERTEX|o0.Buffer.COPY_DST|o0.Buffer.COPY_SRC}),this.constantBuffers[u.name]=p),p.write(h),this.buffers[u.name]=p,c.add(u.name)}}for(let[u,l]of Object.entries(this.constantBuffers))c.has(u)||(l.destroy(),delete this.constantBuffers[u])}get batchCount(){let e=Object.values(this.inputs).find(t=>t&&!q(t));return e&&!q(e)?e.data.length:1}getBatch(e){return Object.fromEntries(Object.entries(this.inputs).map(([t,n])=>{if(!n||q(n))return[t,n];let i=n.data[e];return[t,{...n,length:i?.length??0,data:i?[i]:[]}]}))}destroy(){for(let e of Object.values(this.constantBuffers))e.destroy();this.constantBuffers={}}bindVector(e,t,n){let i=t.data[0];if(!i)return;let s=i.byteOffset-n;(0,o0.assert)(s>=0),this.buffers[e]=i.buffer,this.byteOffsets[e]=s}};function q(r){return!!(r&&"isConstant"in r&&r.isConstant)}function p5(r){let e=o0.vertexFormatDecoder.getVertexFormatInfo(r.format);if(r.format==="unorm10-10-10-2"){let n=r.value[0];return new Float32Array([(n&1023)/1023,(n>>>10&1023)/1023,(n>>>20&1023)/1023,(n>>>30)/3])}let t=Array.from(r.value);if(r.format==="unorm8x4-bgra"&&([t[0],t[2]]=[t[2],t[0]]),e.normalized){let n=r.value.BYTES_PER_ELEMENT*8,i=2**n-1;return new Float32Array(t.map(s=>e.signed?(s+2**(n-1))/i*2-1:s/i))}return e.integer?e.signed?new Int32Array(t):new Uint32Array(t):new Float32Array(t)}function m5(r,e){let t=[],n,i=0,s=[...e].sort((o,a)=>{let c=r[o.name],u=r[a.name];return(c&&!q(c)?c.data[0]?.byteOffset??0:0)-(u&&!q(u)?u.data[0]?.byteOffset??0:0)});for(let o of s){let a=r[o.name],c=o.attributes[0];if(q(a)){n||(n={...o,attributes:[]},t.push(n));let l=Math.min(4,a.byteLength);i=Math.ceil(i/l)*l,n.attributes.push({...c,byteOffset:i}),i+=a.byteLength;continue}let u=t.find(l=>{let d=r[l.name];if(!d||q(d)||!d.data.length||!a.data.length)return!1;let f=a.data[0].byteOffset-d.data[0].byteOffset;return l.stepMode===o.stepMode&&l.byteStride===o.byteStride&&f>=0&&f+a.rowByteLength<=a.byteStride&&a.data.every((h,p)=>{let m=d.data[p];return h.buffer===m.buffer&&h.byteStride===m.byteStride&&h.byteOffset-m.byteOffset===f})});if(u){let l=r[u.name];u.attributes.push({...c,byteOffset:a.data[0].byteOffset-l.data[0].byteOffset})}else t.push({...o,attributes:[...o.attributes]})}return t}var Qr=B(k(),1),Ki=B(b0(),1);function Yi(r){return(Array.isArray(r)?r.length===0||typeof r[0]=="number":ArrayBuffer.isView(r)&&!(r instanceof DataView))||typeof r=="number"||typeof r=="boolean"}function P9(r,e={}){let t={bindings:{},uniforms:{}};return Object.keys(r).forEach(n=>{let i=r[n];Object.prototype.hasOwnProperty.call(e,n)||Yi(i)?t.uniforms[n]=i:t.bindings[n]=i}),t}var e0=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,Ki.getShaderModuleDependencies)(Object.values(e).filter(g5));for(let i of n)e[i.name]=i;Qr.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[i,s]of Object.entries(e))s&&(this._addModule(s),s.name&&i!==s.name&&!this.options.disableWarnings&&Qr.log.warn(`Module name: ${i} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,i=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||Qr.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(i,o)||i,{uniforms:u,bindings:l}=P9(c,s.uniformTypes);this.moduleUniforms[n]=L9(o,u,s.uniformTypes),this.moduleBindings[n]={...a,...l}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,Ki.getShaderModuleDependencies)(e);for(let n of t){let i=n.name;this.modules[i]||(this.modules[i]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[i,s]of Object.entries(n))e[`${t}.${i}`]={type:this.modules[t].uniformTypes?.[i],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=L9({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function L9(r={},e={},t={}){let n={...r};for(let[i,s]of Object.entries(e))s!==void 0&&(n[i]=Zi(r[i],s,t[i]));return n}function Zi(r,e,t){if(!t||typeof t=="string")return Lt(e);if(Array.isArray(t)){if(Qi(e)||!Array.isArray(e))return Lt(e);let o=Array.isArray(r)&&!Qi(r)?[...r]:[],a=o.slice();for(let c=0;c<e.length;c++){let u=e[c];u!==void 0&&(a[c]=Zi(o[c],u,t[0]))}return a}if(!Ji(e))return Lt(e);let n=t,i=Ji(r)?r:{},s={...i};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=Zi(i[o],a,n[o]));return s}function Lt(r){return ArrayBuffer.isView(r)?Array.prototype.slice.call(r):Array.isArray(r)?Qi(r)?r.slice():r.map(t=>t===void 0?void 0:Lt(t)):Ji(r)?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t===void 0?void 0:Lt(t)])):r}function Qi(r){return ArrayBuffer.isView(r)||Array.isArray(r)&&(r.length===0||typeof r[0]=="number")}function Ji(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&!ArrayBuffer.isView(r)}function g5(r){return!!r?.dependencies}var Rt=globalThis,y5=globalThis.document||{},Jr=globalThis.process||{},x5=globalThis.console,b5=globalThis.navigator||{};function en(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}function j0(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||en()}var e1="5.0.0";function ze(r,e){if(!r)throw new Error(e||"Assertion failed")}function tn(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return ze(Number.isFinite(e)&&e>=0),e}function t1(r){let{logLevel:e,message:t}=r;r.logLevel=tn(e);let n=r.args?Array.from(r.args):[];for(;n.length&&n.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&n.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let i=typeof r.message;return ze(i==="string"||i==="object"),Object.assign(r,{args:n},r.opts)}var W0=()=>{},le=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...n){return this._log("log",e,t,n)}info(e,t,...n){return this._log("info",e,t,n)}once(e,t,...n){return this._log("once",e,t,n,{once:!0})}_log(e,t,n,i,s={}){let o=t1({logLevel:t,message:n,args:this._buildArgs(t,n,i),opts:s});return this._createLogFunction(e,o,s)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return W0;let i=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&i!==void 0){if(this._onceCache.has(i))return W0;this._onceCache.add(i)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=tn(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function T5(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var Ct=class{constructor(e,t,n="sessionStorage"){this.storage=T5(n),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}};function R9(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function r1(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Dt;(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(Dt||(Dt={}));var S5=10;function C9(r){return typeof r!="string"?r:(r=r.toUpperCase(),Dt[r]||Dt.WHITE)}function n1(r,e,t){return!j0&&typeof r=="string"&&(e&&(r=`\x1B[${C9(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${C9(t)+S5}m${r}\x1B[49m`)),r}function i1(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),i=r;for(let s of n){let o=i[s];typeof o=="function"&&(e.find(a=>s===a)||(i[s]=o.bind(r)))}}var rn=class{getHighResolutionTimer(){let e;if(j0()&&Rt.performance)e=Rt?.performance?.now?.();else if("hrtime"in Jr){let t=Jr?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=Rt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},f0=new rn;globalThis.Probe=rn;globalThis.probe=f0;var $e={debug:j0()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},s1={enabled:!0,level:0},D0=class extends le{constructor({id:e}={id:""}){super({level:0}),this.VERSION=e1,this._startTs=f0.getHighResolutionTimer(),this._deltaTs=f0.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new Ct(`__probe-${this.id}__`,{[this.id]:s1}),this.timeStamp(`${this.id} started`),i1(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((f0.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((f0.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:$e.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:$e.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...n){let i=f0.getMemoryUsageMB();if(i!==null){let s=`${i}MB `;typeof t=="function"?t=()=>`${s}${t()}`:typeof t=="string"&&(t=`${s}${t}`)}return this._log("log",e,t,n,{method:$e.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:$e.debug})}info(e,t,...n){return this._log("info",e,t,n,{method:console.info})}once(e,t,...n){return this._log("once",e,t,n,{method:$e.debug||$e.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||W0,tag:I5(t)}):W0}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||W0})}group(e,t,n={collapsed:!1}){let i=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:i})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||W0})}withGroup(e,t,n){this.group(e,t)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let n=t.method;ze(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=f0.getHighResolutionTimer();let i=w5(this.id,t.message,t);return n.bind(console,i,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(s1),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...s1};this._storage.setConfiguration({[this.id]:{...t,...e}})}};D0.VERSION=e1;function w5(r,e,t){if(typeof e=="string"){let n=t.time?r1(R9(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=n1(e,t.color,t.background)}return e}function I5(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=f0);var sh=new D0({id:"@probe.gl/log"});var a0=new D0({id:"luma.gl"});var o1={};function Ue(r="id"){o1[r]=o1[r]||1;let e=o1[r]++;return`${r}-${e}`}function Ve(r,e){if(!r){let t=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(t,Ve),t}}var nn=class{_owner=null;_ownedResources=new Set;_state="live";_destroyingOwnedResources=!1;_destroyRequested=!1;get owner(){return this._owner}get ownedResources(){return Array.from(this._ownedResources)}get destroyed(){return this._state==="destroyed"}transferOwnershipTo(e){Ve(this._state==="live"&&!this._destroyingOwnedResources),Ve(!this._owner||this._owner.canChangeOwnership()),Ve(!e||e.canChangeOwnership());for(let t=e;t;t=t._owner)Ve(t!==this);return e!==this._owner&&(this._owner?._ownedResources.delete(this),this._owner=e,e?._ownedResources.add(this)),this}destroy(){if(this._state!=="live")return;if(this._destroyingOwnedResources){this._destroyRequested=!0;return}this._destroyRequested=!1,this._state="destroying",this._owner?._ownedResources.delete(this),this._owner=null;let e=[];try{try{this.onBeforeDestroy()}catch(t){e.push(t)}this.destroyChildren(e);try{this.onDestroy()}catch(t){e.push(t)}}finally{this._state="destroyed"}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}delete(){return this.destroy(),this}attachResource(e){e.transferOwnershipTo(this)}detachResource(e){e._owner===this&&e.transferOwnershipTo(null)}destroyAttachedResource(e){e._owner===this&&e.destroy()}destroyAttachedResources(){if(this._state!=="live"||this._destroyingOwnedResources)return;let e=[];if(this.destroyChildren(e),this._destroyRequested)try{this.destroy()}catch(t){e.push(t)}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}onBeforeDestroy(){}onDestroy(){}canChangeOwnership(){return this._state==="live"&&!this._destroyingOwnedResources}destroyChildren(e){this._destroyingOwnedResources=!0;try{for(let t of this._ownedResources)try{t.destroy()}catch(n){e.push(n)}}finally{this._ownedResources.clear(),this._destroyingOwnedResources=!1}}};var A5="cpu-hotspot-profiler",D9="GPU Resource Counts",B9="Resource Counts",O9="GPU Time and Memory",_5=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],M5=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],E5=_5.flatMap(r=>[`${r} Created`,`${r} Active`]),P5=M5.flatMap(r=>[`${r} Created`,`${r} Active`]),N9=new WeakMap,k9=new WeakMap,h0=class extends nn{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;allocatedBytes=0;allocatedBytesName=null;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,n){if(super(),!e)throw new Error("no device");this._device=e,this.props=L5(t,n);let i=this.props.id!=="undefined"?this.props.id:Ue(this[Symbol.toStringTag]);this.props.id=i,this.id=i,this.userData=this.props.userData||{},this.addStats()}getProps(){return this.props}destroyHandle(){}onDestroy(){try{this.destroyHandle()}finally{this.trackDeallocatedMemory(),this.removeStats()}}removeStats(){let e=Bt(this._device),t=e?q0():0,n=[this._device.statsManager.getStats(D9),this._device.statsManager.getStats(B9)],i=G9(this._device);for(let o of n)F9(o,i);let s=this.getStatsName();for(let o of n)o.get("Resources Active").decrementCount(),o.get(`${s}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(q0()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Bt(this._device),i=n?q0():0,s=this._device.statsManager.getStats(O9);this.allocatedBytes>0&&this.allocatedBytesName&&(s.get("GPU Memory").subtractCount(this.allocatedBytes),s.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),s.get("GPU Memory").addCount(e),s.get(`${t} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(q0()-i)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=Bt(this._device),n=t?q0():0,i=this._device.statsManager.getStats(O9);i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(q0()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Bt(this._device),n=t?q0():0,i=[this._device.statsManager.getStats(D9),this._device.statsManager.getStats(B9)],s=G9(this._device);for(let o of i)F9(o,s);for(let o of i)o.get("Resources Created").incrementCount(),o.get("Resources Active").incrementCount(),o.get(`${e}s Created`).incrementCount(),o.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(q0()-n)),R5(this._device,e)}getStatsName(){return C5(this)}};function L5(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function F9(r,e){let t=r.stats,n=!1;for(let c of e)t[c]||(r.get(c),n=!0);let i=Object.keys(t).length,s=N9.get(r);if(!n&&s?.orderedStatNames===e&&s.statCount===i)return;let o={},a=k9.get(e);a||(a=new Set(e),k9.set(e,a));for(let c of e)t[c]&&(o[c]=t[c]);for(let[c,u]of Object.entries(t))a.has(c)||(o[c]=u);for(let c of Object.keys(t))delete t[c];Object.assign(t,o),N9.set(r,{orderedStatNames:e,statCount:i})}function G9(r){return r.type==="webgl"?P5:E5}function Bt(r){let e=r.userData[A5];return e?.enabled?e:null}function q0(){return globalThis.performance?.now?.()??Date.now()}function R5(r,e){let t=Bt(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function C5(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===h0.prototype)return D5(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function D5(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var A0=class r extends h0{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let n={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?n.indexType="uint32":t.data instanceof Uint16Array?n.indexType="uint16":t.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,r.defaultProps),this.usage=n.usage||0,this.indexType=n.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,n){if(!this.device.props.debug)return;let i=null,s;ArrayBuffer.isView(e)?(i=e,s=e.buffer):s=e;let o=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(s===null)this.debugData=new ArrayBuffer(o);else{let a=Math.min(i?.byteOffset||0,s.byteLength),c=Math.max(0,s.byteLength-a),u=Math.min(o,c);this.debugData=new Uint8Array(s,a,u).slice().buffer}}static defaultProps={...h0.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var a1=globalThis.Float16Array;function z9(){return a1??Uint16Array}function $9(r){return!!(a1&&r===a1)}var U9=new Map;function V9(r){let e=U9.get(r);if(e)return e;let t=Object.freeze(B5(r));return Object.hasOwn(sn,r)&&U9.set(r,t),t}function B5(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),i=sn[r],[s,o,a]=i||["uint8 ","i32",1];return{signedType:s,primitiveType:o,byteLength:a,normalized:e,integer:t,signed:n}}function j9(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function O5(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if($9(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(sn).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function W9(r){return O5(r)}function N5(r){if(r==="float16")return z9();let e=sn[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function q9(r){return N5(r)}var sn={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]};var c1=class{getDataTypeInfo(e){return V9(e)}getNormalizedDataType(e){return j9(e)}alignTo(e,t){return Or(e,t)}getDataType(e){return W9(e)}getTypedArrayConstructor(e){return q9(e)}},H9=new c1;var t0="texture-compression-bc",F="texture-compression-astc",_0="texture-compression-etc2",X9="texture-compression-etc1-webgl",on="texture-compression-pvrtc-webgl",u1="texture-compression-atc-webgl",an="float32-renderable-webgl",l1="float16-renderable-webgl",k5="rgb9e5ufloat-renderable-webgl",d1="snorm8-renderable-webgl",H0="norm16-webgl",f1="norm16-renderable-webgl",h1="snorm16-renderable-webgl",cn="float32-filterable",Y9="float16-filterable-webgl",Ot=1,Nt=2,g1=4,y1=8,We=16,ln=5,Z9=10,H=Ot|Nt,un=Ot|g1,B0=Ot|Nt|g1|y1,M0=Ot|Nt|We,F5=Ot|g1|We,m1=B0|We,K9=(Nt|y1|We)<<ln,G5=(Nt|y1)<<ln,i0=We<<ln,je=m1<<ln,z5=B0<<Z9,p1=We<<Z9;function dn(r){let e=V5[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var $5={r8unorm:{webgpu:B0|i0},rg8unorm:{webgpu:B0|i0},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:m1},"rgba8unorm-srgb":{webgpu:B0},r8snorm:{render:d1,webgpu:un|K9},rg8snorm:{render:d1,webgpu:un|K9},"rgb8snorm-webgl":{},rgba8snorm:{render:d1,webgpu:F5|G5},r8uint:{webgpu:H|i0},rg8uint:{webgpu:H|i0},rgba8uint:{webgpu:M0},r8sint:{webgpu:H|i0},rg8sint:{webgpu:H|i0},rgba8sint:{webgpu:M0},bgra8unorm:{webgpu:B0},"bgra8unorm-srgb":{webgpu:z5},r16unorm:{f:H0,render:f1,webgpu:je},rg16unorm:{f:H0,render:f1,webgpu:je},"rgb16unorm-webgl":{f:H0,render:!1},rgba16unorm:{f:H0,render:f1,webgpu:je},r16snorm:{f:H0,render:h1,webgpu:je},rg16snorm:{f:H0,render:h1,webgpu:je},"rgb16snorm-webgl":{f:H0,render:!1},rgba16snorm:{f:H0,render:h1,webgpu:je},r16uint:{webgpu:H|i0},rg16uint:{webgpu:H|i0},rgba16uint:{webgpu:M0},r16sint:{webgpu:H|i0},rg16sint:{webgpu:H|i0},rgba16sint:{webgpu:M0},r16float:{render:l1,filter:"float16-filterable-webgl",webgpu:B0|i0},rg16float:{render:l1,filter:Y9,webgpu:B0|i0},rgba16float:{render:l1,filter:Y9,webgpu:m1},r32uint:{webgpu:M0},rg32uint:{webgpu:H|p1},rgba32uint:{webgpu:M0},r32sint:{webgpu:M0},rg32sint:{webgpu:H|p1},rgba32sint:{webgpu:M0},r32float:{render:an,filter:cn,webgpu:M0},rg32float:{render:!1,filter:cn,webgpu:H|p1},"rgb32float-webgl":{render:an,filter:cn},rgba32float:{render:an,filter:cn,webgpu:M0},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:k5,webgpu:un},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:an,webgpu:un|i0},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:B0|i0},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:H|i0},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:H},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:H},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:H},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:H},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:H},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:H}},U5={"bc1-rgb-unorm-webgl":{f:t0},"bc1-rgb-unorm-srgb-webgl":{f:t0},"bc1-rgba-unorm":{f:t0},"bc1-rgba-unorm-srgb":{f:t0},"bc2-rgba-unorm":{f:t0},"bc2-rgba-unorm-srgb":{f:t0},"bc3-rgba-unorm":{f:t0},"bc3-rgba-unorm-srgb":{f:t0},"bc4-r-unorm":{f:t0},"bc4-r-snorm":{f:t0},"bc5-rg-unorm":{f:t0},"bc5-rg-snorm":{f:t0},"bc6h-rgb-ufloat":{f:t0},"bc6h-rgb-float":{f:t0},"bc7-rgba-unorm":{f:t0},"bc7-rgba-unorm-srgb":{f:t0},"etc2-rgb8unorm":{f:_0},"etc2-rgb8unorm-srgb":{f:_0},"etc2-rgb8a1unorm":{f:_0},"etc2-rgb8a1unorm-srgb":{f:_0},"etc2-rgba8unorm":{f:_0},"etc2-rgba8unorm-srgb":{f:_0},"eac-r11unorm":{f:_0},"eac-r11snorm":{f:_0},"eac-rg11unorm":{f:_0},"eac-rg11snorm":{f:_0},"astc-4x4-unorm":{f:F},"astc-4x4-unorm-srgb":{f:F},"astc-5x4-unorm":{f:F},"astc-5x4-unorm-srgb":{f:F},"astc-5x5-unorm":{f:F},"astc-5x5-unorm-srgb":{f:F},"astc-6x5-unorm":{f:F},"astc-6x5-unorm-srgb":{f:F},"astc-6x6-unorm":{f:F},"astc-6x6-unorm-srgb":{f:F},"astc-8x5-unorm":{f:F},"astc-8x5-unorm-srgb":{f:F},"astc-8x6-unorm":{f:F},"astc-8x6-unorm-srgb":{f:F},"astc-8x8-unorm":{f:F},"astc-8x8-unorm-srgb":{f:F},"astc-10x5-unorm":{f:F},"astc-10x5-unorm-srgb":{f:F},"astc-10x6-unorm":{f:F},"astc-10x6-unorm-srgb":{f:F},"astc-10x8-unorm":{f:F},"astc-10x8-unorm-srgb":{f:F},"astc-10x10-unorm":{f:F},"astc-10x10-unorm-srgb":{f:F},"astc-12x10-unorm":{f:F},"astc-12x10-unorm-srgb":{f:F},"astc-12x12-unorm":{f:F},"astc-12x12-unorm-srgb":{f:F},"pvrtc-rgb4unorm-webgl":{f:on},"pvrtc-rgba4unorm-webgl":{f:on},"pvrtc-rgb2unorm-webgl":{f:on},"pvrtc-rgba2unorm-webgl":{f:on},"etc1-rgb-unorm-webgl":{f:X9},"etc1-rbg-unorm-webgl":{f:X9},"atc-rgb-unorm-webgl":{f:u1},"atc-rgba-unorm-webgl":{f:u1},"atc-rgbai-unorm-webgl":{f:u1}},V5={...$5,...U5};var j5=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,W5=["rgb","rgba","bgra"],q5=["depth","stencil"],H5=5,X5=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],x1=class{isColor(e){return W5.some(t=>e.startsWith(t))}isDepthStencil(e){return q5.some(t=>e.startsWith(t))}isCompressed(e){return X5.some(t=>e.startsWith(t))}getInfo(e){return J9(e)}getCapabilities(e){return K5(e)}getWebGPUCapabilities(e){let t=dn(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?H5:0}computeMemoryLayout(e,t){return Y5(e,t)}},qe=new x1;function Y5({format:r,width:e,height:t,depth:n,byteAlignment:i},s={}){let o=qe.getInfo(r),{bytesPerPixel:a,blockHeight:c=1,compressed:u=!1}=o,l=b1(o,e,i),d=u?Math.ceil(t/c):t;return s.bytesPerPixel=a,s.bytesPerRow=l,s.rowsPerImage=d,s.depthOrArrayLayers=n,s.bytesPerImage=l*d,s.byteLength=s.bytesPerImage*n,s}function b1(r,e,t){let{bytesPerPixel:n,bytesPerBlock:i=n,blockWidth:s=1,compressed:o=!1}=r,a=o?Math.ceil(e/s):e;return Math.ceil(a*i/t)*t}function K5(r){let e=dn(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=J9(r),i=r.startsWith("depth")||r.startsWith("stencil"),s=n?.signed,o=n?.integer,a=n?.webgl,c=!!n?.compressed;return t.render&&=!i&&!c,t.filter&&=!i&&!s&&!o&&!a,t}var Q9=new Map;function J9(r){let e=Q9.get(r);if(!e){let t=Z5(r);t.bitsPerChannel=Object.freeze([...t.bitsPerChannel]),e=Object.freeze(t),Q9.set(r,e)}return e}function Z5(r){let e=Q5(r);if(qe.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=e8(r);let n=J5(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:j5.exec(r);if(t){let[,n,i,s,o,a]=t,c=`${s}${i}`,u=H9.getDataTypeInfo(c),l=u.byteLength*8,d=n?.length??1,f=[l,d>=2?l:0,d>=3?l:0,d>=4?l:0];e={format:r,attachment:e.attachment,dataType:u.signedType,components:d,channels:n,integer:u.integer,signed:u.signed,normalized:u.normalized,bitsPerChannel:f,bytesPerPixel:u.byteLength*d,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),o==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Q5(r){let e={...dn(r)},t=e.bytesPerPixel||1,n=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:n,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function J5(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,i]=t;return{blockWidth:Number(n),blockHeight:Number(i)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function e8(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}function kt(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function fn(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var X0=class r extends h0{static defaultProps={...h0.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}};function e2(r,e){let t=e instanceof X0?e:r.device.createSampler(e);if(t===r.sampler)return;e instanceof X0||t.transferOwnershipTo(r);let n=r.sampler;r.sampler=t,n?.owner===r&&n.destroy()}var t2=[],t8=Object.freeze({}),r8={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},r0=class r extends h0{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,n){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=r8[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let i=e.getExternalImageSize(t.data);this.width=i?.width||1,this.height=i?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&a0.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){e2(this,e)}copyImageData(e){let{data:t,depth:n,...i}=e;this.writeData(t,{...i,depthOrArrayLayers:i.depthOrArrayLayers??n})}computeMemoryLayout(e=t8,t){let n=t2.pop()||{readOptions:{},layoutOptions:{}};try{let i=this._normalizeTextureReadOptions(e,n.readOptions),s=n.layoutOptions;return s.format=this.format,s.width=i.width,s.height=i.height,s.depth=i.depthOrArrayLayers,s.byteAlignment=this.byteAlignment,qe.computeMemoryLayout(s,t)}finally{t2.push(n)}}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let n={...t},{width:i,height:s}=n;return typeof i=="number"&&(n.width=Math.max(1,Math.ceil(i))),typeof s=="number"&&(n.height=Math.max(1,Math.ceil(s))),n}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e,t={}){let{data:n,depth:i,depthOrArrayLayers:s}=e;if(this._normalizeTextureWriteOptions(e,t),s===void 0&&i!==void 0){let o=this.dimension==="3d"?Math.max(1,this.depth>>t.mipLevel):this.depth;t.depthOrArrayLayers=Math.min(i,o-t.z)}return t.data=n,t.depth=t.depthOrArrayLayers,t}_normalizeCopyExternalImageOptions(e,t={}){let{width:n,height:i}=e,s=this.device.getExternalImageSize(e.image),o=r._normalizeOptions(e,r.defaultCopyExternalImageOptions,t),a=Math.max(1,this.width>>o.mipLevel),c=this.baseDimension==="1d"?1:Math.max(1,this.height>>o.mipLevel),u=this.dimension==="3d"?Math.max(1,this.depth>>o.mipLevel):this.depth;return o.width=Math.min(n??s.width,a-o.x),o.height=Math.min(i??s.height,c-o.y),o.depth=Math.min(o.depth,u-o.z),o}_normalizeCopyElementImageOptions(e,t={}){let n=r._normalizeOptions(e,r.defaultCopyElementImageOptions,t),i=Math.max(1,this.width>>n.mipLevel),s=this.baseDimension==="1d"?1:Math.max(1,this.height>>n.mipLevel),o=this.dimension==="3d"?Math.max(1,this.depth>>n.mipLevel):this.depth;return n.width=Math.min(n.width??i,i-n.x),n.height=Math.min(n.height??s,s-n.y),n.depth=Math.min(n.depth,o-n.z),n}_normalizeTextureReadOptions(e,t={}){let{depthOrArrayLayers:n}=e,i=r._normalizeOptions(e,r.defaultTextureReadOptions,t),s=Math.max(1,this.width>>i.mipLevel),o=this.baseDimension==="1d"?1:Math.max(1,this.height>>i.mipLevel),a=this.dimension==="3d"?Math.max(1,this.depth>>i.mipLevel):this.depth;return i.width=Math.min(i.width??s,s-i.x),i.height=Math.min(i.height??o,o-i.y),i.depthOrArrayLayers=Math.min(n??a,a-i.z),i}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=qe.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(n),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e,t={}){let{byteOffset:n=0,bytesPerRow:i,rowsPerImage:s}=e;this._normalizeTextureReadOptions(e,t);let o=t;o.byteOffset=n;let a=this.device.getTextureFormatInfo(this.format),c=a.bytesPerPixel*o.width;if(o.bytesPerRow=i??b1(a,o.width,this.byteAlignment),o.rowsPerImage=s??o.height,o.bytesPerRow<c)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be at least ${c} for ${this.format}`);if(o.rowsPerImage<o.height)throw new Error(`rowsPerImage (${o.rowsPerImage}) must be at least ${o.height} for ${this.format}`);let{bytesPerPixel:u}=a;if(u&&o.bytesPerRow%u!==0)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be a multiple of bytesPerPixel (${u}) for ${this.format}`);return o}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),i=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:i}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:i,depthOrArrayLayers:s}=this._getMipLevelSize(t);e+=qe.computeMemoryLayout({format:this.format,width:n,height:i,depth:s,byteAlignment:1}).byteLength}return e*this.samples}static _normalizeOptions(e,t,n){for(let i in t)n[i]=e[i]===void 0?t[i]:e[i];return n}static defaultProps={...h0.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}};function hn(r,e,t){let n=r.bindings.find(i=>i.name===e||`${i.name.toLocaleLowerCase()}uniforms`===e.toLocaleLowerCase());return!n&&!t?.ignoreWarnings&&a0.warn(`Binding ${e} not set: Not found in shader layout.`)(),n||null}var s8=A0.DEBUG_DATA_MAX_LENGTH,$=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:i,ownsBuffer:s=!0,...o}=t;if(i&&i.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(i&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||i?.id||Ue("dynamic-buffer"),c={...o,id:a,usage:o.usage??i?.usage,indexType:o.indexType??i?.indexType};(c.usage||0)&A0.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:s8,this._ownsBuffer=s,this._buffer=i??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let i=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),i=new Uint8Array(s.slice(0,n))},t,n),this._touch(),i&&this._writeDebugData(i,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let i=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(i=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return i&&this._writeDebugData(i,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let i=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...u}=this.props,l=this.device.createBuffer({...u,byteLength:t});return n&&i>0&&this._copyBufferContents(s,l,i),this._buffer=l,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let i=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:i}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),i=new Uint8Array(this.debugData),s=Math.min(n.byteLength,i.byteLength-t);return i.set(n.subarray(0,s),t),s>0}};function O0(r){return r!==null&&typeof r=="object"&&"buffer"in r}function pn(r){return r instanceof $?r:O0(r)&&r.buffer instanceof $?r.buffer:null}function v1(r){return r instanceof $?r.buffer:r}function He(r){return{buffer:v1(r.buffer),offset:r.offset,size:r.size}}var T1={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function Ft(r){return r?Array.isArray(r)?r[0]??null:r:null}function r2(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=Ft(t);if(!n)return null;let{width:i}=Gt(n);return{width:i,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=Ft(t);return n?Gt(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=Ft(t[0]);return n?Gt(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let i=t[n],s=Ft(i);return s?Gt(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],i=Object.keys(n)[0]??null;if(!i)return null;let s=Ft(n[i]);return s?Gt(s):null}default:return null}}function Gt(r){if(kt(r))return fn(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function o8(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function a8(r){return ArrayBuffer.isView(r)}function S1(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function n2(r){let e=T1[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function c8(r,e){return 6*r+n2(e)}function w1(r){throw new Error("setTexture1DData not supported in WebGL.")}function u8(r){return Array.isArray(r)?r:[r]}function de(r,e,t,n){let i=u8(e),s=r,o=[];for(let a=0;a<i.length;a++){let c=i[a];if(kt(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(o8(c))o.push({type:"texture-data",data:c,textureFormat:S1(c),z:s,mipLevel:a});else if(a8(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function I1(r){let e=[];for(let t=0;t<r.length;t++)e.push(...de(t,r[t]));return e}function A1(r){let e=[];for(let t=0;t<r.length;t++)e.push(...de(t,r[t]));return e}function _1(r){let e=[];for(let[t,n]of Object.entries(r)){let i=n2(t);e.push(...de(i,n))}return e}function M1(r){let e=[];return r.forEach((t,n)=>{for(let[i,s]of Object.entries(t)){let o=c8(n,i);e.push(...de(o,s))}}),e}var c0=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=Ue("dynamic-texture"),i=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(i)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?l8({...t,width:e.width,height:e.height,format:e.format}):[],i="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let m=r2(t);return m||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=d8(this.device,n,a,{format:i?e.format:void 0}),u=c.format??this.props.format,l={...this.props,...a,format:u,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(u)&&!s&&(l.usage=r0.SAMPLE|r0.COPY_DST);let d=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(u);if(this.device.type==="webgpu"&&d){let m=this.props.dimension==="3d"?r0.SAMPLE|r0.STORAGE|r0.COPY_DST|r0.COPY_SRC:r0.SAMPLE|r0.RENDER|r0.COPY_DST|r0.COPY_SRC;l.usage|=m}let f=this.device.getMipLevelCount(l.width,l.height),h=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?f:Math.max(1,Math.min(f,this.props.mipLevels??1)),p={...l,mipLevels:h};this._texture=this.device.createTexture(p),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!d&&a0.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),a0.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):a0.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof X0?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),o=this.device.createBuffer({byteLength:s.byteLength,usage:A0.COPY_DST|A0.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:i},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),a0.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=T1[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=w1(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=de(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=I1(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=A1(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=_1(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=M1(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:i}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:i,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${i} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:i});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await E1(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&a0.warn(`${this} already destroyed`)}_checkReady(){this.isReady||a0.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...r0.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function l8(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return w1(r.data);case"2d":return de(0,r.data,e,t);case"3d":return I1(r.data);case"2d-array":return A1(r.data);case"cube":return _1(r.data);case"cube-array":return M1(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function d8(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let i=new Map;for(let l of e){let d=i.get(l.z)??[];d.push(l),i.set(l.z,d)}let s=e.some(l=>l.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[l,d]of i){let f=[...d].sort((v,T)=>v.mipLevel-T.mipLevel),h=f[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${l} is missing mip level 0`);let p=s2(r,h);if(p.width!==t.width||p.height!==t.height)throw new Error(`DynamicTexture: slice ${l} base level dimensions ${p.width}x${p.height} do not match expected ${t.width}x${t.height}`);let m=i2(h);if(m){if(o&&o!==m)throw new Error(`DynamicTexture: slice ${l} base level format "${m}" does not match texture format "${o}"`);o=m}let g=o&&r.isTextureFormatCompressed(o)?f8(r,p.width,p.height,o):r.getMipLevelCount(p.width,p.height),b=0;for(let v=0;v<f.length;v++){let T=f[v];if(!T||T.mipLevel!==v||v>=g)break;let S=s2(r,T),y=Math.max(1,p.width>>v),x=Math.max(1,p.height>>v);if(S.width!==y||S.height!==x)break;let w=i2(T);if(w&&(o||(o=w),w!==o))break;b++,c.push(T)}a=Math.min(a,b)}let u=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(l=>l.mipLevel<u),mipLevels:u,format:o,hasExplicitMipChain:s}}function i2(r){if(r.type==="texture-data")return r.textureFormat??S1(r.data)}function s2(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function f8(r,e,t,n){let{blockWidth:i=1,blockHeight:s=1}=r.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),u=Math.max(1,t>>a);if(c<i||u<s)break;o++}return o}async function E1(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(E1));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(E1)),n=Object.keys(e),i={};for(let s=0;s<n.length;s++)i[n[s]]=t[s];return i}return r}function v0(r){return r!==null&&typeof r=="object"&&"resolveTextureBinding"in r&&typeof r.resolveTextureBinding=="function"}function o2(r){return r?.type==="texture"||r?.type==="external-texture"}function zt(r,e,t){let n=hn(r,e,{ignoreWarnings:!0});return o2(n)?n:r.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var E0=2,m8=1e4,P1="render pipeline initialization failed",g8=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],p0=class r{static async createAsync(e,t){let n=!E.PipelineFactory.getAsyncCompilation(e),i=n?E.PipelineFactory.beginAsyncCompilation(e):E.PipelineFactory.getAsyncCompilation(e),s;try{s=new this(e,t)}finally{n&&E.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}static defaultProps={...E.RenderPipeline.defaultProps,inferDrawCount:"no",enforceMatchingVectorLengths:!0,geometry:null,attributeVectors:void 0,source:void 0,sourceLanguage:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:void 0,debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;_uniformStore;_attributeInfos={};props;batchUniformBuffer;geometryVectorBindings;attributeVectorBindings;explicitBufferLayout=[];constructorDrawCounts;constructorDrawOffsets;drawingVectorBatches=!1;indexVector=null;currentAttributes={};currentAttributeByteOffsets={};_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_vertexCountSet=!1;_lastDrawTimestamp=-1;_bindingTable=[];_pipelineInitialization;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){this.constructorDrawOffsets={firstVertex:t.firstVertex,firstIndex:t.firstIndex};let n=this.constructor.defaultProps;this.constructorDrawCounts={vertexCount:t.vertexCount??(n.vertexCount||void 0),instanceCount:t.instanceCount??(n.instanceCount||void 0)};let i=n.shaderAssembler,s=Object.hasOwn(t,"vertexCount");this.props={...n,...t,shaderAssembler:t.shaderAssembler??(i&&L1(i,e.info.shadingLanguage)?i:e.info.shadingLanguage==="wgsl"?new $0:new At)},this._vertexCountSet=s,t=this.props,this.id=t.id||J("model"),this.device=e,Object.assign(this.userData,t.userData),this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,this.isInstanced=t.isInstanced??(t.instanceCount?!0:void 0),this.explicitBufferLayout=this.bufferLayout,this.geometryVectorBindings=new Pt(e,`${this.id}-geometry`),this.attributeVectorBindings=new Pt(e,`${this.id}-attributes`);try{this._initializeProps(t);let o=ue(e),a=(0,mn.resolveShaderPlugins)(this.props.plugins,o.shaderLanguage),c=(0,mn.mergeShaderPluginModules)(this.props.modules,a.modules),u=Object.fromEntries(c.map(m=>[m.name,m])),l=t.shaderInputs||new e0(u,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&a.modules.length>0&&l.addModules(a.modules),this.setShaderInputs(l);let d=Kr(this.props.modules,l.getModules()),f={...a.defines,...this.props.defines};if(this.device.type==="webgl"&&(this.props._uniformBlockLayouts=I9(d)),this.props.shaderLayout=Ge(this.props.shaderLayout,d)||null,this.device.type==="webgpu"&&this.props.source){let m=this.props.shaderAssembler;(0,E.assert)(L1(m,"wgsl"));let{source:g,getUniforms:b,bindingTable:v,entryPoints:T={},shaderLayout:S}=m.assembleWGSLShader({platformInfo:o,...this.props,modules:d,defines:f,pluginInjectionTargets:a.injectionTargets,pluginInjections:a.injections,pluginVertexInputs:a.vertexInputs,pluginInterStageVariables:a.interStageVariables});this.source=g,this.props.vertexEntryPoint=T.vertex||this.props.vertexEntryPoint,this.props.fragmentEntryPoint=T.fragment||this.props.fragmentEntryPoint,this._getModuleUniforms=b,this._bindingTable=v;let y=S??e.getShaderLayout?.(this.source),x=y8(y,a.vertexInputs),w=w9(this.props.shaderLayout,x,Object.keys(a.vertexInputs));this.props.shaderLayout=Ge(w||null,d)||null}else{let m=this.props.shaderAssembler;(0,E.assert)(L1(m,"glsl"));let{vs:g,fs:b,getUniforms:v}=m.assembleGLSLShaderPair({platformInfo:o,...this.props,modules:d,defines:f,pluginInjectionTargets:a.injectionTargets,pluginInjections:a.injections,pluginVertexInputs:a.vertexInputs,pluginInterStageVariables:a.interStageVariables});this.vs=g,this.fs=b,this._getModuleUniforms=v,this._bindingTable=[]}this.pipelineFactory=t.pipelineFactory||E.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||E.ShaderFactory.getDefaultShaderFactory(this.device);let p=E.PipelineFactory.getAsyncCompilation(this.device);p?(this._pipelineInitialization=this._initializePipelineAsync(t),p.push(this._pipelineInitialization)):(this.pipeline=this._updatePipeline(),this._initializePipelineResources(t))}catch(o){try{r.prototype.destroy.call(this)}finally{throw o}}}_initializeProps(e){e.geometry&&this.setGeometry(e.geometry),e.attributeVectors&&this.setAttributeVectors(e.attributeVectors)}_usesManagedUniformBuffer(e){return!0}async _initializePipelineAsync(e){await this._updatePipelineAsync(),this._initializePipelineResources(e)}_initializeAttributes(){this.applyVectorAttributes(),this.indexVector&&this.bindIndexVector()}_initializePipelineResources(e){this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._initializeAttributes(),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.indexCount!==void 0&&this.setIndexCount(e.indexCount),this.constructorDrawOffsets.firstVertex!==void 0&&(this.firstVertex=this.constructorDrawOffsets.firstVertex),this.constructorDrawOffsets.firstIndex!==void 0&&(this.firstIndex=this.constructorDrawOffsets.firstIndex),e.isInstanced!==void 0&&(this.isInstanced=e.isInstanced),this.constructorDrawCounts.instanceCount!==void 0&&this.setInstanceCount(this.constructorDrawCounts.instanceCount),this.constructorDrawCounts.vertexCount!==void 0&&this.setVertexCount(this.constructorDrawCounts.vertexCount),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback)}destroy(){this._destroyed||(this.pipeline&&(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs)),this.vertexArray?.destroy(),this.geometryVectorBindings.destroy(),this.attributeVectorBindings.destroy(),this._uniformStore?.destroy(),this.batchUniformBuffer?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e,t){return t?.parameters?this._withDrawParameters(e,t.parameters,()=>this._draw(e)):this._draw(e)}_withDrawParameters(e,t,n){let i=e.getParameters();try{return e.setParameters(t),n()}finally{e.setParameters(i)}}_draw(e){if(this.indexVector?.length===0)return this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1,!0;if(!this.drawingVectorBatches&&(this.geometryVectorBindings.batchCount!==1||this.attributeVectorBindings.batchCount!==1))return this.drawVectorGroups(e);if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,i=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),i=this.pipeline.isErrored,i)E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${P1}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:u}=this.vertexArray,l=u?this.indexCount??(this._vertexCountSet?this.vertexCount:u.byteLength/(u.indexType==="uint32"?4:2)):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:l,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):i?(this._needsRedraw=P1,this._drawBlockedReason=P1):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){e&&this.setTopology(e.topology),this.setGeometryVectors(e?.attributes??{},e?.bufferLayout),this.setIndexVector(e?.indices??null),e?.vertexCount!==void 0&&this.setVertexCount(e.vertexCount)}setGeometryVectors(e,t){t??=this.getExplicitVectorLayouts(e)??this.getExplicitVectorLayouts(e,this.geometryVectorBindings.sourceLayouts),this.validateVectorLengthPolicy(),this.props.enforceMatchingVectorLengths&&C0(e),this.props.enforceMatchingVectorLengths&&(!this.isInstanced||this.attributeVectorBindings.vertexCount!==void 0)&&C0([...Object.values(e),...Object.values(this.attributeVectorBindings.inputs)]),this.geometryVectorBindings.setInputs(e,t,"vertex",this.props.enforceMatchingVectorLengths),this.claimVectorLayouts(this.geometryVectorBindings),this.syncVectorBindings();let n=this.geometryVectorBindings.rowCount;(0,E.assert)(n===void 0||this.attributeVectorBindings.vertexCount===void 0||n===this.attributeVectorBindings.vertexCount),this.props.inferDrawCount==="vertex"&&this.setVertexCount(n??this.attributeVectorBindings.vertexCount??0)}setAttributeVectors(e,t){t??=this.getExplicitVectorLayouts(e)??this.getExplicitVectorLayouts(e,this.attributeVectorBindings.sourceLayouts),this.isInstanced===void 0&&(t?.some(s=>s.stepMode==="instance")||Object.values(e).some(s=>s&&"data"in s&&s.bufferLayout?.stepMode==="instance"))&&(this.isInstanced=!0);let n=!this.isInstanced||Object.entries(e).some(([s,o])=>o&&"data"in o&&(t?.find(a=>a.name===s||a.attributes?.some(c=>c.attribute===s))?.stepMode??o.bufferLayout?.stepMode)==="vertex");this.validateVectorLengthPolicy(),n&&this.props.enforceMatchingVectorLengths&&C0([...Object.values(this.geometryVectorBindings.inputs),...Object.values(e)]),this.attributeVectorBindings.setInputs(e,t,this.isInstanced?"instance":"vertex",this.props.enforceMatchingVectorLengths),this.claimVectorLayouts(this.attributeVectorBindings),this.syncVectorBindings(),this.props.inferDrawCount==="instance"&&this.attributeVectorBindings.instanceCount!==void 0&&this.setInstanceCount(this.attributeVectorBindings.instanceCount);let i=this.attributeVectorBindings.vertexCount;if(i!==void 0&&this.props.inferDrawCount==="vertex"){let s=this.geometryVectorBindings.rowCount;(0,E.assert)(s===void 0||s===i),s===void 0&&this.setVertexCount(i)}}setGPUAttributes(e,t){this.setAttributeVectors(e,t)}setIndexVector(e){e&&((0,E.assert)(e.format==="uint8"||e.format==="uint16"||e.format==="uint32"),(0,E.assert)(e.data.length<=1),(0,E.assert)(e.byteStride===(e.format==="uint32"?4:e.format==="uint16"?2:1))),this.indexVector=e,this.vertexArray&&this.bindIndexVector()}bindIndexVector(){let e=this.indexVector,t=e?.data[0];if(t&&this.indexVector){let n=t.buffer instanceof $?t.buffer.buffer:t.buffer;(0,E.assert)(n.indexType===this.indexVector.format&&t.byteOffset%this.indexVector.byteStride===0)}this.indexVector=null,this.setIndexBuffer(t?.buffer??null),this.indexVector=e,this.indexCount=e?.length,this.setDrawOffsets({firstVertex:t?.byteOffset??0,firstIndex:t?t.byteOffset/this.indexVector.byteStride:0})}claimVectorLayouts(e){this.explicitBufferLayout=this.explicitBufferLayout.filter(t=>!e.claimedNames.has(t.name)&&!t.attributes?.some(n=>e.claimedNames.has(n.attribute)))}getExplicitVectorLayouts(e,t=this.explicitBufferLayout){let n=new Set(Object.keys(e)),i=t.filter(s=>n.has(s.name)||s.attributes?.some(o=>n.has(o.attribute)));return i.length?i:void 0}getVectorBufferLayout(){let e=[this.geometryVectorBindings,this.attributeVectorBindings];return[...this.explicitBufferLayout.filter(n=>!e.some(i=>i.claimedNames.has(n.name)||n.attributes?.some(s=>i.claimedNames.has(s.attribute)))),...this.geometryVectorBindings.layouts,...this.attributeVectorBindings.layouts]}syncVectorBindings(){let e=this.getVectorBufferLayout();this.vertexArray?(this.applyBufferLayout(e),this.applyVectorAttributes()):this.bufferLayout=e}applyVectorAttributes(){let e=new Set(this.bufferLayout.map(t=>t.name));for(let t of Object.keys(this.currentAttributes))e.has(t)||delete this.currentAttributes[t];this.setAttributes({...this.currentAttributes,...this.geometryVectorBindings.buffers,...this.attributeVectorBindings.buffers},{byteOffsets:{...this.currentAttributeByteOffsets,...this.geometryVectorBindings.byteOffsets,...this.attributeVectorBindings.byteOffsets},disableWarnings:!0}),this.device.type==="webgl"&&this.setConstantAttributes({...this.geometryVectorBindings.constants,...this.attributeVectorBindings.constants})}setGPUVectors(e,t){let n=V0(this.id,e);(0,E.assert)(n.length<=1),Xi(this.id,e,this.bufferLayout),n[0]&&this.setGPUData(n[0].data),this.setBatchDrawCount(n[0]?.rowCount??0,t?.count)}drawVectorGroups(e){let t=this.drawingVectorBatches,n=this._vertexCountSet;this.drawingVectorBatches=!0;try{let i=E9(this,this.geometryVectorBindings,this.attributeVectorBindings,()=>this.syncVectorBindings(),()=>r.prototype.draw.call(this,e),this.props.inferDrawCount);return i&&(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1),i}finally{this._vertexCountSet=n,this.drawingVectorBatches=t}}drawBatches(e,{vectors:t,onBatch:n}){let i=V0(this.id,t);Xi(this.id,t,this.bufferLayout);for(let m of Object.keys(t))(0,E.assert)(!t[m]||this.currentAttributes[m]);let s={...this.currentAttributes},o={...this.currentAttributeByteOffsets},a={...this.bindings},c=this.instanceCount,u=this.vertexCount,l=this.isInstanced,d=this._vertexCountSet,f=this.drawingVectorBatches,h=this.device.type==="webgpu"&&i.length?new E.UniformStore(this.device,this.shaderInputs.modules):void 0;if(h&&this._uniformStore.uniformBuffers.size){this.batchUniformBuffer??=new Hr(this.device);let m=0;for(let g of this._uniformStore.uniformBuffers.keys())m+=this.batchUniformBuffer.getAlignedByteLength(h.getUniformBufferData(g).byteLength);this.batchUniformBuffer.prepare(m*i.length)}this.drawingVectorBatches=!0;let p=!0;try{for(let m of i){this.setGPUData(m.data),this.setBatchDrawCount(m.rowCount),n?.(m);let g={};try{if(h){h.setUniforms(this.shaderInputs.getUniformValues());for(let[b,v]of this._uniformStore.uniformBuffers){let T=`${b}Uniforms`;this.bindings[T]===v&&(g[T]=v,this.setBindings({[T]:this.batchUniformBuffer.write(h.getUniformBufferData(b))}))}}p=r.prototype.draw.call(this,e)&&p}finally{this.setBindings(g)}}}finally{h?.destroy(),this.setAttributes(s,{byteOffsets:o});for(let m of Object.keys(this.bindings))m in a||delete this.bindings[m];this.setBindings(a),this.setInstanceCount(c),this.setVertexCount(u),this.isInstanced=l,this._vertexCountSet=d,this.drawingVectorBatches=f}return p}setGPUData(e){this.setAttributes(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.buffer])),{byteOffsets:Object.fromEntries(Object.entries(e).map(([t,n])=>{let i=this.bufferLayout.find(o=>o.name===t),s=n.byteOffset-(i?.attributes?.[0]?.byteOffset??0);return(0,E.assert)(s>=0),[t,s]}))})}validateVectorLengthPolicy(){(0,E.assert)(this.props.enforceMatchingVectorLengths!==!1||this.props.inferDrawCount==="no")}setBatchDrawCount(e,t=this.props.inferDrawCount==="no"?"none":this.props.inferDrawCount){t==="instance"?this.setInstanceCount(e):t==="vertex"&&this.setVertexCount(e)}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){this.explicitBufferLayout=e;let t=this.geometryVectorBindings,n=this.attributeVectorBindings,i=this.getExplicitVectorLayouts(t.inputs)??t.sourceLayouts,s=this.getExplicitVectorLayouts(n.inputs)??n.sourceLayouts;t.setInputs(t.inputs,i,"vertex",this.props.enforceMatchingVectorLengths),n.setInputs(n.inputs,s,this.isInstanced?"instance":"vertex",this.props.enforceMatchingVectorLengths),this.props.enforceMatchingVectorLengths&&(!this.isInstanced||n.vertexCount!==void 0)&&C0([...Object.values(t.inputs),...Object.values(n.inputs)]),this.claimVectorLayouts(t),this.claimVectorLayouts(n),this.applyBufferLayout(this.getVectorBufferLayout())}applyBufferLayout(e){if(e=qi(this.pipeline.shaderLayout,e),Fe(e,this.bufferLayout,-1))return;this.bufferLayout=e,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline();let t=this.vertexArray;this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),t.destroy(),this._dynamicAttributeBufferSources={},this.applyVectorAttributes(),this.indexBuffer&&this.vertexArray.setIndexBuffer(this.indexBuffer)}setParameters(e){Fe(e,this.parameters,2)||(this.parameters=e,this.device.type==="webgl"?this.setNeedsRedraw("parameters"):this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this._vertexCountSet=!0,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new E.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(ce(n)&&this._usesManagedUniformBuffer(t)){let i=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=i}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getShaderInputBindings()),this.setNeedsRedraw("shaderInputs")}_getShaderInputBindings(){return this.shaderInputs.getBindingValues()}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){this.indexVector&&(this.indexCount=void 0,this.firstVertex=0,this.firstIndex=0),this.indexVector=null;let t=e instanceof $?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof $?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){Object.assign(this.currentAttributes,e);for(let s of Object.keys(e))this.currentAttributeByteOffsets[s]=t?.byteOffsets?.[s]??0;this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&E.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=qi(this.pipeline.shaderLayout,this.bufferLayout);let i=new Xr(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof $?o.buffer:o,c=i.getBufferLayout(s);if(!c){n||E.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let u=i.getAttributeNamesForBuffer(c),l=!1;for(let d of u){let f=this._attributeInfos[d];if(f){let h=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(f.bufferName):f.location;if(h===null){n||E.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${f.bufferName}".`)();continue}let p=t?.byteOffsets?.[s]??0;this.vertexArray.setBuffer(h,a,p),o instanceof $?this._dynamicAttributeBufferSources[h]={source:o,generation:o.generation,byteOffset:p}:delete this._dynamicAttributeBufferSources[h],l=!0}}!l&&!n&&E.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,i]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,i):(t?.disableWarnings??this.props.disableWarnings)||E.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(v0(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,i]of Object.entries(this.bindings)){let s=x8(n,i,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){return e.bindings.length?(0,E.normalizeBindingsByGroup)(e,t):{0:t}}_getBindGroupCacheKeys(){return{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof E.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof E.Buffer||t instanceof E.Texture||t instanceof E.ExternalTexture||t instanceof $?e=Math.max(e,t.updateTimestamp):v0(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:O0(t)&&(e=Math.max(e,(t.buffer instanceof $,t.buffer.updateTimestamp)));return e}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=this.pipelineFactory.createRenderPipeline(e.props)}catch(t){throw this._releasePipelineShaders(e.vertexShader,e.fragmentShader),this._pipelineNeedsUpdate="pipeline creation failed",t}this._finishPipelineUpdate(e)}return this.pipeline}async _updatePipelineAsync(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=await this.pipelineFactory.createRenderPipelineAsync(e.props)}catch(t){throw this._releasePipelineShaders(e.vertexShader,e.fragmentShader),this._pipelineNeedsUpdate="asynchronous pipeline creation failed",t}this._finishPipelineUpdate(e)}return this.pipeline}_preparePipelineUpdate(){if(!this._pipelineNeedsUpdate)return null;let e=this.pipeline?.vs??null,t=this.pipeline?.fs??null;this.pipeline&&E.log.log(1,`GPUVectorModel ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),this._pipelineNeedsUpdate=!1;let n=null,i=null;try{n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),this.source?i=n:this.fs&&(i=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fs,debugShaders:this.props.debugShaders}))}catch(s){throw this._releasePipelineShaders(n,i),this._pipelineNeedsUpdate="shader creation failed",s}return{props:{...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:i},vertexShader:n,fragmentShader:i,previousVertexShader:e,previousFragmentShader:t}}_finishPipelineUpdate(e){this._attributeInfos=(0,E.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),this._releasePipelineShaders(e.previousVertexShader,e.previousFragmentShader)}_releasePipelineShaders(e,t){e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=E.log.level>3?0:m8;E.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,E.log.group(E0,`>>> DRAWING MODEL ${this.id}`,{collapsed:E.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=x9(this.pipeline.shaderLayout,this.id);E.log.table(E0,e)();let t=this.shaderInputs.getDebugTable();E.log.table(E0,t)();let n=this._getAttributeDebugTable();E.log.table(E0,this._attributeInfos)(),E.log.table(E0,n)(),E.log.groupEnd(E0)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;T9(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let i=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:i?this._getBufferOrConstantValues(i,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=E.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof E.Buffer?new n(e.debugData):e).toString()}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer,t.byteOffset),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,i=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>b8(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??v8(t?.depthStencilAttachment?.texture?.format);(!Fe(this._colorAttachmentFormats,i,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=i,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function L1(r,e){return r.shaderLanguage!==void 0&&r.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in r&&typeof r.assembleGLSLShaderPair=="function":"assembleWGSLShader"in r&&typeof r.assembleWGSLShader=="function"}function y8(r,e){return!r||Object.keys(e).length===0?r:{...r,attributes:r.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function x8(r,e,t){if(v0(e)){let n=zt(t,r,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof $?e.buffer:O0(e)?He(e):e}function b8(r){return r&&!a2(r)?r:null}function v8(r){return r&&a2(r)?r:void 0}function a2(r){return g8.includes(r)}var R1=B(k(),1);var Xe=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||J("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&R1.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function $t(r,e){if(e instanceof Xe)return e;let t=Me(e),n=T8(r,t),{attributes:i,bufferLayout:s}=S8(r,t);return new Xe({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:i})}function T8(r,e){if(!e.indices)return;let t=e.indices.value;return r.createBuffer({usage:R1.Buffer.INDEX,data:t})}function S8(r,e){let t={};for(let[n,i]of Object.entries(e.attributes)){let s=e.bufferLayout?.find(o=>o.name===n)?.name||ne(n);i&&(t[s]=r.createBuffer({data:i.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout||_i(e.attributes),vertexCount:e.vertexCount}}var m0=class{attributes;indices;topology;vertexCount;bufferLayout;destroy(){}constructor(e){this.attributes=e.attributes,this.indices=e.indices??null,this.topology=e.topology??"triangle-list",this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout}};var c2=B(k(),1);function u2(r,e){let t=$t(r,e);try{let n=gn(t);return n.destroy=()=>t.destroy(),n}catch(n){throw t.destroy(),n}}function gn(r){let e={};for(let[o,a]of Object.entries(r.attributes)){let c=r.bufferLayout.find(f=>f.name===o),u=c?.format,l=c?.byteStride??(u?c2.vertexFormatDecoder.getVertexFormatInfo(u).byteLength:0),d=r.indices&&l?Math.floor(a.byteLength/l):r.vertexCount;e[o]={name:o,format:u,length:d,byteStride:l,rowByteLength:l,bufferLayout:c,data:[{buffer:a,byteOffset:0,length:d,format:u,byteStride:l,rowByteLength:l}]}}if(r.indices){let o=Math.min(...Object.values(e).map(a=>a.length));for(let[a,c]of Object.entries(e))e[a]={...c,length:o,data:c.data.map(u=>({...u,length:o}))}}let t=r.indices,n=t?.indexType==="uint32"?4:t?.indexType==="uint8"?1:2,i=t?t.byteLength/n:0,s=t?{name:"indices",format:t.indexType,length:i,byteStride:n,rowByteLength:n,data:[{buffer:t,byteOffset:0,length:i,format:t.indexType,byteStride:n,rowByteLength:n}]}:null;return new m0({attributes:e,indices:s,topology:r.topology,vertexCount:r.vertexCount,bufferLayout:r.bufferLayout})}var Y0=class extends p0{static defaultProps={...p0.defaultProps,material:void 0};get sourceGeometry(){return this.sourceGeometryValue}constructor(e,t){let n=t.geometry===void 0?new.target.defaultProps.geometry:t.geometry,i=n&&!(n instanceof m0)?$t(e,n):null,s=i?gn(i):n,o={...t,geometry:s instanceof m0?s:null};try{super(e,o)}catch(a){throw i?.destroy(),a}this._gpuGeometry=i,this.sourceGeometryValue=n,i&&this.setIndexCount(this.props.indexCount)}_initializeProps(e){this.material=e.material||null,this._gpuGeometry=null,this.sourceGeometryValue=null,super._initializeProps(e)}_initializeAttributes(){super._initializeAttributes(),this._gpuGeometry&&super.setIndexCount(this.indexCountOverride)}destroy(){super.destroy(),this._gpuGeometry?.destroy(),this._gpuGeometry=null,this.sourceGeometryValue=null}setGeometry(e){this._gpuGeometry?.destroy(),this._gpuGeometry=e&&!(e instanceof m0)?$t(this.device,e):null;let t=this._gpuGeometry?gn(this._gpuGeometry):e;super.setGeometry(t instanceof m0?t:null),e instanceof m0||super.setIndexCount(this.indexCountOverride),this.sourceGeometryValue=e}setIndexCount(e){this.indexCountOverride=e,super.setIndexCount(e)}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}_usesManagedUniformBuffer(e){return!this.material?.ownsModule(e)}updateShaderInputs(e){super.updateShaderInputs(e),this.material?.updateShaderInputs(e)}_getShaderInputBindings(){let e=super._getShaderInputBindings(),t=this.material;return t?Object.fromEntries(Object.entries(e).filter(([n])=>!t.ownsBinding(n))):e}_areBindingsLoading(){let e=super._areBindingsLoading();if(e)return e;for(let t of Object.values(this.material?.bindings||{}))if(v0(t)&&!t.isReady)return t.id;return!1}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=super._getBindGroups(e,t);for(let[i,s]of Object.entries(this.material?.getBindingsByGroup(e)||{})){let o=Number(i);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){return Math.max(super._getBindingsUpdateTimestamp(),this.material?.getBindingsUpdateTimestamp()||0)}};var P0=B(k(),1);var Ke=3,Ye=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new e0(Object.fromEntries(this.modules.map(i=>[i.name,i])));this._materialBindingNames=w8(n),this._materialModuleNames=I8(n)}createMaterial(e={}){return new Ze(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=C1(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Ke]:e}:{}}};function C1(r){return r.endsWith("Uniforms")?r.slice(0,-8):null}function w8(r){let e=new Set;for(let t of Object.values(r.modules))for(let n of t.bindingLayout||[])n.group===Ke&&e.add(n.name);return e}function I8(r){let e=new Set;for(let t of Object.values(r.modules))t.name&&t.bindingLayout?.some(n=>n.group===Ke&&n.name===t.name)&&e.add(t.name);return e}var Ze=class{id;metadata={};device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||J("material"),this.device=e,this.factory=t.factory||new Ye(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(i=>[i.name,i]));this.shaderInputs=t.shaderInputs||new e0(n),this._uniformStore=new P0.UniformStore(this.device,this.shaderInputs.modules);for(let[i,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(i)&&ce(s)){let o=this._uniformStore.getManagedUniformBuffer(i);this.bindings[`${i}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.metadata={...this.metadata},t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))C1(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[i,s]of Object.entries(this.bindings))if(v0(s)){let o=zt(e,i,{fallbackGroup:Ke}),a=o?s.resolveTextureBinding(o):null;a&&(n[i]=a)}else s instanceof $?n[i]=s.buffer:O0(s)?n[i]=He(s):n[i]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Ke?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof P0.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof P0.Buffer||t instanceof P0.Texture||t instanceof P0.ExternalTexture||t instanceof $?e=Math.max(e,t.updateTimestamp):v0(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:O0(t)&&(e=Math.max(e,(t.buffer instanceof $,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,i]of Object.entries(e))i!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==i&&(this.bindings[n]=i,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,i]of Object.entries(this.bindings)){let s=A8(i);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function A8(r){return v0(r)?r.generation:pn(r)?.generation??null}var Qe=B(k(),1),d2=B(b0(),1);var l2=35980,_8=35981,yn=class r{device;model;transformFeedback;outputVectorBindings={};outputBuffers={};static defaultProps={...p0.defaultProps,inputVectors:void 0,outputVectors:void 0,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=r.defaultProps){if(!r.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.outputBuffers=t.feedbackBuffers||{};let{inputVectors:n,outputVectors:i,...s}=t;this.model=new p0(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,d2.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...s,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?l2:_8)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),n&&this.model.setGPUVectors(n,{count:"vertex"}),i&&this.setOutputVectors(i)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){let{inputVectors:t,outputVectors:n,inputBuffers:i,outputBuffers:s,...o}=e??{};i&&this.model.setAttributes(i),t&&this.model.setGPUVectors(t,{count:"vertex"}),s&&(this.outputBuffers=s),(s||n||Object.keys(this.outputVectorBindings).length>0)&&this.setOutputVectors(n??this.outputVectorBindings);let a=this.device.beginRenderPass({discard:!0,...o});try{this.model.draw(a)}finally{a.end()}}setOutputVectors(e){let t=V0(this.model.id,e);(0,Qe.assert)(t.length===0||this.model.pipeline.props.bufferMode!==l2),(0,Qe.assert)(t.length<=1),this.outputVectorBindings=e,this.transformFeedback.setBuffers({...this.outputBuffers,...Object.fromEntries(Object.entries(t[0]?.data??{}).map(([n,i])=>((0,Qe.assert)(i.byteStride===i.rowByteLength),[n,{buffer:i.buffer instanceof $?i.buffer.buffer:i.buffer,byteOffset:i.byteOffset,byteLength:i.length*i.byteStride}])))})}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof Qe.Buffer)return t.readAsync();let{buffer:n,byteOffset:i=0,byteLength:s=n.byteLength}=t;return n.readAsync(i,s)}};var f2=B(b0(),1);var M8="transform_output",xn=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e;let{inputVectors:n,...i}=t;this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new p0(this.device,{id:t.id||J("texture-transform-model"),fs:t.fs||(0,f2.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:M8}),vertexCount:t.vertexCount,...i}),n&&this.model.setGPUVectors(n,{count:"vertex"}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{inputVectors:t,...n}=e??{};t&&this.model.setGPUVectors(t,{count:"vertex"});let{framebuffer:i}=this.bindings[this.currentIndex],s=this.device.beginRenderPass({framebuffer:i,...n});try{this.model.draw(s)}finally{s.end()}this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:i}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),i){e.targetTexture=i;let{width:s,height:o}=i;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[i]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var E8=`struct VertexInputs {
|
|
130
|
+
`,e}function qr(r,e,t){return`${r}:${e}:${t}`}function r5(r,e){let t=/^\/\/ ----- MODULE ([^\n]+) ---------------$/gm,n,i;for(i=t.exec(r);i&&i.index<=e;)n=i[1],i=t.exec(r);return n}function n5(r,e){let t=r.indexOf(wt);return t>=0?e>t:!0}function i5(r){return r.replace(/\s+/g," ").trim()}var $0=class r extends Le{shaderLanguage="wgsl";_wgslBindingRegistry=new Map;assembleWGSLShader(e){let t=this._getModuleList(e.modules),n=[...this._injectionTargets,...e.injectionTargets||[]],i=this._transpileShader(e,t,e.source,e.shaderStage??(e.computeEntryPoint?"compute":void 0)),s={vertex:i.entryPoints?.vertex??e.vertexEntryPoint,fragment:i.entryPoints?.fragment??e.fragmentEntryPoint,compute:i.entryPoints?.compute??e.computeEntryPoint},o=r.getShaderPreprocessorDefines(e,t),a=e.platformInfo.shaderLanguage==="wgsl"&&i.code?Ne(i.code,{defines:o}):i.code,{source:c,getUniforms:u,bindingAssignments:l}=y9({...e,source:a,vertexEntryPoint:s.vertex,fragmentEntryPoint:s.fragment,defines:o,_bindingRegistry:this._wgslBindingRegistry,modules:i.modules,injectionTargets:n}),d=e.platformInfo.shaderLanguage==="wgsl"?Ne(c,{defines:o}):c;return{source:d,entryPoints:s,getUniforms:u,modules:t,bindingAssignments:l,bindingTable:p9(d,l),shaderLayout:s9(d,{vertexEntryPoint:s.vertex,scanVertexAttributes:e.scanVertexAttributes})}}static getShaderPreprocessorDefines(e,t){return{...r.getPlatformPreprocessorDefines(e.platformInfo),...t.reduce((n,i)=>(Object.assign(n,i.defines),n),{}),...e.defines}}static getPlatformPreprocessorDefines(e){let t=e.limits||{};return{LUMA_SUPPORTS_VERTEX_STORAGE_BUFFERS:e.type==="webgpu"&&(t.maxStorageBuffersInVertexStage||0)>0,LUMA_FP32_TAN_PRECISION_WORKAROUND:e.type==="webgpu"&&e.gpu.toLowerCase()!=="nvidia"&&e.gpu.toLowerCase()!=="amd",LUMA_FP64_INTEGER_ARITHMETIC:e.type==="webgpu"&&e.gpu.toLowerCase()==="apple"}}};var Et=B(k(),1),Hr=class{device;buffer;byteOffset=0;constructor(e){this.device=e}prepare(e){if(!this.buffer||this.buffer.byteLength<e){let t=Math.max(1024,(this.buffer?.byteLength??0)*2,e),n=this.device.createBuffer({id:"batch-uniforms",byteLength:t,usage:Et.Buffer.UNIFORM|Et.Buffer.COPY_DST});this.buffer?.destroy(),this.buffer=n}this.byteOffset=0}getAlignedByteLength(e){let t=this.device.limits.minUniformBufferOffsetAlignment||1;return Math.ceil(e/t)*t}write(e){(0,Et.assert)(this.buffer&&this.byteOffset+e.byteLength<=this.buffer.byteLength);let t={buffer:this.buffer,offset:this.byteOffset,size:e.byteLength};return this.buffer.write(e,t.offset),this.byteOffset+=this.getAlignedByteLength(e.byteLength),t}destroy(){this.buffer?.destroy(),this.buffer=void 0,this.byteOffset=0}};function x9(r,e){let t={},n="Values";if(r.attributes.length===0&&!r.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let i of r.attributes)if(i){let s=`${i.location} ${i.name}: ${i.type}`;t[`in ${s}`]={[n]:i.stepMode||"vertex"}}for(let i of r.varyings||[]){let s=`${i.location} ${i.name}`;t[`out ${s}`]={[n]:JSON.stringify(i)}}return t}var b9="__debugFramebufferState";function T9(r,e,t){if(r.device.type!=="webgl")return;let n=a5(r.device);if(!n.flushing){if(u5(r)){s5(r,t,n);return}e&&c5(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function s5(r,e,t){if(t.queuedFramebuffers.length===0)return;let n=r.device,{gl:i}=n,s=i.getParameter(36010),o=i.getParameter(36006),[a,c]=r.device.getDefaultCanvasContext().getDrawingBufferSize(),u=v9(e.top,8),l=v9(e.left,8);t.flushing=!0;try{for(let d of t.queuedFramebuffers){let[f,h,p,m,g]=o5({framebuffer:d,targetWidth:a,targetHeight:c,topPx:u,leftPx:l,minimap:e.minimap});i.bindFramebuffer(36008,d.handle),i.bindFramebuffer(36009,null),i.blitFramebuffer(0,0,d.width,d.height,f,h,p,m,16384,9728),u+=g+8}}finally{i.bindFramebuffer(36008,s),i.bindFramebuffer(36009,o),t.flushing=!1}}function o5(r){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:i,leftPx:s,minimap:o}=r,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,u=Math.min(a/e.width,c/e.height),l=Math.max(Math.floor(e.width*u),1),d=Math.max(Math.floor(e.height*u),1),f=s,h=Math.max(n-i-d,0),p=f+l,m=h+d;return[f,h,p,m,d]}function a5(r){return r.userData[b9]||={flushing:!1,queuedFramebuffers:[]},r.userData[b9]}function c5(r){return"colorAttachments"in r}function u5(r){let e=r.props.framebuffer;return!e||e.handle===null}function v9(r,e){if(!r)return e;let t=Number.parseInt(r,10);return Number.isFinite(t)?t:e}function Fe(r,e,t){if(r===e)return!0;if(!t||!r||!e)return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!Fe(r[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof r=="object"&&typeof e=="object"){let n=r,i=e,s=Object.keys(r),o=Object.keys(e);if(s.length!==o.length)return!1;for(let a of s)if(!e.hasOwnProperty(a)||!Fe(n[a],i[a],t-1))return!1;return!0}return!1}var S9=B(k(),1),Xr=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,S9.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let i of t){let s=n.findIndex(o=>o.name===i.name);s<0?n.push(i):n[s]=i}return n}};var U0=B(k(),1);function qi(r,e){let t=(0,U0.getShaderAttributeLocationMap)(r),n=e.slice();return n.sort((i,s)=>{let o=(0,U0.getMinimumAttributeLocation)((0,U0.getBufferLayoutAttributeNames)(i).map(c=>t[c])),a=(0,U0.getMinimumAttributeLocation)((0,U0.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}var Yr=B(b0(),1);function Ge(r,e){if(!r||!e.some(n=>n.bindingLayout?.length))return r;let t={...r,bindings:r.bindings.map(n=>({...n}))};"attributes"in(r||{})&&(t.attributes=r?.attributes||[]);for(let n of e)for(let i of n.bindingLayout||[])for(let s of l5(i.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=i.group),o&&i.visibility!==void 0&&(o.visibility=i.visibility)}return t}function w9(r,e,t=[]){return r?e?{...r,attributes:r.attributes.length?h5(r.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:f5(r.bindings,e.bindings)}:r:e}function ce(r){return!!(r.uniformTypes&&!d5(r.uniformTypes))}function I9(r){let e=[];for(let t of r){let n=(0,Yr.getShaderModuleUniformBlockName)(t),i=new Set([t.vs,t.fs].flatMap(o=>o?(0,Yr.getGLSLUniformBlocks)(o).filter(a=>a.isStd140).map(a=>a.blockName):[])),s=i.has(n)?n:i.size===1?i.values().next().value:void 0;ce(t)&&s&&e.push({name:s,uniformTypes:t.uniformTypes})}return e}function Kr(r,e){let t=[],n=new Set;for(let i of[...r||[],...e||[]])n.has(i.name)||(n.add(i.name),t.push(i));return t}function l5(r){let e=new Set([r,`${r}Uniforms`]);return r.endsWith("Uniforms")||e.add(`${r}Sampler`),[...e]}function d5(r){for(let e in r)return!1;return!0}function f5(r,e){let t=r.map(s=>({...s})),n=new Set(r.map(s=>s.name)),i=new Set(r.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!i.has(o)&&t.push({...s})}return t}function h5(r,e){let t=r.map(s=>({...s})),n=new Map(r.map(s=>[s.name,s])),i=new Map(r.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=i.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}function ue(r){return{type:r.type,shaderLanguage:r.info.shadingLanguage,shaderLanguageVersion:r.info.shadingLanguageVersion,gpu:r.info.gpu,limits:r.limits,features:r.features}}var Hi={};function J(r="id"){Hi[r]=Hi[r]||1;let e=Hi[r]++;return`${r}-${e}`}var A9=B(k(),1);function Xi(r,e,t){for(let[n,i]of Object.entries(e)){if(!i)continue;if(!i.format)throw new Error(`${r} GPUVector "${n}" requires a format`);let s=t.find(d=>d.name===n);if(!s)throw new Error(`${r} GPUVector "${n}" requires a Model buffer layout`);let o=s.attributes??[];if(o.length>1)throw new Error(`${r} GPUVector "${n}" does not support interleaved layouts`);let a=o[0],c=s.format??a?.format,u=_9(r,n,i.format),l=s.byteStride??u.byteLength;if(c!==i.format||l!==i.byteStride||i.rowByteLength!==u.byteLength)throw new Error(`${r} GPUVector "${n}" must match its Model buffer layout`)}}function V0(r,e){let t=Object.entries(e).filter(o=>o[1]!==void 0);if(t.length===0)return[];let[n,i]=t[0];for(let[o,a]of t){if(!a.format)throw new Error(`${r} GPUVector "${o}" requires a format`);if(_9(r,o,a.format),a.length!==i.length)throw new Error(`${r} GPUVector "${o}" rows must match "${n}" rows`);if(a.data.length!==i.data.length)throw new Error(`${r} GPUVector chunk counts must align`)}let s=0;return i.data.map((o,a)=>{let c={};for(let[l,d]of t){let f=d.data[a];if(!f||f.length!==o.length)throw new Error(`${r} GPUVector chunk ${a} row counts must align`);if(f.format!==d.format||f.byteStride!==d.byteStride||f.rowByteLength!==d.rowByteLength)throw new Error(`${r} GPUVector "${l}" chunk layout must be stable`);c[l]=f}let u={batchIndex:a,rowIndexOffset:s,rowCount:o.length,data:c};return s+=o.length,u})}function _9(r,e,t){if(t.includes("<"))throw new Error(`${r} GPUVector "${e}" requires a fixed-width scalar format`);return A9.vertexFormatDecoder.getVertexFormatInfo(t)}var Zr=B(k(),1);function C0(r){let e;for(let t of Object.values(r)){if(!t||"isConstant"in t)continue;let n=0;for(let i of t.data)n+=i.length;if((0,Zr.assert)(n===t.length),e){(0,Zr.assert)(t.length===e.length&&t.data.length===e.data.length);for(let i=0;i<t.data.length;i++)(0,Zr.assert)(t.data[i].length===e.data[i].length)}else e=t}}function E9(r,e,t,n,i,s){let o=e.inputs,a=t.inputs,c=e.sourceLayouts,u=t.sourceLayouts,l=e.layouts,d=t.layouts,f=t.stepMode,h=e.batchCount,p=t.batchCount,m=Array.from({length:h},(x,w)=>e.getBatch(w)),g=Array.from({length:p},(x,w)=>t.getBatch(w)),b=M9(m),v=M9(g),T=r.vertexCount,S=r.instanceCount,y=!0;try{let x=r.isInstanced&&t.vertexCount===void 0,w=x?h*p:Math.max(h,p);if(h===0||p===0)return!0;for(let I=0;I<w;I++){let A=x?Math.floor(I/p):Math.min(I,h-1),M=x?I%p:Math.min(I,p-1);e.setInputs(m[A],l,"vertex"),t.setInputs(g[M],d,f),n();let R=e.rowCount!==void 0?b[A]:t.vertexCount!==void 0?v[M]:0;s==="vertex"&&r.setVertexCount(Math.max(0,Math.min(e.rowCount??t.vertexCount??T,T-R))),s==="instance"&&t.instanceCount!==void 0&&r.setInstanceCount(Math.max(0,Math.min(t.instanceCount,S-v[M]))),!(!r.indexBuffer&&r.vertexCount===0||r.isInstanced&&r.instanceCount===0)&&(y=i()&&y)}}finally{e.setInputs(o,c,"vertex"),t.setInputs(a,u,f),n(),r.setVertexCount(T),r.setInstanceCount(S)}return y}function M9(r){let e=0;return r.map(t=>{let n=e;for(let i of Object.values(t))if(i&&"data"in i){e+=i.length;break}return n})}var o0=B(k(),1);var Pt=class{device;id;inputs={};sourceLayouts;stepMode="vertex";claimedNames=new Set;layouts=[];buffers={};byteOffsets={};constants={};rowCount;vertexCount;instanceCount;constantBuffers={};constructor(e,t){this.device=e,this.id=t}setInputs(e,t,n,i=!0){if(i)C0(e);else for(let u of Object.values(e))u&&!q(u)&&(0,o0.assert)(u.data.length===1);this.claimedNames.clear(),this.inputs=e,this.sourceLayouts=t,this.stepMode=n,this.rowCount=void 0,this.vertexCount=void 0,this.instanceCount=void 0;let s=t??Object.entries(e).flatMap(([u,l])=>l&&!q(l)&&l.bufferLayout?[{...l.bufferLayout,name:u}]:[]),o=Object.entries(e).flatMap(([u,l])=>{if(!l||s.some(h=>h.name===u||h.attributes?.some(p=>p.attribute===u)))return[];(0,o0.assert)(l.format);let d=l.format,f=q(l)?0:l.byteStride;return[{name:u,stepMode:n,byteStride:f,attributes:[{attribute:u,format:d,byteOffset:0}]}]}),a=[...s,...m5(e,o)];for(let[u,l]of Object.entries(e))if(l){if(!q(l)&&!Array.isArray(l.data))throw new TypeError(`Expected a GPU vector or constant for ${u}`);!q(l)&&i&&((a.find(h=>h.name===u||h.attributes?.some(p=>p.attribute===u))?.stepMode??n)==="instance"?((0,o0.assert)(this.instanceCount===void 0||this.instanceCount===l.length),this.instanceCount=l.length):((0,o0.assert)(this.vertexCount===void 0||this.vertexCount===l.length),this.vertexCount=l.length),this.rowCount=n==="instance"?this.instanceCount:this.vertexCount),this.claimedNames.add(u)}this.layouts=a.flatMap(u=>{let l=e[u.name],d=u.attributes??(u.format?[{attribute:u.name,format:u.format,byteOffset:0}]:[]),f=d.filter(p=>q(e[p.attribute])),h={...u,stepMode:u.stepMode??n};return this.device.type!=="webgpu"||l&&!q(l)&&l.bufferLayout||!f.length||f.length===d.length?[{...h,byteStride:f.length===d.length&&f.length?0:h.byteStride}]:[{...h,attributes:d.filter(p=>!q(e[p.attribute]))},{...h,name:`${u.name}-constants`,byteStride:0,attributes:f}]}),this.buffers={},this.byteOffsets={},this.constants={};let c=new Set;for(let u of this.layouts){this.claimedNames.add(u.name);let l=u.attributes??(u.format?[{attribute:u.name,format:u.format,byteOffset:0}]:[]);for(let h of l)this.claimedNames.add(h.attribute);let d=e[u.name];if(d&&!q(d)){let h=d.bufferLayout||!d.format?0:(l.find(p=>p.attribute===u.name)??l[0])?.byteOffset??0;this.bindVector(u.name,d,h)}let f=0;for(let h of l){let p=e[h.attribute]??(h.attribute===u.name?e[u.name]:void 0);p&&((0,o0.assert)(p.format===void 0||p.format===h.format),q(p)?(this.constants[h.attribute]=p5(p),f=Math.max(f,(h.byteOffset??0)+p.byteLength)):this.buffers[u.name]||this.bindVector(u.name,p,h.byteOffset??0))}if(this.device.type==="webgpu"&&f&&!this.buffers[u.name]){let h=new Uint8Array(Math.ceil(f/4)*4);for(let m of l){let g=e[m.attribute];q(g)&&h.set(new Uint8Array(g.value.buffer,g.value.byteOffset,g.byteLength),m.byteOffset??0)}let p=this.constantBuffers[u.name];(!p||p.byteLength<h.byteLength)&&(p?.destroy(),p=this.device.createBuffer({id:`${this.id}-${u.name}-constant`,byteLength:h.byteLength,usage:o0.Buffer.VERTEX|o0.Buffer.COPY_DST|o0.Buffer.COPY_SRC}),this.constantBuffers[u.name]=p),p.write(h),this.buffers[u.name]=p,c.add(u.name)}}for(let[u,l]of Object.entries(this.constantBuffers))c.has(u)||(l.destroy(),delete this.constantBuffers[u])}get batchCount(){let e=Object.values(this.inputs).find(t=>t&&!q(t));return e&&!q(e)?e.data.length:1}getBatch(e){return Object.fromEntries(Object.entries(this.inputs).map(([t,n])=>{if(!n||q(n))return[t,n];let i=n.data[e];return[t,{...n,length:i?.length??0,data:i?[i]:[]}]}))}destroy(){for(let e of Object.values(this.constantBuffers))e.destroy();this.constantBuffers={}}bindVector(e,t,n){let i=t.data[0];if(!i)return;let s=i.byteOffset-n;(0,o0.assert)(s>=0),this.buffers[e]=i.buffer,this.byteOffsets[e]=s}};function q(r){return!!(r&&"isConstant"in r&&r.isConstant)}function p5(r){let e=o0.vertexFormatDecoder.getVertexFormatInfo(r.format);if(r.format==="unorm10-10-10-2"){let n=r.value[0];return new Float32Array([(n&1023)/1023,(n>>>10&1023)/1023,(n>>>20&1023)/1023,(n>>>30)/3])}let t=Array.from(r.value);if(r.format==="unorm8x4-bgra"&&([t[0],t[2]]=[t[2],t[0]]),e.normalized){let n=r.value.BYTES_PER_ELEMENT*8,i=2**n-1;return new Float32Array(t.map(s=>e.signed?(s+2**(n-1))/i*2-1:s/i))}return e.integer?e.signed?new Int32Array(t):new Uint32Array(t):new Float32Array(t)}function m5(r,e){let t=[],n,i=0,s=[...e].sort((o,a)=>{let c=r[o.name],u=r[a.name];return(c&&!q(c)?c.data[0]?.byteOffset??0:0)-(u&&!q(u)?u.data[0]?.byteOffset??0:0)});for(let o of s){let a=r[o.name],c=o.attributes[0];if(q(a)){n||(n={...o,attributes:[]},t.push(n));let l=Math.min(4,a.byteLength);i=Math.ceil(i/l)*l,n.attributes.push({...c,byteOffset:i}),i+=a.byteLength;continue}let u=t.find(l=>{let d=r[l.name];if(!d||q(d)||!d.data.length||!a.data.length)return!1;let f=a.data[0].byteOffset-d.data[0].byteOffset;return l.stepMode===o.stepMode&&l.byteStride===o.byteStride&&f>=0&&f+a.rowByteLength<=a.byteStride&&a.data.every((h,p)=>{let m=d.data[p];return h.buffer===m.buffer&&h.byteStride===m.byteStride&&h.byteOffset-m.byteOffset===f})});if(u){let l=r[u.name];u.attributes.push({...c,byteOffset:a.data[0].byteOffset-l.data[0].byteOffset})}else t.push({...o,attributes:[...o.attributes]})}return t}var Qr=B(k(),1),Ki=B(b0(),1);function Yi(r){return(Array.isArray(r)?r.length===0||typeof r[0]=="number":ArrayBuffer.isView(r)&&!(r instanceof DataView))||typeof r=="number"||typeof r=="boolean"}function P9(r,e={}){let t={bindings:{},uniforms:{}};return Object.keys(r).forEach(n=>{let i=r[n];Object.prototype.hasOwnProperty.call(e,n)||Yi(i)?t.uniforms[n]=i:t.bindings[n]=i}),t}var e0=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,Ki.getShaderModuleDependencies)(Object.values(e).filter(g5));for(let i of n)e[i.name]=i;Qr.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[i,s]of Object.entries(e))s&&(this._addModule(s),s.name&&i!==s.name&&!this.options.disableWarnings&&Qr.log.warn(`Module name: ${i} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,i=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||Qr.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(i,o)||i,{uniforms:u,bindings:l}=P9(c,s.uniformTypes);this.moduleUniforms[n]=L9(o,u,s.uniformTypes),this.moduleBindings[n]={...a,...l}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,Ki.getShaderModuleDependencies)(e);for(let n of t){let i=n.name;this.modules[i]||(this.modules[i]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[i,s]of Object.entries(n))e[`${t}.${i}`]={type:this.modules[t].uniformTypes?.[i],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=L9({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function L9(r={},e={},t={}){let n={...r};for(let[i,s]of Object.entries(e))s!==void 0&&(n[i]=Zi(r[i],s,t[i]));return n}function Zi(r,e,t){if(!t||typeof t=="string")return Lt(e);if(Array.isArray(t)){if(Qi(e)||!Array.isArray(e))return Lt(e);let o=Array.isArray(r)&&!Qi(r)?[...r]:[],a=o.slice();for(let c=0;c<e.length;c++){let u=e[c];u!==void 0&&(a[c]=Zi(o[c],u,t[0]))}return a}if(!Ji(e))return Lt(e);let n=t,i=Ji(r)?r:{},s={...i};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=Zi(i[o],a,n[o]));return s}function Lt(r){return ArrayBuffer.isView(r)?Array.prototype.slice.call(r):Array.isArray(r)?Qi(r)?r.slice():r.map(t=>t===void 0?void 0:Lt(t)):Ji(r)?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t===void 0?void 0:Lt(t)])):r}function Qi(r){return ArrayBuffer.isView(r)||Array.isArray(r)&&(r.length===0||typeof r[0]=="number")}function Ji(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&!ArrayBuffer.isView(r)}function g5(r){return!!r?.dependencies}var Rt=globalThis,y5=globalThis.document||{},Jr=globalThis.process||{},x5=globalThis.console,b5=globalThis.navigator||{};function en(r){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;let e=typeof navigator<"u"&&navigator.userAgent,t=r||e;return!!(t&&t.indexOf("Electron")>=0)}function j0(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||en()}var e1="5.0.0";function ze(r,e){if(!r)throw new Error(e||"Assertion failed")}function tn(r){if(!r)return 0;let e;switch(typeof r){case"number":e=r;break;case"object":e=r.logLevel||r.priority||0;break;default:return 0}return ze(Number.isFinite(e)&&e>=0),e}function t1(r){let{logLevel:e,message:t}=r;r.logLevel=tn(e);let n=r.args?Array.from(r.args):[];for(;n.length&&n.shift()!==t;);switch(typeof e){case"string":case"function":t!==void 0&&n.unshift(t),r.message=e;break;case"object":Object.assign(r,e);break;default:}typeof r.message=="function"&&(r.message=r.message());let i=typeof r.message;return ze(i==="string"||i==="object"),Object.assign(r,{args:n},r.opts)}var W0=()=>{},le=class{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...t){return this._log("warn",0,e,t,{once:!0})}error(e,...t){return this._log("error",0,e,t)}log(e,t,...n){return this._log("log",e,t,n)}info(e,t,...n){return this._log("info",e,t,n)}once(e,t,...n){return this._log("once",e,t,n,{once:!0})}_log(e,t,n,i,s={}){let o=t1({logLevel:t,message:n,args:this._buildArgs(t,n,i),opts:s});return this._createLogFunction(e,o,s)}_buildArgs(e,t,n){return[e,t,...n]}_createLogFunction(e,t,n){if(!this._shouldLog(t.logLevel))return W0;let i=this._getOnceTag(n.tag??t.tag??t.message);if((n.once||t.once)&&i!==void 0){if(this._onceCache.has(i))return W0;this._onceCache.add(i)}return this._emit(e,t)}_shouldLog(e){return this.getLevel()>=tn(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}};function T5(r){try{let e=window[r],t="__storage_test__";return e.setItem(t,t),e.removeItem(t),e}catch{return null}}var Ct=class{constructor(e,t,n="sessionStorage"){this.storage=T5(n),this.id=e,this.config=t,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){let t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}}_loadConfiguration(){let e={};if(this.storage){let t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}};function R9(r){let e;return r<10?e=`${r.toFixed(2)}ms`:r<100?e=`${r.toFixed(1)}ms`:r<1e3?e=`${r.toFixed(0)}ms`:e=`${(r/1e3).toFixed(2)}s`,e}function r1(r,e=8){let t=Math.max(e-r.length,0);return`${" ".repeat(t)}${r}`}var Dt;(function(r){r[r.BLACK=30]="BLACK",r[r.RED=31]="RED",r[r.GREEN=32]="GREEN",r[r.YELLOW=33]="YELLOW",r[r.BLUE=34]="BLUE",r[r.MAGENTA=35]="MAGENTA",r[r.CYAN=36]="CYAN",r[r.WHITE=37]="WHITE",r[r.BRIGHT_BLACK=90]="BRIGHT_BLACK",r[r.BRIGHT_RED=91]="BRIGHT_RED",r[r.BRIGHT_GREEN=92]="BRIGHT_GREEN",r[r.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",r[r.BRIGHT_BLUE=94]="BRIGHT_BLUE",r[r.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",r[r.BRIGHT_CYAN=96]="BRIGHT_CYAN",r[r.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(Dt||(Dt={}));var S5=10;function C9(r){return typeof r!="string"?r:(r=r.toUpperCase(),Dt[r]||Dt.WHITE)}function n1(r,e,t){return!j0&&typeof r=="string"&&(e&&(r=`\x1B[${C9(e)}m${r}\x1B[39m`),t&&(r=`\x1B[${C9(t)+S5}m${r}\x1B[49m`)),r}function i1(r,e=["constructor"]){let t=Object.getPrototypeOf(r),n=Object.getOwnPropertyNames(t),i=r;for(let s of n){let o=i[s];typeof o=="function"&&(e.find(a=>s===a)||(i[s]=o.bind(r)))}}var rn=class{getHighResolutionTimer(){let e;if(j0()&&Rt.performance)e=Rt?.performance?.now?.();else if("hrtime"in Jr){let t=Jr?.hrtime?.();e=t[0]*1e3+t[1]/1e6}else e=Date.now();return e}getMemoryUsageMB(){let t=Rt?.performance?.memory?.usedJSHeapSize;return t==null?null:Math.trunc(t/1024/1024)}},f0=new rn;globalThis.Probe=rn;globalThis.probe=f0;var $e={debug:j0()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},s1={enabled:!0,level:0},D0=class extends le{constructor({id:e}={id:""}){super({level:0}),this.VERSION=e1,this._startTs=f0.getHighResolutionTimer(),this._deltaTs=f0.getHighResolutionTimer(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new Ct(`__probe-${this.id}__`,{[this.id]:s1}),this.timeStamp(`${this.id} started`),i1(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((f0.getHighResolutionTimer()-this._startTs).toPrecision(10))}getDelta(){return Number((f0.getHighResolutionTimer()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,t){this._updateConfiguration({[e]:t})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,t){if(!e)throw new Error(t||"Assertion failed")}warn(e,...t){return this._log("warn",0,e,t,{method:$e.warn,once:!0})}error(e,...t){return this._log("error",0,e,t,{method:$e.error})}deprecated(e,t){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${t}\` instead`)}removed(e,t){return this.error(`\`${e}\` has been removed. Use \`${t}\` instead`)}probe(e,t,...n){let i=f0.getMemoryUsageMB();if(i!==null){let s=`${i}MB `;typeof t=="function"?t=()=>`${s}${t()}`:typeof t=="string"&&(t=`${s}${t}`)}return this._log("log",e,t,n,{method:$e.log,time:!0,once:!0})}log(e,t,...n){return this._log("log",e,t,n,{method:$e.debug})}info(e,t,...n){return this._log("info",e,t,n,{method:console.info})}once(e,t,...n){return this._log("once",e,t,n,{method:$e.debug||$e.info,once:!0})}table(e,t,n){return t?this._log("table",e,t,n&&[n]||[],{method:console.table||W0,tag:I5(t)}):W0}time(e,t){return this._log("time",e,t,[],{method:console.time?console.time:console.info})}timeEnd(e,t){return this._log("time",e,t,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,t){return this._log("time",e,t,[],{method:console.timeStamp||W0})}group(e,t,n={collapsed:!1}){let i=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,t,[],{method:i})}groupCollapsed(e,t,n={}){return this.group(e,t,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||W0})}withGroup(e,t,n){this.group(e,t)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,t){let n=t.method;ze(n),t.total=this.getTotal(),t.delta=this.getDelta(),this._deltaTs=f0.getHighResolutionTimer();let i=w5(this.id,t.message,t);return n.bind(console,i,...t.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(s1),this._storage.config[this.id]}_updateConfiguration(e){let t=this._storage.config[this.id]||{...s1};this._storage.setConfiguration({[this.id]:{...t,...e}})}};D0.VERSION=e1;function w5(r,e,t){if(typeof e=="string"){let n=t.time?r1(R9(t.total)):"";e=t.time?`${r}: ${n} ${e}`:`${r}: ${e}`,e=n1(e,t.color,t.background)}return e}function I5(r){for(let e in r)for(let t in r[e])return t||"untitled";return"empty"}globalThis.probe||(globalThis.probe=f0);var sh=new D0({id:"@probe.gl/log"});var a0=new D0({id:"luma.gl"});var o1={};function Ue(r="id"){o1[r]=o1[r]||1;let e=o1[r]++;return`${r}-${e}`}function Ve(r,e){if(!r){let t=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(t,Ve),t}}var nn=class{_owner=null;_ownedResources=new Set;_state="live";_destroyingOwnedResources=!1;_destroyRequested=!1;get owner(){return this._owner}get ownedResources(){return Array.from(this._ownedResources)}get destroyed(){return this._state==="destroyed"}transferOwnershipTo(e){Ve(this._state==="live"&&!this._destroyingOwnedResources),Ve(!this._owner||this._owner.canChangeOwnership()),Ve(!e||e.canChangeOwnership());for(let t=e;t;t=t._owner)Ve(t!==this);return e!==this._owner&&(this._owner?._ownedResources.delete(this),this._owner=e,e?._ownedResources.add(this)),this}destroy(){if(this._state!=="live")return;if(this._destroyingOwnedResources){this._destroyRequested=!0;return}this._destroyRequested=!1,this._state="destroying",this._owner?._ownedResources.delete(this),this._owner=null;let e=[];try{try{this.onBeforeDestroy()}catch(t){e.push(t)}this.destroyChildren(e);try{this.onDestroy()}catch(t){e.push(t)}}finally{this._state="destroyed"}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}delete(){return this.destroy(),this}attachResource(e){e.transferOwnershipTo(this)}detachResource(e){e._owner===this&&e.transferOwnershipTo(null)}destroyAttachedResource(e){e._owner===this&&e.destroy()}destroyAttachedResources(){if(this._state!=="live"||this._destroyingOwnedResources)return;let e=[];if(this.destroyChildren(e),this._destroyRequested)try{this.destroy()}catch(t){e.push(t)}if(e.length)throw new AggregateError(e,"Resource cleanup failed")}onBeforeDestroy(){}onDestroy(){}canChangeOwnership(){return this._state==="live"&&!this._destroyingOwnedResources}destroyChildren(e){this._destroyingOwnedResources=!0;try{for(let t of this._ownedResources)try{t.destroy()}catch(n){e.push(n)}}finally{this._ownedResources.clear(),this._destroyingOwnedResources=!1}}};var A5="cpu-hotspot-profiler",D9="GPU Resource Counts",B9="Resource Counts",O9="GPU Time and Memory",_5=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],M5=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","RenderBundleEncoders","RenderBundles","ComputePasss","CommandEncoders","CommandBuffers"],E5=_5.flatMap(r=>[`${r} Created`,`${r} Active`]),P5=M5.flatMap(r=>[`${r} Created`,`${r} Active`]),N9=new WeakMap,k9=new WeakMap,h0=class extends nn{static defaultProps={id:"undefined",handle:void 0,_isHandleBorrowed:!1,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}toJSON(){return this.toString()}id;props;userData={};_device;allocatedBytes=0;allocatedBytesName=null;get ownsHandle(){return(this.props.handle===void 0||this.props.handle===null)&&!this.isHandleBorrowed}get isHandleBorrowed(){return!!this.props._isHandleBorrowed}constructor(e,t,n){if(super(),!e)throw new Error("no device");this._device=e,this.props=L5(t,n);let i=this.props.id!=="undefined"?this.props.id:Ue(this[Symbol.toStringTag]);this.props.id=i,this.id=i,this.userData=this.props.userData||{},this.addStats()}getProps(){return this.props}destroyHandle(){}onDestroy(){try{this.destroyHandle()}finally{this.trackDeallocatedMemory(),this.removeStats()}}removeStats(){let e=Bt(this._device),t=e?q0():0,n=[this._device.statsManager.getStats(D9),this._device.statsManager.getStats(B9)],i=G9(this._device);for(let o of n)F9(o,i);let s=this.getStatsName();for(let o of n)o.get("Resources Active").decrementCount(),o.get(`${s}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(q0()-t))}trackAllocatedMemory(e,t=this.getStatsName()){let n=Bt(this._device),i=n?q0():0,s=this._device.statsManager.getStats(O9);this.allocatedBytes>0&&this.allocatedBytesName&&(s.get("GPU Memory").subtractCount(this.allocatedBytes),s.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),s.get("GPU Memory").addCount(e),s.get(`${t} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(q0()-i)),this.allocatedBytes=e,this.allocatedBytesName=t}trackReferencedMemory(e,t=this.getStatsName()){this.trackAllocatedMemory(e,`External ${t}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}let t=Bt(this._device),n=t?q0():0,i=this._device.statsManager.getStats(O9);i.get("GPU Memory").subtractCount(this.allocatedBytes),i.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(q0()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){let e=this.getStatsName(),t=Bt(this._device),n=t?q0():0,i=[this._device.statsManager.getStats(D9),this._device.statsManager.getStats(B9)],s=G9(this._device);for(let o of i)F9(o,s);for(let o of i)o.get("Resources Created").incrementCount(),o.get("Resources Active").incrementCount(),o.get(`${e}s Created`).incrementCount(),o.get(`${e}s Active`).incrementCount();t&&(t.statsBookkeepingCalls=(t.statsBookkeepingCalls||0)+1,t.statsBookkeepingTimeMs=(t.statsBookkeepingTimeMs||0)+(q0()-n)),R5(this._device,e)}getStatsName(){return C5(this)}};function L5(r,e){let t={...e};for(let n in r)r[n]!==void 0&&(t[n]=r[n]);return t}function F9(r,e){let t=r.stats,n=!1;for(let c of e)t[c]||(r.get(c),n=!0);let i=Object.keys(t).length,s=N9.get(r);if(!n&&s?.orderedStatNames===e&&s.statCount===i)return;let o={},a=k9.get(e);a||(a=new Set(e),k9.set(e,a));for(let c of e)t[c]&&(o[c]=t[c]);for(let[c,u]of Object.entries(t))a.has(c)||(o[c]=u);for(let c of Object.keys(t))delete t[c];Object.assign(t,o),N9.set(r,{orderedStatNames:e,statCount:i})}function G9(r){return r.type==="webgl"?P5:E5}function Bt(r){let e=r.userData[A5];return e?.enabled?e:null}function q0(){return globalThis.performance?.now?.()??Date.now()}function R5(r,e){let t=Bt(r);if(!(!t||!t.activeDefaultFramebufferAcquireDepth))switch(t.transientCanvasResourceCreates=(t.transientCanvasResourceCreates||0)+1,e){case"Texture":t.transientCanvasTextureCreates=(t.transientCanvasTextureCreates||0)+1;break;case"TextureView":t.transientCanvasTextureViewCreates=(t.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":t.transientCanvasSamplerCreates=(t.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":t.transientCanvasFramebufferCreates=(t.transientCanvasFramebufferCreates||0)+1;break;default:break}}function C5(r){let e=Object.getPrototypeOf(r);for(;e;){let t=Object.getPrototypeOf(e);if(!t||t===h0.prototype)return D5(e)||r[Symbol.toStringTag]||r.constructor.name;e=t}return r[Symbol.toStringTag]||r.constructor.name}function D5(r){let e=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(r):typeof e?.value=="string"?e.value:null}var A0=class r extends h0{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,t){let n={...t};(t.usage||0)&r.INDEX&&!t.indexType&&(t.data instanceof Uint32Array?n.indexType="uint32":t.data instanceof Uint16Array?n.indexType="uint16":t.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,r.defaultProps),this.usage=n.usage||0,this.indexType=n.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,t,n){if(!this.device.props.debug)return;let i=null,s;ArrayBuffer.isView(e)?(i=e,s=e.buffer):s=e;let o=Math.min(e?e.byteLength:n,r.DEBUG_DATA_MAX_LENGTH);if(s===null)this.debugData=new ArrayBuffer(o);else{let a=Math.min(i?.byteOffset||0,s.byteLength),c=Math.max(0,s.byteLength-a),u=Math.min(o,c);this.debugData=new Uint8Array(s,a,u).slice().buffer}}static defaultProps={...h0.defaultProps,handle:void 0,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}};var a1=globalThis.Float16Array;function z9(){return a1??Uint16Array}function $9(r){return!!(a1&&r===a1)}var U9=new Map;function V9(r){let e=U9.get(r);if(e)return e;let t=Object.freeze(B5(r));return Object.hasOwn(sn,r)&&U9.set(r,t),t}function B5(r){let e=r.includes("norm"),t=!e&&!r.startsWith("float"),n=r.startsWith("s"),i=sn[r],[s,o,a]=i||["uint8 ","i32",1];return{signedType:s,primitiveType:o,byteLength:a,normalized:e,integer:t,signed:n}}function j9(r){let e=r;switch(e){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return e}}function O5(r){let e=ArrayBuffer.isView(r)?r.constructor:r;if($9(e))return"float16";if(e===Uint8ClampedArray)return"uint8";let t=Object.values(sn).find(n=>e===n[4]);if(!t)throw new Error(e.name);return t[0]}function W9(r){return O5(r)}function N5(r){if(r==="float16")return z9();let e=sn[r];if(!e)throw new Error(r);let[,,,,t]=e;return t}function q9(r){return N5(r)}var sn={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]};var c1=class{getDataTypeInfo(e){return V9(e)}getNormalizedDataType(e){return j9(e)}alignTo(e,t){return Or(e,t)}getDataType(e){return W9(e)}getTypedArrayConstructor(e){return q9(e)}},H9=new c1;var t0="texture-compression-bc",F="texture-compression-astc",_0="texture-compression-etc2",X9="texture-compression-etc1-webgl",on="texture-compression-pvrtc-webgl",u1="texture-compression-atc-webgl",an="float32-renderable-webgl",l1="float16-renderable-webgl",k5="rgb9e5ufloat-renderable-webgl",d1="snorm8-renderable-webgl",H0="norm16-webgl",f1="norm16-renderable-webgl",h1="snorm16-renderable-webgl",cn="float32-filterable",Y9="float16-filterable-webgl",Ot=1,Nt=2,g1=4,y1=8,We=16,ln=5,Z9=10,H=Ot|Nt,un=Ot|g1,B0=Ot|Nt|g1|y1,M0=Ot|Nt|We,F5=Ot|g1|We,m1=B0|We,K9=(Nt|y1|We)<<ln,G5=(Nt|y1)<<ln,i0=We<<ln,je=m1<<ln,z5=B0<<Z9,p1=We<<Z9;function dn(r){let e=V5[r];if(!e)throw new Error(`Unsupported texture format ${r}`);return e}var $5={r8unorm:{webgpu:B0|i0},rg8unorm:{webgpu:B0|i0},"rgb8unorm-webgl":{},rgba8unorm:{webgpu:m1},"rgba8unorm-srgb":{webgpu:B0},r8snorm:{render:d1,webgpu:un|K9},rg8snorm:{render:d1,webgpu:un|K9},"rgb8snorm-webgl":{},rgba8snorm:{render:d1,webgpu:F5|G5},r8uint:{webgpu:H|i0},rg8uint:{webgpu:H|i0},rgba8uint:{webgpu:M0},r8sint:{webgpu:H|i0},rg8sint:{webgpu:H|i0},rgba8sint:{webgpu:M0},bgra8unorm:{webgpu:B0},"bgra8unorm-srgb":{webgpu:z5},r16unorm:{f:H0,render:f1,webgpu:je},rg16unorm:{f:H0,render:f1,webgpu:je},"rgb16unorm-webgl":{f:H0,render:!1},rgba16unorm:{f:H0,render:f1,webgpu:je},r16snorm:{f:H0,render:h1,webgpu:je},rg16snorm:{f:H0,render:h1,webgpu:je},"rgb16snorm-webgl":{f:H0,render:!1},rgba16snorm:{f:H0,render:h1,webgpu:je},r16uint:{webgpu:H|i0},rg16uint:{webgpu:H|i0},rgba16uint:{webgpu:M0},r16sint:{webgpu:H|i0},rg16sint:{webgpu:H|i0},rgba16sint:{webgpu:M0},r16float:{render:l1,filter:"float16-filterable-webgl",webgpu:B0|i0},rg16float:{render:l1,filter:Y9,webgpu:B0|i0},rgba16float:{render:l1,filter:Y9,webgpu:m1},r32uint:{webgpu:M0},rg32uint:{webgpu:H|p1},rgba32uint:{webgpu:M0},r32sint:{webgpu:M0},rg32sint:{webgpu:H|p1},rgba32sint:{webgpu:M0},r32float:{render:an,filter:cn,webgpu:M0},rg32float:{render:!1,filter:cn,webgpu:H|p1},"rgb32float-webgl":{render:an,filter:cn},rgba32float:{render:an,filter:cn,webgpu:M0},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:k5,webgpu:un},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:an,webgpu:un|i0},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:B0|i0},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1,webgpu:H|i0},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8",webgpu:H},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16",webgpu:H},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32",webgpu:H},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32",webgpu:H},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0,webgpu:H},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0,f:"depth32float-stencil8",webgpu:H}},U5={"bc1-rgb-unorm-webgl":{f:t0},"bc1-rgb-unorm-srgb-webgl":{f:t0},"bc1-rgba-unorm":{f:t0},"bc1-rgba-unorm-srgb":{f:t0},"bc2-rgba-unorm":{f:t0},"bc2-rgba-unorm-srgb":{f:t0},"bc3-rgba-unorm":{f:t0},"bc3-rgba-unorm-srgb":{f:t0},"bc4-r-unorm":{f:t0},"bc4-r-snorm":{f:t0},"bc5-rg-unorm":{f:t0},"bc5-rg-snorm":{f:t0},"bc6h-rgb-ufloat":{f:t0},"bc6h-rgb-float":{f:t0},"bc7-rgba-unorm":{f:t0},"bc7-rgba-unorm-srgb":{f:t0},"etc2-rgb8unorm":{f:_0},"etc2-rgb8unorm-srgb":{f:_0},"etc2-rgb8a1unorm":{f:_0},"etc2-rgb8a1unorm-srgb":{f:_0},"etc2-rgba8unorm":{f:_0},"etc2-rgba8unorm-srgb":{f:_0},"eac-r11unorm":{f:_0},"eac-r11snorm":{f:_0},"eac-rg11unorm":{f:_0},"eac-rg11snorm":{f:_0},"astc-4x4-unorm":{f:F},"astc-4x4-unorm-srgb":{f:F},"astc-5x4-unorm":{f:F},"astc-5x4-unorm-srgb":{f:F},"astc-5x5-unorm":{f:F},"astc-5x5-unorm-srgb":{f:F},"astc-6x5-unorm":{f:F},"astc-6x5-unorm-srgb":{f:F},"astc-6x6-unorm":{f:F},"astc-6x6-unorm-srgb":{f:F},"astc-8x5-unorm":{f:F},"astc-8x5-unorm-srgb":{f:F},"astc-8x6-unorm":{f:F},"astc-8x6-unorm-srgb":{f:F},"astc-8x8-unorm":{f:F},"astc-8x8-unorm-srgb":{f:F},"astc-10x5-unorm":{f:F},"astc-10x5-unorm-srgb":{f:F},"astc-10x6-unorm":{f:F},"astc-10x6-unorm-srgb":{f:F},"astc-10x8-unorm":{f:F},"astc-10x8-unorm-srgb":{f:F},"astc-10x10-unorm":{f:F},"astc-10x10-unorm-srgb":{f:F},"astc-12x10-unorm":{f:F},"astc-12x10-unorm-srgb":{f:F},"astc-12x12-unorm":{f:F},"astc-12x12-unorm-srgb":{f:F},"pvrtc-rgb4unorm-webgl":{f:on},"pvrtc-rgba4unorm-webgl":{f:on},"pvrtc-rgb2unorm-webgl":{f:on},"pvrtc-rgba2unorm-webgl":{f:on},"etc1-rgb-unorm-webgl":{f:X9},"etc1-rbg-unorm-webgl":{f:X9},"atc-rgb-unorm-webgl":{f:u1},"atc-rgba-unorm-webgl":{f:u1},"atc-rgbai-unorm-webgl":{f:u1}},V5={...$5,...U5};var j5=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,W5=["rgb","rgba","bgra"],q5=["depth","stencil"],H5=5,X5=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"],x1=class{isColor(e){return W5.some(t=>e.startsWith(t))}isDepthStencil(e){return q5.some(t=>e.startsWith(t))}isCompressed(e){return X5.some(t=>e.startsWith(t))}getInfo(e){return J9(e)}getCapabilities(e){return K5(e)}getWebGPUCapabilities(e){let t=dn(e);return t.webgpu!==void 0?t.webgpu:this.isCompressed(e)&&!e.endsWith("-webgl")?H5:0}computeMemoryLayout(e,t){return Y5(e,t)}},qe=new x1;function Y5({format:r,width:e,height:t,depth:n,byteAlignment:i},s={}){let o=qe.getInfo(r),{bytesPerPixel:a,blockHeight:c=1,compressed:u=!1}=o,l=b1(o,e,i),d=u?Math.ceil(t/c):t;return s.bytesPerPixel=a,s.bytesPerRow=l,s.rowsPerImage=d,s.depthOrArrayLayers=n,s.bytesPerImage=l*d,s.byteLength=s.bytesPerImage*n,s}function b1(r,e,t){let{bytesPerPixel:n,bytesPerBlock:i=n,blockWidth:s=1,compressed:o=!1}=r,a=o?Math.ceil(e/s):e;return Math.ceil(a*i/t)*t}function K5(r){let e=dn(r),t={format:r,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=J9(r),i=r.startsWith("depth")||r.startsWith("stencil"),s=n?.signed,o=n?.integer,a=n?.webgl,c=!!n?.compressed;return t.render&&=!i&&!c,t.filter&&=!i&&!s&&!o&&!a,t}var Q9=new Map;function J9(r){let e=Q9.get(r);if(!e){let t=Z5(r);t.bitsPerChannel=Object.freeze([...t.bitsPerChannel]),e=Object.freeze(t),Q9.set(r,e)}return e}function Z5(r){let e=Q5(r);if(qe.isCompressed(r)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=e8(r);let n=J5(r);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}let t=e.packed?null:j5.exec(r);if(t){let[,n,i,s,o,a]=t,c=`${s}${i}`,u=H9.getDataTypeInfo(c),l=u.byteLength*8,d=n?.length??1,f=[l,d>=2?l:0,d>=3?l:0,d>=4?l:0];e={format:r,attachment:e.attachment,dataType:u.signedType,components:d,channels:n,integer:u.integer,signed:u.signed,normalized:u.normalized,bitsPerChannel:f,bytesPerPixel:u.byteLength*d,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),o==="-srgb"&&(e.srgb=!0)}return r.endsWith("-webgl")&&(e.webgl=!0),r.endsWith("-srgb")&&(e.srgb=!0),e}function Q5(r){let e={...dn(r)},t=e.bytesPerPixel||1,n=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,delete e.webgpu,{...e,format:r,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:t,bitsPerChannel:n,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function J5(r){let t=/.*-(\d+)x(\d+)-.*/.exec(r);if(t){let[,n,i]=t;return{blockWidth:Number(n),blockHeight:Number(i)}}return r.startsWith("bc")||r.startsWith("etc1")||r.startsWith("etc2")||r.startsWith("eac")||r.startsWith("atc")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb4")||r.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:r.startsWith("pvrtc-rgb2")||r.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function e8(r){return r.startsWith("bc1")||r.startsWith("bc4")||r.startsWith("etc1")||r.startsWith("etc2-rgb8")||r.startsWith("etc2-rgb8a1")||r.startsWith("eac-r11")||r==="atc-rgb-unorm-webgl"?8:r.startsWith("bc2")||r.startsWith("bc3")||r.startsWith("bc5")||r.startsWith("bc6h")||r.startsWith("bc7")||r.startsWith("etc2-rgba8")||r.startsWith("eac-rg11")||r.startsWith("astc")||r==="atc-rgba-unorm-webgl"||r==="atc-rgbai-unorm-webgl"?16:r.startsWith("pvrtc")?8:16}function kt(r){return typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement||typeof VideoFrame<"u"&&r instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas}function fn(r){if(typeof ImageData<"u"&&r instanceof ImageData||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas)return{width:r.width,height:r.height};if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement)return{width:r.naturalWidth,height:r.naturalHeight};if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement)return{width:r.videoWidth,height:r.videoHeight};if(typeof VideoFrame<"u"&&r instanceof VideoFrame)return{width:r.displayWidth,height:r.displayHeight};throw new Error("Unknown image type")}var X0=class r extends h0{static defaultProps={...h0.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,t){t=r.normalizeProps(e,t),super(e,t,r.defaultProps)}static normalizeProps(e,t){return t}};function e2(r,e){let t=e instanceof X0?e:r.device.createSampler(e);if(t===r.sampler)return;e instanceof X0||t.transferOwnershipTo(r);let n=r.sampler;r.sampler=t,n?.owner===r&&n.destroy()}var t2=[],t8=Object.freeze({}),r8={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"},r0=class r extends h0{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,t,n){if(t=r.normalizeProps(e,t),super(e,t,r.defaultProps),this.dimension=this.props.dimension,this.baseDimension=r8[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(t.data)){let i=e.getExternalImageSize(t.data);this.width=i?.width||1,this.height=i?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&a0.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){e2(this,e)}copyImageData(e){let{data:t,depth:n,...i}=e;this.writeData(t,{...i,depthOrArrayLayers:i.depthOrArrayLayers??n})}computeMemoryLayout(e=t8,t){let n=t2.pop()||{readOptions:{},layoutOptions:{}};try{let i=this._normalizeTextureReadOptions(e,n.readOptions),s=n.layoutOptions;return s.format=this.format,s.width=i.width,s.height=i.height,s.depth=i.depthOrArrayLayers,s.byteAlignment=this.byteAlignment,qe.computeMemoryLayout(s,t)}finally{t2.push(n)}}readBuffer(e,t){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,t){throw new Error("readBuffer not implemented")}writeData(e,t){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,t){let n={...t},{width:i,height:s}=n;return typeof i=="number"&&(n.width=Math.max(1,Math.ceil(i))),typeof s=="number"&&(n.height=Math.max(1,Math.ceil(s))),n}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e,t={}){let{data:n,depth:i,depthOrArrayLayers:s}=e;if(this._normalizeTextureWriteOptions(e,t),s===void 0&&i!==void 0){let o=this.dimension==="3d"?Math.max(1,this.depth>>t.mipLevel):this.depth;t.depthOrArrayLayers=Math.min(i,o-t.z)}return t.data=n,t.depth=t.depthOrArrayLayers,t}_normalizeCopyExternalImageOptions(e,t={}){let{width:n,height:i}=e,s=this.device.getExternalImageSize(e.image),o=r._normalizeOptions(e,r.defaultCopyExternalImageOptions,t),a=Math.max(1,this.width>>o.mipLevel),c=this.baseDimension==="1d"?1:Math.max(1,this.height>>o.mipLevel),u=this.dimension==="3d"?Math.max(1,this.depth>>o.mipLevel):this.depth;return o.width=Math.min(n??s.width,a-o.x),o.height=Math.min(i??s.height,c-o.y),o.depth=Math.min(o.depth,u-o.z),o}_normalizeCopyElementImageOptions(e,t={}){let n=r._normalizeOptions(e,r.defaultCopyElementImageOptions,t),i=Math.max(1,this.width>>n.mipLevel),s=this.baseDimension==="1d"?1:Math.max(1,this.height>>n.mipLevel),o=this.dimension==="3d"?Math.max(1,this.depth>>n.mipLevel):this.depth;return n.width=Math.min(n.width??i,i-n.x),n.height=Math.min(n.height??s,s-n.y),n.depth=Math.min(n.depth,o-n.z),n}_normalizeTextureReadOptions(e,t={}){let{depthOrArrayLayers:n}=e,i=r._normalizeOptions(e,r.defaultTextureReadOptions,t),s=Math.max(1,this.width>>i.mipLevel),o=this.baseDimension==="1d"?1:Math.max(1,this.height>>i.mipLevel),a=this.dimension==="3d"?Math.max(1,this.depth>>i.mipLevel):this.depth;return i.width=Math.min(i.width??s,s-i.x),i.height=Math.min(i.height??o,o-i.y),i.depthOrArrayLayers=Math.min(n??a,a-i.z),i}_getSupportedColorReadOptions(e){let t=this._normalizeTextureReadOptions(e),n=qe.getInfo(this.format);switch(this._validateColorReadAspect(t),this._validateColorReadFormat(n),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return t;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e,t={}){let{byteOffset:n=0,bytesPerRow:i,rowsPerImage:s}=e;this._normalizeTextureReadOptions(e,t);let o=t;o.byteOffset=n;let a=this.device.getTextureFormatInfo(this.format),c=a.bytesPerPixel*o.width;if(o.bytesPerRow=i??b1(a,o.width,this.byteAlignment),o.rowsPerImage=s??o.height,o.bytesPerRow<c)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be at least ${c} for ${this.format}`);if(o.rowsPerImage<o.height)throw new Error(`rowsPerImage (${o.rowsPerImage}) must be at least ${o.height} for ${this.format}`);let{bytesPerPixel:u}=a;if(u&&o.bytesPerRow%u!==0)throw new Error(`bytesPerRow (${o.bytesPerRow}) must be a multiple of bytesPerPixel (${u}) for ${this.format}`);return o}_getMipLevelSize(e){let t=Math.max(1,this.width>>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),i=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:t,height:n,depthOrArrayLayers:i}}getAllocatedByteLength(){let e=0;for(let t=0;t<this.mipLevels;t++){let{width:n,height:i,depthOrArrayLayers:s}=this._getMipLevelSize(t);e+=qe.computeMemoryLayout({format:this.format,width:n,height:i,depth:s,byteAlignment:1}).byteLength}return e*this.samples}static _normalizeOptions(e,t,n){for(let i in t)n[i]=e[i]===void 0?t[i]:e[i];return n}static defaultProps={...h0.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:r.SAMPLE|r.RENDER|r.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultCopyElementImageOptions={element:void 0,width:void 0,height:void 0,sourceX:0,sourceY:0,sourceWidth:void 0,sourceHeight:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}};function hn(r,e,t){let n=r.bindings.find(i=>i.name===e||`${i.name.toLocaleLowerCase()}uniforms`===e.toLocaleLowerCase());return!n&&!t?.ignoreWarnings&&a0.warn(`Binding ${e} not set: Not found in shader layout.`)(),n||null}var s8=A0.DEBUG_DATA_MAX_LENGTH,$=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:i,ownsBuffer:s=!0,...o}=t;if(i&&i.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(i&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||i?.id||Ue("dynamic-buffer"),c={...o,id:a,usage:o.usage??i?.usage,indexType:o.indexType??i?.indexType};(c.usage||0)&A0.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:s8,this._ownsBuffer=s,this._buffer=i??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let i=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),i=new Uint8Array(s.slice(0,n))},t,n),this._touch(),i&&this._writeDebugData(i,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let i=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(i=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return i&&this._writeDebugData(i,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let i=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...u}=this.props,l=this.device.createBuffer({...u,byteLength:t});return n&&i>0&&this._copyBufferContents(s,l,i),this._buffer=l,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let i=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:i}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),i=new Uint8Array(this.debugData),s=Math.min(n.byteLength,i.byteLength-t);return i.set(n.subarray(0,s),t),s>0}};function O0(r){return r!==null&&typeof r=="object"&&"buffer"in r}function pn(r){return r instanceof $?r:O0(r)&&r.buffer instanceof $?r.buffer:null}function v1(r){return r instanceof $?r.buffer:r}function He(r){return{buffer:v1(r.buffer),offset:r.offset,size:r.size}}var T1={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function Ft(r){return r?Array.isArray(r)?r[0]??null:r:null}function r2(r){let{dimension:e,data:t}=r;if(!t)return null;switch(e){case"1d":{let n=Ft(t);if(!n)return null;let{width:i}=Gt(n);return{width:i,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=Ft(t);return n?Gt(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=Ft(t[0]);return n?Gt(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let i=t[n],s=Ft(i);return s?Gt(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],i=Object.keys(n)[0]??null;if(!i)return null;let s=Ft(n[i]);return s?Gt(s):null}default:return null}}function Gt(r){if(kt(r))return fn(r);if(typeof r=="object"&&"width"in r&&"height"in r)return{width:r.width,height:r.height};throw new Error("Unsupported mip-level data")}function o8(r){return typeof r=="object"&&r!==null&&"data"in r&&"width"in r&&"height"in r}function a8(r){return ArrayBuffer.isView(r)}function S1(r){let{textureFormat:e,format:t}=r;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function n2(r){let e=T1[r];if(e===void 0)throw new Error(`Invalid cube face: ${r}`);return e}function c8(r,e){return 6*r+n2(e)}function w1(r){throw new Error("setTexture1DData not supported in WebGL.")}function u8(r){return Array.isArray(r)?r:[r]}function de(r,e,t,n){let i=u8(e),s=r,o=[];for(let a=0;a<i.length;a++){let c=i[a];if(kt(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(o8(c))o.push({type:"texture-data",data:c,textureFormat:S1(c),z:s,mipLevel:a});else if(a8(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function I1(r){let e=[];for(let t=0;t<r.length;t++)e.push(...de(t,r[t]));return e}function A1(r){let e=[];for(let t=0;t<r.length;t++)e.push(...de(t,r[t]));return e}function _1(r){let e=[];for(let[t,n]of Object.entries(r)){let i=n2(t);e.push(...de(i,n))}return e}function M1(r){let e=[];return r.forEach((t,n)=>{for(let[i,s]of Object.entries(t)){let o=c8(n,i);e.push(...de(o,s))}}),e}var c0=class r{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=Ue("dynamic-texture"),i=t;this.props={...r.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(i)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?l8({...t,width:e.width,height:e.height,format:e.format}):[],i="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};let m=r2(t);return m||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);let c=d8(this.device,n,a,{format:i?e.format:void 0}),u=c.format??this.props.format,l={...this.props,...a,format:u,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(u)&&!s&&(l.usage=r0.SAMPLE|r0.COPY_DST);let d=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(u);if(this.device.type==="webgpu"&&d){let m=this.props.dimension==="3d"?r0.SAMPLE|r0.STORAGE|r0.COPY_DST|r0.COPY_SRC:r0.SAMPLE|r0.RENDER|r0.COPY_DST|r0.COPY_SRC;l.usage|=m}let f=this.device.getMipLevelCount(l.width,l.height),h=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?f:Math.max(1,Math.min(f,this.props.mipLevels??1)),p={...l,mipLevels:h};this._texture=this.device.createTexture(p),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!d&&a0.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),a0.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):a0.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof X0?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),o=this.device.createBuffer({byteLength:s.byteLength,usage:A0.COPY_DST|A0.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:i},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,i=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:i}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),a0.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=T1[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=w1(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=de(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=I1(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=A1(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=_1(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=M1(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:i}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:i,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${i} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:i});break;default:throw new Error("Unsupported 2D mip-level payload")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await E1(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&a0.warn(`${this} already destroyed`)}_checkReady(){this.isReady||a0.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...r0.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function l8(r){if(!r.data)return[];let e=r.width&&r.height?{width:r.width,height:r.height}:void 0,t="format"in r?r.format:void 0;switch(r.dimension){case"1d":return w1(r.data);case"2d":return de(0,r.data,e,t);case"3d":return I1(r.data);case"2d-array":return A1(r.data);case"cube":return _1(r.data);case"cube-array":return M1(r.data);default:throw new Error(`Unhandled dimension ${r.dimension}`)}}function d8(r,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let i=new Map;for(let l of e){let d=i.get(l.z)??[];d.push(l),i.set(l.z,d)}let s=e.some(l=>l.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[l,d]of i){let f=[...d].sort((v,T)=>v.mipLevel-T.mipLevel),h=f[0];if(!h||h.mipLevel!==0)throw new Error(`DynamicTexture: slice ${l} is missing mip level 0`);let p=s2(r,h);if(p.width!==t.width||p.height!==t.height)throw new Error(`DynamicTexture: slice ${l} base level dimensions ${p.width}x${p.height} do not match expected ${t.width}x${t.height}`);let m=i2(h);if(m){if(o&&o!==m)throw new Error(`DynamicTexture: slice ${l} base level format "${m}" does not match texture format "${o}"`);o=m}let g=o&&r.isTextureFormatCompressed(o)?f8(r,p.width,p.height,o):r.getMipLevelCount(p.width,p.height),b=0;for(let v=0;v<f.length;v++){let T=f[v];if(!T||T.mipLevel!==v||v>=g)break;let S=s2(r,T),y=Math.max(1,p.width>>v),x=Math.max(1,p.height>>v);if(S.width!==y||S.height!==x)break;let w=i2(T);if(w&&(o||(o=w),w!==o))break;b++,c.push(T)}a=Math.min(a,b)}let u=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(l=>l.mipLevel<u),mipLevels:u,format:o,hasExplicitMipChain:s}}function i2(r){if(r.type==="texture-data")return r.textureFormat??S1(r.data)}function s2(r,e){switch(e.type){case"external-image":return r.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function f8(r,e,t,n){let{blockWidth:i=1,blockHeight:s=1}=r.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),u=Math.max(1,t>>a);if(c<i||u<s)break;o++}return o}async function E1(r){if(r=await r,Array.isArray(r))return await Promise.all(r.map(E1));if(r&&typeof r=="object"&&r.constructor===Object){let e=r,t=await Promise.all(Object.values(e).map(E1)),n=Object.keys(e),i={};for(let s=0;s<n.length;s++)i[n[s]]=t[s];return i}return r}function v0(r){return r!==null&&typeof r=="object"&&"resolveTextureBinding"in r&&typeof r.resolveTextureBinding=="function"}function o2(r){return r?.type==="texture"||r?.type==="external-texture"}function zt(r,e,t){let n=hn(r,e,{ignoreWarnings:!0});return o2(n)?n:r.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var E0=2,m8=1e4,P1="render pipeline initialization failed",g8=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],p0=class r{static async createAsync(e,t){let n=!E.PipelineFactory.getAsyncCompilation(e),i=n?E.PipelineFactory.beginAsyncCompilation(e):E.PipelineFactory.getAsyncCompilation(e),s;try{s=new this(e,t)}finally{n&&E.PipelineFactory.endAsyncCompilation(e,i)}try{return n?await Promise.all(i):await s._pipelineInitialization,s}catch(o){throw s.destroy(),o}}static defaultProps={...E.RenderPipeline.defaultProps,inferDrawCount:"no",enforceMatchingVectorLengths:!0,geometry:null,attributeVectors:void 0,source:void 0,sourceLanguage:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:void 0,debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;_uniformStore;_attributeInfos={};props;batchUniformBuffer;geometryVectorBindings;attributeVectorBindings;explicitBufferLayout=[];constructorDrawCounts;constructorDrawOffsets;drawingVectorBatches=!1;indexVector=null;currentAttributes={};currentAttributeByteOffsets={};_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_vertexCountSet=!1;_lastDrawTimestamp=-1;_bindingTable=[];_pipelineInitialization;get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){this.constructorDrawOffsets={firstVertex:t.firstVertex,firstIndex:t.firstIndex};let n=this.constructor.defaultProps;this.constructorDrawCounts={vertexCount:t.vertexCount??(n.vertexCount||void 0),instanceCount:t.instanceCount??(n.instanceCount||void 0)};let i=n.shaderAssembler,s=Object.hasOwn(t,"vertexCount");this.props={...n,...t,shaderAssembler:t.shaderAssembler??(i&&L1(i,e.info.shadingLanguage)?i:e.info.shadingLanguage==="wgsl"?new $0:new At)},this._vertexCountSet=s,t=this.props,this.id=t.id||J("model"),this.device=e,Object.assign(this.userData,t.userData),this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,this.isInstanced=t.isInstanced??(t.instanceCount?!0:void 0),this.explicitBufferLayout=this.bufferLayout,this.geometryVectorBindings=new Pt(e,`${this.id}-geometry`),this.attributeVectorBindings=new Pt(e,`${this.id}-attributes`);try{this._initializeProps(t);let o=ue(e),a=(0,mn.resolveShaderPlugins)(this.props.plugins,o.shaderLanguage),c=(0,mn.mergeShaderPluginModules)(this.props.modules,a.modules),u=Object.fromEntries(c.map(m=>[m.name,m])),l=t.shaderInputs||new e0(u,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&a.modules.length>0&&l.addModules(a.modules),this.setShaderInputs(l);let d=Kr(this.props.modules,l.getModules()),f={...a.defines,...this.props.defines};if(this.device.type==="webgl"&&(this.props._uniformBlockLayouts=I9(d)),this.props.shaderLayout=Ge(this.props.shaderLayout,d)||null,this.device.type==="webgpu"&&this.props.source){let m=this.props.shaderAssembler;(0,E.assert)(L1(m,"wgsl"));let{source:g,getUniforms:b,bindingTable:v,entryPoints:T={},shaderLayout:S}=m.assembleWGSLShader({platformInfo:o,...this.props,modules:d,defines:f,pluginInjectionTargets:a.injectionTargets,pluginInjections:a.injections,pluginVertexInputs:a.vertexInputs,pluginInterStageVariables:a.interStageVariables});this.source=g,this.props.vertexEntryPoint=T.vertex||this.props.vertexEntryPoint,this.props.fragmentEntryPoint=T.fragment||this.props.fragmentEntryPoint,this._getModuleUniforms=b,this._bindingTable=v;let y=S??e.getShaderLayout?.(this.source),x=y8(y,a.vertexInputs),w=w9(this.props.shaderLayout,x,Object.keys(a.vertexInputs));this.props.shaderLayout=Ge(w||null,d)||null}else{let m=this.props.shaderAssembler;(0,E.assert)(L1(m,"glsl"));let{vs:g,fs:b,getUniforms:v}=m.assembleGLSLShaderPair({platformInfo:o,...this.props,modules:d,defines:f,pluginInjectionTargets:a.injectionTargets,pluginInjections:a.injections,pluginVertexInputs:a.vertexInputs,pluginInterStageVariables:a.interStageVariables});this.vs=g,this.fs=b,this._getModuleUniforms=v,this._bindingTable=[]}this.pipelineFactory=t.pipelineFactory||E.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||E.ShaderFactory.getDefaultShaderFactory(this.device);let p=E.PipelineFactory.getAsyncCompilation(this.device);p?(this._pipelineInitialization=this._initializePipelineAsync(t),p.push(this._pipelineInitialization)):(this.pipeline=this._updatePipeline(),this._initializePipelineResources(t))}catch(o){try{r.prototype.destroy.call(this)}finally{throw o}}}_initializeProps(e){e.geometry&&this.setGeometry(e.geometry),e.attributeVectors&&this.setAttributeVectors(e.attributeVectors)}_usesManagedUniformBuffer(e){return!0}async _initializePipelineAsync(e){await this._updatePipelineAsync(),this._initializePipelineResources(e)}_initializeAttributes(){this.applyVectorAttributes(),this.indexVector&&this.bindIndexVector()}_initializePipelineResources(e){this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._initializeAttributes(),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.indexCount!==void 0&&this.setIndexCount(e.indexCount),this.constructorDrawOffsets.firstVertex!==void 0&&(this.firstVertex=this.constructorDrawOffsets.firstVertex),this.constructorDrawOffsets.firstIndex!==void 0&&(this.firstIndex=this.constructorDrawOffsets.firstIndex),e.isInstanced!==void 0&&(this.isInstanced=e.isInstanced),this.constructorDrawCounts.instanceCount!==void 0&&this.setInstanceCount(this.constructorDrawCounts.instanceCount),this.constructorDrawCounts.vertexCount!==void 0&&this.setVertexCount(this.constructorDrawCounts.vertexCount),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback)}destroy(){this._destroyed||(this.pipeline&&(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs)),this.vertexArray?.destroy(),this.geometryVectorBindings.destroy(),this.attributeVectorBindings.destroy(),this._uniformStore?.destroy(),this.batchUniformBuffer?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e,t){return t?.parameters?this._withDrawParameters(e,t.parameters,()=>this._draw(e)):this._draw(e)}_withDrawParameters(e,t,n){let i=e.getParameters();try{return e.setParameters(t),n()}finally{e.setParameters(i)}}_draw(e){if(this.indexVector?.length===0)return this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1,!0;if(!this.drawingVectorBatches&&(this.geometryVectorBindings.batchCount!==1||this.attributeVectorBindings.batchCount!==1))return this.drawVectorGroups(e);if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,i=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),i=this.pipeline.isErrored,i)E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${P1}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)E.log.info(E0,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:u}=this.vertexArray,l=u?this.indexCount??(this._vertexCountSet?this.vertexCount:u.byteLength/(u.indexType==="uint32"?4:2)):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:l,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):i?(this._needsRedraw=P1,this._drawBlockedReason=P1):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){e&&this.setTopology(e.topology),this.setGeometryVectors(e?.attributes??{},e?.bufferLayout),this.setIndexVector(e?.indices??null),e?.vertexCount!==void 0&&this.setVertexCount(e.vertexCount)}setGeometryVectors(e,t){t??=this.getExplicitVectorLayouts(e)??this.getExplicitVectorLayouts(e,this.geometryVectorBindings.sourceLayouts),this.validateVectorLengthPolicy(),this.props.enforceMatchingVectorLengths&&C0(e),this.props.enforceMatchingVectorLengths&&(!this.isInstanced||this.attributeVectorBindings.vertexCount!==void 0)&&C0([...Object.values(e),...Object.values(this.attributeVectorBindings.inputs)]),this.geometryVectorBindings.setInputs(e,t,"vertex",this.props.enforceMatchingVectorLengths),this.claimVectorLayouts(this.geometryVectorBindings),this.syncVectorBindings();let n=this.geometryVectorBindings.rowCount;(0,E.assert)(n===void 0||this.attributeVectorBindings.vertexCount===void 0||n===this.attributeVectorBindings.vertexCount),this.props.inferDrawCount==="vertex"&&this.setVertexCount(n??this.attributeVectorBindings.vertexCount??0)}setAttributeVectors(e,t){t??=this.getExplicitVectorLayouts(e)??this.getExplicitVectorLayouts(e,this.attributeVectorBindings.sourceLayouts),this.isInstanced===void 0&&(t?.some(s=>s.stepMode==="instance")||Object.values(e).some(s=>s&&"data"in s&&s.bufferLayout?.stepMode==="instance"))&&(this.isInstanced=!0);let n=!this.isInstanced||Object.entries(e).some(([s,o])=>o&&"data"in o&&(t?.find(a=>a.name===s||a.attributes?.some(c=>c.attribute===s))?.stepMode??o.bufferLayout?.stepMode)==="vertex");this.validateVectorLengthPolicy(),n&&this.props.enforceMatchingVectorLengths&&C0([...Object.values(this.geometryVectorBindings.inputs),...Object.values(e)]),this.attributeVectorBindings.setInputs(e,t,this.isInstanced?"instance":"vertex",this.props.enforceMatchingVectorLengths),this.claimVectorLayouts(this.attributeVectorBindings),this.syncVectorBindings(),this.props.inferDrawCount==="instance"&&this.attributeVectorBindings.instanceCount!==void 0&&this.setInstanceCount(this.attributeVectorBindings.instanceCount);let i=this.attributeVectorBindings.vertexCount;if(i!==void 0&&this.props.inferDrawCount==="vertex"){let s=this.geometryVectorBindings.rowCount;(0,E.assert)(s===void 0||s===i),s===void 0&&this.setVertexCount(i)}}setGPUAttributes(e,t){this.setAttributeVectors(e,t)}setIndexVector(e){e&&((0,E.assert)(e.format==="uint8"||e.format==="uint16"||e.format==="uint32"),(0,E.assert)(e.data.length<=1),(0,E.assert)(e.byteStride===(e.format==="uint32"?4:e.format==="uint16"?2:1))),this.indexVector=e,this.vertexArray&&this.bindIndexVector()}bindIndexVector(){let e=this.indexVector,t=e?.data[0];if(t&&this.indexVector){let n=t.buffer instanceof $?t.buffer.buffer:t.buffer;(0,E.assert)(n.indexType===this.indexVector.format&&t.byteOffset%this.indexVector.byteStride===0)}this.indexVector=null,this.setIndexBuffer(t?.buffer??null),this.indexVector=e,this.indexCount=e?.length,this.setDrawOffsets({firstVertex:t?.byteOffset??0,firstIndex:t?t.byteOffset/this.indexVector.byteStride:0})}claimVectorLayouts(e){this.explicitBufferLayout=this.explicitBufferLayout.filter(t=>!e.claimedNames.has(t.name)&&!t.attributes?.some(n=>e.claimedNames.has(n.attribute)))}getExplicitVectorLayouts(e,t=this.explicitBufferLayout){let n=new Set(Object.keys(e)),i=t.filter(s=>n.has(s.name)||s.attributes?.some(o=>n.has(o.attribute)));return i.length?i:void 0}getVectorBufferLayout(){let e=[this.geometryVectorBindings,this.attributeVectorBindings];return[...this.explicitBufferLayout.filter(n=>!e.some(i=>i.claimedNames.has(n.name)||n.attributes?.some(s=>i.claimedNames.has(s.attribute)))),...this.geometryVectorBindings.layouts,...this.attributeVectorBindings.layouts]}syncVectorBindings(){let e=this.getVectorBufferLayout();this.vertexArray?(this.applyBufferLayout(e),this.applyVectorAttributes()):this.bufferLayout=e}applyVectorAttributes(){let e=new Set(this.bufferLayout.map(t=>t.name));for(let t of Object.keys(this.currentAttributes))e.has(t)||delete this.currentAttributes[t];this.setAttributes({...this.currentAttributes,...this.geometryVectorBindings.buffers,...this.attributeVectorBindings.buffers},{byteOffsets:{...this.currentAttributeByteOffsets,...this.geometryVectorBindings.byteOffsets,...this.attributeVectorBindings.byteOffsets},disableWarnings:!0}),this.device.type==="webgl"&&this.setConstantAttributes({...this.geometryVectorBindings.constants,...this.attributeVectorBindings.constants})}setGPUVectors(e,t){let n=V0(this.id,e);(0,E.assert)(n.length<=1),Xi(this.id,e,this.bufferLayout),n[0]&&this.setGPUData(n[0].data),this.setBatchDrawCount(n[0]?.rowCount??0,t?.count)}drawVectorGroups(e){let t=this.drawingVectorBatches,n=this._vertexCountSet;this.drawingVectorBatches=!0;try{let i=E9(this,this.geometryVectorBindings,this.attributeVectorBindings,()=>this.syncVectorBindings(),()=>r.prototype.draw.call(this,e),this.props.inferDrawCount);return i&&(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1),i}finally{this._vertexCountSet=n,this.drawingVectorBatches=t}}drawBatches(e,{vectors:t,onBatch:n}){let i=V0(this.id,t);Xi(this.id,t,this.bufferLayout);for(let m of Object.keys(t))(0,E.assert)(!t[m]||this.currentAttributes[m]);let s={...this.currentAttributes},o={...this.currentAttributeByteOffsets},a={...this.bindings},c=this.instanceCount,u=this.vertexCount,l=this.isInstanced,d=this._vertexCountSet,f=this.drawingVectorBatches,h=this.device.type==="webgpu"&&i.length?new E.UniformStore(this.device,this.shaderInputs.modules):void 0;if(h&&this._uniformStore.uniformBuffers.size){this.batchUniformBuffer??=new Hr(this.device);let m=0;for(let g of this._uniformStore.uniformBuffers.keys())m+=this.batchUniformBuffer.getAlignedByteLength(h.getUniformBufferData(g).byteLength);this.batchUniformBuffer.prepare(m*i.length)}this.drawingVectorBatches=!0;let p=!0;try{for(let m of i){this.setGPUData(m.data),this.setBatchDrawCount(m.rowCount),n?.(m);let g={};try{if(h){h.setUniforms(this.shaderInputs.getUniformValues());for(let[b,v]of this._uniformStore.uniformBuffers){let T=`${b}Uniforms`;this.bindings[T]===v&&(g[T]=v,this.setBindings({[T]:this.batchUniformBuffer.write(h.getUniformBufferData(b))}))}}p=r.prototype.draw.call(this,e)&&p}finally{this.setBindings(g)}}}finally{h?.destroy(),this.setAttributes(s,{byteOffsets:o});for(let m of Object.keys(this.bindings))m in a||delete this.bindings[m];this.setBindings(a),this.setInstanceCount(c),this.setVertexCount(u),this.isInstanced=l,this._vertexCountSet=d,this.drawingVectorBatches=f}return p}setGPUData(e){this.setAttributes(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.buffer])),{byteOffsets:Object.fromEntries(Object.entries(e).map(([t,n])=>{let i=this.bufferLayout.find(o=>o.name===t),s=n.byteOffset-(i?.attributes?.[0]?.byteOffset??0);return(0,E.assert)(s>=0),[t,s]}))})}validateVectorLengthPolicy(){(0,E.assert)(this.props.enforceMatchingVectorLengths!==!1||this.props.inferDrawCount==="no")}setBatchDrawCount(e,t=this.props.inferDrawCount==="no"?"none":this.props.inferDrawCount){t==="instance"?this.setInstanceCount(e):t==="vertex"&&this.setVertexCount(e)}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){this.explicitBufferLayout=e;let t=this.geometryVectorBindings,n=this.attributeVectorBindings,i=this.getExplicitVectorLayouts(t.inputs)??t.sourceLayouts,s=this.getExplicitVectorLayouts(n.inputs)??n.sourceLayouts;t.setInputs(t.inputs,i,"vertex",this.props.enforceMatchingVectorLengths),n.setInputs(n.inputs,s,this.isInstanced?"instance":"vertex",this.props.enforceMatchingVectorLengths),this.props.enforceMatchingVectorLengths&&(!this.isInstanced||n.vertexCount!==void 0)&&C0([...Object.values(t.inputs),...Object.values(n.inputs)]),this.claimVectorLayouts(t),this.claimVectorLayouts(n),this.applyBufferLayout(this.getVectorBufferLayout())}applyBufferLayout(e){if(e=qi(this.pipeline.shaderLayout,e),Fe(e,this.bufferLayout,-1))return;this.bufferLayout=e,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline();let t=this.vertexArray;this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),t.destroy(),this._dynamicAttributeBufferSources={},this.applyVectorAttributes(),this.indexBuffer&&this.vertexArray.setIndexBuffer(this.indexBuffer)}setParameters(e){Fe(e,this.parameters,2)||(this.parameters=e,this.device.type==="webgl"?this.setNeedsRedraw("parameters"):this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this._vertexCountSet=!0,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new E.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(ce(n)&&this._usesManagedUniformBuffer(t)){let i=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=i}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getShaderInputBindings()),this.setNeedsRedraw("shaderInputs")}_getShaderInputBindings(){return this.shaderInputs.getBindingValues()}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){this.indexVector&&(this.indexCount=void 0,this.firstVertex=0,this.firstIndex=0),this.indexVector=null;let t=e instanceof $?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof $?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){Object.assign(this.currentAttributes,e);for(let s of Object.keys(e))this.currentAttributeByteOffsets[s]=t?.byteOffsets?.[s]??0;this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&E.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=qi(this.pipeline.shaderLayout,this.bufferLayout);let i=new Xr(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof $?o.buffer:o,c=i.getBufferLayout(s);if(!c){n||E.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let u=i.getAttributeNamesForBuffer(c),l=!1;for(let d of u){let f=this._attributeInfos[d];if(f){let h=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(f.bufferName):f.location;if(h===null){n||E.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${f.bufferName}".`)();continue}let p=t?.byteOffsets?.[s]??0;this.vertexArray.setBuffer(h,a,p),o instanceof $?this._dynamicAttributeBufferSources[h]={source:o,generation:o.generation,byteOffset:p}:delete this._dynamicAttributeBufferSources[h],l=!0}}!l&&!n&&E.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,i]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,i):(t?.disableWarnings??this.props.disableWarnings)||E.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(v0(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,i]of Object.entries(this.bindings)){let s=x8(n,i,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){return e.bindings.length?(0,E.normalizeBindingsByGroup)(e,t):{0:t}}_getBindGroupCacheKeys(){return{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof E.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof E.Buffer||t instanceof E.Texture||t instanceof E.ExternalTexture||t instanceof $?e=Math.max(e,t.updateTimestamp):v0(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:O0(t)&&(e=Math.max(e,(t.buffer instanceof $,t.buffer.updateTimestamp)));return e}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=this.pipelineFactory.createRenderPipeline(e.props)}catch(t){throw this._releasePipelineShaders(e.vertexShader,e.fragmentShader),this._pipelineNeedsUpdate="pipeline creation failed",t}this._finishPipelineUpdate(e)}return this.pipeline}async _updatePipelineAsync(){let e=this._preparePipelineUpdate();if(e){try{this.pipeline=await this.pipelineFactory.createRenderPipelineAsync(e.props)}catch(t){throw this._releasePipelineShaders(e.vertexShader,e.fragmentShader),this._pipelineNeedsUpdate="asynchronous pipeline creation failed",t}this._finishPipelineUpdate(e)}return this.pipeline}_preparePipelineUpdate(){if(!this._pipelineNeedsUpdate)return null;let e=this.pipeline?.vs??null,t=this.pipeline?.fs??null;this.pipeline&&E.log.log(1,`GPUVectorModel ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),this._pipelineNeedsUpdate=!1;let n=null,i=null;try{n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),this.source?i=n:this.fs&&(i=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.fs,debugShaders:this.props.debugShaders}))}catch(s){throw this._releasePipelineShaders(n,i),this._pipelineNeedsUpdate="shader creation failed",s}return{props:{...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:i},vertexShader:n,fragmentShader:i,previousVertexShader:e,previousFragmentShader:t}}_finishPipelineUpdate(e){this._attributeInfos=(0,E.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),this._releasePipelineShaders(e.previousVertexShader,e.previousFragmentShader)}_releasePipelineShaders(e,t){e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=E.log.level>3?0:m8;E.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,E.log.group(E0,`>>> DRAWING MODEL ${this.id}`,{collapsed:E.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=x9(this.pipeline.shaderLayout,this.id);E.log.table(E0,e)();let t=this.shaderInputs.getDebugTable();E.log.table(E0,t)();let n=this._getAttributeDebugTable();E.log.table(E0,this._attributeInfos)(),E.log.table(E0,n)(),E.log.groupEnd(E0)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;T9(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let i=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:i?this._getBufferOrConstantValues(i,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=E.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof E.Buffer?new n(e.debugData):e).toString()}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer,t.byteOffset),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,i=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>b8(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??v8(t?.depthStencilAttachment?.props?.format??t?.depthStencilAttachment?.texture?.format);(!Fe(this._colorAttachmentFormats,i,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=i,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function L1(r,e){return r.shaderLanguage!==void 0&&r.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in r&&typeof r.assembleGLSLShaderPair=="function":"assembleWGSLShader"in r&&typeof r.assembleWGSLShader=="function"}function y8(r,e){return!r||Object.keys(e).length===0?r:{...r,attributes:r.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function x8(r,e,t){if(v0(e)){let n=zt(t,r,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof $?e.buffer:O0(e)?He(e):e}function b8(r){return r&&!a2(r)?r:null}function v8(r){return r&&a2(r)?r:void 0}function a2(r){return g8.includes(r)}var R1=B(k(),1);var Xe=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||J("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&R1.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function $t(r,e){if(e instanceof Xe)return e;let t=Me(e),n=T8(r,t),{attributes:i,bufferLayout:s}=S8(r,t);return new Xe({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:i})}function T8(r,e){if(!e.indices)return;let t=e.indices.value;return r.createBuffer({usage:R1.Buffer.INDEX,data:t})}function S8(r,e){let t={};for(let[n,i]of Object.entries(e.attributes)){let s=e.bufferLayout?.find(o=>o.name===n)?.name||ne(n);i&&(t[s]=r.createBuffer({data:i.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout||_i(e.attributes),vertexCount:e.vertexCount}}var m0=class{attributes;indices;topology;vertexCount;bufferLayout;destroy(){}constructor(e){this.attributes=e.attributes,this.indices=e.indices??null,this.topology=e.topology??"triangle-list",this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout}};var c2=B(k(),1);function u2(r,e){let t=$t(r,e);try{let n=gn(t);return n.destroy=()=>t.destroy(),n}catch(n){throw t.destroy(),n}}function gn(r){let e={};for(let[o,a]of Object.entries(r.attributes)){let c=r.bufferLayout.find(f=>f.name===o),u=c?.format,l=c?.byteStride??(u?c2.vertexFormatDecoder.getVertexFormatInfo(u).byteLength:0),d=r.indices&&l?Math.floor(a.byteLength/l):r.vertexCount;e[o]={name:o,format:u,length:d,byteStride:l,rowByteLength:l,bufferLayout:c,data:[{buffer:a,byteOffset:0,length:d,format:u,byteStride:l,rowByteLength:l}]}}if(r.indices){let o=Math.min(...Object.values(e).map(a=>a.length));for(let[a,c]of Object.entries(e))e[a]={...c,length:o,data:c.data.map(u=>({...u,length:o}))}}let t=r.indices,n=t?.indexType==="uint32"?4:t?.indexType==="uint8"?1:2,i=t?t.byteLength/n:0,s=t?{name:"indices",format:t.indexType,length:i,byteStride:n,rowByteLength:n,data:[{buffer:t,byteOffset:0,length:i,format:t.indexType,byteStride:n,rowByteLength:n}]}:null;return new m0({attributes:e,indices:s,topology:r.topology,vertexCount:r.vertexCount,bufferLayout:r.bufferLayout})}var Y0=class extends p0{static defaultProps={...p0.defaultProps,material:void 0};get sourceGeometry(){return this.sourceGeometryValue}constructor(e,t){let n=t.geometry===void 0?new.target.defaultProps.geometry:t.geometry,i=n&&!(n instanceof m0)?$t(e,n):null,s=i?gn(i):n,o={...t,geometry:s instanceof m0?s:null};try{super(e,o)}catch(a){throw i?.destroy(),a}this._gpuGeometry=i,this.sourceGeometryValue=n,i&&this.setIndexCount(this.props.indexCount)}_initializeProps(e){this.material=e.material||null,this._gpuGeometry=null,this.sourceGeometryValue=null,super._initializeProps(e)}_initializeAttributes(){super._initializeAttributes(),this._gpuGeometry&&super.setIndexCount(this.indexCountOverride)}destroy(){super.destroy(),this._gpuGeometry?.destroy(),this._gpuGeometry=null,this.sourceGeometryValue=null}setGeometry(e){this._gpuGeometry?.destroy(),this._gpuGeometry=e&&!(e instanceof m0)?$t(this.device,e):null;let t=this._gpuGeometry?gn(this._gpuGeometry):e;super.setGeometry(t instanceof m0?t:null),e instanceof m0||super.setIndexCount(this.indexCountOverride),this.sourceGeometryValue=e}setIndexCount(e){this.indexCountOverride=e,super.setIndexCount(e)}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}_usesManagedUniformBuffer(e){return!this.material?.ownsModule(e)}updateShaderInputs(e){super.updateShaderInputs(e),this.material?.updateShaderInputs(e)}_getShaderInputBindings(){let e=super._getShaderInputBindings(),t=this.material;return t?Object.fromEntries(Object.entries(e).filter(([n])=>!t.ownsBinding(n))):e}_areBindingsLoading(){let e=super._areBindingsLoading();if(e)return e;for(let t of Object.values(this.material?.bindings||{}))if(v0(t)&&!t.isReady)return t.id;return!1}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=super._getBindGroups(e,t);for(let[i,s]of Object.entries(this.material?.getBindingsByGroup(e)||{})){let o=Number(i);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){return Math.max(super._getBindingsUpdateTimestamp(),this.material?.getBindingsUpdateTimestamp()||0)}};var P0=B(k(),1);var Ke=3,Ye=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new e0(Object.fromEntries(this.modules.map(i=>[i.name,i])));this._materialBindingNames=w8(n),this._materialModuleNames=I8(n)}createMaterial(e={}){return new Ze(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=C1(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Ke]:e}:{}}};function C1(r){return r.endsWith("Uniforms")?r.slice(0,-8):null}function w8(r){let e=new Set;for(let t of Object.values(r.modules))for(let n of t.bindingLayout||[])n.group===Ke&&e.add(n.name);return e}function I8(r){let e=new Set;for(let t of Object.values(r.modules))t.name&&t.bindingLayout?.some(n=>n.group===Ke&&n.name===t.name)&&e.add(t.name);return e}var Ze=class{id;metadata={};device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||J("material"),this.device=e,this.factory=t.factory||new Ye(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(i=>[i.name,i]));this.shaderInputs=t.shaderInputs||new e0(n),this._uniformStore=new P0.UniformStore(this.device,this.shaderInputs.modules);for(let[i,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(i)&&ce(s)){let o=this._uniformStore.getManagedUniformBuffer(i);this.bindings[`${i}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.metadata={...this.metadata},t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))C1(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[i,s]of Object.entries(this.bindings))if(v0(s)){let o=zt(e,i,{fallbackGroup:Ke}),a=o?s.resolveTextureBinding(o):null;a&&(n[i]=a)}else s instanceof $?n[i]=s.buffer:O0(s)?n[i]=He(s):n[i]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Ke?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof P0.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof P0.Buffer||t instanceof P0.Texture||t instanceof P0.ExternalTexture||t instanceof $?e=Math.max(e,t.updateTimestamp):v0(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:O0(t)&&(e=Math.max(e,(t.buffer instanceof $,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,i]of Object.entries(e))i!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==i&&(this.bindings[n]=i,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,i]of Object.entries(this.bindings)){let s=A8(i);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function A8(r){return v0(r)?r.generation:pn(r)?.generation??null}var Qe=B(k(),1),d2=B(b0(),1);var l2=35980,_8=35981,yn=class r{device;model;transformFeedback;outputVectorBindings={};outputBuffers={};static defaultProps={...p0.defaultProps,inputVectors:void 0,outputVectors:void 0,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=r.defaultProps){if(!r.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.outputBuffers=t.feedbackBuffers||{};let{inputVectors:n,outputVectors:i,...s}=t;this.model=new p0(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,d2.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...s,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?l2:_8)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),n&&this.model.setGPUVectors(n,{count:"vertex"}),i&&this.setOutputVectors(i)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){let{inputVectors:t,outputVectors:n,inputBuffers:i,outputBuffers:s,...o}=e??{};i&&this.model.setAttributes(i),t&&this.model.setGPUVectors(t,{count:"vertex"}),s&&(this.outputBuffers=s),(s||n||Object.keys(this.outputVectorBindings).length>0)&&this.setOutputVectors(n??this.outputVectorBindings);let a=this.device.beginRenderPass({discard:!0,...o});try{this.model.draw(a)}finally{a.end()}}setOutputVectors(e){let t=V0(this.model.id,e);(0,Qe.assert)(t.length===0||this.model.pipeline.props.bufferMode!==l2),(0,Qe.assert)(t.length<=1),this.outputVectorBindings=e,this.transformFeedback.setBuffers({...this.outputBuffers,...Object.fromEntries(Object.entries(t[0]?.data??{}).map(([n,i])=>((0,Qe.assert)(i.byteStride===i.rowByteLength),[n,{buffer:i.buffer instanceof $?i.buffer.buffer:i.buffer,byteOffset:i.byteOffset,byteLength:i.length*i.byteStride}])))})}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof Qe.Buffer)return t.readAsync();let{buffer:n,byteOffset:i=0,byteLength:s=n.byteLength}=t;return n.readAsync(i,s)}};var f2=B(b0(),1);var M8="transform_output",xn=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e;let{inputVectors:n,...i}=t;this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new p0(this.device,{id:t.id||J("texture-transform-model"),fs:t.fs||(0,f2.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:M8}),vertexCount:t.vertexCount,...i}),n&&this.model.setGPUVectors(n,{count:"vertex"}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{inputVectors:t,...n}=e??{};t&&this.model.setGPUVectors(t,{count:"vertex"});let{framebuffer:i}=this.bindings[this.currentIndex],s=this.device.beginRenderPass({framebuffer:i,...n});try{this.model.draw(s)}finally{s.end()}this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:i}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),i){e.targetTexture=i;let{width:s,height:o}=i;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[i]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var E8=`struct VertexInputs {
|
|
131
131
|
@location(0) clipSpacePositions: vec2<f32>,
|
|
132
132
|
@location(1) texCoords: vec2<f32>,
|
|
133
133
|
@location(2) coordinates: vec2<f32>
|