UNPKG

typegpu

Version:

A thin layer between JS and WebGPU/WGSL that improves development experience and allows for faster iteration.

18 lines 81 kB
import{S as V,T as H,V as v,X as st,_ as Yt,a as L,aa as mt,b as Ne,ba as Ue,ca as on}from"./chunk-SFECI7OX.js";import{c as an}from"./chunk-SLWTVY6K.js";import{$ as O,A as qr,Aa as Jt,B as Jr,Ba as nn,C as Y,Ca as ut,D as Yr,Da as pt,E as Qr,Ea as lt,F as Xr,G as me,I as be,J as z,K as A,L as jt,M as Zr,S as ot,T as it,U as Se,V as ve,W as K,X as en,_ as Z,a as f,aa as k,b as S,ba as T,c as I,ca as tn,d as D,da as rn,e as p,ea as zt,f as h,fa as De,g as j,ga as Kt,h as pe,ha as _,i as he,ia as P,j as Gt,ja as C,k as Lt,ka as m,l as Ot,la as Le,m as le,ma as M,n as Ee,na as Oe,o as Ge,oa as ee,p as jr,pa as te,q as X,qa as Ht,r as Mt,ra as de,s as Wt,sa as Me,t as J,ta as Fe,u as zr,ua as Ie,v as Kr,va as qt,w as Nt,wa as B,x as Hr,xa as We,y as we,ya as E,z as at,za as G}from"./chunk-L7HIBZAX.js";function sn(e){if(typeof e?.[I]=="function")return e[I].bind(e)}function dt(e,t){throw new Error(`Failed to handle ${e} at ${t}`)}var pa={f:{1:m,2:M,3:de,4:B},h:{1:Le,2:Oe,3:Me,4:We},i:{1:C,2:ee,3:Fe,4:E},u:{1:P,2:te,3:Ie,4:G},b:{1:_,2:Ht,3:qt,4:Jt}},la={vec2f:M,vec2h:Oe,vec2i:ee,vec2u:te,"vec2<bool>":Ht,vec3f:de,vec3h:Me,vec3i:Fe,vec3u:Ie,"vec3<bool>":qt,vec4f:B,vec4h:We,vec4i:E,vec4u:G,"vec4<bool>":Jt,mat2x2f:ut,mat3x3f:pt,mat4x4f:lt},un={vec2f:m,vec2h:Le,vec2i:C,vec2u:P,"vec2<bool>":_,vec3f:m,vec3h:Le,vec3i:C,vec3u:P,"vec3<bool>":_,vec4f:m,vec4h:Le,vec4i:C,vec4u:P,"vec4<bool>":_,mat2x2f:M,mat3x3f:de,mat4x4f:B};function je(e,t){if(A(e)||K(e))return e.propTypes[t]??k;if(e===_||an(e))return k;let r=t.length;if(Y(e)&&r>=1&&r<=4){let n=e.type.includes("bool")?"b":e.type[4],a=pa[n][r];if(a)return a}return k}function Qt(e){return z(e)||ve(e)?e.elementType:e.type in un?un[e.type]:k}function Xt(e){if(/^0x[0-9a-f]+$/i.test(e))return T(e,De);if(/^0b[01]+$/i.test(e))return T(`${Number.parseInt(e.slice(2),2)}`,De);if(/^-?(?:\d+\.\d*|\d*\.\d+)$/i.test(e))return T(e,Kt);if(/^-?\d+(?:\.\d+)?e-?\d+$/i.test(e))return T(e,Kt);if(/^-?\d+$/i.test(e))return T(e,De)}var Zt={rank:Number.POSITIVE_INFINITY,action:"none"};function Ae(e){return e.type==="decorated"?e.inner:e}function pn(e){return Y(e)?nn[e.type]:void 0}function ft(e,t){let r=Ae(e),n=Ae(t);if(r.type===n.type)return{rank:0,action:"none"};if(r.type==="abstractFloat"){if(n.type==="f32")return{rank:1,action:"none"};if(n.type==="f16")return{rank:2,action:"none"}}if(r.type==="abstractInt"){if(n.type==="i32")return{rank:3,action:"none"};if(n.type==="u32")return{rank:4,action:"none"};if(n.type==="abstractFloat")return{rank:5,action:"none"};if(n.type==="f32")return{rank:6,action:"none"};if(n.type==="f16")return{rank:7,action:"none"}}if(Y(r)&&Y(n)){let a=pn(r),o=pn(n);if(a&&o)return ft(a,o)}return me(r)&&me(n)?{rank:0,action:"none"}:Zt}function ma(e,t){let r=Ae(e),n=Ae(t);if(r.type==="ptr"&&ft(r.inner,n).rank<Number.POSITIVE_INFINITY)return{rank:0,action:"deref"};if(n.type==="ptr"&&ft(r,n.inner).rank<Number.POSITIVE_INFINITY)return{rank:1,action:"ref"};let a={f32:0,f16:1,i32:2,u32:3,bool:4};if(r.type in a&&n.type in a){let o=r.type,i=n.type;if(o!==i){let s=a[o];return{rank:a[i]<s?10:20,action:"cast",targetType:n}}}return Zt}function da(e,t,r){let n=ft(e,t);return n.rank<Number.POSITIVE_INFINITY?n:r?ma(e,t):Zt}function ln(e,t,r){let n,a=Number.POSITIVE_INFINITY,o=new Map;for(let u of t){let d=0,g=[],c=!0;for(let y of e){let x=da(y,u,r);if(x.rank===Number.POSITIVE_INFINITY){c=!1;break}d+=x.rank,g.push(x)}c&&d<a&&(a=d,n=u,o.set(n,g))}if(!n)return;let s=o.get(n).map((u,d)=>({sourceIndex:d,action:u.action,...u.action==="cast"&&{targetType:u.targetType}})),l=s.some(u=>u.action==="cast");return{targetType:n,actions:s,hasImplicitConversions:l}}function er(e){return e.type==="abstractFloat"?m:e.type==="abstractInt"?C:e}function mn(e,t){if(e.length===0)return;let r=[...new Set(e.map(Ae))],n=t?[...new Set(t.map(Ae))]:r,a=ln(e,n,!1);if(a)return a;let o=ln(e,n,!0);if(o)return o.hasImplicitConversions=o.actions.some(i=>i.action==="cast"),o}function fa(e,t,r,n){if(r.action==="none")return T(t.value,n);let a=e.resolve(t.value);switch(r.action){case"ref":return T(`&${a}`,n);case"deref":return T(`*${a}`,n);case"cast":return T(`${e.resolve(n)}(${a})`,n);default:dt(r.action,"applyActionToSnippet")}}function W(e,t,r){let n=t.map(o=>o.dataType);if(n.some(o=>o===k))return;let a=mn(n,r);if(a)return a.hasImplicitConversions&&console.warn(`Implicit conversions from [ ${t.map(o=>` ${o.value}: ${o.dataType.type}`).join(`, `)} ] to ${a.targetType.type} are supported, but not recommended. Consider using explicit conversions instead.`),t.map((o,i)=>{let s=a.actions[i];return pe(s,"Action should not be undefined"),fa(e,o,s,a.targetType)})}function tr(e,t,r){return Object.keys(t.propTypes).map(a=>{let o=r[a];if(!o)throw new Error(`Missing property ${a}`);let i=t.propTypes[a];return W(e,[o],[i])?.[0]??o})}function fe(e){if(tn(e))return e;if(Hr(e))return T(e,e[S]);if(at(e)||Yr(e))return T(e,la[e.kind]);if(Array.isArray(e)){let t=e.map(fe).filter(Boolean),r=X();if(!r)throw new Error("Tried to coerce array without a context");let n=W(r,t),a=mn(t.map(o=>o.dataType))?.targetType;return!n||!a?T(e,k):T(n.map(o=>o.value).join(", "),st(er(a),e.length))}return typeof e=="string"||typeof e=="function"||typeof e=="object"||typeof e=="symbol"||typeof e>"u"||e===null?T(e,k):typeof e=="number"||typeof e=="bigint"?T(e,Xt(String(e))?.dataType??k):typeof e=="boolean"?T(e,_):T(e,k)}var q={get(e,t){if(t in e)return Reflect.get(e,t);if(t!=="~providing")return t==="toString"||t===Symbol.toStringTag||t===Symbol.toPrimitive?()=>e.toString():new Proxy({"~resolve":r=>`${r.resolve(e)}.${String(t)}`,toString:()=>`.value(...).${String(t)}:${p(e)??"<unnamed>"}`,[S]:je(e[S],String(t))},q)}};function ze(e,t){let r=t,n;for(;n=sn(r);)r=n(e);return r}function dn(e,t){return new rr(e,t)}var rr=class{constructor(t,r){this.dataType=t;this._value=r;this[f]={dataType:t}}[f];$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.resolveValue(this._value,this.dataType);return t.addDeclaration(`const ${r} = ${n};`),r}toString(){return`const:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.dataType},q)}get value(){return J()?this[I]():this._value}};function Be(e){return e?.resourceType==="slot"}function Re(e){return e?.resourceType==="derived"}function Ke(e){return e?.["~providing"]!==void 0}function He(e){return e?.resourceType==="accessor"}function nr(e){return typeof e?.["~resolve"]=="function"}function gt(e){return typeof e=="number"||typeof e=="boolean"||typeof e=="string"||nr(e)||be(e)||Be(e)||Re(e)||Ke(e)}function fn(e){return!!e&&typeof e=="object"&&"getMappedRange"in e&&"mapAsync"in e}function gn(e){return e?.resourceType==="buffer-usage"}function ar(e){return!!e?.[f]}function ge(e,t){for(let[r,n]of Object.entries(t))e[r]=n,j(n)&&p(n)===void 0&&n.$name(r)}function cn(e,t,r){let n=[...e.matchAll(/:\s*(?<arg>.*?)\s*[,)]/g)].map(a=>a?a[1]:void 0);r(Object.fromEntries(t.flatMap((a,o)=>{let i=n?n[o]:void 0;return A(a)&&i!==void 0?[[i,a]]:[]})))}function Pe(e,t,r){let n=e.match(/->\s(?<output>[\w\d_]+)\s{/),a=n?n[1]?.trim():void 0;A(t)&&a&&!/\s/g.test(a)&&r({[a]:t})}function ga(e){return new RegExp(`(?<![\\w\\$_.])${e.replaceAll(".","\\.").replaceAll("$","\\$")}(?![\\w\\$_])`,"g")}function ce(e,t,r){return Object.entries(t).reduce((n,[a,o])=>gt(o)||Se(o)?n.replaceAll(ga(a),e.resolve(o)):o!==null&&typeof o=="object"?([...r.matchAll(new RegExp(`${a.replaceAll(".","\\.").replaceAll("$","\\$")}\\.(?<prop>.*?)(?![\\w\\$_])`,"g"))].map(s=>s[1])??[]).reduce((s,l)=>l&&l in o?ce(e,{[`${a}.${l}`]:o[l]},s):s,n):n,r)}function yn(e){return new or(e)}var or=class{constructor(t){this.declaration=t}externalsToApply=[];$uses(t){return this.externalsToApply.push(t),this}"~resolve"(t){let r={};for(let a of this.externalsToApply)ge(r,a);let n=ce(t,r,this.declaration);return t.addDeclaration(n),""}toString(){return`declare: ${this.declaration}`}};var Tn=new WeakMap;function xn(e){return Tn.get(e)}function hn(e,t,r){return Tn.set(e,{ast:t,externals:r}),e}function wn(e){return()=>{throw new Error(`The function "${e??"<unnamed>"}" is invokable only on the GPU. If you want to use it on the CPU, mark it with the "kernel & js" directive.`)}}import{FuncParameterType as bn}from"tinyest";function re(e,t){let r=[];typeof t=="string"&&(e.isEntry?(A(e.argTypes[0])&&r.push({In:e.argTypes[0]}),A(e.returnType)&&r.push({Out:e.returnType})):(cn(t,e.argTypes,o=>r.push(o)),Pe(t,e.returnType,o=>r.push(o))));let n={applyExternals(o){r.push(o)},resolve(o,i=""){let s={};for(let u of r)ge(s,u);let l=o.names.makeUnique(p(this));if(typeof t=="string"){let u="";if(e.isEntry){let g=A(e.argTypes[0])?"(in: In)":"()",c=be(e.returnType)?Ue(e.returnType):"",y=e.returnType!==we?A(e.returnType)?"-> Out":`-> ${c!==""?c:"@location(0)"} ${o.resolve(e.returnType)}`:"";u=`${g} ${y} `}let d=ce(o,s,`${u}${t.trim()}`);o.addDeclaration(`${i}fn ${l}${d}`)}else{let u=xn(t);if(u?.externals){let x=Object.fromEntries(Object.entries(u.externals).filter(([w])=>!(w in s)));ge(s,x)}let d=u?.ast??o.transpileFn(String(t)),g=d.externalNames.filter(x=>!(x in s));if(g.length>0)throw new Ot(p(this),g);let{head:c,body:y}=o.fnToWgsl({args:e.argTypes.map((x,w)=>T(d.params[w]?.type===bn.identifier?d.params[w].name:`_arg_${w}`,x)),argAliases:Object.fromEntries(d.params.flatMap((x,w)=>x.type===bn.destructuredObject?x.props.map(({name:b,alias:U})=>[U,T(`_arg_${w}.${b}`,e.argTypes[w].propTypes[b])]):[])),returnType:e.returnType,body:d.body,externalMap:s});o.addDeclaration(`${i}fn ${l}${o.resolve(c)}${o.resolve(y)}`)}return l}},a=p(t);return a!==void 0&&h(n,a),n}function ca(e){let t=0;return Object.fromEntries(Object.entries(e).map(([r,n])=>{if(mt(n))return[r,n];let a=Z(n);return a!==void 0?(t=a+1,[r,n]):[r,Yt(t++,n)]}))}function ne(e){return O(e)?it(e)||Z(e)!==void 0?e:Yt(0,e):on(ca(e))}function ae(e,...t){return ya(e)?Ta(e,...t):e}function ya(e){return Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw)&&e.raw.every(t=>typeof t=="string")}function Ta(e,...t){return e.slice(1).reduce((r,n,a)=>`${r}${t[a]}${n}`,e[0])}function Sn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[ne(e.in)]:[],returnType:we,workgroupSize:[e.workgroupSize[0]??1,e.workgroupSize[1]??1,e.workgroupSize[2]??1],isEntry:!0},r=(n,...a)=>xa(t,e.workgroupSize,ae(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function xa(e,t,r){let n=re(e,r),a=e.argTypes[0];return{shell:e,$uses(o){return n.applyExternals(o),this},[D]:n,$name(o){return h(n,o),j(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){return n.resolve(o,`@compute @workgroup_size(${t.join(", ")}) `)},toString(){return`computeFn:${p(n)??"<unnamed>"}`}}}function vn(e,t){let r={[f]:!0,argTypes:e,returnType:t??we,isEntry:!1},n=(a,...o)=>wa(r,ae(a,...o));return Object.assign(Object.assign(n,r),{does:n})}function ir(e){return!!e?.[f]&&e?.resourceType==="function"}function ha([e,t]){return`${p(e)??"<unnamed>"}=${t}`}function wa(e,t){let r=re(e,t),n={[f]:{implementation:t,argTypes:e.argTypes},shell:e,resourceType:"function",$uses(i){return r.applyExternals(i),this},[D]:r,$name(i){return h(r,i),this},with(i,s){return Dn(o,[[He(i)?i.slot:i,s]])},"~resolve"(i){if(typeof t=="string")return r.resolve(i);let s=i;if(s.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return s.callStack.push(e.returnType),r.resolve(i)}finally{s.callStack.pop()}}},a=zt((...i)=>{if(typeof t=="string")throw new Error("Cannot execute on the CPU functions constructed with raw WGSL");return t(...i)},(...i)=>T(new ct(o,i.map(s=>s.value)),e.returnType??k),e.argTypes);a[f].implementation=t;let o=Object.assign(a,n);return Object.defineProperty(o,"toString",{value(){return`fn:${p(r)??"<unnamed>"}`}}),o}function Dn(e,t){let r={[f]:{implementation:e[f].implementation,argTypes:e[f].argTypes},resourceType:"function",shell:e.shell,"~providing":{inner:e,pairs:t},$uses(o){return e.$uses(o),this},[D]:e,$name(o){return e.$name(o),this},with(o,i){return Dn(a,[...t,[He(o)?o.slot:o,i]])}},n=zt((...o)=>e(...o),(...o)=>T(new ct(a,o.map(i=>i.value)),e.shell.returnType??k),e.shell.argTypes),a=Object.assign(n,r);return Object.defineProperty(a,"toString",{value(){return`fn:${p(e)??"<unnamed>"}[${t.map(ha).join(", ")}]`}}),a[f].implementation=e[f].implementation,a}var ct=class{constructor(t,r){this._fn=t;this._params=r;this[D]=t}[D];"~resolve"(t){return t.resolve(`${t.resolve(this._fn)}(${this._params.map(r=>t.resolve(r)).join(", ")})`)}toString(){return`call:${p(this)??"<unnamed>"}`}};function Fn(e){let t={argTypes:e.in&&Object.keys(e.in).length!==0?[ne(e.in)]:[],targets:e.out,returnType:ne(e.out),isEntry:!0},r=(n,...a)=>ba(t,ae(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function ba(e,t){let r=re(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&Pe(t,n,i=>r.applyExternals(i)),{shell:e,outputType:n,$uses(i){return r.applyExternals(i),this},[D]:r,$name(i){return h(r,i),j(n)&&n.$name(`${i}_Output`),j(a)&&a.$name(`${i}_Input`),this},"~resolve"(i){if(typeof t=="string")return r.resolve(i,"@fragment ");let s=i;if(s.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return s.callStack.push(n),r.resolve(i,"@fragment ")}finally{s.callStack.pop()}},toString(){return`fragmentFn:${p(r)??"<unnamed>"}`}}}function In(e){let t={attributes:[e.in??{}],returnType:Object.keys(e.out).length!==0?ne(e.out):void 0,argTypes:e.in&&Object.keys(e.in).length!==0?[ne(e.in)]:[],isEntry:!0},r=(n,...a)=>Sa(t,ae(n,...a));return Object.assign(Object.assign(r,t),{does:r})}function Sa(e,t){let r=re(e,t),n=e.returnType,a=e.argTypes[0];return typeof t=="string"&&Pe(t,n,o=>r.applyExternals(o)),{shell:e,outputType:n,inputType:a,$uses(o){return r.applyExternals(o),this},[D]:r,$name(o){return h(r,o),j(n)&&n.$name(`${o}_Output`),j(a)&&a.$name(`${o}_Input`),this},"~resolve"(o){if(typeof t=="string")return r.resolve(o,"@vertex ");let i=o;if(i.callStack===void 0)throw new Error("Cannot resolve a TGSL function outside of a generation context");try{return i.callStack.push(n),r.resolve(o,"@vertex ")}finally{i.callStack.pop()}},toString(){return`vertexFn:${p(r)??"<unnamed>"}`}}}var oe=class{lastUniqueId=0;makeUnique(t){let r;return t?(r=t.replaceAll(/\s/g,"_"),r=r.replaceAll(/[^\w\d]/g,"")):r="item",`${r}_${this.lastUniqueId++}`}},ie=class{_usedNames=new Set;makeUnique(t){if(t===void 0)throw new Error("Unnamed item found when using a strict name registry");let r=0,n=t;for(;this._usedNames.has(n);)r++,n=`${t}_${r}`;return this._usedNames.add(n),n}};function qe(e){return typeof e?.format=="string"}function Un(e,t){let r=[];if(O(e)){if(!qe(t))throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");return r.push(t._layout),{usedVertexLayouts:r,bufferDefinitions:[{arrayStride:t._layout.stride,stepMode:t._layout.stepMode,attributes:[{format:t.format,offset:t.offset,shaderLocation:Z(e)??0}]}]}}let n=[],a=new WeakMap,o=0;for(let[i,s]of Object.entries(e)){if(mt(s))continue;let l=t[i];if(!l)throw new Error(`An attribute by the name of '${i}' was not provided to the shader.`);let u=l._layout,d=a.get(u);d||(r.push(u),d=[],n.push({arrayStride:u.stride,stepMode:u.stepMode,attributes:d}),a.set(u,d)),o=Z(s)??o,d.push({format:l.format,offset:l.offset,shaderLocation:o++})}return{usedVertexLayouts:r,bufferDefinitions:n}}var va=["bool","f32","f16","i32","u32","vec2f","vec3f","vec4f","vec2h","vec3h","vec4h","vec2i","vec3i","vec4i","vec2u","vec3u","vec4u","vec2<bool>","vec3<bool>","vec4<bool>","mat2x2f","mat3x3f","mat4x4f"];function Da(e){return va.includes(e.type)}function sr(e,[t,r]){return` ${Ue(r)}${t}: ${e.resolve(r)}, `}function Fa(e,t){let r=e.names.makeUnique(p(t));return e.addDeclaration(` struct ${r} { ${Object.entries(t.propTypes).map(n=>sr(e,n)).join("")}} `),r}function Ia(e,t){let r=e.names.makeUnique(p(t));return e.addDeclaration(` struct ${r} { ${Object.entries(t.propTypes).map(n=>qe(n[1])?sr(e,[n[0],Ne[n[1].format]]):sr(e,n)).join("")} } `),r}function Ua(e,t){let r=e.resolve(t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function Aa(e,t){let r=e.resolve(qe(t.elementType)?Ne[t.elementType.format]:t.elementType);return t.elementCount===0?`array<${r}>`:`array<${r}, ${t.elementCount}>`}function ur(e,t){if(Se(t))return t.type==="unstruct"?Ia(e,t):t.type==="disarray"?Aa(e,t):t.type==="loose-decorated"?e.resolve(qe(t.inner)?Ne[t.inner.format]:t.inner):e.resolve(Ne[t.type]);if(Da(t))return t.type;if(t.type==="struct")return Fa(e,t);if(t.type==="array")return Ua(e,t);if(t.type==="atomic")return`atomic<${ur(e,t.inner)}>`;if(t.type==="decorated")return e.resolve(t.inner);if(t.type==="ptr")return t.addressSpace==="storage"?`ptr<storage, ${e.resolve(t.inner)}, ${t.access==="read-write"?"read_write":t.access}>`:`ptr<${t.addressSpace}, ${e.resolve(t.inner)}>`;if(t.type==="abstractInt"||t.type==="abstractFloat")throw new Error("Abstract types have no concrete representation in WGSL");if(t.type==="void")throw new Error("Void has no representation in WGSL");dt(t,"resolveData")}import{BufferReader as cr,BufferWriter as yr,getSystemEndianness as Va}from"typed-binary";import{Measurer as Ra}from"typed-binary";function Ba(e,t){let r="size"in e?e.size:e.currentByteOffset,n=t-1,a=r&n;"skipBytes"in e?e.skipBytes(t-a&n):e.add(t-a&n)}var R=Ba;var An=new WeakMap;function yt(e){let t=An.get(e);if(t)return t;let r=new Ra,n={},a;for(let o in e.propTypes){let i=e.propTypes[o];if(i===void 0)throw new Error(`Property ${o} is undefined in struct`);let s=r.size;R(r,K(e)?H(i):V(i)),a&&(a.padding=r.size-s);let l=v(i);n[o]={offset:r.size,size:l},a=n[o],r.add(l)}return a&&(a.padding=L(v(e),V(e))-r.size),An.set(e,n),n}var xt=(()=>{try{return new Function("return true"),!0}catch{return!1}})(),pr=new WeakMap,lr={u32:"u32",vec2u:"u32",vec3u:"u32",vec4u:"u32",i32:"i32",vec2i:"i32",vec3i:"i32",vec4i:"i32",f32:"f32",vec2f:"f32",vec3f:"f32",vec4f:"f32",vec2h:"f32",vec3h:"f32",vec4h:"f32",mat2x2f:"f32",mat3x3f:"f32",mat4x4f:"f32"},mr={u32:"setUint32",i32:"setInt32",f32:"setFloat32"};function Tt(e,t,r){if(Zr(e)||ot(e))return Tt(e.inner,t,r);if(A(e)||K(e)){let a=yt(e),o=Object.entries(a).sort((s,l)=>s[1].offset-l[1].offset),i="";for(let[s,l]of o){let u=e.propTypes[s];u&&(i+=Tt(u,`(${t} + ${l.offset})`,`${r}.${s}`))}return i}if(z(e)||ve(e)){let a=e,o=L(v(a.elementType),V(a.elementType)),i="";return i+=`for (let i = 0; i < ${a.elementCount}; i++) { `,i+=Tt(a.elementType,`(${t} + i * ${o})`,`${r}[i]`),i+=`} `,i}if(Y(e)){let a=lr[e.type],o="",i=mr[a],s=["x","y","z","w"],l=qr(e)?2:Jr(e)?3:4;for(let u=0;u<l;u++)o+=`output.${i}((${t} + ${u*4}), ${r}.${s[u]}, littleEndian); `;return o}if(me(e)){let a=lr[e.type],o=mr[a],i=Qr(e)?2:Xr(e)?3:4,s=i*i,l=L(i*4,8),u="";for(let d=0;d<s;d++){let g=Math.floor(d/i),c=d%i,y=g*l+c*4;u+=`output.${o}((${t} + ${y}), ${r}.columns[${g}].${["x","y","z","w"][c]}, littleEndian); `}return u}let n=lr[e.type];return`output.${mr[n]}(${t}, ${r}, littleEndian); `}function ht(e){if(pr.has(e))return pr.get(e);let t=Tt(e,"offset","value"),r=new Function("output","offset","value","littleEndian=true",t);return pr.set(e,r),r}var Ce={bool(){throw new Error("Booleans are not host-shareable")},f32(e,t,r){e.writeFloat32(r)},f16(e,t,r){e.writeFloat16(r)},i32(e,t,r){e.writeInt32(r)},u32(e,t,r){e.writeUint32(r)},vec2f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},vec2h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},vec2i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},vec2u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},"vec2<bool>"(){throw new Error("Booleans are not host-shareable")},vec3f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},vec3h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z)},vec3i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},vec3u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},"vec3<bool>"(){throw new Error("Booleans are not host-shareable")},vec4f(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},vec4h(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},vec4i(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},vec4u(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},"vec4<bool>"(){throw new Error("Booleans are not host-shareable")},mat2x2f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat3x3f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},mat4x4f(e,t,r){for(let n=0;n<r.length;++n)e.writeFloat32(r[n])},struct(e,t,r){let n=V(t);R(e,n);for(let[a,o]of Object.entries(t.propTypes))R(e,V(o)),se(e,o,r[a]);R(e,n)},array(e,t,r){if(t.elementCount===0)throw new Error("Cannot write using a runtime-sized schema.");let n=V(t);R(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)R(e,n),se(e,t.elementType,r[o]);e.seekTo(a+v(t))},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t,r){Ce[t.inner.type]?.(e,t,r)},decorated(e,t,r){let n=H(t);R(e,n);let a=e.currentByteOffset;Ce[t.inner?.type]?.(e,t.inner,r),e.seekTo(a+v(t))},uint8(e,t,r){e.writeUint8(r)},uint8x2(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y)},uint8x4(e,t,r){e.writeUint8(r.x),e.writeUint8(r.y),e.writeUint8(r.z),e.writeUint8(r.w)},sint8(e,t,r){e.writeInt8(r)},sint8x2(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y)},sint8x4(e,t,r){e.writeInt8(r.x),e.writeInt8(r.y),e.writeInt8(r.z),e.writeInt8(r.w)},unorm8(e,t,r){e.writeUint8(r*255)},unorm8x2(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255)},unorm8x4(e,t,r){e.writeUint8(r.x*255),e.writeUint8(r.y*255),e.writeUint8(r.z*255),e.writeUint8(r.w*255)},snorm8(e,t,r){e.writeUint8(r*127+128)},snorm8x2(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128)},snorm8x4(e,t,r){e.writeUint8(r.x*127+128),e.writeUint8(r.y*127+128),e.writeUint8(r.z*127+128),e.writeUint8(r.w*127+128)},uint16(e,t,r){e.writeUint16(r)},uint16x2(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y)},uint16x4(e,t,r){e.writeUint16(r.x),e.writeUint16(r.y),e.writeUint16(r.z),e.writeUint16(r.w)},sint16(e,t,r){e.writeInt16(r)},sint16x2(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y)},sint16x4(e,t,r){e.writeInt16(r.x),e.writeInt16(r.y),e.writeInt16(r.z),e.writeInt16(r.w)},unorm16(e,t,r){e.writeUint16(r*65535)},unorm16x2(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535)},unorm16x4(e,t,r){e.writeUint16(r.x*65535),e.writeUint16(r.y*65535),e.writeUint16(r.z*65535),e.writeUint16(r.w*65535)},snorm16(e,t,r){e.writeUint16(r*32767+32768)},snorm16x2(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768)},snorm16x4(e,t,r){e.writeUint16(r.x*32767+32768),e.writeUint16(r.y*32767+32768),e.writeUint16(r.z*32767+32768),e.writeUint16(r.w*32767+32768)},float16(e,t,r){e.writeFloat16(r)},float16x2(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y)},float16x4(e,t,r){e.writeFloat16(r.x),e.writeFloat16(r.y),e.writeFloat16(r.z),e.writeFloat16(r.w)},float32(e,t,r){e.writeFloat32(r)},float32x2(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y)},float32x3(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z)},float32x4(e,t,r){e.writeFloat32(r.x),e.writeFloat32(r.y),e.writeFloat32(r.z),e.writeFloat32(r.w)},uint32(e,t,r){e.writeUint32(r)},uint32x2(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y)},uint32x3(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z)},uint32x4(e,t,r){e.writeUint32(r.x),e.writeUint32(r.y),e.writeUint32(r.z),e.writeUint32(r.w)},sint32(e,t,r){e.writeInt32(r)},sint32x2(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y)},sint32x3(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z)},sint32x4(e,t,r){e.writeInt32(r.x),e.writeInt32(r.y),e.writeInt32(r.z),e.writeInt32(r.w)},"unorm10-10-10-2"(e,t,r){let n=0;n|=(r.x*1023&1023)<<22,n|=(r.x*1023&1023)<<12,n|=(r.y*1023&1023)<<2,n|=r.z*3&3,e.writeUint32(n)},"unorm8x4-bgra"(e,t,r){e.writeUint8(r.z*255),e.writeUint8(r.y*255),e.writeUint8(r.x*255),e.writeUint8(r.w*255)},disarray(e,t,r){let n=V(t);R(e,n);let a=e.currentByteOffset;for(let o=0;o<Math.min(t.elementCount,r.length);o++)R(e,n),Ce[t.elementType?.type]?.(e,t.elementType,r[o]);e.seekTo(a+v(t))},unstruct(e,t,r){for(let[n,a]of Object.entries(t.propTypes))Ce[a.type]?.(e,a,r[n])},"loose-decorated"(e,t,r){let n=H(t);R(e,n);let a=e.currentByteOffset,o=Ce[t.inner?.type];return o?.(e,t.inner,r),e.seekTo(a+v(t)),r}};function se(e,t,r){let n=Ce[t.type];if(!n)throw new Error(`Cannot write data of type '${t.type}'.`);n(e,t,r)}var ye={bool(){throw new Error("Booleans are not host-shareable")},f32(e){return e.readFloat32()},f16(e){return e.readFloat16()},i32(e){return e.readInt32()},u32(e){return e.readUint32()},vec2f(e){return M(e.readFloat32(),e.readFloat32())},vec3f(e){return de(e.readFloat32(),e.readFloat32(),e.readFloat32())},vec4f(e){return B(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},vec2h(e){return Oe(e.readFloat16(),e.readFloat16())},vec3h(e){return Me(e.readFloat16(),e.readFloat16(),e.readFloat16())},vec4h(e){return We(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16())},vec2i(e){return ee(e.readInt32(),e.readInt32())},vec3i(e){return Fe(e.readInt32(),e.readInt32(),e.readInt32())},vec4i(e){return E(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32())},vec2u(e){return te(e.readUint32(),e.readUint32())},vec3u(e){return Ie(e.readUint32(),e.readUint32(),e.readUint32())},vec4u(e){return G(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32())},"vec2<bool>"(){throw new Error("Booleans are not host-shareable")},"vec3<bool>"(){throw new Error("Booleans are not host-shareable")},"vec4<bool>"(){throw new Error("Booleans are not host-shareable")},mat2x2f(e){return ut(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},mat3x3f(e){let t=()=>{let r=e.readFloat32();return e.readFloat32(),r};return pt(e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t(),e.readFloat32(),e.readFloat32(),t())},mat4x4f(e){return lt(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32())},struct(e,t){let r=V(t);R(e,r);let n={};for(let[a,o]of Object.entries(t.propTypes))R(e,V(o)),n[a]=N(e,o);return R(e,r),n},array(e,t){if(t.elementCount===0)throw new Error("Cannot read using a runtime-sized schema.");let r=V(t),n=[];for(let a=0;a<t.elementCount;a++){R(e,r);let o=t.elementType,i=N(e,o);n.push(i)}return R(e,r),n},ptr(){throw new Error("Pointers are not host-shareable")},atomic(e,t){return N(e,t.inner)},decorated(e,t){let r=H(t);R(e,r);let n=e.currentByteOffset,a=N(e,t.inner);return e.seekTo(n+v(t)),a},uint8:e=>e.readUint8(),uint8x2:e=>te(e.readUint8(),e.readUint8()),uint8x4:e=>G(e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8()),sint8:e=>e.readInt8(),sint8x2:e=>ee(e.readInt8(),e.readInt8()),sint8x4:e=>E(e.readInt8(),e.readInt8(),e.readInt8(),e.readInt8()),unorm8:e=>e.readUint8()/255,unorm8x2:e=>M(e.readUint8()/255,e.readUint8()/255),unorm8x4:e=>B(e.readUint8()/255,e.readUint8()/255,e.readUint8()/255,e.readUint8()/255),snorm8:e=>(e.readUint8()-128)/127,snorm8x2:e=>M((e.readUint8()-128)/127,(e.readUint8()-128)/127),snorm8x4:e=>B((e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127,(e.readUint8()-128)/127),uint16:e=>e.readUint16(),uint16x2:e=>te(e.readUint16(),e.readUint16()),uint16x4:e=>G(e.readUint16(),e.readUint16(),e.readUint16(),e.readUint16()),sint16:e=>e.readInt16(),sint16x2:e=>ee(e.readInt16(),e.readInt16()),sint16x4:e=>E(e.readInt16(),e.readInt16(),e.readInt16(),e.readInt16()),unorm16:e=>e.readUint16()/65535,unorm16x2:e=>M(e.readUint16()/65535,e.readUint16()/65535),unorm16x4:e=>B(e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535,e.readUint16()/65535),snorm16:e=>(e.readUint16()-32768)/32767,snorm16x2:e=>M(ye.snorm16(e),ye.snorm16(e)),snorm16x4:e=>B(ye.snorm16(e),ye.snorm16(e),ye.snorm16(e),ye.snorm16(e)),float16(e){return e.readFloat16()},float16x2:e=>M(e.readFloat16(),e.readFloat16()),float16x4:e=>B(e.readFloat16(),e.readFloat16(),e.readFloat16(),e.readFloat16()),float32:e=>e.readFloat32(),float32x2:e=>M(e.readFloat32(),e.readFloat32()),float32x3:e=>de(e.readFloat32(),e.readFloat32(),e.readFloat32()),float32x4:e=>B(e.readFloat32(),e.readFloat32(),e.readFloat32(),e.readFloat32()),uint32:e=>e.readUint32(),uint32x2:e=>te(e.readUint32(),e.readUint32()),uint32x3:e=>Ie(e.readUint32(),e.readUint32(),e.readUint32()),uint32x4:e=>G(e.readUint32(),e.readUint32(),e.readUint32(),e.readUint32()),sint32:e=>e.readInt32(),sint32x2:e=>ee(e.readInt32(),e.readInt32()),sint32x3:e=>Fe(e.readInt32(),e.readInt32(),e.readInt32()),sint32x4:e=>E(e.readInt32(),e.readInt32(),e.readInt32(),e.readInt32()),"unorm10-10-10-2"(e){let t=e.readUint32(),r=(t>>22)/1023,n=(t>>12&1023)/1023,a=(t>>2&1023)/1023,o=(t&3)/3;return B(r,n,a,o)},"unorm8x4-bgra"(e){let t=e.readByte()/255,r=e.readByte()/255,n=e.readByte()/255,a=e.readByte()/255;return B(n,r,t,a)},unstruct(e,t){let r={};for(let[n,a]of Object.entries(t.propTypes))r[n]=N(e,a);return r},disarray(e,t){let r=V(t),n=[];for(let a=0;a<t.elementCount;a++)R(e,r),n.push(N(e,t.elementType));return R(e,r),n},"loose-decorated"(e,t){R(e,H(t));let r=e.currentByteOffset,n=N(e,t.inner);return e.seekTo(r+v(t)),n}};function N(e,t){let r=ye[t.type];if(!r)throw new Error(`Cannot read data of type '${t.type}'.`);return r(e,t)}import{BufferWriter as Ca}from"typed-binary";function Bn(e,t){let r=v(e);if(r===0||t===void 0||t===null)return[];let n=new ArrayBuffer(r),a=new Ca(n),o=[];function i(u,d,g,c){if(d!=null){if(A(u)||K(u)){let y=yt(u);for(let[x,w]of Object.entries(y)){let b=u.propTypes[x];if(!b)continue;let U=d[x];U!==void 0&&i(b,U,g+w.offset,w.padding??c)}return}if(z(u)||ve(u)){let y=u,x=L(v(y.elementType),V(y.elementType));if(!Array.isArray(d))throw new Error("Partial value for array must be an array");let w=d??[];w.sort((b,U)=>b.idx-U.idx);for(let{idx:b,value:U}of w)i(y.elementType,U,g+b*x,x-v(y.elementType))}else{let y=v(u);a.seekTo(g),se(a,u,d),o.push({start:g,end:g+y,padding:c})}}}if(i(e,t,0),o.length===0)return[];let s=[],l=o[0];for(let u=1;u<o.length;u++){let d=o[u];if(!d||!l)throw new Error("Internal error: missing segment");d.start===l.end+(l.padding??0)?(l.end=d.end,l.padding=d.padding):(s.push({data:new Uint8Array(n,l.start,l.end-l.start)}),l=d)}if(!l)throw new Error("Internal error: missing segment");return s.push({data:new Uint8Array(n,l.start,l.end-l.start)}),s}function Te(e){return!!e?.usableAsStorage}var Je=class e extends Error{constructor(t){super(`Resource '${p(t)??"<unnamed>"}' cannot be bound as 'storage'. Use .$usage('storage') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function wt(e){return!!e.usableAsUniform}var Vn={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Ye=class{constructor(t,r){this.usage=t;this.buffer=r;this[f]={dataType:r.dataType},this[D]=r}resourceType="buffer-usage";[f];[D];$name(t){return this.buffer.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry(this.usage==="uniform"?{uniform:this.buffer.dataType}:{storage:this.buffer.dataType,access:this.usage},this.buffer),o=Vn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${a}) var<${o}> ${r}: ${t.resolve(this.buffer.dataType)};`),r}write(t){this.buffer.write(t)}toString(){return`${this.usage}:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.buffer.dataType},q)}get value(){if(!J())throw new Error("Cannot access buffer's value directly in JS.");return this[I]()}},Qe=class{constructor(t,r,n){this.usage=t;this.dataType=r;this._membership=n;this[f]={dataType:r},h(this,n.key)}resourceType="buffer-usage";[f];"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=Vn[this.usage];return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var<${a}> ${r}: ${t.resolve(this.dataType)};`),r}toString(){return`${this.usage}:${p(this)??"<unnamed>"}`}[I](){return new Proxy({"~resolve":t=>t.resolve(this),toString:()=>`.value:${p(this)??"<unnamed>"}`,[S]:this.dataType},q)}get value(){if(!J())throw new Error("Cannot access buffer's value directly in JS.");return this[I]()}},Rn=new WeakMap;function dr(e){if(!Te(e))throw new Error(`Cannot pass ${e} to asMutable, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Rn.get(e);return t||(t=new Ye("mutable",e),Rn.set(e,t)),t}var Pn=new WeakMap;function fr(e){if(!Te(e))throw new Error(`Cannot pass ${e} to asReadonly, as it is not allowed to be used as storage. To allow it, call .$usage('storage') when creating the buffer.`);let t=Pn.get(e);return t||(t=new Ye("readonly",e),Pn.set(e,t)),t}var Cn=new WeakMap;function gr(e){if(!wt(e))throw new Error(`Cannot pass ${e} to asUniform, as it is not allowed to be used as a uniform. To allow it, call .$usage('uniform') when creating the buffer.`);let t=Cn.get(e);return t||(t=new Ye("uniform",e),Cn.set(e,t)),t}var $a={uniform:gr,mutable:dr,readonly:fr};function kn(e,t,r){return be(t)?new bt(e,t,r):new bt(e,t,r,["storage","uniform"])}function ue(e){return e.resourceType==="buffer"}function ka(e){return!!e.usableAsVertex}var $n=Va(),bt=class{constructor(t,r,n,a){this._group=t;this.dataType=r;this.initialOrBuffer=n;this._disallowedUsages=a;fn(n)?(this._ownBuffer=!1,this._buffer=n):(this._ownBuffer=!0,this.initial=n)}resourceType="buffer";flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC;_buffer=null;_ownBuffer;_destroyed=!1;_hostBuffer;initial;usableAsUniform=!1;usableAsStorage=!1;usableAsVertex=!1;get buffer(){let t=this._group.device;if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=t.createBuffer({size:v(this.dataType),usage:this.flags,mappedAtCreation:!!this.initial,label:p(this)??"<unnamed>"}),this.initial)){let r=new yr(this._buffer.getMappedRange());se(r,this.dataType,this.initial),this._buffer.unmap()}return this._buffer}get destroyed(){return this._destroyed}$name(t){return h(this,t),this._buffer&&(this._buffer.label=t),this}$usage(...t){for(let r of t){if(this._disallowedUsages?.includes(r))throw new Error(`Buffer of type ${this.dataType.type} cannot be used as ${r}`);this.flags|=r==="uniform"?GPUBufferUsage.UNIFORM:0,this.flags|=r==="storage"?GPUBufferUsage.STORAGE:0,this.flags|=r==="vertex"?GPUBufferUsage.VERTEX:0,this.usableAsUniform=this.usableAsUniform||r==="uniform",this.usableAsStorage=this.usableAsStorage||r==="storage",this.usableAsVertex=this.usableAsVertex||r==="vertex"}return this}$addFlags(t){if(!this._ownBuffer)throw new Error("Cannot add flags to a buffer that is not managed by TypeGPU.");return t&GPUBufferUsage.MAP_READ?(this.flags=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this):t&GPUBufferUsage.MAP_WRITE?(this.flags=GPUBufferUsage.COPY_SRC|GPUBufferUsage.MAP_WRITE,this):(this.flags|=t,this)}compileWriter(){if(xt)ht(this.dataType);else throw new Error("This environment does not allow eval")}write(t){let r=this.buffer,n=this._group.device;if(r.mapState==="mapped"){let o=r.getMappedRange();if(xt){ht(this.dataType)(new DataView(o),0,t,$n==="little");return}se(new yr(o),this.dataType,t);return}let a=v(this.dataType);this._hostBuffer||(this._hostBuffer=new ArrayBuffer(a)),this._group.flush(),xt?ht(this.dataType)(new DataView(this._hostBuffer),0,t,$n==="little"):se(new yr(this._hostBuffer),this.dataType,t),n.queue.writeBuffer(r,0,this._hostBuffer,0,a)}writePartial(t){let r=this.buffer,n=this._group.device,a=Bn(this.dataType,t);if(r.mapState==="mapped"){let o=r.getMappedRange(),i=new Uint8Array(o);for(let s of a)i.set(s.data,s.data.byteOffset)}else for(let o of a)n.queue.writeBuffer(r,o.data.byteOffset,o.data,0,o.data.byteLength)}copyFrom(t){if(this.buffer.mapState==="mapped")throw new Error("Cannot copy to a mapped buffer.");let r=v(this.dataType);this._group.commandEncoder.copyBufferToBuffer(t.buffer,0,this.buffer,0,r)}async read(){this._group.flush();let t=this.buffer,r=this._group.device;if(t.mapState==="mapped"){let i=t.getMappedRange();return N(new cr(i),this.dataType)}if(t.usage&GPUBufferUsage.MAP_READ){await t.mapAsync(GPUMapMode.READ);let i=t.getMappedRange(),s=N(new cr(i),this.dataType);return t.unmap(),s}let n=r.createBuffer({size:v(this.dataType),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(t,0,n,0,v(this.dataType)),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,v(this.dataType));let o=N(new cr(n.getMappedRange()),this.dataType);return n.unmap(),n.destroy(),o}as(t){return $a[t]?.(this)}destroy(){this._destroyed||(this._destroyed=!0,this._ownBuffer&&this._buffer?.destroy())}toString(){return`buffer:${p(this)??"<unnamed>"}`}};function _n(e){return new Tr(e)}function En(e){return new xr(e)}function Xe(e){let t=e;return t?.resourceType==="sampler"&&!!t[f]}function Ze(e){let t=e;return t?.resourceType==="sampler-comparison"&&!!t[f]}var St=class{constructor(t){this._membership=t;this[S]=this,this[f]={},h(this,t.key)}[S];[f];resourceType="sampler";"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},vt=class{constructor(t){this._membership=t;this[S]=this,this[f]={},h(this,t.key)}[S];[f];resourceType="sampler-comparison";"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: sampler_comparison;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},Tr=class{constructor(t){this._props=t;this[S]=this,this[f]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:p(this)??"<unnamed>"})),this._sampler)},this._filtering=t.minFilter==="linear"||t.magFilter==="linear"||t.mipmapFilter==="linear"}[S];[f];resourceType="sampler";_filtering;_sampler=null;$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry({sampler:this._filtering?"filtering":"non-filtering"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},xr=class{constructor(t){this._props=t;this[S]=this,this[f]={unwrap:r=>(this._sampler||(this._sampler=r.device.createSampler({...this._props,label:p(this)??"<unnamed>"})),this._sampler)}}[S];[f];resourceType="sampler-comparison";_sampler=null;$name(t){return h(this,t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry({sampler:"comparison"},this);return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: sampler_comparison;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}};var Dt=class{constructor(t){this._membership=t;h(this,t.key)}resourceType="external-texture";"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout);return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: texture_external;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}};var Gn={r8unorm:m,r8snorm:m,r8uint:P,r8sint:C,r16uint:P,r16sint:C,r16float:m,rg8unorm:m,rg8snorm:m,rg8uint:P,rg8sint:C,r32uint:P,r32sint:C,r32float:m,rg16uint:P,rg16sint:C,rg16float:m,rgba8unorm:m,"rgba8unorm-srgb":m,rgba8snorm:m,rgba8uint:P,rgba8sint:C,bgra8unorm:m,"bgra8unorm-srgb":m,rgb9e5ufloat:m,rgb10a2uint:P,rgb10a2unorm:m,rg11b10ufloat:m,rg32uint:P,rg32sint:C,rg32float:m,rgba16uint:P,rgba16sint:C,rgba16float:m,rgba32uint:P,rgba32sint:C,rgba32float:m,stencil8:m,depth16unorm:m,depth24plus:m,"depth24plus-stencil8":m,depth32float:m,"depth32float-stencil8":m,"bc1-rgba-unorm":m,"bc1-rgba-unorm-srgb":m,"bc2-rgba-unorm":m,"bc2-rgba-unorm-srgb":m,"bc3-rgba-unorm":m,"bc3-rgba-unorm-srgb":m,"bc4-r-unorm":m,"bc4-r-snorm":m,"bc5-rg-unorm":m,"bc5-rg-snorm":m,"bc6h-rgb-ufloat":m,"bc6h-rgb-float":m,"bc7-rgba-unorm":m,"bc7-rgba-unorm-srgb":m,"etc2-rgb8unorm":m,"etc2-rgb8unorm-srgb":m,"etc2-rgb8a1unorm":m,"etc2-rgb8a1unorm-srgb":m,"etc2-rgba8unorm":m,"etc2-rgba8unorm-srgb":m,"eac-r11unorm":m,"eac-r11snorm":m,"eac-rg11unorm":m,"eac-rg11snorm":m,"astc-4x4-unorm":m,"astc-4x4-unorm-srgb":m,"astc-5x4-unorm":m,"astc-5x4-unorm-srgb":m,"astc-5x5-unorm":m,"astc-5x5-unorm-srgb":m,"astc-6x5-unorm":m,"astc-6x5-unorm-srgb":m,"astc-6x6-unorm":m,"astc-6x6-unorm-srgb":m,"astc-8x5-unorm":m,"astc-8x5-unorm-srgb":m,"astc-8x6-unorm":m,"astc-8x6-unorm-srgb":m,"astc-8x8-unorm":m,"astc-8x8-unorm-srgb":m,"astc-10x5-unorm":m,"astc-10x5-unorm-srgb":m,"astc-10x6-unorm":m,"astc-10x6-unorm-srgb":m,"astc-10x8-unorm":m,"astc-10x8-unorm-srgb":m,"astc-10x10-unorm":m,"astc-10x10-unorm-srgb":m,"astc-12x10-unorm":m,"astc-12x10-unorm-srgb":m,"astc-12x12-unorm":m,"astc-12x12-unorm-srgb":m},et={rgba8unorm:B,rgba8snorm:B,rgba8uint:G,rgba8sint:E,rgba16uint:G,rgba16sint:E,rgba16float:B,r32uint:G,r32sint:E,r32float:B,rg32uint:G,rg32sint:E,rg32float:B,rgba32uint:G,rgba32sint:E,rgba32float:B,bgra8unorm:B},Ln={f32:"float",u32:"uint",i32:"sint"},On={float:m,"unfilterable-float":m,uint:P,sint:C,depth:m};function Mn(e,t){return new hr(e,t)}function Q(e){return e?.resourceType==="texture"&&!!e[f]}function tt(e){return e?.resourceType==="texture-storage-view"&&!!e[f]}function rt(e){return e?.resourceType==="texture-sampled-view"&&!!e[f]}var Wn={mutable:"read_write",readonly:"read",writeonly:"write"},hr=class{constructor(t,r){this.props=t;this._branch=r;this[f]={unwrap:()=>{if(this._destroyed)throw new Error("This texture has been destroyed");return this._texture||(this._texture=this._branch.device.createTexture({label:p(this)??"<unnamed>",format:this.props.format,size:this.props.size,usage:this._flags,dimension:this.props.dimension??"2d",viewFormats:this.props.viewFormats??[],mipLevelCount:this.props.mipLevelCount??1,sampleCount:this.props.sampleCount??1})),this._texture}}}[f];resourceType="texture";usableAsSampled=!1;usableAsStorage=!1;usableAsRender=!1;_destroyed=!1;_flags=GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;_texture=null;$name(t){return h(this,t),this}$usage(...t){let r=t.includes("storage"),n=t.includes("sampled"),a=t.includes("render");return this._flags|=n?GPUTextureUsage.TEXTURE_BINDING:0,this._flags|=r?GPUTextureUsage.STORAGE_BINDING:0,this._flags|=a?GPUTextureUsage.RENDER_ATTACHMENT:0,this.usableAsStorage||=r,this.usableAsSampled||=n,this.usableAsRender||=a,this}createView(t,r){if(t==="sampled")return this._asSampled(r);let n=r;switch(t){case"mutable":return this._asMutable(n);case"readonly":return this._asReadonly(n);case"writeonly":return this._asWriteonly(n)}}_asStorage(t,r){if(!this.usableAsStorage)throw new Error("Unusable as storage");let n=t?.format??this.props.format,a=et[n];return pe(!!a,`Unsupported storage texture format: ${n}`),new wr(t??{},r,this)}_asReadonly(t){return this._asStorage(t,"readonly")}_asWriteonly(t){return this._asStorage(t,"writeonly")}_asMutable(t){return this._asStorage(t,"mutable")}_asSampled(t){if(!this.usableAsSampled)throw new Error("Unusable as sampled");let r=t?.format??this.props.format;if(!et[r])throw new Error(`Unsupported storage texture format: ${r}`);return new br(t,this)}destroy(){this._destroyed||(this._destroyed=!0,this._texture?.destroy())}},Ut={"1d":"1d","2d":"2d","2d-array":"2d_array",cube:"cube","cube-array":"cube_array","3d":"3d"},wr=class{constructor(t,r,n){this.access=r;this._texture=n;this[S]=this,this[f]={unwrap:()=>(this._view||(this._view=this._texture[f].unwrap().createView({label:`${p(this)??"<unnamed>"} - View`,format:this._format,dimension:this.dimension})),this._view)},this[D]=n,this.dimension=t?.dimension??n.props.dimension??"2d",this._format=t?.format??n.props.format,this.texelDataType=et[this._format]}[S];[f];[D];resourceType="texture-storage-view";texelDataType;dimension;_view;_format;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),{group:n,binding:a}=t.allocateFixedEntry({storageTexture:this._format,access:this.access,viewDimension:this.dimension},this),o=`texture_storage_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${a}) var ${r}: ${o}<${this._format}, ${Wn[this.access]}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},Ft=class{constructor(t,r,n,a){this._format=t;this.dimension=r;this.access=n;this._membership=a;this[S]=this,this[f]={},this.texelDataType=et[this._format],h(this,a.key)}[S];[f];resourceType="texture-storage-view";texelDataType;"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=`texture_storage_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${this._format}, ${Wn[this.access]}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},br=class{constructor(t,r){this._props=t;this._texture=r;this[S]=this,this[f]={unwrap:()=>(this._view||(this._view=this._texture[f].unwrap().createView({label:`${p(this)??"<unnamed>"} - View`,...this._props})),this._view)},this[D]=r,this.dimension=t?.dimension??r.props.dimension??"2d",this._format=t?.format??r.props.format,this.channelDataType=Gn[this._format]}[S];[f];[D];resourceType="texture-sampled-view";channelDataType;dimension;_format;_view;$name(t){return this._texture.$name(t),this}"~resolve"(t){let r=t.names.makeUnique(p(this)),n=(this._texture.props.sampleCount??1)>1,{group:a,binding:o}=t.allocateFixedEntry({texture:Ln[this.channelDataType.type],viewDimension:this.dimension,multisampled:n},this),i=n?"texture_multisampled_2d":`texture_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${a}) @binding(${o}) var ${r}: ${i}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}},It=class{constructor(t,r,n,a){this.dimension=r;this._multisampled=n;this._membership=a;this[S]=this,this[f]={},h(this,a.key),this.channelDataType=On[t]}[S];[f];resourceType="texture-sampled-view";channelDataType;"~resolve"(t){let r=t.names.makeUnique(p(this)),n=t.allocateLayoutEntry(this._membership.layout),a=this._multisampled?"texture_multisampled_2d":`texture_${Ut[this.dimension]}`;return t.addDeclaration(`@group(${n}) @binding(${this._membership.idx}) var ${r}: ${a}<${t.resolve(this.channelDataType)}>;`),r}toString(){return`${this.resourceType}:${p(this)??"<unnamed>"}`}};function Sr(e){return!!e?.usableAsSampled}function _a(e){return!!e?.usableAsRender}var At=class e extends Error{constructor(t){super(`Resource '${p(t)??"<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`),Object.setPrototypeOf(this,e.prototype)}};function Bt(e){return new Dr(e)}function Rt(e){return!!e&&e.resourceType==="bind-group-layout"}function Fr(e){return!!e&&e.resourceType==="bind-group"}var vr=class e extends Error{constructor(t,r){super(`Bind group '${t??"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,e.prototype)}},Nn=["compute"],Ve=["compute","vertex","fragment"],Dr=class{constructor(t){this.entries=t;let r=0;for(let[n,a]of Object.entries(t)){if(a===null){r++;continue}let o={layout:this,key:n,idx:r};if("uniform"in a&&(this.bound[n]=new Qe("uniform",a.uniform,o)),"storage"in a){let i="type"in a.storage?a.storage:a.storage(0);this.bound[n]=new Qe(a.access??"readonly",i,o)}"texture"in a&&(this.bound[n]=new It(a.texture,a.viewDimension??"2d",a.multisampled??!1,o)),"storageTexture"in a&&(this.bound[n]=new Ft(a.storageTexture,a.viewDimension??"2d",a.access??"writeonly",o)),"externalTexture"in a&&(this.bound[n]=new Dt(o)),"sampler"in a&&(a.sampler==="comparison"?this.bound[n]=new vt(o):this.bound[n]=new St(o)),"texture"in a||"storageTexture"in a||"externalTexture"in a||"sampler"in a?this.value[n]=this.bound[n]:Object.defineProperty(this.value,n,{get:()=>this.bound[n].value}),r++}}_index;resourceType="bind-group-layout";bound={};value={};$=this.value;toString(){return`bindGroupLayout:${p(this)??"<unnamed>"}`}get index(){return this._index}$name(t){return h(this,t),this}$idx(t){return this._index=t,this}unwrap(t){return t.device.createBindGroupLayout({label:p(this)??"<unnamed>",entries:Object.values(this.entries).map((n,a)=>{if(n===null)return null;let o=n.visibility,i={binding:a,visibility:0};if("uniform"in n)o=o??Ve,i.buffer={type:"uniform"};else if("storage"in n)o=o??(n.access==="mutable"?Nn:Ve),i.buffer={type:n.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in n)o=o??Ve,i.sampler={type:n.sampler};else if("texture"in n)o=o??Ve,i.texture={sampleType:n.texture,viewDimension:n.viewDimension??"2d",multisampled:n.multisampled??!1};else if("storageTexture"in n){let s=n.access??"writeonly";o=o??(s==="readonly"?Ve:Nn),i.storageTexture={format:n.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[s],viewDimension:n.viewDimension??"2d"}}else"externalTexture"in n&&(o=o??Ve,i.externalTexture={});return o?.includes("compute")&&(i.visibility|=GPUShaderStage.COMPUTE),o?.includes("vertex")&&(i.visibility|=GPUShaderStage.VERTEX),o?.includes("fragment")&&(i.visibility|=GPUShaderStage.FRAGMENT),i}).filter(n=>n!==null)})}},$e=class{constructor(t,r){this.layout=t;this.entries=r;for(let n of Object.keys(t.entries))if(t.entries[n]!==null&&!(n in r))throw new vr(p(t),n)}resourceType="bind-group";unwrap(t){return t.device.createBindGroup({label:p(this.layout)??"<unnamed>",layout:t.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([n,a],o)=>{if(a===null)return null;let i=this.entries[n];if(i===void 0)throw new Error(`'${n}' is a resource required to populate bind group layout '${p(this.layout)??"<unnamed>"}'.`);if("unif